Estratégia ATR Reversion
ATR Reversion procura movimentos repentinos medidos em múltiplos do Average True Range (ATR). Quando o preço ultrapassa o multiplicador de ATR, o sistema espera uma reversão à média.
Os testes indicam um retorno anual médio de aproximadamente 133%. Funciona melhor no mercado de criptomoedas.
A estratégia abre uma operação na direção oposta ao movimento brusco e utiliza uma média móvel para avaliar o momentum.
As posições fecham em um cruzamento de média móvel ou quando o stop de volatilidade é atingido.
Detalhes
- Critérios de entrada: O movimento do preço excede
AtrMultipliervezes ATR. - Comprado/Vendido: Ambos os lados.
- Critérios de saída: O preço cruza a média móvel ou o stop.
- Stops: Sim.
- Valores padrão:
AtrPeriod= 14AtrMultiplier= 2.0mMAPeriod= 20StopLossPercent= 2.0mCandleType= TimeSpan.FromMinutes(5)
- Filtros:
- Categoria: Reversão à média
- Direção: Ambos
- Indicadores: ATR, MA
- Stops: Sim
- Complexidade: Básico
- 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>
/// Strategy that trades on sudden price movements measured in ATR units.
/// It enters positions when price makes a significant move in one direction (N * ATR)
/// and expects a reversion to the mean.
/// </summary>
public class AtrReversionStrategy : Strategy
{
private readonly StrategyParam<int> _atrPeriod;
private readonly StrategyParam<decimal> _atrMultiplier;
private readonly StrategyParam<int> _maPeriod;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _stopLossPercent;
private decimal _prevClose;
private decimal _prevMean;
private bool _hasPrevious;
private Order _pendingOrder;
/// <summary>
/// Period for ATR calculation.
/// </summary>
public int AtrPeriod
{
get => _atrPeriod.Value;
set => _atrPeriod.Value = value;
}
/// <summary>
/// ATR multiplier for entry signal.
/// </summary>
public decimal AtrMultiplier
{
get => _atrMultiplier.Value;
set => _atrMultiplier.Value = value;
}
/// <summary>
/// Period for Moving Average calculation for exit.
/// </summary>
public int MAPeriod
{
get => _maPeriod.Value;
set => _maPeriod.Value = value;
}
/// <summary>
/// Type of candles used for strategy calculation.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initialize the ATR Reversion strategy.
/// </summary>
public AtrReversionStrategy()
{
_atrPeriod = Param(nameof(AtrPeriod), 14).SetGreaterThanZero()
.SetDisplay("ATR Period", "Period for ATR calculation", "Indicators")
.SetOptimize(7, 21, 7);
_atrMultiplier = Param(nameof(AtrMultiplier), 2.0m).SetGreaterThanZero()
.SetDisplay("ATR Multiplier", "ATR multiplier for entry signal", "Entry")
.SetOptimize(1.5m, 3.0m, 0.5m);
_maPeriod = Param(nameof(MAPeriod), 20).SetGreaterThanZero()
.SetDisplay("MA Period", "Period for MA calculation for exit", "Indicators")
.SetOptimize(10, 50, 5);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_stopLossPercent = Param(nameof(StopLossPercent), 2m).SetNotNegative()
.SetDisplay("Stop Loss (%)", "Actual-fill percent stop; zero disables it.", "Protection");
OrderRegistering += order => _pendingOrder = order;
}
public decimal StopLossPercent { get => _stopLossPercent.Value; set => _stopLossPercent.Value = value; }
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType), (Security, DataType.Level1)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevClose = default;
_prevMean = default;
_hasPrevious = false;
_pendingOrder = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var atr = new AverageTrueRange { Length = AtrPeriod };
var sma = new SimpleMovingAverage { Length = MAPeriod };
StartProtection(new Unit(), new Unit(StopLossPercent, UnitTypes.Percent), useMarketOrders: true, isLocalStop: true);
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 subscription = SubscribeCandles(CandleType);
subscription
.BindEx(atr, sma, ProcessCandle, false)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, sma);
DrawIndicator(area, atr);
DrawOwnTrades(area);
}
}
private void ObserveProtectionQuote(Level1ChangeMessage quote)
{
// Native protection runs before the callback, including between finished candles.
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue atrValue, IIndicatorValue smaValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!atrValue.IsFormed || !smaValue.IsFormed || !IsFormedAndOnlineAndAllowTrading())
return;
var atr = atrValue.GetValue<decimal>();
var mean = smaValue.GetValue<decimal>();
var close = candle.ClosePrice;
if (!_hasPrevious)
{
_hasPrevious = true;
_prevClose = close;
_prevMean = mean;
return;
}
if (_pendingOrder is not null && _pendingOrder.State is not (OrderStates.Done or OrderStates.Failed))
{
_prevClose = close;
_prevMean = mean;
return;
}
// A current level is not a crossing: compare each close against its own SMA.
if (Position > 0m && _prevClose <= _prevMean && close > mean)
SellMarket(Position);
else if (Position < 0m && _prevClose >= _prevMean && close < mean)
BuyMarket(Math.Abs(Position));
else if (Position == 0m && atr > 0m && close - _prevClose < -AtrMultiplier * atr)
BuyMarket(Volume);
else if (Position == 0m && atr > 0m && close - _prevClose > AtrMultiplier * atr)
SellMarket(Volume);
_prevClose = close;
_prevMean = mean;
}
}
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, Math
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes, OrderStates, Level1Fields
from StockSharp.BusinessEntities import Subscription
from StockSharp.Algo.Indicators import AverageTrueRange, SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class atr_reversion_strategy(Strategy):
"""
ATR Reversion strategy. Trades when price moves N*ATR in one direction.
"""
def __init__(self):
super(atr_reversion_strategy, self).__init__()
self._atr_period = self.Param("AtrPeriod", 14).SetGreaterThanZero().SetDisplay("ATR Period", "Period for ATR calculation", "Indicators")
self._atr_multiplier = self.Param("AtrMultiplier", 2.0).SetGreaterThanZero().SetDisplay("ATR Multiplier", "ATR multiplier for entry signal", "Entry")
self._ma_period = self.Param("MAPeriod", 20).SetGreaterThanZero().SetDisplay("MA Period", "Period for MA calculation for exit", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._stop_loss_percent = self.Param("StopLossPercent", 2.0).SetNotNegative() \
.SetDisplay("Stop Loss (%)", "Actual-fill percent stop; zero disables it.", "Protection")
self._prev_close = Decimal.Zero
self._prev_mean = Decimal.Zero
self._has_previous = False
self._pending_order = None
self.OrderRegistering += self._track_pending
def GetWorkingSecurities(self):
return [(self.Security, self.candle_type), (self.Security, DataType.Level1)]
def _track_pending(self, order):
self._pending_order = order
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(atr_reversion_strategy, self).OnReseted()
self._prev_close = Decimal.Zero
self._prev_mean = Decimal.Zero
self._has_previous = False
self._pending_order = None
def OnStarted2(self, time):
super(atr_reversion_strategy, self).OnStarted2(time)
atr = AverageTrueRange()
atr.Length = self._atr_period.Value
sma = SimpleMovingAverage()
sma.Length = self._ma_period.Value
self.StartProtection(Unit(), Unit(Decimal(self._stop_loss_percent.Value), UnitTypes.Percent), useMarketOrders=True, isLocalStop=True)
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()
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(atr, sma, self._process_candle, False).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, sma)
self.DrawIndicator(area, atr)
self.DrawOwnTrades(area)
def _observe_protection_quote(self, quote):
# Native protection runs before this callback, including between signal bars.
pass
def _process_candle(self, candle, atr_val, sma_val):
if candle.State != CandleStates.Finished:
return
if not atr_val.IsFormed or not sma_val.IsFormed or not self.IsFormedAndOnlineAndAllowTrading():
return
close = candle.ClosePrice
av = atr_val.GetValue[Decimal](None)
mean = sma_val.GetValue[Decimal](None)
if not self._has_previous:
self._has_previous = True
self._prev_close = close
self._prev_mean = mean
return
if self._pending_order is not None and self._pending_order.State not in (OrderStates.Done, OrderStates.Failed):
self._prev_close = close
self._prev_mean = mean
return
mult = Decimal(self._atr_multiplier.Value)
# A current level is not a crossing: compare each close against its own SMA.
if self.Position > 0 and self._prev_close <= self._prev_mean and close > mean:
self.SellMarket(self.Position)
elif self.Position < 0 and self._prev_close >= self._prev_mean and close < mean:
self.BuyMarket(Math.Abs(self.Position))
elif self.Position == 0 and av > 0 and close - self._prev_close < -mult * av:
self.BuyMarket(self.Volume)
elif self.Position == 0 and av > 0 and close - self._prev_close > mult * av:
self.SellMarket(self.Volume)
self._prev_close = close
self._prev_mean = mean
def CreateClone(self):
return atr_reversion_strategy()