ADX-Abschwächungs-Strategie
Der Average Directional Index misst die Trendstärke. Wenn der ADX zu sinken beginnt, signalisiert dies oft, dass die aktuelle Bewegung an Schwung verliert. Dieses System handelt gegen diesen sich abschwächenden Trend, wenn der Preis auf der entgegengesetzten Seite eines einfachen gleitenden Durchschnitts liegt.
Tests zeigen eine durchschnittliche Jahresrendite von etwa 136%. Am besten funktioniert die Strategie am Aktienmarkt.
Für jeden Balken berechnet die Strategie ADX und eine MA. Wenn ADX im Vergleich zum vorherigen Wert sinkt und der Preis über der MA liegt, wird ein Long-Einstieg gesetzt. Fällt ADX, während der Preis unter der MA liegt, wird Short gegangen. Ein fester Stop-Loss schützt die Position.
Da der Ansatz eine Verlangsamung und keine vollständige Umkehr erwartet, werden Trades in der Regel nur gehalten, bis ADX wieder zu steigen beginnt oder der Stop erreicht wird.
Details
- Einstiegskriterien: ADX niedriger als der vorherige Wert und Preis relativ zur MA.
- Long/Short: Beide.
- Ausstiegskriterien: Stop-Loss.
- Stops: Ja, prozentbasiert.
- Standardwerte:
AdxPeriod = 14
MaPeriod = 20
StopLossPercent = 2
CandleType = 15 minute
- Filter:
- Kategorie: Trendfolge
- Richtung: Beide
- Indikatoren: ADX, MA
- Stops: Ja
- Komplexität: Grundlegend
- Zeitrahmen: Intraday
- Saisonalität: Nein
- Neuronale Netze: Nein
- Divergenz: Nein
- Risikolevel: Mittel
using System;
using System.Collections.Generic;
using Ecng.Common;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// ADX Weakening strategy.
/// While flat, a fall of ADX from the previous candle buys when the close is above the SMA and sells when it is below.
/// The position is held until ADX rises again or the percent stop is hit.
/// </summary>
public class AdxWeakeningStrategy : Strategy
{
private readonly StrategyParam<int> _adxPeriod;
private readonly StrategyParam<int> _maPeriod;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prevAdx;
/// <summary>
/// ADX period.
/// </summary>
public int AdxPeriod
{
get => _adxPeriod.Value;
set => _adxPeriod.Value = value;
}
/// <summary>
/// SMA period.
/// </summary>
public int MaPeriod
{
get => _maPeriod.Value;
set => _maPeriod.Value = value;
}
/// <summary>
/// Stop-loss percentage.
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public AdxWeakeningStrategy()
{
_adxPeriod = Param(nameof(AdxPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("ADX Period", "Period for ADX", "Indicators");
_maPeriod = Param(nameof(MaPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("MA Period", "Period for SMA", "Indicators");
_stopLossPercent = Param(nameof(StopLossPercent), 2m)
.SetNotNegative()
.SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(15).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();
_prevAdx = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevAdx = null;
var sma = new SimpleMovingAverage { Length = MaPeriod };
var adx = new AverageDirectionalIndex { Length = AdxPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(sma, adx, ProcessCandle)
.Start();
StartProtection(new Unit(), new Unit(StopLossPercent, UnitTypes.Percent), useMarketOrders: true, isLocalStop: true);
// The stop has to see prices between candles, not only at their close.
foreach (var field in new[] { Level1Fields.BestBidPrice, Level1Fields.BestAskPrice })
{
var quotes = new Subscription(DataType.Level1, Security);
quotes.MarketData.BuildField = field;
SubscribeLevel1(quotes).Bind(ObserveProtectionQuote).Start();
}
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, sma);
DrawIndicator(area, adx);
DrawOwnTrades(area);
}
}
private void ObserveProtectionQuote(Level1ChangeMessage quote)
{
// The high-level handler activates native protection before this callback, also between signal bars.
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue smaIv, IIndicatorValue adxIv)
{
if (candle.State != CandleStates.Finished || !adxIv.IsFormed || !smaIv.IsFormed)
return;
if (adxIv is not AverageDirectionalIndexValue { MovingAverage: decimal adx })
return;
var prevAdx = _prevAdx;
_prevAdx = adx;
if (prevAdx is not decimal lastAdx || !IsFormedAndOnlineAndAllowTrading())
return;
var sma = smaIv.GetValue<decimal>();
var close = candle.ClosePrice;
if (Position > 0)
{
if (adx > lastAdx)
SellMarket(Position);
}
else if (Position < 0)
{
if (adx > lastAdx)
BuyMarket(-Position);
}
else if (adx < lastAdx)
{
if (close > sma)
BuyMarket(Volume);
else if (close < sma)
SellMarket(Volume);
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
clr.AddReference("StockSharp.BusinessEntities")
from System import TimeSpan, Decimal
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes, Level1Fields
from StockSharp.BusinessEntities import Subscription
from StockSharp.Algo.Indicators import SimpleMovingAverage, AverageDirectionalIndex
from StockSharp.Algo.Strategies import Strategy
class adx_weakening_strategy(Strategy):
"""
ADX Weakening strategy.
While flat, a fall of ADX from the previous candle buys when the close is above the SMA and sells when it is below.
The position is held until ADX rises again or the percent stop is hit.
"""
def __init__(self):
super(adx_weakening_strategy, self).__init__()
self._adx_period = self.Param("AdxPeriod", 14).SetGreaterThanZero().SetDisplay("ADX Period", "Period for ADX", "Indicators")
self._ma_period = self.Param("MaPeriod", 20).SetGreaterThanZero().SetDisplay("MA Period", "Period for SMA", "Indicators")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0).SetNotNegative().SetDisplay("Stop Loss %", "Stop loss percentage from entry price", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(15))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._prev_adx = None
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(adx_weakening_strategy, self).OnReseted()
self._prev_adx = None
def OnStarted2(self, time):
super(adx_weakening_strategy, self).OnStarted2(time)
self._prev_adx = None
sma = SimpleMovingAverage()
sma.Length = self._ma_period.Value
adx = AverageDirectionalIndex()
adx.Length = self._adx_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(sma, adx, self._process_candle).Start()
self.StartProtection(Unit(), Unit(Decimal(self._stop_loss_percent.Value), UnitTypes.Percent), useMarketOrders=True, isLocalStop=True)
# The stop has to see prices between candles, not only at their close.
for field in (Level1Fields.BestBidPrice, Level1Fields.BestAskPrice):
quotes = Subscription(DataType.Level1, self.Security)
quotes.MarketData.BuildField = field
self.SubscribeLevel1(quotes).Bind(self._observe_protection_quote).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, sma)
self.DrawIndicator(area, adx)
self.DrawOwnTrades(area)
def _observe_protection_quote(self, quote):
# The high-level handler activates native protection before the callback, including between bars.
pass
def _process_candle(self, candle, sma_iv, adx_iv):
if candle.State != CandleStates.Finished or not adx_iv.IsFormed or not sma_iv.IsFormed:
return
if adx_iv.MovingAverage is None:
return
adx = adx_iv.MovingAverage
prev_adx = self._prev_adx
self._prev_adx = adx
if prev_adx is None or not self.IsFormedAndOnlineAndAllowTrading():
return
sma = sma_iv.GetValue[Decimal](None)
close = candle.ClosePrice
if self.Position > 0:
if adx > prev_adx:
self.SellMarket(self.Position)
elif self.Position < 0:
if adx > prev_adx:
self.BuyMarket(-self.Position)
elif adx < prev_adx:
if close > sma:
self.BuyMarket(self.Volume)
elif close < sma:
self.SellMarket(self.Volume)
def CreateClone(self):
return adx_weakening_strategy()