1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
//! Anchored Volume-Weighted Average Price.
use crate::ohlcv::Candle;
use crate::traits::Indicator;
/// Anchored VWAP — a cumulative VWAP whose accumulation begins at a
/// user-chosen anchor bar rather than the session open.
///
/// ```text
/// AVWAP_t = Σ_{i ≥ anchor} (typical_price_i · volume_i) / Σ_{i ≥ anchor} volume_i
/// ```
///
/// The indicator emits `None` until the first anchored bar has been ingested.
/// Calling [`AnchoredVwap::set_anchor`] re-anchors at the **next** bar that
/// arrives, clearing the running sums; this is the conventional behaviour for
/// "click to anchor" trader workflows where the anchor is set on the close of
/// a swing point and the next bar starts the new accumulation. The cumulative
/// total is unbounded; for finite-memory needs use [`crate::RollingVwap`].
///
/// Bars where the running volume is still zero (only happens if every anchored
/// bar so far carried zero volume) return `None` to avoid a zero-division.
///
/// # Example
///
/// ```
/// use wickra_core::{AnchoredVwap, Candle, Indicator};
///
/// let mut indicator = AnchoredVwap::new();
/// let mut last = None;
/// for i in 0..80 {
/// let base = 100.0 + f64::from(i);
/// let candle =
/// Candle::new(base, base + 2.0, base - 2.0, base + 1.0, 10.0, i64::from(i)).unwrap();
/// // Re-anchor at bar 40 (e.g. a major swing low).
/// if i == 40 {
/// indicator.set_anchor();
/// }
/// last = indicator.update(candle);
/// }
/// assert!(last.is_some());
/// ```
#[derive(Debug, Clone, Default)]
pub struct AnchoredVwap {
sum_pv: f64,
sum_v: f64,
has_emitted: bool,
pending_anchor: bool,
}
impl AnchoredVwap {
/// Construct a fresh Anchored VWAP. The first bar to arrive is the anchor.
pub const fn new() -> Self {
Self {
sum_pv: 0.0,
sum_v: 0.0,
has_emitted: false,
pending_anchor: false,
}
}
/// Mark a re-anchor: the **next** [`Indicator::update`] call clears the
/// running sums before adding its own contribution, effectively starting a
/// fresh anchored window.
pub fn set_anchor(&mut self) {
self.pending_anchor = true;
}
/// Current anchored value if at least one bar with non-zero volume has
/// been observed in the current anchor window.
pub fn value(&self) -> Option<f64> {
if self.sum_v == 0.0 {
None
} else {
Some(self.sum_pv / self.sum_v)
}
}
}
impl Indicator for AnchoredVwap {
type Input = Candle;
type Output = f64;
fn update(&mut self, candle: Candle) -> Option<f64> {
if self.pending_anchor {
// Drop the old window before folding in this bar.
self.sum_pv = 0.0;
self.sum_v = 0.0;
self.has_emitted = false;
self.pending_anchor = false;
}
let tp = candle.typical_price();
self.sum_pv += tp * candle.volume;
self.sum_v += candle.volume;
if self.sum_v == 0.0 {
return None;
}
self.has_emitted = true;
Some(self.sum_pv / self.sum_v)
}
fn reset(&mut self) {
self.sum_pv = 0.0;
self.sum_v = 0.0;
self.has_emitted = false;
self.pending_anchor = false;
}
fn warmup_period(&self) -> usize {
1
}
fn is_ready(&self) -> bool {
self.has_emitted
}
fn name(&self) -> &'static str {
"AnchoredVWAP"
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::traits::BatchExt;
use approx::assert_relative_eq;
fn c(price: f64, volume: f64, ts: i64) -> Candle {
Candle::new(price, price, price, price, volume, ts).unwrap()
}
#[test]
fn accessors_and_metadata() {
let v = AnchoredVwap::new();
assert_eq!(v.name(), "AnchoredVWAP");
assert_eq!(v.warmup_period(), 1);
assert_eq!(v.value(), None);
}
#[test]
fn first_bar_with_zero_volume_returns_none() {
let mut v = AnchoredVwap::new();
assert_eq!(v.update(c(50.0, 0.0, 0)), None);
assert!(!v.is_ready());
// The next bar with volume still works.
assert_relative_eq!(v.update(c(10.0, 4.0, 1)).unwrap(), 10.0, epsilon = 1e-12);
}
#[test]
fn equal_volumes_yield_mean_typical_price() {
// typical_price of a flat OHLC bar equals the price.
let mut v = AnchoredVwap::new();
let out = v.batch(&[c(10.0, 1.0, 0), c(20.0, 1.0, 1), c(30.0, 1.0, 2)]);
assert_relative_eq!(out[2].unwrap(), 20.0, epsilon = 1e-12);
}
#[test]
fn set_anchor_clears_old_window() {
// Run a few bars at price 10, then re-anchor and pump in price 100.
// After the re-anchor the running mean must be 100, not the mix.
let mut v = AnchoredVwap::new();
v.batch(&[c(10.0, 1.0, 0), c(10.0, 1.0, 1), c(10.0, 1.0, 2)]);
assert_relative_eq!(v.value().unwrap(), 10.0, epsilon = 1e-12);
v.set_anchor();
let after = v.update(c(100.0, 5.0, 3)).unwrap();
assert_relative_eq!(after, 100.0, epsilon = 1e-12);
}
#[test]
fn set_anchor_before_first_bar_acts_as_normal_first_bar() {
// Calling set_anchor on an empty indicator should be a no-op effect:
// the first bar still anchors the window.
let mut v = AnchoredVwap::new();
v.set_anchor();
assert_relative_eq!(v.update(c(42.0, 2.0, 0)).unwrap(), 42.0, epsilon = 1e-12);
}
#[test]
fn weighted_average_reference() {
// Two bars: 10@1, 20@3 -> (10 + 60) / 4 = 17.5.
let mut v = AnchoredVwap::new();
let out = v.batch(&[c(10.0, 1.0, 0), c(20.0, 3.0, 1)]);
assert_relative_eq!(out[1].unwrap(), 17.5, epsilon = 1e-12);
}
#[test]
fn batch_equals_streaming() {
let candles: Vec<Candle> = (1..30).map(|i| c(f64::from(i), 1.0, i.into())).collect();
let mut a = AnchoredVwap::new();
let mut b = AnchoredVwap::new();
assert_eq!(
a.batch(&candles),
candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
);
}
#[test]
fn reset_clears_state() {
let mut v = AnchoredVwap::new();
v.batch(&[c(10.0, 1.0, 0), c(20.0, 1.0, 1)]);
assert!(v.is_ready());
v.reset();
assert!(!v.is_ready());
assert_eq!(v.value(), None);
// After reset the first bar acts as the new anchor.
assert_relative_eq!(v.update(c(50.0, 1.0, 2)).unwrap(), 50.0, epsilon = 1e-12);
}
}