MACD Enhanced Strategy MTF with Stop Loss
Multi-timeframe strategy using MACD-based scoring and an ATR-derived trailing stop line.
Details
- Entry Criteria: MACD score turns positive or negative.
- Long/Short: Both directions.
- Exit Criteria: Opposite signal or trailing stop line break.
- Stops: ATR trailing stop.
- Default Values:
FastLength= 12SlowLength= 26SignalLength= 9CrossScore= 10IndicatorScore= 8HistogramScore= 2StopLossFactor= 1.2StopLossPeriod= 10CandleType= TimeSpan.FromMinutes(1)
- Filters:
- Category: Trend
- Direction: Both
- Indicators: MACD, ATR
- Stops: Yes
- Complexity: Intermediate
- Timeframe: Intraday
- Seasonality: No
- Neural Networks: No
- Divergence: No
- Risk Level: Medium
using System;
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 ATR-based stop loss.
/// </summary>
public class MacdEnhancedMtfWithStopLossStrategy : Strategy
{
private readonly StrategyParam<int> _fastLength;
private readonly StrategyParam<int> _slowLength;
private readonly StrategyParam<int> _atrLength;
private readonly StrategyParam<decimal> _stopAtrMult;
private readonly StrategyParam<int> _cooldownBars;
private readonly StrategyParam<DataType> _candleType;
private ExponentialMovingAverage _emaFast;
private ExponentialMovingAverage _emaSlow;
private AverageTrueRange _atr;
private bool _prevFastAbove;
private bool _initialized;
private decimal _stopPrice;
private int _barsFromSignal;
public int FastLength { get => _fastLength.Value; set => _fastLength.Value = value; }
public int SlowLength { get => _slowLength.Value; set => _slowLength.Value = value; }
public int AtrLength { get => _atrLength.Value; set => _atrLength.Value = value; }
public decimal StopAtrMult { get => _stopAtrMult.Value; set => _stopAtrMult.Value = value; }
public int CooldownBars { get => _cooldownBars.Value; set => _cooldownBars.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public MacdEnhancedMtfWithStopLossStrategy()
{
_fastLength = Param(nameof(FastLength), 8).SetDisplay("Fast", "Fast EMA", "MACD");
_slowLength = Param(nameof(SlowLength), 17).SetDisplay("Slow", "Slow EMA", "MACD");
_atrLength = Param(nameof(AtrLength), 14).SetDisplay("ATR", "ATR period", "Risk");
_stopAtrMult = Param(nameof(StopAtrMult), 3m).SetDisplay("SL Mult", "ATR stop mult", "Risk");
_cooldownBars = Param(nameof(CooldownBars), 10).SetDisplay("Cooldown", "Bars between signals", "Risk");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Candles", "General");
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_emaFast = null;
_emaSlow = null;
_atr = null;
_prevFastAbove = false;
_initialized = false;
_stopPrice = 0m;
_barsFromSignal = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_prevFastAbove = false;
_initialized = false;
_stopPrice = 0;
_barsFromSignal = 0;
_emaFast = new ExponentialMovingAverage { Length = FastLength };
_emaSlow = new ExponentialMovingAverage { Length = SlowLength };
_atr = new AverageTrueRange { Length = AtrLength };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_emaFast, _emaSlow, _atr, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _emaFast);
DrawIndicator(area, _emaSlow);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow, decimal atr)
{
if (candle.State != CandleStates.Finished)
return;
if (fast == 0 || slow == 0)
return;
var isFastAbove = fast > slow;
if (!_initialized) { _prevFastAbove = isFastAbove; _initialized = true; return; }
if (_barsFromSignal < 10000) _barsFromSignal++;
var crossUp = isFastAbove && !_prevFastAbove;
var crossDown = !isFastAbove && _prevFastAbove;
var canSignal = _barsFromSignal >= CooldownBars;
// Stop loss check
if (Position > 0 && _stopPrice > 0 && candle.ClosePrice <= _stopPrice)
{
SellMarket();
_stopPrice = 0;
_barsFromSignal = 0;
_prevFastAbove = isFastAbove;
return;
}
if (Position < 0 && _stopPrice > 0 && candle.ClosePrice >= _stopPrice)
{
BuyMarket();
_stopPrice = 0;
_barsFromSignal = 0;
_prevFastAbove = isFastAbove;
return;
}
if (canSignal && crossUp && Position <= 0)
{
BuyMarket();
_stopPrice = atr > 0 ? candle.ClosePrice - atr * StopAtrMult : 0;
_barsFromSignal = 0;
}
else if (canSignal && crossDown && Position >= 0)
{
SellMarket();
_stopPrice = atr > 0 ? candle.ClosePrice + atr * StopAtrMult : 0;
_barsFromSignal = 0;
}
_prevFastAbove = isFastAbove;
}
}
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 ExponentialMovingAverage, AverageTrueRange
from StockSharp.Algo.Strategies import Strategy
class macd_enhanced_mtf_with_stop_loss_strategy(Strategy):
"""
MACD crossover with ATR-based stop loss.
"""
def __init__(self):
super(macd_enhanced_mtf_with_stop_loss_strategy, self).__init__()
self._fast_length = self.Param("FastLength", 8).SetDisplay("Fast", "Fast EMA", "MACD")
self._slow_length = self.Param("SlowLength", 17).SetDisplay("Slow", "Slow EMA", "MACD")
self._atr_length = self.Param("AtrLength", 14).SetDisplay("ATR", "ATR period", "Risk")
self._stop_atr_mult = self.Param("StopAtrMult", 3.0).SetDisplay("SL Mult", "ATR stop mult", "Risk")
self._cooldown_bars = self.Param("CooldownBars", 10).SetDisplay("Cooldown", "Bars between signals", "Risk")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))).SetDisplay("Candle Type", "Candles", "General")
self._prev_fast_above = False
self._is_init = False
self._stop_price = 0.0
self._bars_from_signal = 0
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(macd_enhanced_mtf_with_stop_loss_strategy, self).OnReseted()
self._prev_fast_above = False
self._is_init = False
self._stop_price = 0.0
self._bars_from_signal = 0
def OnStarted2(self, time):
super(macd_enhanced_mtf_with_stop_loss_strategy, self).OnStarted2(time)
fast = ExponentialMovingAverage()
fast.Length = self._fast_length.Value
slow = ExponentialMovingAverage()
slow.Length = self._slow_length.Value
atr = AverageTrueRange()
atr.Length = self._atr_length.Value
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(fast, slow, atr, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, fast)
self.DrawIndicator(area, slow)
self.DrawOwnTrades(area)
def _process_candle(self, candle, fast_val, slow_val, atr_val):
if candle.State != CandleStates.Finished:
return
fast = float(fast_val)
slow = float(slow_val)
atr = float(atr_val)
if fast == 0 or slow == 0:
return
is_fast_above = fast > slow
if not self._is_init:
self._prev_fast_above = is_fast_above
self._is_init = True
return
self._bars_from_signal += 1
close = float(candle.ClosePrice)
cross_up = is_fast_above and not self._prev_fast_above
cross_down = not is_fast_above and self._prev_fast_above
can_signal = self._bars_from_signal >= self._cooldown_bars.Value
if self.Position > 0 and self._stop_price > 0 and close <= self._stop_price:
self.SellMarket()
self._stop_price = 0
self._bars_from_signal = 0
self._prev_fast_above = is_fast_above
return
if self.Position < 0 and self._stop_price > 0 and close >= self._stop_price:
self.BuyMarket()
self._stop_price = 0
self._bars_from_signal = 0
self._prev_fast_above = is_fast_above
return
if can_signal and cross_up and self.Position <= 0:
self.BuyMarket()
self._stop_price = close - atr * self._stop_atr_mult.Value if atr > 0 else 0
self._bars_from_signal = 0
elif can_signal and cross_down and self.Position >= 0:
self.SellMarket()
self._stop_price = close + atr * self._stop_atr_mult.Value if atr > 0 else 0
self._bars_from_signal = 0
self._prev_fast_above = is_fast_above
def CreateClone(self):
return macd_enhanced_mtf_with_stop_loss_strategy()