Color NonLag Dot MACD Strategy
Strategy using MACD indicator with several signal detection modes. The approach is ported from the MQL "Exp_ColorNonLagDotMACD" expert advisor.
Details
- Entry Criteria: Depends on selected mode (zero line breakout, MACD twist, signal line twist, or MACD crossing signal line).
- Long/Short: Both directions, can be enabled separately.
- Exit Criteria: Opposite signals or configured stop/target.
- Stops: Optional percent based stop loss and take profit.
- Default Values:
FastLength= 12SlowLength= 26SignalLength= 9Mode=MacdDispositionTakeProfitPercent= 4StopLossPercent= 2CandleType= TimeSpan.FromHours(4)
- Filters:
- Category: Trend
- Direction: Both
- Indicators: MACD
- Stops: Yes
- Complexity: Intermediate
- Timeframe: 4H
- Seasonality: No
- Neural Networks: No
- Divergence: No
- Risk Level: Medium
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 signal line crossover.
/// Buys when MACD crosses above signal, sells when below.
/// </summary>
public class ColorNonLagDotMacdStrategy : 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;
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 ColorNonLagDotMacdStrategy()
{
_fastLength = Param(nameof(FastLength), 12)
.SetGreaterThanZero()
.SetDisplay("Fast Length", "Fast EMA period", "Indicator");
_slowLength = Param(nameof(SlowLength), 26)
.SetGreaterThanZero()
.SetDisplay("Slow Length", "Slow EMA period", "Indicator");
_signalLength = Param(nameof(SignalLength), 9)
.SetGreaterThanZero()
.SetDisplay("Signal Length", "Signal line period", "Indicator");
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
=> [(Security, CandleType)];
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevMacd = null;
_prevSignal = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var macd = new MovingAverageConvergenceDivergenceSignal
{
Macd =
{
ShortMa = { Length = FastLength },
LongMa = { Length = SlowLength },
},
SignalMa = { Length = SignalLength }
};
SubscribeCandles(CandleType)
.BindEx(macd, ProcessCandle)
.Start();
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue macdValue)
{
if (candle.State != CandleStates.Finished)
return;
var value = (IMovingAverageConvergenceDivergenceSignalValue)macdValue;
if (value.Macd is not decimal macd || value.Signal is not decimal signal)
return;
if (_prevMacd is not null && _prevSignal is not null)
{
var crossUp = _prevMacd <= _prevSignal && macd > signal;
var crossDown = _prevMacd >= _prevSignal && macd < signal;
if (crossUp && Position <= 0)
{
if (Position < 0) BuyMarket();
BuyMarket();
}
else if (crossDown && Position >= 0)
{
if (Position > 0) SellMarket();
SellMarket();
}
}
_prevMacd = macd;
_prevSignal = signal;
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from System import TimeSpan, Math
from StockSharp.Messages import DataType, CandleStates
from StockSharp.Algo.Indicators import MovingAverageConvergenceDivergenceSignal
from StockSharp.Algo.Strategies import Strategy
class color_non_lag_dot_macd_strategy(Strategy):
def __init__(self):
super(color_non_lag_dot_macd_strategy, self).__init__()
self._fast_length = self.Param("FastLength", 12) \
.SetDisplay("Fast Length", "Fast EMA period", "Indicator")
self._slow_length = self.Param("SlowLength", 26) \
.SetDisplay("Slow Length", "Slow EMA period", "Indicator")
self._signal_length = self.Param("SignalLength", 9) \
.SetDisplay("Signal Length", "Signal line period", "Indicator")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._prev_macd = None
self._prev_signal = None
@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(color_non_lag_dot_macd_strategy, self).OnStarted2(time)
macd = MovingAverageConvergenceDivergenceSignal()
macd.Macd.ShortMa.Length = self.FastLength
macd.Macd.LongMa.Length = self.SlowLength
macd.SignalMa.Length = self.SignalLength
self.SubscribeCandles(self.CandleType) \
.BindEx(macd, self.ProcessCandle) \
.Start()
def ProcessCandle(self, candle, macd_value):
if candle.State != CandleStates.Finished:
return
macd_raw = macd_value.Macd
signal_raw = macd_value.Signal
if macd_raw is None or signal_raw is None:
return
macd_line = float(macd_raw)
signal_line = float(signal_raw)
if self._prev_macd is not None and self._prev_signal is not None:
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:
if self.Position < 0:
self.BuyMarket()
self.BuyMarket()
elif cross_down and self.Position >= 0:
if self.Position > 0:
self.SellMarket()
self.SellMarket()
self._prev_macd = macd_line
self._prev_signal = signal_line
def OnReseted(self):
super(color_non_lag_dot_macd_strategy, self).OnReseted()
self._prev_macd = None
self._prev_signal = None
def CreateClone(self):
return color_non_lag_dot_macd_strategy()