OBV Slope Breakout
The OBV Slope Breakout strategy watches the rate of change of the OBV. An unusually steep slope hints that a new trend is forming.
Testing indicates an average annual return of about 154%. 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 LookbackPeriod = 20.
Details
- Entry Criteria: Indicator exceeds average by deviation multiplier.
- Long/Short: Both directions.
- Exit Criteria: Indicator reverts to average.
- Stops: Yes.
- Default Values:
LookbackPeriod= 20SlopeLength= 5Multiplier= 2mStopLoss= 2mCandleType= TimeSpan.FromMinutes(5)
- Filters:
- Category: Breakout
- Direction: Both
- Indicators: OBV
- 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>
/// On-Balance Volume slope breakout.
/// The slope is the OBV change over <see cref="SlopeLength"/> bars. Enters in the direction of the slope
/// when it exceeds its average by a standard deviation multiplier and exits when it returns to the average.
/// </summary>
public class ObvSlopeBreakoutStrategy : Strategy
{
private readonly StrategyParam<int> _lookbackPeriod;
private readonly StrategyParam<int> _slopeLength;
private readonly StrategyParam<decimal> _multiplier;
private readonly StrategyParam<decimal> _stopLoss;
private readonly StrategyParam<DataType> _candleType;
private readonly Queue<decimal> _obvHistory = new();
private SimpleMovingAverage _slopeAverage;
private StandardDeviation _slopeStdDev;
/// <summary>
/// Lookback period for slope statistics.
/// </summary>
public int LookbackPeriod
{
get => _lookbackPeriod.Value;
set => _lookbackPeriod.Value = value;
}
/// <summary>
/// Number of bars used to measure the OBV slope.
/// </summary>
public int SlopeLength
{
get => _slopeLength.Value;
set => _slopeLength.Value = value;
}
/// <summary>
/// Standard deviation multiplier for breakout detection.
/// </summary>
public decimal Multiplier
{
get => _multiplier.Value;
set => _multiplier.Value = value;
}
/// <summary>
/// Stop-loss percentage.
/// </summary>
public decimal StopLoss
{
get => _stopLoss.Value;
set => _stopLoss.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Initialize <see cref="ObvSlopeBreakoutStrategy"/>.
/// </summary>
public ObvSlopeBreakoutStrategy()
{
_lookbackPeriod = Param(nameof(LookbackPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("Lookback Period", "Period for slope statistics", "Strategy");
_slopeLength = Param(nameof(SlopeLength), 5)
.SetGreaterThanZero()
.SetDisplay("Slope Length", "Bars used to measure the OBV slope", "Indicators");
_multiplier = Param(nameof(Multiplier), 2m)
.SetGreaterThanZero()
.SetDisplay("Multiplier", "Standard deviation multiplier for breakout", "Strategy");
_stopLoss = Param(nameof(StopLoss), 2m)
.SetNotNegative()
.SetDisplay("Stop Loss %", "Stop-loss percentage", "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();
_obvHistory.Clear();
_slopeAverage = null;
_slopeStdDev = null;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var obv = new OnBalanceVolume();
_slopeAverage = new SimpleMovingAverage { Length = LookbackPeriod };
_slopeStdDev = new StandardDeviation { Length = LookbackPeriod };
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(obv, ProcessCandle)
.Start();
StartProtection(
takeProfit: null,
stopLoss: StopLoss > 0 ? new Unit(StopLoss, UnitTypes.Percent) : null
);
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawOwnTrades(area);
var obvArea = CreateChartArea();
if (obvArea != null)
DrawIndicator(obvArea, obv);
}
}
private void ProcessCandle(ICandleMessage candle, decimal obvValue)
{
if (candle.State != CandleStates.Finished)
return;
_obvHistory.Enqueue(obvValue);
if (_obvHistory.Count <= SlopeLength)
return;
var slope = obvValue - _obvHistory.Dequeue();
var avgSlope = _slopeAverage.Process(slope, candle.ServerTime, true).ToDecimal();
var stdSlope = _slopeStdDev.Process(slope, candle.ServerTime, true).ToDecimal();
if (!_slopeAverage.IsFormed || !_slopeStdDev.IsFormed)
return;
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (slope > avgSlope + Multiplier * stdSlope && Position <= 0)
{
BuyMarket(Volume + Math.Abs(Position));
}
else if (slope < avgSlope - Multiplier * stdSlope && Position >= 0)
{
SellMarket(Volume + Math.Abs(Position));
}
else if (Position > 0 && slope < avgSlope)
{
SellMarket(Position);
}
else if (Position < 0 && slope > avgSlope)
{
BuyMarket(-Position);
}
}
}
import clr
clr.AddReference("StockSharp.Messages")
clr.AddReference("StockSharp.Algo")
clr.AddReference("StockSharp.Algo.Indicators")
clr.AddReference("StockSharp.Algo.Strategies")
from collections import deque
from System import TimeSpan
from StockSharp.Messages import DataType, CandleStates, Unit, UnitTypes
from StockSharp.Algo.Indicators import OnBalanceVolume, SimpleMovingAverage, StandardDeviation
from StockSharp.Algo.Strategies import Strategy
from indicator_extensions import *
class obv_slope_breakout_strategy(Strategy):
"""
On-Balance Volume slope breakout.
The slope is the OBV change over SlopeLength bars. Enters in the direction of the slope
when it exceeds its average by a standard deviation multiplier and exits when it returns to the average.
"""
def __init__(self):
super(obv_slope_breakout_strategy, self).__init__()
self._lookback_period = self.Param("LookbackPeriod", 20) \
.SetGreaterThanZero() \
.SetDisplay("Lookback Period", "Period for slope statistics", "Strategy")
self._slope_length = self.Param("SlopeLength", 5) \
.SetGreaterThanZero() \
.SetDisplay("Slope Length", "Bars used to measure the OBV slope", "Indicators")
self._multiplier = self.Param("Multiplier", 2.0) \
.SetGreaterThanZero() \
.SetDisplay("Multiplier", "Standard deviation multiplier for breakout", "Strategy")
self._stop_loss = self.Param("StopLoss", 2.0) \
.SetNotNegative() \
.SetDisplay("Stop Loss %", "Stop-loss percentage", "Risk Management")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles to use", "General")
self._obv_history = deque()
self._slope_average = None
self._slope_std_dev = None
@property
def CandleType(self):
return self._candle_type.Value
def GetWorkingSecurities(self):
return [(self.Security, self.CandleType)]
def OnReseted(self):
super(obv_slope_breakout_strategy, self).OnReseted()
self._obv_history.clear()
self._slope_average = None
self._slope_std_dev = None
def OnStarted2(self, time):
super(obv_slope_breakout_strategy, self).OnStarted2(time)
obv = OnBalanceVolume()
self._slope_average = SimpleMovingAverage()
self._slope_average.Length = self._lookback_period.Value
self._slope_std_dev = StandardDeviation()
self._slope_std_dev.Length = self._lookback_period.Value
subscription = self.SubscribeCandles(self.CandleType)
subscription.Bind(obv, self._process_candle).Start()
stop = float(self._stop_loss.Value)
self.StartProtection(None, Unit(stop, UnitTypes.Percent) if stop > 0 else None)
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawOwnTrades(area)
obv_area = self.CreateChartArea()
if obv_area is not None:
self.DrawIndicator(obv_area, obv)
def _process_candle(self, candle, obv_value):
if candle.State != CandleStates.Finished:
return
obv_value = float(obv_value)
self._obv_history.append(obv_value)
if len(self._obv_history) <= self._slope_length.Value:
return
slope = obv_value - self._obv_history.popleft()
avg_slope = float(process_float(self._slope_average, slope, candle.ServerTime, True))
std_slope = float(process_float(self._slope_std_dev, slope, candle.ServerTime, True))
if not self._slope_average.IsFormed or not self._slope_std_dev.IsFormed:
return
if not self.IsFormedAndOnlineAndAllowTrading():
return
k = float(self._multiplier.Value)
if slope > avg_slope + k * std_slope and self.Position <= 0:
self.BuyMarket(self.Volume + abs(self.Position))
elif slope < avg_slope - k * std_slope and self.Position >= 0:
self.SellMarket(self.Volume + abs(self.Position))
elif self.Position > 0 and slope < avg_slope:
self.SellMarket(self.Position)
elif self.Position < 0 and slope > avg_slope:
self.BuyMarket(-self.Position)
def CreateClone(self):
return obv_slope_breakout_strategy()