Volatility Bias Model
Counts bullish vs bearish closes over a window and trades in the direction of the dominant bias when volatility is sufficient. Uses ATR targets and exits after a maximum number of bars.
Details
- Entry Criteria: Bias ratio above
BiasThresholdfor long or below1 - BiasThresholdfor short with range aboveRangeMin. - Long/Short: Both directions.
- Exit Criteria: Stop, take profit, or
MaxBarsreached. - Stops: Yes.
- Default Values:
BiasWindow= 10BiasThreshold= 0.6RangeMin= 0.05RiskReward= 2MaxBars= 20AtrLength= 14CandleType= TimeSpan.FromMinutes(5)
- Filters:
- Category: Volatility
- Direction: Both
- Indicators: ATR, SMA, Highest, Lowest
- Stops: Yes
- Complexity: Beginner
- Timeframe: Intraday
- Seasonality: No
- Neural Networks: No
- Divergence: No
- Risk Level: Medium
using System;
using System.Collections.Generic;
using StockSharp.Algo.Indicators;
using StockSharp.Algo.Strategies;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
namespace StockSharp.Samples.Strategies;
/// <summary>
/// Measures directional bias over a window and trades when bias conditions align.
/// Uses EMA crossover with bias confirmation.
/// </summary>
public class VolatilityBiasModelStrategy : Strategy
{
private readonly StrategyParam<int> _biasWindow;
private readonly StrategyParam<decimal> _biasThreshold;
private readonly StrategyParam<int> _maxBars;
private readonly StrategyParam<DataType> _candleType;
private decimal _prevFast;
private decimal _prevSlow;
private readonly Queue<bool> _biasQueue = new();
private int _barsInPosition;
private int _cooldown;
public int BiasWindow { get => _biasWindow.Value; set => _biasWindow.Value = value; }
public decimal BiasThreshold { get => _biasThreshold.Value; set => _biasThreshold.Value = value; }
public int MaxBars { get => _maxBars.Value; set => _maxBars.Value = value; }
public DataType CandleType { get => _candleType.Value; set => _candleType.Value = value; }
public VolatilityBiasModelStrategy()
{
_biasWindow = Param(nameof(BiasWindow), 10)
.SetGreaterThanZero()
.SetDisplay("Bias Window", "Bars for bias calculation", "Parameters");
_biasThreshold = Param(nameof(BiasThreshold), 0.6m)
.SetRange(0m, 1m)
.SetDisplay("Bias Threshold", "Directional bias threshold", "Parameters");
_maxBars = Param(nameof(MaxBars), 100)
.SetGreaterThanZero()
.SetDisplay("Max Bars", "Maximum bars to hold", "Parameters");
_candleType = Param(nameof(CandleType), TimeSpan.FromMinutes(5).TimeFrame())
.SetDisplay("Candle Type", "Type of candles", "Parameters");
}
/// <inheritdoc />
public override IEnumerable<(Security sec, DataType dt)> GetWorkingSecurities()
{
return [(Security, CandleType)];
}
/// <inheritdoc />
protected override void OnReseted()
{
base.OnReseted();
_prevFast = 0;
_prevSlow = 0;
_biasQueue.Clear();
_barsInPosition = 0;
_cooldown = 0;
}
/// <inheritdoc />
protected override void OnStarted2(DateTime time)
{
base.OnStarted2(time);
var fastEma = new ExponentialMovingAverage { Length = 10 };
var slowEma = new ExponentialMovingAverage { Length = 30 };
_prevFast = 0;
_prevSlow = 0;
_biasQueue.Clear();
_barsInPosition = 0;
_cooldown = 0;
var subscription = SubscribeCandles(CandleType);
subscription
.Bind(fastEma, slowEma, ProcessCandle)
.Start();
var area = CreateChartArea();
if (area != null)
{
DrawCandles(area, subscription);
DrawIndicator(area, fastEma);
DrawIndicator(area, slowEma);
DrawOwnTrades(area);
}
}
private void ProcessCandle(ICandleMessage candle, decimal fast, decimal slow)
{
if (candle.State != CandleStates.Finished)
return;
// Track bias in rolling window
_biasQueue.Enqueue(candle.ClosePrice > candle.OpenPrice);
while (_biasQueue.Count > BiasWindow)
_biasQueue.Dequeue();
if (_cooldown > 0)
{
_cooldown--;
if (Position != 0)
_barsInPosition++;
_prevFast = fast;
_prevSlow = slow;
return;
}
if (_prevFast == 0)
{
_prevFast = fast;
_prevSlow = slow;
return;
}
// Time-based exit
if (Position != 0)
{
_barsInPosition++;
if (_barsInPosition >= MaxBars)
{
if (Position > 0)
SellMarket();
else
BuyMarket();
_barsInPosition = 0;
_cooldown = 50;
_prevFast = fast;
_prevSlow = slow;
return;
}
}
if (_biasQueue.Count < BiasWindow)
{
_prevFast = fast;
_prevSlow = slow;
return;
}
var bullCount = 0;
foreach (var b in _biasQueue)
if (b) bullCount++;
var biasRatio = (decimal)bullCount / _biasQueue.Count;
var longCross = _prevFast <= _prevSlow && fast > slow;
var shortCross = _prevFast >= _prevSlow && fast < slow;
if (longCross && biasRatio >= BiasThreshold && Position <= 0)
{
BuyMarket();
_barsInPosition = 0;
_cooldown = 50;
}
else if (shortCross && biasRatio <= (1 - BiasThreshold) && Position >= 0)
{
SellMarket();
_barsInPosition = 0;
_cooldown = 50;
}
_prevFast = fast;
_prevSlow = slow;
}
}
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
from StockSharp.Algo.Strategies import Strategy
class volatility_bias_model_strategy(Strategy):
def __init__(self):
super(volatility_bias_model_strategy, self).__init__()
self._bias_window = self.Param("BiasWindow", 10) \
.SetDisplay("Bias Window", "Bars for bias calculation", "Parameters")
self._bias_threshold = self.Param("BiasThreshold", 0.6) \
.SetDisplay("Bias Threshold", "Directional bias threshold", "Parameters")
self._max_bars = self.Param("MaxBars", 100) \
.SetDisplay("Max Bars", "Maximum bars to hold", "Parameters")
self._candle_type = self.Param("CandleType", DataType.TimeFrame(TimeSpan.FromMinutes(5))) \
.SetDisplay("Candle Type", "Type of candles", "Parameters")
self._prev_fast = 0.0
self._prev_slow = 0.0
self._bias_queue = []
self._bars_in_position = 0
self._cooldown = 0
@property
def bias_window(self):
return self._bias_window.Value
@property
def bias_threshold(self):
return self._bias_threshold.Value
@property
def max_bars(self):
return self._max_bars.Value
@property
def candle_type(self):
return self._candle_type.Value
def OnReseted(self):
super(volatility_bias_model_strategy, self).OnReseted()
self._prev_fast = 0.0
self._prev_slow = 0.0
self._bias_queue = []
self._bars_in_position = 0
self._cooldown = 0
def OnStarted2(self, time):
super(volatility_bias_model_strategy, self).OnStarted2(time)
fast_ema = ExponentialMovingAverage()
fast_ema.Length = 10
slow_ema = ExponentialMovingAverage()
slow_ema.Length = 30
self._prev_fast = 0.0
self._prev_slow = 0.0
self._bias_queue = []
self._bars_in_position = 0
self._cooldown = 0
subscription = self.SubscribeCandles(self.candle_type)
subscription.Bind(fast_ema, slow_ema, self.on_process).Start()
area = self.CreateChartArea()
if area is not None:
self.DrawCandles(area, subscription)
self.DrawIndicator(area, fast_ema)
self.DrawIndicator(area, slow_ema)
self.DrawOwnTrades(area)
def on_process(self, candle, fast, slow):
if candle.State != CandleStates.Finished:
return
fast = float(fast)
slow = float(slow)
# Track bias in rolling window
self._bias_queue.append(float(candle.ClosePrice) > float(candle.OpenPrice))
while len(self._bias_queue) > self.bias_window:
self._bias_queue.pop(0)
if self._cooldown > 0:
self._cooldown -= 1
if self.Position != 0:
self._bars_in_position += 1
self._prev_fast = fast
self._prev_slow = slow
return
if self._prev_fast == 0:
self._prev_fast = fast
self._prev_slow = slow
return
# Time-based exit
if self.Position != 0:
self._bars_in_position += 1
if self._bars_in_position >= self.max_bars:
if self.Position > 0:
self.SellMarket()
else:
self.BuyMarket()
self._bars_in_position = 0
self._cooldown = 50
self._prev_fast = fast
self._prev_slow = slow
return
if len(self._bias_queue) < self.bias_window:
self._prev_fast = fast
self._prev_slow = slow
return
bull_count = 0
for b in self._bias_queue:
if b:
bull_count += 1
bias_ratio = float(bull_count) / len(self._bias_queue)
long_cross = self._prev_fast <= self._prev_slow and fast > slow
short_cross = self._prev_fast >= self._prev_slow and fast < slow
if long_cross and bias_ratio >= self.bias_threshold and self.Position <= 0:
self.BuyMarket()
self._bars_in_position = 0
self._cooldown = 50
elif short_cross and bias_ratio <= (1 - self.bias_threshold) and self.Position >= 0:
self.SellMarket()
self._bars_in_position = 0
self._cooldown = 50
self._prev_fast = fast
self._prev_slow = slow
def CreateClone(self):
return volatility_bias_model_strategy()