Estratégia ADX MACD
ADX MACD combina a força de tendência do Average Directional Index com as mudanças de momentum do MACD. Quando o ADX está em alta, os rompimentos têm maior probabilidade de continuar, especialmente se o MACD cruzar na mesma direção.
Os testes indicam um retorno anual médio de aproximadamente 139%. Funciona melhor no mercado de ações.
A estratégia opera esses sinais alinhados e sai quando o ADX começa a enfraquecer ou o MACD vira contra a posição.
Um stop percentual moderado contém as perdas durante mercados instáveis.
Detalhes
- Critérios de entrada: sinal de indicador
- Comprado/Vendido: Ambos
- Critérios de saída: stop-loss ou sinal oposto
- Stops: Sim, baseado em percentual
- Valores padrão:
CandleType= 15 minuteStopLossPercent= 2AdxPeriod= 14MacdFast= 12MacdSlow= 26MacdSignal= 9 Sem posição, um cruzamento do MACD acima da linha de sinal abre uma compra e abaixo uma venda, mas apenas enquanto o ADX está acima do valor anterior. A posição é encerrada quando o ADX cai abaixo do valor anterior ou o MACD volta para o outro lado da linha de sinal.
- Filtros:
- Categoria: Seguidor de tendência
- Direção: Ambos
- Indicadores: ADX, MACD
- Stops: Sim
- Complexidade: Intermediário
- Período: Intradiário
- Sazonalidade: Não
- Redes neurais: Não
- Divergência: Não
- Nível de risco: Médio
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 MACD strategy.
/// While flat, a MACD cross above its signal line goes long and a cross below goes short, but only while ADX is rising.
/// The position closes once ADX weakens below its previous value or MACD returns to the other side of its signal line,
/// and a percent stop limits the loss.
/// </summary>
public class AdxMacdStrategy : Strategy
{
private readonly StrategyParam<int> _adxPeriod;
private readonly StrategyParam<int> _macdFast;
private readonly StrategyParam<int> _macdSlow;
private readonly StrategyParam<int> _macdSignal;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<DataType> _candleType;
private bool? _prevAbove;
private decimal? _prevAdx;
/// <summary>
/// Period of ADX.
/// </summary>
public int AdxPeriod
{
get => _adxPeriod.Value;
set => _adxPeriod.Value = value;
}
/// <summary>
/// Fast EMA period of MACD.
/// </summary>
public int MacdFast
{
get => _macdFast.Value;
set => _macdFast.Value = value;
}
/// <summary>
/// Slow EMA period of MACD.
/// </summary>
public int MacdSlow
{
get => _macdSlow.Value;
set => _macdSlow.Value = value;
}
/// <summary>
/// Signal line period of MACD.
/// </summary>
public int MacdSignal
{
get => _macdSignal.Value;
set => _macdSignal.Value = value;
}
/// <summary>
/// Stop loss percentage from entry price.
/// </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 AdxMacdStrategy()
{
_adxPeriod = Param(nameof(AdxPeriod), 14)
.SetGreaterThanZero()
.SetDisplay("ADX Period", "Period of ADX", "ADX");
_macdFast = Param(nameof(MacdFast), 12)
.SetGreaterThanZero()
.SetDisplay("MACD Fast", "Fast EMA period of MACD", "MACD");
_macdSlow = Param(nameof(MacdSlow), 26)
.SetGreaterThanZero()
.SetDisplay("MACD Slow", "Slow EMA period of MACD", "MACD");
_macdSignal = Param(nameof(MacdSignal), 9)
.SetGreaterThanZero()
.SetDisplay("MACD Signal", "Signal line period of MACD", "MACD");
_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();
_prevAbove = null;
_prevAdx = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevAbove = null;
_prevAdx = null;
var adx = new AverageDirectionalIndex { Length = AdxPeriod };
var macd = new MovingAverageConvergenceDivergenceSignal
{
Macd =
{
ShortMa = { Length = MacdFast },
LongMa = { Length = MacdSlow },
},
SignalMa = { Length = MacdSignal }
};
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(adx, macd, 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);
DrawOwnTrades(area);
var oscillators = CreateChartArea();
if (oscillators != null)
{
DrawIndicator(oscillators, adx);
DrawIndicator(oscillators, macd);
}
}
}
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 adxValue, IIndicatorValue macdValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!adxValue.IsFormed || !macdValue.IsFormed)
return;
if (adxValue is not AverageDirectionalIndexValue { MovingAverage: decimal strength })
return;
var macdTyped = (MovingAverageConvergenceDivergenceSignalValue)macdValue;
if (macdTyped.Macd is not decimal macd || macdTyped.Signal is not decimal signal)
return;
var isAbove = macd > signal;
var wasAbove = _prevAbove;
var prevAdx = _prevAdx;
_prevAbove = isAbove;
_prevAdx = strength;
if (wasAbove is not bool was || prevAdx is not decimal lastStrength)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var rising = strength > lastStrength;
if (Position > 0)
{
if (!rising || !isAbove)
SellMarket(Position);
}
else if (Position < 0)
{
if (!rising || isAbove)
BuyMarket(-Position);
}
else if (rising && was != isAbove)
{
if (isAbove)
BuyMarket(Volume);
else
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 AverageDirectionalIndex, MovingAverageConvergenceDivergenceSignal
from StockSharp.Algo.Strategies import Strategy
class adx_macd_strategy(Strategy):
"""
ADX MACD strategy.
While flat, a MACD cross above its signal line goes long and a cross below goes short, but only while ADX is rising.
The position closes once ADX weakens below its previous value or MACD returns to the other side of its signal line,
and a percent stop limits the loss.
"""
def __init__(self):
super(adx_macd_strategy, self).__init__()
self._adx_period = self.Param("AdxPeriod", 14).SetGreaterThanZero().SetDisplay("ADX Period", "Period of ADX", "ADX")
self._macd_fast = self.Param("MacdFast", 12).SetGreaterThanZero().SetDisplay("MACD Fast", "Fast EMA period of MACD", "MACD")
self._macd_slow = self.Param("MacdSlow", 26).SetGreaterThanZero().SetDisplay("MACD Slow", "Slow EMA period of MACD", "MACD")
self._macd_signal = self.Param("MacdSignal", 9).SetGreaterThanZero().SetDisplay("MACD Signal", "Signal line period of MACD", "MACD")
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._reset_state()
@property
def candle_type(self):
return self._candle_type.Value
def _reset_state(self):
self._prev_above = None
self._prev_adx = None
def OnReseted(self):
super(adx_macd_strategy, self).OnReseted()
self._reset_state()
def OnStarted2(self, time):
super(adx_macd_strategy, self).OnStarted2(time)
self._reset_state()
adx = AverageDirectionalIndex()
adx.Length = self._adx_period.Value
macd = MovingAverageConvergenceDivergenceSignal()
macd.Macd.ShortMa.Length = self._macd_fast.Value
macd.Macd.LongMa.Length = self._macd_slow.Value
macd.SignalMa.Length = self._macd_signal.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(adx, macd, 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.DrawOwnTrades(area)
oscillators = self.CreateChartArea()
if oscillators is not None:
self.DrawIndicator(oscillators, adx)
self.DrawIndicator(oscillators, macd)
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, adx_value, macd_value):
if candle.State != CandleStates.Finished:
return
if not adx_value.IsFormed or not macd_value.IsFormed:
return
if adx_value.MovingAverage is None or macd_value.Macd is None or macd_value.Signal is None:
return
strength = adx_value.MovingAverage
is_above = macd_value.Macd > macd_value.Signal
was_above = self._prev_above
prev_adx = self._prev_adx
self._prev_above = is_above
self._prev_adx = strength
if was_above is None or prev_adx is None:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
rising = strength > prev_adx
if self.Position > 0:
if not rising or not is_above:
self.SellMarket(self.Position)
elif self.Position < 0:
if not rising or is_above:
self.BuyMarket(-self.Position)
elif rising and was_above != is_above:
if is_above:
self.BuyMarket(self.Volume)
else:
self.SellMarket(self.Volume)
def CreateClone(self):
return adx_macd_strategy()