Skip to main content

kestrel_chartkit/indicator/
volume_flow_hires.rs

1//! High-resolution volume flow: direct aggressor/delta inputs, intrabar delta from grouped child
2//! bars, absorption detection, and explicitly quality-tagged fallbacks — the capabilities
3//! [`super::volume_flow::CvdEngine`]'s single OHLC-close-location heuristic per bar cannot offer.
4
5use std::collections::HashMap;
6
7use crate::clustering::RollingRobustThreshold;
8use crate::intrabar::IntrabarGroup;
9use crate::model::{Bar, BarQuality};
10
11use super::{Indicator, IndicatorAlert, IndicatorOutput};
12
13/// Directly known aggressor-side (taker buy vs. taker sell) volume for a bar, from real trade/
14/// tick data rather than an OHLC-inferred estimate.
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct AggressorVolume {
17    pub buy_volume: f64,
18    pub sell_volume: f64,
19}
20
21impl AggressorVolume {
22    pub fn delta(&self) -> f64 {
23        self.buy_volume - self.sell_volume
24    }
25}
26
27/// Estimates a bar's aggressor split from its OHLC close-location within its range — the same
28/// heuristic [`super::volume_flow::CvdEngine`] uses, kept here as the explicit, tagged fallback
29/// path when no direct aggressor/tick data is available. Shared with
30/// [`super::volume_profile_extended`] for its delta-profile bins.
31pub(crate) fn estimate_aggressor_from_ohlc(bar: &Bar) -> AggressorVolume {
32    let range = (bar.high - bar.low).max(1e-8);
33    let buy_pct = ((bar.close - bar.low) / range).clamp(0.0, 1.0);
34    AggressorVolume {
35        buy_volume: bar.volume * buy_pct,
36        sell_volume: bar.volume * (1.0 - buy_pct),
37    }
38}
39
40#[derive(Debug, Clone, Copy, PartialEq)]
41pub struct HiResVolumeFlowOutput {
42    pub delta: f64,
43    pub cumulative_delta: f64,
44    pub quality: BarQuality,
45    /// `true` when this bar's volume is an outlier-high spike (per the rolling robust volume
46    /// threshold) while its price range stayed unremarkable — high participation without
47    /// proportional price displacement, the classic order-flow absorption signature.
48    pub absorption: bool,
49}
50
51/// Streaming volume flow: a cumulative buy-minus-sell delta with an absorption flag.
52///
53/// Through [`Indicator::on_bar`] the split is estimated from the bar's shape: the buy share is the
54/// close's position in its range, `(close - low) / (high - low)` clamped to `0..=1`, so
55/// `delta = volume * (2 * share - 1)`. [`HiResVolumeFlowEngine::on_bar_with_aggressor`] takes a
56/// known split instead, and [`HiResVolumeFlowEngine::on_intrabar_group`] sums the children's own
57/// estimates. `value` is the running total of the deltas, `extra["delta"]` this bar's, and
58/// `extra["is_estimated"]` is `1` on the estimated path.
59///
60/// A bar is flagged as absorption (`state = "absorption"`) when its volume exceeds the upper band
61/// of a rolling robust threshold (factor `2.5`) over the last `window_len` volumes while its range
62/// stays at or below the rolling median range.
63///
64/// First output: with the first bar. [`Indicator::reset`] clears the total and both thresholds.
65pub struct HiResVolumeFlowEngine {
66    cumulative_delta: f64,
67    volume_threshold: RollingRobustThreshold,
68    range_threshold: RollingRobustThreshold,
69    alerts: Vec<IndicatorAlert>,
70}
71
72impl HiResVolumeFlowEngine {
73    pub fn new(window_len: usize) -> Self {
74        Self {
75            cumulative_delta: 0.0,
76            volume_threshold: RollingRobustThreshold::new(window_len, 2.5),
77            range_threshold: RollingRobustThreshold::new(window_len, 2.5),
78            alerts: Vec::new(),
79        }
80    }
81
82    pub fn reset(&mut self) {
83        self.cumulative_delta = 0.0;
84        self.volume_threshold.reset();
85        self.range_threshold.reset();
86        self.alerts.clear();
87    }
88
89    fn absorb_step(&mut self, bar: &Bar, delta: f64, quality: BarQuality) -> HiResVolumeFlowOutput {
90        self.alerts.clear();
91        self.cumulative_delta += delta;
92
93        let volume_band = self.volume_threshold.update(bar.volume);
94        let range_band = self.range_threshold.update(bar.high - bar.low);
95
96        let absorption = match (volume_band, range_band) {
97            (Some(vb), Some(rb)) => bar.volume > vb.upper && (bar.high - bar.low) <= rb.median,
98            _ => false,
99        };
100
101        if absorption {
102            self.alerts.push(IndicatorAlert::new(
103                "volume_absorption",
104                "Outlier volume with unremarkable price range: possible absorption",
105                0.7,
106            ));
107        }
108
109        HiResVolumeFlowOutput {
110            delta,
111            cumulative_delta: self.cumulative_delta,
112            quality,
113            absorption,
114        }
115    }
116
117    /// High-resolution path: feeds a bar with directly known aggressor volume (e.g. aggregated
118    /// from trade-tape data).
119    pub fn on_bar_with_aggressor(
120        &mut self,
121        bar: &Bar,
122        aggressor: AggressorVolume,
123    ) -> HiResVolumeFlowOutput {
124        self.absorb_step(bar, aggressor.delta(), BarQuality::observed())
125    }
126
127    /// High-resolution path: feeds a confirmed [`IntrabarGroup`] (a parent bar's full ordered
128    /// child-bar sequence), summing each child's own OHLC-inferred delta instead of applying the
129    /// heuristic once to the aggregate parent bar — preserves the intrabar price path the
130    /// aggregate alone loses.
131    pub fn on_intrabar_group(&mut self, group: &IntrabarGroup) -> HiResVolumeFlowOutput {
132        let mut delta = 0.0;
133        let mut open = f64::NAN;
134        let mut high = f64::NEG_INFINITY;
135        let mut low = f64::INFINITY;
136        let mut close = f64::NAN;
137        let mut volume = 0.0;
138
139        for (i, child) in group.children.iter().enumerate() {
140            let aggressor = estimate_aggressor_from_ohlc(child);
141            delta += aggressor.delta();
142            if i == 0 {
143                open = child.open;
144            }
145            high = high.max(child.high);
146            low = low.min(child.low);
147            close = child.close;
148            volume += child.volume;
149        }
150
151        let parent_bar = Bar::new(group.parent_timestamp, open, high, low, close, volume);
152        let mut quality = BarQuality::observed();
153        quality.is_forward_filled = false;
154        self.absorb_step(&parent_bar, delta, quality)
155    }
156
157    /// Fallback path: OHLC-inferred estimate when no direct aggressor or intrabar data is
158    /// available, explicitly tagged as such via [`BarQuality::volume_available`] staying accurate
159    /// but the estimate not being a genuine tick-level measurement.
160    pub fn on_bar_estimated(&mut self, bar: &Bar) -> HiResVolumeFlowOutput {
161        let aggressor = estimate_aggressor_from_ohlc(bar);
162        let mut quality = BarQuality::observed();
163        quality.is_synthetic = true; // the buy/sell split itself is inferred, not observed
164        self.absorb_step(bar, aggressor.delta(), quality)
165    }
166}
167
168impl Indicator for HiResVolumeFlowEngine {
169    fn name(&self) -> &str {
170        "hires_volume_flow"
171    }
172
173    fn reset(&mut self) {
174        HiResVolumeFlowEngine::reset(self)
175    }
176
177    /// Delegates to the OHLC-estimated fallback path; use
178    /// [`HiResVolumeFlowEngine::on_bar_with_aggressor`] or
179    /// [`HiResVolumeFlowEngine::on_intrabar_group`] directly for the high-resolution paths, which
180    /// this trait's single-`Bar` signature cannot express.
181    fn on_bar(&mut self, bar: &Bar) -> Option<IndicatorOutput> {
182        let out = self.on_bar_estimated(bar);
183        let mut extra = HashMap::new();
184        extra.insert("delta".to_string(), out.delta);
185        extra.insert(
186            "is_estimated".to_string(),
187            if out.quality.is_synthetic { 1.0 } else { 0.0 },
188        );
189        Some(
190            IndicatorOutput::with_extra(out.cumulative_delta, extra).with_state(
191                if out.absorption {
192                    "absorption"
193                } else {
194                    "normal"
195                },
196            ),
197        )
198    }
199
200    fn alerts(&self) -> Vec<IndicatorAlert> {
201        self.alerts.clone()
202    }
203}
204
205#[cfg(test)]
206mod tests {
207    use super::*;
208    use crate::intrabar::IntrabarGrouper;
209    use crate::timeframe::Timeframe;
210
211    #[test]
212    fn test_direct_aggressor_delta_matches_input_exactly() {
213        let mut engine = HiResVolumeFlowEngine::new(5);
214        let bar = Bar::new(0, 100.0, 101.0, 99.0, 100.5, 1000.0);
215        let out = engine.on_bar_with_aggressor(
216            &bar,
217            AggressorVolume {
218                buy_volume: 700.0,
219                sell_volume: 300.0,
220            },
221        );
222        assert_eq!(out.delta, 400.0);
223        assert_eq!(out.quality, BarQuality::observed());
224    }
225
226    #[test]
227    fn test_estimated_fallback_is_tagged_synthetic() {
228        let mut engine = HiResVolumeFlowEngine::new(5);
229        let bar = Bar::new(0, 100.0, 101.0, 99.0, 100.5, 1000.0);
230        let out = engine.on_bar_estimated(&bar);
231        assert!(
232            out.quality.is_synthetic,
233            "estimated delta must be tagged as such"
234        );
235    }
236
237    #[test]
238    fn test_intrabar_group_sums_child_deltas() {
239        let mut grouper = IntrabarGrouper::new(Timeframe::Minute(5)).unwrap();
240        let children = [
241            Bar::new(0, 100.0, 101.0, 100.0, 101.0, 100.0),
242            Bar::new(60, 101.0, 102.0, 100.5, 101.5, 100.0),
243        ];
244        for child in &children {
245            grouper.on_child_bar(child);
246        }
247        // Starts a new parent bucket, completing the first with the two children above.
248        let completed = grouper.on_child_bar(&Bar::new(300, 101.5, 102.0, 101.0, 101.8, 50.0));
249
250        let mut engine = HiResVolumeFlowEngine::new(5);
251        let out = engine.on_intrabar_group(&completed.unwrap());
252
253        let expected: f64 = children
254            .iter()
255            .map(|c| estimate_aggressor_from_ohlc(c).delta())
256            .sum();
257        assert!((out.delta - expected).abs() < 1e-9);
258    }
259
260    #[test]
261    fn test_absorption_flags_outlier_volume_with_tight_range() {
262        let mut engine = HiResVolumeFlowEngine::new(6);
263        // Establish a normal volume/range baseline.
264        for _ in 0..5 {
265            engine.on_bar_estimated(&Bar::new(0, 100.0, 101.0, 99.0, 100.5, 100.0));
266        }
267        // One bar with a volume spike but a tight (unremarkable) range.
268        let out = engine.on_bar_estimated(&Bar::new(60, 100.0, 100.3, 99.8, 100.1, 5000.0));
269        assert!(
270            out.absorption,
271            "large volume with tight range must flag absorption"
272        );
273        assert!(!engine.alerts().is_empty());
274    }
275
276    #[test]
277    fn test_normal_bar_does_not_flag_absorption() {
278        let mut engine = HiResVolumeFlowEngine::new(6);
279        let mut last = HiResVolumeFlowOutput {
280            delta: 0.0,
281            cumulative_delta: 0.0,
282            quality: BarQuality::observed(),
283            absorption: false,
284        };
285        for _ in 0..6 {
286            last = engine.on_bar_estimated(&Bar::new(0, 100.0, 101.0, 99.0, 100.5, 100.0));
287        }
288        assert!(!last.absorption);
289    }
290}