MACD Slope Breakout
The MACD Slope Breakout strategy tracks the rate of change of the MACD. An unusually steep slope hints that a new trend is forming.
Testing indicates an average annual return of about 142%. It performs best in the stocks market.
Entries occur when slope exceeds its typical level by a multiple of standard deviation, taking trades in the direction of acceleration with a protective stop.
It appeals to active traders eager for early trend exposure. Positions exit when the slope drifts back toward normal readings. Default FastEma = 12.
Details
- Entry Criteria: Indicator exceeds average by deviation multiplier.
- Long/Short: Both directions.
- Exit Criteria: Indicator reverts to average.
- Stops: Yes.
- Default Values:
FastEma= 12SlowEma= 26SignalMa= 9SlopePeriod= 20BreakoutMultiplier= 2.0mStopLossPercent= 2.0mCandleType= TimeSpan.FromMinutes(5)
- Filters:
- Category: Breakout
- Direction: Both
- Indicators: MACD
- Stops: Yes
- Complexity: Intermediate
- Timeframe: Short-term
- 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 histogram slope breakout.
/// Opens positions when MACD histogram slope deviates from its recent average by a multiple of standard deviation.
/// </summary>
public class MacdSlopeBreakoutStrategy : Strategy
{
private readonly StrategyParam<int> _fastEma;
private readonly StrategyParam<int> _slowEma;
private readonly StrategyParam<int> _signalMa;
private readonly StrategyParam<int> _slopePeriod;
private readonly StrategyParam<decimal> _breakoutMultiplier;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<int> _cooldownBars;
private MovingAverageConvergenceDivergenceSignal _macd;
private decimal _prevHistogramValue;
private decimal _currentSlope;
private decimal _avgSlope;
private decimal _stdDevSlope;
private decimal[] _slopes;
private int _currentIndex;
private int _filledCount;
private int _cooldown;
private bool _isInitialized;
/// <summary>
/// Fast EMA period.
/// </summary>
public int FastEma
{
get => _fastEma.Value;
set => _fastEma.Value = value;
}
/// <summary>
/// Slow EMA period.
/// </summary>
public int SlowEma
{
get => _slowEma.Value;
set => _slowEma.Value = value;
}
/// <summary>
/// Signal MA period.
/// </summary>
public int SignalMa
{
get => _signalMa.Value;
set => _signalMa.Value = value;
}
/// <summary>
/// Lookback period for slope statistics calculation.
/// </summary>
public int SlopePeriod
{
get => _slopePeriod.Value;
set => _slopePeriod.Value = value;
}
/// <summary>
/// Standard deviation multiplier for breakout detection.
/// </summary>
public decimal BreakoutMultiplier
{
get => _breakoutMultiplier.Value;
set => _breakoutMultiplier.Value = value;
}
/// <summary>
/// Stop loss percentage.
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Cooldown bars between orders.
/// </summary>
public int CooldownBars
{
get => _cooldownBars.Value;
set => _cooldownBars.Value = value;
}
/// <summary>
/// Initializes a new instance of <see cref="MacdSlopeBreakoutStrategy"/>.
/// </summary>
public MacdSlopeBreakoutStrategy()
{
_fastEma = Param(nameof(FastEma), 12)
.SetGreaterThanZero()
.SetDisplay("Fast EMA", "Fast EMA period", "Indicator Parameters")
.SetOptimize(8, 16, 2);
_slowEma = Param(nameof(SlowEma), 26)
.SetGreaterThanZero()
.SetDisplay("Slow EMA", "Slow EMA period", "Indicator Parameters")
.SetOptimize(20, 30, 2);
_signalMa = Param(nameof(SignalMa), 9)
.SetGreaterThanZero()
.SetDisplay("Signal MA", "Signal MA period", "Indicator Parameters")
.SetOptimize(7, 12, 1);
_slopePeriod = Param(nameof(SlopePeriod), 20)
.SetGreaterThanZero()
.SetDisplay("Slope Period", "Period for slope statistics calculation", "Strategy Parameters")
.SetOptimize(10, 50, 5);
_breakoutMultiplier = Param(nameof(BreakoutMultiplier), 2.5m)
.SetGreaterThanZero()
.SetDisplay("Breakout Multiplier", "Standard deviation multiplier for breakout detection", "Strategy Parameters")
.SetOptimize(1.5m, 4m, 0.5m);
_stopLossPercent = Param(nameof(StopLossPercent), 2m)
.SetGreaterThanZero()
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk Management");
_cooldownBars = Param(nameof(CooldownBars), 1200)
.SetRange(1, 5000)
.SetDisplay("Cooldown Bars", "Bars to wait between orders", "Risk Management");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles to use", "General");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_macd = null;
_prevHistogramValue = default;
_currentSlope = default;
_avgSlope = default;
_stdDevSlope = default;
_currentIndex = default;
_filledCount = default;
_cooldown = default;
_isInitialized = default;
_slopes = new decimal[SlopePeriod];
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_macd = new MovingAverageConvergenceDivergenceSignal
{
Macd =
{
ShortMa = { Length = FastEma },
LongMa = { Length = SlowEma },
},
SignalMa = { Length = SignalMa },
};
_slopes = new decimal[SlopePeriod];
_cooldown = 0;
var subscription = SubscribeCandles(CandleType);
subscription
.BindEx(_macd, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _macd);
DrawOwnTrades(area);
}
StartProtection(new(), new Unit(StopLossPercent, UnitTypes.Percent));
}
private void ProcessCandle(ICandleMessage candle, IIndicatorValue macdValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_macd.IsFormed)
return;
var typedValue = (MovingAverageConvergenceDivergenceSignalValue)macdValue;
if (typedValue.Macd is not decimal macd ||
typedValue.Signal is not decimal signal)
return;
var histogram = macd - signal;
if (!_isInitialized)
{
_prevHistogramValue = histogram;
_isInitialized = true;
return;
}
_currentSlope = histogram - _prevHistogramValue;
_prevHistogramValue = histogram;
_slopes[_currentIndex] = _currentSlope;
_currentIndex = (_currentIndex + 1) % SlopePeriod;
if (_filledCount < SlopePeriod)
_filledCount++;
if (_filledCount < SlopePeriod)
return;
CalculateStatistics();
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (_stdDevSlope <= 0)
return;
if (_cooldown > 0)
{
_cooldown--;
return;
}
var upperThreshold = _avgSlope + BreakoutMultiplier * _stdDevSlope;
var lowerThreshold = _avgSlope - BreakoutMultiplier * _stdDevSlope;
if (Position == 0)
{
if (_currentSlope > upperThreshold && histogram > 0)
{
BuyMarket();
_cooldown = CooldownBars;
}
else if (_currentSlope < lowerThreshold && histogram < 0)
{
SellMarket();
_cooldown = CooldownBars;
}
}
else if (Position > 0)
{
if (_currentSlope <= _avgSlope || histogram <= 0)
{
SellMarket(Math.Abs(Position));
_cooldown = CooldownBars;
}
}
else if (Position < 0)
{
if (_currentSlope >= _avgSlope || histogram >= 0)
{
BuyMarket(Math.Abs(Position));
_cooldown = CooldownBars;
}
}
}
private void CalculateStatistics()
{
_avgSlope = 0;
var sumSquaredDiffs = 0m;
for (var i = 0; i < SlopePeriod; i++)
_avgSlope += _slopes[i];
_avgSlope /= SlopePeriod;
for (var i = 0; i < SlopePeriod; i++)
{
var diff = _slopes[i] - _avgSlope;
sumSquaredDiffs += diff * diff;
}
_stdDevSlope = (decimal)Math.Sqrt((double)(sumSquaredDiffs / SlopePeriod));
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
import math
from System import TimeSpan, Math
from StockSharp.Messages import DataType, Unit, UnitTypes, CandleStates
from StockSharp.Algo.Indicators import MovingAverageConvergenceDivergenceSignal
from StockSharp.Algo.Strategies import Strategy
class macd_slope_breakout_strategy(Strategy):
"""
Strategy based on MACD histogram slope breakout.
Opens positions when MACD histogram slope deviates from its recent average by a multiple of standard deviation.
"""
def __init__(self):
super(macd_slope_breakout_strategy, self).__init__()
self._fast_ema = self.Param("FastEma", 12) \
.SetGreaterThanZero() \
.SetDisplay("Fast EMA", "Fast EMA period", "Indicator Parameters") \
.SetOptimize(8, 16, 2)
self._slow_ema = self.Param("SlowEma", 26) \
.SetGreaterThanZero() \
.SetDisplay("Slow EMA", "Slow EMA period", "Indicator Parameters") \
.SetOptimize(20, 30, 2)
self._signal_ma = self.Param("SignalMa", 9) \
.SetGreaterThanZero() \
.SetDisplay("Signal MA", "Signal MA period", "Indicator Parameters") \
.SetOptimize(7, 12, 1)
self._slope_period = self.Param("SlopePeriod", 20) \
.SetGreaterThanZero() \
.SetDisplay("Slope Period", "Period for slope statistics calculation", "Strategy Parameters") \
.SetOptimize(10, 50, 5)
self._breakout_multiplier = self.Param("BreakoutMultiplier", 2.5) \
.SetGreaterThanZero() \
.SetDisplay("Breakout Multiplier", "Standard deviation multiplier for breakout detection", "Strategy Parameters") \
.SetOptimize(1.5, 4.0, 0.5)
self._stop_loss_percent = self.Param("StopLossPercent", 2.0) \
.SetGreaterThanZero() \
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk Management")
self._cooldown_bars = self.Param("CooldownBars", 1200) \
.SetDisplay("Cooldown Bars", "Bars to wait between orders", "Risk Management")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._macd = None
self._prev_histogram = 0.0
self._current_slope = 0.0
self._avg_slope = 0.0
self._std_dev_slope = 0.0
self._slopes = None
self._current_index = 0
self._filled_count = 0
self._cooldown = 0
self._is_initialized = False
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(macd_slope_breakout_strategy, self).OnReseted()
self._macd = None
self._prev_histogram = 0.0
self._current_slope = 0.0
self._avg_slope = 0.0
self._std_dev_slope = 0.0
sp = int(self._slope_period.Value)
self._slopes = [0.0] * sp
self._current_index = 0
self._filled_count = 0
self._cooldown = 0
self._is_initialized = False
def OnStarted2(self, time):
super(macd_slope_breakout_strategy, self).OnStarted2(time)
sp = int(self._slope_period.Value)
self._slopes = [0.0] * sp
self._cooldown = 0
self._filled_count = 0
self._current_index = 0
self._macd = MovingAverageConvergenceDivergenceSignal()
self._macd.Macd.ShortMa.Length = int(self._fast_ema.Value)
self._macd.Macd.LongMa.Length = int(self._slow_ema.Value)
self._macd.SignalMa.Length = int(self._signal_ma.Value)
subscription = self.SubscribeCandles(self.candle_type)
subscription.BindEx(self._macd, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._macd)
self.DrawOwnTrades(area)
self.StartProtection(Unit(), Unit(self._stop_loss_percent.Value, UnitTypes.Percent))
def _process_candle(self, candle, macd_value):
if candle.State != CandleStates.Finished:
return
if not self._macd.IsFormed:
return
macd_val = macd_value.Macd
signal_val = macd_value.Signal
if macd_val is None or signal_val is None:
return
histogram = float(macd_val) - float(signal_val)
if not self._is_initialized:
self._prev_histogram = histogram
self._is_initialized = True
return
self._current_slope = histogram - self._prev_histogram
self._prev_histogram = histogram
sp = int(self._slope_period.Value)
self._slopes[self._current_index] = self._current_slope
self._current_index = (self._current_index + 1) % sp
if self._filled_count < sp:
self._filled_count += 1
if self._filled_count < sp:
return
self._calculate_statistics()
if not self.IsFormedAndOnlineAndAllowTrading():
return
if self._std_dev_slope <= 0:
return
if self._cooldown > 0:
self._cooldown -= 1
return
bm = float(self._breakout_multiplier.Value)
upper_threshold = self._avg_slope + bm * self._std_dev_slope
lower_threshold = self._avg_slope - bm * self._std_dev_slope
if self.Position == 0:
if self._current_slope > upper_threshold and histogram > 0:
self.BuyMarket()
self._cooldown = int(self._cooldown_bars.Value)
elif self._current_slope < lower_threshold and histogram < 0:
self.SellMarket()
self._cooldown = int(self._cooldown_bars.Value)
elif self.Position > 0:
if self._current_slope <= self._avg_slope or histogram <= 0:
self.SellMarket(Math.Abs(self.Position))
self._cooldown = int(self._cooldown_bars.Value)
elif self.Position < 0:
if self._current_slope >= self._avg_slope or histogram >= 0:
self.BuyMarket(Math.Abs(self.Position))
self._cooldown = int(self._cooldown_bars.Value)
def _calculate_statistics(self):
sp = int(self._slope_period.Value)
self._avg_slope = 0.0
sum_sq = 0.0
for i in range(sp):
self._avg_slope += self._slopes[i]
self._avg_slope /= float(sp)
for i in range(sp):
diff = self._slopes[i] - self._avg_slope
sum_sq += diff * diff
self._std_dev_slope = math.sqrt(sum_sq / float(sp))
def CreateClone(self):
return macd_slope_breakout_strategy()