Стратегия ATR Stop Loss Double SMA
Стратегия открывает длинные позиции, когда быстрая скользящая средняя (SMA) пересекает медленную сверху, и короткие — при обратном пересечении. Опциональный стоп‑лосс рассчитывается на основе индикатора ATR, умноженного на заданный коэффициент, и определяет цену выхода.
Подробности
- Условия входа:
- Лонг: быстрая SMA пересекает медленную снизу вверх.
- Шорт: быстрая SMA пересекает медленную сверху вниз.
- Направление: обе стороны.
- Условия выхода:
- Стоп‑лосс по ATR, если включён.
- Стопы: расстояние = ATR * множитель.
- Параметры по умолчанию:
FastLength= 15SlowLength= 45AtrLength= 14AtrMultiplier= 2
- Фильтры:
- Категория: Следование за трендом
- Направление: Обе
- Индикаторы: SMA, ATR
- Стопы: Да
- Сложность: Низкая
- Таймфрейм: Любой
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
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>
/// ATR stop-loss double SMA strategy.
/// A fast SMA crossing above the slow SMA goes long and a cross below goes short, reversing an opposite position. Each entry
/// fixes a stop-loss AtrMultiplier ATRs from the entry close; an AtrMultiplier of 0 disables it.
/// </summary>
public class AtrStopLossDoubleSmaStrategy : Strategy
{
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<int> _atrLength;
private readonly StrategyParam<decimal> _atrMultiplier;
private readonly StrategyParam<DataType> _candleType;
private decimal? _prevFast;
private decimal? _prevSlow;
private decimal _stopPrice;
/// <summary>
/// Fast SMA period.
/// </summary>
public int FastLength
{
get => _fastLength.Value;
set => _fastLength.Value = value;
}
/// <summary>
/// Slow SMA period.
/// </summary>
public int SlowLength
{
get => _slowLength.Value;
set => _slowLength.Value = value;
}
/// <summary>
/// ATR period.
/// </summary>
public int AtrLength
{
get => _atrLength.Value;
set => _atrLength.Value = value;
}
/// <summary>
/// Stop-loss distance in ATR multiples.
/// </summary>
public decimal AtrMultiplier
{
get => _atrMultiplier.Value;
set => _atrMultiplier.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Constructor.
/// </summary>
public AtrStopLossDoubleSmaStrategy()
{
_fastLength = Param(nameof(FastLength), 15)
.SetGreaterThanZero()
.SetDisplay("Fast Length", "Fast SMA period", "Indicators");
_slowLength = Param(nameof(SlowLength), 45)
.SetGreaterThanZero()
.SetDisplay("Slow Length", "Slow SMA period", "Indicators");
_atrLength = Param(nameof(AtrLength), 14)
.SetGreaterThanZero()
.SetDisplay("ATR Length", "ATR period", "Risk");
_atrMultiplier = Param(nameof(AtrMultiplier), 2m)
.SetNotNegative()
.SetDisplay("ATR Multiplier", "Stop-loss distance in ATR multiples, 0 disables it", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(1).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();
ResetState();
}
private void ResetState()
{
_prevFast = null;
_prevSlow = null;
_stopPrice = 0m;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
ResetState();
var fast = new SimpleMovingAverage { Length = FastLength };
var slow = new SimpleMovingAverage { Length = SlowLength };
var atr = new AverageTrueRange { Length = AtrLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fast, slow, atr, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, fast);
DrawIndicator(area, slow);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow, decimal atr)
{
if (candle.State != CandleStates.Finished)
return;
var prevFast = _prevFast;
var prevSlow = _prevSlow;
_prevFast = fast;
_prevSlow = slow;
if (prevFast is not decimal pf || prevSlow is not decimal ps)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var close = candle.ClosePrice;
var distance = AtrMultiplier * atr;
if (pf <= ps && fast > slow && Position <= 0)
{
BuyMarket(Volume + Math.Abs(Position));
_stopPrice = close - distance;
}
else if (pf >= ps && fast < slow && Position >= 0)
{
SellMarket(Volume + Math.Abs(Position));
_stopPrice = close + distance;
}
else if (AtrMultiplier > 0m)
{
if (Position > 0 && candle.LowPrice <= _stopPrice)
SellMarket(Position);
else if (Position < 0 && candle.HighPrice >= _stopPrice)
BuyMarket(-Position);
}
}
}
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 SimpleMovingAverage, AverageTrueRange
from StockSharp.Algo.Strategies import Strategy
class atr_stop_loss_double_sma_strategy(Strategy):
"""
ATR stop-loss double SMA strategy.
A fast SMA crossing above the slow SMA goes long and a cross below goes short, reversing an opposite position. Each entry
fixes a stop-loss AtrMultiplier ATRs from the entry close; an AtrMultiplier of 0 disables it.
"""
def __init__(self):
super(atr_stop_loss_double_sma_strategy, self).__init__()
self._fast_length = self.Param("FastLength", 15) \
.SetGreaterThanZero() \
.SetDisplay("Fast Length", "Fast SMA period", "Indicators")
self._slow_length = self.Param("SlowLength", 45) \
.SetGreaterThanZero() \
.SetDisplay("Slow Length", "Slow SMA period", "Indicators")
self._atr_length = self.Param("AtrLength", 14) \
.SetGreaterThanZero() \
.SetDisplay("ATR Length", "ATR period", "Risk")
self._atr_multiplier = self.Param("AtrMultiplier", 2.0) \
.SetNotNegative() \
.SetDisplay("ATR Multiplier", "Stop-loss distance in ATR multiples, 0 disables it", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(1))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._reset_state()
@property
def CandleType(self):
return self._candle_type.Value
def GetWorkingSecurities(self):
return [(self.Security, self.CandleType)]
def _reset_state(self):
self._prev_fast = None
self._prev_slow = None
self._stop_price = 0.0
def OnReseted(self):
super(atr_stop_loss_double_sma_strategy, self).OnReseted()
self._reset_state()
def OnStarted2(self, time):
super(atr_stop_loss_double_sma_strategy, self).OnStarted2(time)
self._reset_state()
fast = SimpleMovingAverage()
fast.Length = self._fast_length.Value
slow = SimpleMovingAverage()
slow.Length = self._slow_length.Value
atr = AverageTrueRange()
atr.Length = self._atr_length.Value
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(fast, slow, atr, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, fast)
self.DrawIndicator(area, slow)
self.DrawOwnTrades(area)
def _process_candle(self, candle, fast_value, slow_value, atr_value):
if candle.State != CandleStates.Finished:
return
fast = float(fast_value)
slow = float(slow_value)
prev_fast = self._prev_fast
prev_slow = self._prev_slow
self._prev_fast = fast
self._prev_slow = slow
if prev_fast is None or prev_slow is None:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
close = float(candle.ClosePrice)
multiplier = float(self._atr_multiplier.Value)
distance = multiplier * float(atr_value)
if prev_fast <= prev_slow and fast > slow and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
self._stop_price = close - distance
elif prev_fast >= prev_slow and fast < slow and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
self._stop_price = close + distance
elif multiplier > 0:
if self.Position > 0 and float(candle.LowPrice) <= self._stop_price:
self.SellMarket(self.Position)
elif self.Position < 0 and float(candle.HighPrice) >= self._stop_price:
self.BuyMarket(-self.Position)
def CreateClone(self):
return atr_stop_loss_double_sma_strategy()