VWAP Slope Breakout
The VWAP Slope Breakout strategy observes the rate of change of the VWAP. An unusually steep slope hints that a new trend is forming.
Testing indicates an average annual return of about 133%. It performs best in the crypto 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= 20DeviationMultiplier= 2mStopLossPercent= 2mCandleType= TimeSpan.FromMinutes(5)
- Filters:
- Category: Breakout
- Direction: Both
- Indicators: VWAP
- 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 VWAP slope breakout.
/// Opens positions when VWAP slope deviates from its recent average by a multiple of standard deviation.
/// </summary>
public class VwapSlopeBreakoutStrategy : Strategy
{
private readonly StrategyParam<int> _lookbackPeriod;
private readonly StrategyParam<decimal> _deviationMultiplier;
private readonly StrategyParam<DataType> _candleType;
private readonly StrategyParam<decimal> _stopLossPercent;
private readonly StrategyParam<int> _cooldownBars;
private VolumeWeightedMovingAverage _vwap;
private decimal _prevVwapValue;
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>
/// Lookback period for slope statistics calculation.
/// </summary>
public int LookbackPeriod
{
get => _lookbackPeriod.Value;
set => _lookbackPeriod.Value = value;
}
/// <summary>
/// Standard deviation multiplier for breakout detection.
/// </summary>
public decimal DeviationMultiplier
{
get => _deviationMultiplier.Value;
set => _deviationMultiplier.Value = value;
}
/// <summary>
/// Candle type.
/// </summary>
public DataType CandleType
{
get => _candleType.Value;
set => _candleType.Value = value;
}
/// <summary>
/// Stop loss percentage.
/// </summary>
public decimal StopLossPercent
{
get => _stopLossPercent.Value;
set => _stopLossPercent.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="VwapSlopeBreakoutStrategy"/>.
/// </summary>
public VwapSlopeBreakoutStrategy()
{
_lookbackPeriod = Param(nameof(LookbackPeriod), 20)
.SetGreaterThanZero()
.SetDisplay("Lookback Period", "Period for slope statistics calculation", "Strategy Parameters")
.SetOptimize(10, 50, 5);
_deviationMultiplier = Param(nameof(DeviationMultiplier), 2m)
.SetGreaterThanZero()
.SetDisplay("Deviation Multiplier", "Standard deviation multiplier for breakout detection", "Strategy Parameters")
.SetOptimize(1m, 3m, 0.5m);
_stopLossPercent = Param(nameof(StopLossPercent), 2m)
.SetGreaterThanZero()
.SetDisplay("Stop Loss %", "Stop loss percentage", "Risk Management");
_cooldownBars = Param(nameof(CooldownBars), 2400)
.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();
_vwap = null;
_prevVwapValue = default;
_currentSlope = default;
_avgSlope = default;
_stdDevSlope = default;
_currentIndex = default;
_filledCount = default;
_cooldown = default;
_isInitialized = default;
_slopes = new decimal[LookbackPeriod];
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
_vwap = new VolumeWeightedMovingAverage();
_slopes = new decimal[LookbackPeriod];
_cooldown = 0;
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(_vwap, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, _vwap);
DrawOwnTrades(area);
}
StartProtection(new(), new Unit(StopLossPercent, UnitTypes.Percent));
}
private void ProcessCandle(ICandleMessage candle, decimal vwapValue)
{
if (candle.State != CandleStates.Finished)
return;
if (!_isInitialized)
{
_prevVwapValue = vwapValue;
_isInitialized = true;
return;
}
_currentSlope = vwapValue - _prevVwapValue;
_prevVwapValue = vwapValue;
_slopes[_currentIndex] = _currentSlope;
_currentIndex = (_currentIndex + 1) % LookbackPeriod;
if (_filledCount < LookbackPeriod)
_filledCount++;
if (_filledCount < LookbackPeriod)
return;
CalculateStatistics();
if (!IsFormedAndOnlineAndAllowTrading())
return;
if (_stdDevSlope <= 0)
return;
if (_cooldown > 0)
{
_cooldown--;
return;
}
var upperThreshold = _avgSlope + DeviationMultiplier * _stdDevSlope;
var lowerThreshold = _avgSlope - DeviationMultiplier * _stdDevSlope;
if (Position == 0)
{
if (_currentSlope > upperThreshold)
{
BuyMarket();
_cooldown = CooldownBars;
}
else if (_currentSlope < lowerThreshold)
{
SellMarket();
_cooldown = CooldownBars;
}
}
else if (Position > 0)
{
if (_currentSlope <= _avgSlope)
{
SellMarket(Math.Abs(Position));
_cooldown = CooldownBars;
}
}
else if (Position < 0)
{
if (_currentSlope >= _avgSlope)
{
BuyMarket(Math.Abs(Position));
_cooldown = CooldownBars;
}
}
}
private void CalculateStatistics()
{
_avgSlope = 0;
var sumSquaredDiffs = 0m;
for (var i = 0; i < LookbackPeriod; i++)
_avgSlope += _slopes[i];
_avgSlope /= LookbackPeriod;
for (var i = 0; i < LookbackPeriod; i++)
{
var diff = _slopes[i] - _avgSlope;
sumSquaredDiffs += diff * diff;
}
_stdDevSlope = (decimal)Math.Sqrt((double)(sumSquaredDiffs / LookbackPeriod));
}
}
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 VolumeWeightedMovingAverage
from StockSharp.Algo.Strategies import Strategy
class vwap_slope_breakout_strategy(Strategy):
"""
Strategy based on VWAP slope breakout.
Opens positions when VWAP slope deviates from its recent average by a multiple of standard deviation.
"""
def __init__(self):
super(vwap_slope_breakout_strategy, self).__init__()
self._lookback_period = self.Param("LookbackPeriod", 20) \
.SetGreaterThanZero() \
.SetDisplay("Lookback Period", "Period for slope statistics calculation", "Strategy Parameters") \
.SetOptimize(10, 50, 5)
self._deviation_multiplier = self.Param("DeviationMultiplier", 2.0) \
.SetGreaterThanZero() \
.SetDisplay("Deviation Multiplier", "Standard deviation multiplier for breakout detection", "Strategy Parameters") \
.SetOptimize(1.0, 3.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", 2400) \
.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._vwap = None
self._prev_vwap_value = 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(vwap_slope_breakout_strategy, self).OnReseted()
self._vwap = None
self._prev_vwap_value = 0.0
self._current_slope = 0.0
self._avg_slope = 0.0
self._std_dev_slope = 0.0
lb = int(self._lookback_period.Value)
self._slopes = [0.0] * lb
self._current_index = 0
self._filled_count = 0
self._cooldown = 0
self._is_initialized = False
def OnStarted2(self, time):
super(vwap_slope_breakout_strategy, self).OnStarted2(time)
lb = int(self._lookback_period.Value)
self._slopes = [0.0] * lb
self._cooldown = 0
self._filled_count = 0
self._current_index = 0
self._vwap = VolumeWeightedMovingAverage()
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(self._vwap, self._process_candle).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, self._vwap)
self.DrawOwnTrades(area)
self.StartProtection(Unit(), Unit(self._stop_loss_percent.Value, UnitTypes.Percent))
def _process_candle(self, candle, vwap_value):
if candle.State != CandleStates.Finished:
return
vwap_value = float(vwap_value)
if not self._is_initialized:
self._prev_vwap_value = vwap_value
self._is_initialized = True
return
self._current_slope = vwap_value - self._prev_vwap_value
self._prev_vwap_value = vwap_value
lb = int(self._lookback_period.Value)
self._slopes[self._current_index] = self._current_slope
self._current_index = (self._current_index + 1) % lb
if self._filled_count < lb:
self._filled_count += 1
if self._filled_count < lb:
return
self._calculate_statistics()
if not self.IsFormedAndOnlineAndAllowTrading():
return
if self._std_dev_slope <= 0:
return
if self._cooldown > 0:
self._cooldown -= 1
return
dm = float(self._deviation_multiplier.Value)
upper_threshold = self._avg_slope + dm * self._std_dev_slope
lower_threshold = self._avg_slope - dm * self._std_dev_slope
if self.Position == 0:
if self._current_slope > upper_threshold:
self.BuyMarket()
self._cooldown = int(self._cooldown_bars.Value)
elif self._current_slope < lower_threshold:
self.SellMarket()
self._cooldown = int(self._cooldown_bars.Value)
elif self.Position > 0:
if self._current_slope <= self._avg_slope:
self.SellMarket(Math.Abs(self.Position))
self._cooldown = int(self._cooldown_bars.Value)
elif self.Position < 0:
if self._current_slope >= self._avg_slope:
self.BuyMarket(Math.Abs(self.Position))
self._cooldown = int(self._cooldown_bars.Value)
def _calculate_statistics(self):
lb = int(self._lookback_period.Value)
self._avg_slope = 0.0
sum_sq = 0.0
for i in range(lb):
self._avg_slope += self._slopes[i]
self._avg_slope /= float(lb)
for i in range(lb):
diff = self._slopes[i] - self._avg_slope
sum_sq += diff * diff
self._std_dev_slope = math.sqrt(sum_sq / float(lb))
def CreateClone(self):
return vwap_slope_breakout_strategy()