Multi-Step FlexiMA Strategy
Uses a variable-length moving average oscillator with a SuperTrend filter and multi-step take profit.
- Long when price is above the SuperTrend line and the oscillator is positive.
- Short when price is below the SuperTrend line and the oscillator is negative.
- Partial exits at three take-profit levels.
- Close remaining position when the opposite condition appears.
Indicators: Variable-length SMA oscillator, SuperTrend Stops: multi-step take profit only
using System;
using System.Linq;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Serialization;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Multi-step FlexiMA strategy using fast and slow SMA crossover.
/// </summary>
public class MultiStepFlexiMaStrategy : Strategy
{
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<int> _signalCooldownBars;
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public int FastLength { get => _fastLength.Value; set => _fastLength.Value = value; }
public int SlowLength { get => _slowLength.Value; set => _slowLength.Value = value; }
public int SignalCooldownBars { get => _signalCooldownBars.Value; set => _signalCooldownBars.Value = value; }
public MultiStepFlexiMaStrategy()
{
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(15).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
_fastLength = Param(nameof(FastLength), 10)
.SetGreaterThanZero()
.SetDisplay("Fast Length", "Fast SMA period", "FlexiMA");
_slowLength = Param(nameof(SlowLength), 30)
.SetGreaterThanZero()
.SetDisplay("Slow Length", "Slow SMA period", "FlexiMA");
_signalCooldownBars = Param(nameof(SignalCooldownBars), 4)
.SetGreaterThanZero()
.SetDisplay("Signal Cooldown", "Bars to wait between crossovers", "FlexiMA");
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fastSma = new SMA { Length = FastLength };
var slowSma = new SMA { Length = SlowLength };
var prevFast = 0m;
var prevSlow = 0m;
var initialized = false;
var cooldownRemaining = 0;
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(candle =>
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (cooldownRemaining > 0)
cooldownRemaining--;
var fastResult = fastSma.Process(candle);
var slowResult = slowSma.Process(candle);
if (!fastSma.IsFormed || !slowSma.IsFormed || fastResult.IsEmpty || slowResult.IsEmpty)
return;
var fastVal = fastResult.ToDecimal();
var slowVal = slowResult.ToDecimal();
if (!initialized)
{
prevFast = fastVal;
prevSlow = slowVal;
initialized = true;
return;
}
if (cooldownRemaining == 0 && prevFast <= prevSlow && fastVal > slowVal && Position <= 0)
{
BuyMarket();
cooldownRemaining = SignalCooldownBars;
}
else if (cooldownRemaining == 0 && prevFast >= prevSlow && fastVal < slowVal && Position > 0)
{
SellMarket();
cooldownRemaining = SignalCooldownBars;
}
prevFast = fastVal;
prevSlow = slowVal;
})
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, fastSma);
DrawIndicator(area, slowSma);
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 SimpleMovingAverage
from StockSharp.Algo.Strategies import Strategy
class multi_step_flexi_ma_strategy(Strategy):
def __init__(self):
super(multi_step_flexi_ma_strategy, self).__init__()
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(15))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._fast_length = self.Param("FastLength", 10) \
.SetGreaterThanZero() \
.SetDisplay("Fast Length", "Fast SMA period", "FlexiMA")
self._slow_length = self.Param("SlowLength", 30) \
.SetGreaterThanZero() \
.SetDisplay("Slow Length", "Slow SMA period", "FlexiMA")
self._signal_cooldown_bars = self.Param("SignalCooldownBars", 4) \
.SetGreaterThanZero() \
.SetDisplay("Signal Cooldown", "Bars to wait between crossovers", "FlexiMA")
self._prev_fast = 0.0
self._prev_slow = 0.0
self._initialized = False
self._cooldown_remaining = 0
@property
def candle_type(self):
return self._candle_type.Value
@candle_type.setter
def candle_type(self, value):
self._candle_type.Value = value
def OnReseted(self):
super(multi_step_flexi_ma_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._initialized = False
self._cooldown_remaining = 0
def OnStarted2(self, time):
super(multi_step_flexi_ma_strategy, self).OnStarted2(time)
self._prev_fast = 0.0
self._prev_slow = 0.0
self._initialized = False
self._cooldown_remaining = 0
self._fast_sma = SimpleMovingAverage()
self._fast_sma.Length = self._fast_length.Value
self._slow_sma = SimpleMovingAverage()
self._slow_sma.Length = self._slow_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._fast_sma, self._slow_sma, self.OnProcess).Start()
def OnProcess(self, candle, fast_val, slow_val):
if candle.State != CandleStates.Finished:
return
fv = float(fast_val)
sv = float(slow_val)
if not self._fast_sma.IsFormed or not self._slow_sma.IsFormed:
return
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
if not self._initialized:
self._prev_fast = fv
self._prev_slow = sv
self._initialized = True
return
if self._cooldown_remaining == 0 and self._prev_fast <= self._prev_slow and fv > sv and self.Position <= 0:
self.BuyMarket()
self._cooldown_remaining = self._signal_cooldown_bars.Value
elif self._cooldown_remaining == 0 and self._prev_fast >= self._prev_slow and fv < sv and self.Position > 0:
self.SellMarket()
self._cooldown_remaining = self._signal_cooldown_bars.Value
self._prev_fast = fv
self._prev_slow = sv
def CreateClone(self):
return multi_step_flexi_ma_strategy()