Стратегия Super Trend
Стратегия основана на индикаторе Supertrend.
Тестирование показывает среднегодичную доходность около 67%. Стратегию лучше запускать на фондовом рынке.
Super Trend строит динамическую линию по ATR, которая чередуется между поддержкой и сопротивлением. Пересечение цены выше неё меняет уклон на бычий, ниже — на медвежий. Сделка завершается, когда линия разворачивается.
Следуя этой адаптивной линии, стратегия пытается захватывать устойчивые движения и снижать ложные входы. Стоп следует за ценой, фиксируя прибыль, когда импульс угасает.
Детали
- Критерии входа: сигналы на основе ATR, Supertrend.
- Длинные/короткие: оба направления.
- Критерии выхода: противоположный сигнал.
- Стопы: нет.
- Значения по умолчанию:
Period= 10Multiplier= 3.0mCandleType= TimeSpan.FromMinutes(5)
- Фильтры:
- Категория: Тренд
- Направление: Оба
- Индикаторы: ATR, Supertrend
- Стопы: Нет
- Сложность: Базовая
- Таймфрейм: Внутридневной (5m)
- Сезонность: Нет
- Нейросети: Нет
- Дивергенция: Нет
- Уровень риска: Средний
using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Strategy based on Supertrend indicator.
/// It turns long when the Supertrend line flips below price and short when it flips above, reversing on every flip.
/// </summary>
public class SupertrendStrategy : Strategy
{
private readonly StrategyParam<int> _period;
private readonly StrategyParam<decimal> _multiplier;
private readonly StrategyParam<DataType> _candleType;
// Trend of the previous candle; unknown until the indicator forms.
private bool? _prevIsUpTrend;
/// <summary>
/// Period for Supertrend calculation.
/// </summary>
public int Period
{
get => _period.Value;
set => _period.Value = value;
}
/// <summary>
/// Multiplier for Supertrend calculation.
/// </summary>
public decimal Multiplier
{
get => _multiplier.Value;
set => _multiplier.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initialize the Supertrend strategy.
/// </summary>
public SupertrendStrategy()
{
_period = Param(nameof(Period), 10)
.SetGreaterThanZero()
.SetDisplay("Period", "Period for Supertrend calculation", "Indicators")
.SetOptimize(7, 21, 2);
_multiplier = Param(nameof(Multiplier), 3.0m)
.SetGreaterThanZero()
.SetDisplay("Multiplier", "Multiplier for Supertrend calculation", "Indicators")
.SetOptimize(2.0m, 4.0m, 0.5m);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).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();
_prevIsUpTrend = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
// Create custom supertrend indicator
// Since StockSharp doesn't have a built-in Supertrend indicator,
// we'll use ATR to calculate the basic components
var supertrend = new SuperTrend { Length = Period, Multiplier = Multiplier };
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(supertrend, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, supertrend);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue supertrendValue)
{
if (candle.State != CandleStates.Finished || !supertrendValue.IsFormed || supertrendValue is not SuperTrendIndicatorValue value)
return;
var isUpTrend = value.IsUpTrend;
var wasUpTrend = _prevIsUpTrend;
_prevIsUpTrend = isUpTrend;
if (wasUpTrend is not bool wasUp || wasUp == isUpTrend)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var line = value.Value;
if (isUpTrend && Position <= 0)
{
BuyMarket(Volume + Math.Abs(Position));
LogInfo($"Buy signal: Price ({candle.ClosePrice}) crossed above Supertrend ({line})");
}
else if (!isUpTrend && Position >= 0)
{
SellMarket(Volume + Math.Abs(Position));
LogInfo($"Sell signal: Price ({candle.ClosePrice}) crossed below Supertrend ({line})");
}
}
}
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, Decimal
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import SuperTrend
from StockSharp.Algo.Strategies import Strategy
class supertrend_strategy(Strategy):
"""
Strategy based on Supertrend indicator.
It turns long when the Supertrend line flips below price and short when it flips above, reversing on every flip.
"""
def __init__(self):
super(supertrend_strategy, self).__init__()
self._period = self.Param("Period", 10).SetGreaterThanZero().SetDisplay("Period", "Period for Supertrend calculation", "Indicators")
self._multiplier = self.Param("Multiplier", 3.0).SetGreaterThanZero().SetDisplay("Multiplier", "Multiplier for Supertrend calculation", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))).SetDisplay("Candle Type", "Type of candles to use", "General")
# Trend of the previous candle; unknown until the indicator forms.
self._prev_is_up_trend = None
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(supertrend_strategy, self).OnReseted()
self._prev_is_up_trend = None
def OnStarted2(self, time):
super(supertrend_strategy, self).OnStarted2(time)
supertrend = SuperTrend()
supertrend.Length = self._period.Value
supertrend.Multiplier = Decimal(self._multiplier.Value)
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(supertrend, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, supertrend)
self.DrawOwnTrades(area)
def _process_candle(self, candle, supertrend_value):
if candle.State != CandleStates.Finished or not supertrend_value.IsFormed:
return
is_up_trend = supertrend_value.IsUpTrend
was_up_trend = self._prev_is_up_trend
self._prev_is_up_trend = is_up_trend
if was_up_trend is None or was_up_trend == is_up_trend:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
if is_up_trend and self.Position <= 0:
self.BuyMarket(self.Volume + Math.Abs(self.Position))
elif not is_up_trend and self.Position >= 0:
self.SellMarket(self.Volume + Math.Abs(self.Position))
def CreateClone(self):
return supertrend_strategy()