ADX Donchian Strategy
该策略结合ADX和唐奇安通道。当ADX高于阈值且价格突破上轨时做多;当ADX高于阈值且价格跌破下轨时做空,体现强势趋势突破。
测试表明年均收益约为 67%,该策略在股票市场表现最佳。
适合在趋势明显的市场中寻找机会的交易者。
细节
- 入场条件:
- 多头:
ADX > AdxThreshold && Price >= upperBorder - 空头:
ADX > AdxThreshold && Price <= lowerBorder
- 多头:
- 多/空: 双向
- 离场条件:
- 多头: 当ADX跌破(阈值-5)时平仓
- 空头: 当ADX跌破(阈值-5)时平仓
- 止损: 是
- 默认值:
AdxPeriod= 14DonchianPeriod= 5StopLossPercent= 2mCandleType= TimeSpan.FromMinutes(5)AdxThreshold= 10Multiplier= 0.1m
- 过滤器:
- 类别: Mixed
- 方向: 双向
- 指标: ADX Donchian
- 止损: 是
- 复杂度: 中等
- 时间框架: 日内
- 季节性: 否
- 神经网络: 否
- 背离: 否
- 风险等级: 中等
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 ADX and Donchian Channel indicators
/// </summary>
public class AdxDonchianStrategy : Strategy
{
private readonly StrategyParam<int> _adxPeriod;
private readonly StrategyParam<int> _donchianPeriod;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _adxThreshold;
private readonly StrategyParam<decimal> _multiplier;
private readonly StrategyParam<int> _cooldownBars;
private int _cooldown;
/// <summary>
/// ADX period
/// </summary>
public int AdxPeriod
{
get => _adxPeriod.Value;
set => _adxPeriod.Value = value;
}
/// <summary>
/// Donchian Channel period
/// </summary>
public int DonchianPeriod
{
get => _donchianPeriod.Value;
set => _donchianPeriod.Value = value;
}
/// <summary>
/// Stop-loss percentage
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// Candle type for strategy
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Bars to wait between trades.
/// </summary>
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
/// <summary>
/// ADX threshold for strong trend detection
/// </summary>
public int AdxThreshold
{
get => _adxThreshold.Value;
set => _adxThreshold.Value = value;
}
/// <summary>
/// Multiplier for Donchian Channel border sensitivity (in percent, e.g. 0.1 for 0.1%)
/// </summary>
public decimal Multiplier
{
get => _multiplier.Value;
set => _multiplier.Value = value;
}
/// <summary>
/// Constructor
/// </summary>
public AdxDonchianStrategy()
{
_adxPeriod = Param(nameof(AdxPeriod), 14)
.SetRange(7, 28)
.SetDisplay("ADX Period", "Period for ADX indicator", "Indicators")
;
_donchianPeriod = Param(nameof(DonchianPeriod), 5)
.SetRange(5, 50)
.SetDisplay("Donchian Period", "Period for Donchian Channel", "Indicators")
;
_stopLossPercent = Param(nameof(StopLossPercent), 2m)
.SetRange(0.5m, 5m)
.SetDisplay("Stop-Loss %", "Stop-loss percentage from entry price", "Risk Management")
;
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(15).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_adxThreshold = Param(nameof(AdxThreshold), 10)
.SetRange(5, 40)
.SetDisplay("ADX Threshold", "ADX value for strong trend detection", "Indicators")
;
_multiplier = Param(nameof(Multiplier), 0.1m)
.SetRange(0m, 1m)
.SetDisplay("Multiplier %", "Sensitivity to Donchian Channel border (percent)", "Indicators")
;
_cooldownBars = Param(nameof(CooldownBars), 40)
.SetRange(1, 200)
.SetDisplay("Cooldown Bars", "Bars between trades", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_cooldown = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
// Initialize indicators
var adx = new AverageDirectionalIndex { Length = AdxPeriod };
var donchian = new DonchianChannels { Length = DonchianPeriod };
// Create subscription and bind indicators
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(donchian, adx, ProcessCandle)
.Start();
// Setup chart visualization if available
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, adx);
DrawIndicator(area, donchian);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue donchianValue, IIndicatorValue adxValue)
{
// Skip unfinished candles
if (candle.State != CandleStates.Finished)
return;
// Check if strategy is ready to trade
if (!IsFormedAndOnlineAndAllowTrading())
return;
// Process ADX
var typedAdx = (AverageDirectionalIndexValue)adxValue;
// Get Donchian Channel values
var typedDonchian = (DonchianChannelsValue)donchianValue;
var upperBand = typedDonchian.UpperBand;
var middleBand = typedDonchian.Middle;
var lowerBand = typedDonchian.LowerBand;
var price = candle.ClosePrice;
// Trading logic:
// Long: ADX > AdxThreshold && Price >= upperBorder (strong trend with breakout up)
// Short: ADX > AdxThreshold && Price <= lowerBorder (strong trend with breakout down)
var strongTrend = typedAdx.MovingAverage > AdxThreshold;
if (_cooldown > 0)
_cooldown--;
var upperBorder = upperBand * (1 - Multiplier / 100);
var lowerBorder = lowerBand * (1 + Multiplier / 100);
if (_cooldown == 0 && strongTrend && price >= upperBorder && Position <= 0)
{
// Buy signal - Strong trend with Donchian Channel breakout up (with multiplier)
var volume = Volume + Math.Abs(Position);
BuyMarket(volume);
_cooldown = CooldownBars;
}
else if (_cooldown == 0 && strongTrend && price <= lowerBorder && Position >= 0)
{
// Sell signal - Strong trend with Donchian Channel breakout down (with multiplier)
var volume = Volume + Math.Abs(Position);
SellMarket(volume);
_cooldown = CooldownBars;
}
// Exit conditions - ADX weakness
else if (Position != 0 && typedAdx.MovingAverage < AdxThreshold - 5)
{
// Exit position when ADX falls below (threshold - 5)
if (Position > 0)
SellMarket(Position);
else
BuyMarket(Math.Abs(Position));
_cooldown = CooldownBars;
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import AverageDirectionalIndex, DonchianChannels
from StockSharp.Algo.Strategies import Strategy
from datatype_extensions import *
class adx_donchian_strategy(Strategy):
"""Strategy based on ADX and Donchian Channel indicators"""
def __init__(self):
super(adx_donchian_strategy, self).__init__()
self._adx_period = self.Param("AdxPeriod", 14) \
.SetRange(7, 28) \
.SetDisplay("ADX Period", "Period for ADX indicator", "Indicators")
self._donchian_period = self.Param("DonchianPeriod", 5) \
.SetRange(5, 50) \
.SetDisplay("Donchian Period", "Period for Donchian Channel", "Indicators")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0) \
.SetRange(0.5, 5.0) \
.SetDisplay("Stop-Loss %", "Stop-loss percentage from entry price", "Risk Management")
self._candle_type = self.Param("CandleType", tf(15)) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._adx_threshold = self.Param("AdxThreshold", 10) \
.SetRange(5, 40) \
.SetDisplay("ADX Threshold", "ADX value for strong trend detection", "Indicators")
self._multiplier = self.Param("Multiplier", 0.1) \
.SetRange(0.0, 1.0) \
.SetDisplay("Multiplier %", "Sensitivity to Donchian Channel border (percent)", "Indicators")
self._cooldown_bars = self.Param("CooldownBars", 40) \
.SetRange(1, 200) \
.SetDisplay("Cooldown Bars", "Bars between trades", "General")
self._cooldown = 0
@property
def CandleType(self):
return self._candle_type.Value
def OnReseted(self):
super(adx_donchian_strategy, self).OnReseted()
self._cooldown = 0
def OnStarted2(self, time):
super(adx_donchian_strategy, self).OnStarted2(time)
self._cooldown = 0
adx = AverageDirectionalIndex()
adx.Length = self._adx_period.Value
donchian = DonchianChannels()
donchian.Length = self._donchian_period.Value
subscription = self.SubscribeCandles(self.CandleType)
subscription.BindEx(donchian, adx, self.ProcessCandle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, adx)
self.DrawIndicator(area, donchian)
self.DrawOwnTrades(area)
def ProcessCandle(self, candle, donchian_value, adx_value):
if candle.State != CandleStates.Finished:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
adx_ma = adx_value.MovingAverage
if adx_ma is None:
return
upper_band = donchian_value.UpperBand
lower_band = donchian_value.LowerBand
if upper_band is None or lower_band is None:
return
price = float(candle.ClosePrice)
adx_val = float(adx_ma)
threshold = float(self._adx_threshold.Value)
mult = float(self._multiplier.Value)
strong_trend = adx_val > threshold
upper_border = float(upper_band) * (1 - mult / 100)
lower_border = float(lower_band) * (1 + mult / 100)
if self._cooldown > 0:
self._cooldown -= 1
cooldown_val = int(self._cooldown_bars.Value)
if self._cooldown == 0 and strong_trend and price >= upper_border and self.Position <= 0:
volume = self.Volume + abs(self.Position)
self.BuyMarket(volume)
self._cooldown = cooldown_val
elif self._cooldown == 0 and strong_trend and price <= lower_border and self.Position >= 0:
volume = self.Volume + abs(self.Position)
self.SellMarket(volume)
self._cooldown = cooldown_val
elif self.Position != 0 and adx_val < threshold - 5:
if self.Position > 0:
self.SellMarket(self.Position)
else:
self.BuyMarket(abs(self.Position))
self._cooldown = cooldown_val
def CreateClone(self):
return adx_donchian_strategy()