Возврат по ATR
Стратегия ищет резкие движения, измеряемые кратными среднему истинному диапазону (ATR). Когда цена выходит за порог множителя ATR, система ожидает возвращения к среднему.
Тестирование показывает среднегодичную доходность около 133%. Стратегию лучше запускать на крипторынке.
Сделка открывается против направления импульса и использует скользящую среднюю для оценки момента.
Позиции закрываются при пересечении скользящих средних или срабатывании волатильного стопа.
Подробности
- Условия входа: движение цены превышает
AtrMultiplierраз ATR. - Длинные/короткие позиции: обе стороны.
- Условия выхода: цена пересекает скользящую среднюю или стоп.
- Стопы: да.
- Значения по умолчанию:
AtrPeriod= 14AtrMultiplier= 2.0mMAPeriod= 20StopLossPercent= 2.0mCandleType= TimeSpan.FromMinutes(5)
- Фильтры:
- Категория: Mean Reversion
- Направление: обе стороны
- Индикаторы: ATR, MA
- Стопы: да
- Сложность: базовая
- Таймфрейм: внутридневной
- Сезонность: нет
- Нейросети: нет
- Дивергенция: нет
- Уровень риска: средний
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<int> _cooldownBars;
private decimal _prevClose;
private int _cooldown;
/// <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>
/// Cooldown bars between trades.
/// </summary>
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
/// <summary>
/// Initialize the ATR Reversion strategy.
/// </summary>
public AtrReversionStrategy()
{
_atrPeriod = Param(nameof(AtrPeriod), 14)
.SetDisplay("ATR Period", "Period for ATR calculation", "Indicators")
.SetOptimize(7, 21, 7);
_atrMultiplier = Param(nameof(AtrMultiplier), 2.0m)
.SetDisplay("ATR Multiplier", "ATR multiplier for entry signal", "Entry")
.SetOptimize(1.5m, 3.0m, 0.5m);
_maPeriod = Param(nameof(MAPeriod), 20)
.SetDisplay("MA Period", "Period for MA calculation for exit", "Indicators")
.SetOptimize(10, 50, 5);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(1).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
_cooldownBars = Param(nameof(CooldownBars), 500)
.SetRange(1, 1000)
.SetDisplay("Cooldown Bars", "Bars to wait between trades", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevClose = default;
_cooldown = default;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevClose = 0;
_cooldown = 0;
var atr = new AverageTrueRange { Length = AtrPeriod };
var sma = new SimpleMovingAverage { Length = MAPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(atr, sma, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, sma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal atrValue, decimal smaValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (_prevClose == 0)
{
_prevClose = candle.ClosePrice;
return;
}
if (_cooldown > 0)
{
_cooldown--;
_prevClose = candle.ClosePrice;
return;
}
var priceChange = candle.ClosePrice - _prevClose;
decimal normalizedChange = 0;
if (atrValue > 0)
normalizedChange = priceChange / atrValue;
if (Position == 0)
{
if (normalizedChange < -AtrMultiplier)
{
BuyMarket();
_cooldown = CooldownBars;
}
else if (normalizedChange > AtrMultiplier)
{
SellMarket();
_cooldown = CooldownBars;
}
}
else if (Position > 0)
{
if (candle.ClosePrice > smaValue)
{
SellMarket();
_cooldown = CooldownBars;
}
}
else if (Position < 0)
{
if (candle.ClosePrice < smaValue)
{
BuyMarket();
_cooldown = CooldownBars;
}
}
_prevClose = candle.ClosePrice;
}
}
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
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).SetDisplay("ATR Period", "Period for ATR calculation", "Indicators")
self._atr_multiplier = self.Param("AtrMultiplier", 2.0).SetDisplay("ATR Multiplier", "ATR multiplier for entry signal", "Entry")
self._ma_period = self.Param("MAPeriod", 20).SetDisplay("MA Period", "Period for MA calculation for exit", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(1))).SetDisplay("Candle Type", "Type of candles to use", "General")
self._cooldown_bars = self.Param("CooldownBars", 500).SetDisplay("Cooldown Bars", "Bars to wait between trades", "General")
self._prev_close = 0.0
self._cooldown = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(atr_reversion_strategy, self).OnReseted()
self._prev_close = 0.0
self._cooldown = 0
def OnStarted2(self, time):
super(atr_reversion_strategy, self).OnStarted2(time)
self._prev_close = 0.0
self._cooldown = 0
atr = AverageTrueRange()
atr.Length = self._atr_period.Value
sma = SimpleMovingAverage()
sma.Length = self._ma_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(atr, sma, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, sma)
self.DrawOwnTrades(area)
def _process_candle(self, candle, atr_val, sma_val):
if candle.State != CandleStates.Finished:
return
close = float(candle.ClosePrice)
if self._prev_close == 0:
self._prev_close = close
return
if self._cooldown > 0:
self._cooldown -= 1
self._prev_close = close
return
av = float(atr_val)
sv = float(sma_val)
mult = float(self._atr_multiplier.Value)
cd = self._cooldown_bars.Value
norm = 0.0
if av > 0:
norm = (close - self._prev_close) / av
if self.Position == 0:
if norm < -mult:
self.BuyMarket()
self._cooldown = cd
elif norm > mult:
self.SellMarket()
self._cooldown = cd
elif self.Position > 0:
if close > sv:
self.SellMarket()
self._cooldown = cd
elif self.Position < 0:
if close < sv:
self.BuyMarket()
self._cooldown = cd
self._prev_close = close
def CreateClone(self):
return atr_reversion_strategy()