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>
/// Trailing stop management based on CandleStop logic.
/// Uses EMA crossover for entries and Highest/Lowest channel for trailing exits.
/// </summary>
public class CandleStopTrailingStrategy : Strategy
{
private readonly StrategyParam<int> _trailPeriod;
private readonly StrategyParam<int> _fastEma;
private readonly StrategyParam<int> _slowEma;
private readonly StrategyParam<DataType> _candleType;
private Highest _highest;
private Lowest _lowest;
private decimal _stopPrice;
public int TrailPeriod { get => _trailPeriod.Value; set => _trailPeriod.Value = value; }
public int FastEma { get => _fastEma.Value; set => _fastEma.Value = value; }
public int SlowEma { get => _slowEma.Value; set => _slowEma.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public CandleStopTrailingStrategy()
{
_trailPeriod = Param(nameof(TrailPeriod), 5)
.SetDisplay("Trail Period", "Look-back for channel trailing", "Parameters");
_fastEma = Param(nameof(FastEma), 10)
.SetDisplay("Fast EMA", "Fast EMA period", "Parameters");
_slowEma = Param(nameof(SlowEma), 30)
.SetDisplay("Slow EMA", "Slow EMA period", "Parameters");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Candle type for analysis", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_highest = default;
_lowest = default;
_stopPrice = 0m;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fast = new ExponentialMovingAverage { Length = FastEma };
var slow = new ExponentialMovingAverage { Length = SlowEma };
_highest = new Highest { Length = TrailPeriod };
_lowest = new Lowest { Length = TrailPeriod };
Indicators.Add(_highest);
Indicators.Add(_lowest);
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fast, slow, (candle, fastVal, slowVal) =>
{
if (candle.State != CandleStates.Finished)
return;
var highResult = _highest.Process(candle);
var lowResult = _lowest.Process(candle);
if (!highResult.IsFormed || !lowResult.IsFormed)
return;
var upper = highResult.ToDecimal();
var lower = lowResult.ToDecimal();
// Entry logic based on EMA crossover
if (Position == 0)
{
if (fastVal > slowVal && candle.ClosePrice > slowVal)
{
BuyMarket();
_stopPrice = lower;
}
else if (fastVal < slowVal && candle.ClosePrice < slowVal)
{
SellMarket();
_stopPrice = upper;
}
}
else if (Position > 0)
{
if (lower > _stopPrice)
_stopPrice = lower;
if (candle.LowPrice <= _stopPrice)
{
SellMarket();
_stopPrice = 0m;
}
}
else if (Position < 0)
{
if (_stopPrice == 0 || upper < _stopPrice)
_stopPrice = upper;
if (candle.HighPrice >= _stopPrice)
{
BuyMarket();
_stopPrice = 0m;
}
}
})
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, fast);
DrawIndicator(area, slow);
DrawOwnTrades(area);
}
}
}
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 ExponentialMovingAverage, Highest, Lowest, CandleIndicatorValue
from StockSharp.Algo.Strategies import Strategy
class candle_stop_trailing_strategy(Strategy):
def __init__(self):
super(candle_stop_trailing_strategy, self).__init__()
self._trail_period = self.Param("TrailPeriod", 5) \
.SetDisplay("Trail Period", "Look-back for channel trailing", "Parameters")
self._fast_ema = self.Param("FastEma", 10) \
.SetDisplay("Fast EMA", "Fast EMA period", "Parameters")
self._slow_ema = self.Param("SlowEma", 30) \
.SetDisplay("Slow EMA", "Slow EMA period", "Parameters")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Candle type for analysis", "General")
self._highest = None
self._lowest = None
self._stop_price = 0.0
@property
def trail_period(self):
return self._trail_period.Value
@property
def fast_ema(self):
return self._fast_ema.Value
@property
def slow_ema(self):
return self._slow_ema.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(candle_stop_trailing_strategy, self).OnReseted()
self._highest = None
self._lowest = None
self._stop_price = 0.0
def OnStarted2(self, time):
super(candle_stop_trailing_strategy, self).OnStarted2(time)
fast = ExponentialMovingAverage()
fast.Length = self.fast_ema
slow = ExponentialMovingAverage()
slow.Length = self.slow_ema
self._highest = Highest()
self._highest.Length = self.trail_period
self._lowest = Lowest()
self._lowest.Length = self.trail_period
self.Indicators.Add(self._highest)
self.Indicators.Add(self._lowest)
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(fast, slow, self.on_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 on_candle(self, candle, fast_val, slow_val):
if candle.State != CandleStates.Finished:
return
fast_val = float(fast_val)
slow_val = float(slow_val)
cv_h = CandleIndicatorValue(self._highest, candle)
high_result = self._highest.Process(cv_h)
cv_l = CandleIndicatorValue(self._lowest, candle)
low_result = self._lowest.Process(cv_l)
if not high_result.IsFormed or not low_result.IsFormed:
return
upper = float(high_result)
lower = float(low_result)
if self.Position == 0:
if fast_val > slow_val and float(candle.ClosePrice) > slow_val:
self.BuyMarket()
self._stop_price = lower
elif fast_val < slow_val and float(candle.ClosePrice) < slow_val:
self.SellMarket()
self._stop_price = upper
elif self.Position > 0:
if lower > self._stop_price:
self._stop_price = lower
if float(candle.LowPrice) <= self._stop_price:
self.SellMarket()
self._stop_price = 0.0
elif self.Position < 0:
if self._stop_price == 0 or upper < self._stop_price:
self._stop_price = upper
if float(candle.HighPrice) >= self._stop_price:
self.BuyMarket()
self._stop_price = 0.0
def CreateClone(self):
return candle_stop_trailing_strategy()