Ergodic Ticks Volume OSMA Strategy
Overview
This strategy adapts the MQL5 expert "Exp_Ergodic_Ticks_Volume_OSMA" to StockSharp. The original expert uses a custom indicator to evaluate tick volume momentum. In this version the custom indicator is approximated by the MACD histogram.
The strategy looks for consecutive increases or decreases in the histogram:
- Two rising steps trigger a long entry and close any short position.
- Two falling steps trigger a short entry and close any long position.
StartProtection() is used to avoid conflicts with existing positions when the strategy starts.
Parameters
FastLength– fast EMA period for the MACD. Default: 12.SlowLength– slow EMA period for the MACD. Default: 26.SignalLength– signal EMA period for the MACD. Default: 9.CandleType– timeframe of candles, default is 8 hours.
Trading Logic
- Subscribe to candles of the selected
CandleType. - Compute the MACD histogram for each finished candle.
- If the histogram grows for two consecutive bars, close shorts and buy.
- If the histogram falls for two consecutive bars, close longs and sell.
- Continue processing for each new candle.
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 based on MACD histogram as an approximation of the Ergodic Ticks Volume OSMA indicator.
/// </summary>
public class ErgodicTicksVolumeOsmaStrategy : Strategy
{
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<int> _signalLength;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevHist;
private decimal _prevPrevHist;
private int _candleCount;
public int FastLength { get => _fastLength.Value; set => _fastLength.Value = value; }
public int SlowLength { get => _slowLength.Value; set => _slowLength.Value = value; }
public int SignalLength { get => _signalLength.Value; set => _signalLength.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public ErgodicTicksVolumeOsmaStrategy()
{
_fastLength = Param(nameof(FastLength), 12).SetDisplay("Fast EMA", "Fast EMA length", "Indicators");
_slowLength = Param(nameof(SlowLength), 26).SetDisplay("Slow EMA", "Slow EMA length", "Indicators");
_signalLength = Param(nameof(SignalLength), 9).SetDisplay("Signal EMA", "Signal EMA length", "Indicators");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(8).TimeFrame()).SetDisplay("Timeframe", "Timeframe", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevHist = default;
_prevPrevHist = default;
_candleCount = default;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var macd = new MovingAverageConvergenceDivergenceSignal(
new MovingAverageConvergenceDivergence
{
ShortMa = { Length = FastLength },
LongMa = { Length = SlowLength },
},
new ExponentialMovingAverage { Length = SignalLength }
);
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(macd, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue value)
{
if (candle.State != CandleStates.Finished)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (value is not MovingAverageConvergenceDivergenceSignalValue macdTyped)
return;
if (macdTyped.Macd is not decimal macdVal || macdTyped.Signal is not decimal signalVal)
return;
var hist = macdVal - signalVal;
_candleCount++;
if (_candleCount <= 2)
{
_prevPrevHist = _prevHist;
_prevHist = hist;
return;
}
var rising = _prevHist >= _prevPrevHist && hist >= _prevHist;
var falling = _prevHist <= _prevPrevHist && hist <= _prevHist;
if (rising && Position <= 0)
{
BuyMarket();
}
else if (falling && Position >= 0)
{
SellMarket();
}
_prevPrevHist = _prevHist;
_prevHist = hist;
}
}
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 MovingAverageConvergenceDivergence, MovingAverageConvergenceDivergenceSignal, ExponentialMovingAverage
from StockSharp.Algo.Strategies import Strategy
class ergodic_ticks_volume_osma_strategy(Strategy):
def __init__(self):
super(ergodic_ticks_volume_osma_strategy, self).__init__()
self._fast_length = self.Param("FastLength", 12) \
.SetDisplay("Fast EMA", "Fast EMA length", "Indicators")
self._slow_length = self.Param("SlowLength", 26) \
.SetDisplay("Slow EMA", "Slow EMA length", "Indicators")
self._signal_length = self.Param("SignalLength", 9) \
.SetDisplay("Signal EMA", "Signal EMA length", "Indicators")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(8))) \
.SetDisplay("Timeframe", "Timeframe", "General")
self._prev_hist = 0.0
self._prev_prev_hist = 0.0
self._candle_count = 0
@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 SignalLength(self):
return self._signal_length.Value
@SignalLength.setter
def SignalLength(self, value):
self._signal_length.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(ergodic_ticks_volume_osma_strategy, self).OnStarted2(time)
inner_macd = MovingAverageConvergenceDivergence()
inner_macd.ShortMa.Length = self.FastLength
inner_macd.LongMa.Length = self.SlowLength
signal_ema = ExponentialMovingAverage()
signal_ema.Length = self.SignalLength
macd = MovingAverageConvergenceDivergenceSignal(inner_macd, signal_ema)
self.SubscribeCandles(self.CandleType) \
.BindEx(macd, self.ProcessCandle) \
.Start()
def ProcessCandle(self, candle, value):
if candle.State != CandleStates.Finished:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
macd_val = value.Macd
signal_val = value.Signal
if macd_val is None or signal_val is None:
return
hist = float(macd_val) - float(signal_val)
self._candle_count += 1
if self._candle_count <= 2:
self._prev_prev_hist = self._prev_hist
self._prev_hist = hist
return
rising = self._prev_hist >= self._prev_prev_hist and hist >= self._prev_hist
falling = self._prev_hist <= self._prev_prev_hist and hist <= self._prev_hist
if rising and self.Position <= 0:
self.BuyMarket()
elif falling and self.Position >= 0:
self.SellMarket()
self._prev_prev_hist = self._prev_hist
self._prev_hist = hist
def OnReseted(self):
super(ergodic_ticks_volume_osma_strategy, self).OnReseted()
self._prev_hist = 0.0
self._prev_prev_hist = 0.0
self._candle_count = 0
def CreateClone(self):
return ergodic_ticks_volume_osma_strategy()