在 GitHub 上查看

MACD + DMI 策略

该策略将移动平均收敛背离指标与方向性运动指数结合,只在趋势强度得到确认时交易。系统等待 MACD 金叉/死叉,同时检查主导方向线高于相反方向线,并且 ADX 高于关键水平。

策略适用于多头和空头。通过将动量和趋势过滤结合,可在震荡行情中减少噪音。基于波动率的保护性止损控制风险。

细节

  • 入场条件
    • 多头:MACD 线向上穿越信号线,+DI > -DI,且 ADX 高于关键值。
    • 空头:MACD 线向下穿越信号线,-DI > +DI,且 ADX 高于关键值。
  • 出场条件
    • 反向信号或波动率止损触发。
  • 指标
    • MACD(快线12,慢线26,信号线9)
    • DMI(周期14,ADX 平滑14)
  • 止损:通过 StartProtection 设置固定止损和止盈。
  • 默认值
    • Ma1Length = 10
    • Ma2Length = 20
    • DmiLength = 14
    • AdxSmoothing = 14
    • KeyLevel = 20
  • 过滤
    • 趋势跟随
    • 多时间框架
    • 指标:MACD、DMI
    • 止损:是
    • 复杂度:中等
namespace StockSharp.Samples.Strategies;

using System;
using System.Collections.Generic;

using Ecng.Common;

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

/// <summary>
/// MACD + DMI Strategy.
/// Uses MACD for momentum and DMI for directional confirmation.
/// Buys when MACD crosses above zero and DI+ > DI-.
/// Sells when MACD crosses below zero and DI- > DI+.
/// </summary>
public class MacdDmiStrategy : Strategy
{
	private readonly StrategyParam<DataType> _candleTypeParam;
	private readonly StrategyParam<int> _dmiLength;
	private readonly StrategyParam<int> _cooldownBars;

	private MovingAverageConvergenceDivergence _macd;
	private DirectionalIndex _dmi;
	private decimal _prevMacd;
	private int _cooldownRemaining;

	public MacdDmiStrategy()
	{
		_candleTypeParam = Param(nameof(CandleType), TimeSpan.FromMinutes(30).TimeFrame())
			.SetDisplay("Candle type", "Candle type for strategy calculation.", "General");

		_dmiLength = Param(nameof(DmiLength), 14)
			.SetGreaterThanZero()
			.SetDisplay("DMI Length", "DMI period", "DMI");

		_cooldownBars = Param(nameof(CooldownBars), 10)
			.SetDisplay("Cooldown Bars", "Bars to wait between trades", "Risk");
	}

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

	public int DmiLength
	{
		get => _dmiLength.Value;
		set => _dmiLength.Value = value;
	}

	public int CooldownBars
	{
		get => _cooldownBars.Value;
		set => _cooldownBars.Value = value;
	}

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();

		_macd = null;
		_dmi = null;
		_prevMacd = 0;
		_cooldownRemaining = 0;
	}

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

		_macd = new MovingAverageConvergenceDivergence();
		_dmi = new DirectionalIndex { Length = DmiLength };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.BindEx(_macd, _dmi, OnProcess)
			.Start();

		var area = CreateChartArea();
		if (area != null)
		{
			DrawCandles(area, subscription);
			DrawOwnTrades(area);
		}
	}

	private void OnProcess(ICandleMessage candle, IIndicatorValue macdValue, IIndicatorValue dmiValue)
	{
		if (candle.State != CandleStates.Finished)
			return;

		if (!_macd.IsFormed || !_dmi.IsFormed)
			return;

		if (macdValue.IsEmpty)
			return;

		var macdVal = macdValue.ToDecimal();

		var dmiTyped = (DirectionalIndexValue)dmiValue;
		if (dmiTyped.Plus is not decimal diPlus || dmiTyped.Minus is not decimal diMinus)
			return;

		if (!IsFormedAndOnlineAndAllowTrading())
		{
			_prevMacd = macdVal;
			return;
		}

		if (_cooldownRemaining > 0)
		{
			_cooldownRemaining--;
			_prevMacd = macdVal;
			return;
		}

		// MACD zero crossover + DMI direction
		var macdCrossUp = macdVal > 0 && _prevMacd <= 0 && _prevMacd != 0;
		var macdCrossDown = macdVal < 0 && _prevMacd >= 0 && _prevMacd != 0;

		// Buy: MACD crosses above zero + DI+ > DI-
		if (macdCrossUp && diPlus > diMinus && Position <= 0)
		{
			if (Position < 0)
				BuyMarket(Math.Abs(Position));
			BuyMarket(Volume);
			_cooldownRemaining = CooldownBars;
		}
		// Sell: MACD crosses below zero + DI- > DI+
		else if (macdCrossDown && diMinus > diPlus && Position >= 0)
		{
			if (Position > 0)
				SellMarket(Math.Abs(Position));
			SellMarket(Volume);
			_cooldownRemaining = CooldownBars;
		}
		// Exit long: DI- crosses above DI+
		else if (Position > 0 && diMinus > diPlus && macdVal < 0)
		{
			SellMarket(Math.Abs(Position));
			_cooldownRemaining = CooldownBars;
		}
		// Exit short: DI+ crosses above DI-
		else if (Position < 0 && diPlus > diMinus && macdVal > 0)
		{
			BuyMarket(Math.Abs(Position));
			_cooldownRemaining = CooldownBars;
		}

		_prevMacd = macdVal;
	}
}