在 GitHub 上查看

Fractal ADX Cloud

该策略在 StockSharp 中使用平均趋向指数(ADX)指标,复现原始 MQL Fractal_ADX_Cloud 专家的思想。策略基于四小时K线,分析 +DI 与 -DI 分量的交叉。当 +DI 上穿 -DI 时,策略平掉空头并可开多头;当 -DI 上穿 +DI 时则反向操作开空。

止损和止盈以绝对价格单位设置,可分别启用或禁用多空方向的开仓和平仓。

细节

  • 入场条件:ADX 的 +DI/-DI 交叉。
  • 多空方向:双向。
  • 离场条件:反向信号或止损/止盈。
  • 止损:是,绝对价格。
  • 默认值
    • AdxPeriod = 30
    • StopLoss = 1000m
    • TakeProfit = 2000m
    • BuyPosOpen = true
    • SellPosOpen = true
    • BuyPosClose = true
    • SellPosClose = true
    • CandleType = TimeSpan.FromHours(4)
  • 过滤器
    • 分类:趋势
    • 方向:双向
    • 指标:ADX
    • 止损:有
    • 复杂度:基础
    • 周期:4小时
    • 季节性:无
    • 神经网络:无
    • 背离:无
    • 风险等级:中等
using System;
using System.Linq;
using System.Collections.Generic;

using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;

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

namespace StockSharp.Samples.Strategies;

/// <summary>
/// Strategy based on crossing of +DI and -DI from the ADX indicator.
/// </summary>
public class FractalAdxCloudStrategy : Strategy
{
	private readonly StrategyParam<int> _adxPeriod;
	private readonly StrategyParam<decimal> _stopLoss;
	private readonly StrategyParam<decimal> _takeProfit;
	private readonly StrategyParam<bool> _buyPosOpen;
	private readonly StrategyParam<bool> _sellPosOpen;
	private readonly StrategyParam<bool> _buyPosClose;
	private readonly StrategyParam<bool> _sellPosClose;
	private readonly StrategyParam<DataType> _candleType;

	private decimal? _prevPlusDi;
	private decimal? _prevMinusDi;

	/// <summary>
	/// ADX period.
	/// </summary>
	public int AdxPeriod
	{
		get => _adxPeriod.Value;
		set => _adxPeriod.Value = value;
	}

	/// <summary>
	/// Stop loss level in price units.
	/// </summary>
	public decimal StopLoss
	{
		get => _stopLoss.Value;
		set => _stopLoss.Value = value;
	}

	/// <summary>
	/// Take profit level in price units.
	/// </summary>
	public decimal TakeProfit
	{
		get => _takeProfit.Value;
		set => _takeProfit.Value = value;
	}

	/// <summary>
	/// Allow opening of long positions.
	/// </summary>
	public bool BuyPosOpen
	{
		get => _buyPosOpen.Value;
		set => _buyPosOpen.Value = value;
	}

	/// <summary>
	/// Allow opening of short positions.
	/// </summary>
	public bool SellPosOpen
	{
		get => _sellPosOpen.Value;
		set => _sellPosOpen.Value = value;
	}

	/// <summary>
	/// Allow closing of long positions on opposite signal.
	/// </summary>
	public bool BuyPosClose
	{
		get => _buyPosClose.Value;
		set => _buyPosClose.Value = value;
	}

	/// <summary>
	/// Allow closing of short positions on opposite signal.
	/// </summary>
	public bool SellPosClose
	{
		get => _sellPosClose.Value;
		set => _sellPosClose.Value = value;
	}

	/// <summary>
	/// Candle type used by the strategy.
	/// </summary>
	public DataType CandleType
	{
		get => _candleType.Value;
		set => _candleType.Value = value;
	}

	/// <summary>
	/// Initializes a new instance of the <see cref="FractalAdxCloudStrategy"/>.
	/// </summary>
	public FractalAdxCloudStrategy()
	{
		_adxPeriod = Param(nameof(AdxPeriod), 30)
			.SetRange(5, 60)
			.SetDisplay("ADX Period", "Period for ADX calculation", "Indicators")
			;

		_stopLoss = Param(nameof(StopLoss), 1000m)
			.SetRange(100m, 5000m)
			.SetDisplay("Stop Loss", "Stop loss level", "Risk Management")
			;

		_takeProfit = Param(nameof(TakeProfit), 2000m)
			.SetRange(100m, 10000m)
			.SetDisplay("Take Profit", "Take profit level", "Risk Management")
			;

		_buyPosOpen = Param(nameof(BuyPosOpen), true)
			.SetDisplay("Buy Open", "Allow opening long positions", "Trading");

		_sellPosOpen = Param(nameof(SellPosOpen), true)
			.SetDisplay("Sell Open", "Allow opening short positions", "Trading");

		_buyPosClose = Param(nameof(BuyPosClose), true)
			.SetDisplay("Buy Close", "Allow closing long positions", "Trading");

		_sellPosClose = Param(nameof(SellPosClose), true)
			.SetDisplay("Sell Close", "Allow closing short positions", "Trading");

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

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

	/// <inheritdoc />
	protected override void OnReseted()
	{
		base.OnReseted();
		_prevPlusDi = null;
		_prevMinusDi = null;
	}

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

		var adx = new AverageDirectionalIndex { Length = AdxPeriod };

		var subscription = SubscribeCandles(CandleType);
		subscription
			.BindEx(adx, ProcessCandle)
			.Start();

		StartProtection(
			takeProfit: new Unit(TakeProfit, UnitTypes.Absolute),
			stopLoss: new Unit(StopLoss, UnitTypes.Absolute),
			useMarketOrders: true);

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

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

		if (!IsFormedAndOnlineAndAllowTrading())
			return;

		var adx = (AverageDirectionalIndexValue)adxValue;
		if (adx.Dx.Plus is not decimal plusDi || adx.Dx.Minus is not decimal minusDi)
			return;

		if (_prevPlusDi is decimal prevPlus && _prevMinusDi is decimal prevMinus)
		{
			if (plusDi > minusDi)
			{
				if (SellPosClose && Position < 0)
					BuyMarket(Math.Abs(Position));

				if (BuyPosOpen && prevPlus <= prevMinus && Position <= 0)
					BuyMarket(Volume + Math.Abs(Position));
			}
			else if (minusDi > plusDi)
			{
				if (BuyPosClose && Position > 0)
					SellMarket(Math.Abs(Position));

				if (SellPosOpen && prevPlus >= prevMinus && Position >= 0)
					SellMarket(Volume + Math.Abs(Position));
			}
		}

		_prevPlusDi = plusDi;
		_prevMinusDi = minusDi;
	}
}