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>
/// Strategy that opens positions using a simple MA crossover and protects
/// them with a trailing stop loss and take profit.
/// </summary>
public class AutoTrailingStopStrategy : Strategy
{
private readonly StrategyParam<int> _fastMaPeriod;
private readonly StrategyParam<int> _slowMaPeriod;
private readonly StrategyParam<decimal> _takeProfitPct;
private readonly StrategyParam<decimal> _stopLossPct;
private readonly StrategyParam<DataType> _candleType;
private SimpleMovingAverage _slowMa;
private decimal _prevFast;
private decimal _prevSlow;
private bool _isFirst = true;
public int FastMaPeriod { get => _fastMaPeriod.Value; set => _fastMaPeriod.Value = value; }
public int SlowMaPeriod { get => _slowMaPeriod.Value; set => _slowMaPeriod.Value = value; }
public decimal TakeProfitPct { get => _takeProfitPct.Value; set => _takeProfitPct.Value = value; }
public decimal StopLossPct { get => _stopLossPct.Value; set => _stopLossPct.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public AutoTrailingStopStrategy()
{
_fastMaPeriod = Param(nameof(FastMaPeriod), 5)
.SetGreaterThanZero()
.SetDisplay("Fast MA", "Fast moving average period", "Indicators");
_slowMaPeriod = Param(nameof(SlowMaPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("Slow MA", "Slow moving average period", "Indicators");
_takeProfitPct = Param(nameof(TakeProfitPct), 5m)
.SetDisplay("Take Profit %", "Take profit percentage", "Protection");
_stopLossPct = Param(nameof(StopLossPct), 3m)
.SetDisplay("Stop Loss %", "Initial stop loss percentage", "Protection");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(15).TimeFrame())
.SetDisplay("Candle Type", "Candle type for price updates", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevFast = 0;
_prevSlow = 0;
_isFirst = true;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fastMa = new SimpleMovingAverage { Length = FastMaPeriod };
_slowMa = new SimpleMovingAverage { Length = SlowMaPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fastMa, ProcessCandle)
.Start();
StartProtection(
stopLoss: new Unit(StopLossPct, UnitTypes.Percent),
takeProfit: new Unit(TakeProfitPct, UnitTypes.Percent)
);
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, fastMa);
DrawIndicator(area, _slowMa);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fast)
{
if (candle.State != CandleStates.Finished)
return;
var slowResult = _slowMa.Process(candle.ClosePrice, candle.OpenTime, true);
if (!slowResult.IsFormed)
return;
var slow = slowResult.ToDecimal();
if (_isFirst)
{
_prevFast = fast;
_prevSlow = slow;
_isFirst = false;
return;
}
// Bullish crossover: fast crosses above slow
if (_prevFast <= _prevSlow && fast > slow && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
}
// Bearish crossover: fast crosses below slow
else if (_prevFast >= _prevSlow && fast < slow && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
}
_prevFast = fast;
_prevSlow = slow;
}
}
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, Unit, UnitTypes
from StockSharp.Algo.Indicators import SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
from indicator_extensions import *
class auto_trailing_stop_strategy(Strategy):
def __init__(self):
super(auto_trailing_stop_strategy, self).__init__()
self._fast_ma_period = self.Param("FastMaPeriod", 5) \
.SetGreaterThanZero() \
.SetDisplay("Fast MA", "Fast moving average period", "Indicators")
self._slow_ma_period = self.Param("SlowMaPeriod", 20) \
.SetGreaterThanZero() \
.SetDisplay("Slow MA", "Slow moving average period", "Indicators")
self._take_profit_pct = self.Param("TakeProfitPct", 5.0) \
.SetDisplay("Take Profit %", "Take profit percentage", "Protection")
self._stop_loss_pct = self.Param("StopLossPct", 3.0) \
.SetDisplay("Stop Loss %", "Initial stop loss percentage", "Protection")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(15))) \
.SetDisplay("Candle Type", "Candle type for price updates", "General")
self._slow_ma = None
self._prev_fast = 0.0
self._prev_slow = 0.0
self._is_first = True
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(auto_trailing_stop_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._is_first = True
def OnStarted2(self, time):
super(auto_trailing_stop_strategy, self).OnStarted2(time)
fast_ma = SimpleMovingAverage()
fast_ma.Length = self._fast_ma_period.Value
self._slow_ma = SimpleMovingAverage()
self._slow_ma.Length = self._slow_ma_period.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(fast_ma, self.process_candle).Start()
self.StartProtection(
Unit(float(self._take_profit_pct.Value), UnitTypes.Percent),
Unit(float(self._stop_loss_pct.Value), UnitTypes.Percent))
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, fast_ma)
self.DrawIndicator(area, self._slow_ma)
self.DrawOwnTrades(area)
def process_candle(self, candle, fast):
if candle.State != CandleStates.Finished:
return
slow_result = process_float(self._slow_ma, candle.ClosePrice, candle.OpenTime, True)
if not slow_result.IsFormed:
return
slow = float(slow_result)
fast_val = float(fast)
if self._is_first:
self._prev_fast = fast_val
self._prev_slow = slow
self._is_first = False
return
if self._prev_fast <= self._prev_slow and fast_val > slow and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif self._prev_fast >= self._prev_slow and fast_val < slow and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_fast = fast_val
self._prev_slow = slow
def CreateClone(self):
return auto_trailing_stop_strategy()