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>
/// Moving average crossover strategy with risk management via StartProtection.
/// </summary>
public class MovingUpStrategy : Strategy
{
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<decimal> _stopLoss;
private readonly StrategyParam<decimal> _takeProfit;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<bool> _useTp, _useSl, _useTs;
private readonly StrategyParam<decimal> _trailingStop;
private Order _pending;
private bool _isInitialized;
private bool _wasFastBelowSlow;
public int FastLength { get => _fastLength.Value; set => _fastLength.Value = value; }
public int SlowLength { get => _slowLength.Value; set => _slowLength.Value = value; }
public decimal StopLoss { get => _stopLoss.Value; set => _stopLoss.Value = value; }
public decimal TakeProfit { get => _takeProfit.Value; set => _takeProfit.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public bool UseTakeProfit { get => _useTp.Value; set => _useTp.Value = value; }
public bool UseStopLoss { get => _useSl.Value; set => _useSl.Value = value; }
public bool UseTrailingStop { get => _useTs.Value; set => _useTs.Value = value; }
public decimal TrailingStop { get => _trailingStop.Value; set => _trailingStop.Value = value; }
public MovingUpStrategy()
{
_fastLength = Param(nameof(FastLength), 13)
.SetGreaterThanZero()
.SetDisplay("Fast MA", "Fast MA period", "MA");
_slowLength = Param(nameof(SlowLength), 21)
.SetGreaterThanZero()
.SetDisplay("Slow MA", "Slow MA period", "MA");
_stopLoss = Param(nameof(StopLoss), 250m)
.SetGreaterThanZero()
.SetDisplay("SL", "Stop loss distance", "Risk");
_takeProfit = Param(nameof(TakeProfit), 500m)
.SetGreaterThanZero()
.SetDisplay("TP", "Take profit distance", "Risk");
_useTp = Param(nameof(UseTakeProfit), true);
_useSl = Param(nameof(UseStopLoss), true);
_useTs = Param(nameof(UseTrailingStop), false);
_trailingStop = Param(nameof(TrailingStop), 200m).SetNotNegative();
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(1).TimeFrame())
.SetDisplay("Candle", "Candle type", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_isInitialized = default;
_wasFastBelowSlow = default;
_pending = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_pending = null;
var fastMa = new SimpleMovingAverage { Length = FastLength };
var slowMa = new SimpleMovingAverage { Length = SlowLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fastMa, slowMa, ProcessCandle)
.Start();
StartProtection(
takeProfit: new Unit(UseTakeProfit ? TakeProfit : 0m, UnitTypes.Absolute),
stopLoss: new Unit(UseStopLoss ? StopLoss : 0m, UnitTypes.Absolute), useMarketOrders: true);
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (!_isInitialized)
{
_wasFastBelowSlow = fast < slow;
_isInitialized = true;
return;
}
var isFastBelowSlow = fast < slow;
if (_wasFastBelowSlow != isFastBelowSlow && (_pending is null || _pending.State is OrderStates.Done or OrderStates.Failed))
{
if (!isFastBelowSlow && Position <= 0)
{
_pending = BuyMarket(Volume + Math.Abs(Math.Min(0m, Position)));
}
else if (isFastBelowSlow && Position >= 0)
{
_pending = SellMarket(Volume + Math.Max(0m, Position));
}
_wasFastBelowSlow = isFastBelowSlow;
}
}
}
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, OrderStates
from StockSharp.Algo.Indicators import SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class moving_up_strategy(Strategy):
def __init__(self):
super(moving_up_strategy, self).__init__()
self._fast_length = self.Param("FastLength", 13) \
.SetDisplay("Fast MA", "Fast MA period", "MA")
self._slow_length = self.Param("SlowLength", 21) \
.SetDisplay("Slow MA", "Slow MA period", "MA")
self._stop_loss = self.Param("StopLoss", 250.0) \
.SetDisplay("SL", "Stop loss distance", "Risk")
self._take_profit = self.Param("TakeProfit", 500.0) \
.SetDisplay("TP", "Take profit distance", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(1))) \
.SetDisplay("Candle", "Candle type", "General")
self._use_tp = self.Param("UseTakeProfit", True)
self._use_sl = self.Param("UseStopLoss", True)
self._use_ts = self.Param("UseTrailingStop", False)
self._trailing_stop = self.Param("TrailingStop", 200.0)
self._pending = None
self._is_initialized = False
self._was_fast_below_slow = False
@property
def FastLength(self):
return self._fast_length.Value
@FastLength.setter
def FastLength(self, value):
self._fast_length.Value = value
@property
def SlowLength(self):
return self._slow_length.Value
@SlowLength.setter
def SlowLength(self, value):
self._slow_length.Value = value
@property
def StopLoss(self):
return self._stop_loss.Value
@StopLoss.setter
def StopLoss(self, value):
self._stop_loss.Value = value
@property
def TakeProfit(self):
return self._take_profit.Value
@TakeProfit.setter
def TakeProfit(self, value):
self._take_profit.Value = value
@property
def CandleType(self):
return self._candle_type.Value
@CandleType.setter
def CandleType(self, value):
self._candle_type.Value = value
def OnStarted2(self, time):
super(moving_up_strategy, self).OnStarted2(time)
self._pending = None
fast_ma = SimpleMovingAverage()
fast_ma.Length = self.FastLength
slow_ma = SimpleMovingAverage()
slow_ma.Length = self.SlowLength
self.SubscribeCandles(self.CandleType) \
.Bind(fast_ma, slow_ma, self.ProcessCandle) \
.Start()
self.StartProtection(
stopLoss=Unit(self.StopLoss if self._use_sl.Value else 0, UnitTypes.Absolute),
takeProfit=Unit(self.TakeProfit if self._use_tp.Value else 0, UnitTypes.Absolute), useMarketOrders=True
)
def ProcessCandle(self, candle, fast_value, slow_value):
if candle.State != CandleStates.Finished:
return
fast = float(fast_value)
slow = float(slow_value)
if not self._is_initialized:
self._was_fast_below_slow = fast < slow
self._is_initialized = True
return
is_fast_below_slow = fast < slow
if self._was_fast_below_slow != is_fast_below_slow and self.IsFormedAndOnlineAndAllowTrading() and (self._pending is None or self._pending.State in (OrderStates.Done, OrderStates.Failed)):
if not is_fast_below_slow and self.Position <= 0:
self._pending = self.BuyMarket(self.Volume + abs(min(self.Position, 0)))
elif is_fast_below_slow and self.Position >= 0:
self._pending = self.SellMarket(self.Volume + max(self.Position, 0))
self._was_fast_below_slow = is_fast_below_slow
def OnReseted(self):
super(moving_up_strategy, self).OnReseted()
self._is_initialized = False
self._was_fast_below_slow = False
def CreateClone(self):
return moving_up_strategy()