Volatility Momentum Breakout Strategy
Combines ATR-based breakout levels with EMA trend filter and RSI momentum to capture strong moves.
Details
- Entry Criteria: price closes above/below ATR breakout levels with EMA and RSI confirmation
- Long/Short: Both
- Exit Criteria: ATR-based stop loss and 1:2 risk-reward take profit
- Stops: ATR stop
- Default Values:
AtrPeriod= 14AtrMultiplier= 1.5Lookback= 20EmaPeriod= 50RsiPeriod= 14RsiLongThreshold= 50RsiShortThreshold= 50RiskReward= 2AtrStopMultiplier= 1
- Filters:
- Category: Breakout
- Direction: Both
- Indicators: ATR, EMA, RSI, Highest, Lowest
- Stops: ATR
- Complexity: Intermediate
- Timeframe: Intraday
- Seasonality: No
- Neural networks: No
- Divergence: No
- Risk level: Medium
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>
/// Volatility breakout strategy with momentum filter.
/// Breaks out above/below rolling high/low with EMA trend and RSI momentum filter.
/// Uses StdDev-based stop and risk/reward target.
/// </summary>
public class VolatilityMomentumBreakoutStrategy : Strategy
{
private readonly StrategyParam<int> _lookback;
private readonly StrategyParam<int> _emaLength;
private readonly StrategyParam<int> _rsiLength;
private readonly StrategyParam<decimal> _rsiLong;
private readonly StrategyParam<decimal> _rsiShort;
private readonly StrategyParam<decimal> _riskReward;
private readonly StrategyParam<decimal> _stopMult;
private readonly StrategyParam<int> _signalCooldownBars;
private readonly StrategyParam<DataType> _candleType;
private readonly List<decimal> _highs = new();
private readonly List<decimal> _lows = new();
private decimal _entryPrice;
private decimal _stopDist;
private int _cooldownRemaining;
public int Lookback { get => _lookback.Value; set => _lookback.Value = value; }
public int EmaLength { get => _emaLength.Value; set => _emaLength.Value = value; }
public int RsiLength { get => _rsiLength.Value; set => _rsiLength.Value = value; }
public decimal RsiLong { get => _rsiLong.Value; set => _rsiLong.Value = value; }
public decimal RsiShort { get => _rsiShort.Value; set => _rsiShort.Value = value; }
public decimal RiskReward { get => _riskReward.Value; set => _riskReward.Value = value; }
public decimal StopMult { get => _stopMult.Value; set => _stopMult.Value = value; }
public int SignalCooldownBars { get => _signalCooldownBars.Value; set => _signalCooldownBars.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public VolatilityMomentumBreakoutStrategy()
{
_lookback = Param(nameof(Lookback), 40)
.SetGreaterThanZero()
.SetDisplay("Lookback", "Breakout lookback", "General");
_emaLength = Param(nameof(EmaLength), 50)
.SetGreaterThanZero()
.SetDisplay("EMA Length", "EMA trend filter", "General");
_rsiLength = Param(nameof(RsiLength), 14)
.SetGreaterThanZero()
.SetDisplay("RSI Length", "RSI period", "General");
_rsiLong = Param(nameof(RsiLong), 55m)
.SetDisplay("RSI Long", "RSI above for longs", "General");
_rsiShort = Param(nameof(RsiShort), 45m)
.SetDisplay("RSI Short", "RSI below for shorts", "General");
_riskReward = Param(nameof(RiskReward), 2m)
.SetGreaterThanZero()
.SetDisplay("Risk/Reward", "Target ratio", "Risk");
_stopMult = Param(nameof(StopMult), 1.5m)
.SetGreaterThanZero()
.SetDisplay("Stop Mult", "StdDev multiplier for stop", "Risk");
_signalCooldownBars = Param(nameof(SignalCooldownBars), 12)
.SetGreaterThanZero()
.SetDisplay("Signal Cooldown", "Bars to wait after a trade", "General");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(15).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "General");
}
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
protected override void OnReseted()
{
base.OnReseted();
_highs.Clear();
_lows.Clear();
_entryPrice = 0;
_stopDist = 0;
_cooldownRemaining = 0;
}
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var ema = new ExponentialMovingAverage { Length = EmaLength };
var rsi = new RelativeStrengthIndex { Length = RsiLength };
var stdDev = new StandardDeviation { Length = 14 };
_highs.Clear();
_lows.Clear();
_entryPrice = 0;
_stopDist = 0;
_cooldownRemaining = 0;
var subscription = SubscribeCandles(CandleType);
subscription.Bind(ema, rsi, stdDev, ProcessCandle).Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, ema);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal emaVal, decimal rsiVal, decimal stdVal)
{
if (candle.State != CandleStates.Finished)
return;
if (_cooldownRemaining > 0)
_cooldownRemaining--;
_highs.Add(candle.HighPrice);
_lows.Add(candle.LowPrice);
while (_highs.Count > Lookback + 1)
{
_highs.RemoveAt(0);
_lows.RemoveAt(0);
}
if (_highs.Count <= Lookback)
return;
// Previous highest/lowest (exclude current bar)
decimal prevHigh = decimal.MinValue;
decimal prevLow = decimal.MaxValue;
for (int i = 0; i < _highs.Count - 1; i++)
{
if (_highs[i] > prevHigh) prevHigh = _highs[i];
if (_lows[i] < prevLow) prevLow = _lows[i];
}
// TP/SL management
if (Position > 0 && _entryPrice > 0 && _stopDist > 0)
{
var sl = _entryPrice - _stopDist;
var tp = _entryPrice + _stopDist * RiskReward;
if (candle.LowPrice <= sl || candle.HighPrice >= tp)
{
SellMarket();
_entryPrice = 0;
_stopDist = 0;
_cooldownRemaining = SignalCooldownBars;
}
}
else if (Position < 0 && _entryPrice > 0 && _stopDist > 0)
{
var sl = _entryPrice + _stopDist;
var tp = _entryPrice - _stopDist * RiskReward;
if (candle.HighPrice >= sl || candle.LowPrice <= tp)
{
BuyMarket();
_entryPrice = 0;
_stopDist = 0;
_cooldownRemaining = SignalCooldownBars;
}
}
// Entry signals
if (_cooldownRemaining == 0 && Position <= 0 && candle.ClosePrice > prevHigh && candle.ClosePrice > emaVal && rsiVal > RsiLong && stdVal > 0)
{
BuyMarket();
_entryPrice = candle.ClosePrice;
_stopDist = StopMult * stdVal;
}
else if (_cooldownRemaining == 0 && Position >= 0 && candle.ClosePrice < prevLow && candle.ClosePrice < emaVal && rsiVal < RsiShort && stdVal > 0)
{
SellMarket();
_entryPrice = candle.ClosePrice;
_stopDist = StopMult * stdVal;
}
}
}
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, RelativeStrengthIndex, StandardDeviation
from StockSharp.Algo.Strategies import Strategy
class volatility_momentum_breakout_strategy(Strategy):
def __init__(self):
super(volatility_momentum_breakout_strategy, self).__init__()
self._lookback = self.Param("Lookback", 40) \
.SetDisplay("Lookback", "Breakout lookback", "General")
self._ema_length = self.Param("EmaLength", 50) \
.SetDisplay("EMA Length", "EMA trend filter", "General")
self._rsi_length = self.Param("RsiLength", 14) \
.SetDisplay("RSI Length", "RSI period", "General")
self._rsi_long = self.Param("RsiLong", 55.0) \
.SetDisplay("RSI Long", "RSI above for longs", "General")
self._rsi_short = self.Param("RsiShort", 45.0) \
.SetDisplay("RSI Short", "RSI below for shorts", "General")
self._risk_reward = self.Param("RiskReward", 2.0) \
.SetDisplay("Risk/Reward", "Target ratio", "Risk")
self._stop_mult = self.Param("StopMult", 1.5) \
.SetDisplay("Stop Mult", "StdDev multiplier for stop", "Risk")
self._signal_cooldown_bars = self.Param("SignalCooldownBars", 12) \
.SetDisplay("Signal Cooldown", "Bars to wait after a trade", "General")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(15))) \
.SetDisplay("Candle Type", "Type of candles", "General")
self._highs = []
self._lows = []
self._entry_price = 0.0
self._stop_dist = 0.0
self._cooldown_remaining = 0
@property
def lookback(self):
return self._lookback.Value
@property
def ema_length(self):
return self._ema_length.Value
@property
def rsi_length(self):
return self._rsi_length.Value
@property
def rsi_long(self):
return self._rsi_long.Value
@property
def rsi_short(self):
return self._rsi_short.Value
@property
def risk_reward(self):
return self._risk_reward.Value
@property
def stop_mult(self):
return self._stop_mult.Value
@property
def signal_cooldown_bars(self):
return self._signal_cooldown_bars.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(volatility_momentum_breakout_strategy, self).OnReseted()
self._highs = []
self._lows = []
self._entry_price = 0.0
self._stop_dist = 0.0
self._cooldown_remaining = 0
def OnStarted2(self, time):
super(volatility_momentum_breakout_strategy, self).OnStarted2(time)
ema = ExponentialMovingAverage()
ema.Length = self.ema_length
rsi = RelativeStrengthIndex()
rsi.Length = self.rsi_length
std_dev = StandardDeviation()
std_dev.Length = 14
self._highs = []
self._lows = []
self._entry_price = 0.0
self._stop_dist = 0.0
self._cooldown_remaining = 0
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(ema, rsi, std_dev, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, ema)
self.DrawOwnTrades(area)
def on_process(self, candle, ema_val, rsi_val, std_val):
if candle.State != CandleStates.Finished:
return
if self._cooldown_remaining > 0:
self._cooldown_remaining -= 1
self._highs.append(float(candle.HighPrice))
self._lows.append(float(candle.LowPrice))
while len(self._highs) > self.lookback + 1:
self._highs.pop(0)
self._lows.pop(0)
if len(self._highs) <= self.lookback:
return
prev_high = -1e18
prev_low = 1e18
for i in range(len(self._highs) - 1):
if self._highs[i] > prev_high:
prev_high = self._highs[i]
if self._lows[i] < prev_low:
prev_low = self._lows[i]
close = float(candle.ClosePrice)
ema_f = float(ema_val)
rsi_f = float(rsi_val)
std_f = float(std_val)
if self.Position > 0 and self._entry_price > 0 and self._stop_dist > 0:
sl = self._entry_price - self._stop_dist
tp = self._entry_price + self._stop_dist * self.risk_reward
if float(candle.LowPrice) <= sl or float(candle.HighPrice) >= tp:
self.SellMarket()
self._entry_price = 0.0
self._stop_dist = 0.0
self._cooldown_remaining = self.signal_cooldown_bars
elif self.Position < 0 and self._entry_price > 0 and self._stop_dist > 0:
sl = self._entry_price + self._stop_dist
tp = self._entry_price - self._stop_dist * self.risk_reward
if float(candle.HighPrice) >= sl or float(candle.LowPrice) <= tp:
self.BuyMarket()
self._entry_price = 0.0
self._stop_dist = 0.0
self._cooldown_remaining = self.signal_cooldown_bars
if self._cooldown_remaining == 0 and self.Position <= 0 and close > prev_high and close > ema_f and rsi_f > self.rsi_long and std_f > 0:
self.BuyMarket()
self._entry_price = close
self._stop_dist = self.stop_mult * std_f
elif self._cooldown_remaining == 0 and self.Position >= 0 and close < prev_low and close < ema_f and rsi_f < self.rsi_short and std_f > 0:
self.SellMarket()
self._entry_price = close
self._stop_dist = self.stop_mult * std_f
def CreateClone(self):
return volatility_momentum_breakout_strategy()