Стратегия Universal Trailing Stop Hedge
Стратегия демонстрирует различные методы трейлинг-стопа для защиты открытых позиций. Поддерживает варианты на основе ATR, Parabolic SAR, скользящей средней, процента прибыли и фиксированного числа пунктов. Простое правило входа по направлению свечи используется только в обучающих целях.
Подробности
- Условия входа: длинная, если свеча закрылась выше открытия; короткая, если закрылась ниже
- Long/Short: Оба
- Условия выхода: срабатывание трейлинг-стопа
- Стопы: ATR, Parabolic SAR, скользящая средняя, процент прибыли или фиксированные пункты в зависимости от режима
- Параметры по умолчанию:
Mode=TrailingModes.AtrDelta= 10AtrPeriod= 14AtrMultiplier= 1mSarStep= 0.02mSarMax= 0.2mMaPeriod= 34PercentProfit= 50mCandleType= TimeSpan.FromMinutes(5).TimeFrame()
- Фильтры:
- Категория: управление риском
- Направление: оба
- Индикаторы: ATR, Parabolic SAR, SMA
- Стопы: трейлинг-стоп
- Сложность: средняя
- Таймфрейм: внутридневной
- Сезонность: нет
- Нейросети: нет
- Дивергенция: нет
- Уровень риска: средний
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-based trailing stop strategy.
/// Enters on candle direction, trails stop using ATR distance.
/// </summary>
public class UniversalTrailingStopHedgeStrategy : Strategy
{
private readonly StrategyParam<int> _atrPeriod;
private readonly StrategyParam<decimal> _atrMultiplier;
private readonly StrategyParam<DataType> _candleType;
private decimal _entryPrice;
private decimal _trailingStop;
public int AtrPeriod { get => _atrPeriod.Value; set => _atrPeriod.Value = value; }
public decimal AtrMultiplier { get => _atrMultiplier.Value; set => _atrMultiplier.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public UniversalTrailingStopHedgeStrategy()
{
_atrPeriod = Param(nameof(AtrPeriod), 14)
.SetDisplay("ATR Period", "ATR calculation period", "Indicators");
_atrMultiplier = Param(nameof(AtrMultiplier), 2m)
.SetDisplay("ATR Multiplier", "ATR multiplier for stop distance", "Indicators")
.SetGreaterThanZero();
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Timeframe for calculations", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_entryPrice = 0;
_trailingStop = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_entryPrice = 0;
_trailingStop = 0;
var atr = new AverageTrueRange { Length = AtrPeriod };
var subscription = SubscribeCandles(CandleType);
subscription.Bind(atr, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, atr);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal atr)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var distance = atr * AtrMultiplier;
if (Position == 0)
{
// Enter based on candle direction
if (candle.ClosePrice > candle.OpenPrice)
{
BuyMarket();
_entryPrice = candle.ClosePrice;
_trailingStop = candle.ClosePrice - distance;
}
else if (candle.ClosePrice < candle.OpenPrice)
{
SellMarket();
_entryPrice = candle.ClosePrice;
_trailingStop = candle.ClosePrice + distance;
}
return;
}
if (Position > 0)
{
var newStop = candle.ClosePrice - distance;
if (newStop > _trailingStop)
_trailingStop = newStop;
if (candle.LowPrice <= _trailingStop)
{
SellMarket();
_trailingStop = 0;
}
}
else if (Position < 0)
{
var newStop = candle.ClosePrice + distance;
if (newStop < _trailingStop || _trailingStop == 0)
_trailingStop = newStop;
if (candle.HighPrice >= _trailingStop)
{
BuyMarket();
_trailingStop = 0;
}
}
}
}
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
from StockSharp.Algo.Strategies import Strategy
class universal_trailing_stop_hedge_strategy(Strategy):
def __init__(self):
super(universal_trailing_stop_hedge_strategy, self).__init__()
self._atr_period = self.Param("AtrPeriod", 14) \
.SetDisplay("ATR Period", "ATR calculation period", "Indicators")
self._atr_multiplier = self.Param("AtrMultiplier", 2.0) \
.SetDisplay("ATR Multiplier", "ATR multiplier for stop distance", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Timeframe for calculations", "General")
self._entry_price = 0.0
self._trailing_stop = 0.0
@property
def atr_period(self):
return self._atr_period.Value
@property
def atr_multiplier(self):
return self._atr_multiplier.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(universal_trailing_stop_hedge_strategy, self).OnReseted()
self._entry_price = 0.0
self._trailing_stop = 0.0
def OnStarted2(self, time):
super(universal_trailing_stop_hedge_strategy, self).OnStarted2(time)
self._entry_price = 0.0
self._trailing_stop = 0.0
atr = AverageTrueRange()
atr.Length = self.atr_period
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(atr, self.process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, atr)
self.DrawOwnTrades(area)
def process_candle(self, candle, atr):
if candle.State != CandleStates.Finished:
return
atr = float(atr)
distance = atr * float(self.atr_multiplier)
close_price = float(candle.ClosePrice)
open_price = float(candle.OpenPrice)
high_price = float(candle.HighPrice)
low_price = float(candle.LowPrice)
if self.Position == 0:
if close_price > open_price:
self.BuyMarket()
self._entry_price = close_price
self._trailing_stop = close_price - distance
elif close_price < open_price:
self.SellMarket()
self._entry_price = close_price
self._trailing_stop = close_price + distance
return
if self.Position > 0:
new_stop = close_price - distance
if new_stop > self._trailing_stop:
self._trailing_stop = new_stop
if low_price <= self._trailing_stop:
self.SellMarket()
self._trailing_stop = 0.0
elif self.Position < 0:
new_stop = close_price + distance
if new_stop < self._trailing_stop or self._trailing_stop == 0.0:
self._trailing_stop = new_stop
if high_price >= self._trailing_stop:
self.BuyMarket()
self._trailing_stop = 0.0
def CreateClone(self):
return universal_trailing_stop_hedge_strategy()