Adr, Ap, Atrp, Atrs, Vp, Vwap, Vwma

This commit is contained in:
Miha Kralj
2024-11-01 18:36:01 -07:00
parent 7c6b698c9a
commit f519594371
14 changed files with 1035 additions and 120 deletions
+1 -1
View File
@@ -4,7 +4,7 @@ Done: 11, Todo: 18
✔️ AC - Acceleration Oscillator
✔️ AO - Awesome Oscillator
✔️ *AROON - Aroon oscillator (Up, Down)
BOP - Balance of Power
✔️ BOP - Balance of Power
✔️ CCI - Commodity Channel Index
✔️ CFO - Chande Forcast Oscillator
✔️ CMO - Chande Momentum Oscillator
+83
View File
@@ -0,0 +1,83 @@
using System.Runtime.CompilerServices;
namespace QuanTAlib;
/// <summary>
/// ADR: Average Daily Range
/// A volatility indicator that measures the average range of price movement over
/// a specified period. It helps identify normal trading ranges and potential
/// breakout levels.
/// </summary>
/// <remarks>
/// The ADR calculation process:
/// 1. Calculate daily range (High - Low)
/// 2. Apply SMA to daily ranges
/// 3. Updates with each new price bar
///
/// Key characteristics:
/// - Simple volatility measure
/// - Period-based average
/// - Trend independent
/// - Absolute price measure
/// - Support/resistance aid
///
/// Formula:
/// Daily Range = High - Low
/// ADR = SMA(Daily Range, period)
///
/// Market Applications:
/// - Position sizing
/// - Volatility analysis
/// - Support/resistance levels
/// - Breakout identification
/// - Risk assessment
///
/// Note: Simpler alternative to ATR, doesn't consider gaps
/// </remarks>
[SkipLocalsInit]
public sealed class Adr : AbstractBase
{
private readonly Sma _ma;
private const int DefaultPeriod = 14;
/// <param name="period">The number of periods for ADR calculation (default 14).</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when period is less than 1.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Adr(int period = DefaultPeriod)
{
if (period < 1)
throw new ArgumentOutOfRangeException(nameof(period));
_ma = new(period);
WarmupPeriod = period;
Name = $"ADR({period})";
}
/// <param name="source">The data source object that publishes updates.</param>
/// <param name="period">The number of periods for ADR calculation.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Adr(object source, int period = DefaultPeriod) : this(period)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new BarSignal(Sub));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void ManageState(bool isNew)
{
if (isNew)
_index++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
protected override double Calculation()
{
ManageState(BarInput.IsNew);
// Calculate daily range
double range = BarInput.High - BarInput.Low;
// Apply SMA smoothing
return _ma.Calc(range, BarInput.IsNew);
}
}
+120
View File
@@ -0,0 +1,120 @@
using System.Runtime.CompilerServices;
namespace QuanTAlib;
/// <summary>
/// AP: Andrew's Pitchfork
/// A trend channel tool that uses three points to create a channel with a median
/// line and two parallel lines. It helps identify potential support and resistance
/// levels based on market pivots.
/// </summary>
/// <remarks>
/// The AP calculation process:
/// 1. Use three pivot points (P0, P1, P2)
/// 2. Calculate median line from P0 to midpoint of P1-P2
/// 3. Draw parallel lines at P1 and P2
/// 4. Project all lines forward
///
/// Key characteristics:
/// - Trend channel tool
/// - Support/resistance levels
/// - Price projection
/// - Market geometry
/// - Pivot-based analysis
///
/// Formula:
/// Median Line = Line from P0 to (P1 + P2)/2
/// Upper Line = Parallel to median at P1
/// Lower Line = Parallel to median at P2
///
/// Market Applications:
/// - Trend analysis
/// - Support/resistance
/// - Price targets
/// - Channel trading
/// - Market structure
///
/// Sources:
/// Dr. Alan Andrews
/// https://www.investopedia.com/terms/a/andrewspitchfork.asp
///
/// Note: Returns median line value for current price level
/// </remarks>
[SkipLocalsInit]
public sealed class Ap : AbstractBase
{
private readonly CircularBuffer _highs;
private readonly CircularBuffer _lows;
private readonly CircularBuffer _closes;
private const int DefaultPeriod = 20;
/// <param name="period">The lookback period for pivot points (default 20).</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when period is less than 3.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Ap(int period = DefaultPeriod)
{
if (period < 3)
throw new ArgumentOutOfRangeException(nameof(period));
_highs = new(period);
_lows = new(period);
_closes = new(period);
WarmupPeriod = period;
Name = $"AP({period})";
}
/// <param name="source">The data source object that publishes updates.</param>
/// <param name="period">The lookback period for pivot points.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Ap(object source, int period = DefaultPeriod) : this(period)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new BarSignal(Sub));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void ManageState(bool isNew)
{
if (isNew)
_index++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static (double x, double y) FindPivot(CircularBuffer highs, CircularBuffer lows, CircularBuffer closes, int offset)
{
double high = highs[offset];
double low = lows[offset];
double close = closes[offset];
return (offset, (high + low + close) / 3.0); // Simple pivot point calculation
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
protected override double Calculation()
{
ManageState(BarInput.IsNew);
// Store price data
_highs.Add(BarInput.High, BarInput.IsNew);
_lows.Add(BarInput.Low, BarInput.IsNew);
_closes.Add(BarInput.Close, BarInput.IsNew);
if (_index < WarmupPeriod)
return BarInput.Close;
// Find three pivot points
var p0 = FindPivot(_highs, _lows, _closes, 2);
var p1 = FindPivot(_highs, _lows, _closes, 1);
var p2 = FindPivot(_highs, _lows, _closes, 0);
// Calculate midpoint of P1-P2
double midX = (p1.x + p2.x) / 2.0;
double midY = (p1.y + p2.y) / 2.0;
// Calculate slope of median line
double slope = (midY - p0.y) / (midX - p0.x);
// Project median line to current bar
double currentX = _index - p0.x;
return p0.y + slope * currentX;
}
}
+85
View File
@@ -0,0 +1,85 @@
using System.Runtime.CompilerServices;
namespace QuanTAlib;
/// <summary>
/// ATRP: Average True Range Percent
/// A volatility indicator that expresses ATR as a percentage of current price.
/// This normalization allows for comparison across different price levels and
/// instruments.
/// </summary>
/// <remarks>
/// The ATRP calculation process:
/// 1. Calculate ATR normally
/// 2. Divide by current price
/// 3. Multiply by 100 for percentage
///
/// Key characteristics:
/// - Normalized volatility measure
/// - Price-independent comparison
/// - Percentage output
/// - Cross-market analysis
/// - Relative volatility measure
///
/// Formula:
/// ATRP = (ATR / Close) * 100
///
/// Market Applications:
/// - Cross-market comparison
/// - Position sizing
/// - Volatility analysis
/// - Risk assessment
/// - Market comparison
///
/// Note: More suitable for comparing different instruments than raw ATR
/// </remarks>
[SkipLocalsInit]
public sealed class Atrp : AbstractBase
{
private readonly Atr _atr;
private const int DefaultPeriod = 14;
private const double ScalingFactor = 100.0;
/// <param name="period">The number of periods for ATR calculation (default 14).</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when period is less than 1.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Atrp(int period = DefaultPeriod)
{
if (period < 1)
throw new ArgumentOutOfRangeException(nameof(period));
_atr = new(period);
WarmupPeriod = period;
Name = $"ATRP({period})";
}
/// <param name="source">The data source object that publishes updates.</param>
/// <param name="period">The number of periods for ATR calculation.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Atrp(object source, int period = DefaultPeriod) : this(period)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new BarSignal(Sub));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void ManageState(bool isNew)
{
if (isNew)
_index++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
protected override double Calculation()
{
ManageState(BarInput.IsNew);
// Calculate ATR
double atr = _atr.Calc(BarInput);
// Convert to percentage of price
return Math.Abs(BarInput.Close) > double.Epsilon
? (atr / BarInput.Close) * ScalingFactor
: 0.0;
}
}
+159
View File
@@ -0,0 +1,159 @@
using System.Runtime.CompilerServices;
namespace QuanTAlib;
/// <summary>
/// ATRS: ATR Trailing Stop
/// A volatility-based trailing stop indicator that uses ATR to dynamically adjust
/// stop levels. It helps maintain position while allowing for normal market
/// fluctuations.
/// </summary>
/// <remarks>
/// The ATRS calculation process:
/// 1. Calculate ATR
/// 2. Multiply ATR by factor
/// 3. Apply trailing logic based on trend
/// 4. Update stop levels
///
/// Key characteristics:
/// - Dynamic stop levels
/// - Trend-following
/// - Volatility-based
/// - Position protection
/// - Risk management
///
/// Formula:
/// Long Stop = High - (ATR * Factor)
/// Short Stop = Low + (ATR * Factor)
/// where Factor is multiplier for ATR (default 2.0)
///
/// Market Applications:
/// - Stop loss placement
/// - Position management
/// - Trend following
/// - Risk control
/// - Exit strategy
///
/// Note: Returns stop level based on current trend
/// </remarks>
[SkipLocalsInit]
public sealed class Atrs : AbstractBase
{
private readonly Atr _atr;
private double _prevStop;
private double _p_prevStop;
private bool _isLong;
private bool _p_isLong;
private const int DefaultPeriod = 14;
private const double DefaultFactor = 2.0;
/// <summary>
/// Gets the current trend direction (true for long, false for short)
/// </summary>
public bool IsLong => _isLong;
/// <param name="period">The number of periods for ATR calculation (default 14).</param>
/// <param name="factor">The multiplier for ATR (default 2.0).</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when period is less than 1 or factor is less than or equal to 0.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Atrs(int period = DefaultPeriod, double factor = DefaultFactor)
{
if (period < 1)
throw new ArgumentOutOfRangeException(nameof(period));
if (factor <= 0)
throw new ArgumentOutOfRangeException(nameof(factor));
_atr = new(period);
Factor = factor;
WarmupPeriod = period;
Name = $"ATRS({period},{factor:F1})";
}
/// <param name="source">The data source object that publishes updates.</param>
/// <param name="period">The number of periods for ATR calculation.</param>
/// <param name="factor">The multiplier for ATR.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Atrs(object source, int period = DefaultPeriod, double factor = DefaultFactor) : this(period, factor)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new BarSignal(Sub));
}
/// <summary>
/// Gets or sets the ATR multiplier factor
/// </summary>
public double Factor { get; set; }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Init()
{
base.Init();
_atr.Init();
_prevStop = double.NaN;
_isLong = true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void ManageState(bool isNew)
{
if (isNew)
{
_index++;
_p_prevStop = _prevStop;
_p_isLong = _isLong;
}
else
{
_prevStop = _p_prevStop;
_isLong = _p_isLong;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
protected override double Calculation()
{
ManageState(BarInput.IsNew);
// Calculate ATR
double atr = _atr.Calc(BarInput);
double atrBand = atr * Factor;
if (_index == 1 || double.IsNaN(_prevStop))
{
// Initialize stop level
_isLong = BarInput.Close > BarInput.Open;
_prevStop = _isLong ? BarInput.Low - atrBand : BarInput.High + atrBand;
return _prevStop;
}
// Update stop level based on trend
if (_isLong)
{
double newStop = BarInput.High - atrBand;
if (BarInput.Close < _prevStop)
{
_isLong = false;
_prevStop = BarInput.High + atrBand;
}
else if (newStop > _prevStop)
{
_prevStop = newStop;
}
}
else
{
double newStop = BarInput.Low + atrBand;
if (BarInput.Close > _prevStop)
{
_isLong = true;
_prevStop = BarInput.Low - atrBand;
}
else if (newStop < _prevStop)
{
_prevStop = newStop;
}
}
return _prevStop;
}
}
+5 -5
View File
@@ -1,11 +1,11 @@
# Volatility indicators
Done: 11, Todo: 24
Done: 15, Todo: 20
ADR - Average Daily Range
AP - Andrew's Pitchfork
✔️ ADR - Average Daily Range
✔️ AP - Andrew's Pitchfork
✔️ ATR - Average True Range
ATRP - Average True Range Percent
ATRS - ATR Trailing Stop
✔️ ATRP - Average True Range Percent
✔️ ATRS - ATR Trailing Stop
*BB - Bollinger Bands® (Upper, Middle, Lower)
CCV - Close-to-Close Volatility
CE - Chandelier Exit
+110
View File
@@ -0,0 +1,110 @@
using System.Runtime.CompilerServices;
namespace QuanTAlib;
/// <summary>
/// VF: Volume Force
/// A volume-based indicator that measures the strength of volume relative to price
/// movement. It helps identify whether volume is supporting or contradicting the
/// current price trend.
/// </summary>
/// <remarks>
/// The VF calculation process:
/// 1. Calculate price change
/// 2. Calculate volume force as volume * price change
/// 3. Optionally smooth the result with EMA
///
/// Key characteristics:
/// - Volume-weighted measure
/// - Trend strength indicator
/// - No upper/lower bounds
/// - Raw and smoothed versions
/// - Divergence indicator
///
/// Formula:
/// VF = Volume * (Close - Close[1])
/// Smoothed VF = EMA(VF, period)
///
/// Market Applications:
/// - Volume analysis
/// - Trend confirmation
/// - Price/volume divergence
/// - Market participation
/// - Momentum confirmation
///
/// Note: Higher values indicate stronger volume force
/// </remarks>
[SkipLocalsInit]
public sealed class Vf : AbstractBase
{
private readonly Ema _ema;
private double _prevClose;
private double _p_prevClose;
private const int DefaultPeriod = 13;
/// <param name="period">The smoothing period for EMA calculation (default 13).</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when period is less than 1.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vf(int period = DefaultPeriod)
{
if (period < 1)
throw new ArgumentOutOfRangeException(nameof(period));
_ema = new(period);
WarmupPeriod = period + 1;
Name = $"VF({period})";
}
/// <param name="source">The data source object that publishes updates.</param>
/// <param name="period">The smoothing period for EMA calculation.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vf(object source, int period = DefaultPeriod) : this(period)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new BarSignal(Sub));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Init()
{
base.Init();
_ema.Init();
_prevClose = double.NaN;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void ManageState(bool isNew)
{
if (isNew)
{
_index++;
_p_prevClose = _prevClose;
}
else
{
_prevClose = _p_prevClose;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
protected override double Calculation()
{
ManageState(BarInput.IsNew);
if (_index == 1)
{
_prevClose = BarInput.Close;
return 0;
}
// Calculate raw volume force
double priceChange = BarInput.Close - _prevClose;
double volumeForce = BarInput.Volume * priceChange;
// Update previous close
_prevClose = BarInput.Close;
// Apply EMA smoothing
return _ema.Calc(volumeForce, BarInput.IsNew);
}
}
+105
View File
@@ -0,0 +1,105 @@
using System.Runtime.CompilerServices;
namespace QuanTAlib;
/// <summary>
/// VP: Volume Profile
/// A volume-based indicator that analyzes volume distribution across price levels.
/// It helps identify significant price levels where most trading activity occurs.
/// </summary>
/// <remarks>
/// The VP calculation process:
/// 1. Track volume at each price level within a period
/// 2. Calculate Point of Control (POC) - price with highest volume
/// 3. Calculate Value Area (70% of total volume)
///
/// Key characteristics:
/// - Price level analysis
/// - Volume distribution
/// - Support/resistance identification
/// - Trading activity concentration
/// - Market structure analysis
///
/// Formula:
/// VP = Σ Volume at each price level
/// POC = Price level with max volume
/// Value Area = Price range containing 70% of volume
///
/// Market Applications:
/// - Support/resistance levels
/// - Market structure analysis
/// - Trading activity patterns
/// - Price level significance
/// - Volume concentration
///
/// Note: Returns Point of Control (price level with highest volume)
/// </remarks>
[SkipLocalsInit]
public sealed class Vp : AbstractBase
{
private readonly CircularBuffer _volumes;
private readonly CircularBuffer _prices;
private const int DefaultPeriod = 14;
/// <param name="period">The number of periods to analyze volume distribution (default 14).</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when period is less than 1.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vp(int period = DefaultPeriod)
{
if (period < 1)
throw new ArgumentOutOfRangeException(nameof(period));
_volumes = new(period);
_prices = new(period);
WarmupPeriod = period;
Name = $"VP({period})";
}
/// <param name="source">The data source object that publishes updates.</param>
/// <param name="period">The number of periods to analyze volume distribution.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vp(object source, int period = DefaultPeriod) : this(period)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new BarSignal(Sub));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void ManageState(bool isNew)
{
if (isNew)
_index++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static int FindMaxVolumeIndex(CircularBuffer volumes)
{
int maxIndex = 0;
double maxVolume = volumes[0];
for (int i = 1; i < volumes.Count; i++)
{
if (volumes[i] > maxVolume)
{
maxVolume = volumes[i];
maxIndex = i;
}
}
return maxIndex;
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
protected override double Calculation()
{
ManageState(BarInput.IsNew);
// Store volume and price
_volumes.Add(BarInput.Volume, BarInput.IsNew);
_prices.Add(BarInput.Close, BarInput.IsNew);
// Find price level with highest volume (Point of Control)
int pocIndex = FindMaxVolumeIndex(_volumes);
return _prices[pocIndex];
}
}
+93
View File
@@ -0,0 +1,93 @@
using System.Runtime.CompilerServices;
namespace QuanTAlib;
/// <summary>
/// VWAP: Volume Weighted Average Price
/// A trading benchmark that shows the ratio of the value traded to total volume
/// traded over a specific period. VWAP equals the dollar value of all trading
/// periods divided by the total trading volume for the current day.
/// </summary>
/// <remarks>
/// The VWAP calculation process:
/// 1. Calculate typical price for each period
/// 2. Multiply typical price by volume
/// 3. Calculate cumulative values
/// 4. Divide cumulative (price * volume) by cumulative volume
///
/// Key characteristics:
/// - Intraday trading benchmark
/// - Volume-weighted measure
/// - Institutional trading reference
/// - Price momentum indicator
/// - Trading efficiency measure
///
/// Formula:
/// VWAP = Σ(Price * Volume) / ΣVolume
/// where Price = (High + Low + Close)/3
///
/// Market Applications:
/// - Best execution analysis
/// - Trading algorithms
/// - Price momentum
/// - Market impact analysis
/// - Order timing
///
/// Sources:
/// https://www.investopedia.com/terms/v/vwap.asp
///
/// Note: Commonly used by institutional traders
/// </remarks>
[SkipLocalsInit]
public sealed class Vwap : AbstractBase
{
private double _cumulativeTPV; // Cumulative (Typical Price * Volume)
private double _cumulativeVolume;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vwap()
{
WarmupPeriod = 1;
Name = "VWAP";
Init();
}
/// <param name="source">The data source object that publishes updates.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vwap(object source) : this()
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new BarSignal(Sub));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Init()
{
base.Init();
_cumulativeTPV = 0;
_cumulativeVolume = 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void ManageState(bool isNew)
{
if (isNew)
_index++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
protected override double Calculation()
{
ManageState(BarInput.IsNew);
// Update cumulative values only for new bars
if (BarInput.IsNew)
{
_cumulativeTPV += BarInput.HLC3 * BarInput.Volume;
_cumulativeVolume += BarInput.Volume;
}
// Calculate VWAP
return _cumulativeVolume > 0 ? _cumulativeTPV / _cumulativeVolume : BarInput.HLC3;
}
}
+92
View File
@@ -0,0 +1,92 @@
using System.Runtime.CompilerServices;
namespace QuanTAlib;
/// <summary>
/// VWMA: Volume Weighted Moving Average
/// A technical indicator that combines price and volume to show the average price
/// weighted by volume over a period. It gives more weight to prices with higher
/// volume, making it more responsive to high-volume price movements.
/// </summary>
/// <remarks>
/// The VWMA calculation process:
/// 1. Multiply price by volume for each period
/// 2. Sum (price * volume) over the period
/// 3. Sum volume over the period
/// 4. Divide sums to get weighted average
///
/// Key characteristics:
/// - Volume-sensitive average
/// - Trend indicator
/// - Support/resistance levels
/// - Price momentum
/// - Volume emphasis
///
/// Formula:
/// VWMA = Σ(Price * Volume) / ΣVolume
/// where sums are taken over the specified period
///
/// Market Applications:
/// - Trend identification
/// - Support/resistance levels
/// - Volume analysis
/// - Price momentum
/// - Trading signals
///
/// Note: More responsive to high-volume price movements
/// </remarks>
[SkipLocalsInit]
public sealed class Vwma : AbstractBase
{
private readonly CircularBuffer _priceVolume;
private readonly CircularBuffer _volume;
private const int DefaultPeriod = 20;
/// <param name="period">The number of periods for VWMA calculation (default 20).</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when period is less than 1.</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vwma(int period = DefaultPeriod)
{
if (period < 1)
throw new ArgumentOutOfRangeException(nameof(period));
_priceVolume = new(period);
_volume = new(period);
WarmupPeriod = period;
Name = $"VWMA({period})";
}
/// <param name="source">The data source object that publishes updates.</param>
/// <param name="period">The number of periods for VWMA calculation.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vwma(object source, int period = DefaultPeriod) : this(period)
{
var pubEvent = source.GetType().GetEvent("Pub");
pubEvent?.AddEventHandler(source, new BarSignal(Sub));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected override void ManageState(bool isNew)
{
if (isNew)
_index++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
protected override double Calculation()
{
ManageState(BarInput.IsNew);
// Calculate and store price * volume
double priceVolume = BarInput.Close * BarInput.Volume;
_priceVolume.Add(priceVolume, BarInput.IsNew);
_volume.Add(BarInput.Volume, BarInput.IsNew);
// Calculate sums
double sumPriceVolume = _priceVolume.Sum();
double sumVolume = _volume.Sum();
// Calculate VWMA
return sumVolume > 0 ? sumPriceVolume / sumVolume : BarInput.Close;
}
}
+5 -5
View File
@@ -1,5 +1,5 @@
# Volume indicators
Done: 15, Todo: 3
Done: 19, Todo: 0
✔️ ADL - Chaikin Accumulation Distribution Line
✔️ ADOSC - Chaikin Accumulation Distribution Oscillator
@@ -16,7 +16,7 @@ Done: 15, Todo: 3
✔️ PVR - Price Volume Rank
✔️ PVT - Price Volume Trend
✔️ TVI - Trade Volume Index
VF - Volume Force
VP - Volume Profile
VWAP - Volume Weighted Average Price
VWMA - Volume Weighted Moving Average
✔️ VF - Volume Force
✔️ VP - Volume Profile
✔️ VWAP - Volume Weighted Average Price
✔️ VWMA - Volume Weighted Moving Average