using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace QuanTAlib;
///
/// BBW: Bollinger Band Width (Normalized)
///
///
/// Measures the normalized width between upper and lower Bollinger Bands as a
/// fraction of the SMA. BBW quantifies volatility relative to price level and is
/// useful for identifying "squeeze" conditions (low volatility) that often precede
/// significant price moves.
///
/// Formula:
/// BBW = (2 × multiplier × StdDev(source, period)) / SMA(source, period)
///
/// Since Bollinger Bands are calculated as SMA ± (multiplier × StdDev), the raw width
/// is 2 × multiplier × StdDev. This implementation normalizes by dividing by the SMA,
/// expressing the band width as a percentage/fraction of the mean price. This makes
/// BBW comparable across instruments with different price levels.
///
/// This implementation uses O(1) running variance calculation via the sum-of-squares
/// method, with periodic resynchronization to prevent floating-point drift.
///
/// Key properties:
/// - Always non-negative (output is normalized as fraction of SMA)
/// - High BBW indicates high relative volatility
/// - Low BBW indicates low relative volatility ("squeeze")
/// - Default: 20-period, 2.0 multiplier (same as standard Bollinger Bands)
///
[SkipLocalsInit]
public sealed class Bbw : AbstractBase
{
private readonly int _period;
private readonly double _multiplier;
private readonly RingBuffer _buffer;
[StructLayout(LayoutKind.Auto)]
private record struct State(
double Sum,
double SumSq,
double SumComp,
double SumSqComp,
double LastValid);
private State _state;
private State _p_state;
///
/// Creates BBW with specified period and multiplier.
///
/// Lookback period (must be > 0)
/// Standard deviation multiplier (must be > 0)
public Bbw(int period, double multiplier = 2.0)
{
if (period <= 0)
{
throw new ArgumentException("Period must be greater than 0", nameof(period));
}
if (multiplier <= 0)
{
throw new ArgumentException("Multiplier must be greater than 0", nameof(multiplier));
}
_period = period;
_multiplier = multiplier;
_buffer = new RingBuffer(period);
Name = $"Bbw({period},{multiplier:F1})";
WarmupPeriod = period;
}
///
/// Creates BBW with specified source, period, and multiplier.
///
public Bbw(ITValuePublisher source, int period, double multiplier = 2.0) : this(period, multiplier)
{
source.Pub += Handle;
}
private void Handle(object? sender, in TValueEventArgs e) => Update(e.Value, e.IsNew);
///
/// True if the indicator has enough data for valid results.
///
public override bool IsHot => _buffer.IsFull;
///
/// Period of the indicator.
///
public int Period => _period;
///
/// Standard deviation multiplier.
///
public double Multiplier => _multiplier;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override TValue Update(TValue input, bool isNew = true)
{
double value = input.Value;
// Sanitize input
if (!double.IsFinite(value))
{
value = double.IsFinite(_state.LastValid) ? _state.LastValid : 0.0;
}
else
{
_state.LastValid = value;
}
if (isNew)
{
_p_state = _state;
// Kahan compensated sliding window update
if (_buffer.Count == _buffer.Capacity)
{
double oldest = _buffer.Oldest;
double delta = value - oldest;
{
double y = delta - _state.SumComp;
double t = _state.Sum + y;
_state.SumComp = (t - _state.Sum) - y;
_state.Sum = t;
}
{
double deltaSq = (value * value) - (oldest * oldest);
double y = deltaSq - _state.SumSqComp;
double t = _state.SumSq + y;
_state.SumSqComp = (t - _state.SumSq) - y;
_state.SumSq = t;
}
}
else
{
{
double y = value - _state.SumComp;
double t = _state.Sum + y;
_state.SumComp = (t - _state.Sum) - y;
_state.Sum = t;
}
{
double sq = value * value;
double y = sq - _state.SumSqComp;
double t = _state.SumSq + y;
_state.SumSqComp = (t - _state.SumSq) - y;
_state.SumSq = t;
}
}
_buffer.Add(value);
}
else
{
_state = _p_state;
// Update the newest value in buffer
_buffer.UpdateNewest(value);
RecalculateSums();
}
// Calculate variance: Var = E[X²] - E[X]²
int count = _buffer.Count;
double mean = _state.Sum / count;
double variance = Math.Max(0.0, (_state.SumSq / count) - (mean * mean));
double stddev = Math.Sqrt(variance);
// BBW = 2 × multiplier × StdDev / SMA (normalized band width)
// Guard against division by zero
double bbw = mean > 0 ? (2.0 * _multiplier * stddev) / mean : 0.0;
Last = new TValue(input.Time, bbw);
PubEvent(Last, isNew);
return Last;
}
public override TSeries Update(TSeries source)
{
int len = source.Count;
var t = new List(len);
var v = new List(len);
CollectionsMarshal.SetCount(t, len);
CollectionsMarshal.SetCount(v, len);
var tSpan = CollectionsMarshal.AsSpan(t);
var vSpan = CollectionsMarshal.AsSpan(v);
Batch(source.Values, vSpan, _period, _multiplier);
source.Times.CopyTo(tSpan);
// Update internal state to match final position
for (int i = 0; i < len; i++)
{
Update(new TValue(source.Times[i], source.Values[i]), isNew: true);
}
return new TSeries(t, v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void RecalculateSums()
{
_state.Sum = 0.0;
_state.SumSq = 0.0;
for (int i = 0; i < _buffer.Count; i++)
{
double v = _buffer[i];
_state.Sum += v;
_state.SumSq += v * v;
}
}
public override void Prime(ReadOnlySpan source, TimeSpan? step = null)
{
for (int i = 0; i < source.Length; i++)
{
Update(new TValue(DateTime.UtcNow, source[i]), isNew: true);
}
}
public override void Reset()
{
_buffer.Clear();
_state = default;
_p_state = default;
Last = default;
}
///
/// Calculates BBW for entire series.
///
public static TSeries Batch(TSeries source, int period, double multiplier = 2.0)
{
int len = source.Count;
var t = new List(len);
var v = new List(len);
CollectionsMarshal.SetCount(t, len);
CollectionsMarshal.SetCount(v, len);
var tSpan = CollectionsMarshal.AsSpan(t);
var vSpan = CollectionsMarshal.AsSpan(v);
Batch(source.Values, vSpan, period, multiplier);
source.Times.CopyTo(tSpan);
return new TSeries(t, v);
}
///
/// Batch BBW calculation with O(1) rolling variance.
///
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Batch(ReadOnlySpan source, Span output, int period, double multiplier = 2.0)
{
if (source.Length != output.Length)
{
throw new ArgumentException("Source and output must have the same length", nameof(output));
}
if (period <= 0)
{
throw new ArgumentException("Period must be greater than 0", nameof(period));
}
if (multiplier <= 0)
{
throw new ArgumentException("Multiplier must be greater than 0", nameof(multiplier));
}
int len = source.Length;
if (len == 0)
{
return;
}
double sum = 0.0;
double sumSq = 0.0;
double mult2 = 2.0 * multiplier;
double lastValid = 0.0;
// Buffer to track sanitized values for correct window removal
var valueBuffer = new RingBuffer(period);
for (int i = 0; i < len; i++)
{
double val = source[i];
// Sanitize input - mirror Update method behavior
if (!double.IsFinite(val))
{
val = lastValid;
}
else
{
lastValid = val;
}
// Remove oldest sanitized value if past warmup
if (i >= period)
{
double oldest = valueBuffer.Oldest;
sum -= oldest;
sumSq -= oldest * oldest;
}
// Add new sanitized value
sum += val;
sumSq += val * val;
valueBuffer.Add(val);
// Calculate variance and BBW
int count = Math.Min(i + 1, period);
double mean = sum / count;
double variance = Math.Max(0.0, (sumSq / count) - (mean * mean));
double stddev = Math.Sqrt(variance);
// BBW = 2 × multiplier × StdDev / SMA (normalized)
output[i] = mean > 0 ? (mult2 * stddev) / mean : 0.0;
}
}
public static (TSeries Results, Bbw Indicator) Calculate(TSeries source, int period, double multiplier = 2.0)
{
var indicator = new Bbw(period, multiplier);
TSeries results = indicator.Update(source);
return (results, indicator);
}
}