在 GitHub 上查看

Heiken Ashi 无影线策略

该策略利用没有影线的 Heiken Ashi 蜡烛反向交易。当当前蜡烛看涨、实体大于前一根且没有下影线,并且前一根也为看涨时,开空单。当当前蜡烛看跌、实体大于前一根且没有上影线,并且前一根也为看跌时,开多单。出现相反颜色且没有对应影线的蜡烛时平仓。

细节

  • 入场条件:看涨 HA 无下影线且实体大于前一根时做空;看跌 HA 无上影线且实体大于前一根时做多
  • 多空方向:多头和空头
  • 出场条件:相反颜色且无影线的 HA 蜡烛
  • 止损:无
  • 默认值
    • CandleType = 15 分钟蜡烛
  • 过滤器
    • 类别:形态
    • 方向:反转
    • 指标:Heikin-Ashi
    • 止损:无
    • 复杂度:基础
    • 时间框架:日内
    • 季节性:无
    • 神经网络:无
    • 背离:无
    • 风险等级:中
using System;
using System.Collections.Generic;

using Ecng.Common;

using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Strategy trading Heiken Ashi candle color changes.
/// Buys when HA turns bullish, sells when HA turns bearish.
/// </summary>
public class HeikenAshiNoWickStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleType;

	private decimal _prevHaOpen;
	private decimal _prevHaClose;
	private bool _prevIsBull;
	private bool _hasPrev;

	public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }

	public HeikenAshiNoWickStrategy()
	{
		_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
			.SetDisplay("Candle Type", "Type of candles", "General");
	}

	/// <inheritdoc />
	public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
		=> [(Security, CandleType)];

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_prevHaOpen = 0;
		_prevHaClose = 0;
		_prevIsBull = false;
		_hasPrev = false;
	}

	/// <inheritdoc />
	protected override void OnStarted2(DateTime time)
	{
		base.OnStarted2(time);

		SubscribeCandles(CandleType)
			.Bind(ProcessCandle)
			.Start();
	}

	private void ProcessCandle(ICandleMessage candle)
	{
		if (candle.State != CandleStates.Finished)
			return;

		decimal haOpen;
		decimal haClose;

		if (_prevHaOpen == 0 && _prevHaClose == 0)
		{
			haOpen = (candle.OpenPrice + candle.ClosePrice) / 2m;
			haClose = (candle.OpenPrice + candle.HighPrice + candle.LowPrice + candle.ClosePrice) / 4m;
		}
		else
		{
			haOpen = (_prevHaOpen + _prevHaClose) / 2m;
			haClose = (candle.OpenPrice + candle.HighPrice + candle.LowPrice + candle.ClosePrice) / 4m;
		}

		var isBull = haClose > haOpen;

		if (_hasPrev)
		{
			// Buy on bearish -> bullish transition
			if (isBull && !_prevIsBull && Position <= 0)
			{
				if (Position < 0) BuyMarket();
				BuyMarket();
			}
			// Sell on bullish -> bearish transition
			else if (!isBull && _prevIsBull && Position >= 0)
			{
				if (Position > 0) SellMarket();
				SellMarket();
			}
		}

		_prevHaOpen = haOpen;
		_prevHaClose = haClose;
		_prevIsBull = isBull;
		_hasPrev = true;
	}
}