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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
use std::collections::{HashMap, VecDeque};
use crate::indicator::{Indicator, IndicatorAlert, IndicatorOutput};
use crate::model::Bar;
/// Bar volume with its moving average.
///
/// `value` is the bar's own volume. Once `ma_period` volumes have been seen, `extra` adds
/// `avg_volume` — the plain mean of the last `ma_period` volumes, this bar included — and
/// `volume_ratio = volume / avg_volume` (`1` for a zero average); a volume above twice the average
/// raises an alert. Before that, only the volume itself is published.
///
/// First output: with the first bar. [`Indicator::reset`] clears the window.
pub struct VolumeEngine {
ma_period: usize,
volumes: VecDeque<f64>,
alerts: Vec<IndicatorAlert>,
}
impl VolumeEngine {
pub fn new(ma_period: usize) -> Self {
Self {
ma_period,
volumes: VecDeque::new(),
alerts: Vec::new(),
}
}
}
impl Indicator for VolumeEngine {
fn name(&self) -> &str {
"volume"
}
fn warmup_period(&self) -> usize {
self.ma_period
}
fn reset(&mut self) {
self.volumes.clear();
self.alerts.clear();
}
fn on_bar(&mut self, bar: &Bar) -> Option<IndicatorOutput> {
let vol = bar.volume;
self.volumes.push_back(vol);
if self.volumes.len() > self.ma_period {
self.volumes.pop_front();
}
self.alerts.clear();
if self.volumes.len() < self.ma_period {
return Some(IndicatorOutput::new(vol));
}
let avg_vol: f64 = self.volumes.iter().sum::<f64>() / self.ma_period as f64;
let mut extra = HashMap::new();
extra.insert("avg_volume".to_string(), avg_vol);
extra.insert(
"volume_ratio".to_string(),
if avg_vol > 0.0 { vol / avg_vol } else { 1.0 },
);
if avg_vol > 0.0 && vol > 2.0 * avg_vol {
self.alerts.push(IndicatorAlert::new(
"high_volume_spike",
format!("High Volume Spike: {:.0} (>2.0x avg {:.0})", vol, avg_vol),
0.80,
));
}
Some(IndicatorOutput::with_extra(vol, extra))
}
fn alerts(&self) -> Vec<IndicatorAlert> {
self.alerts.clone()
}
}
/// Relative Volume (RVOL): this bar's volume against the recent average.
///
/// `RVOL = volume / avg`, where `avg` is the plain mean of the last `period` volumes **including
/// this bar's own**, and `1` for a zero average. Including the current bar damps the ratio: a
/// spike raises its own reference. For the comparison against the same time of day on earlier
/// days see [`super::rvat::RelativeVolumeAtTime`].
///
/// First output: with the `period`-th bar. [`Indicator::reset`] clears the window.
#[derive(Debug, Clone)]
pub struct RvolEngine {
period: usize,
volumes: VecDeque<f64>,
alerts: Vec<IndicatorAlert>,
}
impl RvolEngine {
pub fn new(period: usize) -> Self {
Self {
period,
volumes: VecDeque::new(),
alerts: Vec::new(),
}
}
}
impl Indicator for RvolEngine {
fn name(&self) -> &str {
"rvol"
}
fn warmup_period(&self) -> usize {
self.period
}
fn reset(&mut self) {
self.volumes.clear();
self.alerts.clear();
}
fn on_bar(&mut self, bar: &Bar) -> Option<IndicatorOutput> {
let vol = bar.volume;
self.volumes.push_back(vol);
if self.volumes.len() > self.period {
self.volumes.pop_front();
}
self.alerts.clear();
if self.volumes.len() < self.period {
return None;
}
let avg_vol: f64 = self.volumes.iter().sum::<f64>() / self.period as f64;
let rvol = if avg_vol > 0.0 { vol / avg_vol } else { 1.0 };
if rvol >= 2.5 {
self.alerts.push(IndicatorAlert::new(
"extreme_rvol",
format!("Extreme Relative Volume: {:.2}x", rvol),
0.90,
));
}
Some(IndicatorOutput::new(rvol))
}
fn alerts(&self) -> Vec<IndicatorAlert> {
self.alerts.clone()
}
}
/// On-Balance Volume (OBV): a running total of volume signed by the direction of the close.
///
/// Starting at `0`, each bar adds its volume when the close rose against the previous close,
/// subtracts it when the close fell, and leaves the total unchanged when the close is equal. The
/// first bar has no previous close and contributes nothing.
///
/// First output: with the first bar. [`Indicator::reset`] returns the total to zero.
pub struct ObvEngine {
prev_close: Option<f64>,
cum_obv: f64,
alerts: Vec<IndicatorAlert>,
}
impl ObvEngine {
pub fn new() -> Self {
Self {
prev_close: None,
cum_obv: 0.0,
alerts: Vec::new(),
}
}
}
impl Default for ObvEngine {
fn default() -> Self {
Self::new()
}
}
impl Indicator for ObvEngine {
fn name(&self) -> &str {
"obv"
}
fn warmup_period(&self) -> usize {
1
}
fn reset(&mut self) {
self.prev_close = None;
self.cum_obv = 0.0;
self.alerts.clear();
}
fn on_bar(&mut self, bar: &Bar) -> Option<IndicatorOutput> {
if let Some(prev) = self.prev_close {
if bar.close > prev {
self.cum_obv += bar.volume;
} else if bar.close < prev {
self.cum_obv -= bar.volume;
}
}
self.prev_close = Some(bar.close);
Some(IndicatorOutput::new(self.cum_obv))
}
fn alerts(&self) -> Vec<IndicatorAlert> {
self.alerts.clone()
}
}
/// Chaikin Money Flow (CMF) over `period` bars.
///
/// Each bar's money-flow multiplier places the close in its range,
/// `MFM = ((close - low) - (high - close)) / (high - low)` (`0` for a range below `1e-8`), and its
/// money-flow volume is `MFM * volume`. CMF is the sum of the last `period` money-flow volumes over
/// the sum of their volumes (`0` without volume), clamped to `-1..=1`.
///
/// First output: with the `period`-th bar. [`Indicator::reset`] clears both windows.
pub struct CmfEngine {
period: usize,
mf_volumes: VecDeque<f64>,
volumes: VecDeque<f64>,
alerts: Vec<IndicatorAlert>,
}
impl CmfEngine {
pub fn new(period: usize) -> Self {
Self {
period,
mf_volumes: VecDeque::new(),
volumes: VecDeque::new(),
alerts: Vec::new(),
}
}
}
impl Indicator for CmfEngine {
fn name(&self) -> &str {
"cmf"
}
fn warmup_period(&self) -> usize {
self.period
}
fn reset(&mut self) {
self.mf_volumes.clear();
self.volumes.clear();
self.alerts.clear();
}
fn on_bar(&mut self, bar: &Bar) -> Option<IndicatorOutput> {
let high_low = bar.high - bar.low;
let mfm = if high_low > 1e-8 {
((bar.close - bar.low) - (bar.high - bar.close)) / high_low
} else {
0.0
};
let mfv = mfm * bar.volume;
self.mf_volumes.push_back(mfv);
self.volumes.push_back(bar.volume);
if self.mf_volumes.len() > self.period {
self.mf_volumes.pop_front();
self.volumes.pop_front();
}
self.alerts.clear();
if self.mf_volumes.len() < self.period {
return None;
}
let sum_mfv: f64 = self.mf_volumes.iter().sum();
let sum_vol: f64 = self.volumes.iter().sum();
let cmf = if sum_vol > 0.0 {
sum_mfv / sum_vol
} else {
0.0
};
if cmf > 0.20 {
self.alerts.push(IndicatorAlert::new(
"cmf_bullish",
format!("Strong Buying Pressure (CMF: {:.2})", cmf),
0.80,
));
} else if cmf < -0.20 {
self.alerts.push(IndicatorAlert::new(
"cmf_bearish",
format!("Strong Selling Pressure (CMF: {:.2})", cmf),
0.80,
));
}
Some(IndicatorOutput::new(cmf.clamp(-1.0, 1.0)))
}
fn alerts(&self) -> Vec<IndicatorAlert> {
self.alerts.clone()
}
}
/// Accumulation/Distribution Line (A/D): a running total of money-flow volume.
///
/// Each bar adds `MFM * volume` with the money-flow multiplier of [`CmfEngine`],
/// `((close - low) - (high - close)) / (high - low)` (`0` for a range below `1e-8`). A close in
/// the middle of its range therefore adds nothing, however large the volume.
///
/// First output: with the first bar. [`Indicator::reset`] returns the total to zero.
#[derive(Debug, Clone)]
pub struct AccDistEngine {
cum_ad: f64,
alerts: Vec<IndicatorAlert>,
}
impl AccDistEngine {
pub fn new() -> Self {
Self {
cum_ad: 0.0,
alerts: Vec::new(),
}
}
}
impl Default for AccDistEngine {
fn default() -> Self {
Self::new()
}
}
impl Indicator for AccDistEngine {
fn name(&self) -> &str {
"acc_dist"
}
fn warmup_period(&self) -> usize {
1
}
fn reset(&mut self) {
self.cum_ad = 0.0;
self.alerts.clear();
}
fn on_bar(&mut self, bar: &Bar) -> Option<IndicatorOutput> {
let high_low = bar.high - bar.low;
let mfm = if high_low > 1e-8 {
((bar.close - bar.low) - (bar.high - bar.close)) / high_low
} else {
0.0
};
let mfv = mfm * bar.volume;
self.cum_ad += mfv;
Some(IndicatorOutput::new(self.cum_ad))
}
fn alerts(&self) -> Vec<IndicatorAlert> {
self.alerts.clone()
}
}