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>
/// Port of the MetaTrader advisor MacdPatternTrader.
/// Implements the MACD histogram double-top/double-bottom pattern with adaptive arming logic.
/// </summary>
public class MacdPatternTraderTriggerStrategy : Strategy
{
private readonly StrategyParam<decimal> _tradeVolume;
private readonly StrategyParam<int> _fastPeriod;
private readonly StrategyParam<int> _slowPeriod;
private readonly StrategyParam<int> _signalPeriod;
private readonly StrategyParam<decimal> _bullishTrigger;
private readonly StrategyParam<decimal> _bullishReset;
private readonly StrategyParam<decimal> _bearishTrigger;
private readonly StrategyParam<decimal> _bearishReset;
private readonly StrategyParam<decimal> _stopLossPoints;
private readonly StrategyParam<decimal> _takeProfitPoints;
private readonly StrategyParam<DataType> _candleType;
private MovingAverageConvergenceDivergenceSignal _macd = null!;
private decimal? _macdPrev1;
private decimal? _macdPrev2;
private decimal? _macdPrev3;
private bool _bullishArmed;
private bool _bullishWindow;
private bool _bullishReady;
private bool _bearishArmed;
private bool _bearishWindow;
private bool _bearishReady;
private decimal _priceStep = 1m;
/// <summary>
/// Trade volume used for market orders.
/// </summary>
public decimal TradeVolume
{
get => _tradeVolume.Value;
set => _tradeVolume.Value = value;
}
/// <summary>
/// Fast EMA length of the MACD indicator.
/// </summary>
public int FastPeriod
{
get => _fastPeriod.Value;
set => _fastPeriod.Value = value;
}
/// <summary>
/// Slow EMA length of the MACD indicator.
/// </summary>
public int SlowPeriod
{
get => _slowPeriod.Value;
set => _slowPeriod.Value = value;
}
/// <summary>
/// Signal smoothing period of the MACD indicator.
/// </summary>
public int SignalPeriod
{
get => _signalPeriod.Value;
set => _signalPeriod.Value = value;
}
/// <summary>
/// Positive MACD value that arms the bullish pattern.
/// </summary>
public decimal BullishTrigger
{
get => _bullishTrigger.Value;
set => _bullishTrigger.Value = value;
}
/// <summary>
/// Threshold that marks the bullish pullback zone.
/// </summary>
public decimal BullishReset
{
get => _bullishReset.Value;
set => _bullishReset.Value = value;
}
/// <summary>
/// Negative MACD value that arms the bearish pattern.
/// </summary>
public decimal BearishTrigger
{
get => _bearishTrigger.Value;
set => _bearishTrigger.Value = value;
}
/// <summary>
/// Threshold that marks the bearish pullback zone.
/// </summary>
public decimal BearishReset
{
get => _bearishReset.Value;
set => _bearishReset.Value = value;
}
/// <summary>
/// Stop-loss distance expressed in instrument points.
/// </summary>
public decimal StopLossPoints
{
get => _stopLossPoints.Value;
set => _stopLossPoints.Value = value;
}
/// <summary>
/// Take-profit distance expressed in instrument points.
/// </summary>
public decimal TakeProfitPoints
{
get => _takeProfitPoints.Value;
set => _takeProfitPoints.Value = value;
}
/// <summary>
/// Candle type that drives the MACD calculation.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initializes strategy parameters.
/// </summary>
public MacdPatternTraderTriggerStrategy()
{
_tradeVolume = Param(nameof(TradeVolume), 0.1m)
.SetGreaterThanZero()
.SetDisplay("Trade Volume", "Order volume for entries", "Trading")
.SetOptimize(0.05m, 0.3m, 0.05m);
_fastPeriod = Param(nameof(FastPeriod), 13)
.SetGreaterThanZero()
.SetDisplay("Fast EMA", "Fast EMA length for MACD", "Indicators")
.SetOptimize(8, 18, 1);
_slowPeriod = Param(nameof(SlowPeriod), 5)
.SetGreaterThanZero()
.SetDisplay("Slow EMA", "Slow EMA length for MACD", "Indicators")
.SetOptimize(4, 15, 1);
_signalPeriod = Param(nameof(SignalPeriod), 1)
.SetGreaterThanZero()
.SetDisplay("Signal EMA", "Signal EMA length for MACD", "Indicators")
.SetOptimize(1, 5, 1);
_bullishTrigger = Param(nameof(BullishTrigger), 50m)
.SetGreaterThanZero()
.SetDisplay("Bullish Trigger", "MACD level that arms the bullish pattern", "Logic");
_bullishReset = Param(nameof(BullishReset), 20m)
.SetGreaterThanZero()
.SetDisplay("Bullish Reset", "MACD pullback threshold for bullish setup", "Logic");
_bearishTrigger = Param(nameof(BearishTrigger), 50m)
.SetGreaterThanZero()
.SetDisplay("Bearish Trigger", "Absolute MACD level that arms the bearish pattern", "Logic");
_bearishReset = Param(nameof(BearishReset), 20m)
.SetGreaterThanZero()
.SetDisplay("Bearish Reset", "MACD pullback threshold for bearish setup", "Logic");
_stopLossPoints = Param(nameof(StopLossPoints), 100m)
.SetNotNegative()
.SetDisplay("Stop Loss", "Stop-loss distance in points", "Risk")
.SetOptimize(50m, 200m, 25m);
_takeProfitPoints = Param(nameof(TakeProfitPoints), 300m)
.SetNotNegative()
.SetDisplay("Take Profit", "Take-profit distance in points", "Risk")
.SetOptimize(100m, 400m, 50m);
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Time frame for indicator calculations", "Data");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_macdPrev1 = null;
_macdPrev2 = null;
_macdPrev3 = null;
_bullishArmed = false;
_bullishWindow = false;
_bullishReady = false;
_bearishArmed = false;
_bearishWindow = false;
_bearishReady = false;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_priceStep = Security?.PriceStep ?? 1m;
if (_priceStep <= 0m)
_priceStep = 1m;
var takeProfit = TakeProfitPoints > 0m ? new Unit(TakeProfitPoints * _priceStep, UnitTypes.Absolute) : null;
var stopLoss = StopLossPoints > 0m ? new Unit(StopLossPoints * _priceStep, UnitTypes.Absolute) : null;
StartProtection(takeProfit, stopLoss);
_macd = new MovingAverageConvergenceDivergenceSignal();
_macd.Macd.ShortMa.Length = FastPeriod;
_macd.Macd.LongMa.Length = SlowPeriod;
_macd.SignalMa.Length = SignalPeriod;
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 || macdValue is not MovingAverageConvergenceDivergenceSignalValue macdLineValue)
return;
if (macdLineValue.Macd is not decimal currentMacd)
return;
if (!IsFormedAndOnlineAndAllowTrading())
{
ShiftHistory(currentMacd);
return;
}
if (_macdPrev1 is null || _macdPrev2 is null || _macdPrev3 is null)
{
ShiftHistory(currentMacd);
return;
}
var macdCurr = _macdPrev1.Value;
var macdLast = _macdPrev2.Value;
var macdLast3 = _macdPrev3.Value;
EvaluateBearishPattern(macdCurr, macdLast, macdLast3);
EvaluateBullishPattern(macdCurr, macdLast, macdLast3);
ShiftHistory(currentMacd);
}
private void EvaluateBullishPattern(decimal macdCurr, decimal macdLast, decimal macdLast3)
{
if (macdCurr < 0m)
{
_bullishArmed = false;
_bullishWindow = false;
_bullishReady = false;
}
else
{
if (!_bullishArmed && macdCurr > BullishTrigger)
_bullishArmed = true;
if (_bullishArmed && macdCurr < BullishReset)
{
_bullishArmed = false;
_bullishWindow = true;
}
}
if (_bullishWindow && macdCurr > macdLast && macdLast < macdLast3 && macdCurr > BullishReset && macdLast < BullishReset)
{
_bullishReady = true;
_bullishWindow = false;
}
if (!_bullishReady)
return;
var volumeToBuy = TradeVolume + Math.Max(0m, -Position);
if (volumeToBuy > 0m)
BuyMarket(volumeToBuy);
_bullishReady = false;
_bullishArmed = false;
_bullishWindow = false;
}
private void EvaluateBearishPattern(decimal macdCurr, decimal macdLast, decimal macdLast3)
{
if (macdCurr > 0m)
{
_bearishArmed = false;
_bearishWindow = false;
_bearishReady = false;
}
else
{
if (!_bearishArmed && macdCurr < -BearishTrigger)
_bearishArmed = true;
if (_bearishArmed && macdCurr > -BearishReset)
{
_bearishArmed = false;
_bearishWindow = true;
}
}
if (_bearishWindow && macdCurr < macdLast && macdLast > macdLast3 && macdCurr < -BearishReset && macdLast > -BearishReset)
{
_bearishReady = true;
_bearishWindow = false;
}
if (!_bearishReady)
return;
var volumeToSell = TradeVolume + Math.Max(0m, Position);
if (volumeToSell > 0m)
SellMarket(volumeToSell);
_bearishReady = false;
_bearishArmed = false;
_bearishWindow = false;
}
private void ShiftHistory(decimal current)
{
_macdPrev3 = _macdPrev2;
_macdPrev2 = _macdPrev1;
_macdPrev1 = current;
}
}
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, UnitTypes, Unit
from StockSharp.Algo.Strategies import Strategy
from StockSharp.Algo.Indicators import MovingAverageConvergenceDivergenceSignal
class macd_pattern_trader_trigger_strategy(Strategy):
def __init__(self):
super(macd_pattern_trader_trigger_strategy, self).__init__()
self._trade_volume = self.Param("TradeVolume", 0.1) \
.SetDisplay("Trade Volume", "Order volume for entries", "Trading")
self._fast_period = self.Param("FastPeriod", 13) \
.SetDisplay("Fast EMA", "Fast EMA length for MACD", "Indicators")
self._slow_period = self.Param("SlowPeriod", 5) \
.SetDisplay("Slow EMA", "Slow EMA length for MACD", "Indicators")
self._signal_period = self.Param("SignalPeriod", 1) \
.SetDisplay("Signal EMA", "Signal EMA length for MACD", "Indicators")
self._bullish_trigger = self.Param("BullishTrigger", 50.0) \
.SetDisplay("Bullish Trigger", "MACD level that arms the bullish pattern", "Logic")
self._bullish_reset = self.Param("BullishReset", 20.0) \
.SetDisplay("Bullish Reset", "MACD pullback threshold for bullish setup", "Logic")
self._bearish_trigger = self.Param("BearishTrigger", 50.0) \
.SetDisplay("Bearish Trigger", "Absolute MACD level that arms the bearish pattern", "Logic")
self._bearish_reset = self.Param("BearishReset", 20.0) \
.SetDisplay("Bearish Reset", "MACD pullback threshold for bearish setup", "Logic")
self._stop_loss_points = self.Param("StopLossPoints", 100.0) \
.SetDisplay("Stop Loss", "Stop-loss distance in points", "Risk")
self._take_profit_points = self.Param("TakeProfitPoints", 300.0) \
.SetDisplay("Take Profit", "Take-profit distance in points", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Time frame for indicator calculations", "Data")
self._macd_prev1 = None
self._macd_prev2 = None
self._macd_prev3 = None
self._bullish_armed = False
self._bullish_window = False
self._bullish_ready = False
self._bearish_armed = False
self._bearish_window = False
self._bearish_ready = False
self._price_step = 1.0
@property
def TradeVolume(self):
return self._trade_volume.Value
@property
def FastPeriod(self):
return self._fast_period.Value
@property
def SlowPeriod(self):
return self._slow_period.Value
@property
def SignalPeriod(self):
return self._signal_period.Value
@property
def BullishTrigger(self):
return self._bullish_trigger.Value
@property
def BullishReset(self):
return self._bullish_reset.Value
@property
def BearishTrigger(self):
return self._bearish_trigger.Value
@property
def BearishReset(self):
return self._bearish_reset.Value
@property
def StopLossPoints(self):
return self._stop_loss_points.Value
@property
def TakeProfitPoints(self):
return self._take_profit_points.Value
@property
def CandleType(self):
return self._candle_type.Value
def OnStarted2(self, time):
super(macd_pattern_trader_trigger_strategy, self).OnStarted2(time)
ps = self.Security.PriceStep if self.Security is not None else None
self._price_step = float(ps) if ps is not None else 1.0
if self._price_step <= 0:
self._price_step = 1.0
tp = float(self.TakeProfitPoints)
sl = float(self.StopLossPoints)
take_profit = Unit(tp * self._price_step, UnitTypes.Absolute) if tp > 0 else None
stop_loss = Unit(sl * self._price_step, UnitTypes.Absolute) if sl > 0 else None
self.StartProtection(take_profit, stop_loss)
macd = MovingAverageConvergenceDivergenceSignal()
macd.Macd.ShortMa.Length = self.FastPeriod
macd.Macd.LongMa.Length = self.SlowPeriod
macd.SignalMa.Length = self.SignalPeriod
subscription = self.SubscribeCandles(self.CandleType)
subscription.BindEx(macd, self.ProcessCandle).Start()
def ProcessCandle(self, candle, macd_value):
if candle.State != CandleStates.Finished:
return
if not macd_value.IsFinal:
return
macd_line = macd_value.Macd
if macd_line is None:
return
current_macd = float(macd_line)
if not self.IsFormedAndOnlineAndAllowTrading():
self._shift_history(current_macd)
return
if self._macd_prev1 is None or self._macd_prev2 is None or self._macd_prev3 is None:
self._shift_history(current_macd)
return
macd_curr = self._macd_prev1
macd_last = self._macd_prev2
macd_last3 = self._macd_prev3
self._evaluate_bearish_pattern(macd_curr, macd_last, macd_last3)
self._evaluate_bullish_pattern(macd_curr, macd_last, macd_last3)
self._shift_history(current_macd)
def _evaluate_bullish_pattern(self, macd_curr, macd_last, macd_last3):
bull_trigger = float(self.BullishTrigger)
bull_reset = float(self.BullishReset)
if macd_curr < 0:
self._bullish_armed = False
self._bullish_window = False
self._bullish_ready = False
else:
if not self._bullish_armed and macd_curr > bull_trigger:
self._bullish_armed = True
if self._bullish_armed and macd_curr < bull_reset:
self._bullish_armed = False
self._bullish_window = True
if (self._bullish_window and macd_curr > macd_last and macd_last < macd_last3
and macd_curr > bull_reset and macd_last < bull_reset):
self._bullish_ready = True
self._bullish_window = False
if not self._bullish_ready:
return
tv = float(self.TradeVolume)
volume_to_buy = tv + max(0.0, -float(self.Position))
if volume_to_buy > 0:
self.BuyMarket(volume_to_buy)
self._bullish_ready = False
self._bullish_armed = False
self._bullish_window = False
def _evaluate_bearish_pattern(self, macd_curr, macd_last, macd_last3):
bear_trigger = float(self.BearishTrigger)
bear_reset = float(self.BearishReset)
if macd_curr > 0:
self._bearish_armed = False
self._bearish_window = False
self._bearish_ready = False
else:
if not self._bearish_armed and macd_curr < -bear_trigger:
self._bearish_armed = True
if self._bearish_armed and macd_curr > -bear_reset:
self._bearish_armed = False
self._bearish_window = True
if (self._bearish_window and macd_curr < macd_last and macd_last > macd_last3
and macd_curr < -bear_reset and macd_last > -bear_reset):
self._bearish_ready = True
self._bearish_window = False
if not self._bearish_ready:
return
tv = float(self.TradeVolume)
volume_to_sell = tv + max(0.0, float(self.Position))
if volume_to_sell > 0:
self.SellMarket(volume_to_sell)
self._bearish_ready = False
self._bearish_armed = False
self._bearish_window = False
def _shift_history(self, current):
self._macd_prev3 = self._macd_prev2
self._macd_prev2 = self._macd_prev1
self._macd_prev1 = current
def OnReseted(self):
super(macd_pattern_trader_trigger_strategy, self).OnReseted()
self._macd_prev1 = None
self._macd_prev2 = None
self._macd_prev3 = None
self._bullish_armed = False
self._bullish_window = False
self._bullish_ready = False
self._bearish_armed = False
self._bearish_window = False
self._bearish_ready = False
def CreateClone(self):
return macd_pattern_trader_trigger_strategy()