View on GitHub
Up3x1 Strategy
The Up3x1 strategy uses three simple moving averages to capture trend changes:
- Fast SMA: reacts quickly to price changes.
- Middle SMA: provides additional confirmation of the trend.
- Slow SMA: defines the global direction of the market.
Entry Rules
- Buy when the fast SMA crosses above the middle SMA and both are below the slow SMA.
- Sell when the fast SMA crosses below the middle SMA and both are above the slow SMA.
Exit Rules
- A fixed take profit and stop loss are applied to each position.
- An optional trailing stop can protect profits by following the price after entry.
Parameters
Volume – order size.
TakeProfit – profit target in price units.
StopLoss – loss limit in price units.
TrailingStop – trailing distance; set to 0 to disable.
FastPeriod, MiddlePeriod, SlowPeriod – lengths of the moving averages.
CandleType – candle timeframe used for calculations.
The strategy is designed for demonstration and can be further customized for specific trading instruments or conditions.
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>
/// Triple moving average crossover strategy.
/// </summary>
public class Up3x1Strategy : Strategy
{
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _middlePeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevFast;
private decimal _prevMiddle;
private bool _isInitialized;
public int FastPeriod { get => _fastPeriod.Value; set => _fastPeriod.Value = value; }
public int MiddlePeriod { get => _middlePeriod.Value; set => _middlePeriod.Value = value; }
public int SlowPeriod { get => _slowPeriod.Value; set => _slowPeriod.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public Up3x1Strategy()
{
_fastPeriod = Param(nameof(FastPeriod), 12)
.SetDisplay("Fast Period", "Fast EMA period", "General");
_middlePeriod = Param(nameof(MiddlePeriod), 26)
.SetDisplay("Middle Period", "Middle EMA period", "General");
_slowPeriod = Param(nameof(SlowPeriod), 50)
.SetDisplay("Slow Period", "Slow EMA period", "General");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Candle Type", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
protected override void OnReseted()
{
base.OnReseted();
_prevFast = 0;
_prevMiddle = 0;
_isInitialized = false;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fastMa = new ExponentialMovingAverage { Length = FastPeriod };
var middleMa = new ExponentialMovingAverage { Length = MiddlePeriod };
var slowMa = new ExponentialMovingAverage { Length = SlowPeriod };
SubscribeCandles(CandleType)
.Bind(fastMa, middleMa, slowMa, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal middle, decimal slow)
{
if (candle.State != CandleStates.Finished) return;
if (!_isInitialized)
{
_prevFast = fast;
_prevMiddle = middle;
_isInitialized = true;
return;
}
// Buy: fast crosses above middle
var buySignal = _prevFast <= _prevMiddle && fast > middle;
// Sell: fast crosses below middle
var sellSignal = _prevFast >= _prevMiddle && fast < middle;
_prevFast = fast;
_prevMiddle = middle;
if (buySignal && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
}
else if (sellSignal && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
}
}
}
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
from StockSharp.Algo.Strategies import Strategy
class up3x1_strategy(Strategy):
def __init__(self):
super(up3x1_strategy, self).__init__()
self._fast_period = self.Param("FastPeriod", 12) \
.SetDisplay("Fast Period", "Fast EMA period", "General")
self._middle_period = self.Param("MiddlePeriod", 26) \
.SetDisplay("Middle Period", "Middle EMA period", "General")
self._slow_period = self.Param("SlowPeriod", 50) \
.SetDisplay("Slow Period", "Slow EMA period", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Candle Type", "General")
self._prev_fast = 0.0
self._prev_middle = 0.0
self._is_initialized = False
@property
def fast_period(self):
return self._fast_period.Value
@property
def middle_period(self):
return self._middle_period.Value
@property
def slow_period(self):
return self._slow_period.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(up3x1_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_middle = 0.0
self._is_initialized = False
def OnStarted2(self, time):
super(up3x1_strategy, self).OnStarted2(time)
fast_ma = ExponentialMovingAverage()
fast_ma.Length = self.fast_period
middle_ma = ExponentialMovingAverage()
middle_ma.Length = self.middle_period
slow_ma = ExponentialMovingAverage()
slow_ma.Length = self.slow_period
self.SubscribeCandles(self.candle_type).Bind(fast_ma, middle_ma, slow_ma, self.process_candle).Start()
def process_candle(self, candle, fast, middle, slow):
if candle.State != CandleStates.Finished:
return
fv = float(fast)
mv = float(middle)
if not self._is_initialized:
self._prev_fast = fv
self._prev_middle = mv
self._is_initialized = True
return
buy_signal = self._prev_fast <= self._prev_middle and fv > mv
sell_signal = self._prev_fast >= self._prev_middle and fv < mv
self._prev_fast = fv
self._prev_middle = mv
if buy_signal and self.Position <= 0:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif sell_signal and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
def CreateClone(self):
return up3x1_strategy()