Расширенная стратегия Supertrend
Расширенная стратегия Supertrend дополняет классический индикатор Supertrend опциональными фильтрами RSI, скользящей средней и силы тренда. Вход в лонг происходит при смене Supertrend на бычий, вход в шорт — при смене на медвежий. Необязательные стоп‑лосс и тейк‑профит рассчитываются как кратные ATR.
Подробности
- Условия входа:
- Изменение направления Supertrend (медвежий→бычий для лонга, бычий→медвежий для шорта).
- Дополнительно: RSI в заданных пределах, цена относительно скользящей средней, сила тренда и подтверждение пробоя.
- Направление: Лонг и шорт.
- Условия выхода:
- Противоположный сигнал Supertrend или опциональные уровни стоп‑лосса/тейк‑профита.
- Стопы: Необязательные стоп‑лосс и тейк‑профит на основе ATR.
- Параметры по умолчанию:
AtrLength= 6Multiplier= 3.0UseRsiFilter= falseRsiLength= 14RsiOverbought= 70RsiOversold= 30UseMaFilter= trueMaLength= 50MaType= WeightedUseStopLoss= trueSlMultiplier= 3.0UseTakeProfit= trueTpMultiplier= 9.0UseTrendStrength= falseMinTrendBars= 2UseBreakoutConfirmation= true
- Фильтры:
- Категория: Следование тренду
- Направление: Лонг и шорт
- Индикаторы: Supertrend, RSI, скользящая средняя
- Стопы: На основе 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>
/// Advanced Supertrend strategy with EMA trend filter and ATR-based stops.
/// </summary>
public class AdvancedSupertrendStrategy : Strategy
{
private readonly StrategyParam<int> _atrLength;
private readonly StrategyParam<decimal> _multiplier;
private readonly StrategyParam<int> _maLength;
private readonly StrategyParam<int> _atrStopLength;
private readonly StrategyParam<decimal> _slMultiplier;
private readonly StrategyParam<decimal> _tpMultiplier;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _cooldownBars;
private bool _prevUpTrend;
private bool _hasPrev;
private decimal _entryPrice;
private decimal _atrAtEntry;
private int _cooldownRemaining;
public int AtrLength { get => _atrLength.Value; set => _atrLength.Value = value; }
public decimal Multiplier { get => _multiplier.Value; set => _multiplier.Value = value; }
public int MaLength { get => _maLength.Value; set => _maLength.Value = value; }
public int AtrStopLength { get => _atrStopLength.Value; set => _atrStopLength.Value = value; }
public decimal SlMultiplier { get => _slMultiplier.Value; set => _slMultiplier.Value = value; }
public decimal TpMultiplier { get => _tpMultiplier.Value; set => _tpMultiplier.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public int CooldownBars { get => _cooldownBars.Value; set => _cooldownBars.Value = value; }
public AdvancedSupertrendStrategy()
{
_atrLength = Param(nameof(AtrLength), 10)
.SetGreaterThanZero()
.SetDisplay("ATR Length", "ATR period for SuperTrend", "SuperTrend");
_multiplier = Param(nameof(Multiplier), 3m)
.SetDisplay("Multiplier", "SuperTrend multiplier", "SuperTrend");
_maLength = Param(nameof(MaLength), 50)
.SetGreaterThanZero()
.SetDisplay("EMA Length", "EMA period for trend filter", "Filters");
_atrStopLength = Param(nameof(AtrStopLength), 14)
.SetGreaterThanZero()
.SetDisplay("ATR Stop Length", "ATR period for stops", "Risk");
_slMultiplier = Param(nameof(SlMultiplier), 2m)
.SetDisplay("SL Multiplier", "Stop loss ATR multiplier", "Risk");
_tpMultiplier = Param(nameof(TpMultiplier), 4m)
.SetDisplay("TP Multiplier", "Take profit ATR multiplier", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(30).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
_cooldownBars = Param(nameof(CooldownBars), 10)
.SetDisplay("Cooldown Bars", "Bars between trades", "Risk");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevUpTrend = false;
_hasPrev = false;
_entryPrice = 0;
_atrAtEntry = 0;
_cooldownRemaining = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var st = new SuperTrend { Length = AtrLength, Multiplier = Multiplier };
var ema = new ExponentialMovingAverage { Length = MaLength };
var atr = new AverageTrueRange { Length = AtrStopLength };
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(st, ema, atr, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, st);
DrawIndicator(area, ema);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue stValue, IIndicatorValue emaValue, IIndicatorValue atrValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (stValue.IsEmpty || emaValue.IsEmpty || atrValue.IsEmpty)
return;
var stv = (SuperTrendIndicatorValue)stValue;
var upTrend = stv.IsUpTrend;
var emaVal = emaValue.ToDecimal();
var atrVal = atrValue.ToDecimal();
if (!_hasPrev)
{
_prevUpTrend = upTrend;
_hasPrev = true;
return;
}
// Check stop/TP
if (Position > 0 && _entryPrice > 0 && _atrAtEntry > 0)
{
var sl = _entryPrice - _atrAtEntry * SlMultiplier;
var tp = _entryPrice + _atrAtEntry * TpMultiplier;
if (candle.ClosePrice <= sl || candle.ClosePrice >= tp)
{
SellMarket(Math.Abs(Position));
_entryPrice = 0;
_cooldownRemaining = CooldownBars;
_prevUpTrend = upTrend;
return;
}
}
else if (Position < 0 && _entryPrice > 0 && _atrAtEntry > 0)
{
var sl = _entryPrice + _atrAtEntry * SlMultiplier;
var tp = _entryPrice - _atrAtEntry * TpMultiplier;
if (candle.ClosePrice >= sl || candle.ClosePrice <= tp)
{
BuyMarket(Math.Abs(Position));
_entryPrice = 0;
_cooldownRemaining = CooldownBars;
_prevUpTrend = upTrend;
return;
}
}
if (_cooldownRemaining > 0)
{
_cooldownRemaining--;
_prevUpTrend = upTrend;
return;
}
var bullishFlip = upTrend && !_prevUpTrend;
var bearishFlip = !upTrend && _prevUpTrend;
if (bullishFlip && candle.ClosePrice > emaVal && Position <= 0)
{
if (Position < 0)
BuyMarket(Math.Abs(Position));
BuyMarket(Volume);
_entryPrice = candle.ClosePrice;
_atrAtEntry = atrVal;
_cooldownRemaining = CooldownBars;
}
else if (bearishFlip && candle.ClosePrice < emaVal && Position >= 0)
{
if (Position > 0)
SellMarket(Math.Abs(Position));
SellMarket(Volume);
_entryPrice = candle.ClosePrice;
_atrAtEntry = atrVal;
_cooldownRemaining = CooldownBars;
}
_prevUpTrend = upTrend;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import SuperTrend, ExponentialMovingAverage, AverageTrueRange, IndicatorHelper
from StockSharp.Algo.Strategies import Strategy
class advanced_supertrend_strategy(Strategy):
def __init__(self):
super(advanced_supertrend_strategy, self).__init__()
self._atr_length = self.Param("AtrLength", 10) \
.SetGreaterThanZero() \
.SetDisplay("ATR Length", "ATR period for SuperTrend", "SuperTrend")
self._multiplier = self.Param("Multiplier", 3.0) \
.SetDisplay("Multiplier", "SuperTrend multiplier", "SuperTrend")
self._ma_length = self.Param("MaLength", 50) \
.SetGreaterThanZero() \
.SetDisplay("EMA Length", "EMA period for trend filter", "Filters")
self._atr_stop_length = self.Param("AtrStopLength", 14) \
.SetGreaterThanZero() \
.SetDisplay("ATR Stop Length", "ATR period for stops", "Risk")
self._sl_multiplier = self.Param("SlMultiplier", 2.0) \
.SetDisplay("SL Multiplier", "Stop loss ATR multiplier", "Risk")
self._tp_multiplier = self.Param("TpMultiplier", 4.0) \
.SetDisplay("TP Multiplier", "Take profit ATR multiplier", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(30))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._cooldown_bars = self.Param("CooldownBars", 10) \
.SetDisplay("Cooldown Bars", "Bars between trades", "Risk")
self._prev_up_trend = False
self._has_prev = False
self._entry_price = 0.0
self._atr_at_entry = 0.0
self._cooldown_remaining = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(advanced_supertrend_strategy, self).OnReseted()
self._prev_up_trend = False
self._has_prev = False
self._entry_price = 0.0
self._atr_at_entry = 0.0
self._cooldown_remaining = 0
def OnStarted2(self, time):
super(advanced_supertrend_strategy, self).OnStarted2(time)
st = SuperTrend()
st.Length = int(self._atr_length.Value)
st.Multiplier = self._multiplier.Value
ema = ExponentialMovingAverage()
ema.Length = int(self._ma_length.Value)
atr = AverageTrueRange()
atr.Length = int(self._atr_stop_length.Value)
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(st, ema, atr, self._on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, st)
self.DrawIndicator(area, ema)
self.DrawOwnTrades(area)
def _on_process(self, candle, st_value, ema_value, atr_value):
if candle.State != CandleStates.Finished:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
if st_value.IsEmpty or ema_value.IsEmpty or atr_value.IsEmpty:
return
up_trend = st_value.IsUpTrend
ema_v = float(IndicatorHelper.ToDecimal(ema_value))
atr_v = float(IndicatorHelper.ToDecimal(atr_value))
close = float(candle.ClosePrice)
if not self._has_prev:
self._prev_up_trend = up_trend
self._has_prev = True
return
sl_mult = float(self._sl_multiplier.Value)
tp_mult = float(self._tp_multiplier.Value)
cooldown = int(self._cooldown_bars.Value)
# Check stop/TP
if self.Position > 0 and self._entry_price > 0 and self._atr_at_entry > 0:
sl = self._entry_price - self._atr_at_entry * sl_mult
tp = self._entry_price + self._atr_at_entry * tp_mult
if close <= sl or close >= tp:
self.SellMarket(Math.Abs(self.Position))
self._entry_price = 0.0
self._cooldown_remaining = cooldown
self._prev_up_trend = up_trend
return
elif self.Position < 0 and self._entry_price > 0 and self._atr_at_entry > 0:
sl = self._entry_price + self._atr_at_entry * sl_mult
tp = self._entry_price - self._atr_at_entry * tp_mult
if close >= sl or close <= tp:
self.BuyMarket(Math.Abs(self.Position))
self._entry_price = 0.0
self._cooldown_remaining = cooldown
self._prev_up_trend = up_trend
return
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
self._prev_up_trend = up_trend
return
bullish_flip = up_trend and not self._prev_up_trend
bearish_flip = not up_trend and self._prev_up_trend
if bullish_flip and close > ema_v and self.Position <= 0:
if self.Position < 0:
self.BuyMarket(Math.Abs(self.Position))
self.BuyMarket(self.Volume)
self._entry_price = close
self._atr_at_entry = atr_v
self._cooldown_remaining = cooldown
elif bearish_flip and close < ema_v and self.Position >= 0:
if self.Position > 0:
self.SellMarket(Math.Abs(self.Position))
self.SellMarket(self.Volume)
self._entry_price = close
self._atr_at_entry = atr_v
self._cooldown_remaining = cooldown
self._prev_up_trend = up_trend
def CreateClone(self):
return advanced_supertrend_strategy()