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>
/// Strategy that replicates the MetaTrader "MACD + Parabolic SAR" expert built with the MQL5 Wizard.
/// Combines the trend direction from Parabolic SAR with MACD momentum scores and uses weighted thresholds for decisions.
/// </summary>
public class MacdParabolicSarWizardStrategy : Strategy
{
private readonly StrategyParam<int> _macdFastPeriod;
private readonly StrategyParam<int> _macdSlowPeriod;
private readonly StrategyParam<int> _macdSignalPeriod;
private readonly StrategyParam<decimal> _macdWeight;
private readonly StrategyParam<decimal> _sarWeight;
private readonly StrategyParam<decimal> _openThreshold;
private readonly StrategyParam<decimal> _closeThreshold;
private readonly StrategyParam<decimal> _sarStep;
private readonly StrategyParam<decimal> _sarMax;
private readonly StrategyParam<decimal> _stopLossPoints;
private readonly StrategyParam<decimal> _takeProfitPoints;
private readonly StrategyParam<DataType> _candleType;
private MovingAverageConvergenceDivergenceSignal _macd = null!;
private ParabolicSar _parabolicSar = null!;
private decimal _lastBullScore;
private decimal _lastBearScore;
/// <summary>
/// Fast EMA period for MACD.
/// </summary>
public int MacdFastPeriod
{
get => _macdFastPeriod.Value;
set => _macdFastPeriod.Value = value;
}
/// <summary>
/// Slow EMA period for MACD.
/// </summary>
public int MacdSlowPeriod
{
get => _macdSlowPeriod.Value;
set => _macdSlowPeriod.Value = value;
}
/// <summary>
/// Signal line period for MACD.
/// </summary>
public int MacdSignalPeriod
{
get => _macdSignalPeriod.Value;
set => _macdSignalPeriod.Value = value;
}
/// <summary>
/// Weight of the MACD signal in the combined score (0..1).
/// </summary>
public decimal MacdWeight
{
get => _macdWeight.Value;
set => _macdWeight.Value = value;
}
/// <summary>
/// Weight of the Parabolic SAR signal in the combined score (0..1).
/// </summary>
public decimal SarWeight
{
get => _sarWeight.Value;
set => _sarWeight.Value = value;
}
/// <summary>
/// Minimum combined bullish or bearish score required to open a position.
/// </summary>
public decimal OpenThreshold
{
get => _openThreshold.Value;
set => _openThreshold.Value = value;
}
/// <summary>
/// Minimum opposite score required to exit the current position.
/// </summary>
public decimal CloseThreshold
{
get => _closeThreshold.Value;
set => _closeThreshold.Value = value;
}
/// <summary>
/// Acceleration step for Parabolic SAR.
/// </summary>
public decimal SarStep
{
get => _sarStep.Value;
set => _sarStep.Value = value;
}
/// <summary>
/// Maximum acceleration factor for Parabolic SAR.
/// </summary>
public decimal SarMax
{
get => _sarMax.Value;
set => _sarMax.Value = value;
}
/// <summary>
/// Stop-loss distance expressed in price points.
/// </summary>
public decimal StopLossPoints
{
get => _stopLossPoints.Value;
set => _stopLossPoints.Value = value;
}
/// <summary>
/// Take-profit distance expressed in price points.
/// </summary>
public decimal TakeProfitPoints
{
get => _takeProfitPoints.Value;
set => _takeProfitPoints.Value = value;
}
/// <summary>
/// Type of candles used for calculations.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initialize <see cref="MacdParabolicSarWizardStrategy"/>.
/// </summary>
public MacdParabolicSarWizardStrategy()
{
_macdFastPeriod = Param(nameof(MacdFastPeriod), 12)
.SetDisplay("MACD Fast", "Fast EMA period for MACD", "MACD")
;
_macdSlowPeriod = Param(nameof(MacdSlowPeriod), 24)
.SetDisplay("MACD Slow", "Slow EMA period for MACD", "MACD")
;
_macdSignalPeriod = Param(nameof(MacdSignalPeriod), 9)
.SetDisplay("MACD Signal", "Signal SMA period for MACD", "MACD")
;
_macdWeight = Param(nameof(MacdWeight), 0.9m)
.SetDisplay("MACD Weight", "Relative weight of MACD in scoring", "Scoring")
;
_sarWeight = Param(nameof(SarWeight), 0.1m)
.SetDisplay("SAR Weight", "Relative weight of SAR in scoring", "Scoring")
;
_openThreshold = Param(nameof(OpenThreshold), 90m)
.SetDisplay("Open Threshold", "Score required to open trades", "Scoring")
;
_closeThreshold = Param(nameof(CloseThreshold), 90m)
.SetDisplay("Close Threshold", "Score required to exit trades", "Scoring")
;
_sarStep = Param(nameof(SarStep), 0.02m)
.SetDisplay("SAR Step", "Acceleration factor for Parabolic SAR", "Parabolic SAR")
;
_sarMax = Param(nameof(SarMax), 0.2m)
.SetDisplay("SAR Max", "Maximum acceleration for Parabolic SAR", "Parabolic SAR")
;
_stopLossPoints = Param(nameof(StopLossPoints), 50m)
.SetDisplay("Stop Loss (pts)", "Stop-loss distance in points", "Risk")
;
_takeProfitPoints = Param(nameof(TakeProfitPoints), 115m)
.SetDisplay("Take Profit (pts)", "Take-profit distance in points", "Risk")
;
_candleType = Param(nameof(CandleType), TimeSpan.FromHours(4).TimeFrame())
.SetDisplay("Candle Type", "Primary candle source", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_lastBullScore = 0m;
_lastBearScore = 0m;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
// Configure MACD indicator replicating the wizard defaults.
_macd = new MovingAverageConvergenceDivergenceSignal
{
Macd =
{
ShortMa = { Length = MacdFastPeriod },
LongMa = { Length = MacdSlowPeriod },
},
SignalMa = { Length = MacdSignalPeriod }
};
// Configure Parabolic SAR indicator.
_parabolicSar = new ParabolicSar
{
AccelerationStep = SarStep,
AccelerationMax = SarMax,
};
// Subscribe to candles and bind indicators.
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(_macd, _parabolicSar, ProcessCandle)
.Start();
// Configure risk management using point-based distances.
var step = Security?.PriceStep ?? 1m;
var takeProfit = TakeProfitPoints > 0m ? new Unit(TakeProfitPoints * step, UnitTypes.Absolute) : new Unit();
var stopLoss = StopLossPoints > 0m ? new Unit(StopLossPoints * step, UnitTypes.Absolute) : new Unit();
StartProtection(takeProfit, stopLoss, useMarketOrders: true);
// Prepare chart visualization if the environment supports it.
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _parabolicSar);
DrawIndicator(area, _macd);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue macdValue, IIndicatorValue sarValue)
{
// Process only finished candles to avoid premature trades.
if (candle.State != CandleStates.Finished)
return;
if (!macdValue.IsFinal || !sarValue.IsFinal)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
var macdTyped = (MovingAverageConvergenceDivergenceSignalValue)macdValue;
if (macdTyped.Macd is not decimal macdLine || macdTyped.Signal is not decimal signalLine)
return;
var sar = sarValue.ToDecimal();
// Translate indicator states into normalized scores (0..100).
var macdBull = macdLine > signalLine ? 100m : 0m;
var macdBear = macdLine < signalLine ? 100m : 0m;
var sarBull = candle.ClosePrice > sar ? 100m : 0m;
var sarBear = candle.ClosePrice < sar ? 100m : 0m;
var bullScore = macdBull * MacdWeight + sarBull * SarWeight;
var bearScore = macdBear * MacdWeight + sarBear * SarWeight;
_lastBullScore = bullScore;
_lastBearScore = bearScore;
// Exit conditions take priority to mirror the wizard behaviour.
if (Position > 0 && bearScore >= CloseThreshold)
{
SellMarket();
return;
}
if (Position < 0 && bullScore >= CloseThreshold)
{
BuyMarket();
return;
}
// Entry rules: open when the weighted score exceeds the open threshold.
if (Position <= 0 && bullScore >= OpenThreshold)
{
BuyMarket();
return;
}
if (Position >= 0 && bearScore >= OpenThreshold)
{
SellMarket();
}
}
}
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, Unit, UnitTypes
from StockSharp.Algo.Indicators import MovingAverageConvergenceDivergenceSignal, ParabolicSar
from StockSharp.Algo.Strategies import Strategy
class macd_parabolic_sar_wizard_strategy(Strategy):
"""
MACD + Parabolic SAR wizard: weighted scoring system for entries/exits.
"""
def __init__(self):
super(macd_parabolic_sar_wizard_strategy, self).__init__()
self._macd_fast = self.Param("MacdFastPeriod", 12).SetDisplay("MACD Fast", "Fast EMA period", "MACD")
self._macd_slow = self.Param("MacdSlowPeriod", 24).SetDisplay("MACD Slow", "Slow EMA period", "MACD")
self._macd_signal = self.Param("MacdSignalPeriod", 9).SetDisplay("MACD Signal", "Signal period", "MACD")
self._macd_weight = self.Param("MacdWeight", 0.9).SetDisplay("MACD Weight", "Weight of MACD in scoring", "Scoring")
self._sar_weight = self.Param("SarWeight", 0.1).SetDisplay("SAR Weight", "Weight of SAR in scoring", "Scoring")
self._open_threshold = self.Param("OpenThreshold", 90.0).SetDisplay("Open Threshold", "Score to open", "Scoring")
self._close_threshold = self.Param("CloseThreshold", 90.0).SetDisplay("Close Threshold", "Score to exit", "Scoring")
self._sar_step = self.Param("SarStep", 0.02).SetDisplay("SAR Step", "Acceleration factor", "Parabolic SAR")
self._sar_max = self.Param("SarMax", 0.2).SetDisplay("SAR Max", "Max acceleration", "Parabolic SAR")
self._stop_loss_points = self.Param("StopLossPoints", 50.0).SetDisplay("Stop Loss", "SL in points", "Risk")
self._take_profit_points = self.Param("TakeProfitPoints", 115.0).SetDisplay("Take Profit", "TP in points", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromHours(4))).SetDisplay("Candle Type", "Candles", "General")
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(macd_parabolic_sar_wizard_strategy, self).OnReseted()
def OnStarted2(self, time):
super(macd_parabolic_sar_wizard_strategy, self).OnStarted2(time)
macd = MovingAverageConvergenceDivergenceSignal()
macd.Macd.ShortMa.Length = self._macd_fast.Value
macd.Macd.LongMa.Length = self._macd_slow.Value
macd.SignalMa.Length = self._macd_signal.Value
sar = ParabolicSar()
sar.AccelerationStep = self._sar_step.Value
sar.AccelerationMax = self._sar_max.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(macd, sar, self._process_candle).Start()
step = float(self.Security.PriceStep) if self.Security is not None and self.Security.PriceStep is not None else 1.0
tp = self._take_profit_points.Value * step if self._take_profit_points.Value > 0 else 0
sl = self._stop_loss_points.Value * step if self._stop_loss_points.Value > 0 else 0
if tp > 0 or sl > 0:
self.StartProtection(
Unit(tp, UnitTypes.Absolute) if tp > 0 else Unit(),
Unit(sl, UnitTypes.Absolute) if sl > 0 else Unit(),
True
)
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, macd)
self.DrawIndicator(area, sar)
self.DrawOwnTrades(area)
def _process_candle(self, candle, macd_value, sar_value):
if candle.State != CandleStates.Finished:
return
typed_val = macd_value
macd_line = typed_val.Macd
signal_line = typed_val.Signal
if macd_line is None or signal_line is None:
return
macd_f = float(macd_line)
signal_f = float(signal_line)
sar_f = float(sar_value)
close = float(candle.ClosePrice)
macd_bull = 100.0 if macd_f > signal_f else 0.0
macd_bear = 100.0 if macd_f < signal_f else 0.0
sar_bull = 100.0 if close > sar_f else 0.0
sar_bear = 100.0 if close < sar_f else 0.0
mw = float(self._macd_weight.Value)
sw = float(self._sar_weight.Value)
bull_score = macd_bull * mw + sar_bull * sw
bear_score = macd_bear * mw + sar_bear * sw
ot = float(self._open_threshold.Value)
ct = float(self._close_threshold.Value)
if self.Position > 0 and bear_score >= ct:
self.SellMarket()
return
if self.Position < 0 and bull_score >= ct:
self.BuyMarket()
return
if self.Position <= 0 and bull_score >= ot:
self.BuyMarket()
return
if self.Position >= 0 and bear_score >= ot:
self.SellMarket()
def CreateClone(self):
return macd_parabolic_sar_wizard_strategy()