ZeroLag MACD Cross Strategy
This strategy trades based on a crossover between the MACD line and its signal line. It was converted from the MetaTrader expert advisor ZeroLagEA-AIP v0.0.4. The strategy operates only during the configured session hours and can optionally require that the crossover happens on the current bar.
Details
- Entry Criteria:
- Long: MACD line crosses above the signal line.
- Short: MACD line crosses below the signal line.
- Long/Short: Both.
- Exit Criteria:
- Opposite crossover or forced exit at the specified day and hour.
- Stops: None.
- Filters:
- Session hours defined by
StartHourandEndHour. - Optional fresh crossover requirement (
UseFreshSignal).
- Session hours defined by
Parameters
FastEmaLength= 2SlowEmaLength= 34SignalEmaLength= 2UseFreshSignal= trueVolume= 2StartHour= 9EndHour= 15KillDay= 5KillHour= 21CandleType= 1-minute candles
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>
/// MACD crossover strategy with signal line.
/// </summary>
public class ZeroLagMacdStrategy : Strategy
{
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<int> _signalLength;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevMacd;
private decimal _prevSignal;
private bool _hasPrev;
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 ZeroLagMacdStrategy()
{
_fastLength = Param(nameof(FastLength), 12)
.SetGreaterThanZero()
.SetDisplay("Fast EMA", "Fast EMA period", "MACD");
_slowLength = Param(nameof(SlowLength), 26)
.SetGreaterThanZero()
.SetDisplay("Slow EMA", "Slow EMA period", "MACD");
_signalLength = Param(nameof(SignalLength), 9)
.SetGreaterThanZero()
.SetDisplay("Signal", "Signal EMA period", "MACD");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Candle Type", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevMacd = 0;
_prevSignal = 0;
_hasPrev = false;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var macd = new MovingAverageConvergenceDivergenceSignal
{
Macd =
{
ShortMa = { Length = FastLength },
LongMa = { Length = SlowLength },
},
SignalMa = { Length = SignalLength }
};
var subscription = SubscribeCandles(CandleType);
subscription.BindEx(macd, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, macd);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue macdValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!macdValue.IsFinal)
return;
var macdTyped = (MovingAverageConvergenceDivergenceSignalValue)macdValue;
if (macdTyped.Macd is not decimal macdLine || macdTyped.Signal is not decimal signalLine)
return;
if (_hasPrev)
{
var crossUp = _prevMacd <= _prevSignal && macdLine > signalLine;
var crossDown = _prevMacd >= _prevSignal && macdLine < signalLine;
if (crossUp && Position <= 0)
BuyMarket();
else if (crossDown && Position >= 0)
SellMarket();
}
_prevMacd = macdLine;
_prevSignal = signalLine;
_hasPrev = true;
}
}
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 MovingAverageConvergenceDivergenceSignal
from StockSharp.Algo.Strategies import Strategy
class zero_lag_macd_strategy(Strategy):
def __init__(self):
super(zero_lag_macd_strategy, self).__init__()
self._fast_length = self.Param("FastLength", 12) \
.SetDisplay("Fast EMA", "Fast EMA period", "MACD")
self._slow_length = self.Param("SlowLength", 26) \
.SetDisplay("Slow EMA", "Slow EMA period", "MACD")
self._signal_length = self.Param("SignalLength", 9) \
.SetDisplay("Signal", "Signal EMA period", "MACD")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Candle Type", "General")
self._prev_macd = 0.0
self._prev_signal = 0.0
self._has_prev = False
@property
def fast_length(self):
return self._fast_length.Value
@property
def slow_length(self):
return self._slow_length.Value
@property
def signal_length(self):
return self._signal_length.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(zero_lag_macd_strategy, self).OnReseted()
self._prev_macd = 0.0
self._prev_signal = 0.0
self._has_prev = False
def OnStarted2(self, time):
super(zero_lag_macd_strategy, self).OnStarted2(time)
macd = MovingAverageConvergenceDivergenceSignal()
macd.Macd.ShortMa.Length = self.fast_length
macd.Macd.LongMa.Length = self.slow_length
macd.SignalMa.Length = self.signal_length
self._prev_macd = 0.0
self._prev_signal = 0.0
self._has_prev = False
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(macd, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, macd)
self.DrawOwnTrades(area)
def on_process(self, candle, macd_value):
if candle.State != CandleStates.Finished:
return
if not macd_value.IsFinal:
return
if macd_value.Macd is None or macd_value.Signal is None:
return
macd_line = float(macd_value.Macd)
signal_line = float(macd_value.Signal)
if self._has_prev:
cross_up = self._prev_macd <= self._prev_signal and macd_line > signal_line
cross_down = self._prev_macd >= self._prev_signal and macd_line < signal_line
if cross_up and self.Position <= 0:
self.BuyMarket()
elif cross_down and self.Position >= 0:
self.SellMarket()
self._prev_macd = macd_line
self._prev_signal = signal_line
self._has_prev = True
def CreateClone(self):
return zero_lag_macd_strategy()