Fractal ADX Cloud
该策略在 StockSharp 中使用平均趋向指数(ADX)指标,复现原始 MQL Fractal_ADX_Cloud 专家的思想。策略基于四小时K线,分析 +DI 与 -DI 分量的交叉。当 +DI 上穿 -DI 时,策略平掉空头并可开多头;当 -DI 上穿 +DI 时则反向操作开空。
止损和止盈以绝对价格单位设置,可分别启用或禁用多空方向的开仓和平仓。
细节
- 入场条件:ADX 的 +DI/-DI 交叉。
- 多空方向:双向。
- 离场条件:反向信号或止损/止盈。
- 止损:是,绝对价格。
- 默认值:
AdxPeriod= 30StopLoss= 1000mTakeProfit= 2000mBuyPosOpen= trueSellPosOpen= trueBuyPosClose= trueSellPosClose= trueCandleType= 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;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes
from StockSharp.Algo.Indicators import AverageDirectionalIndex
from StockSharp.Algo.Strategies import Strategy
class fractal_adx_cloud_strategy(Strategy):
def __init__(self):
super(fractal_adx_cloud_strategy, self).__init__()
self._adx_period = self.Param("AdxPeriod", 30)
self._stop_loss = self.Param("StopLoss", 1000.0)
self._take_profit = self.Param("TakeProfit", 2000.0)
self._buy_pos_open = self.Param("BuyPosOpen", True)
self._sell_pos_open = self.Param("SellPosOpen", True)
self._buy_pos_close = self.Param("BuyPosClose", True)
self._sell_pos_close = self.Param("SellPosClose", True)
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4)))
self._prev_plus_di = None
self._prev_minus_di = None
@property
def AdxPeriod(self):
return self._adx_period.Value
@AdxPeriod.setter
def AdxPeriod(self, value):
self._adx_period.Value = value
@property
def StopLoss(self):
return self._stop_loss.Value
@StopLoss.setter
def StopLoss(self, value):
self._stop_loss.Value = value
@property
def TakeProfit(self):
return self._take_profit.Value
@TakeProfit.setter
def TakeProfit(self, value):
self._take_profit.Value = value
@property
def BuyPosOpen(self):
return self._buy_pos_open.Value
@BuyPosOpen.setter
def BuyPosOpen(self, value):
self._buy_pos_open.Value = value
@property
def SellPosOpen(self):
return self._sell_pos_open.Value
@SellPosOpen.setter
def SellPosOpen(self, value):
self._sell_pos_open.Value = value
@property
def BuyPosClose(self):
return self._buy_pos_close.Value
@BuyPosClose.setter
def BuyPosClose(self, value):
self._buy_pos_close.Value = value
@property
def SellPosClose(self):
return self._sell_pos_close.Value
@SellPosClose.setter
def SellPosClose(self, value):
self._sell_pos_close.Value = value
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
def OnStarted2(self, time):
super(fractal_adx_cloud_strategy, self).OnStarted2(time)
self._prev_plus_di = None
self._prev_minus_di = None
adx = AverageDirectionalIndex()
adx.Length = self.AdxPeriod
subscription = self.SubscribeCandles(self.CandleType)
subscription.BindEx(adx, self.ProcessCandle).Start()
self.StartProtection(
Unit(float(self.TakeProfit), UnitTypes.Absolute),
Unit(float(self.StopLoss), UnitTypes.Absolute))
def ProcessCandle(self, candle, adx_value):
if candle.State != CandleStates.Finished:
return
plus_di_val = adx_value.Dx.Plus
minus_di_val = adx_value.Dx.Minus
if plus_di_val is None or minus_di_val is None:
return
plus_di = float(plus_di_val)
minus_di = float(minus_di_val)
if self._prev_plus_di is not None and self._prev_minus_di is not None:
if plus_di > minus_di:
if self.SellPosClose and self.Position < 0:
self.BuyMarket()
if self.BuyPosOpen and self._prev_plus_di <= self._prev_minus_di and self.Position <= 0:
self.BuyMarket()
elif minus_di > plus_di:
if self.BuyPosClose and self.Position > 0:
self.SellMarket()
if self.SellPosOpen and self._prev_plus_di >= self._prev_minus_di and self.Position >= 0:
self.SellMarket()
self._prev_plus_di = plus_di
self._prev_minus_di = minus_di
def OnReseted(self):
super(fractal_adx_cloud_strategy, self).OnReseted()
self._prev_plus_di = None
self._prev_minus_di = None
def CreateClone(self):
return fractal_adx_cloud_strategy()