Skip to main content

nautilus_data/
aggregation.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Bar aggregation machinery.
17//!
18//! Defines the `BarAggregator` trait and core aggregation types (tick, volume, value, time),
19//! along with the `BarBuilder` and `BarAggregatorCore` components for constructing bars.
20
21use std::{
22    any::Any,
23    cell::{Cell, RefCell},
24    fmt::Debug,
25    ops::Add,
26    rc::{Rc, Weak},
27};
28
29use ahash::AHashMap;
30use jiff::{SignedDuration, civil::Date, tz::TimeZone};
31use nautilus_common::{
32    clock::{Clock, VirtualClock},
33    timer::{TimeEvent, TimeEventCallback},
34};
35use nautilus_core::{
36    DurationNanos, UnixNanos,
37    correctness::{self, FAILED},
38};
39use nautilus_model::{
40    data::{
41        QuoteTick, TradeTick,
42        bar::{Bar, BarType, get_bar_interval_ns, get_time_bar_bounds},
43    },
44    enums::{
45        AggregationSource, AggressorSide, BarAggregation, BarIntervalType,
46        ContinuousFutureAdjustmentType,
47    },
48    identifiers::InstrumentId,
49    instruments::{FixedTickScheme, TickSchemeRule},
50    types::{
51        Price, Quantity,
52        fixed::{FIXED_PRECISION, FIXED_SCALAR, mantissa_exponent_to_fixed_i128},
53        price::PriceRaw,
54        quantity::QuantityRaw,
55    },
56};
57use rust_decimal::{Decimal, prelude::ToPrimitive};
58
59/// Type alias for bar handler to reduce type complexity.
60type BarHandler = Box<dyn FnMut(Bar)>;
61
62/// Trait for aggregating incoming price and trade events into time-, tick-, volume-, or value-based bars.
63///
64/// Implementors receive updates and produce completed bars via handlers.
65pub trait BarAggregator: Any + Debug {
66    /// The [`BarType`] to be aggregated.
67    fn bar_type(&self) -> BarType;
68    /// If the aggregator is running and will receive data from the message bus.
69    fn is_running(&self) -> bool;
70    /// Sets the running state of the aggregator (receiving updates when `true`).
71    fn set_is_running(&mut self, value: bool);
72    /// Updates the aggregator  with the given price and size.
73    fn update(&mut self, price: Price, size: Quantity, ts_init: UnixNanos);
74    /// Updates the aggregator with the given quote.
75    fn handle_quote(&mut self, quote: QuoteTick) {
76        let spec = self.bar_type().spec();
77        // Quote-fed aggregators use Bid/Ask/Mid (Last uses trades), so this cannot fail; guard
78        // rather than unwrap to stay panic-free
79        let (Ok(price), Ok(size)) = (
80            quote.extract_price(spec.price_type),
81            quote.extract_size(spec.price_type),
82        ) else {
83            log::error!(
84                "Cannot aggregate quote for {}: price type {} unsupported for quotes",
85                self.bar_type(),
86                spec.price_type,
87            );
88            return;
89        };
90
91        self.update(price, size, quote.ts_init);
92    }
93    /// Updates the aggregator with the given trade.
94    fn handle_trade(&mut self, trade: TradeTick) {
95        self.update(trade.price, trade.size, trade.ts_init);
96    }
97    /// Updates the aggregator with the given bar.
98    fn handle_bar(&mut self, bar: Bar) {
99        self.update_bar(bar, bar.volume, bar.ts_init);
100    }
101    fn update_bar(&mut self, bar: Bar, volume: Quantity, ts_init: UnixNanos);
102    /// Stop the aggregator, e.g., cancel timers. Default is no-op.
103    fn stop(&mut self) {}
104    /// Sets historical mode and the handler used for completed bars.
105    fn set_historical_mode(&mut self, _historical_mode: bool, _handler: Box<dyn FnMut(Bar)>) {}
106    /// Sets historical events (default implementation does nothing, `TimeBarAggregator` overrides)
107    fn set_historical_events(&mut self, _events: Vec<TimeEvent>) {}
108    /// Sets clock for time bar aggregators (default implementation does nothing, `TimeBarAggregator` overrides)
109    fn set_clock(&mut self, _clock: Rc<RefCell<dyn Clock>>) {}
110    /// Builds a bar from a time event (default implementation does nothing, `TimeBarAggregator` overrides)
111    fn build_bar(&mut self, _event: &TimeEvent) {}
112    /// Starts the timer for time bar aggregators.
113    /// Default implementation does nothing, `TimeBarAggregator` overrides.
114    /// Takes an optional Rc to create weak reference internally.
115    fn start_timer(&mut self, _aggregator_rc: Option<Rc<RefCell<Box<dyn BarAggregator>>>>) {}
116
117    /// Sets the weak reference to the aggregator wrapper (for historical mode).
118    /// Default implementation does nothing, `TimeBarAggregator` overrides.
119    fn set_aggregator_weak(&mut self, _weak: BarAggregatorWeak) {}
120
121    /// Configures the continuous-future price adjustment for the underlying builder.
122    fn set_adjustment(&mut self, _adjustment: Decimal, _mode: ContinuousFutureAdjustmentType) {}
123    /// Sets whether empty intervals emit bars at the last close.
124    /// Default implementation does nothing, `TimeBarAggregator` overrides.
125    fn set_build_with_no_updates(&mut self, _value: bool) {}
126    /// If the aggregator is processing historical data on a private clock.
127    /// Default implementation returns `false`, `TimeBarAggregator` overrides.
128    fn is_historical(&self) -> bool {
129        false
130    }
131}
132
133impl dyn BarAggregator {
134    /// Returns a reference to this aggregator as `Any` for downcasting.
135    pub fn as_any(&self) -> &dyn Any {
136        self
137    }
138    /// Returns a mutable reference to this aggregator as `Any` for downcasting.
139    pub fn as_any_mut(&mut self) -> &mut dyn Any {
140        self
141    }
142}
143
144type BarAggregatorWeak = Weak<RefCell<Box<dyn BarAggregator>>>;
145
146/// Provides a generic bar builder for aggregation.
147#[derive(Debug)]
148pub struct BarBuilder {
149    bar_type: BarType,
150    price_precision: u8,
151    size_precision: u8,
152    initialized: bool,
153    ts_last: UnixNanos,
154    count: usize,
155    last_close: Option<Price>,
156    open: Option<Price>,
157    high: Option<Price>,
158    low: Option<Price>,
159    close: Option<Price>,
160    volume: Quantity,
161    adjustment_spread: Price,
162    adjustment_ratio: f64,
163    adjustment_active: bool,
164    adjustment_is_ratio: bool,
165}
166
167impl BarBuilder {
168    /// Creates a new [`BarBuilder`] instance.
169    ///
170    /// # Panics
171    ///
172    /// Panics if `bar_type.aggregation_source` is not `AggregationSource::Internal`.
173    #[must_use]
174    pub fn new(bar_type: BarType, price_precision: u8, size_precision: u8) -> Self {
175        correctness::check_equal(
176            &bar_type.aggregation_source(),
177            &AggregationSource::Internal,
178            "bar_type.aggregation_source",
179            "AggregationSource::Internal",
180        )
181        .expect(FAILED);
182
183        Self {
184            bar_type,
185            price_precision,
186            size_precision,
187            initialized: false,
188            ts_last: UnixNanos::default(),
189            count: 0,
190            last_close: None,
191            open: None,
192            high: None,
193            low: None,
194            close: None,
195            volume: Quantity::zero(size_precision),
196            adjustment_spread: Price::zero(0),
197            adjustment_ratio: 1.0,
198            adjustment_active: false,
199            adjustment_is_ratio: false,
200        }
201    }
202
203    /// Configures the per-tick continuous-future price adjustment.
204    ///
205    /// Adjustment applies on ingress in [`Self::update`] and [`Self::update_bar`], so the running
206    /// OHLC state is always in the adjusted (common) frame. The adjustment configuration is
207    /// retained across [`Self::reset`] so it spans subsequent bars within the same continuous-
208    /// future segment.
209    ///
210    /// # Panics
211    ///
212    /// Panics if scaling the spread `adjustment` to the fixed-point representation overflows.
213    pub fn set_adjustment(&mut self, adjustment: Decimal, mode: ContinuousFutureAdjustmentType) {
214        if mode.is_ratio() {
215            self.adjustment_is_ratio = true;
216            self.adjustment_ratio = adjustment.to_f64().unwrap_or(1.0);
217            self.adjustment_active = adjustment != Decimal::ONE;
218            return;
219        }
220
221        // Retain sub-display-precision offsets when adding the spread to each price.
222        self.adjustment_is_ratio = false;
223        let exponent = -(adjustment.scale() as i8);
224        let raw_i128 =
225            mantissa_exponent_to_fixed_i128(adjustment.mantissa(), exponent, FIXED_PRECISION)
226                .expect("Failed to scale continuous-future adjustment to fixed precision");
227
228        #[allow(
229            clippy::useless_conversion,
230            reason = "i128 to PriceRaw is real when not high-precision"
231        )]
232        let raw: PriceRaw = raw_i128
233            .try_into()
234            .expect("Continuous-future adjustment exceeds PriceRaw range");
235
236        self.adjustment_spread = Price::from_raw(raw, FIXED_PRECISION);
237        self.adjustment_active = !self.adjustment_spread.is_zero();
238    }
239
240    fn apply_adjustment_to_price(&self, price: Price) -> Price {
241        if !self.adjustment_active {
242            return price;
243        }
244
245        if self.adjustment_is_ratio {
246            // Multiply in double; `Price::new` rounds to the target precision.
247            // Float can shift 1 ULP for high-precision raws (spread mode is exact).
248            return Price::new(price.as_f64() * self.adjustment_ratio, price.precision);
249        }
250
251        let mut spread = self.adjustment_spread;
252        spread.precision = price.precision;
253        let mut adjusted = price
254            .checked_add(spread)
255            .expect("Continuous-future adjustment exceeds Price bounds");
256        adjusted.precision = price.precision;
257        adjusted
258    }
259
260    /// Updates the builder state with the given price, size, and init timestamp.
261    ///
262    /// # Panics
263    ///
264    /// Panics if `high` or `low` values are unexpectedly `None` when updating.
265    pub fn update(&mut self, price: Price, size: Quantity, ts_init: UnixNanos) {
266        if ts_init < self.ts_last {
267            return; // Not applicable
268        }
269
270        let price = self.apply_adjustment_to_price(price);
271
272        if self.open.is_none() {
273            self.open = Some(price);
274            self.high = Some(price);
275            self.low = Some(price);
276            self.initialized = true;
277        } else {
278            if price > self.high.unwrap() {
279                self.high = Some(price);
280            }
281
282            if price < self.low.unwrap() {
283                self.low = Some(price);
284            }
285        }
286
287        self.close = Some(price);
288        self.volume = self.volume.add(size);
289        self.count += 1;
290        self.ts_last = ts_init;
291
292        debug_assert!(self.high >= self.low, "OHLC invariant violated: high < low");
293    }
294
295    /// Updates the builder state with a completed bar, its volume, and the bar init timestamp.
296    ///
297    /// # Panics
298    ///
299    /// Panics if `high` or `low` values are unexpectedly `None` when updating.
300    pub fn update_bar(&mut self, bar: Bar, volume: Quantity, ts_init: UnixNanos) {
301        if ts_init < self.ts_last {
302            return; // Not applicable
303        }
304
305        let bar_open = self.apply_adjustment_to_price(bar.open);
306        let bar_high = self.apply_adjustment_to_price(bar.high);
307        let bar_low = self.apply_adjustment_to_price(bar.low);
308        let bar_close = self.apply_adjustment_to_price(bar.close);
309
310        if self.open.is_none() {
311            self.open = Some(bar_open);
312            self.high = Some(bar_high);
313            self.low = Some(bar_low);
314            self.initialized = true;
315        } else {
316            if bar_high > self.high.unwrap() {
317                self.high = Some(bar_high);
318            }
319
320            if bar_low < self.low.unwrap() {
321                self.low = Some(bar_low);
322            }
323        }
324
325        self.close = Some(bar_close);
326        self.volume = self.volume.add(volume);
327        self.count += 1;
328        self.ts_last = ts_init;
329
330        debug_assert!(self.high >= self.low, "OHLC invariant violated: high < low");
331    }
332
333    /// Resets per-bar OHLCV state.
334    ///
335    /// Adjustment configuration set via [`Self::set_adjustment`] is retained across resets so it
336    /// spans subsequent bars within the same continuous-future segment.
337    pub fn reset(&mut self) {
338        self.open = None;
339        self.high = None;
340        self.low = None;
341        self.close = None;
342        self.volume = Quantity::zero(self.size_precision);
343        self.count = 0;
344    }
345
346    /// Return the aggregated bar and reset.
347    pub fn build_now(&mut self) -> Bar {
348        self.build(self.ts_last, self.ts_last)
349    }
350
351    /// Returns the aggregated bar for the given timestamps, then resets the builder.
352    ///
353    /// # Panics
354    ///
355    /// Panics if `open`, `high`, `low`, or `close` values are `None` when building the bar.
356    pub fn build(&mut self, ts_event: UnixNanos, ts_init: UnixNanos) -> Bar {
357        if self.open.is_none() {
358            self.open = self.last_close;
359            self.high = self.last_close;
360            self.low = self.last_close;
361            self.close = self.last_close;
362        }
363
364        if let (Some(close), Some(low)) = (self.close, self.low)
365            && close < low
366        {
367            self.low = Some(close);
368        }
369
370        if let (Some(close), Some(high)) = (self.close, self.high)
371            && close > high
372        {
373            self.high = Some(close);
374        }
375
376        // The open was checked, so we can assume all prices are Some
377        let bar = Bar::new(
378            self.bar_type,
379            self.open.unwrap(),
380            self.high.unwrap(),
381            self.low.unwrap(),
382            self.close.unwrap(),
383            self.volume,
384            ts_event,
385            ts_init,
386        );
387
388        self.last_close = self.close;
389        self.reset();
390        bar
391    }
392}
393
394/// Provides a means of aggregating specified bar types and sending to a registered handler.
395pub struct BarAggregatorCore {
396    builder: BarBuilder,
397    handler: BarHandler,
398    is_running: bool,
399}
400
401impl Debug for BarAggregatorCore {
402    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
403        f.debug_struct(stringify!(BarAggregatorCore))
404            .field("bar_type", &self.builder.bar_type)
405            .field("builder", &self.builder)
406            .field("is_running", &self.is_running)
407            .finish()
408    }
409}
410
411impl BarAggregatorCore {
412    /// Creates a new [`BarAggregatorCore`] instance.
413    ///
414    /// The `bar_type` is standardized so aggregators always emit bars carrying the
415    /// standard form: the composite suffix is a local aggregation detail and must not
416    /// leak into emitted bars, publish topics, or cache keys.
417    ///
418    /// # Panics
419    ///
420    /// Panics if `bar_type.aggregation_source` is not `AggregationSource::Internal`.
421    pub fn new<H: FnMut(Bar) + 'static>(
422        bar_type: BarType,
423        price_precision: u8,
424        size_precision: u8,
425        handler: H,
426    ) -> Self {
427        let bar_type = bar_type.standard();
428        Self {
429            builder: BarBuilder::new(bar_type, price_precision, size_precision),
430            handler: Box::new(handler),
431            is_running: false,
432        }
433    }
434
435    /// Sets the running state of the aggregator (receives updates when `true`).
436    pub const fn set_is_running(&mut self, value: bool) {
437        self.is_running = value;
438    }
439
440    fn set_handler(&mut self, handler: BarHandler) {
441        self.handler = handler;
442    }
443
444    fn is_stale(&self, ts_init: UnixNanos) -> bool {
445        ts_init < self.builder.ts_last
446    }
447
448    fn build_now_and_send(&mut self) {
449        let bar = self.builder.build_now();
450        (self.handler)(bar);
451    }
452
453    fn build_and_send(&mut self, ts_event: UnixNanos, ts_init: UnixNanos) {
454        let bar = self.builder.build(ts_event, ts_init);
455        (self.handler)(bar);
456    }
457
458    fn set_adjustment(&mut self, adjustment: Decimal, mode: ContinuousFutureAdjustmentType) {
459        self.builder.set_adjustment(adjustment, mode);
460    }
461}
462
463macro_rules! impl_core_bar_aggregator {
464    () => {
465        fn bar_type(&self) -> BarType {
466            self.core.builder.bar_type
467        }
468
469        fn is_running(&self) -> bool {
470            self.core.is_running
471        }
472
473        fn set_is_running(&mut self, value: bool) {
474            self.core.set_is_running(value);
475        }
476
477        fn set_historical_mode(&mut self, _historical_mode: bool, handler: Box<dyn FnMut(Bar)>) {
478            self.core.set_handler(handler);
479        }
480
481        fn set_adjustment(&mut self, adjustment: Decimal, mode: ContinuousFutureAdjustmentType) {
482            self.core.set_adjustment(adjustment, mode);
483        }
484    };
485}
486
487/// Provides a means of building tick bars aggregated from quote and trades.
488///
489/// When received tick count reaches the step threshold of the bar
490/// specification, then a bar is created and sent to the handler.
491#[derive(Debug)]
492pub struct TickBarAggregator {
493    core: BarAggregatorCore,
494}
495
496impl TickBarAggregator {
497    /// Creates a new [`TickBarAggregator`] instance.
498    ///
499    /// # Panics
500    ///
501    /// Panics if `bar_type.aggregation_source` is not `AggregationSource::Internal`.
502    pub fn new<H: FnMut(Bar) + 'static>(
503        bar_type: BarType,
504        price_precision: u8,
505        size_precision: u8,
506        handler: H,
507    ) -> Self {
508        Self {
509            core: BarAggregatorCore::new(bar_type, price_precision, size_precision, handler),
510        }
511    }
512}
513
514impl BarAggregator for TickBarAggregator {
515    impl_core_bar_aggregator!();
516
517    /// Apply the given update to the aggregator.
518    fn update(&mut self, price: Price, size: Quantity, ts_init: UnixNanos) {
519        self.core.builder.update(price, size, ts_init);
520        let spec = self.core.builder.bar_type.spec();
521
522        if self.core.builder.count >= spec.step.get() {
523            self.core.build_now_and_send();
524        }
525    }
526
527    fn update_bar(&mut self, bar: Bar, volume: Quantity, ts_init: UnixNanos) {
528        self.core.builder.update_bar(bar, volume, ts_init);
529        let spec = self.core.builder.bar_type.spec();
530
531        if self.core.builder.count >= spec.step.get() {
532            self.core.build_now_and_send();
533        }
534    }
535}
536
537/// Aggregates bars based on tick buy/sell imbalance.
538///
539/// Increments imbalance by +1 for buyer-aggressed trades and -1 for seller-aggressed trades.
540/// Emits a bar when the absolute imbalance reaches the step threshold.
541#[derive(Debug)]
542pub struct TickImbalanceBarAggregator {
543    core: BarAggregatorCore,
544    imbalance: isize,
545}
546
547impl TickImbalanceBarAggregator {
548    /// Creates a new [`TickImbalanceBarAggregator`] instance.
549    ///
550    /// # Panics
551    ///
552    /// Panics if `bar_type.aggregation_source` is not `AggregationSource::Internal`.
553    pub fn new<H: FnMut(Bar) + 'static>(
554        bar_type: BarType,
555        price_precision: u8,
556        size_precision: u8,
557        handler: H,
558    ) -> Self {
559        Self {
560            core: BarAggregatorCore::new(bar_type, price_precision, size_precision, handler),
561            imbalance: 0,
562        }
563    }
564}
565
566impl BarAggregator for TickImbalanceBarAggregator {
567    impl_core_bar_aggregator!();
568
569    /// Apply the given update to the aggregator.
570    ///
571    /// Note: side-aware logic lives in `handle_trade`. This method is used for
572    /// quote/bar updates where no aggressor side is available.
573    fn update(&mut self, price: Price, size: Quantity, ts_init: UnixNanos) {
574        self.core.builder.update(price, size, ts_init);
575    }
576
577    fn handle_trade(&mut self, trade: TradeTick) {
578        if self.core.is_stale(trade.ts_init) {
579            return;
580        }
581
582        self.core
583            .builder
584            .update(trade.price, trade.size, trade.ts_init);
585
586        let delta = match trade.aggressor_side {
587            AggressorSide::Buy => 1,
588            AggressorSide::Sell => -1,
589            AggressorSide::NoAggressor => return,
590        };
591
592        self.imbalance += delta;
593        let threshold = self.core.builder.bar_type.spec().step.get();
594        if self.imbalance.unsigned_abs() >= threshold {
595            self.core.build_now_and_send();
596            self.imbalance = 0;
597        }
598    }
599
600    fn update_bar(&mut self, bar: Bar, volume: Quantity, ts_init: UnixNanos) {
601        self.core.builder.update_bar(bar, volume, ts_init);
602    }
603}
604
605/// Aggregates bars based on consecutive buy/sell tick runs.
606#[derive(Debug)]
607pub struct TickRunsBarAggregator {
608    core: BarAggregatorCore,
609    current_run_side: Option<AggressorSide>,
610    run_count: usize,
611}
612
613impl TickRunsBarAggregator {
614    /// Creates a new [`TickRunsBarAggregator`] instance.
615    ///
616    /// # Panics
617    ///
618    /// Panics if `bar_type.aggregation_source` is not `AggregationSource::Internal`.
619    pub fn new<H: FnMut(Bar) + 'static>(
620        bar_type: BarType,
621        price_precision: u8,
622        size_precision: u8,
623        handler: H,
624    ) -> Self {
625        Self {
626            core: BarAggregatorCore::new(bar_type, price_precision, size_precision, handler),
627            current_run_side: None,
628            run_count: 0,
629        }
630    }
631}
632
633impl BarAggregator for TickRunsBarAggregator {
634    impl_core_bar_aggregator!();
635
636    /// Apply the given update to the aggregator.
637    ///
638    /// Note: side-aware logic lives in `handle_trade`. This method is used for
639    /// quote/bar updates where no aggressor side is available.
640    fn update(&mut self, price: Price, size: Quantity, ts_init: UnixNanos) {
641        self.core.builder.update(price, size, ts_init);
642    }
643
644    fn handle_trade(&mut self, trade: TradeTick) {
645        if self.core.is_stale(trade.ts_init) {
646            return;
647        }
648
649        let side = match trade.aggressor_side {
650            AggressorSide::Buy => AggressorSide::Buy,
651            AggressorSide::Sell => AggressorSide::Sell,
652            AggressorSide::NoAggressor => {
653                self.core
654                    .builder
655                    .update(trade.price, trade.size, trade.ts_init);
656                return;
657            }
658        };
659
660        if self.current_run_side != Some(side) {
661            self.current_run_side = Some(side);
662            self.run_count = 0;
663            self.core.builder.reset();
664        }
665
666        self.core
667            .builder
668            .update(trade.price, trade.size, trade.ts_init);
669        self.run_count += 1;
670
671        let threshold = self.core.builder.bar_type.spec().step.get();
672        if self.run_count >= threshold {
673            self.core.build_now_and_send();
674            self.run_count = 0;
675            self.current_run_side = None;
676        }
677    }
678
679    fn update_bar(&mut self, bar: Bar, volume: Quantity, ts_init: UnixNanos) {
680        self.core.builder.update_bar(bar, volume, ts_init);
681    }
682}
683
684/// Provides a means of building volume bars aggregated from quote and trades.
685#[derive(Debug)]
686pub struct VolumeBarAggregator {
687    core: BarAggregatorCore,
688    step: Quantity,
689}
690
691impl VolumeBarAggregator {
692    /// Creates a new [`VolumeBarAggregator`] instance.
693    ///
694    /// # Panics
695    ///
696    /// Panics if `bar_type.aggregation_source` is not `AggregationSource::Internal`.
697    pub fn new<H: FnMut(Bar) + 'static>(
698        bar_type: BarType,
699        price_precision: u8,
700        size_precision: u8,
701        handler: H,
702    ) -> Self {
703        Self {
704            core: BarAggregatorCore::new(bar_type, price_precision, size_precision, handler),
705            step: step_as_quantity(bar_type.spec().step.get(), size_precision),
706        }
707    }
708}
709
710impl BarAggregator for VolumeBarAggregator {
711    impl_core_bar_aggregator!();
712
713    /// Apply the given update to the aggregator.
714    fn update(&mut self, price: Price, size: Quantity, ts_init: UnixNanos) {
715        if self.core.is_stale(ts_init) {
716            return;
717        }
718
719        let mut size_update = size;
720        let step = self.step;
721
722        while size_update.non_zero() {
723            debug_assert!(
724                self.core.builder.volume < step,
725                "builder volume must stay below the step threshold between emissions"
726            );
727
728            let mut size_diff = step - self.core.builder.volume;
729            size_diff.precision = size.precision;
730
731            if size_update < size_diff {
732                self.core.builder.update(price, size_update, ts_init);
733                break;
734            }
735
736            self.core.builder.update(price, size_diff, ts_init);
737
738            self.core.build_now_and_send();
739            size_update = size_update - size_diff;
740        }
741    }
742
743    fn update_bar(&mut self, bar: Bar, volume: Quantity, ts_init: UnixNanos) {
744        if self.core.is_stale(ts_init) {
745            return;
746        }
747
748        let mut volume_update = volume;
749        let step = self.step;
750
751        while volume_update.non_zero() {
752            debug_assert!(
753                self.core.builder.volume < step,
754                "builder volume must stay below the step threshold between emissions"
755            );
756
757            let mut volume_diff = step - self.core.builder.volume;
758            volume_diff.precision = volume.precision;
759
760            if volume_update < volume_diff {
761                self.core.builder.update_bar(bar, volume_update, ts_init);
762                break;
763            }
764
765            self.core.builder.update_bar(bar, volume_diff, ts_init);
766
767            self.core.build_now_and_send();
768            volume_update = volume_update - volume_diff;
769        }
770    }
771}
772
773/// Aggregates bars based on buy/sell volume imbalance.
774#[derive(Debug)]
775pub struct VolumeImbalanceBarAggregator {
776    core: BarAggregatorCore,
777    imbalance: Quantity,
778    imbalance_side: AggressorSide,
779    step: Quantity,
780}
781
782impl VolumeImbalanceBarAggregator {
783    /// Creates a new [`VolumeImbalanceBarAggregator`] instance.
784    ///
785    /// # Panics
786    ///
787    /// Panics if `bar_type.aggregation_source` is not `AggregationSource::Internal`.
788    pub fn new<H: FnMut(Bar) + 'static>(
789        bar_type: BarType,
790        price_precision: u8,
791        size_precision: u8,
792        handler: H,
793    ) -> Self {
794        let step = step_as_quantity(bar_type.spec().step.get(), size_precision);
795
796        Self {
797            core: BarAggregatorCore::new(bar_type, price_precision, size_precision, handler),
798            imbalance: Quantity::zero(size_precision),
799            imbalance_side: AggressorSide::NoAggressor,
800            step,
801        }
802    }
803}
804
805impl BarAggregator for VolumeImbalanceBarAggregator {
806    impl_core_bar_aggregator!();
807
808    /// Apply the given update to the aggregator.
809    ///
810    /// Note: side-aware logic lives in `handle_trade`. This method is used for
811    /// quote/bar updates where no aggressor side is available.
812    fn update(&mut self, price: Price, size: Quantity, ts_init: UnixNanos) {
813        self.core.builder.update(price, size, ts_init);
814    }
815
816    fn handle_trade(&mut self, trade: TradeTick) {
817        if self.core.is_stale(trade.ts_init) {
818            return;
819        }
820
821        let side = match trade.aggressor_side {
822            AggressorSide::Buy => AggressorSide::Buy,
823            AggressorSide::Sell => AggressorSide::Sell,
824            AggressorSide::NoAggressor => {
825                self.core
826                    .builder
827                    .update(trade.price, trade.size, trade.ts_init);
828                return;
829            }
830        };
831
832        let mut remaining = trade.size;
833        while remaining.non_zero() {
834            let mut needed = self.step - self.imbalance;
835            needed.precision = trade.size.precision;
836            let qty_chunk = remaining.min(needed);
837
838            self.core
839                .builder
840                .update(trade.price, qty_chunk, trade.ts_init);
841
842            if self.imbalance_side == side {
843                self.imbalance = self.imbalance + qty_chunk;
844            } else if qty_chunk >= self.imbalance {
845                self.imbalance = qty_chunk - self.imbalance;
846                self.imbalance_side = side;
847            } else {
848                self.imbalance = self.imbalance - qty_chunk;
849            }
850
851            remaining = remaining - qty_chunk;
852
853            if self.imbalance >= self.step {
854                self.core.build_now_and_send();
855                self.imbalance = Quantity::zero(trade.size.precision);
856                self.imbalance_side = AggressorSide::NoAggressor;
857            }
858        }
859    }
860
861    fn update_bar(&mut self, bar: Bar, volume: Quantity, ts_init: UnixNanos) {
862        self.core.builder.update_bar(bar, volume, ts_init);
863    }
864}
865
866/// Aggregates bars based on consecutive buy/sell volume runs.
867#[derive(Debug)]
868pub struct VolumeRunsBarAggregator {
869    core: BarAggregatorCore,
870    current_run_side: Option<AggressorSide>,
871    run_volume: Quantity,
872    step: Quantity,
873}
874
875impl VolumeRunsBarAggregator {
876    /// Creates a new [`VolumeRunsBarAggregator`] instance.
877    ///
878    /// # Panics
879    ///
880    /// Panics if `bar_type.aggregation_source` is not `AggregationSource::Internal`.
881    pub fn new<H: FnMut(Bar) + 'static>(
882        bar_type: BarType,
883        price_precision: u8,
884        size_precision: u8,
885        handler: H,
886    ) -> Self {
887        let step = step_as_quantity(bar_type.spec().step.get(), size_precision);
888
889        Self {
890            core: BarAggregatorCore::new(bar_type, price_precision, size_precision, handler),
891            current_run_side: None,
892            run_volume: Quantity::zero(size_precision),
893            step,
894        }
895    }
896}
897
898impl BarAggregator for VolumeRunsBarAggregator {
899    impl_core_bar_aggregator!();
900
901    /// Apply the given update to the aggregator.
902    ///
903    /// Note: side-aware logic lives in `handle_trade`. This method is used for
904    /// quote/bar updates where no aggressor side is available.
905    fn update(&mut self, price: Price, size: Quantity, ts_init: UnixNanos) {
906        self.core.builder.update(price, size, ts_init);
907    }
908
909    fn handle_trade(&mut self, trade: TradeTick) {
910        if self.core.is_stale(trade.ts_init) {
911            return;
912        }
913
914        let side = match trade.aggressor_side {
915            AggressorSide::Buy => AggressorSide::Buy,
916            AggressorSide::Sell => AggressorSide::Sell,
917            AggressorSide::NoAggressor => {
918                self.core
919                    .builder
920                    .update(trade.price, trade.size, trade.ts_init);
921                return;
922            }
923        };
924
925        if self.current_run_side != Some(side) {
926            self.current_run_side = Some(side);
927            self.run_volume = Quantity::zero(trade.size.precision);
928            self.core.builder.reset();
929        }
930
931        let mut remaining = trade.size;
932        while remaining.non_zero() {
933            let mut needed = self.step - self.run_volume;
934            needed.precision = trade.size.precision;
935            let chunk = remaining.min(needed);
936
937            self.core.builder.update(trade.price, chunk, trade.ts_init);
938
939            self.run_volume = self.run_volume + chunk;
940            remaining = remaining - chunk;
941
942            if self.run_volume >= self.step {
943                self.core.build_now_and_send();
944                self.run_volume = Quantity::zero(trade.size.precision);
945                self.current_run_side = None;
946            }
947        }
948
949        // Leftover volume past the last emitted bar starts a new run on the same
950        // side; without this the next same-side trade reads as a side change and
951        // resets the builder, silently dropping the pending volume.
952        if self.run_volume.non_zero() {
953            self.current_run_side = Some(side);
954        }
955    }
956
957    fn update_bar(&mut self, bar: Bar, volume: Quantity, ts_init: UnixNanos) {
958        self.core.builder.update_bar(bar, volume, ts_init);
959    }
960}
961
962/// Provides a means of building value bars aggregated from quote and trades.
963///
964/// When received value reaches the step threshold of the bar
965/// specification, then a bar is created and sent to the handler.
966#[derive(Debug)]
967pub struct ValueBarAggregator {
968    core: BarAggregatorCore,
969    cum_value: Decimal,
970}
971
972impl ValueBarAggregator {
973    /// Creates a new [`ValueBarAggregator`] instance.
974    ///
975    /// # Panics
976    ///
977    /// Panics if `bar_type.aggregation_source` is not `AggregationSource::Internal`.
978    pub fn new<H: FnMut(Bar) + 'static>(
979        bar_type: BarType,
980        price_precision: u8,
981        size_precision: u8,
982        handler: H,
983    ) -> Self {
984        Self {
985            core: BarAggregatorCore::new(bar_type, price_precision, size_precision, handler),
986            cum_value: Decimal::ZERO,
987        }
988    }
989
990    #[must_use]
991    /// Returns the cumulative value for the aggregator.
992    pub const fn get_cumulative_value(&self) -> Decimal {
993        self.cum_value
994    }
995}
996
997impl BarAggregator for ValueBarAggregator {
998    impl_core_bar_aggregator!();
999
1000    /// Apply the given update to the aggregator.
1001    fn update(&mut self, price: Price, size: Quantity, ts_init: UnixNanos) {
1002        if self.core.is_stale(ts_init) {
1003            return;
1004        }
1005
1006        let step_value = Decimal::from(self.core.builder.bar_type.spec().step.get());
1007        let price_value = price.as_decimal();
1008        let mut size_update = size.as_decimal();
1009
1010        while size_update > Decimal::ZERO {
1011            // cum_value < step_value holds between emissions, so a zero value_update
1012            // (zero price) always falls into the accumulate branch below and the
1013            // division cannot see a zero divisor.
1014            debug_assert!(self.cum_value < step_value);
1015            let value_update = price_value * size_update;
1016
1017            if self.cum_value + value_update < step_value {
1018                self.cum_value += value_update;
1019                self.core.builder.update(
1020                    price,
1021                    quantity_from_decimal(size_update, size.precision),
1022                    ts_init,
1023                );
1024                break;
1025            }
1026
1027            let value_diff = step_value - self.cum_value;
1028            let mut size_diff = size_update * (value_diff / value_update);
1029
1030            // Clamp to minimum representable size to avoid zero-volume bars
1031            if is_below_min_size_decimal(size_diff, size.precision) {
1032                if is_below_min_size_decimal(size_update, size.precision) {
1033                    break;
1034                }
1035                size_diff = min_size_decimal(size.precision);
1036            }
1037
1038            // Subtract the representable quantity actually applied, not the ideal
1039            // fraction, so rounding does not leak volume from the accounting
1040            let applied = quantity_from_decimal(size_diff, size.precision);
1041            self.core.builder.update(price, applied, ts_init);
1042
1043            self.core.build_now_and_send();
1044            self.cum_value = Decimal::ZERO;
1045            size_update -= applied.as_decimal();
1046        }
1047    }
1048
1049    fn update_bar(&mut self, bar: Bar, volume: Quantity, ts_init: UnixNanos) {
1050        if self.core.is_stale(ts_init) {
1051            return;
1052        }
1053
1054        let step_value = Decimal::from(self.core.builder.bar_type.spec().step.get());
1055        let average_price =
1056            ((bar.high.as_decimal() + bar.low.as_decimal() + bar.close.as_decimal())
1057                / Decimal::from(3))
1058            .round_dp(u32::from(self.core.builder.price_precision));
1059        let mut volume_update = volume.as_decimal();
1060
1061        while volume_update > Decimal::ZERO {
1062            // See `update` for why a zero divisor cannot occur here.
1063            debug_assert!(self.cum_value < step_value);
1064            let value_update = average_price * volume_update;
1065
1066            if self.cum_value + value_update < step_value {
1067                self.cum_value += value_update;
1068                self.core.builder.update_bar(
1069                    bar,
1070                    quantity_from_decimal(volume_update, volume.precision),
1071                    ts_init,
1072                );
1073                break;
1074            }
1075
1076            let value_diff = step_value - self.cum_value;
1077            let mut volume_diff = volume_update * (value_diff / value_update);
1078
1079            // Clamp to minimum representable size to avoid zero-volume bars
1080            if is_below_min_size_decimal(volume_diff, volume.precision) {
1081                if is_below_min_size_decimal(volume_update, volume.precision) {
1082                    break;
1083                }
1084                volume_diff = min_size_decimal(volume.precision);
1085            }
1086
1087            // Subtract the representable quantity actually applied, not the ideal
1088            // fraction, so rounding does not leak volume from the accounting
1089            let applied = quantity_from_decimal(volume_diff, volume.precision);
1090            self.core.builder.update_bar(bar, applied, ts_init);
1091
1092            self.core.build_now_and_send();
1093            self.cum_value = Decimal::ZERO;
1094            volume_update -= applied.as_decimal();
1095        }
1096    }
1097}
1098
1099/// Aggregates bars based on buy/sell notional imbalance.
1100#[derive(Debug)]
1101pub struct ValueImbalanceBarAggregator {
1102    core: BarAggregatorCore,
1103    imbalance_value: Decimal,
1104    step_value: Decimal,
1105}
1106
1107impl ValueImbalanceBarAggregator {
1108    /// Creates a new [`ValueImbalanceBarAggregator`] instance.
1109    ///
1110    /// # Panics
1111    ///
1112    /// Panics if `bar_type.aggregation_source` is not `AggregationSource::Internal`.
1113    pub fn new<H: FnMut(Bar) + 'static>(
1114        bar_type: BarType,
1115        price_precision: u8,
1116        size_precision: u8,
1117        handler: H,
1118    ) -> Self {
1119        Self {
1120            core: BarAggregatorCore::new(bar_type, price_precision, size_precision, handler),
1121            imbalance_value: Decimal::ZERO,
1122            step_value: Decimal::from(bar_type.spec().step.get()),
1123        }
1124    }
1125}
1126
1127impl BarAggregator for ValueImbalanceBarAggregator {
1128    impl_core_bar_aggregator!();
1129
1130    /// Apply the given update to the aggregator.
1131    ///
1132    /// Note: side-aware logic lives in `handle_trade`. This method is used for
1133    /// quote/bar updates where no aggressor side is available.
1134    fn update(&mut self, price: Price, size: Quantity, ts_init: UnixNanos) {
1135        self.core.builder.update(price, size, ts_init);
1136    }
1137
1138    fn handle_trade(&mut self, trade: TradeTick) {
1139        if self.core.is_stale(trade.ts_init) {
1140            return;
1141        }
1142
1143        let price_value = trade.price.as_decimal();
1144        if price_value.is_zero() {
1145            self.core
1146                .builder
1147                .update(trade.price, trade.size, trade.ts_init);
1148            return;
1149        }
1150
1151        let (side_sign, side_is_buy) = match trade.aggressor_side {
1152            AggressorSide::Buy => (Decimal::ONE, true),
1153            AggressorSide::Sell => (Decimal::NEGATIVE_ONE, false),
1154            AggressorSide::NoAggressor => {
1155                self.core
1156                    .builder
1157                    .update(trade.price, trade.size, trade.ts_init);
1158                return;
1159            }
1160        };
1161
1162        let precision = trade.size.precision;
1163        let mut size_remaining = trade.size.as_decimal();
1164        while size_remaining > Decimal::ZERO {
1165            let value_remaining = price_value * size_remaining;
1166
1167            let value_chunk = if self.imbalance_value.is_zero()
1168                || self.imbalance_value.is_sign_positive() == side_is_buy
1169            {
1170                let needed = self.step_value - self.imbalance_value.abs();
1171                if value_remaining <= needed {
1172                    self.imbalance_value += side_sign * value_remaining;
1173                    self.core.builder.update(
1174                        trade.price,
1175                        quantity_from_decimal(size_remaining, precision),
1176                        trade.ts_init,
1177                    );
1178
1179                    self.build_if_complete();
1180                    break;
1181                }
1182
1183                needed
1184            } else {
1185                self.imbalance_value.abs().min(value_remaining)
1186            };
1187
1188            let Some(size_applied) =
1189                self.apply_chunk(trade, value_chunk, size_remaining, side_sign)
1190            else {
1191                break;
1192            };
1193
1194            size_remaining -= size_applied;
1195        }
1196    }
1197
1198    fn update_bar(&mut self, bar: Bar, volume: Quantity, ts_init: UnixNanos) {
1199        self.core.builder.update_bar(bar, volume, ts_init);
1200    }
1201}
1202
1203impl ValueImbalanceBarAggregator {
1204    fn apply_chunk(
1205        &mut self,
1206        trade: TradeTick,
1207        mut value_chunk: Decimal,
1208        size_remaining: Decimal,
1209        side_sign: Decimal,
1210    ) -> Option<Decimal> {
1211        let precision = trade.size.precision;
1212        let price_value = trade.price.as_decimal();
1213        let mut size_chunk = value_chunk / price_value;
1214
1215        if is_below_min_size_decimal(size_chunk, precision) {
1216            if is_below_min_size_decimal(size_remaining, precision) {
1217                return None;
1218            }
1219
1220            size_chunk = min_size_decimal(precision);
1221            value_chunk = price_value * size_chunk;
1222        }
1223
1224        // Account for ideal notional unless clamped, but conserve the representable volume
1225        let applied = quantity_from_decimal(size_chunk, precision);
1226        self.core
1227            .builder
1228            .update(trade.price, applied, trade.ts_init);
1229        self.imbalance_value += side_sign * value_chunk;
1230
1231        self.build_if_complete();
1232
1233        Some(applied.as_decimal())
1234    }
1235
1236    fn build_if_complete(&mut self) {
1237        if self.imbalance_value.abs() >= self.step_value {
1238            self.core.build_now_and_send();
1239            self.imbalance_value = Decimal::ZERO;
1240        }
1241    }
1242}
1243
1244/// Aggregates bars based on consecutive buy/sell notional runs.
1245#[derive(Debug)]
1246pub struct ValueRunsBarAggregator {
1247    core: BarAggregatorCore,
1248    current_run_side: Option<AggressorSide>,
1249    run_value: Decimal,
1250    step_value: Decimal,
1251}
1252
1253impl ValueRunsBarAggregator {
1254    /// Creates a new [`ValueRunsBarAggregator`] instance.
1255    ///
1256    /// # Panics
1257    ///
1258    /// Panics if `bar_type.aggregation_source` is not `AggregationSource::Internal`.
1259    pub fn new<H: FnMut(Bar) + 'static>(
1260        bar_type: BarType,
1261        price_precision: u8,
1262        size_precision: u8,
1263        handler: H,
1264    ) -> Self {
1265        Self {
1266            core: BarAggregatorCore::new(bar_type, price_precision, size_precision, handler),
1267            current_run_side: None,
1268            run_value: Decimal::ZERO,
1269            step_value: Decimal::from(bar_type.spec().step.get()),
1270        }
1271    }
1272}
1273
1274impl BarAggregator for ValueRunsBarAggregator {
1275    impl_core_bar_aggregator!();
1276
1277    /// Apply the given update to the aggregator.
1278    ///
1279    /// Note: side-aware logic lives in `handle_trade`. This method is used for
1280    /// quote/bar updates where no aggressor side is available.
1281    fn update(&mut self, price: Price, size: Quantity, ts_init: UnixNanos) {
1282        self.core.builder.update(price, size, ts_init);
1283    }
1284
1285    fn handle_trade(&mut self, trade: TradeTick) {
1286        if self.core.is_stale(trade.ts_init) {
1287            return;
1288        }
1289
1290        let price_value = trade.price.as_decimal();
1291        if price_value.is_zero() {
1292            self.core
1293                .builder
1294                .update(trade.price, trade.size, trade.ts_init);
1295            return;
1296        }
1297
1298        let side = match trade.aggressor_side {
1299            AggressorSide::Buy => AggressorSide::Buy,
1300            AggressorSide::Sell => AggressorSide::Sell,
1301            AggressorSide::NoAggressor => {
1302                self.core
1303                    .builder
1304                    .update(trade.price, trade.size, trade.ts_init);
1305                return;
1306            }
1307        };
1308
1309        if self.current_run_side != Some(side) {
1310            self.current_run_side = Some(side);
1311            self.run_value = Decimal::ZERO;
1312            self.core.builder.reset();
1313        }
1314
1315        let precision = trade.size.precision;
1316        let mut size_remaining = trade.size.as_decimal();
1317        while size_remaining > Decimal::ZERO {
1318            let value_update = price_value * size_remaining;
1319            if self.run_value + value_update < self.step_value {
1320                self.run_value += value_update;
1321                self.core.builder.update(
1322                    trade.price,
1323                    quantity_from_decimal(size_remaining, precision),
1324                    trade.ts_init,
1325                );
1326                break;
1327            }
1328
1329            let value_needed = self.step_value - self.run_value;
1330            let mut size_chunk = value_needed / price_value;
1331
1332            // Clamp to minimum representable size to avoid zero-volume bars
1333            if is_below_min_size_decimal(size_chunk, precision) {
1334                if is_below_min_size_decimal(size_remaining, precision) {
1335                    break;
1336                }
1337                size_chunk = min_size_decimal(precision);
1338            }
1339
1340            // Subtract the representable quantity actually applied, not the ideal
1341            // fraction, so rounding does not leak volume from the accounting
1342            let applied = quantity_from_decimal(size_chunk, precision);
1343            self.core
1344                .builder
1345                .update(trade.price, applied, trade.ts_init);
1346
1347            self.core.build_now_and_send();
1348            self.run_value = Decimal::ZERO;
1349            self.current_run_side = None;
1350            size_remaining -= applied.as_decimal();
1351        }
1352
1353        // Leftover value past the last emitted bar starts a new run on the same
1354        // side; without this the next same-side trade reads as a side change and
1355        // resets the builder, silently dropping the pending volume.
1356        if self.run_value > Decimal::ZERO {
1357            self.current_run_side = Some(side);
1358        }
1359    }
1360
1361    fn update_bar(&mut self, bar: Bar, volume: Quantity, ts_init: UnixNanos) {
1362        self.core.builder.update_bar(bar, volume, ts_init);
1363    }
1364}
1365
1366/// Provides a means of building Renko bars aggregated from quote and trades.
1367///
1368/// Renko bars are created when the price moves by a fixed amount (brick size)
1369/// regardless of time or volume. Each bar represents a price movement equal
1370/// to the step size in the bar specification.
1371#[derive(Debug)]
1372pub struct RenkoBarAggregator {
1373    core: BarAggregatorCore,
1374    pub brick_size: Price,
1375    last_close: Option<Price>,
1376}
1377
1378impl RenkoBarAggregator {
1379    /// Creates a new [`RenkoBarAggregator`] instance.
1380    ///
1381    /// # Panics
1382    ///
1383    /// Panics if `bar_type.aggregation_source` is not `AggregationSource::Internal`.
1384    pub fn new<H: FnMut(Bar) + 'static>(
1385        bar_type: BarType,
1386        price_precision: u8,
1387        size_precision: u8,
1388        price_increment: Price,
1389        handler: H,
1390    ) -> Self {
1391        let brick_size = Price::from_raw(
1392            price_increment.raw() * bar_type.spec().step.get() as PriceRaw,
1393            price_increment.precision,
1394        );
1395
1396        Self {
1397            core: BarAggregatorCore::new(bar_type, price_precision, size_precision, handler),
1398            brick_size,
1399            last_close: None,
1400        }
1401    }
1402}
1403
1404impl BarAggregator for RenkoBarAggregator {
1405    impl_core_bar_aggregator!();
1406
1407    /// Apply the given update to the aggregator.
1408    ///
1409    /// For Renko bars, we check if the price movement from the last close
1410    /// is greater than or equal to the brick size. If so, we create new bars.
1411    fn update(&mut self, price: Price, size: Quantity, ts_init: UnixNanos) {
1412        if self.core.is_stale(ts_init) {
1413            return;
1414        }
1415
1416        // Always update the builder with the current tick
1417        self.core.builder.update(price, size, ts_init);
1418        let price = self.core.builder.apply_adjustment_to_price(price);
1419        self.build_bricks(price, ts_init);
1420    }
1421
1422    fn update_bar(&mut self, bar: Bar, volume: Quantity, ts_init: UnixNanos) {
1423        if self.core.is_stale(ts_init) {
1424            return;
1425        }
1426
1427        // Always update the builder with the current bar
1428        self.core.builder.update_bar(bar, volume, ts_init);
1429        let close = self.core.builder.apply_adjustment_to_price(bar.close);
1430        self.build_bricks(close, ts_init);
1431    }
1432}
1433
1434impl RenkoBarAggregator {
1435    fn build_bricks(&mut self, price: Price, ts_init: UnixNanos) {
1436        let Some(last_close) = self.last_close else {
1437            self.last_close = Some(price);
1438            return;
1439        };
1440
1441        let rising = price > last_close;
1442
1443        let mut remaining_move = if rising {
1444            price - last_close
1445        } else {
1446            last_close - price
1447        };
1448
1449        if remaining_move < self.brick_size {
1450            return;
1451        }
1452
1453        assert!(
1454            self.brick_size.is_positive(),
1455            "Renko brick size must be positive"
1456        );
1457        let mut current_close = last_close;
1458        let total_volume = self.core.builder.volume;
1459
1460        while remaining_move >= self.brick_size {
1461            let mut brick_close = if rising {
1462                current_close + self.brick_size
1463            } else {
1464                current_close - self.brick_size
1465            };
1466
1467            brick_close.precision = price.precision;
1468
1469            let (brick_high, brick_low) = if rising {
1470                (brick_close, current_close)
1471            } else {
1472                (current_close, brick_close)
1473            };
1474
1475            self.core.builder.reset();
1476            self.core.builder.open = Some(current_close);
1477            self.core.builder.high = Some(brick_high);
1478            self.core.builder.low = Some(brick_low);
1479            self.core.builder.close = Some(brick_close);
1480            self.core.builder.volume = total_volume;
1481            self.core.builder.count = 1;
1482            self.core.builder.ts_last = ts_init;
1483            self.core.builder.initialized = true;
1484            self.core.build_and_send(ts_init, ts_init);
1485
1486            current_close = brick_close;
1487            self.last_close = Some(brick_close);
1488            remaining_move = remaining_move - self.brick_size;
1489        }
1490    }
1491}
1492
1493/// Provides a means of building time bars aggregated from quote and trades.
1494///
1495/// At each aggregation time interval, a bar is created and sent to the handler.
1496pub struct TimeBarAggregator {
1497    core: BarAggregatorCore,
1498    clock: Rc<RefCell<dyn Clock>>,
1499    build_with_no_updates: bool,
1500    timestamp_on_close: bool,
1501    is_left_open: bool,
1502    stored_open_ns: UnixNanos,
1503    timer_name: String,
1504    timer_active: Rc<Cell<bool>>,
1505    timer_source: Option<BarAggregatorWeak>,
1506    interval_ns: DurationNanos,
1507    next_close_ns: UnixNanos,
1508    first_close_ns: UnixNanos,
1509    bar_build_delay: u64,
1510    time_bars_origin_offset: Option<SignedDuration>,
1511    calendar_origin: Option<Date>,
1512    time_zone: TimeZone,
1513    skip_first_non_full_bar: bool,
1514    pub historical_mode: bool,
1515    historical_events: Vec<TimeEvent>,
1516    historical_event_at_ts_init: Option<TimeEvent>,
1517    aggregator_weak: Option<BarAggregatorWeak>,
1518}
1519
1520impl Debug for TimeBarAggregator {
1521    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1522        f.debug_struct(stringify!(TimeBarAggregator))
1523            .field("core", &self.core)
1524            .field("build_with_no_updates", &self.build_with_no_updates)
1525            .field("timestamp_on_close", &self.timestamp_on_close)
1526            .field("is_left_open", &self.is_left_open)
1527            .field("timer_name", &self.timer_name)
1528            .field("timer_active", &self.timer_active.get())
1529            .field("interval_ns", &self.interval_ns)
1530            .field("bar_build_delay", &self.bar_build_delay)
1531            .field("skip_first_non_full_bar", &self.skip_first_non_full_bar)
1532            .finish()
1533    }
1534}
1535
1536impl TimeBarAggregator {
1537    /// Creates a new [`TimeBarAggregator`] instance.
1538    ///
1539    /// `time_zone` aligns day, week, month, and year boundaries to local civil time. Shorter
1540    /// periods keep UTC alignment. `time_bars_origin_offset` shifts the nominal boundary;
1541    /// `bar_build_delay` adds an elapsed delay in microseconds after each resolved boundary.
1542    ///
1543    /// # Panics
1544    ///
1545    /// Panics if `bar_type.aggregation_source` is not `AggregationSource::Internal`.
1546    #[expect(clippy::too_many_arguments)]
1547    pub fn new<H: FnMut(Bar) + 'static>(
1548        bar_type: BarType,
1549        price_precision: u8,
1550        size_precision: u8,
1551        clock: Rc<RefCell<dyn Clock>>,
1552        handler: H,
1553        build_with_no_updates: bool,
1554        timestamp_on_close: bool,
1555        interval_type: BarIntervalType,
1556        time_bars_origin_offset: Option<SignedDuration>,
1557        time_zone: TimeZone,
1558        bar_build_delay: u64,
1559        skip_first_non_full_bar: bool,
1560    ) -> Self {
1561        let is_left_open = match interval_type {
1562            BarIntervalType::LeftOpen => true,
1563            BarIntervalType::RightOpen => false,
1564        };
1565
1566        let core = BarAggregatorCore::new(bar_type, price_precision, size_precision, handler);
1567
1568        Self {
1569            clock,
1570            build_with_no_updates,
1571            timestamp_on_close,
1572            is_left_open,
1573            stored_open_ns: UnixNanos::default(),
1574            timer_name: format!("TIME_BAR_{}", core.builder.bar_type),
1575            timer_active: Rc::new(Cell::new(false)),
1576            timer_source: None,
1577            interval_ns: get_bar_interval_ns(&bar_type),
1578            core,
1579            next_close_ns: UnixNanos::default(),
1580            first_close_ns: UnixNanos::default(),
1581            bar_build_delay,
1582            time_bars_origin_offset,
1583            calendar_origin: None,
1584            time_zone,
1585            skip_first_non_full_bar,
1586            historical_mode: false,
1587            historical_events: Vec::new(),
1588            historical_event_at_ts_init: None,
1589            aggregator_weak: None,
1590        }
1591    }
1592
1593    /// Returns the calendar time zone used to align bar boundaries.
1594    #[must_use]
1595    pub(crate) fn time_zone(&self) -> &TimeZone {
1596        &self.time_zone
1597    }
1598
1599    /// Sets the clock for the aggregator (internal method).
1600    pub fn set_clock_internal(&mut self, clock: Rc<RefCell<dyn Clock>>) {
1601        self.clock = clock;
1602    }
1603
1604    /// Starts the time bar aggregator, scheduling periodic bar builds on the clock.
1605    ///
1606    /// Creates a callback to `build_bar` using a weak reference to the aggregator.
1607    ///
1608    /// # Panics
1609    ///
1610    /// Panics if `aggregator_rc` is None and `aggregator_weak` hasn't been set, or if timer registration fails.
1611    pub fn start_timer_internal(
1612        &mut self,
1613        aggregator_rc: Option<Rc<RefCell<Box<dyn BarAggregator>>>>,
1614    ) {
1615        let callback = self.create_timer_callback(aggregator_rc);
1616
1617        let now = self.clock.borrow().utc_now();
1618        self.calendar_origin = Some(self.time_zone.to_datetime(now).date());
1619        let (previous, open, close) = get_time_bar_bounds(
1620            now,
1621            &self.bar_type(),
1622            self.time_bars_origin_offset,
1623            &self.time_zone,
1624            self.calendar_origin,
1625        );
1626        let delay = SignedDuration::from_micros(self.bar_build_delay as i64);
1627        let start_time = open + delay;
1628        let fire_immediately = start_time == now;
1629        let start_time_ns = UnixNanos::from(start_time);
1630        let first_close_ns = if fire_immediately {
1631            start_time_ns
1632        } else {
1633            UnixNanos::from(close + delay)
1634        };
1635
1636        if self.uses_calendar_timer() {
1637            self.clock
1638                .borrow_mut()
1639                .set_time_alert_ns(&self.timer_name, first_close_ns, Some(callback), Some(true))
1640                .expect(FAILED);
1641
1642            self.stored_open_ns = if fire_immediately {
1643                UnixNanos::from(previous + delay)
1644            } else {
1645                start_time_ns
1646            };
1647        } else {
1648            self.clock
1649                .borrow_mut()
1650                .set_timer_ns(
1651                    &self.timer_name,
1652                    self.interval_ns,
1653                    Some(start_time_ns),
1654                    None,
1655                    Some(callback),
1656                    Some(true),
1657                    Some(fire_immediately),
1658                )
1659                .expect(FAILED);
1660
1661            self.stored_open_ns = first_close_ns.saturating_sub(self.interval_ns);
1662        }
1663
1664        if self.skip_first_non_full_bar {
1665            self.first_close_ns = first_close_ns;
1666        }
1667
1668        self.next_close_ns = self
1669            .clock
1670            .borrow()
1671            .next_time_ns(&self.timer_name)
1672            .unwrap_or(first_close_ns);
1673
1674        log::debug!(
1675            "Started timer {}, start_time={:?}, historical_mode={}, fire_immediately={}, now={:?}, bar_build_delay={}",
1676            self.timer_name,
1677            start_time,
1678            self.historical_mode,
1679            fire_immediately,
1680            now,
1681            self.bar_build_delay
1682        );
1683    }
1684
1685    fn create_timer_callback(
1686        &mut self,
1687        aggregator_rc: Option<Rc<RefCell<Box<dyn BarAggregator>>>>,
1688    ) -> TimeEventCallback {
1689        let aggregator_weak = if let Some(rc) = aggregator_rc {
1690            let weak = Rc::downgrade(&rc);
1691            self.aggregator_weak = Some(Weak::clone(&weak));
1692            weak
1693        } else {
1694            self.aggregator_weak
1695                .as_ref()
1696                .map(Weak::clone)
1697                .expect("Aggregator weak reference must be set before calling start_timer()")
1698        };
1699
1700        self.timer_active.set(false);
1701        self.timer_active = Rc::new(Cell::new(true));
1702        let active = Rc::clone(&self.timer_active);
1703        TimeEventCallback::RustLocal(Rc::new(move |event: TimeEvent| {
1704            if !active.get() {
1705                return;
1706            }
1707
1708            if let Some(agg) = aggregator_weak.upgrade() {
1709                Self::dispatch_timer(&agg, &event);
1710            }
1711        }))
1712    }
1713
1714    pub(crate) fn set_timer_source(&mut self, source: BarAggregatorWeak) {
1715        let mut current = Some(Weak::clone(&source));
1716
1717        while let Some(candidate) = current {
1718            if self
1719                .aggregator_weak
1720                .as_ref()
1721                .is_some_and(|target| Weak::ptr_eq(target, &candidate))
1722            {
1723                log::warn!(
1724                    "Cannot link time bar source for {}, circular dependency",
1725                    self.bar_type()
1726                );
1727                return;
1728            }
1729
1730            current = candidate.upgrade().and_then(|source| {
1731                source
1732                    .borrow()
1733                    .as_any()
1734                    .downcast_ref::<Self>()?
1735                    .timer_source
1736                    .clone()
1737            });
1738        }
1739
1740        self.timer_source = Some(source);
1741    }
1742
1743    fn dispatch_timer(aggregator: &Rc<RefCell<Box<dyn BarAggregator>>>, event: &TimeEvent) {
1744        let source = {
1745            let aggregator = aggregator.borrow();
1746
1747            let Some(aggregator) = aggregator.as_any().downcast_ref::<Self>() else {
1748                return;
1749            };
1750
1751            if !aggregator.timer_active.get() || event.ts_event <= aggregator.stored_open_ns {
1752                return;
1753            }
1754
1755            aggregator.timer_source.as_ref().and_then(Weak::upgrade)
1756        };
1757
1758        if let Some(source) = source {
1759            let source_due =
1760                source
1761                    .borrow()
1762                    .as_any()
1763                    .downcast_ref::<Self>()
1764                    .is_some_and(|source| {
1765                        !source.historical_mode && source.next_close_ns == event.ts_event
1766                    });
1767
1768            // Release the target borrow before the source publishes back into it
1769            if source_due {
1770                Self::dispatch_timer(&source, event);
1771            }
1772        }
1773
1774        aggregator.borrow_mut().build_bar(event);
1775    }
1776
1777    /// Stops the time bar aggregator.
1778    pub fn stop(&mut self) {
1779        self.timer_active.set(false);
1780        self.clock.borrow_mut().cancel_timer(&self.timer_name);
1781    }
1782
1783    fn build_and_send(&mut self, ts_event: UnixNanos, ts_init: UnixNanos) {
1784        if self.skip_first_non_full_bar && ts_init <= self.first_close_ns {
1785            // Carry the skipped close so a following empty interval can build a flat bar
1786            let builder = &mut self.core.builder;
1787            builder.last_close = builder.close.or(builder.last_close);
1788            builder.reset();
1789        } else {
1790            // Clear for the transition from historical to live data; subsequent
1791            // bars always emit regardless of timestamp.
1792            self.skip_first_non_full_bar = false;
1793            self.core.build_and_send(ts_event, ts_init);
1794        }
1795    }
1796
1797    fn build_bar(&mut self, event: &TimeEvent) {
1798        // Skip the bar before the first update, or when there were no updates and empty bars
1799        // are disabled, but still open the next interval and schedule its calendar alert
1800        if self.core.builder.initialized
1801            && (self.build_with_no_updates || self.core.builder.count > 0)
1802        {
1803            let ts_init = event.ts_event;
1804            let ts_event = if self.is_left_open {
1805                if self.timestamp_on_close {
1806                    event.ts_event
1807                } else {
1808                    self.stored_open_ns
1809                }
1810            } else {
1811                self.stored_open_ns
1812            };
1813
1814            self.build_and_send(ts_event, ts_init);
1815        }
1816
1817        // Close time becomes the next open time
1818        self.stored_open_ns = event.ts_event;
1819
1820        if self.uses_calendar_timer() {
1821            if !self.timer_active.get() {
1822                return;
1823            }
1824
1825            let delay = SignedDuration::from_micros(self.bar_build_delay as i64);
1826            let boundary = event.ts_event.to_datetime_utc() - delay;
1827            let next = get_time_bar_bounds(
1828                boundary,
1829                &self.bar_type(),
1830                self.time_bars_origin_offset,
1831                &self.time_zone,
1832                self.calendar_origin,
1833            )
1834            .2 + delay;
1835            let next = UnixNanos::from(next);
1836            self.clock
1837                .borrow_mut()
1838                .set_time_alert_ns(&self.timer_name, next, None, Some(true))
1839                .expect(FAILED);
1840            self.next_close_ns = next;
1841        } else {
1842            self.next_close_ns = event.ts_event.saturating_add(self.interval_ns);
1843        }
1844    }
1845
1846    fn uses_calendar_timer(&self) -> bool {
1847        matches!(
1848            self.bar_type().spec().aggregation,
1849            BarAggregation::Month | BarAggregation::Year
1850        ) || (self.time_zone != TimeZone::UTC
1851            && matches!(
1852                self.bar_type().spec().aggregation,
1853                BarAggregation::Day | BarAggregation::Week
1854            ))
1855    }
1856
1857    fn preprocess_historical_events(&mut self, ts_init: UnixNanos, include_close: bool) {
1858        if self.clock.borrow().timestamp_ns() == UnixNanos::default() {
1859            // In historical mode, clock is always a VirtualClock (set by data engine)
1860            {
1861                let mut clock_borrow = self.clock.borrow_mut();
1862                let test_clock = clock_borrow
1863                    .as_any_mut()
1864                    .downcast_mut::<VirtualClock>()
1865                    .expect("Expected VirtualClock in historical mode");
1866                test_clock.set_time(ts_init);
1867            }
1868            // In historical mode, weak reference should already be set
1869            self.start_timer_internal(None);
1870        }
1871
1872        if let Some(event) = &self.historical_event_at_ts_init
1873            && event.ts_event < ts_init
1874        {
1875            self.flush_pending_historical_bar();
1876        }
1877
1878        // Advance this aggregator's independent clock and collect timer events. Month and year
1879        // alerts re-arm from each built event, so repeat until none fall at or before `ts_init`
1880        // and only then move the clock, otherwise a re-armed alert is clamped to `ts_init`.
1881        loop {
1882            let events = {
1883                let mut clock_borrow = self.clock.borrow_mut();
1884                let test_clock = clock_borrow
1885                    .as_any_mut()
1886                    .downcast_mut::<VirtualClock>()
1887                    .expect("Expected VirtualClock in historical mode");
1888                test_clock.advance_time(ts_init, false)
1889            };
1890
1891            if events.is_empty() {
1892                break;
1893            }
1894
1895            for event in events {
1896                if include_close && event.ts_event == ts_init {
1897                    self.historical_event_at_ts_init = Some(event);
1898                } else {
1899                    self.build_bar(&event);
1900                }
1901            }
1902        }
1903
1904        let mut clock_borrow = self.clock.borrow_mut();
1905        let test_clock = clock_borrow
1906            .as_any_mut()
1907            .downcast_mut::<VirtualClock>()
1908            .expect("Expected VirtualClock in historical mode");
1909        test_clock.set_time(ts_init);
1910    }
1911
1912    /// Flushes the deferred historical close, if any.
1913    ///
1914    /// Call once no more updates can arrive at its timestamp.
1915    pub(crate) fn flush_pending_historical_bar(&mut self) {
1916        if let Some(ref event) = self.historical_event_at_ts_init.take() {
1917            self.build_bar(event);
1918        }
1919    }
1920
1921    /// Sets historical events (called by data engine after advancing clock)
1922    pub fn set_historical_events_internal(&mut self, events: Vec<TimeEvent>) {
1923        self.historical_events = events;
1924    }
1925}
1926
1927impl BarAggregator for TimeBarAggregator {
1928    fn bar_type(&self) -> BarType {
1929        self.core.builder.bar_type
1930    }
1931
1932    fn is_running(&self) -> bool {
1933        self.core.is_running
1934    }
1935
1936    fn set_is_running(&mut self, value: bool) {
1937        self.core.set_is_running(value);
1938    }
1939
1940    /// Stop time-based aggregator by canceling its timer.
1941    fn stop(&mut self) {
1942        Self::stop(self);
1943    }
1944
1945    fn update(&mut self, price: Price, size: Quantity, ts_init: UnixNanos) {
1946        if self.historical_mode {
1947            // Stale data is not applicable, and must not move the private clock backwards
1948            if self.core.is_stale(ts_init) {
1949                return;
1950            }
1951
1952            self.preprocess_historical_events(ts_init, self.is_left_open);
1953        }
1954
1955        self.core.builder.update(price, size, ts_init);
1956    }
1957
1958    fn update_bar(&mut self, bar: Bar, volume: Quantity, ts_init: UnixNanos) {
1959        if self.historical_mode {
1960            if self.core.is_stale(ts_init) {
1961                return;
1962            }
1963
1964            // Completed source bars belong to the interval ending at their init timestamp
1965            self.preprocess_historical_events(ts_init, true);
1966        }
1967
1968        self.core.builder.update_bar(bar, volume, ts_init);
1969
1970        // A completed source interval needs no later update to confirm its close
1971        if self.historical_mode {
1972            self.flush_pending_historical_bar();
1973        }
1974    }
1975
1976    fn set_historical_mode(&mut self, historical_mode: bool, handler: Box<dyn FnMut(Bar)>) {
1977        self.historical_mode = historical_mode;
1978        self.core.handler = handler;
1979    }
1980
1981    fn set_historical_events(&mut self, events: Vec<TimeEvent>) {
1982        self.set_historical_events_internal(events);
1983    }
1984
1985    fn set_clock(&mut self, clock: Rc<RefCell<dyn Clock>>) {
1986        self.set_clock_internal(clock);
1987    }
1988
1989    fn build_bar(&mut self, event: &TimeEvent) {
1990        // Delegate to the implementation method
1991        // We use the struct name here to disambiguate from the trait method
1992        {
1993            #[expect(clippy::use_self)]
1994            TimeBarAggregator::build_bar(self, event);
1995        }
1996    }
1997
1998    fn set_aggregator_weak(&mut self, weak: BarAggregatorWeak) {
1999        self.aggregator_weak = Some(weak);
2000    }
2001
2002    fn start_timer(&mut self, aggregator_rc: Option<Rc<RefCell<Box<dyn BarAggregator>>>>) {
2003        self.start_timer_internal(aggregator_rc);
2004    }
2005
2006    fn set_adjustment(&mut self, adjustment: Decimal, mode: ContinuousFutureAdjustmentType) {
2007        self.core.set_adjustment(adjustment, mode);
2008    }
2009
2010    fn set_build_with_no_updates(&mut self, value: bool) {
2011        self.build_with_no_updates = value;
2012    }
2013
2014    fn is_historical(&self) -> bool {
2015        self.historical_mode
2016    }
2017}
2018
2019fn is_below_min_size_decimal(size: Decimal, precision: u8) -> bool {
2020    quantity_from_decimal(size, precision).is_zero()
2021}
2022
2023fn min_size_decimal(precision: u8) -> Decimal {
2024    Decimal::new(1, u32::from(precision))
2025}
2026
2027fn quantity_from_decimal(size: Decimal, precision: u8) -> Quantity {
2028    Quantity::from_decimal_dp(size, precision).expect(FAILED)
2029}
2030
2031fn step_as_quantity(step: usize, precision: u8) -> Quantity {
2032    let raw = (FIXED_SCALAR as QuantityRaw)
2033        .checked_mul(step as QuantityRaw)
2034        .expect("`step` overflows raw quantity units for volume aggregation");
2035    Quantity::from_raw(raw, precision)
2036}
2037
2038/// Provider for vega per leg (option spreads). Returns `None` when greeks are unavailable.
2039pub trait VegaProvider {
2040    /// Returns vega for the given leg instrument, or `None` if not available.
2041    fn vega_for_leg(&self, instrument_id: InstrumentId) -> Option<f64>;
2042}
2043
2044/// Rounder for spread bid/ask (e.g. tick scheme). When absent, raw prices are used with instrument precision.
2045pub trait SpreadPriceRounder {
2046    /// Rounds raw bid/ask to valid prices (handles negative prices with mirroring when using tick scheme).
2047    fn round_prices(&self, raw_bid: f64, raw_ask: f64, precision: u8) -> (Price, Price);
2048}
2049
2050/// Vega provider that returns leg vegas from a map (e.g. populated from greeks cache).
2051#[derive(Debug, Default)]
2052pub struct MapVegaProvider {
2053    vegas: AHashMap<InstrumentId, f64>,
2054}
2055
2056impl MapVegaProvider {
2057    pub fn new() -> Self {
2058        Self::default()
2059    }
2060
2061    pub fn insert(&mut self, instrument_id: InstrumentId, vega: f64) {
2062        self.vegas.insert(instrument_id, vega);
2063    }
2064
2065    pub fn get(&self, instrument_id: &InstrumentId) -> Option<f64> {
2066        self.vegas.get(instrument_id).copied()
2067    }
2068}
2069
2070impl VegaProvider for MapVegaProvider {
2071    fn vega_for_leg(&self, instrument_id: InstrumentId) -> Option<f64> {
2072        self.vegas.get(&instrument_id).copied()
2073    }
2074}
2075
2076/// Rounder that uses a fixed tick size; mirrors negative prices for tick alignment.
2077#[derive(Debug)]
2078pub struct FixedTickSchemeRounder {
2079    scheme: FixedTickScheme,
2080}
2081
2082impl FixedTickSchemeRounder {
2083    /// Creates a rounder with the given tick size.
2084    ///
2085    /// # Errors
2086    ///
2087    /// Returns an error if `tick` is not a valid positive price increment.
2088    pub fn new(tick: Price) -> anyhow::Result<Self> {
2089        Ok(Self {
2090            scheme: FixedTickScheme::new(tick)?,
2091        })
2092    }
2093
2094    fn round_one(&self, raw: f64, precision: u8, use_bid_rounding: bool) -> Price {
2095        if raw >= 0.0 {
2096            let p = if use_bid_rounding {
2097                self.scheme.next_bid_price(raw, 0, precision)
2098            } else {
2099                self.scheme.next_ask_price(raw, 0, precision)
2100            };
2101            p.unwrap_or_else(|| Price::new(raw, precision))
2102        } else {
2103            let p = if use_bid_rounding {
2104                self.scheme.next_ask_price(-raw, 0, precision)
2105            } else {
2106                self.scheme.next_bid_price(-raw, 0, precision)
2107            };
2108
2109            p.map_or_else(|| Price::new(raw, precision), |q| -q)
2110        }
2111    }
2112}
2113
2114impl SpreadPriceRounder for FixedTickSchemeRounder {
2115    fn round_prices(&self, raw_bid: f64, raw_ask: f64, precision: u8) -> (Price, Price) {
2116        (
2117            self.round_one(raw_bid, precision, true),
2118            self.round_one(raw_ask, precision, false),
2119        )
2120    }
2121}
2122
2123/// Spread quote aggregator: builds synthetic quotes from leg quotes.
2124///
2125/// Quote-driven mode (`update_interval_seconds == None`): emits when all legs have quotes.
2126/// Timer-driven mode: emits on timer fire when `_has_update` is true.
2127/// Historical mode: defers timer event at `ts_init` until after the update.
2128pub struct SpreadQuoteAggregator {
2129    spread_instrument_id: InstrumentId,
2130    leg_ids: Vec<InstrumentId>,
2131    ratios: Vec<i64>,
2132    is_futures_spread: bool,
2133    price_precision: u8,
2134    size_precision: u8,
2135    last_quotes: AHashMap<InstrumentId, QuoteTick>,
2136    mid_prices: Vec<f64>,
2137    bid_prices: Vec<f64>,
2138    ask_prices: Vec<f64>,
2139    vegas: Vec<f64>,
2140    bid_ask_spreads: Vec<f64>,
2141    bid_sizes: Vec<f64>,
2142    ask_sizes: Vec<f64>,
2143    handler: Box<dyn FnMut(QuoteTick)>,
2144    clock: Rc<RefCell<dyn Clock>>,
2145    historical_mode: bool,
2146    update_interval_seconds: Option<u64>,
2147    quote_build_delay: u64,
2148    has_update: bool,
2149    timer_name: String,
2150    vega_pricing_timeout_timer_name: String,
2151    historical_event_at_ts_init: Option<TimeEvent>,
2152    vega_provider: Option<Box<dyn VegaProvider>>,
2153    disable_vega_pricing: bool,
2154    vega_pricing_temporarily_disabled: bool,
2155    vega_pricing_timeout_seconds: u64,
2156    price_rounder: Option<Box<dyn SpreadPriceRounder>>,
2157    is_running: bool,
2158    aggregator_weak: Option<Weak<RefCell<Self>>>,
2159}
2160
2161impl Debug for SpreadQuoteAggregator {
2162    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2163        f.debug_struct(stringify!(SpreadQuoteAggregator))
2164            .field("spread_instrument_id", &self.spread_instrument_id)
2165            .field("n_legs", &self.leg_ids.len())
2166            .field("is_futures_spread", &self.is_futures_spread)
2167            .field("update_interval_seconds", &self.update_interval_seconds)
2168            .finish()
2169    }
2170}
2171
2172impl SpreadQuoteAggregator {
2173    /// Creates a new [`SpreadQuoteAggregator`].
2174    ///
2175    /// # Panics
2176    ///
2177    /// Panics if `legs` has fewer than 2 entries or any ratio is zero.
2178    #[expect(clippy::too_many_arguments)]
2179    pub fn new(
2180        spread_instrument_id: InstrumentId,
2181        legs: &[(InstrumentId, i64)],
2182        is_futures_spread: bool,
2183        price_precision: u8,
2184        size_precision: u8,
2185        handler: Box<dyn FnMut(QuoteTick)>,
2186        clock: Rc<RefCell<dyn Clock>>,
2187        historical_mode: bool,
2188        update_interval_seconds: Option<u64>,
2189        quote_build_delay: u64,
2190        disable_vega_pricing: bool,
2191        vega_pricing_timeout_seconds: u64,
2192        vega_provider: Option<Box<dyn VegaProvider>>,
2193        price_rounder: Option<Box<dyn SpreadPriceRounder>>,
2194    ) -> Self {
2195        assert!(legs.len() >= 2, "Spread must have more than one leg");
2196        let n_legs = legs.len();
2197        let leg_ids: Vec<InstrumentId> = legs.iter().map(|(id, _)| *id).collect();
2198        let ratios: Vec<i64> = legs.iter().map(|(_, r)| *r).collect();
2199        for &r in &ratios {
2200            assert!(r != 0, "Ratio cannot be zero");
2201        }
2202        let timer_name = format!("SPREAD_QUOTE_{spread_instrument_id}");
2203        let vega_pricing_timeout_timer_name =
2204            format!("VEGA_PRICING_TIMEOUT_{spread_instrument_id}");
2205        Self {
2206            spread_instrument_id,
2207            leg_ids,
2208            ratios,
2209            is_futures_spread,
2210            price_precision,
2211            size_precision,
2212            last_quotes: AHashMap::new(),
2213            mid_prices: vec![0.0; n_legs],
2214            bid_prices: vec![0.0; n_legs],
2215            ask_prices: vec![0.0; n_legs],
2216            vegas: vec![0.0; n_legs],
2217            bid_ask_spreads: vec![0.0; n_legs],
2218            bid_sizes: vec![0.0; n_legs],
2219            ask_sizes: vec![0.0; n_legs],
2220            handler,
2221            clock,
2222            historical_mode,
2223            update_interval_seconds,
2224            quote_build_delay,
2225            has_update: false,
2226            timer_name,
2227            vega_pricing_timeout_timer_name,
2228            historical_event_at_ts_init: None,
2229            vega_provider,
2230            disable_vega_pricing,
2231            vega_pricing_temporarily_disabled: false,
2232            vega_pricing_timeout_seconds,
2233            price_rounder,
2234            is_running: false,
2235            aggregator_weak: None,
2236        }
2237    }
2238
2239    /// Sets the weak reference to this aggregator (used when starting the timer so the callback can call back).
2240    /// Prefer [`Self::prepare_for_timer_mode`] so the owner passes the owning `Rc` in one step.
2241    pub fn set_aggregator_weak(&mut self, weak: Weak<RefCell<Self>>) {
2242        self.aggregator_weak = Some(weak);
2243    }
2244
2245    /// One-step setup for timer-driven mode (live or historical). Call this with the `Rc` that owns
2246    /// this aggregator before feeding any quotes when `update_interval_seconds` is set. The timer
2247    /// callback will use the stored weak reference to call back into this aggregator; without this,
2248    /// [`Self::start_timer`] will panic in historical mode or when called with `None`.
2249    pub fn prepare_for_timer_mode(&mut self, self_rc: &Rc<RefCell<Self>>) {
2250        self.aggregator_weak = Some(Rc::downgrade(self_rc));
2251    }
2252
2253    /// Sets historical mode and handler (and optionally greeks provider when switching).
2254    pub fn set_historical_mode(
2255        &mut self,
2256        historical_mode: bool,
2257        handler: Box<dyn FnMut(QuoteTick)>,
2258        vega_provider: Option<Box<dyn VegaProvider>>,
2259    ) {
2260        self.historical_mode = historical_mode;
2261        self.handler = handler;
2262
2263        if let Some(vp) = vega_provider {
2264            self.vega_provider = Some(vp);
2265        }
2266    }
2267
2268    pub fn set_running(&mut self, is_running: bool) {
2269        self.is_running = is_running;
2270    }
2271
2272    pub fn set_clock(&mut self, clock: Rc<RefCell<dyn Clock>>) {
2273        self.clock = clock;
2274    }
2275
2276    /// Starts the timer when `update_interval_seconds` is set (timer-driven mode).
2277    /// In live mode pass `Some(rc)` so the weak is set and the timer can call back.
2278    /// In historical mode the owner must have called [`Self::prepare_for_timer_mode`] with the
2279    /// owning `Rc` before any quote is processed, then call with `None` here.
2280    ///
2281    /// # Panics
2282    ///
2283    /// Panics if called with `None` in timer mode without a prior [`Self::prepare_for_timer_mode`] call.
2284    pub fn start_timer(&mut self, aggregator_rc: Option<Rc<RefCell<Self>>>) {
2285        if let Some(rc) = aggregator_rc {
2286            self.aggregator_weak = Some(Rc::downgrade(&rc));
2287        }
2288
2289        let Some(interval_secs) = self.update_interval_seconds else {
2290            return;
2291        };
2292        let aggregator_weak = self.aggregator_weak.clone().expect(
2293            "SpreadQuoteAggregator: timer mode requires prepare_for_timer_mode(rc) to be \
2294                 called first with the Rc that wraps this aggregator (before feeding quotes in \
2295                 historical mode or before start_timer(None)).",
2296        );
2297
2298        let callback = TimeEventCallback::RustLocal(Rc::new(move |event: TimeEvent| {
2299            if let Some(agg) = aggregator_weak.upgrade() {
2300                agg.borrow_mut().on_timer_fire(event.ts_event);
2301            }
2302        }));
2303
2304        let now_ns = self.clock.borrow().timestamp_ns();
2305        let interval_ns = DurationNanos::from_secs(interval_secs);
2306        let start_time =
2307            now_ns.floor(interval_ns) + DurationNanos::from_micros(self.quote_build_delay);
2308        let fire_immediately = now_ns == start_time;
2309        self.clock
2310            .borrow_mut()
2311            .set_timer_ns(
2312                &self.timer_name,
2313                interval_ns,
2314                Some(start_time),
2315                None,
2316                Some(callback),
2317                Some(true),
2318                Some(fire_immediately),
2319            )
2320            .expect("Failed to set spread quote timer");
2321    }
2322
2323    /// Called when the timer fires (live mode). Builds and sends a spread quote using the timer event timestamp.
2324    pub fn on_timer_fire(&mut self, ts_event: UnixNanos) {
2325        if self.last_quotes.len() == self.leg_ids.len() {
2326            self.build_and_send_quote(ts_event);
2327        }
2328    }
2329
2330    /// Stops the timer when in timer-driven mode.
2331    pub fn stop_timer(&mut self) {
2332        if self.update_interval_seconds.is_some()
2333            && self
2334                .clock
2335                .borrow()
2336                .timer_names()
2337                .contains(&self.timer_name.as_str())
2338        {
2339            self.clock.borrow_mut().cancel_timer(&self.timer_name);
2340        }
2341
2342        if self
2343            .clock
2344            .borrow()
2345            .timer_names()
2346            .contains(&self.vega_pricing_timeout_timer_name.as_str())
2347        {
2348            self.clock
2349                .borrow_mut()
2350                .cancel_timer(&self.vega_pricing_timeout_timer_name);
2351        }
2352    }
2353
2354    /// Handles an incoming leg quote.
2355    pub fn handle_quote_tick(&mut self, tick: QuoteTick) {
2356        let ts_init = tick.ts_init;
2357
2358        if self.update_interval_seconds.is_some() && self.historical_mode {
2359            self.process_historical_events(ts_init);
2360        }
2361        self.last_quotes.insert(tick.instrument_id, tick);
2362        self.has_update = true;
2363
2364        if self.update_interval_seconds.is_none() && self.last_quotes.len() == self.leg_ids.len() {
2365            self.build_and_send_quote(ts_init);
2366        }
2367    }
2368
2369    /// Flushes the deferred historical timer event, if any.
2370    ///
2371    /// This is intended for historical request finalization, where we know no more historical
2372    /// quotes will arrive for the requested range and should not require a later live tick just
2373    /// to release the final same-timestamp spread quote.
2374    pub fn flush_pending_historical_quote(&mut self) {
2375        if self.update_interval_seconds.is_none() || !self.historical_mode {
2376            return;
2377        }
2378
2379        let Some(event) = self.historical_event_at_ts_init.take() else {
2380            return;
2381        };
2382
2383        if self.last_quotes.len() == self.leg_ids.len() {
2384            self.build_and_send_quote(event.ts_event);
2385        }
2386    }
2387
2388    /// Advances the historical clock and collects timer events. Events at `ts_init` are
2389    /// deferred until the next call when time advances. The deferred event is only flushed
2390    /// when all legs have quotes and time has moved past the deferred timestamp. This
2391    /// prevents building a spread quote with stale leg data when multiple legs update at
2392    /// the same timestamp.
2393    fn process_historical_events(&mut self, ts_init: UnixNanos) {
2394        if self.clock.borrow().timestamp_ns() == UnixNanos::default() {
2395            let mut clock_borrow = self.clock.borrow_mut();
2396            let test_clock = clock_borrow
2397                .as_any_mut()
2398                .downcast_mut::<VirtualClock>()
2399                .expect("Expected VirtualClock in historical mode");
2400            test_clock.set_time(ts_init);
2401            drop(clock_borrow);
2402            self.start_timer(None);
2403        }
2404
2405        if self.last_quotes.len() == self.leg_ids.len()
2406            && let Some(ref event) = self.historical_event_at_ts_init
2407            && event.ts_event < ts_init
2408        {
2409            // Guarded by `let Some(ref event)` above
2410            let event = self.historical_event_at_ts_init.take().unwrap();
2411            self.build_and_send_quote(event.ts_event);
2412        }
2413
2414        let events = {
2415            let mut clock_borrow = self.clock.borrow_mut();
2416            let test_clock = clock_borrow
2417                .as_any_mut()
2418                .downcast_mut::<VirtualClock>()
2419                .expect("Expected VirtualClock in historical mode");
2420            test_clock.advance_time(ts_init, true)
2421        };
2422
2423        for event in events {
2424            if event.ts_event == ts_init {
2425                self.historical_event_at_ts_init = Some(event);
2426            } else if self.last_quotes.len() == self.leg_ids.len() {
2427                self.build_and_send_quote(event.ts_event);
2428            }
2429        }
2430    }
2431
2432    /// Builds and sends one spread quote.
2433    fn build_and_send_quote(&mut self, ts_event: UnixNanos) {
2434        if !self.has_update {
2435            return;
2436        }
2437
2438        let use_vega_pricing =
2439            !(self.disable_vega_pricing || self.vega_pricing_temporarily_disabled);
2440
2441        for (idx, &leg_id) in self.leg_ids.iter().enumerate() {
2442            let Some(tick) = self.last_quotes.get(&leg_id) else {
2443                log::error!(
2444                    "SpreadQuoteAggregator[{}]: Missing quote for leg {}",
2445                    self.spread_instrument_id,
2446                    leg_id
2447                );
2448                return;
2449            };
2450            let ask_price = tick.ask_price.as_f64();
2451            let bid_price = tick.bid_price.as_f64();
2452            self.bid_prices[idx] = bid_price;
2453            self.ask_prices[idx] = ask_price;
2454            self.bid_sizes[idx] = tick.bid_size.as_f64();
2455            self.ask_sizes[idx] = tick.ask_size.as_f64();
2456
2457            if !self.is_futures_spread {
2458                self.mid_prices[idx] = f64::midpoint(ask_price, bid_price);
2459                self.bid_ask_spreads[idx] = ask_price - bid_price;
2460
2461                if use_vega_pricing
2462                    && let Some(ref vp) = self.vega_provider
2463                    && let Some(vega) = vp.vega_for_leg(leg_id)
2464                {
2465                    self.vegas[idx] = vega;
2466                }
2467            }
2468        }
2469        let (raw_bid, raw_ask) = if self.is_futures_spread {
2470            self.create_futures_spread_prices()
2471        } else {
2472            self.create_option_spread_prices()
2473        };
2474        let spread_quote = self.create_quote_tick_from_raw_prices(raw_bid, raw_ask, ts_event);
2475        self.has_update = false;
2476        (self.handler)(spread_quote);
2477    }
2478
2479    fn create_option_spread_prices(&mut self) -> (f64, f64) {
2480        if self.disable_vega_pricing || self.vega_pricing_temporarily_disabled {
2481            return self.create_futures_spread_prices();
2482        }
2483
2484        let (vega_multiplier_sum, vega_multiplier_count) = (0..self.leg_ids.len())
2485            .filter_map(|i| {
2486                let multiplier = if self.vegas[i] == 0.0 {
2487                    0.0
2488                } else {
2489                    self.bid_ask_spreads[i] / self.vegas[i]
2490                };
2491                (multiplier != 0.0).then_some(multiplier.abs())
2492            })
2493            .fold((0.0, 0_usize), |(sum, count), multiplier| {
2494                (sum + multiplier, count + 1)
2495            });
2496
2497        if vega_multiplier_count == 0 {
2498            log::warn!(
2499                "No vega information available for the components of {}; will generate spread quote using component quotes only, vega pricing is disabled for {} seconds, subscribe to some underlying price information for more precise quotes",
2500                self.spread_instrument_id,
2501                self.vega_pricing_timeout_seconds
2502            );
2503            self.start_vega_pricing_timeout();
2504            return self.create_futures_spread_prices();
2505        }
2506        let vega_multiplier = vega_multiplier_sum / vega_multiplier_count as f64;
2507        let spread_vega = self
2508            .vegas
2509            .iter()
2510            .zip(self.ratios.iter())
2511            .map(|(v, r)| v * (*r as f64))
2512            .sum::<f64>()
2513            .abs();
2514        let bid_ask_spread = spread_vega * vega_multiplier;
2515        let spread_mid_price: f64 = self
2516            .mid_prices
2517            .iter()
2518            .zip(self.ratios.iter())
2519            .map(|(m, r)| m * (*r as f64))
2520            .sum();
2521        let raw_bid = spread_mid_price - bid_ask_spread * 0.5;
2522        let raw_ask = spread_mid_price + bid_ask_spread * 0.5;
2523        (raw_bid, raw_ask)
2524    }
2525
2526    fn clear_vega_pricing_timeout(&mut self) {
2527        self.vega_pricing_temporarily_disabled = false;
2528    }
2529
2530    fn start_vega_pricing_timeout(&mut self) {
2531        self.vega_pricing_temporarily_disabled = true;
2532
2533        if self
2534            .clock
2535            .borrow()
2536            .timer_names()
2537            .contains(&self.vega_pricing_timeout_timer_name.as_str())
2538        {
2539            return;
2540        }
2541
2542        let Some(aggregator_weak) = self.aggregator_weak.clone() else {
2543            return;
2544        };
2545        let callback = TimeEventCallback::RustLocal(Rc::new(move |_event: TimeEvent| {
2546            if let Some(agg) = aggregator_weak.upgrade() {
2547                agg.borrow_mut().clear_vega_pricing_timeout();
2548            }
2549        }));
2550        let timeout = DurationNanos::try_from_secs(self.vega_pricing_timeout_seconds)
2551            .expect("vega pricing timeout exceeds the nanosecond range");
2552        let alert_time = self.clock.borrow().timestamp_ns() + timeout;
2553
2554        self.clock
2555            .borrow_mut()
2556            .set_time_alert_ns(
2557                &self.vega_pricing_timeout_timer_name,
2558                alert_time,
2559                Some(callback),
2560                Some(true),
2561            )
2562            .expect("Failed to set spread quote vega pricing timeout");
2563    }
2564
2565    fn create_futures_spread_prices(&self) -> (f64, f64) {
2566        let mut raw_ask = 0.0_f64;
2567        let mut raw_bid = 0.0_f64;
2568
2569        for i in 0..self.leg_ids.len() {
2570            let r = self.ratios[i] as f64;
2571            if self.ratios[i] >= 0 {
2572                raw_ask += r * self.ask_prices[i];
2573                raw_bid += r * self.bid_prices[i];
2574            } else {
2575                raw_ask += r * self.bid_prices[i];
2576                raw_bid += r * self.ask_prices[i];
2577            }
2578        }
2579        (raw_bid, raw_ask)
2580    }
2581
2582    fn create_quote_tick_from_raw_prices(
2583        &self,
2584        raw_bid_price: f64,
2585        raw_ask_price: f64,
2586        ts_event: UnixNanos,
2587    ) -> QuoteTick {
2588        let (bid_price, ask_price) = if let Some(ref rounder) = self.price_rounder {
2589            rounder.round_prices(raw_bid_price, raw_ask_price, self.price_precision)
2590        } else {
2591            (
2592                Price::new(raw_bid_price, self.price_precision),
2593                Price::new(raw_ask_price, self.price_precision),
2594            )
2595        };
2596        let mut min_bid_size = f64::INFINITY;
2597        let mut min_ask_size = f64::INFINITY;
2598        for i in 0..self.leg_ids.len() {
2599            let abs_ratio = self.ratios[i].unsigned_abs() as f64;
2600            let (bid_size, ask_size) = if self.ratios[i] >= 0 {
2601                (self.bid_sizes[i], self.ask_sizes[i])
2602            } else {
2603                (self.ask_sizes[i], self.bid_sizes[i])
2604            };
2605            let bid_size = bid_size / abs_ratio;
2606            if bid_size < min_bid_size {
2607                min_bid_size = bid_size;
2608            }
2609            let ask_size = ask_size / abs_ratio;
2610            if ask_size < min_ask_size {
2611                min_ask_size = ask_size;
2612            }
2613        }
2614        let bid_size = Quantity::new(min_bid_size, self.size_precision);
2615        let ask_size = Quantity::new(min_ask_size, self.size_precision);
2616        QuoteTick::new(
2617            self.spread_instrument_id,
2618            bid_price,
2619            ask_price,
2620            bid_size,
2621            ask_size,
2622            ts_event,
2623            ts_event,
2624        )
2625    }
2626}
2627
2628#[cfg(test)]
2629mod tests {
2630    use std::sync::Arc;
2631
2632    use nautilus_common::{clock::VirtualClock, timer::TimeEvent};
2633    use nautilus_core::{UUID4, UnixNanos};
2634    use nautilus_model::{
2635        data::{BarSpecification, BarType, QuoteTick},
2636        enums::{AggregationSource, AggressorSide, BarAggregation, PriceType},
2637        identifiers::InstrumentId,
2638        instruments::{CurrencyPair, Equity, Instrument, InstrumentAny, stubs::*},
2639        types::{Price, Quantity, price::PRICE_RAW_MAX},
2640    };
2641    use parking_lot::Mutex;
2642    use rstest::rstest;
2643    use ustr::Ustr;
2644
2645    use super::*;
2646
2647    #[rstest]
2648    #[case::day(BarAggregation::Day, "2026-10-30T16:00:00Z", "2026-11-02T12:00:00Z", ["2026-10-31T04:00:00Z", "2026-11-01T04:00:00Z", "2026-11-02T05:00:00Z"])]
2649    #[case::month(BarAggregation::Month, "2026-10-15T16:00:00Z", "2027-01-15T12:00:00Z", ["2026-11-01T04:00:00Z", "2026-12-01T05:00:00Z", "2027-01-01T05:00:00Z"])]
2650    #[case::year(BarAggregation::Year, "2024-06-15T16:00:00Z", "2027-06-15T12:00:00Z", ["2025-01-01T05:00:00Z", "2026-01-01T05:00:00Z", "2027-01-01T05:00:00Z"])]
2651    #[case::week(BarAggregation::Week, "2026-10-30T16:00:00Z", "2026-11-17T12:00:00Z", ["2026-11-02T05:00:00Z", "2026-11-09T05:00:00Z", "2026-11-16T05:00:00Z"])]
2652    fn test_time_bar_local_calendar_closes_every_period_across_gap(
2653        equity_aapl: Equity,
2654        #[case] aggregation: BarAggregation,
2655        #[case] start: &str,
2656        #[case] finish: &str,
2657        #[case] expected: [&str; 3],
2658    ) {
2659        let instrument = InstrumentAny::Equity(equity_aapl);
2660
2661        let bar_type = BarType::new(
2662            instrument.id(),
2663            BarSpecification::new(1, aggregation, PriceType::Last),
2664            AggregationSource::Internal,
2665        );
2666        let (handler, record) = recording_handler();
2667
2668        let mut agg = TimeBarAggregator::new(
2669            bar_type,
2670            instrument.price_precision(),
2671            instrument.size_precision(),
2672            Rc::new(RefCell::new(VirtualClock::new())),
2673            record,
2674            true,
2675            true,
2676            BarIntervalType::LeftOpen,
2677            None,
2678            nautilus_core::datetime::get_timezone("America/New_York").unwrap(),
2679            0,
2680            false,
2681        );
2682        agg.historical_mode = true;
2683        let rc: Rc<RefCell<Box<dyn BarAggregator>>> = Rc::new(RefCell::new(Box::new(agg)));
2684        rc.borrow_mut().set_aggregator_weak(Rc::downgrade(&rc));
2685        for ts in [start, finish] {
2686            rc.borrow_mut().update(
2687                Price::from("103.25"),
2688                Quantity::from(2),
2689                UnixNanos::from(ts.parse::<jiff::Timestamp>().unwrap()),
2690            );
2691        }
2692
2693        let bars = handler.lock();
2694        assert_eq!(bars.len(), 3);
2695
2696        for (i, expected) in expected.into_iter().enumerate() {
2697            assert_eq!(
2698                bars[i],
2699                Bar::new(
2700                    bar_type,
2701                    Price::from("103.25"),
2702                    Price::from("103.25"),
2703                    Price::from("103.25"),
2704                    Price::from("103.25"),
2705                    Quantity::from(if i == 0 { 2 } else { 0 }),
2706                    UnixNanos::from(expected.parse::<jiff::Timestamp>().unwrap()),
2707                    UnixNanos::from(expected.parse::<jiff::Timestamp>().unwrap())
2708                )
2709            );
2710        }
2711    }
2712
2713    #[rstest]
2714    #[case::gap_and_delay((1, BarAggregation::Day), "America/New_York", 9000, 3_600_000_000, ["2026-03-07T12:00:00Z", "2026-03-10T12:00:00Z"], ["2026-03-08T08:30:00Z", "2026-03-09T07:30:00Z", "2026-03-10T07:30:00Z"])]
2715    #[case::clamped_month((1, BarAggregation::Month), "America/New_York", 2_592_000, 0, ["2026-02-01T12:00:00Z", "2026-05-01T12:00:00Z"], ["2026-02-28T05:00:00Z", "2026-03-31T04:00:00Z", "2026-04-30T04:00:00Z"])]
2716    #[case::month_leap_to_common_year((1, BarAggregation::Month), "UTC", 5_097_600, 0, ["2024-12-01T12:00:00Z", "2025-03-01T12:00:00Z"], ["2024-12-29T00:00:00Z", "2025-01-29T00:00:00Z", "2025-02-28T00:00:00Z"])]
2717    #[case::month_common_to_leap_year((1, BarAggregation::Month), "UTC", 5_097_600, 0, ["2023-12-01T12:00:00Z", "2024-03-02T12:00:00Z"], ["2024-01-01T00:00:00Z", "2024-02-01T00:00:00Z", "2024-03-01T00:00:00Z"])]
2718    #[case::multi_day_large_origin((2, BarAggregation::Day), "America/New_York", 129_600, 0, ["2026-10-30T16:00:00Z", "2026-11-05T17:00:00Z"], ["2026-10-31T16:00:00Z", "2026-11-02T17:00:00Z", "2026-11-04T17:00:00Z"])]
2719    #[case::multi_week_large_origin((2, BarAggregation::Week), "America/New_York", 907_200, 0, ["2026-10-30T16:00:00Z", "2026-12-04T17:00:00Z"], ["2026-11-05T17:00:00Z", "2026-11-19T17:00:00Z", "2026-12-03T17:00:00Z"])]
2720    #[case::multi_year_large_origin((2, BarAggregation::Year), "UTC", 43_200_000, 0, ["2026-01-01T12:00:00Z", "2031-06-01T12:00:00Z"], ["2027-05-16T00:00:00Z", "2029-05-15T00:00:00Z", "2031-05-16T00:00:00Z"])]
2721    fn test_time_bar_calendar_rearming_preserves_origin_and_delay(
2722        equity_aapl: Equity,
2723        #[case] interval: (usize, BarAggregation),
2724        #[case] zone: &str,
2725        #[case] origin_secs: i64,
2726        #[case] delay_micros: u64,
2727        #[case] window: [&str; 2],
2728        #[case] expected: [&str; 3],
2729    ) {
2730        let bar_type = BarType::new(
2731            equity_aapl.id,
2732            BarSpecification::new(interval.0, interval.1, PriceType::Last),
2733            AggregationSource::Internal,
2734        );
2735        let (handler, record) = recording_handler();
2736
2737        let mut agg = TimeBarAggregator::new(
2738            bar_type,
2739            equity_aapl.price_precision,
2740            equity_aapl.size_precision(),
2741            Rc::new(RefCell::new(VirtualClock::new())),
2742            record,
2743            true,
2744            true,
2745            BarIntervalType::LeftOpen,
2746            Some(SignedDuration::from_secs(origin_secs)),
2747            nautilus_core::datetime::get_timezone(zone).unwrap(),
2748            delay_micros,
2749            false,
2750        );
2751        agg.historical_mode = true;
2752        let rc: Rc<RefCell<Box<dyn BarAggregator>>> = Rc::new(RefCell::new(Box::new(agg)));
2753        rc.borrow_mut().set_aggregator_weak(Rc::downgrade(&rc));
2754        for ts in window {
2755            rc.borrow_mut().update(
2756                Price::from("103.25"),
2757                Quantity::from(2),
2758                UnixNanos::from(ts.parse::<jiff::Timestamp>().unwrap()),
2759            );
2760        }
2761
2762        let expected: Vec<Bar> = expected
2763            .into_iter()
2764            .enumerate()
2765            .map(|(i, ts)| {
2766                let ts = UnixNanos::from(ts.parse::<jiff::Timestamp>().unwrap());
2767
2768                Bar::new(
2769                    bar_type,
2770                    Price::from("103.25"),
2771                    Price::from("103.25"),
2772                    Price::from("103.25"),
2773                    Price::from("103.25"),
2774                    Quantity::from(if i == 0 { 2 } else { 0 }),
2775                    ts,
2776                    ts,
2777                )
2778            })
2779            .collect();
2780
2781        assert_eq!(*handler.lock(), expected);
2782    }
2783
2784    #[rstest]
2785    #[case::day(
2786        BarAggregation::Day,
2787        "America/New_York",
2788        "2026-11-02T05:00:00Z",
2789        "2026-10-31T04:00:00Z"
2790    )]
2791    #[case::week(
2792        BarAggregation::Week,
2793        "America/New_York",
2794        "2026-11-09T05:00:00Z",
2795        "2026-10-26T04:00:00Z"
2796    )]
2797    #[case::year(
2798        BarAggregation::Year,
2799        "UTC",
2800        "2026-01-01T00:00:00Z",
2801        "2024-01-01T00:00:00Z"
2802    )]
2803    fn test_time_bar_calendar_first_open_spans_full_step(
2804        equity_aapl: Equity,
2805        #[case] aggregation: BarAggregation,
2806        #[case] zone: &str,
2807        #[case] now: &str,
2808        #[case] previous_open: &str,
2809    ) {
2810        let bar_type = BarType::new(
2811            equity_aapl.id,
2812            BarSpecification::new(2, aggregation, PriceType::Last),
2813            AggregationSource::Internal,
2814        );
2815        let clock = Rc::new(RefCell::new(VirtualClock::new()));
2816        let now = UnixNanos::from(now.parse::<jiff::Timestamp>().unwrap());
2817        clock.borrow_mut().set_time(now);
2818        let (handler, record) = recording_handler();
2819
2820        let agg = TimeBarAggregator::new(
2821            bar_type,
2822            equity_aapl.price_precision,
2823            equity_aapl.size_precision(),
2824            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
2825            record,
2826            true,
2827            false,
2828            BarIntervalType::LeftOpen,
2829            None,
2830            nautilus_core::datetime::get_timezone(zone).unwrap(),
2831            0,
2832            false,
2833        );
2834        let rc: Rc<RefCell<Box<dyn BarAggregator>>> = Rc::new(RefCell::new(Box::new(agg)));
2835        rc.borrow_mut()
2836            .as_any_mut()
2837            .downcast_mut::<TimeBarAggregator>()
2838            .unwrap()
2839            .start_timer_internal(Some(Rc::clone(&rc)));
2840        rc.borrow_mut()
2841            .update(Price::from("103.25"), Quantity::from(2), now);
2842        let events = clock.borrow_mut().advance_time(now, true);
2843        let callbacks = clock.borrow().match_handlers(events);
2844        for callback in callbacks {
2845            callback.callback.call(callback.event);
2846        }
2847
2848        assert_eq!(
2849            *handler.lock(),
2850            vec![Bar::new(
2851                bar_type,
2852                Price::from("103.25"),
2853                Price::from("103.25"),
2854                Price::from("103.25"),
2855                Price::from("103.25"),
2856                Quantity::from(2),
2857                UnixNanos::from(previous_open.parse::<jiff::Timestamp>().unwrap()),
2858                now
2859            )]
2860        );
2861    }
2862
2863    #[rstest]
2864    fn test_time_bar_timer_callback_does_not_retain_aggregator(equity_aapl: Equity) {
2865        let bar_type = BarType::new(
2866            equity_aapl.id,
2867            BarSpecification::new(1, BarAggregation::Second, PriceType::Last),
2868            AggregationSource::Internal,
2869        );
2870
2871        let clock = Rc::new(RefCell::new(VirtualClock::new()));
2872
2873        let aggregator = TimeBarAggregator::new(
2874            bar_type,
2875            equity_aapl.price_precision,
2876            equity_aapl.size_precision(),
2877            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
2878            |_bar: Bar| {},
2879            false,
2880            true,
2881            BarIntervalType::LeftOpen,
2882            None,
2883            TimeZone::UTC,
2884            0,
2885            false,
2886        );
2887
2888        let rc: Rc<RefCell<Box<dyn BarAggregator>>> = Rc::new(RefCell::new(Box::new(aggregator)));
2889        let weak = Rc::downgrade(&rc);
2890        rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
2891        drop(rc);
2892
2893        assert!(weak.upgrade().is_none());
2894        let events = clock
2895            .borrow_mut()
2896            .advance_time(UnixNanos::from(1_000_000_000), true);
2897        let callbacks = clock.borrow().match_handlers(events);
2898        assert_eq!(callbacks.len(), 2);
2899
2900        for callback in callbacks {
2901            callback.callback.call(callback.event);
2902        }
2903    }
2904
2905    #[rstest]
2906    #[case::day(BarAggregation::Day, "2026-10-31T04:00:00Z", "2026-11-01T04:00:00Z")]
2907    #[case::week(BarAggregation::Week, "2026-11-02T05:00:00Z", "2026-11-09T05:00:00Z")]
2908    #[case::month(BarAggregation::Month, "2026-11-01T04:00:00Z", "2026-12-01T05:00:00Z")]
2909    #[case::year(BarAggregation::Year, "2027-01-01T05:00:00Z", "2028-01-01T05:00:00Z")]
2910    fn test_time_bar_stopped_calendar_timer_does_not_rearm_queued_event(
2911        equity_aapl: Equity,
2912        #[case] aggregation: BarAggregation,
2913        #[case] first: &str,
2914        #[case] following: &str,
2915    ) {
2916        let bar_type = BarType::new(
2917            equity_aapl.id,
2918            BarSpecification::new(1, aggregation, PriceType::Last),
2919            AggregationSource::Internal,
2920        );
2921        let clock = Rc::new(RefCell::new(VirtualClock::new()));
2922        let now = UnixNanos::from("2026-10-30T16:00:00Z".parse::<jiff::Timestamp>().unwrap());
2923        let first = UnixNanos::from(first.parse::<jiff::Timestamp>().unwrap());
2924        let following = UnixNanos::from(following.parse::<jiff::Timestamp>().unwrap());
2925        clock.borrow_mut().set_time(now);
2926
2927        let aggregator = TimeBarAggregator::new(
2928            bar_type,
2929            equity_aapl.price_precision,
2930            equity_aapl.size_precision(),
2931            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
2932            |_bar: Bar| {},
2933            true,
2934            true,
2935            BarIntervalType::LeftOpen,
2936            None,
2937            nautilus_core::datetime::get_timezone("America/New_York").unwrap(),
2938            0,
2939            false,
2940        );
2941        let rc: Rc<RefCell<Box<dyn BarAggregator>>> = Rc::new(RefCell::new(Box::new(aggregator)));
2942        let timer_name = format!("TIME_BAR_{bar_type}");
2943        rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
2944        assert_eq!(clock.borrow().next_time_ns(&timer_name), Some(first));
2945        let events = clock.borrow_mut().advance_time(first, true);
2946        let callbacks = clock.borrow().match_handlers(events);
2947        rc.borrow_mut().stop();
2948
2949        for callback in callbacks {
2950            callback.callback.call(callback.event);
2951        }
2952
2953        assert_eq!(clock.borrow().timer_count(), 0);
2954        assert_eq!(clock.borrow().next_time_ns(&timer_name), None);
2955
2956        clock.borrow_mut().set_time(first + DurationNanos::new(1));
2957        rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
2958        assert_eq!(clock.borrow().timer_count(), 1);
2959        assert_eq!(clock.borrow().next_time_ns(&timer_name), Some(following));
2960    }
2961
2962    #[rstest]
2963    #[case::day(
2964        BarAggregation::Day,
2965        "2026-10-31T04:00:00Z",
2966        "2026-11-01T04:00:00Z",
2967        "2026-11-02T05:00:00Z"
2968    )]
2969    #[case::week(
2970        BarAggregation::Week,
2971        "2026-11-02T05:00:00Z",
2972        "2026-11-09T05:00:00Z",
2973        "2026-11-16T05:00:00Z"
2974    )]
2975    #[case::month(
2976        BarAggregation::Month,
2977        "2026-11-01T04:00:00Z",
2978        "2026-12-01T05:00:00Z",
2979        "2027-01-01T05:00:00Z"
2980    )]
2981    #[case::year(
2982        BarAggregation::Year,
2983        "2027-01-01T05:00:00Z",
2984        "2028-01-01T05:00:00Z",
2985        "2029-01-01T05:00:00Z"
2986    )]
2987    #[case::hour(
2988        BarAggregation::Hour,
2989        "2026-10-30T16:00:00Z",
2990        "2026-10-30T17:00:00Z",
2991        "2026-10-30T18:00:00Z"
2992    )]
2993    fn test_time_bar_restarted_timer_ignores_previous_registration_event(
2994        equity_aapl: Equity,
2995        #[case] aggregation: BarAggregation,
2996        #[case] first: &str,
2997        #[case] following: &str,
2998        #[case] after_restart: &str,
2999        #[values(true, false)] stop_before_restart: bool,
3000    ) {
3001        let bar_type = BarType::new(
3002            equity_aapl.id,
3003            BarSpecification::new(1, aggregation, PriceType::Last),
3004            AggregationSource::Internal,
3005        );
3006        let clock = Rc::new(RefCell::new(VirtualClock::new()));
3007        let now = UnixNanos::from("2026-10-30T16:00:00Z".parse::<jiff::Timestamp>().unwrap());
3008        let first = UnixNanos::from(first.parse::<jiff::Timestamp>().unwrap());
3009        let following = UnixNanos::from(following.parse::<jiff::Timestamp>().unwrap());
3010        let after_restart = UnixNanos::from(after_restart.parse::<jiff::Timestamp>().unwrap());
3011        clock.borrow_mut().set_time(now);
3012        let (handler, record) = recording_handler();
3013
3014        let aggregator = TimeBarAggregator::new(
3015            bar_type,
3016            equity_aapl.price_precision,
3017            equity_aapl.size_precision(),
3018            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
3019            record,
3020            true,
3021            false,
3022            BarIntervalType::LeftOpen,
3023            None,
3024            nautilus_core::datetime::get_timezone("America/New_York").unwrap(),
3025            0,
3026            false,
3027        );
3028        let rc: Rc<RefCell<Box<dyn BarAggregator>>> = Rc::new(RefCell::new(Box::new(aggregator)));
3029        let timer_name = format!("TIME_BAR_{bar_type}");
3030        rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
3031        assert_eq!(clock.borrow().next_time_ns(&timer_name), Some(first));
3032        let events = clock.borrow_mut().advance_time(first, true);
3033        let callbacks = clock.borrow().match_handlers(events);
3034
3035        if stop_before_restart {
3036            rc.borrow_mut().stop();
3037        }
3038
3039        clock
3040            .borrow_mut()
3041            .set_time(following + DurationNanos::new(1));
3042        rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
3043        assert_eq!(
3044            clock.borrow().next_time_ns(&timer_name),
3045            Some(after_restart)
3046        );
3047        rc.borrow_mut().update(
3048            Price::from("103.25"),
3049            Quantity::from(2),
3050            following + DurationNanos::new(1),
3051        );
3052        {
3053            let _aggregator = rc.borrow_mut();
3054
3055            for callback in callbacks {
3056                callback.callback.call(callback.event);
3057            }
3058        }
3059
3060        assert_eq!(*handler.lock(), Vec::<Bar>::new());
3061        assert_eq!(clock.borrow().timer_count(), 1);
3062        assert_eq!(
3063            clock.borrow().next_time_ns(&timer_name),
3064            Some(after_restart)
3065        );
3066        let events = clock.borrow_mut().advance_time(after_restart, true);
3067        let callbacks = clock.borrow().match_handlers(events);
3068        for callback in callbacks {
3069            callback.callback.call(callback.event);
3070        }
3071
3072        assert_eq!(
3073            *handler.lock(),
3074            vec![Bar::new(
3075                bar_type,
3076                Price::from("103.25"),
3077                Price::from("103.25"),
3078                Price::from("103.25"),
3079                Price::from("103.25"),
3080                Quantity::from(2),
3081                following,
3082                after_restart,
3083            )]
3084        );
3085    }
3086
3087    #[rstest]
3088    fn test_bar_builder_initialization(equity_aapl: Equity) {
3089        let instrument = InstrumentAny::Equity(equity_aapl);
3090        let bar_type = BarType::new(
3091            instrument.id(),
3092            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3093            AggregationSource::Internal,
3094        );
3095        let builder = BarBuilder::new(
3096            bar_type,
3097            instrument.price_precision(),
3098            instrument.size_precision(),
3099        );
3100
3101        assert!(!builder.initialized);
3102        assert_eq!(builder.ts_last, 0);
3103        assert_eq!(builder.count, 0);
3104    }
3105
3106    #[rstest]
3107    fn test_bar_builder_maintains_ohlc_order(equity_aapl: Equity) {
3108        let instrument = InstrumentAny::Equity(equity_aapl);
3109        let bar_type = BarType::new(
3110            instrument.id(),
3111            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3112            AggregationSource::Internal,
3113        );
3114        let mut builder = BarBuilder::new(
3115            bar_type,
3116            instrument.price_precision(),
3117            instrument.size_precision(),
3118        );
3119
3120        builder.update(
3121            Price::from("100.00"),
3122            Quantity::from(1),
3123            UnixNanos::from(1000),
3124        );
3125        builder.update(
3126            Price::from("95.00"),
3127            Quantity::from(1),
3128            UnixNanos::from(2000),
3129        );
3130        builder.update(
3131            Price::from("105.00"),
3132            Quantity::from(1),
3133            UnixNanos::from(3000),
3134        );
3135
3136        let bar = builder.build_now();
3137        assert!(bar.high > bar.low);
3138        assert_eq!(bar.open, Price::from("100.00"));
3139        assert_eq!(bar.high, Price::from("105.00"));
3140        assert_eq!(bar.low, Price::from("95.00"));
3141        assert_eq!(bar.close, Price::from("105.00"));
3142    }
3143
3144    #[rstest]
3145    fn test_update_ignores_earlier_timestamps(equity_aapl: Equity) {
3146        let instrument = InstrumentAny::Equity(equity_aapl);
3147        let bar_type = BarType::new(
3148            instrument.id(),
3149            BarSpecification::new(100, BarAggregation::Tick, PriceType::Last),
3150            AggregationSource::Internal,
3151        );
3152        let mut builder = BarBuilder::new(
3153            bar_type,
3154            instrument.price_precision(),
3155            instrument.size_precision(),
3156        );
3157
3158        builder.update(Price::from("1.00000"), Quantity::from(1), 1_000.into());
3159        builder.update(Price::from("1.00001"), Quantity::from(1), 500.into());
3160
3161        assert_eq!(builder.ts_last, 1_000);
3162        assert_eq!(builder.count, 1);
3163    }
3164
3165    #[rstest]
3166    fn test_bar_builder_single_update_results_in_expected_properties(equity_aapl: Equity) {
3167        let instrument = InstrumentAny::Equity(equity_aapl);
3168        let bar_type = BarType::new(
3169            instrument.id(),
3170            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3171            AggregationSource::Internal,
3172        );
3173        let mut builder = BarBuilder::new(
3174            bar_type,
3175            instrument.price_precision(),
3176            instrument.size_precision(),
3177        );
3178
3179        builder.update(
3180            Price::from("1.00000"),
3181            Quantity::from(1),
3182            UnixNanos::default(),
3183        );
3184
3185        assert!(builder.initialized);
3186        assert_eq!(builder.ts_last, 0);
3187        assert_eq!(builder.count, 1);
3188    }
3189
3190    #[rstest]
3191    fn test_bar_builder_single_update_when_timestamp_less_than_last_update_ignores(
3192        equity_aapl: Equity,
3193    ) {
3194        let instrument = InstrumentAny::Equity(equity_aapl);
3195        let bar_type = BarType::new(
3196            instrument.id(),
3197            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3198            AggregationSource::Internal,
3199        );
3200        let mut builder = BarBuilder::new(bar_type, 2, 0);
3201
3202        builder.update(
3203            Price::from("1.00000"),
3204            Quantity::from(1),
3205            UnixNanos::from(1_000),
3206        );
3207        builder.update(
3208            Price::from("1.00001"),
3209            Quantity::from(1),
3210            UnixNanos::from(500),
3211        );
3212
3213        assert!(builder.initialized);
3214        assert_eq!(builder.ts_last, 1_000);
3215        assert_eq!(builder.count, 1);
3216    }
3217
3218    #[rstest]
3219    fn test_bar_builder_multiple_updates_correctly_increments_count(equity_aapl: Equity) {
3220        let instrument = InstrumentAny::Equity(equity_aapl);
3221        let bar_type = BarType::new(
3222            instrument.id(),
3223            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3224            AggregationSource::Internal,
3225        );
3226        let mut builder = BarBuilder::new(
3227            bar_type,
3228            instrument.price_precision(),
3229            instrument.size_precision(),
3230        );
3231
3232        for _ in 0..5 {
3233            builder.update(
3234                Price::from("1.00000"),
3235                Quantity::from(1),
3236                UnixNanos::from(1_000),
3237            );
3238        }
3239
3240        assert_eq!(builder.count, 5);
3241    }
3242
3243    #[rstest]
3244    #[should_panic]
3245    fn test_bar_builder_build_when_no_updates_panics(equity_aapl: Equity) {
3246        let instrument = InstrumentAny::Equity(equity_aapl);
3247        let bar_type = BarType::new(
3248            instrument.id(),
3249            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3250            AggregationSource::Internal,
3251        );
3252        let mut builder = BarBuilder::new(
3253            bar_type,
3254            instrument.price_precision(),
3255            instrument.size_precision(),
3256        );
3257        let _ = builder.build_now();
3258    }
3259
3260    #[rstest]
3261    fn test_bar_builder_build_when_received_updates_returns_expected_bar(equity_aapl: Equity) {
3262        let instrument = InstrumentAny::Equity(equity_aapl);
3263        let bar_type = BarType::new(
3264            instrument.id(),
3265            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3266            AggregationSource::Internal,
3267        );
3268        let mut builder = BarBuilder::new(
3269            bar_type,
3270            instrument.price_precision(),
3271            instrument.size_precision(),
3272        );
3273
3274        builder.update(
3275            Price::from("1.00001"),
3276            Quantity::from(2),
3277            UnixNanos::default(),
3278        );
3279        builder.update(
3280            Price::from("1.00002"),
3281            Quantity::from(2),
3282            UnixNanos::default(),
3283        );
3284        builder.update(
3285            Price::from("1.00000"),
3286            Quantity::from(1),
3287            UnixNanos::from(1_000_000_000),
3288        );
3289
3290        let bar = builder.build_now();
3291
3292        assert_eq!(bar.open, Price::from("1.00001"));
3293        assert_eq!(bar.high, Price::from("1.00002"));
3294        assert_eq!(bar.low, Price::from("1.00000"));
3295        assert_eq!(bar.close, Price::from("1.00000"));
3296        assert_eq!(bar.volume, Quantity::from(5));
3297        assert_eq!(bar.ts_init, 1_000_000_000);
3298        assert_eq!(builder.ts_last, 1_000_000_000);
3299        assert_eq!(builder.count, 0);
3300    }
3301
3302    #[rstest]
3303    fn test_bar_builder_build_with_previous_close(equity_aapl: Equity) {
3304        let instrument = InstrumentAny::Equity(equity_aapl);
3305        let bar_type = BarType::new(
3306            instrument.id(),
3307            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3308            AggregationSource::Internal,
3309        );
3310        let mut builder = BarBuilder::new(bar_type, 2, 0);
3311
3312        builder.update(
3313            Price::from("1.00001"),
3314            Quantity::from(1),
3315            UnixNanos::default(),
3316        );
3317        builder.build_now();
3318
3319        builder.update(
3320            Price::from("1.00000"),
3321            Quantity::from(1),
3322            UnixNanos::default(),
3323        );
3324        builder.update(
3325            Price::from("1.00003"),
3326            Quantity::from(1),
3327            UnixNanos::default(),
3328        );
3329        builder.update(
3330            Price::from("1.00002"),
3331            Quantity::from(1),
3332            UnixNanos::default(),
3333        );
3334
3335        let bar = builder.build_now();
3336
3337        assert_eq!(bar.open, Price::from("1.00000"));
3338        assert_eq!(bar.high, Price::from("1.00003"));
3339        assert_eq!(bar.low, Price::from("1.00000"));
3340        assert_eq!(bar.close, Price::from("1.00002"));
3341        assert_eq!(bar.volume, Quantity::from(3));
3342    }
3343
3344    #[rstest]
3345    fn test_bar_builder_update_bar_initializes_then_accumulates(equity_aapl: Equity) {
3346        let instrument = InstrumentAny::Equity(equity_aapl);
3347        let bar_type = BarType::new(
3348            instrument.id(),
3349            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3350            AggregationSource::Internal,
3351        );
3352        let mut builder = BarBuilder::new(
3353            bar_type,
3354            instrument.price_precision(),
3355            instrument.size_precision(),
3356        );
3357
3358        let bar_one = Bar::new(
3359            bar_type,
3360            Price::from("100.00"),
3361            Price::from("102.00"),
3362            Price::from("99.00"),
3363            Price::from("101.00"),
3364            Quantity::from(10),
3365            UnixNanos::from(1_000),
3366            UnixNanos::from(1_000),
3367        );
3368        let bar_two = Bar::new(
3369            bar_type,
3370            Price::from("101.00"),
3371            Price::from("103.00"),
3372            Price::from("98.00"),
3373            Price::from("102.00"),
3374            Quantity::from(5),
3375            UnixNanos::from(2_000),
3376            UnixNanos::from(2_000),
3377        );
3378
3379        builder.update_bar(bar_one, bar_one.volume, bar_one.ts_init);
3380        builder.update_bar(bar_two, bar_two.volume, bar_two.ts_init);
3381        let bar = builder.build_now();
3382
3383        assert_eq!(bar.open, Price::from("100.00"));
3384        assert_eq!(bar.high, Price::from("103.00"));
3385        assert_eq!(bar.low, Price::from("98.00"));
3386        assert_eq!(bar.close, Price::from("102.00"));
3387        assert_eq!(bar.volume, Quantity::from(15));
3388        assert_eq!(builder.count, 0);
3389    }
3390
3391    #[rstest]
3392    fn test_bar_builder_update_bar_ignores_earlier_timestamp(equity_aapl: Equity) {
3393        let instrument = InstrumentAny::Equity(equity_aapl);
3394        let bar_type = BarType::new(
3395            instrument.id(),
3396            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3397            AggregationSource::Internal,
3398        );
3399        let mut builder = BarBuilder::new(
3400            bar_type,
3401            instrument.price_precision(),
3402            instrument.size_precision(),
3403        );
3404
3405        let bar_later = Bar::new(
3406            bar_type,
3407            Price::from("100.00"),
3408            Price::from("101.00"),
3409            Price::from("99.00"),
3410            Price::from("100.50"),
3411            Quantity::from(10),
3412            UnixNanos::from(2_000),
3413            UnixNanos::from(2_000),
3414        );
3415        let bar_earlier = Bar::new(
3416            bar_type,
3417            Price::from("200.00"),
3418            Price::from("210.00"),
3419            Price::from("190.00"),
3420            Price::from("205.00"),
3421            Quantity::from(50),
3422            UnixNanos::from(1_000),
3423            UnixNanos::from(1_000),
3424        );
3425
3426        builder.update_bar(bar_later, bar_later.volume, bar_later.ts_init);
3427        builder.update_bar(bar_earlier, bar_earlier.volume, bar_earlier.ts_init);
3428
3429        assert_eq!(builder.ts_last, 2_000);
3430        assert_eq!(builder.count, 1);
3431        assert_eq!(builder.volume, Quantity::from(10));
3432    }
3433
3434    #[rstest]
3435    #[case::spread_zero_inactive(
3436        Decimal::ZERO,
3437        ContinuousFutureAdjustmentType::BackwardSpread,
3438        false
3439    )]
3440    #[case::spread_positive_active(
3441        Decimal::new(150, 2), // 1.50
3442        ContinuousFutureAdjustmentType::BackwardSpread,
3443        true,
3444    )]
3445    #[case::spread_negative_active(
3446        Decimal::new(-250, 2), // -2.50
3447        ContinuousFutureAdjustmentType::ForwardSpread,
3448        true,
3449    )]
3450    #[case::spread_sub_precision_inactive(
3451        // 1e-28 scales to 0 raw under banker's rounding, so should be inactive.
3452        Decimal::new(1, 28),
3453        ContinuousFutureAdjustmentType::BackwardSpread,
3454        false,
3455    )]
3456    #[case::ratio_one_inactive(Decimal::ONE, ContinuousFutureAdjustmentType::BackwardRatio, false)]
3457    #[case::ratio_non_one_active(
3458        Decimal::new(105, 2), // 1.05
3459        ContinuousFutureAdjustmentType::ForwardRatio,
3460        true,
3461    )]
3462    fn test_bar_builder_set_adjustment_active_flag(
3463        equity_aapl: Equity,
3464        #[case] adjustment: Decimal,
3465        #[case] mode: ContinuousFutureAdjustmentType,
3466        #[case] expected_active: bool,
3467    ) {
3468        let instrument = InstrumentAny::Equity(equity_aapl);
3469        let bar_type = BarType::new(
3470            instrument.id(),
3471            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3472            AggregationSource::Internal,
3473        );
3474        let mut builder = BarBuilder::new(bar_type, 2, 0);
3475
3476        builder.set_adjustment(adjustment, mode);
3477
3478        assert_eq!(builder.adjustment_active, expected_active);
3479        assert_eq!(builder.adjustment_is_ratio, mode.is_ratio());
3480    }
3481
3482    #[rstest]
3483    fn test_bar_builder_set_adjustment_mode_switch_resets_flags(equity_aapl: Equity) {
3484        let instrument = InstrumentAny::Equity(equity_aapl);
3485        let bar_type = BarType::new(
3486            instrument.id(),
3487            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3488            AggregationSource::Internal,
3489        );
3490        let mut builder = BarBuilder::new(bar_type, 2, 0);
3491
3492        // ratio -> spread: subsequent update must shift, not scale.
3493        builder.set_adjustment(
3494            Decimal::new(150, 2), // 1.50
3495            ContinuousFutureAdjustmentType::BackwardRatio,
3496        );
3497        builder.set_adjustment(
3498            Decimal::new(50, 2), // +0.50
3499            ContinuousFutureAdjustmentType::BackwardSpread,
3500        );
3501        assert!(!builder.adjustment_is_ratio);
3502        builder.update(Price::from("100.00"), Quantity::from(1), 1_000.into());
3503        assert_eq!(builder.build_now().close, Price::from("100.50"));
3504
3505        // spread -> ratio: subsequent update must scale, not shift.
3506        builder.set_adjustment(
3507            Decimal::new(11, 1), // 1.1
3508            ContinuousFutureAdjustmentType::ForwardRatio,
3509        );
3510        assert!(builder.adjustment_is_ratio);
3511        builder.update(Price::from("100.00"), Quantity::from(1), 2_000.into());
3512        assert_eq!(builder.build_now().close, Price::from("110.00"));
3513    }
3514
3515    #[cfg(feature = "defi")]
3516    #[rstest]
3517    fn test_bar_builder_spread_preserves_legacy_native_raw_units(equity_aapl: Equity) {
3518        let bar_type = BarType::new(
3519            equity_aapl.id(),
3520            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3521            AggregationSource::Internal,
3522        );
3523
3524        let mut builder = BarBuilder::new(bar_type, 18, 0);
3525        builder.set_adjustment(Decimal::ONE, ContinuousFutureAdjustmentType::BackwardSpread);
3526        let adjusted =
3527            builder.apply_adjustment_to_price(Price::from_raw(1_000_000_000_000_000_000, 18));
3528        // Preserve the legacy fixed-scale offset, not a native-scale one-unit adjustment
3529        assert_eq!(adjusted.raw(), 1_010_000_000_000_000_000);
3530        assert_eq!(adjusted.precision, 18);
3531    }
3532
3533    #[rstest]
3534    #[should_panic(expected = "Continuous-future adjustment exceeds Price bounds")]
3535    fn test_bar_builder_spread_rejects_out_of_domain_price(equity_aapl: Equity) {
3536        let bar_type = BarType::new(
3537            equity_aapl.id(),
3538            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3539            AggregationSource::Internal,
3540        );
3541
3542        let mut builder = BarBuilder::new(bar_type, 2, 0);
3543        builder.set_adjustment(Decimal::ONE, ContinuousFutureAdjustmentType::BackwardSpread);
3544        builder.apply_adjustment_to_price(Price::from_raw(PRICE_RAW_MAX, 2));
3545    }
3546
3547    #[cfg(feature = "defi")]
3548    #[rstest]
3549    #[case(BarAggregation::Volume)]
3550    #[case(BarAggregation::VolumeImbalance)]
3551    #[case(BarAggregation::VolumeRuns)]
3552    fn test_volume_aggregators_preserve_legacy_native_raw_threshold(
3553        #[case] aggregation: BarAggregation,
3554        equity_aapl: Equity,
3555    ) {
3556        let bar_type = BarType::new(
3557            equity_aapl.id(),
3558            BarSpecification::new(1, aggregation, PriceType::Last),
3559            AggregationSource::Internal,
3560        );
3561        let (handler, record) = recording_handler();
3562
3563        let mut aggregator: Box<dyn BarAggregator> = match aggregation {
3564            BarAggregation::Volume => Box::new(VolumeBarAggregator::new(bar_type, 2, 18, record)),
3565            BarAggregation::VolumeImbalance => {
3566                Box::new(VolumeImbalanceBarAggregator::new(bar_type, 2, 18, record))
3567            }
3568            BarAggregation::VolumeRuns => {
3569                Box::new(VolumeRunsBarAggregator::new(bar_type, 2, 18, record))
3570            }
3571            _ => unreachable!(),
3572        };
3573
3574        // Preserve the legacy threshold: 0.01 native units for a step of one
3575        let size = Quantity::from_raw(FIXED_SCALAR as QuantityRaw, 18);
3576        aggregator.handle_trade(TradeTick {
3577            price: Price::from("1.00"),
3578            size,
3579            aggressor_side: AggressorSide::Buy,
3580            ..TradeTick::default()
3581        });
3582
3583        let bars = handler.lock();
3584        assert_eq!(bars.len(), 1);
3585        assert_eq!(bars[0].volume, size);
3586        assert_eq!(bars[0].volume.precision, 18);
3587    }
3588
3589    #[rstest]
3590    fn test_bar_builder_update_applies_backward_spread_adjustment(equity_aapl: Equity) {
3591        let instrument = InstrumentAny::Equity(equity_aapl);
3592        let bar_type = BarType::new(
3593            instrument.id(),
3594            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3595            AggregationSource::Internal,
3596        );
3597        let mut builder = BarBuilder::new(bar_type, 2, 0);
3598
3599        builder.set_adjustment(
3600            Decimal::new(250, 2), // +2.50
3601            ContinuousFutureAdjustmentType::BackwardSpread,
3602        );
3603
3604        builder.update(Price::from("100.00"), Quantity::from(1), 1_000.into());
3605        builder.update(Price::from("99.00"), Quantity::from(1), 2_000.into());
3606        builder.update(Price::from("101.00"), Quantity::from(1), 3_000.into());
3607
3608        let bar = builder.build_now();
3609        assert_eq!(bar.open, Price::from("102.50"));
3610        assert_eq!(bar.high, Price::from("103.50"));
3611        assert_eq!(bar.low, Price::from("101.50"));
3612        assert_eq!(bar.close, Price::from("103.50"));
3613    }
3614
3615    #[rstest]
3616    fn test_bar_builder_update_applies_forward_ratio_adjustment(equity_aapl: Equity) {
3617        let instrument = InstrumentAny::Equity(equity_aapl);
3618        let bar_type = BarType::new(
3619            instrument.id(),
3620            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3621            AggregationSource::Internal,
3622        );
3623        let mut builder = BarBuilder::new(bar_type, 2, 0);
3624
3625        builder.set_adjustment(
3626            Decimal::new(11, 1), // 1.1
3627            ContinuousFutureAdjustmentType::ForwardRatio,
3628        );
3629
3630        builder.update(Price::from("100.00"), Quantity::from(1), 1_000.into());
3631        builder.update(Price::from("90.00"), Quantity::from(1), 2_000.into());
3632        builder.update(Price::from("110.00"), Quantity::from(1), 3_000.into());
3633
3634        let bar = builder.build_now();
3635        assert_eq!(bar.open, Price::from("110.00"));
3636        assert_eq!(bar.high, Price::from("121.00"));
3637        assert_eq!(bar.low, Price::from("99.00"));
3638        assert_eq!(bar.close, Price::from("121.00"));
3639    }
3640
3641    #[rstest]
3642    fn test_bar_builder_update_bar_applies_adjustment_to_ohlc(equity_aapl: Equity) {
3643        let instrument = InstrumentAny::Equity(equity_aapl);
3644        let bar_type = BarType::new(
3645            instrument.id(),
3646            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3647            AggregationSource::Internal,
3648        );
3649        let mut builder = BarBuilder::new(bar_type, 2, 0);
3650
3651        builder.set_adjustment(
3652            Decimal::new(-100, 2), // -1.00
3653            ContinuousFutureAdjustmentType::BackwardSpread,
3654        );
3655
3656        let input = Bar::new(
3657            bar_type,
3658            Price::from("100.00"),
3659            Price::from("105.00"),
3660            Price::from("99.00"),
3661            Price::from("102.00"),
3662            Quantity::from(10),
3663            UnixNanos::from(1_000),
3664            UnixNanos::from(1_000),
3665        );
3666        builder.update_bar(input, input.volume, input.ts_init);
3667
3668        let bar = builder.build_now();
3669        assert_eq!(bar.open, Price::from("99.00"));
3670        assert_eq!(bar.high, Price::from("104.00"));
3671        assert_eq!(bar.low, Price::from("98.00"));
3672        assert_eq!(bar.close, Price::from("101.00"));
3673    }
3674
3675    #[rstest]
3676    fn test_bar_builder_reset_retains_adjustment(equity_aapl: Equity) {
3677        let instrument = InstrumentAny::Equity(equity_aapl);
3678        let bar_type = BarType::new(
3679            instrument.id(),
3680            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3681            AggregationSource::Internal,
3682        );
3683        let mut builder = BarBuilder::new(bar_type, 2, 0);
3684
3685        builder.set_adjustment(
3686            Decimal::new(500, 2), // +5.00
3687            ContinuousFutureAdjustmentType::BackwardSpread,
3688        );
3689        builder.update(Price::from("100.00"), Quantity::from(1), 1_000.into());
3690        let bar_one = builder.build_now();
3691        assert_eq!(bar_one.close, Price::from("105.00"));
3692
3693        // Adjustment must persist across the reset triggered by build_now.
3694        assert!(builder.adjustment_active);
3695
3696        builder.update(Price::from("110.00"), Quantity::from(1), 2_000.into());
3697        let bar_two = builder.build_now();
3698        assert_eq!(bar_two.close, Price::from("115.00"));
3699    }
3700
3701    #[rstest]
3702    fn test_bar_builder_update_bar_applies_ratio_adjustment(equity_aapl: Equity) {
3703        let instrument = InstrumentAny::Equity(equity_aapl);
3704        let bar_type = BarType::new(
3705            instrument.id(),
3706            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3707            AggregationSource::Internal,
3708        );
3709        let mut builder = BarBuilder::new(bar_type, 2, 0);
3710
3711        builder.set_adjustment(
3712            Decimal::new(11, 1), // 1.1
3713            ContinuousFutureAdjustmentType::ForwardRatio,
3714        );
3715
3716        let input = Bar::new(
3717            bar_type,
3718            Price::from("100.00"),
3719            Price::from("110.00"),
3720            Price::from("90.00"),
3721            Price::from("105.00"),
3722            Quantity::from(10),
3723            UnixNanos::from(1_000),
3724            UnixNanos::from(1_000),
3725        );
3726        builder.update_bar(input, input.volume, input.ts_init);
3727
3728        let bar = builder.build_now();
3729        assert_eq!(bar.open, Price::from("110.00"));
3730        assert_eq!(bar.high, Price::from("121.00"));
3731        assert_eq!(bar.low, Price::from("99.00"));
3732        assert_eq!(bar.close, Price::from("115.50"));
3733    }
3734
3735    #[rstest]
3736    fn test_bar_builder_spread_below_zero_representable(equity_aapl: Equity) {
3737        // Backward-spread offsets that push prices below zero must stay representable in PriceRaw
3738        let instrument = InstrumentAny::Equity(equity_aapl);
3739        let bar_type = BarType::new(
3740            instrument.id(),
3741            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3742            AggregationSource::Internal,
3743        );
3744        let mut builder = BarBuilder::new(bar_type, 2, 0);
3745
3746        builder.set_adjustment(
3747            Decimal::new(-15000, 2), // -150.00
3748            ContinuousFutureAdjustmentType::BackwardSpread,
3749        );
3750
3751        builder.update(Price::from("100.00"), Quantity::from(1), 1_000.into());
3752        let bar = builder.build_now();
3753        assert_eq!(bar.close, Price::from("-50.00"));
3754        assert!(bar.close.is_negative());
3755        assert_eq!(bar.close.precision, 2);
3756    }
3757
3758    #[rstest]
3759    fn test_bar_builder_build_promotes_close_above_high_from_previous_close(equity_aapl: Equity) {
3760        let instrument = InstrumentAny::Equity(equity_aapl);
3761        let bar_type = BarType::new(
3762            instrument.id(),
3763            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3764            AggregationSource::Internal,
3765        );
3766        let mut builder = BarBuilder::new(bar_type, 2, 0);
3767
3768        builder.update(
3769            Price::from("110.00"),
3770            Quantity::from(1),
3771            UnixNanos::from(100),
3772        );
3773        builder.build_now();
3774
3775        builder.update(
3776            Price::from("100.00"),
3777            Quantity::from(1),
3778            UnixNanos::from(200),
3779        );
3780        builder.update(
3781            Price::from("101.00"),
3782            Quantity::from(1),
3783            UnixNanos::from(300),
3784        );
3785        builder.update(
3786            Price::from("200.00"),
3787            Quantity::from(1),
3788            UnixNanos::from(400),
3789        );
3790
3791        let bar = builder.build_now();
3792        assert_eq!(bar.open, Price::from("100.00"));
3793        assert_eq!(bar.high, Price::from("200.00"));
3794        assert_eq!(bar.low, Price::from("100.00"));
3795        assert_eq!(bar.close, Price::from("200.00"));
3796    }
3797
3798    #[rstest]
3799    fn test_bar_builder_build_clamps_low_to_close(equity_aapl: Equity) {
3800        // On `build`, if `close < low` the low is pulled down to close.
3801        // Reaching this branch requires bypassing `update`'s low tracking (e.g. via bar updates where
3802        // a later bar's close is below the accumulated low). We simulate by direct field assignment.
3803        let instrument = InstrumentAny::Equity(equity_aapl);
3804        let bar_type = BarType::new(
3805            instrument.id(),
3806            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
3807            AggregationSource::Internal,
3808        );
3809        let mut builder = BarBuilder::new(bar_type, 2, 0);
3810
3811        builder.update(
3812            Price::from("100.00"),
3813            Quantity::from(1),
3814            UnixNanos::from(100),
3815        );
3816        builder.close = Some(Price::from("50.00"));
3817
3818        let bar = builder.build_now();
3819        assert_eq!(bar.low, Price::from("50.00"));
3820        assert_eq!(bar.close, Price::from("50.00"));
3821        assert!(bar.low <= bar.open);
3822    }
3823
3824    #[rstest]
3825    fn test_tick_bar_aggregator_handle_trade_when_step_count_below_threshold(equity_aapl: Equity) {
3826        let instrument = InstrumentAny::Equity(equity_aapl);
3827        let bar_spec = BarSpecification::new(3, BarAggregation::Tick, PriceType::Last);
3828        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
3829        let (handler, record) = recording_handler();
3830
3831        let mut aggregator = TickBarAggregator::new(
3832            bar_type,
3833            instrument.price_precision(),
3834            instrument.size_precision(),
3835            record,
3836        );
3837
3838        let trade = TradeTick::default();
3839        aggregator.handle_trade(trade);
3840
3841        let handler_guard = handler.lock();
3842        assert_eq!(handler_guard.len(), 0);
3843    }
3844
3845    #[rstest]
3846    fn test_tick_bar_aggregator_handle_trade_when_step_count_reached(equity_aapl: Equity) {
3847        let instrument = InstrumentAny::Equity(equity_aapl);
3848        let bar_spec = BarSpecification::new(3, BarAggregation::Tick, PriceType::Last);
3849        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
3850        let (handler, record) = recording_handler();
3851
3852        let mut aggregator = TickBarAggregator::new(
3853            bar_type,
3854            instrument.price_precision(),
3855            instrument.size_precision(),
3856            record,
3857        );
3858
3859        let trade = TradeTick::default();
3860        aggregator.handle_trade(trade);
3861        aggregator.handle_trade(trade);
3862        aggregator.handle_trade(trade);
3863
3864        let handler_guard = handler.lock();
3865        let bar = handler_guard.first().unwrap();
3866        assert_eq!(handler_guard.len(), 1);
3867        assert_eq!(bar.open, trade.price);
3868        assert_eq!(bar.high, trade.price);
3869        assert_eq!(bar.low, trade.price);
3870        assert_eq!(bar.close, trade.price);
3871        assert_eq!(bar.volume, Quantity::from(300000));
3872        assert_eq!(bar.ts_event, trade.ts_event);
3873        assert_eq!(bar.ts_init, trade.ts_init);
3874    }
3875
3876    #[rstest]
3877    fn test_tick_bar_aggregator_aggregates_to_step_size(equity_aapl: Equity) {
3878        let instrument = InstrumentAny::Equity(equity_aapl);
3879        let bar_spec = BarSpecification::new(3, BarAggregation::Tick, PriceType::Last);
3880        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
3881        let (handler, record) = recording_handler();
3882
3883        let mut aggregator = TickBarAggregator::new(
3884            bar_type,
3885            instrument.price_precision(),
3886            instrument.size_precision(),
3887            record,
3888        );
3889
3890        aggregator.update(
3891            Price::from("1.00001"),
3892            Quantity::from(1),
3893            UnixNanos::default(),
3894        );
3895        aggregator.update(
3896            Price::from("1.00002"),
3897            Quantity::from(1),
3898            UnixNanos::from(1000),
3899        );
3900        aggregator.update(
3901            Price::from("1.00003"),
3902            Quantity::from(1),
3903            UnixNanos::from(2000),
3904        );
3905
3906        let handler_guard = handler.lock();
3907        assert_eq!(handler_guard.len(), 1);
3908
3909        let bar = handler_guard.first().unwrap();
3910        assert_eq!(bar.open, Price::from("1.00001"));
3911        assert_eq!(bar.high, Price::from("1.00003"));
3912        assert_eq!(bar.low, Price::from("1.00001"));
3913        assert_eq!(bar.close, Price::from("1.00003"));
3914        assert_eq!(bar.volume, Quantity::from(3));
3915    }
3916
3917    #[rstest]
3918    fn test_tick_bar_aggregator_resets_after_bar_created(equity_aapl: Equity) {
3919        let instrument = InstrumentAny::Equity(equity_aapl);
3920        let bar_spec = BarSpecification::new(2, BarAggregation::Tick, PriceType::Last);
3921        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
3922        let (handler, record) = recording_handler();
3923
3924        let mut aggregator = TickBarAggregator::new(
3925            bar_type,
3926            instrument.price_precision(),
3927            instrument.size_precision(),
3928            record,
3929        );
3930
3931        aggregator.update(
3932            Price::from("1.00001"),
3933            Quantity::from(1),
3934            UnixNanos::default(),
3935        );
3936        aggregator.update(
3937            Price::from("1.00002"),
3938            Quantity::from(1),
3939            UnixNanos::from(1000),
3940        );
3941        aggregator.update(
3942            Price::from("1.00003"),
3943            Quantity::from(1),
3944            UnixNanos::from(2000),
3945        );
3946        aggregator.update(
3947            Price::from("1.00004"),
3948            Quantity::from(1),
3949            UnixNanos::from(3000),
3950        );
3951
3952        let handler_guard = handler.lock();
3953        assert_eq!(handler_guard.len(), 2);
3954
3955        let bar1 = &handler_guard[0];
3956        assert_eq!(bar1.open, Price::from("1.00001"));
3957        assert_eq!(bar1.close, Price::from("1.00002"));
3958        assert_eq!(bar1.volume, Quantity::from(2));
3959
3960        let bar2 = &handler_guard[1];
3961        assert_eq!(bar2.open, Price::from("1.00003"));
3962        assert_eq!(bar2.close, Price::from("1.00004"));
3963        assert_eq!(bar2.volume, Quantity::from(2));
3964    }
3965
3966    #[rstest]
3967    #[case(PriceType::Bid, Price::from("100.00"), Quantity::from(10))]
3968    #[case(PriceType::Ask, Price::from("102.00"), Quantity::from(14))]
3969    #[case(PriceType::Mid, Price::from("101.000"), Quantity::from("12.0"))]
3970    fn test_bar_aggregator_handle_quote_selects_price_and_size(
3971        equity_aapl: Equity,
3972        #[case] price_type: PriceType,
3973        #[case] expected_price: Price,
3974        #[case] expected_size: Quantity,
3975    ) {
3976        let instrument = InstrumentAny::Equity(equity_aapl);
3977        let bar_type = BarType::new(
3978            instrument.id(),
3979            BarSpecification::new(1, BarAggregation::Tick, price_type),
3980            AggregationSource::Internal,
3981        );
3982        let (handler, record) = recording_handler();
3983        let mut aggregator = TickBarAggregator::new(
3984            bar_type,
3985            instrument.price_precision(),
3986            instrument.size_precision(),
3987            record,
3988        );
3989        let ts_init = UnixNanos::from(2_000);
3990        let quote = QuoteTick::new(
3991            instrument.id(),
3992            Price::from("100.00"),
3993            Price::from("102.00"),
3994            Quantity::from(10),
3995            Quantity::from(14),
3996            UnixNanos::from(1_000),
3997            ts_init,
3998        );
3999
4000        aggregator.handle_quote(quote);
4001
4002        let bars = handler.lock();
4003        assert_eq!(bars.len(), 1);
4004        assert_eq!(bars[0].open, expected_price);
4005        assert_eq!(bars[0].high, expected_price);
4006        assert_eq!(bars[0].low, expected_price);
4007        assert_eq!(bars[0].close, expected_price);
4008        assert_eq!(bars[0].volume, expected_size);
4009        assert_eq!(bars[0].ts_event, ts_init);
4010        assert_eq!(bars[0].ts_init, ts_init);
4011    }
4012
4013    #[rstest]
4014    fn test_bar_aggregator_handle_quote_rejects_last_price(equity_aapl: Equity) {
4015        let instrument = InstrumentAny::Equity(equity_aapl);
4016        let bar_type = BarType::new(
4017            instrument.id(),
4018            BarSpecification::new(1, BarAggregation::Tick, PriceType::Last),
4019            AggregationSource::Internal,
4020        );
4021        let (handler, record) = recording_handler();
4022        let mut aggregator = TickBarAggregator::new(
4023            bar_type,
4024            instrument.price_precision(),
4025            instrument.size_precision(),
4026            record,
4027        );
4028
4029        aggregator.handle_quote(QuoteTick::new(
4030            instrument.id(),
4031            Price::from("100.00"),
4032            Price::from("102.00"),
4033            Quantity::from(10),
4034            Quantity::from(14),
4035            UnixNanos::from(1_000),
4036            UnixNanos::from(2_000),
4037        ));
4038
4039        assert!(handler.lock().is_empty());
4040        assert!(!aggregator.core.builder.initialized);
4041        assert_eq!(aggregator.core.builder.count, 0);
4042        assert_eq!(aggregator.core.builder.volume, Quantity::zero(0));
4043    }
4044
4045    #[rstest]
4046    fn test_non_time_bar_aggregators_use_historical_handler(
4047        equity_aapl: Equity,
4048        audusd_sim: CurrencyPair,
4049    ) {
4050        let instrument = InstrumentAny::Equity(equity_aapl);
4051        let instrument_id = instrument.id();
4052        let price_precision = instrument.price_precision();
4053        let size_precision = instrument.size_precision();
4054        let make_sink = |bars: Arc<Mutex<Vec<Bar>>>| {
4055            move |bar: Bar| {
4056                bars.lock().push(bar);
4057            }
4058        };
4059        let make_trade = |price: &str, size: i64, ts: u64| TradeTick {
4060            instrument_id,
4061            price: Price::from(price),
4062            size: Quantity::from(size),
4063            aggressor_side: AggressorSide::Buy,
4064            ts_event: UnixNanos::from(ts),
4065            ts_init: UnixNanos::from(ts),
4066            ..TradeTick::default()
4067        };
4068
4069        macro_rules! assert_historical_sink_receives {
4070            ($name:expr, $aggregator:expr, $update:expr) => {{
4071                let initial_bars = Arc::new(Mutex::new(Vec::new()));
4072                let historical_bars = Arc::new(Mutex::new(Vec::new()));
4073                let mut aggregator = $aggregator(Arc::clone(&initial_bars));
4074                aggregator
4075                    .set_historical_mode(true, Box::new(make_sink(Arc::clone(&historical_bars))));
4076                {
4077                    let aggregator: &mut dyn BarAggregator = &mut aggregator;
4078                    $update(aggregator);
4079                }
4080
4081                assert_eq!(initial_bars.lock().len(), 0, "{}", $name,);
4082                assert_eq!(historical_bars.lock().len(), 1, "{}", $name,);
4083            }};
4084        }
4085
4086        let tick_type = BarType::new(
4087            instrument_id,
4088            BarSpecification::new(1, BarAggregation::Tick, PriceType::Last),
4089            AggregationSource::Internal,
4090        );
4091        assert_historical_sink_receives!(
4092            "TickBarAggregator",
4093            |bars| TickBarAggregator::new(
4094                tick_type,
4095                price_precision,
4096                size_precision,
4097                make_sink(bars)
4098            ),
4099            |aggregator: &mut dyn BarAggregator| {
4100                aggregator.handle_trade(make_trade("100.00", 1, 1_000));
4101            }
4102        );
4103
4104        let tick_imbalance_type = BarType::new(
4105            instrument_id,
4106            BarSpecification::new(1, BarAggregation::TickImbalance, PriceType::Last),
4107            AggregationSource::Internal,
4108        );
4109        assert_historical_sink_receives!(
4110            "TickImbalanceBarAggregator",
4111            |bars| TickImbalanceBarAggregator::new(
4112                tick_imbalance_type,
4113                price_precision,
4114                size_precision,
4115                make_sink(bars),
4116            ),
4117            |aggregator: &mut dyn BarAggregator| {
4118                aggregator.handle_trade(make_trade("100.00", 1, 1_000));
4119            }
4120        );
4121
4122        let tick_runs_type = BarType::new(
4123            instrument_id,
4124            BarSpecification::new(1, BarAggregation::TickRuns, PriceType::Last),
4125            AggregationSource::Internal,
4126        );
4127        assert_historical_sink_receives!(
4128            "TickRunsBarAggregator",
4129            |bars| TickRunsBarAggregator::new(
4130                tick_runs_type,
4131                price_precision,
4132                size_precision,
4133                make_sink(bars),
4134            ),
4135            |aggregator: &mut dyn BarAggregator| {
4136                aggregator.handle_trade(make_trade("100.00", 1, 1_000));
4137            }
4138        );
4139
4140        let volume_type = BarType::new(
4141            instrument_id,
4142            BarSpecification::new(1, BarAggregation::Volume, PriceType::Last),
4143            AggregationSource::Internal,
4144        );
4145        assert_historical_sink_receives!(
4146            "VolumeBarAggregator",
4147            |bars| VolumeBarAggregator::new(
4148                volume_type,
4149                price_precision,
4150                size_precision,
4151                make_sink(bars),
4152            ),
4153            |aggregator: &mut dyn BarAggregator| {
4154                aggregator.handle_trade(make_trade("100.00", 1, 1_000));
4155            }
4156        );
4157
4158        let volume_imbalance_type = BarType::new(
4159            instrument_id,
4160            BarSpecification::new(1, BarAggregation::VolumeImbalance, PriceType::Last),
4161            AggregationSource::Internal,
4162        );
4163        assert_historical_sink_receives!(
4164            "VolumeImbalanceBarAggregator",
4165            |bars| VolumeImbalanceBarAggregator::new(
4166                volume_imbalance_type,
4167                price_precision,
4168                size_precision,
4169                make_sink(bars),
4170            ),
4171            |aggregator: &mut dyn BarAggregator| {
4172                aggregator.handle_trade(make_trade("100.00", 1, 1_000));
4173            }
4174        );
4175
4176        let volume_runs_type = BarType::new(
4177            instrument_id,
4178            BarSpecification::new(1, BarAggregation::VolumeRuns, PriceType::Last),
4179            AggregationSource::Internal,
4180        );
4181        assert_historical_sink_receives!(
4182            "VolumeRunsBarAggregator",
4183            |bars| VolumeRunsBarAggregator::new(
4184                volume_runs_type,
4185                price_precision,
4186                size_precision,
4187                make_sink(bars),
4188            ),
4189            |aggregator: &mut dyn BarAggregator| {
4190                aggregator.handle_trade(make_trade("100.00", 1, 1_000));
4191            }
4192        );
4193
4194        let value_type = BarType::new(
4195            instrument_id,
4196            BarSpecification::new(100, BarAggregation::Value, PriceType::Last),
4197            AggregationSource::Internal,
4198        );
4199        assert_historical_sink_receives!(
4200            "ValueBarAggregator",
4201            |bars| ValueBarAggregator::new(
4202                value_type,
4203                price_precision,
4204                size_precision,
4205                make_sink(bars)
4206            ),
4207            |aggregator: &mut dyn BarAggregator| {
4208                aggregator.handle_trade(make_trade("100.00", 1, 1_000));
4209            }
4210        );
4211
4212        let value_imbalance_type = BarType::new(
4213            instrument_id,
4214            BarSpecification::new(100, BarAggregation::ValueImbalance, PriceType::Last),
4215            AggregationSource::Internal,
4216        );
4217        assert_historical_sink_receives!(
4218            "ValueImbalanceBarAggregator",
4219            |bars| ValueImbalanceBarAggregator::new(
4220                value_imbalance_type,
4221                price_precision,
4222                size_precision,
4223                make_sink(bars),
4224            ),
4225            |aggregator: &mut dyn BarAggregator| {
4226                aggregator.handle_trade(make_trade("100.00", 1, 1_000));
4227            }
4228        );
4229
4230        let value_runs_type = BarType::new(
4231            instrument_id,
4232            BarSpecification::new(100, BarAggregation::ValueRuns, PriceType::Last),
4233            AggregationSource::Internal,
4234        );
4235        assert_historical_sink_receives!(
4236            "ValueRunsBarAggregator",
4237            |bars| ValueRunsBarAggregator::new(
4238                value_runs_type,
4239                price_precision,
4240                size_precision,
4241                make_sink(bars),
4242            ),
4243            |aggregator: &mut dyn BarAggregator| {
4244                aggregator.handle_trade(make_trade("100.00", 1, 1_000));
4245            }
4246        );
4247
4248        let fx = InstrumentAny::CurrencyPair(audusd_sim);
4249        let renko_type = BarType::new(
4250            fx.id(),
4251            BarSpecification::new(10, BarAggregation::Renko, PriceType::Mid),
4252            AggregationSource::Internal,
4253        );
4254        let fx_price_precision = fx.price_precision();
4255        let fx_size_precision = fx.size_precision();
4256        let fx_price_increment = fx.price_increment();
4257        assert_historical_sink_receives!(
4258            "RenkoBarAggregator",
4259            |bars| RenkoBarAggregator::new(
4260                renko_type,
4261                fx_price_precision,
4262                fx_size_precision,
4263                fx_price_increment,
4264                make_sink(bars),
4265            ),
4266            |aggregator: &mut dyn BarAggregator| {
4267                aggregator.update(
4268                    Price::from("1.00000"),
4269                    Quantity::from(1),
4270                    UnixNanos::from(1_000),
4271                );
4272                aggregator.update(
4273                    Price::from("1.00010"),
4274                    Quantity::from(1),
4275                    UnixNanos::from(2_000),
4276                );
4277            }
4278        );
4279    }
4280
4281    #[rstest]
4282    fn test_tick_imbalance_bar_aggregator_emits_at_threshold(equity_aapl: Equity) {
4283        let instrument = InstrumentAny::Equity(equity_aapl);
4284        let bar_spec = BarSpecification::new(2, BarAggregation::TickImbalance, PriceType::Last);
4285        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4286        let (handler, record) = recording_handler();
4287
4288        let mut aggregator = TickImbalanceBarAggregator::new(
4289            bar_type,
4290            instrument.price_precision(),
4291            instrument.size_precision(),
4292            record,
4293        );
4294
4295        let trade = TradeTick::default();
4296        aggregator.handle_trade(trade);
4297        aggregator.handle_trade(trade);
4298
4299        let handler_guard = handler.lock();
4300        assert_eq!(handler_guard.len(), 1);
4301        let bar = handler_guard.first().unwrap();
4302        assert_eq!(bar.volume, Quantity::from(200000));
4303    }
4304
4305    #[rstest]
4306    fn test_tick_imbalance_bar_aggregator_handles_seller_direction(equity_aapl: Equity) {
4307        let instrument = InstrumentAny::Equity(equity_aapl);
4308        let bar_spec = BarSpecification::new(1, BarAggregation::TickImbalance, PriceType::Last);
4309        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4310        let (handler, record) = recording_handler();
4311
4312        let mut aggregator = TickImbalanceBarAggregator::new(
4313            bar_type,
4314            instrument.price_precision(),
4315            instrument.size_precision(),
4316            record,
4317        );
4318
4319        let sell = TradeTick {
4320            aggressor_side: AggressorSide::Sell,
4321            ..TradeTick::default()
4322        };
4323
4324        aggregator.handle_trade(sell);
4325
4326        let handler_guard = handler.lock();
4327        assert_eq!(handler_guard.len(), 1);
4328    }
4329
4330    #[rstest]
4331    fn test_tick_runs_bar_aggregator_resets_on_side_change(equity_aapl: Equity) {
4332        let instrument = InstrumentAny::Equity(equity_aapl);
4333        let bar_spec = BarSpecification::new(2, BarAggregation::TickRuns, PriceType::Last);
4334        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4335        let (handler, record) = recording_handler();
4336
4337        let mut aggregator = TickRunsBarAggregator::new(
4338            bar_type,
4339            instrument.price_precision(),
4340            instrument.size_precision(),
4341            record,
4342        );
4343
4344        let buy = TradeTick {
4345            instrument_id: instrument.id(),
4346            price: Price::from("100.00"),
4347            size: Quantity::from(1),
4348            ts_event: UnixNanos::from(1_000),
4349            ts_init: UnixNanos::from(1_000),
4350            ..TradeTick::default()
4351        };
4352        let sell_one = TradeTick {
4353            price: Price::from("200.00"),
4354            size: Quantity::from(2),
4355            aggressor_side: AggressorSide::Sell,
4356            ts_event: UnixNanos::from(2_000),
4357            ts_init: UnixNanos::from(2_000),
4358            ..buy
4359        };
4360        let sell_two = TradeTick {
4361            price: Price::from("201.00"),
4362            size: Quantity::from(3),
4363            ts_event: UnixNanos::from(3_000),
4364            ts_init: UnixNanos::from(3_000),
4365            ..sell_one
4366        };
4367
4368        aggregator.handle_trade(buy);
4369        aggregator.handle_trade(sell_one);
4370        aggregator.handle_trade(sell_two);
4371
4372        let handler_guard = handler.lock();
4373        assert_eq!(handler_guard.len(), 1);
4374        assert_eq!(handler_guard[0].open, Price::from("200.00"));
4375        assert_eq!(handler_guard[0].high, Price::from("201.00"));
4376        assert_eq!(handler_guard[0].low, Price::from("200.00"));
4377        assert_eq!(handler_guard[0].close, Price::from("201.00"));
4378        assert_eq!(handler_guard[0].volume, Quantity::from(5));
4379        assert_eq!(handler_guard[0].ts_event, UnixNanos::from(3_000));
4380        assert_eq!(handler_guard[0].ts_init, UnixNanos::from(3_000));
4381    }
4382
4383    #[rstest]
4384    fn test_tick_runs_bar_aggregator_volume_conservation(equity_aapl: Equity) {
4385        let instrument = InstrumentAny::Equity(equity_aapl);
4386        let bar_spec = BarSpecification::new(2, BarAggregation::TickRuns, PriceType::Last);
4387        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4388        let (handler, record) = recording_handler();
4389
4390        let mut aggregator = TickRunsBarAggregator::new(
4391            bar_type,
4392            instrument.price_precision(),
4393            instrument.size_precision(),
4394            record,
4395        );
4396
4397        let buy = TradeTick {
4398            size: Quantity::from(1),
4399            ..TradeTick::default()
4400        };
4401        let sell = TradeTick {
4402            aggressor_side: AggressorSide::Sell,
4403            size: Quantity::from(1),
4404            ..buy
4405        };
4406
4407        aggregator.handle_trade(buy);
4408        aggregator.handle_trade(buy);
4409        aggregator.handle_trade(sell);
4410        aggregator.handle_trade(sell);
4411
4412        let handler_guard = handler.lock();
4413        assert_eq!(handler_guard.len(), 2);
4414        assert_eq!(handler_guard[0].volume, Quantity::from(2));
4415        assert_eq!(handler_guard[1].volume, Quantity::from(2));
4416    }
4417
4418    #[rstest]
4419    fn test_volume_bar_aggregator_builds_multiple_bars_from_large_update(equity_aapl: Equity) {
4420        let instrument = InstrumentAny::Equity(equity_aapl);
4421        let bar_spec = BarSpecification::new(10, BarAggregation::Volume, PriceType::Last);
4422        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4423        let (handler, record) = recording_handler();
4424
4425        let mut aggregator = VolumeBarAggregator::new(
4426            bar_type,
4427            instrument.price_precision(),
4428            instrument.size_precision(),
4429            record,
4430        );
4431
4432        aggregator.update(
4433            Price::from("1.00001"),
4434            Quantity::from(25),
4435            UnixNanos::default(),
4436        );
4437
4438        let handler_guard = handler.lock();
4439        assert_eq!(handler_guard.len(), 2);
4440        let bar1 = &handler_guard[0];
4441        assert_eq!(bar1.volume, Quantity::from(10));
4442        let bar2 = &handler_guard[1];
4443        assert_eq!(bar2.volume, Quantity::from(10));
4444    }
4445
4446    #[rstest]
4447    fn test_volume_bar_aggregator_zero_size_update_is_noop(equity_aapl: Equity) {
4448        let instrument = InstrumentAny::Equity(equity_aapl);
4449        let bar_spec = BarSpecification::new(10, BarAggregation::Volume, PriceType::Last);
4450        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4451        let (handler, record) = recording_handler();
4452
4453        let mut aggregator = VolumeBarAggregator::new(
4454            bar_type,
4455            instrument.price_precision(),
4456            instrument.size_precision(),
4457            record,
4458        );
4459
4460        aggregator.update(
4461            Price::from("100.00"),
4462            Quantity::from(0),
4463            UnixNanos::default(),
4464        );
4465
4466        let handler_guard = handler.lock();
4467        assert_eq!(handler_guard.len(), 0);
4468    }
4469
4470    #[rstest]
4471    fn test_volume_bar_aggregator_ignores_out_of_order_update(equity_aapl: Equity) {
4472        let instrument = InstrumentAny::Equity(equity_aapl);
4473        let bar_spec = BarSpecification::new(2, BarAggregation::Volume, PriceType::Last);
4474        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4475        let (handler, record) = recording_handler();
4476
4477        let mut aggregator = VolumeBarAggregator::new(
4478            bar_type,
4479            instrument.price_precision(),
4480            instrument.size_precision(),
4481            record,
4482        );
4483
4484        aggregator.update(
4485            Price::from("100.00"),
4486            Quantity::from(1),
4487            UnixNanos::from(1_000),
4488        );
4489        aggregator.update(
4490            Price::from("200.00"),
4491            Quantity::from(3),
4492            UnixNanos::from(500),
4493        );
4494
4495        let handler_guard = handler.lock();
4496        assert!(handler_guard.is_empty());
4497        assert_eq!(aggregator.core.builder.count, 1);
4498        assert_eq!(aggregator.core.builder.volume, Quantity::from(1));
4499        assert_eq!(aggregator.core.builder.close, Some(Price::from("100.00")));
4500        assert_eq!(aggregator.core.builder.ts_last, UnixNanos::from(1_000));
4501    }
4502
4503    #[rstest]
4504    fn test_volume_bar_aggregator_ignores_out_of_order_bar(equity_aapl: Equity) {
4505        let instrument = InstrumentAny::Equity(equity_aapl);
4506        let bar_spec = BarSpecification::new(2, BarAggregation::Volume, PriceType::Last);
4507        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4508        let (handler, record) = recording_handler();
4509
4510        let mut aggregator = VolumeBarAggregator::new(
4511            bar_type,
4512            instrument.price_precision(),
4513            instrument.size_precision(),
4514            record,
4515        );
4516
4517        aggregator.update(
4518            Price::from("100.00"),
4519            Quantity::from(1),
4520            UnixNanos::from(1_000),
4521        );
4522        let stale_bar = Bar::new(
4523            bar_type,
4524            Price::from("200.00"),
4525            Price::from("201.00"),
4526            Price::from("199.00"),
4527            Price::from("200.50"),
4528            Quantity::from(3),
4529            UnixNanos::from(500),
4530            UnixNanos::from(500),
4531        );
4532        aggregator.update_bar(stale_bar, stale_bar.volume, stale_bar.ts_init);
4533
4534        let handler_guard = handler.lock();
4535        assert!(handler_guard.is_empty());
4536        assert_eq!(aggregator.core.builder.count, 1);
4537        assert_eq!(aggregator.core.builder.volume, Quantity::from(1));
4538        assert_eq!(aggregator.core.builder.close, Some(Price::from("100.00")));
4539        assert_eq!(aggregator.core.builder.ts_last, UnixNanos::from(1_000));
4540    }
4541
4542    #[rstest]
4543    fn test_volume_imbalance_bar_aggregator_ignores_out_of_order_trade(equity_aapl: Equity) {
4544        let instrument = InstrumentAny::Equity(equity_aapl);
4545        let bar_spec = BarSpecification::new(2, BarAggregation::VolumeImbalance, PriceType::Last);
4546        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4547        let (handler, record) = recording_handler();
4548        let mut aggregator = VolumeImbalanceBarAggregator::new(
4549            bar_type,
4550            instrument.price_precision(),
4551            instrument.size_precision(),
4552            record,
4553        );
4554        let first = TradeTick {
4555            price: Price::from("100.00"),
4556            size: Quantity::from(1),
4557            aggressor_side: AggressorSide::Buy,
4558            ts_init: UnixNanos::from(1_000),
4559            ..TradeTick::default()
4560        };
4561        let stale = TradeTick {
4562            price: Price::from("200.00"),
4563            size: Quantity::from(2),
4564            aggressor_side: AggressorSide::Buy,
4565            ts_init: UnixNanos::from(500),
4566            ..TradeTick::default()
4567        };
4568
4569        aggregator.handle_trade(first);
4570        aggregator.handle_trade(stale);
4571
4572        assert!(handler.lock().is_empty());
4573        assert_eq!(aggregator.imbalance, Quantity::from(1));
4574        assert_eq!(aggregator.imbalance_side, AggressorSide::Buy);
4575        assert_eq!(aggregator.core.builder.volume, Quantity::from(1));
4576        assert_eq!(aggregator.core.builder.ts_last, UnixNanos::from(1_000));
4577    }
4578
4579    #[rstest]
4580    #[case(BarAggregation::TickImbalance)]
4581    #[case(BarAggregation::TickRuns)]
4582    #[case(BarAggregation::VolumeRuns)]
4583    #[case(BarAggregation::ValueImbalance)]
4584    #[case(BarAggregation::ValueRuns)]
4585    fn test_stateful_trade_aggregators_ignore_out_of_order_trade(
4586        equity_aapl: Equity,
4587        #[case] aggregation: BarAggregation,
4588    ) {
4589        let instrument = InstrumentAny::Equity(equity_aapl);
4590        let (step, price) = match aggregation {
4591            BarAggregation::ValueImbalance | BarAggregation::ValueRuns => {
4592                (100, Price::from("50.00"))
4593            }
4594            _ => (2, Price::from("100.00")),
4595        };
4596        let bar_type = BarType::new(
4597            instrument.id(),
4598            BarSpecification::new(step, aggregation, PriceType::Last),
4599            AggregationSource::Internal,
4600        );
4601        let (handler, record) = recording_handler();
4602        let make_handler = record;
4603        let mut aggregator: Box<dyn BarAggregator> = match aggregation {
4604            BarAggregation::TickImbalance => Box::new(TickImbalanceBarAggregator::new(
4605                bar_type,
4606                instrument.price_precision(),
4607                instrument.size_precision(),
4608                make_handler,
4609            )),
4610            BarAggregation::TickRuns => Box::new(TickRunsBarAggregator::new(
4611                bar_type,
4612                instrument.price_precision(),
4613                instrument.size_precision(),
4614                make_handler,
4615            )),
4616            BarAggregation::VolumeRuns => Box::new(VolumeRunsBarAggregator::new(
4617                bar_type,
4618                instrument.price_precision(),
4619                instrument.size_precision(),
4620                make_handler,
4621            )),
4622            BarAggregation::ValueImbalance => Box::new(ValueImbalanceBarAggregator::new(
4623                bar_type,
4624                instrument.price_precision(),
4625                instrument.size_precision(),
4626                make_handler,
4627            )),
4628            BarAggregation::ValueRuns => Box::new(ValueRunsBarAggregator::new(
4629                bar_type,
4630                instrument.price_precision(),
4631                instrument.size_precision(),
4632                make_handler,
4633            )),
4634            _ => unreachable!(),
4635        };
4636        let first = TradeTick {
4637            instrument_id: instrument.id(),
4638            price,
4639            size: Quantity::from(1),
4640            aggressor_side: AggressorSide::Buy,
4641            ts_event: UnixNanos::from(1_000),
4642            ts_init: UnixNanos::from(1_000),
4643            ..TradeTick::default()
4644        };
4645        let stale = TradeTick {
4646            price: Price::from("999.00"),
4647            ts_event: UnixNanos::from(500),
4648            ts_init: UnixNanos::from(500),
4649            ..first
4650        };
4651        let second = TradeTick {
4652            ts_event: UnixNanos::from(2_000),
4653            ts_init: UnixNanos::from(2_000),
4654            ..first
4655        };
4656
4657        aggregator.handle_trade(first);
4658        aggregator.handle_trade(stale);
4659        aggregator.handle_trade(second);
4660
4661        let bars = handler.lock();
4662        assert_eq!(bars.len(), 1);
4663        assert_eq!(bars[0].open, price);
4664        assert_eq!(bars[0].high, price);
4665        assert_eq!(bars[0].low, price);
4666        assert_eq!(bars[0].close, price);
4667        assert_eq!(bars[0].volume, Quantity::from(2));
4668        assert_eq!(bars[0].ts_event, UnixNanos::from(2_000));
4669        assert_eq!(bars[0].ts_init, UnixNanos::from(2_000));
4670    }
4671
4672    #[rstest]
4673    fn test_volume_bar_aggregator_exact_threshold_emits_single_bar(equity_aapl: Equity) {
4674        let instrument = InstrumentAny::Equity(equity_aapl);
4675        let bar_spec = BarSpecification::new(10, BarAggregation::Volume, PriceType::Last);
4676        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4677        let (handler, record) = recording_handler();
4678
4679        let mut aggregator = VolumeBarAggregator::new(
4680            bar_type,
4681            instrument.price_precision(),
4682            instrument.size_precision(),
4683            record,
4684        );
4685
4686        aggregator.update(
4687            Price::from("100.00"),
4688            Quantity::from(7),
4689            UnixNanos::from(1_000),
4690        );
4691        aggregator.update(
4692            Price::from("101.00"),
4693            Quantity::from(3),
4694            UnixNanos::from(2_000),
4695        );
4696
4697        let handler_guard = handler.lock();
4698        assert_eq!(handler_guard.len(), 1);
4699        assert_eq!(handler_guard[0].volume, Quantity::from(10));
4700        assert_eq!(handler_guard[0].close, Price::from("101.00"));
4701    }
4702
4703    #[rstest]
4704    fn test_volume_bar_aggregator_step_of_one_emits_per_unit(equity_aapl: Equity) {
4705        let instrument = InstrumentAny::Equity(equity_aapl);
4706        let bar_spec = BarSpecification::new(1, BarAggregation::Volume, PriceType::Last);
4707        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4708        let (handler, record) = recording_handler();
4709
4710        let mut aggregator = VolumeBarAggregator::new(
4711            bar_type,
4712            instrument.price_precision(),
4713            instrument.size_precision(),
4714            record,
4715        );
4716
4717        aggregator.update(
4718            Price::from("100.00"),
4719            Quantity::from(1),
4720            UnixNanos::default(),
4721        );
4722
4723        let handler_guard = handler.lock();
4724        assert_eq!(handler_guard.len(), 1);
4725        assert_eq!(handler_guard[0].volume, Quantity::from(1));
4726    }
4727
4728    #[rstest]
4729    fn test_volume_runs_bar_aggregator_side_change_resets(equity_aapl: Equity) {
4730        let instrument = InstrumentAny::Equity(equity_aapl);
4731        let bar_spec = BarSpecification::new(10, BarAggregation::VolumeRuns, PriceType::Last);
4732        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4733        let (handler, record) = recording_handler();
4734
4735        let mut aggregator = VolumeRunsBarAggregator::new(
4736            bar_type,
4737            instrument.price_precision(),
4738            instrument.size_precision(),
4739            record,
4740        );
4741
4742        let buy = TradeTick {
4743            instrument_id: instrument.id(),
4744            price: Price::from("100.00"),
4745            size: Quantity::from(4),
4746            ts_event: UnixNanos::from(1_000),
4747            ts_init: UnixNanos::from(1_000),
4748            ..TradeTick::default()
4749        };
4750        let sell_one = TradeTick {
4751            price: Price::from("200.00"),
4752            size: Quantity::from(6),
4753            aggressor_side: AggressorSide::Sell,
4754            ts_event: UnixNanos::from(2_000),
4755            ts_init: UnixNanos::from(2_000),
4756            ..buy
4757        };
4758        let sell_two = TradeTick {
4759            price: Price::from("201.00"),
4760            size: Quantity::from(4),
4761            ts_event: UnixNanos::from(3_000),
4762            ts_init: UnixNanos::from(3_000),
4763            ..sell_one
4764        };
4765
4766        aggregator.handle_trade(buy);
4767        aggregator.handle_trade(sell_one);
4768        aggregator.handle_trade(sell_two);
4769
4770        let handler_guard = handler.lock();
4771        assert_eq!(handler_guard.len(), 1);
4772        assert_eq!(handler_guard[0].open, Price::from("200.00"));
4773        assert_eq!(handler_guard[0].high, Price::from("201.00"));
4774        assert_eq!(handler_guard[0].low, Price::from("200.00"));
4775        assert_eq!(handler_guard[0].close, Price::from("201.00"));
4776        assert_eq!(handler_guard[0].volume, Quantity::from(10));
4777        assert_eq!(handler_guard[0].ts_event, UnixNanos::from(3_000));
4778        assert_eq!(handler_guard[0].ts_init, UnixNanos::from(3_000));
4779    }
4780
4781    #[rstest]
4782    fn test_volume_runs_bar_aggregator_handles_large_single_trade(equity_aapl: Equity) {
4783        let instrument = InstrumentAny::Equity(equity_aapl);
4784        let bar_spec = BarSpecification::new(3, BarAggregation::VolumeRuns, PriceType::Last);
4785        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4786        let (handler, record) = recording_handler();
4787
4788        let mut aggregator = VolumeRunsBarAggregator::new(
4789            bar_type,
4790            instrument.price_precision(),
4791            instrument.size_precision(),
4792            record,
4793        );
4794
4795        let trade = TradeTick {
4796            instrument_id: instrument.id(),
4797            price: Price::from("1.0"),
4798            size: Quantity::from(5),
4799            ..TradeTick::default()
4800        };
4801
4802        aggregator.handle_trade(trade);
4803
4804        let handler_guard = handler.lock();
4805        assert!(!handler_guard.is_empty());
4806        assert!(handler_guard[0].volume.as_f64() > 0.0);
4807        assert!(handler_guard[0].volume.as_f64() < trade.size.as_f64());
4808    }
4809
4810    #[rstest]
4811    fn test_volume_imbalance_bar_aggregator_splits_large_trade(equity_aapl: Equity) {
4812        let instrument = InstrumentAny::Equity(equity_aapl);
4813        let bar_spec = BarSpecification::new(2, BarAggregation::VolumeImbalance, PriceType::Last);
4814        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4815        let (handler, record) = recording_handler();
4816
4817        let mut aggregator = VolumeImbalanceBarAggregator::new(
4818            bar_type,
4819            instrument.price_precision(),
4820            instrument.size_precision(),
4821            record,
4822        );
4823
4824        let trade_small = TradeTick {
4825            instrument_id: instrument.id(),
4826            price: Price::from("1.0"),
4827            size: Quantity::from(1),
4828            ..TradeTick::default()
4829        };
4830        let trade_large = TradeTick {
4831            size: Quantity::from(3),
4832            ..trade_small
4833        };
4834
4835        aggregator.handle_trade(trade_small);
4836        aggregator.handle_trade(trade_large);
4837
4838        let handler_guard = handler.lock();
4839        assert_eq!(handler_guard.len(), 2);
4840        let total_output = handler_guard
4841            .iter()
4842            .map(|bar| bar.volume.as_f64())
4843            .sum::<f64>();
4844        let total_input = trade_small.size.as_f64() + trade_large.size.as_f64();
4845        assert!((total_output - total_input).abs() < f64::EPSILON);
4846    }
4847
4848    #[rstest]
4849    fn test_value_bar_aggregator_builds_at_value_threshold(equity_aapl: Equity) {
4850        let instrument = InstrumentAny::Equity(equity_aapl);
4851        let bar_spec = BarSpecification::new(1000, BarAggregation::Value, PriceType::Last); // $1000 value step
4852        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4853        let (handler, record) = recording_handler();
4854
4855        let mut aggregator = ValueBarAggregator::new(
4856            bar_type,
4857            instrument.price_precision(),
4858            instrument.size_precision(),
4859            record,
4860        );
4861
4862        // Updates to reach value threshold: 100 * 5 + 100 * 5 = $1000
4863        aggregator.update(
4864            Price::from("100.00"),
4865            Quantity::from(5),
4866            UnixNanos::default(),
4867        );
4868        aggregator.update(
4869            Price::from("100.00"),
4870            Quantity::from(5),
4871            UnixNanos::from(1000),
4872        );
4873
4874        let handler_guard = handler.lock();
4875        assert_eq!(handler_guard.len(), 1);
4876        let bar = handler_guard.first().unwrap();
4877        assert_eq!(bar.volume, Quantity::from(10));
4878    }
4879
4880    #[rstest]
4881    fn test_value_bar_aggregator_handles_large_update(equity_aapl: Equity) {
4882        let instrument = InstrumentAny::Equity(equity_aapl);
4883        let bar_spec = BarSpecification::new(1000, BarAggregation::Value, PriceType::Last);
4884        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4885        let (handler, record) = recording_handler();
4886
4887        let mut aggregator = ValueBarAggregator::new(
4888            bar_type,
4889            instrument.price_precision(),
4890            instrument.size_precision(),
4891            record,
4892        );
4893
4894        // Single large update: $100 * 25 = $2500 (should create 2 bars)
4895        aggregator.update(
4896            Price::from("100.00"),
4897            Quantity::from(25),
4898            UnixNanos::default(),
4899        );
4900
4901        let handler_guard = handler.lock();
4902        assert_eq!(handler_guard.len(), 2);
4903        let remaining_value = aggregator.get_cumulative_value();
4904        assert!(remaining_value < Decimal::from(1_000)); // Should be less than threshold
4905    }
4906
4907    #[rstest]
4908    fn test_value_bar_aggregator_handles_zero_price(equity_aapl: Equity) {
4909        let instrument = InstrumentAny::Equity(equity_aapl);
4910        let bar_spec = BarSpecification::new(1000, BarAggregation::Value, PriceType::Last);
4911        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4912        let (handler, record) = recording_handler();
4913
4914        let mut aggregator = ValueBarAggregator::new(
4915            bar_type,
4916            instrument.price_precision(),
4917            instrument.size_precision(),
4918            record,
4919        );
4920
4921        // Update with zero price should not cause division by zero
4922        aggregator.update(
4923            Price::from("0.00"),
4924            Quantity::from(100),
4925            UnixNanos::default(),
4926        );
4927
4928        // No bars should be emitted since value is zero
4929        let handler_guard = handler.lock();
4930        assert_eq!(handler_guard.len(), 0);
4931
4932        // Cumulative value should remain zero
4933        assert_eq!(aggregator.get_cumulative_value(), Decimal::ZERO);
4934    }
4935
4936    #[rstest]
4937    fn test_value_bar_aggregator_handles_zero_size(equity_aapl: Equity) {
4938        let instrument = InstrumentAny::Equity(equity_aapl);
4939        let bar_spec = BarSpecification::new(1000, BarAggregation::Value, PriceType::Last);
4940        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4941        let (handler, record) = recording_handler();
4942
4943        let mut aggregator = ValueBarAggregator::new(
4944            bar_type,
4945            instrument.price_precision(),
4946            instrument.size_precision(),
4947            record,
4948        );
4949
4950        // Update with zero size should not cause issues
4951        aggregator.update(
4952            Price::from("100.00"),
4953            Quantity::from(0),
4954            UnixNanos::default(),
4955        );
4956
4957        // No bars should be emitted
4958        let handler_guard = handler.lock();
4959        assert_eq!(handler_guard.len(), 0);
4960
4961        // Cumulative value should remain zero
4962        assert_eq!(aggregator.get_cumulative_value(), Decimal::ZERO);
4963    }
4964
4965    #[rstest]
4966    fn test_value_bar_aggregator_conserves_volume_across_rounded_chunks(equity_aapl: Equity) {
4967        let instrument = InstrumentAny::Equity(equity_aapl);
4968        let bar_spec = BarSpecification::new(10, BarAggregation::Value, PriceType::Last);
4969        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
4970        let (handler, record) = recording_handler();
4971
4972        let mut aggregator = ValueBarAggregator::new(
4973            bar_type,
4974            instrument.price_precision(),
4975            instrument.size_precision(),
4976            record,
4977        );
4978
4979        // Step 10 at price 3.00 needs fractional 3.33... chunks; the rounded
4980        // 3-unit chunks must still conserve the 10 input units (3 + 3 + 3 + 1)
4981        aggregator.update(
4982            Price::from("3.00"),
4983            Quantity::from(10),
4984            UnixNanos::from(1_000),
4985        );
4986
4987        let handler_guard = handler.lock();
4988        assert_eq!(handler_guard.len(), 3);
4989        for bar in handler_guard.iter() {
4990            assert_eq!(bar.volume, Quantity::from(3));
4991        }
4992        assert_eq!(aggregator.core.builder.volume, Quantity::from(1));
4993    }
4994
4995    #[rstest]
4996    fn test_value_bar_aggregator_update_bar_conserves_volume_across_rounded_chunks(
4997        equity_aapl: Equity,
4998    ) {
4999        let instrument = InstrumentAny::Equity(equity_aapl);
5000        let bar_spec = BarSpecification::new(10, BarAggregation::Value, PriceType::Last);
5001        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5002        let (handler, record) = recording_handler();
5003
5004        let mut aggregator = ValueBarAggregator::new(
5005            bar_type,
5006            instrument.price_precision(),
5007            instrument.size_precision(),
5008            record,
5009        );
5010
5011        // Average price 3.00 with volume 10 mirrors the tick-path conservation case
5012        let input_bar = Bar::new(
5013            bar_type,
5014            Price::from("3.00"),
5015            Price::from("3.00"),
5016            Price::from("3.00"),
5017            Price::from("3.00"),
5018            Quantity::from(10),
5019            UnixNanos::from(1_000),
5020            UnixNanos::from(1_000),
5021        );
5022        aggregator.handle_bar(input_bar);
5023
5024        let handler_guard = handler.lock();
5025        assert_eq!(handler_guard.len(), 3);
5026        for bar in handler_guard.iter() {
5027            assert_eq!(bar.volume, Quantity::from(3));
5028        }
5029        assert_eq!(aggregator.core.builder.volume, Quantity::from(1));
5030    }
5031
5032    #[rstest]
5033    fn test_value_bar_aggregator_exact_threshold_emits_one_bar(equity_aapl: Equity) {
5034        let instrument = InstrumentAny::Equity(equity_aapl);
5035        let bar_spec = BarSpecification::new(1000, BarAggregation::Value, PriceType::Last);
5036        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5037        let (handler, record) = recording_handler();
5038
5039        let mut aggregator = ValueBarAggregator::new(
5040            bar_type,
5041            instrument.price_precision(),
5042            instrument.size_precision(),
5043            record,
5044        );
5045
5046        aggregator.update(
5047            Price::from("100.00"),
5048            Quantity::from(5),
5049            UnixNanos::from(1_000),
5050        );
5051        aggregator.update(
5052            Price::from("100.00"),
5053            Quantity::from(5),
5054            UnixNanos::from(2_000),
5055        );
5056
5057        let handler_guard = handler.lock();
5058        assert_eq!(handler_guard.len(), 1);
5059        assert_eq!(handler_guard[0].volume, Quantity::from(10));
5060        assert_eq!(aggregator.get_cumulative_value(), Decimal::ZERO);
5061    }
5062
5063    #[rstest]
5064    fn test_value_bar_aggregator_precision_boundary_min_size_clamp(equity_aapl: Equity) {
5065        // step=100, price=100 per-unit value=100 with size_precision=0 lands the divided
5066        // size_chunk at the precision floor. Verifies the min-size clamp branch in update()
5067        // emits one bar per unit rather than looping on zero-volume chunks.
5068        let instrument = InstrumentAny::Equity(equity_aapl);
5069        let bar_spec = BarSpecification::new(100, BarAggregation::Value, PriceType::Last);
5070        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5071        let (handler, record) = recording_handler();
5072
5073        let mut aggregator = ValueBarAggregator::new(
5074            bar_type,
5075            instrument.price_precision(),
5076            instrument.size_precision(),
5077            record,
5078        );
5079
5080        // 4 units at $100 = $400 value, with step $100 gives 4 bars exactly.
5081        aggregator.update(
5082            Price::from("100.00"),
5083            Quantity::from(4),
5084            UnixNanos::default(),
5085        );
5086
5087        let handler_guard = handler.lock();
5088        assert_eq!(handler_guard.len(), 4);
5089        for bar in handler_guard.iter() {
5090            assert_eq!(bar.volume, Quantity::from(1));
5091        }
5092    }
5093
5094    #[rstest]
5095    fn test_value_imbalance_bar_aggregator_emits_on_opposing_overflow(equity_aapl: Equity) {
5096        let instrument = InstrumentAny::Equity(equity_aapl);
5097        let bar_spec = BarSpecification::new(10, BarAggregation::ValueImbalance, PriceType::Last);
5098        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5099        let (handler, record) = recording_handler();
5100
5101        let mut aggregator = ValueImbalanceBarAggregator::new(
5102            bar_type,
5103            instrument.price_precision(),
5104            instrument.size_precision(),
5105            record,
5106        );
5107
5108        let buy = TradeTick {
5109            price: Price::from("5.0"),
5110            size: Quantity::from(2), // value 10, should emit one bar
5111            instrument_id: instrument.id(),
5112            ..TradeTick::default()
5113        };
5114        let sell = TradeTick {
5115            price: Price::from("5.0"),
5116            size: Quantity::from(2), // value 10, should emit another bar
5117            aggressor_side: AggressorSide::Sell,
5118            instrument_id: instrument.id(),
5119            ..buy
5120        };
5121
5122        aggregator.handle_trade(buy);
5123        aggregator.handle_trade(sell);
5124
5125        let handler_guard = handler.lock();
5126        assert_eq!(handler_guard.len(), 2);
5127    }
5128
5129    #[rstest]
5130    fn test_value_runs_bar_aggregator_emits_on_consecutive_side(equity_aapl: Equity) {
5131        let instrument = InstrumentAny::Equity(equity_aapl);
5132        let bar_spec = BarSpecification::new(100, BarAggregation::ValueRuns, PriceType::Last);
5133        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5134        let (handler, record) = recording_handler();
5135
5136        let mut aggregator = ValueRunsBarAggregator::new(
5137            bar_type,
5138            instrument.price_precision(),
5139            instrument.size_precision(),
5140            record,
5141        );
5142
5143        let trade = TradeTick {
5144            price: Price::from("10.0"),
5145            size: Quantity::from(5),
5146            instrument_id: instrument.id(),
5147            ..TradeTick::default()
5148        };
5149
5150        aggregator.handle_trade(trade);
5151        aggregator.handle_trade(trade);
5152
5153        let handler_guard = handler.lock();
5154        assert_eq!(handler_guard.len(), 1);
5155        let bar = handler_guard.first().unwrap();
5156        assert_eq!(bar.volume, Quantity::from(10));
5157    }
5158
5159    #[rstest]
5160    fn test_value_runs_bar_aggregator_resets_on_side_change(equity_aapl: Equity) {
5161        let instrument = InstrumentAny::Equity(equity_aapl);
5162        let bar_spec = BarSpecification::new(100, BarAggregation::ValueRuns, PriceType::Last);
5163        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5164        let (handler, record) = recording_handler();
5165
5166        let mut aggregator = ValueRunsBarAggregator::new(
5167            bar_type,
5168            instrument.price_precision(),
5169            instrument.size_precision(),
5170            record,
5171        );
5172
5173        let buy = TradeTick {
5174            price: Price::from("10.0"),
5175            size: Quantity::from(5),
5176            instrument_id: instrument.id(),
5177            ..TradeTick::default()
5178        }; // value 50
5179        let sell = TradeTick {
5180            price: Price::from("10.0"),
5181            size: Quantity::from(10),
5182            aggressor_side: AggressorSide::Sell,
5183            ..buy
5184        }; // value 100
5185
5186        aggregator.handle_trade(buy);
5187        aggregator.handle_trade(sell);
5188
5189        let handler_guard = handler.lock();
5190        assert_eq!(handler_guard.len(), 1);
5191        assert_eq!(handler_guard[0].volume, Quantity::from(10));
5192    }
5193
5194    #[rstest]
5195    fn test_tick_runs_bar_aggregator_continues_run_after_bar_emission(equity_aapl: Equity) {
5196        let instrument = InstrumentAny::Equity(equity_aapl);
5197        let bar_spec = BarSpecification::new(2, BarAggregation::TickRuns, PriceType::Last);
5198        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5199        let (handler, record) = recording_handler();
5200
5201        let mut aggregator = TickRunsBarAggregator::new(
5202            bar_type,
5203            instrument.price_precision(),
5204            instrument.size_precision(),
5205            record,
5206        );
5207
5208        let buy = TradeTick::default();
5209
5210        aggregator.handle_trade(buy);
5211        aggregator.handle_trade(buy); // Emit bar 1 (run complete)
5212        aggregator.handle_trade(buy); // Start new run
5213        aggregator.handle_trade(buy); // Emit bar 2 (new run complete)
5214
5215        let handler_guard = handler.lock();
5216        assert_eq!(handler_guard.len(), 2);
5217    }
5218
5219    #[rstest]
5220    fn test_tick_runs_bar_aggregator_handles_no_aggressor_trades(equity_aapl: Equity) {
5221        let instrument = InstrumentAny::Equity(equity_aapl);
5222        let bar_spec = BarSpecification::new(2, BarAggregation::TickRuns, PriceType::Last);
5223        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5224        let (handler, record) = recording_handler();
5225
5226        let mut aggregator = TickRunsBarAggregator::new(
5227            bar_type,
5228            instrument.price_precision(),
5229            instrument.size_precision(),
5230            record,
5231        );
5232
5233        let buy = TradeTick::default();
5234        let no_aggressor = TradeTick {
5235            aggressor_side: AggressorSide::NoAggressor,
5236            ..buy
5237        };
5238
5239        aggregator.handle_trade(buy);
5240        aggregator.handle_trade(no_aggressor); // Should not affect run count
5241        aggregator.handle_trade(no_aggressor); // Should not affect run count
5242        aggregator.handle_trade(buy); // Continue run to threshold
5243
5244        let handler_guard = handler.lock();
5245        assert_eq!(handler_guard.len(), 1);
5246    }
5247
5248    #[rstest]
5249    fn test_volume_runs_bar_aggregator_continues_run_after_bar_emission(equity_aapl: Equity) {
5250        let instrument = InstrumentAny::Equity(equity_aapl);
5251        let bar_spec = BarSpecification::new(2, BarAggregation::VolumeRuns, PriceType::Last);
5252        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5253        let (handler, record) = recording_handler();
5254
5255        let mut aggregator = VolumeRunsBarAggregator::new(
5256            bar_type,
5257            instrument.price_precision(),
5258            instrument.size_precision(),
5259            record,
5260        );
5261
5262        let buy = TradeTick {
5263            instrument_id: instrument.id(),
5264            price: Price::from("1.0"),
5265            size: Quantity::from(1),
5266            ..TradeTick::default()
5267        };
5268
5269        aggregator.handle_trade(buy);
5270        aggregator.handle_trade(buy); // Emit bar 1 (2.0 volume reached)
5271        aggregator.handle_trade(buy); // Start new run
5272        aggregator.handle_trade(buy); // Emit bar 2 (new 2.0 volume reached)
5273
5274        let handler_guard = handler.lock();
5275        assert_eq!(handler_guard.len(), 2);
5276        assert_eq!(handler_guard[0].volume, Quantity::from(2));
5277        assert_eq!(handler_guard[1].volume, Quantity::from(2));
5278    }
5279
5280    #[rstest]
5281    fn test_value_runs_bar_aggregator_continues_run_after_bar_emission(equity_aapl: Equity) {
5282        let instrument = InstrumentAny::Equity(equity_aapl);
5283        let bar_spec = BarSpecification::new(100, BarAggregation::ValueRuns, PriceType::Last);
5284        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5285        let (handler, record) = recording_handler();
5286
5287        let mut aggregator = ValueRunsBarAggregator::new(
5288            bar_type,
5289            instrument.price_precision(),
5290            instrument.size_precision(),
5291            record,
5292        );
5293
5294        let buy = TradeTick {
5295            instrument_id: instrument.id(),
5296            price: Price::from("10.0"),
5297            size: Quantity::from(5),
5298            ..TradeTick::default()
5299        }; // value 50 per trade
5300
5301        aggregator.handle_trade(buy);
5302        aggregator.handle_trade(buy); // Emit bar 1 (100 value reached)
5303        aggregator.handle_trade(buy); // Start new run
5304        aggregator.handle_trade(buy); // Emit bar 2 (new 100 value reached)
5305
5306        let handler_guard = handler.lock();
5307        assert_eq!(handler_guard.len(), 2);
5308        assert_eq!(handler_guard[0].volume, Quantity::from(10));
5309        assert_eq!(handler_guard[1].volume, Quantity::from(10));
5310    }
5311
5312    #[rstest]
5313    fn test_time_bar_aggregator_builds_at_interval(equity_aapl: Equity) {
5314        let instrument = InstrumentAny::Equity(equity_aapl);
5315        // One second bars
5316        let bar_spec = BarSpecification::new(1, BarAggregation::Second, PriceType::Last);
5317        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5318        let (handler, record) = recording_handler();
5319        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5320
5321        let mut aggregator = TimeBarAggregator::new(
5322            bar_type,
5323            instrument.price_precision(),
5324            instrument.size_precision(),
5325            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
5326            record,
5327            true,  // build_with_no_updates
5328            false, // timestamp_on_close
5329            BarIntervalType::LeftOpen,
5330            None, // time_bars_origin_offset
5331            TimeZone::UTC,
5332            15,    // bar_build_delay
5333            false, // skip_first_non_full_bar
5334        );
5335
5336        aggregator.update(
5337            Price::from("100.00"),
5338            Quantity::from(1),
5339            UnixNanos::default(),
5340        );
5341
5342        let next_sec = UnixNanos::from(1_000_000_000);
5343        clock.borrow_mut().set_time(next_sec);
5344
5345        let event = TimeEvent::new(
5346            Ustr::from("1-SECOND-LAST"),
5347            UUID4::new(),
5348            next_sec,
5349            next_sec,
5350        );
5351        aggregator.build_bar(&event);
5352
5353        let handler_guard = handler.lock();
5354        assert_eq!(handler_guard.len(), 1);
5355        let bar = handler_guard.first().unwrap();
5356        assert_eq!(bar.ts_event, UnixNanos::default());
5357        assert_eq!(bar.ts_init, next_sec);
5358    }
5359
5360    #[rstest]
5361    #[case::self_link(1)]
5362    #[case::two_levels(2)]
5363    #[case::three_levels(3)]
5364    fn test_time_bar_source_rejects_cyclic_chain(equity_aapl: Equity, #[case] depth: usize) {
5365        let instrument = InstrumentAny::Equity(equity_aapl);
5366        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5367
5368        let aggregators: Vec<_> = (1..=depth)
5369            .map(|step| {
5370                let spec = BarSpecification::new(step, BarAggregation::Minute, PriceType::Last);
5371                let (aggregator, _) = start_time_bar_aggregator(
5372                    &instrument,
5373                    spec,
5374                    &clock,
5375                    true,
5376                    BarIntervalType::LeftOpen,
5377                );
5378                aggregator
5379            })
5380            .collect();
5381
5382        for pair in aggregators.windows(2) {
5383            pair[1]
5384                .borrow_mut()
5385                .as_any_mut()
5386                .downcast_mut::<TimeBarAggregator>()
5387                .unwrap()
5388                .set_timer_source(Rc::downgrade(&pair[0]));
5389        }
5390
5391        aggregators[0]
5392            .borrow_mut()
5393            .as_any_mut()
5394            .downcast_mut::<TimeBarAggregator>()
5395            .unwrap()
5396            .set_timer_source(Rc::downgrade(aggregators.last().unwrap()));
5397
5398        assert!(
5399            aggregators[0]
5400                .borrow()
5401                .as_any()
5402                .downcast_ref::<TimeBarAggregator>()
5403                .unwrap()
5404                .timer_source
5405                .is_none()
5406        );
5407
5408        for pair in aggregators.windows(2) {
5409            let target = pair[1].borrow();
5410            let source = target
5411                .as_any()
5412                .downcast_ref::<TimeBarAggregator>()
5413                .unwrap()
5414                .timer_source
5415                .as_ref()
5416                .unwrap();
5417            assert!(Weak::ptr_eq(source, &Rc::downgrade(&pair[0])));
5418        }
5419    }
5420
5421    #[rstest]
5422    fn test_time_bar_aggregator_stop_clears_timer_and_allows_restart(equity_aapl: Equity) {
5423        let instrument = InstrumentAny::Equity(equity_aapl);
5424        let bar_spec = BarSpecification::new(1, BarAggregation::Second, PriceType::Last);
5425        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5426        let timer_name = format!("TIME_BAR_{bar_type}");
5427        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5428
5429        let aggregator = TimeBarAggregator::new(
5430            bar_type,
5431            instrument.price_precision(),
5432            instrument.size_precision(),
5433            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
5434            |_bar: Bar| {},
5435            true,
5436            false,
5437            BarIntervalType::LeftOpen,
5438            None,
5439            TimeZone::UTC,
5440            15,
5441            false,
5442        );
5443
5444        let boxed: Box<dyn BarAggregator> = Box::new(aggregator);
5445        let rc = Rc::new(RefCell::new(boxed));
5446
5447        rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
5448        assert_eq!(clock.borrow().timer_names(), vec![timer_name.as_str()]);
5449
5450        rc.borrow_mut().stop();
5451        assert!(clock.borrow().timer_names().is_empty());
5452
5453        rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
5454        assert_eq!(clock.borrow().timer_names(), vec![timer_name.as_str()]);
5455    }
5456
5457    #[rstest]
5458    fn test_time_bar_aggregator_accepts_interval_above_i64_nanos(equity_aapl: Equity) {
5459        let instrument = InstrumentAny::Equity(equity_aapl);
5460        let bar_spec = BarSpecification::new(106_752, BarAggregation::Day, PriceType::Last);
5461        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5462        let interval_ns = get_bar_interval_ns(&bar_type);
5463        let timer_name = format!("TIME_BAR_{bar_type}");
5464        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5465        clock.borrow_mut().set_time(UnixNanos::from(1));
5466        let aggregator = TimeBarAggregator::new(
5467            bar_type,
5468            instrument.price_precision(),
5469            instrument.size_precision(),
5470            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
5471            |_bar: Bar| {},
5472            true,
5473            false,
5474            BarIntervalType::LeftOpen,
5475            None,
5476            TimeZone::UTC,
5477            0,
5478            false,
5479        );
5480        let boxed: Box<dyn BarAggregator> = Box::new(aggregator);
5481        let rc = Rc::new(RefCell::new(boxed));
5482
5483        rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
5484
5485        assert_eq!(
5486            clock.borrow().next_time_ns(&timer_name),
5487            UnixNanos::from(1).checked_add(interval_ns)
5488        );
5489    }
5490
5491    #[rstest]
5492    fn test_time_bar_aggregator_left_open_interval(equity_aapl: Equity) {
5493        let instrument = InstrumentAny::Equity(equity_aapl);
5494        let bar_spec = BarSpecification::new(1, BarAggregation::Second, PriceType::Last);
5495        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5496        let (handler, record) = recording_handler();
5497        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5498
5499        let mut aggregator = TimeBarAggregator::new(
5500            bar_type,
5501            instrument.price_precision(),
5502            instrument.size_precision(),
5503            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
5504            record,
5505            true, // build_with_no_updates
5506            true, // timestamp_on_close - changed to true to verify left-open behavior
5507            BarIntervalType::LeftOpen,
5508            None,
5509            TimeZone::UTC,
5510            15,
5511            false, // skip_first_non_full_bar
5512        );
5513
5514        // Update in first interval
5515        aggregator.update(
5516            Price::from("100.00"),
5517            Quantity::from(1),
5518            UnixNanos::default(),
5519        );
5520
5521        // First interval close
5522        let ts1 = UnixNanos::from(1_000_000_000);
5523        clock.borrow_mut().set_time(ts1);
5524        let event = TimeEvent::new(Ustr::from("1-SECOND-LAST"), UUID4::new(), ts1, ts1);
5525        aggregator.build_bar(&event);
5526
5527        // Update in second interval
5528        aggregator.update(Price::from("101.00"), Quantity::from(1), ts1);
5529
5530        // Second interval close
5531        let ts2 = UnixNanos::from(2_000_000_000);
5532        clock.borrow_mut().set_time(ts2);
5533        let event = TimeEvent::new(Ustr::from("1-SECOND-LAST"), UUID4::new(), ts2, ts2);
5534        aggregator.build_bar(&event);
5535
5536        let handler_guard = handler.lock();
5537        assert_eq!(handler_guard.len(), 2);
5538
5539        let bar1 = &handler_guard[0];
5540        assert_eq!(bar1.ts_event, ts1); // For left-open with timestamp_on_close=true
5541        assert_eq!(bar1.ts_init, ts1);
5542        assert_eq!(bar1.close, Price::from("100.00"));
5543        let bar2 = &handler_guard[1];
5544        assert_eq!(bar2.ts_event, ts2);
5545        assert_eq!(bar2.ts_init, ts2);
5546        assert_eq!(bar2.close, Price::from("101.00"));
5547    }
5548
5549    #[rstest]
5550    fn test_time_bar_aggregator_right_open_interval(equity_aapl: Equity) {
5551        let instrument = InstrumentAny::Equity(equity_aapl);
5552        let bar_spec = BarSpecification::new(1, BarAggregation::Second, PriceType::Last);
5553        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5554        let (handler, record) = recording_handler();
5555        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5556        let mut aggregator = TimeBarAggregator::new(
5557            bar_type,
5558            instrument.price_precision(),
5559            instrument.size_precision(),
5560            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
5561            record,
5562            true, // build_with_no_updates
5563            true, // timestamp_on_close
5564            BarIntervalType::RightOpen,
5565            None,
5566            TimeZone::UTC,
5567            15,
5568            false, // skip_first_non_full_bar
5569        );
5570
5571        // Update in first interval
5572        aggregator.update(
5573            Price::from("100.00"),
5574            Quantity::from(1),
5575            UnixNanos::default(),
5576        );
5577
5578        // First interval close
5579        let ts1 = UnixNanos::from(1_000_000_000);
5580        clock.borrow_mut().set_time(ts1);
5581        let event = TimeEvent::new(Ustr::from("1-SECOND-LAST"), UUID4::new(), ts1, ts1);
5582        aggregator.build_bar(&event);
5583
5584        // Update in second interval
5585        aggregator.update(Price::from("101.00"), Quantity::from(1), ts1);
5586
5587        // Second interval close
5588        let ts2 = UnixNanos::from(2_000_000_000);
5589        clock.borrow_mut().set_time(ts2);
5590        let event = TimeEvent::new(Ustr::from("1-SECOND-LAST"), UUID4::new(), ts2, ts2);
5591        aggregator.build_bar(&event);
5592
5593        let handler_guard = handler.lock();
5594        assert_eq!(handler_guard.len(), 2);
5595
5596        let bar1 = &handler_guard[0];
5597        assert_eq!(bar1.ts_event, UnixNanos::default()); // Right-open interval starts inclusive
5598        assert_eq!(bar1.ts_init, ts1);
5599        assert_eq!(bar1.close, Price::from("100.00"));
5600
5601        let bar2 = &handler_guard[1];
5602        assert_eq!(bar2.ts_event, ts1);
5603        assert_eq!(bar2.ts_init, ts2);
5604        assert_eq!(bar2.close, Price::from("101.00"));
5605    }
5606
5607    #[rstest]
5608    fn test_time_bar_aggregator_no_updates_behavior(equity_aapl: Equity) {
5609        let instrument = InstrumentAny::Equity(equity_aapl);
5610        let bar_spec = BarSpecification::new(1, BarAggregation::Second, PriceType::Last);
5611        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5612        let (handler, record) = recording_handler();
5613        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5614
5615        // First test with build_with_no_updates = false
5616        let mut aggregator = TimeBarAggregator::new(
5617            bar_type,
5618            instrument.price_precision(),
5619            instrument.size_precision(),
5620            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
5621            record,
5622            false, // build_with_no_updates disabled
5623            true,  // timestamp_on_close
5624            BarIntervalType::LeftOpen,
5625            None,
5626            TimeZone::UTC,
5627            15,
5628            false, // skip_first_non_full_bar
5629        );
5630
5631        // No updates, just interval close
5632        let ts1 = UnixNanos::from(1_000_000_000);
5633        clock.borrow_mut().set_time(ts1);
5634        let event = TimeEvent::new(Ustr::from("1-SECOND-LAST"), UUID4::new(), ts1, ts1);
5635        aggregator.build_bar(&event);
5636
5637        let handler_guard = handler.lock();
5638        assert_eq!(handler_guard.len(), 0); // No bar should be built without updates
5639        drop(handler_guard);
5640
5641        // Now test with build_with_no_updates = true
5642        let (handler, record) = recording_handler();
5643        let mut aggregator = TimeBarAggregator::new(
5644            bar_type,
5645            instrument.price_precision(),
5646            instrument.size_precision(),
5647            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
5648            record,
5649            true, // build_with_no_updates enabled
5650            true, // timestamp_on_close
5651            BarIntervalType::LeftOpen,
5652            None,
5653            TimeZone::UTC,
5654            15,
5655            false, // skip_first_non_full_bar
5656        );
5657
5658        aggregator.update(
5659            Price::from("100.00"),
5660            Quantity::from(1),
5661            UnixNanos::default(),
5662        );
5663
5664        // First interval with update
5665        let ts1 = UnixNanos::from(1_000_000_000);
5666        clock.borrow_mut().set_time(ts1);
5667        let event = TimeEvent::new(Ustr::from("1-SECOND-LAST"), UUID4::new(), ts1, ts1);
5668        aggregator.build_bar(&event);
5669
5670        // Second interval without updates
5671        let ts2 = UnixNanos::from(2_000_000_000);
5672        clock.borrow_mut().set_time(ts2);
5673        let event = TimeEvent::new(Ustr::from("1-SECOND-LAST"), UUID4::new(), ts2, ts2);
5674        aggregator.build_bar(&event);
5675
5676        let handler_guard = handler.lock();
5677        assert_eq!(handler_guard.len(), 2); // Both bars should be built
5678        let bar1 = &handler_guard[0];
5679        assert_eq!(bar1.close, Price::from("100.00"));
5680        let bar2 = &handler_guard[1];
5681        assert_eq!(bar2.close, Price::from("100.00")); // Should use last close
5682    }
5683
5684    #[rstest]
5685    fn test_time_bar_aggregator_respects_timestamp_on_close(equity_aapl: Equity) {
5686        let instrument = InstrumentAny::Equity(equity_aapl);
5687        let bar_spec = BarSpecification::new(1, BarAggregation::Second, PriceType::Last);
5688        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5689        let clock = Rc::new(RefCell::new(VirtualClock::new()));
5690        let (handler, record) = recording_handler();
5691
5692        let mut aggregator = TimeBarAggregator::new(
5693            bar_type,
5694            instrument.price_precision(),
5695            instrument.size_precision(),
5696            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
5697            record,
5698            true, // build_with_no_updates
5699            true, // timestamp_on_close
5700            BarIntervalType::RightOpen,
5701            None,
5702            TimeZone::UTC,
5703            15,
5704            false, // skip_first_non_full_bar
5705        );
5706
5707        let ts1 = UnixNanos::from(1_000_000_000);
5708        aggregator.update(Price::from("100.00"), Quantity::from(1), ts1);
5709
5710        let ts2 = UnixNanos::from(2_000_000_000);
5711        clock.borrow_mut().set_time(ts2);
5712
5713        // Simulate timestamp on close
5714        let event = TimeEvent::new(Ustr::from("1-SECOND-LAST"), UUID4::new(), ts2, ts2);
5715        aggregator.build_bar(&event);
5716
5717        let handler_guard = handler.lock();
5718        let bar = handler_guard.first().unwrap();
5719        assert_eq!(bar.ts_event, UnixNanos::default());
5720        assert_eq!(bar.ts_init, ts2);
5721    }
5722
5723    #[rstest]
5724    fn test_renko_brick_preserves_subprecision_increment(audusd_sim: CurrencyPair) {
5725        let bar_type = BarType::new(
5726            audusd_sim.id(),
5727            BarSpecification::new(2, BarAggregation::Renko, PriceType::Last),
5728            AggregationSource::Internal,
5729        );
5730        let mut increment = Price::from("0.015");
5731        increment.precision = 2;
5732
5733        let aggregator = RenkoBarAggregator::new(bar_type, 2, 0, increment, |_| {});
5734        assert_eq!(aggregator.brick_size, Price::from("0.03"));
5735    }
5736
5737    #[rstest]
5738    fn test_renko_bar_aggregator_initialization(audusd_sim: CurrencyPair) {
5739        let instrument = InstrumentAny::CurrencyPair(audusd_sim);
5740        let bar_spec = BarSpecification::new(10, BarAggregation::Renko, PriceType::Mid); // 10 pip brick size
5741        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5742        let (_handler, record) = recording_handler();
5743
5744        let aggregator = RenkoBarAggregator::new(
5745            bar_type,
5746            instrument.price_precision(),
5747            instrument.size_precision(),
5748            instrument.price_increment(),
5749            record,
5750        );
5751
5752        assert_eq!(aggregator.bar_type(), bar_type);
5753        assert!(!aggregator.is_running());
5754        // 10 pips * price_increment.raw (depends on precision mode)
5755        let expected_brick_size = Price::from_decimal_dp(
5756            instrument.price_increment() * Decimal::from(10),
5757            instrument.price_precision(),
5758        )
5759        .unwrap();
5760        assert_eq!(aggregator.brick_size, expected_brick_size);
5761    }
5762
5763    #[rstest]
5764    fn test_renko_bar_aggregator_update_below_brick_size_no_bar(audusd_sim: CurrencyPair) {
5765        let instrument = InstrumentAny::CurrencyPair(audusd_sim);
5766        let bar_spec = BarSpecification::new(10, BarAggregation::Renko, PriceType::Mid); // 10 pip brick size
5767        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5768        let (handler, record) = recording_handler();
5769
5770        let mut aggregator = RenkoBarAggregator::new(
5771            bar_type,
5772            instrument.price_precision(),
5773            instrument.size_precision(),
5774            instrument.price_increment(),
5775            record,
5776        );
5777
5778        // Small price movement (5 pips, less than 10 pip brick size)
5779        aggregator.update(
5780            Price::from("1.00000"),
5781            Quantity::from(1),
5782            UnixNanos::default(),
5783        );
5784        aggregator.update(
5785            Price::from("1.00005"),
5786            Quantity::from(1),
5787            UnixNanos::from(1000),
5788        );
5789
5790        let handler_guard = handler.lock();
5791        assert_eq!(handler_guard.len(), 0); // No bar created yet
5792    }
5793
5794    #[rstest]
5795    fn test_renko_bar_aggregator_ignores_out_of_order_bar(audusd_sim: CurrencyPair) {
5796        let instrument = InstrumentAny::CurrencyPair(audusd_sim);
5797        let bar_spec = BarSpecification::new(10, BarAggregation::Renko, PriceType::Mid);
5798        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5799        let (handler, record) = recording_handler();
5800        let mut aggregator = RenkoBarAggregator::new(
5801            bar_type,
5802            instrument.price_precision(),
5803            instrument.size_precision(),
5804            instrument.price_increment(),
5805            record,
5806        );
5807        let first = Bar::new(
5808            bar_type,
5809            Price::from("1.00000"),
5810            Price::from("1.00000"),
5811            Price::from("1.00000"),
5812            Price::from("1.00000"),
5813            Quantity::from(1),
5814            UnixNanos::from(1_000),
5815            UnixNanos::from(1_000),
5816        );
5817        let stale = Bar::new(
5818            bar_type,
5819            Price::from("1.00020"),
5820            Price::from("1.00020"),
5821            Price::from("1.00020"),
5822            Price::from("1.00020"),
5823            Quantity::from(1),
5824            UnixNanos::from(500),
5825            UnixNanos::from(500),
5826        );
5827
5828        aggregator.update_bar(first, first.volume, first.ts_init);
5829        aggregator.update_bar(stale, stale.volume, stale.ts_init);
5830
5831        assert!(handler.lock().is_empty());
5832        assert_eq!(aggregator.last_close, Some(Price::from("1.00000")));
5833        assert_eq!(aggregator.core.builder.ts_last, UnixNanos::from(1_000));
5834    }
5835
5836    #[rstest]
5837    fn test_renko_bar_aggregator_update_exceeds_brick_size_creates_bar(audusd_sim: CurrencyPair) {
5838        let instrument = InstrumentAny::CurrencyPair(audusd_sim);
5839        let bar_spec = BarSpecification::new(10, BarAggregation::Renko, PriceType::Mid); // 10 pip brick size
5840        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5841        let (handler, record) = recording_handler();
5842
5843        let mut aggregator = RenkoBarAggregator::new(
5844            bar_type,
5845            instrument.price_precision(),
5846            instrument.size_precision(),
5847            instrument.price_increment(),
5848            record,
5849        );
5850
5851        // Price movement exceeding brick size (15 pips)
5852        aggregator.update(
5853            Price::from("1.00000"),
5854            Quantity::from(1),
5855            UnixNanos::default(),
5856        );
5857        aggregator.update(
5858            Price::from("1.00015"),
5859            Quantity::from(1),
5860            UnixNanos::from(1000),
5861        );
5862
5863        let handler_guard = handler.lock();
5864        assert_eq!(handler_guard.len(), 1);
5865
5866        let bar = handler_guard.first().unwrap();
5867        assert_eq!(bar.open, Price::from("1.00000"));
5868        assert_eq!(bar.high, Price::from("1.00010"));
5869        assert_eq!(bar.low, Price::from("1.00000"));
5870        assert_eq!(bar.close, Price::from("1.00010"));
5871        assert_eq!(bar.volume, Quantity::from(2));
5872        assert_eq!(bar.ts_event, UnixNanos::from(1000));
5873        assert_eq!(bar.ts_init, UnixNanos::from(1000));
5874    }
5875
5876    #[rstest]
5877    fn test_renko_bar_aggregator_applies_continuous_future_adjustment(audusd_sim: CurrencyPair) {
5878        let instrument = InstrumentAny::CurrencyPair(audusd_sim);
5879        let bar_spec = BarSpecification::new(10, BarAggregation::Renko, PriceType::Mid);
5880        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5881        let (handler, record) = recording_handler();
5882
5883        let mut aggregator = RenkoBarAggregator::new(
5884            bar_type,
5885            instrument.price_precision(),
5886            instrument.size_precision(),
5887            instrument.price_increment(),
5888            record,
5889        );
5890        aggregator.set_adjustment(Decimal::ONE, ContinuousFutureAdjustmentType::BackwardSpread);
5891
5892        aggregator.update(
5893            Price::from("1.00000"),
5894            Quantity::from(1),
5895            UnixNanos::default(),
5896        );
5897        aggregator.update(
5898            Price::from("1.00010"),
5899            Quantity::from(1),
5900            UnixNanos::from(1000),
5901        );
5902
5903        let bars = handler.lock();
5904        assert_eq!(bars.len(), 1);
5905        assert_eq!(bars[0].open, Price::from("2.00000"));
5906        assert_eq!(bars[0].high, Price::from("2.00010"));
5907        assert_eq!(bars[0].low, Price::from("2.00000"));
5908        assert_eq!(bars[0].close, Price::from("2.00010"));
5909        assert_eq!(bars[0].volume, Quantity::from(2));
5910        assert_eq!(bars[0].ts_event, UnixNanos::from(1000));
5911    }
5912
5913    #[rstest]
5914    fn test_renko_bar_aggregator_handle_bar_applies_continuous_future_adjustment(
5915        audusd_sim: CurrencyPair,
5916    ) {
5917        let instrument = InstrumentAny::CurrencyPair(audusd_sim);
5918        let bar_spec = BarSpecification::new(10, BarAggregation::Renko, PriceType::Mid);
5919        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5920
5921        let source_bar_type = BarType::new(
5922            instrument.id(),
5923            BarSpecification::new(1, BarAggregation::Minute, PriceType::Mid),
5924            AggregationSource::Internal,
5925        );
5926        let (handler, record) = recording_handler();
5927
5928        let mut aggregator = RenkoBarAggregator::new(
5929            bar_type,
5930            instrument.price_precision(),
5931            instrument.size_precision(),
5932            instrument.price_increment(),
5933            record,
5934        );
5935        aggregator.set_adjustment(Decimal::ONE, ContinuousFutureAdjustmentType::BackwardSpread);
5936
5937        aggregator.handle_bar(Bar::new(
5938            source_bar_type,
5939            Price::from("1.00000"),
5940            Price::from("1.00005"),
5941            Price::from("0.99995"),
5942            Price::from("1.00000"),
5943            Quantity::from(100),
5944            UnixNanos::default(),
5945            UnixNanos::default(),
5946        ));
5947        aggregator.handle_bar(Bar::new(
5948            source_bar_type,
5949            Price::from("1.00000"),
5950            Price::from("1.00015"),
5951            Price::from("0.99995"),
5952            Price::from("1.00010"),
5953            Quantity::from(50),
5954            UnixNanos::from(60_000_000_000),
5955            UnixNanos::from(60_000_000_000),
5956        ));
5957
5958        let bars = handler.lock();
5959        assert_eq!(bars.len(), 1);
5960        assert_eq!(bars[0].open, Price::from("2.00000"));
5961        assert_eq!(bars[0].high, Price::from("2.00010"));
5962        assert_eq!(bars[0].low, Price::from("2.00000"));
5963        assert_eq!(bars[0].close, Price::from("2.00010"));
5964        assert_eq!(bars[0].volume, Quantity::from(150));
5965        assert_eq!(bars[0].ts_event, UnixNanos::from(60_000_000_000));
5966    }
5967
5968    #[rstest]
5969    fn test_renko_bar_aggregator_multiple_bricks_in_one_update(audusd_sim: CurrencyPair) {
5970        let instrument = InstrumentAny::CurrencyPair(audusd_sim);
5971        let bar_spec = BarSpecification::new(10, BarAggregation::Renko, PriceType::Mid); // 10 pip brick size
5972        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
5973        let (handler, record) = recording_handler();
5974
5975        let mut aggregator = RenkoBarAggregator::new(
5976            bar_type,
5977            instrument.price_precision(),
5978            instrument.size_precision(),
5979            instrument.price_increment(),
5980            record,
5981        );
5982
5983        // Large price movement creating multiple bricks (25 pips = 2 bricks)
5984        aggregator.update(
5985            Price::from("1.00000"),
5986            Quantity::from(1),
5987            UnixNanos::default(),
5988        );
5989        aggregator.update(
5990            Price::from("1.00025"),
5991            Quantity::from(1),
5992            UnixNanos::from(1000),
5993        );
5994
5995        let handler_guard = handler.lock();
5996        assert_eq!(handler_guard.len(), 2);
5997
5998        let bar1 = &handler_guard[0];
5999        assert_eq!(bar1.open, Price::from("1.00000"));
6000        assert_eq!(bar1.high, Price::from("1.00010"));
6001        assert_eq!(bar1.low, Price::from("1.00000"));
6002        assert_eq!(bar1.close, Price::from("1.00010"));
6003
6004        let bar2 = &handler_guard[1];
6005        assert_eq!(bar2.open, Price::from("1.00010"));
6006        assert_eq!(bar2.high, Price::from("1.00020"));
6007        assert_eq!(bar2.low, Price::from("1.00010"));
6008        assert_eq!(bar2.close, Price::from("1.00020"));
6009    }
6010
6011    #[rstest]
6012    fn test_renko_bar_aggregator_downward_movement(audusd_sim: CurrencyPair) {
6013        let instrument = InstrumentAny::CurrencyPair(audusd_sim);
6014        let bar_spec = BarSpecification::new(10, BarAggregation::Renko, PriceType::Mid); // 10 pip brick size
6015        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6016        let (handler, record) = recording_handler();
6017
6018        let mut aggregator = RenkoBarAggregator::new(
6019            bar_type,
6020            instrument.price_precision(),
6021            instrument.size_precision(),
6022            instrument.price_increment(),
6023            record,
6024        );
6025
6026        // Start at higher price and move down
6027        aggregator.update(
6028            Price::from("1.00020"),
6029            Quantity::from(1),
6030            UnixNanos::default(),
6031        );
6032        aggregator.update(
6033            Price::from("1.00005"),
6034            Quantity::from(1),
6035            UnixNanos::from(1000),
6036        );
6037
6038        let handler_guard = handler.lock();
6039        assert_eq!(handler_guard.len(), 1);
6040
6041        let bar = handler_guard.first().unwrap();
6042        assert_eq!(bar.open, Price::from("1.00020"));
6043        assert_eq!(bar.high, Price::from("1.00020"));
6044        assert_eq!(bar.low, Price::from("1.00010"));
6045        assert_eq!(bar.close, Price::from("1.00010"));
6046        assert_eq!(bar.volume, Quantity::from(2));
6047    }
6048
6049    #[rstest]
6050    fn test_renko_bar_aggregator_handle_bar_below_brick_size(audusd_sim: CurrencyPair) {
6051        let instrument = InstrumentAny::CurrencyPair(audusd_sim);
6052        let bar_spec = BarSpecification::new(10, BarAggregation::Renko, PriceType::Mid); // 10 pip brick size
6053        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6054        let (handler, record) = recording_handler();
6055
6056        let mut aggregator = RenkoBarAggregator::new(
6057            bar_type,
6058            instrument.price_precision(),
6059            instrument.size_precision(),
6060            instrument.price_increment(),
6061            record,
6062        );
6063
6064        // Create a bar with small price movement (5 pips)
6065        let input_bar = Bar::new(
6066            BarType::new(
6067                instrument.id(),
6068                BarSpecification::new(1, BarAggregation::Minute, PriceType::Mid),
6069                AggregationSource::Internal,
6070            ),
6071            Price::from("1.00000"),
6072            Price::from("1.00005"),
6073            Price::from("0.99995"),
6074            Price::from("1.00005"), // 5 pip move up (less than 10 pip brick)
6075            Quantity::from(100),
6076            UnixNanos::default(),
6077            UnixNanos::from(1000),
6078        );
6079
6080        aggregator.handle_bar(input_bar);
6081
6082        let handler_guard = handler.lock();
6083        assert_eq!(handler_guard.len(), 0); // No bar created yet
6084    }
6085
6086    #[rstest]
6087    fn test_renko_bar_aggregator_handle_bar_exceeds_brick_size(audusd_sim: CurrencyPair) {
6088        let instrument = InstrumentAny::CurrencyPair(audusd_sim);
6089        let bar_spec = BarSpecification::new(10, BarAggregation::Renko, PriceType::Mid); // 10 pip brick size
6090        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6091        let (handler, record) = recording_handler();
6092
6093        let mut aggregator = RenkoBarAggregator::new(
6094            bar_type,
6095            instrument.price_precision(),
6096            instrument.size_precision(),
6097            instrument.price_increment(),
6098            record,
6099        );
6100
6101        // First bar to establish baseline
6102        let bar1 = Bar::new(
6103            BarType::new(
6104                instrument.id(),
6105                BarSpecification::new(1, BarAggregation::Minute, PriceType::Mid),
6106                AggregationSource::Internal,
6107            ),
6108            Price::from("1.00000"),
6109            Price::from("1.00005"),
6110            Price::from("0.99995"),
6111            Price::from("1.00000"),
6112            Quantity::from(100),
6113            UnixNanos::default(),
6114            UnixNanos::default(),
6115        );
6116
6117        // Second bar with price movement exceeding brick size (10 pips)
6118        let bar2 = Bar::new(
6119            BarType::new(
6120                instrument.id(),
6121                BarSpecification::new(1, BarAggregation::Minute, PriceType::Mid),
6122                AggregationSource::Internal,
6123            ),
6124            Price::from("1.00000"),
6125            Price::from("1.00015"),
6126            Price::from("0.99995"),
6127            Price::from("1.00010"), // 10 pip move up (exactly 1 brick)
6128            Quantity::from(50),
6129            UnixNanos::from(60_000_000_000),
6130            UnixNanos::from(60_000_000_000),
6131        );
6132
6133        aggregator.handle_bar(bar1);
6134        aggregator.handle_bar(bar2);
6135
6136        let handler_guard = handler.lock();
6137        assert_eq!(handler_guard.len(), 1);
6138
6139        let bar = handler_guard.first().unwrap();
6140        assert_eq!(bar.open, Price::from("1.00000"));
6141        assert_eq!(bar.high, Price::from("1.00010"));
6142        assert_eq!(bar.low, Price::from("1.00000"));
6143        assert_eq!(bar.close, Price::from("1.00010"));
6144        assert_eq!(bar.volume, Quantity::from(150));
6145    }
6146
6147    #[rstest]
6148    fn test_renko_bar_aggregator_handle_bar_multiple_bricks(audusd_sim: CurrencyPair) {
6149        let instrument = InstrumentAny::CurrencyPair(audusd_sim);
6150        let bar_spec = BarSpecification::new(10, BarAggregation::Renko, PriceType::Mid); // 10 pip brick size
6151        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6152        let (handler, record) = recording_handler();
6153
6154        let mut aggregator = RenkoBarAggregator::new(
6155            bar_type,
6156            instrument.price_precision(),
6157            instrument.size_precision(),
6158            instrument.price_increment(),
6159            record,
6160        );
6161
6162        // First bar to establish baseline
6163        let bar1 = Bar::new(
6164            BarType::new(
6165                instrument.id(),
6166                BarSpecification::new(1, BarAggregation::Minute, PriceType::Mid),
6167                AggregationSource::Internal,
6168            ),
6169            Price::from("1.00000"),
6170            Price::from("1.00005"),
6171            Price::from("0.99995"),
6172            Price::from("1.00000"),
6173            Quantity::from(100),
6174            UnixNanos::default(),
6175            UnixNanos::default(),
6176        );
6177
6178        // Second bar with large price movement (30 pips = 3 bricks)
6179        let bar2 = Bar::new(
6180            BarType::new(
6181                instrument.id(),
6182                BarSpecification::new(1, BarAggregation::Minute, PriceType::Mid),
6183                AggregationSource::Internal,
6184            ),
6185            Price::from("1.00000"),
6186            Price::from("1.00035"),
6187            Price::from("0.99995"),
6188            Price::from("1.00030"), // 30 pip move up (exactly 3 bricks)
6189            Quantity::from(50),
6190            UnixNanos::from(60_000_000_000),
6191            UnixNanos::from(60_000_000_000),
6192        );
6193
6194        aggregator.handle_bar(bar1);
6195        aggregator.handle_bar(bar2);
6196
6197        let handler_guard = handler.lock();
6198        assert_eq!(handler_guard.len(), 3);
6199
6200        let bar1 = &handler_guard[0];
6201        assert_eq!(bar1.open, Price::from("1.00000"));
6202        assert_eq!(bar1.close, Price::from("1.00010"));
6203
6204        let bar2 = &handler_guard[1];
6205        assert_eq!(bar2.open, Price::from("1.00010"));
6206        assert_eq!(bar2.close, Price::from("1.00020"));
6207
6208        let bar3 = &handler_guard[2];
6209        assert_eq!(bar3.open, Price::from("1.00020"));
6210        assert_eq!(bar3.close, Price::from("1.00030"));
6211    }
6212
6213    #[rstest]
6214    fn test_renko_bar_aggregator_handle_bar_downward_movement(audusd_sim: CurrencyPair) {
6215        let instrument = InstrumentAny::CurrencyPair(audusd_sim);
6216        let bar_spec = BarSpecification::new(10, BarAggregation::Renko, PriceType::Mid); // 10 pip brick size
6217        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6218        let (handler, record) = recording_handler();
6219
6220        let mut aggregator = RenkoBarAggregator::new(
6221            bar_type,
6222            instrument.price_precision(),
6223            instrument.size_precision(),
6224            instrument.price_increment(),
6225            record,
6226        );
6227
6228        // First bar to establish baseline
6229        let bar1 = Bar::new(
6230            BarType::new(
6231                instrument.id(),
6232                BarSpecification::new(1, BarAggregation::Minute, PriceType::Mid),
6233                AggregationSource::Internal,
6234            ),
6235            Price::from("1.00020"),
6236            Price::from("1.00025"),
6237            Price::from("1.00015"),
6238            Price::from("1.00020"),
6239            Quantity::from(100),
6240            UnixNanos::default(),
6241            UnixNanos::default(),
6242        );
6243
6244        // Second bar with downward price movement (10 pips down)
6245        let bar2 = Bar::new(
6246            BarType::new(
6247                instrument.id(),
6248                BarSpecification::new(1, BarAggregation::Minute, PriceType::Mid),
6249                AggregationSource::Internal,
6250            ),
6251            Price::from("1.00020"),
6252            Price::from("1.00025"),
6253            Price::from("1.00005"),
6254            Price::from("1.00010"), // 10 pip move down (exactly 1 brick)
6255            Quantity::from(50),
6256            UnixNanos::from(60_000_000_000),
6257            UnixNanos::from(60_000_000_000),
6258        );
6259
6260        aggregator.handle_bar(bar1);
6261        aggregator.handle_bar(bar2);
6262
6263        let handler_guard = handler.lock();
6264        assert_eq!(handler_guard.len(), 1);
6265
6266        let bar = handler_guard.first().unwrap();
6267        assert_eq!(bar.open, Price::from("1.00020"));
6268        assert_eq!(bar.high, Price::from("1.00020"));
6269        assert_eq!(bar.low, Price::from("1.00010"));
6270        assert_eq!(bar.close, Price::from("1.00010"));
6271        assert_eq!(bar.volume, Quantity::from(150));
6272    }
6273
6274    #[rstest]
6275    fn test_renko_bar_aggregator_brick_size_calculation(audusd_sim: CurrencyPair) {
6276        let instrument = InstrumentAny::CurrencyPair(audusd_sim);
6277
6278        // Test different brick sizes
6279        let bar_spec_5 = BarSpecification::new(5, BarAggregation::Renko, PriceType::Mid); // 5 pip brick size
6280        let bar_type_5 = BarType::new(instrument.id(), bar_spec_5, AggregationSource::Internal);
6281        let (_handler_5, record) = recording_handler();
6282
6283        let aggregator_5 = RenkoBarAggregator::new(
6284            bar_type_5,
6285            instrument.price_precision(),
6286            instrument.size_precision(),
6287            instrument.price_increment(),
6288            record,
6289        );
6290
6291        // 5 pips * price_increment.raw (depends on precision mode)
6292        let expected_brick_size_5 = Price::from_decimal_dp(
6293            instrument.price_increment() * Decimal::from(5),
6294            instrument.price_precision(),
6295        )
6296        .unwrap();
6297        assert_eq!(aggregator_5.brick_size, expected_brick_size_5);
6298
6299        let bar_spec_20 = BarSpecification::new(20, BarAggregation::Renko, PriceType::Mid); // 20 pip brick size
6300        let bar_type_20 = BarType::new(instrument.id(), bar_spec_20, AggregationSource::Internal);
6301        let (_handler_20, record) = recording_handler();
6302
6303        let aggregator_20 = RenkoBarAggregator::new(
6304            bar_type_20,
6305            instrument.price_precision(),
6306            instrument.size_precision(),
6307            instrument.price_increment(),
6308            record,
6309        );
6310
6311        // 20 pips * price_increment.raw (depends on precision mode)
6312        let expected_brick_size_20 = Price::from_decimal_dp(
6313            instrument.price_increment() * Decimal::from(20),
6314            instrument.price_precision(),
6315        )
6316        .unwrap();
6317        assert_eq!(aggregator_20.brick_size, expected_brick_size_20);
6318    }
6319
6320    #[rstest]
6321    fn test_renko_bar_aggregator_sequential_updates(audusd_sim: CurrencyPair) {
6322        let instrument = InstrumentAny::CurrencyPair(audusd_sim);
6323        let bar_spec = BarSpecification::new(10, BarAggregation::Renko, PriceType::Mid); // 10 pip brick size
6324        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6325        let (handler, record) = recording_handler();
6326
6327        let mut aggregator = RenkoBarAggregator::new(
6328            bar_type,
6329            instrument.price_precision(),
6330            instrument.size_precision(),
6331            instrument.price_increment(),
6332            record,
6333        );
6334
6335        // Sequential updates creating multiple bars
6336        aggregator.update(
6337            Price::from("1.00000"),
6338            Quantity::from(1),
6339            UnixNanos::from(1000),
6340        );
6341        aggregator.update(
6342            Price::from("1.00010"),
6343            Quantity::from(1),
6344            UnixNanos::from(2000),
6345        ); // First brick
6346        aggregator.update(
6347            Price::from("1.00020"),
6348            Quantity::from(1),
6349            UnixNanos::from(3000),
6350        ); // Second brick
6351        aggregator.update(
6352            Price::from("1.00025"),
6353            Quantity::from(1),
6354            UnixNanos::from(4000),
6355        ); // Partial third brick
6356        aggregator.update(
6357            Price::from("1.00030"),
6358            Quantity::from(1),
6359            UnixNanos::from(5000),
6360        ); // Complete third brick
6361
6362        let handler_guard = handler.lock();
6363        assert_eq!(handler_guard.len(), 3);
6364
6365        let bar1 = &handler_guard[0];
6366        assert_eq!(bar1.open, Price::from("1.00000"));
6367        assert_eq!(bar1.close, Price::from("1.00010"));
6368
6369        let bar2 = &handler_guard[1];
6370        assert_eq!(bar2.open, Price::from("1.00010"));
6371        assert_eq!(bar2.close, Price::from("1.00020"));
6372
6373        let bar3 = &handler_guard[2];
6374        assert_eq!(bar3.open, Price::from("1.00020"));
6375        assert_eq!(bar3.close, Price::from("1.00030"));
6376    }
6377
6378    #[rstest]
6379    fn test_renko_bar_aggregator_mixed_direction_movement(audusd_sim: CurrencyPair) {
6380        let instrument = InstrumentAny::CurrencyPair(audusd_sim);
6381        let bar_spec = BarSpecification::new(10, BarAggregation::Renko, PriceType::Mid); // 10 pip brick size
6382        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6383        let (handler, record) = recording_handler();
6384
6385        let mut aggregator = RenkoBarAggregator::new(
6386            bar_type,
6387            instrument.price_precision(),
6388            instrument.size_precision(),
6389            instrument.price_increment(),
6390            record,
6391        );
6392
6393        // Mixed direction movement: up then down
6394        aggregator.update(
6395            Price::from("1.00000"),
6396            Quantity::from(1),
6397            UnixNanos::from(1000),
6398        );
6399        aggregator.update(
6400            Price::from("1.00010"),
6401            Quantity::from(1),
6402            UnixNanos::from(2000),
6403        ); // Up brick
6404        aggregator.update(
6405            Price::from("0.99990"),
6406            Quantity::from(1),
6407            UnixNanos::from(3000),
6408        ); // Down 2 bricks (20 pips)
6409
6410        let handler_guard = handler.lock();
6411        assert_eq!(handler_guard.len(), 3);
6412
6413        let bar1 = &handler_guard[0]; // Up brick
6414        assert_eq!(bar1.open, Price::from("1.00000"));
6415        assert_eq!(bar1.high, Price::from("1.00010"));
6416        assert_eq!(bar1.low, Price::from("1.00000"));
6417        assert_eq!(bar1.close, Price::from("1.00010"));
6418
6419        let bar2 = &handler_guard[1]; // First down brick
6420        assert_eq!(bar2.open, Price::from("1.00010"));
6421        assert_eq!(bar2.high, Price::from("1.00010"));
6422        assert_eq!(bar2.low, Price::from("1.00000"));
6423        assert_eq!(bar2.close, Price::from("1.00000"));
6424
6425        let bar3 = &handler_guard[2]; // Second down brick
6426        assert_eq!(bar3.open, Price::from("1.00000"));
6427        assert_eq!(bar3.high, Price::from("1.00000"));
6428        assert_eq!(bar3.low, Price::from("0.99990"));
6429        assert_eq!(bar3.close, Price::from("0.99990"));
6430    }
6431
6432    #[rstest]
6433    fn test_tick_imbalance_bar_aggregator_mixed_trades_cancel_out(equity_aapl: Equity) {
6434        let instrument = InstrumentAny::Equity(equity_aapl);
6435        let bar_spec = BarSpecification::new(3, BarAggregation::TickImbalance, PriceType::Last);
6436        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6437        let (handler, record) = recording_handler();
6438
6439        let mut aggregator = TickImbalanceBarAggregator::new(
6440            bar_type,
6441            instrument.price_precision(),
6442            instrument.size_precision(),
6443            record,
6444        );
6445
6446        let buy = TradeTick {
6447            aggressor_side: AggressorSide::Buy,
6448            ..TradeTick::default()
6449        };
6450        let sell = TradeTick {
6451            aggressor_side: AggressorSide::Sell,
6452            ..TradeTick::default()
6453        };
6454
6455        aggregator.handle_trade(buy);
6456        aggregator.handle_trade(sell);
6457        aggregator.handle_trade(buy);
6458
6459        let handler_guard = handler.lock();
6460        assert_eq!(handler_guard.len(), 0);
6461    }
6462
6463    #[rstest]
6464    fn test_tick_imbalance_bar_aggregator_no_aggressor_ignored(equity_aapl: Equity) {
6465        let instrument = InstrumentAny::Equity(equity_aapl);
6466        let bar_spec = BarSpecification::new(2, BarAggregation::TickImbalance, PriceType::Last);
6467        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6468        let (handler, record) = recording_handler();
6469
6470        let mut aggregator = TickImbalanceBarAggregator::new(
6471            bar_type,
6472            instrument.price_precision(),
6473            instrument.size_precision(),
6474            record,
6475        );
6476
6477        let buy = TradeTick {
6478            aggressor_side: AggressorSide::Buy,
6479            ..TradeTick::default()
6480        };
6481        let no_aggressor = TradeTick {
6482            aggressor_side: AggressorSide::NoAggressor,
6483            ..TradeTick::default()
6484        };
6485
6486        aggregator.handle_trade(buy);
6487        aggregator.handle_trade(no_aggressor);
6488        aggregator.handle_trade(buy);
6489
6490        let handler_guard = handler.lock();
6491        assert_eq!(handler_guard.len(), 1);
6492    }
6493
6494    #[rstest]
6495    fn test_tick_runs_bar_aggregator_multiple_consecutive_runs(equity_aapl: Equity) {
6496        let instrument = InstrumentAny::Equity(equity_aapl);
6497        let bar_spec = BarSpecification::new(2, BarAggregation::TickRuns, PriceType::Last);
6498        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6499        let (handler, record) = recording_handler();
6500
6501        let mut aggregator = TickRunsBarAggregator::new(
6502            bar_type,
6503            instrument.price_precision(),
6504            instrument.size_precision(),
6505            record,
6506        );
6507
6508        let buy = TradeTick {
6509            aggressor_side: AggressorSide::Buy,
6510            ..TradeTick::default()
6511        };
6512        let sell = TradeTick {
6513            aggressor_side: AggressorSide::Sell,
6514            ..TradeTick::default()
6515        };
6516
6517        aggregator.handle_trade(buy);
6518        aggregator.handle_trade(buy);
6519        aggregator.handle_trade(sell);
6520        aggregator.handle_trade(sell);
6521
6522        let handler_guard = handler.lock();
6523        assert_eq!(handler_guard.len(), 2);
6524    }
6525
6526    #[rstest]
6527    fn test_volume_imbalance_bar_aggregator_large_trade_spans_bars(equity_aapl: Equity) {
6528        let instrument = InstrumentAny::Equity(equity_aapl);
6529        let bar_spec = BarSpecification::new(10, BarAggregation::VolumeImbalance, PriceType::Last);
6530        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6531        let (handler, record) = recording_handler();
6532
6533        let mut aggregator = VolumeImbalanceBarAggregator::new(
6534            bar_type,
6535            instrument.price_precision(),
6536            instrument.size_precision(),
6537            record,
6538        );
6539
6540        let large_trade = TradeTick {
6541            size: Quantity::from(25),
6542            aggressor_side: AggressorSide::Buy,
6543            ..TradeTick::default()
6544        };
6545
6546        aggregator.handle_trade(large_trade);
6547
6548        let handler_guard = handler.lock();
6549        assert_eq!(handler_guard.len(), 2);
6550    }
6551
6552    #[rstest]
6553    fn test_volume_imbalance_bar_aggregator_no_aggressor_does_not_affect_imbalance(
6554        equity_aapl: Equity,
6555    ) {
6556        let instrument = InstrumentAny::Equity(equity_aapl);
6557        let bar_spec = BarSpecification::new(10, BarAggregation::VolumeImbalance, PriceType::Last);
6558        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6559        let (handler, record) = recording_handler();
6560
6561        let mut aggregator = VolumeImbalanceBarAggregator::new(
6562            bar_type,
6563            instrument.price_precision(),
6564            instrument.size_precision(),
6565            record,
6566        );
6567
6568        let buy = TradeTick {
6569            size: Quantity::from(5),
6570            aggressor_side: AggressorSide::Buy,
6571            ..TradeTick::default()
6572        };
6573        let no_aggressor = TradeTick {
6574            size: Quantity::from(3),
6575            aggressor_side: AggressorSide::NoAggressor,
6576            ..TradeTick::default()
6577        };
6578
6579        aggregator.handle_trade(buy);
6580        aggregator.handle_trade(no_aggressor);
6581        aggregator.handle_trade(buy);
6582
6583        let handler_guard = handler.lock();
6584        assert_eq!(handler_guard.len(), 1);
6585    }
6586
6587    #[rstest]
6588    fn test_volume_runs_bar_aggregator_large_trade_spans_bars(equity_aapl: Equity) {
6589        let instrument = InstrumentAny::Equity(equity_aapl);
6590        let bar_spec = BarSpecification::new(10, BarAggregation::VolumeRuns, PriceType::Last);
6591        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6592        let (handler, record) = recording_handler();
6593
6594        let mut aggregator = VolumeRunsBarAggregator::new(
6595            bar_type,
6596            instrument.price_precision(),
6597            instrument.size_precision(),
6598            record,
6599        );
6600
6601        let large_trade = TradeTick {
6602            size: Quantity::from(25),
6603            aggressor_side: AggressorSide::Buy,
6604            ..TradeTick::default()
6605        };
6606
6607        aggregator.handle_trade(large_trade);
6608
6609        let handler_guard = handler.lock();
6610        assert_eq!(handler_guard.len(), 2);
6611    }
6612
6613    #[rstest]
6614    fn test_value_runs_bar_aggregator_large_trade_spans_bars(equity_aapl: Equity) {
6615        let instrument = InstrumentAny::Equity(equity_aapl);
6616        let bar_spec = BarSpecification::new(50, BarAggregation::ValueRuns, PriceType::Last);
6617        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6618        let (handler, record) = recording_handler();
6619
6620        let mut aggregator = ValueRunsBarAggregator::new(
6621            bar_type,
6622            instrument.price_precision(),
6623            instrument.size_precision(),
6624            record,
6625        );
6626
6627        let large_trade = TradeTick {
6628            price: Price::from("5.00"),
6629            size: Quantity::from(25),
6630            aggressor_side: AggressorSide::Buy,
6631            ..TradeTick::default()
6632        };
6633
6634        aggregator.handle_trade(large_trade);
6635
6636        let handler_guard = handler.lock();
6637        assert_eq!(handler_guard.len(), 2);
6638    }
6639
6640    #[rstest]
6641    fn test_value_runs_bar_aggregator_keeps_leftover_volume_for_same_side_run(equity_aapl: Equity) {
6642        let instrument = InstrumentAny::Equity(equity_aapl);
6643        let bar_spec = BarSpecification::new(100, BarAggregation::ValueRuns, PriceType::Last);
6644        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6645        let (handler, record) = recording_handler();
6646
6647        let mut aggregator = ValueRunsBarAggregator::new(
6648            bar_type,
6649            instrument.price_precision(),
6650            instrument.size_precision(),
6651            record,
6652        );
6653
6654        // First trade spans one bar (value 150 = step 100 + 50 leftover), the
6655        // leftover 5 units must survive as the start of a new same-side run.
6656        let first = TradeTick {
6657            price: Price::from("10.00"),
6658            size: Quantity::from(15),
6659            aggressor_side: AggressorSide::Sell,
6660            ts_event: UnixNanos::from(1_000),
6661            ts_init: UnixNanos::from(1_000),
6662            ..TradeTick::default()
6663        };
6664        aggregator.handle_trade(first);
6665
6666        // Second same-side trade completes the run (50 + 50 >= 100).
6667        let second = TradeTick {
6668            price: Price::from("10.00"),
6669            size: Quantity::from(5),
6670            aggressor_side: AggressorSide::Sell,
6671            ts_event: UnixNanos::from(2_000),
6672            ts_init: UnixNanos::from(2_000),
6673            ..TradeTick::default()
6674        };
6675        aggregator.handle_trade(second);
6676
6677        let handler_guard = handler.lock();
6678        assert_eq!(handler_guard.len(), 2);
6679        assert_eq!(handler_guard[0].volume, Quantity::from(10));
6680        assert_eq!(handler_guard[1].volume, Quantity::from(10));
6681    }
6682
6683    #[rstest]
6684    fn test_value_bar_high_price_low_step_no_zero_volume_bars(equity_aapl: Equity) {
6685        let instrument = InstrumentAny::Equity(equity_aapl);
6686        let bar_spec = BarSpecification::new(100, BarAggregation::Value, PriceType::Last);
6687        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6688        let (handler, record) = recording_handler();
6689
6690        let mut aggregator = ValueBarAggregator::new(
6691            bar_type,
6692            instrument.price_precision(),
6693            instrument.size_precision(),
6694            record,
6695        );
6696
6697        // price=1000, size=3, value=3000, step=100 → size_chunk=0.1 rounds to 0 at precision 0
6698        aggregator.update(
6699            Price::from("1000.00"),
6700            Quantity::from(3),
6701            UnixNanos::default(),
6702        );
6703
6704        // 3 bars (one per min-size unit), not 30 zero-volume bars
6705        let handler_guard = handler.lock();
6706        assert_eq!(handler_guard.len(), 3);
6707        for bar in handler_guard.iter() {
6708            assert_eq!(bar.volume, Quantity::from(1));
6709        }
6710    }
6711
6712    #[rstest]
6713    fn test_value_imbalance_high_price_low_step_no_zero_volume_bars(equity_aapl: Equity) {
6714        let instrument = InstrumentAny::Equity(equity_aapl);
6715        let bar_spec = BarSpecification::new(100, BarAggregation::ValueImbalance, PriceType::Last);
6716        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6717        let (handler, record) = recording_handler();
6718
6719        let mut aggregator = ValueImbalanceBarAggregator::new(
6720            bar_type,
6721            instrument.price_precision(),
6722            instrument.size_precision(),
6723            record,
6724        );
6725
6726        let trade = TradeTick {
6727            price: Price::from("1000.00"),
6728            size: Quantity::from(3),
6729            aggressor_side: AggressorSide::Buy,
6730            instrument_id: instrument.id(),
6731            ..TradeTick::default()
6732        };
6733
6734        aggregator.handle_trade(trade);
6735
6736        let handler_guard = handler.lock();
6737        assert_eq!(handler_guard.len(), 3);
6738        for bar in handler_guard.iter() {
6739            assert_eq!(bar.volume, Quantity::from(1));
6740        }
6741    }
6742
6743    #[rstest]
6744    fn test_value_imbalance_opposite_side_overshoot_emits_bar(equity_aapl: Equity) {
6745        let instrument = InstrumentAny::Equity(equity_aapl);
6746        let bar_spec = BarSpecification::new(100, BarAggregation::ValueImbalance, PriceType::Last);
6747        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6748        let (handler, record) = recording_handler();
6749
6750        let mut aggregator = ValueImbalanceBarAggregator::new(
6751            bar_type,
6752            instrument.price_precision(),
6753            instrument.size_precision(),
6754            record,
6755        );
6756
6757        // Build seller imbalance of -50 (below step=100, no bar yet)
6758        let sell_tick = TradeTick {
6759            price: Price::from("10.00"),
6760            size: Quantity::from(5),
6761            aggressor_side: AggressorSide::Sell,
6762            instrument_id: instrument.id(),
6763            ..TradeTick::default()
6764        };
6765
6766        // Opposite-side buyer: flatten amount 50/1000=0.05 < min_size (1),
6767        // clamp overshoots imbalance from -50 to +950, crossing threshold
6768        let buy_tick = TradeTick {
6769            price: Price::from("1000.00"),
6770            size: Quantity::from(1),
6771            aggressor_side: AggressorSide::Buy,
6772            instrument_id: instrument.id(),
6773            ts_init: UnixNanos::from(1),
6774            ts_event: UnixNanos::from(1),
6775            ..TradeTick::default()
6776        };
6777
6778        aggregator.handle_trade(sell_tick);
6779        aggregator.handle_trade(buy_tick);
6780
6781        let handler_guard = handler.lock();
6782        assert_eq!(handler_guard.len(), 1);
6783        assert_eq!(handler_guard[0].volume, Quantity::from(6));
6784    }
6785
6786    #[rstest]
6787    fn test_value_runs_high_price_low_step_no_zero_volume_bars(equity_aapl: Equity) {
6788        let instrument = InstrumentAny::Equity(equity_aapl);
6789        let bar_spec = BarSpecification::new(100, BarAggregation::ValueRuns, PriceType::Last);
6790        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
6791        let (handler, record) = recording_handler();
6792
6793        let mut aggregator = ValueRunsBarAggregator::new(
6794            bar_type,
6795            instrument.price_precision(),
6796            instrument.size_precision(),
6797            record,
6798        );
6799
6800        let trade = TradeTick {
6801            price: Price::from("1000.00"),
6802            size: Quantity::from(3),
6803            aggressor_side: AggressorSide::Buy,
6804            instrument_id: instrument.id(),
6805            ..TradeTick::default()
6806        };
6807
6808        aggregator.handle_trade(trade);
6809
6810        let handler_guard = handler.lock();
6811        assert_eq!(handler_guard.len(), 3);
6812        for bar in handler_guard.iter() {
6813            assert_eq!(bar.volume, Quantity::from(1));
6814        }
6815    }
6816
6817    #[rstest]
6818    fn test_value_imbalance_bar_aggregator_exact_below_step_retains_pending() {
6819        // step=9_007_199_254; a single buy of 9007199253.999999999 @ price 1 has a notional
6820        // exactly one raw unit below the step. Exact Decimal arithmetic must NOT emit a bar; the
6821        // prior f64 path rounded the size up to 9007199254.0 and emitted early.
6822        let instrument_id = InstrumentId::from("AAPL.XNAS");
6823        let bar_spec = BarSpecification::new(
6824            9_007_199_254,
6825            BarAggregation::ValueImbalance,
6826            PriceType::Last,
6827        );
6828        let bar_type = BarType::new(instrument_id, bar_spec, AggregationSource::Internal);
6829        let (handler, record) = recording_handler();
6830
6831        let mut aggregator = ValueImbalanceBarAggregator::new(bar_type, 0, 9, record);
6832
6833        let below_step = TradeTick {
6834            instrument_id,
6835            price: Price::from("1"),
6836            size: Quantity::from("9007199253.999999999"),
6837            aggressor_side: AggressorSide::Buy,
6838            ..TradeTick::default()
6839        };
6840        aggregator.handle_trade(below_step);
6841
6842        assert!(handler.lock().is_empty());
6843        assert_eq!(
6844            aggregator.core.builder.volume,
6845            Quantity::from("9007199253.999999999"),
6846        );
6847
6848        // One additional raw unit lifts the notional to exactly the step, emitting one bar whose
6849        // volume is the exact total raw input.
6850        let one_raw_unit = TradeTick {
6851            instrument_id,
6852            price: Price::from("1"),
6853            size: Quantity::from("0.000000001"),
6854            aggressor_side: AggressorSide::Buy,
6855            ts_event: UnixNanos::from(1),
6856            ts_init: UnixNanos::from(1),
6857            ..TradeTick::default()
6858        };
6859        aggregator.handle_trade(one_raw_unit);
6860
6861        let handler_guard = handler.lock();
6862        assert_eq!(handler_guard.len(), 1);
6863        assert_eq!(
6864            handler_guard[0].volume,
6865            Quantity::from("9007199254.000000000")
6866        );
6867        assert_eq!(aggregator.core.builder.volume, Quantity::zero(9));
6868    }
6869
6870    #[rstest]
6871    fn test_value_imbalance_bar_aggregator_conserves_volume_across_split_bars() {
6872        // step=4, price=1: a same-side buy of 10.000000003 splits into two full bars of value 4
6873        // and leaves a fractional 2.000000003 pending. Emitted plus pending volume must equal the
6874        // exact input across the several split bars.
6875        let instrument_id = InstrumentId::from("AAPL.XNAS");
6876        let bar_spec = BarSpecification::new(4, BarAggregation::ValueImbalance, PriceType::Last);
6877        let bar_type = BarType::new(instrument_id, bar_spec, AggregationSource::Internal);
6878        let (handler, record) = recording_handler();
6879
6880        let mut aggregator = ValueImbalanceBarAggregator::new(bar_type, 0, 9, record);
6881
6882        let input = Quantity::from("10.000000003");
6883        let trade = TradeTick {
6884            instrument_id,
6885            price: Price::from("1"),
6886            size: input,
6887            aggressor_side: AggressorSide::Buy,
6888            ..TradeTick::default()
6889        };
6890        aggregator.handle_trade(trade);
6891
6892        let handler_guard = handler.lock();
6893        assert_eq!(handler_guard.len(), 2);
6894        for bar in handler_guard.iter() {
6895            assert_eq!(bar.volume, Quantity::from("4.000000000"));
6896        }
6897        assert_eq!(
6898            aggregator.core.builder.volume,
6899            Quantity::from("2.000000003"),
6900        );
6901        let emitted_plus_pending = handler_guard
6902            .iter()
6903            .map(|bar| bar.volume.as_decimal())
6904            .sum::<Decimal>()
6905            + aggregator.core.builder.volume.as_decimal();
6906        assert_eq!(emitted_plus_pending, input.as_decimal());
6907    }
6908
6909    #[rstest]
6910    fn test_value_runs_bar_aggregator_exact_below_step_retains_pending() {
6911        // step=9_007_199_254; a single buy of 9007199253.999999999 @ price 1 sits one raw unit
6912        // below the step. Exact Decimal arithmetic must NOT emit a bar; the prior f64 path rounded
6913        // the size up and emitted early.
6914        let instrument_id = InstrumentId::from("AAPL.XNAS");
6915        let bar_spec =
6916            BarSpecification::new(9_007_199_254, BarAggregation::ValueRuns, PriceType::Last);
6917        let bar_type = BarType::new(instrument_id, bar_spec, AggregationSource::Internal);
6918        let (handler, record) = recording_handler();
6919
6920        let mut aggregator = ValueRunsBarAggregator::new(bar_type, 0, 9, record);
6921
6922        let below_step = TradeTick {
6923            instrument_id,
6924            price: Price::from("1"),
6925            size: Quantity::from("9007199253.999999999"),
6926            aggressor_side: AggressorSide::Buy,
6927            ..TradeTick::default()
6928        };
6929        aggregator.handle_trade(below_step);
6930
6931        assert!(handler.lock().is_empty());
6932        assert_eq!(
6933            aggregator.core.builder.volume,
6934            Quantity::from("9007199253.999999999"),
6935        );
6936
6937        // One additional same-side raw unit completes the run at exactly the step, emitting one bar
6938        // whose volume is the exact total raw input.
6939        let one_raw_unit = TradeTick {
6940            instrument_id,
6941            price: Price::from("1"),
6942            size: Quantity::from("0.000000001"),
6943            aggressor_side: AggressorSide::Buy,
6944            ts_event: UnixNanos::from(1),
6945            ts_init: UnixNanos::from(1),
6946            ..TradeTick::default()
6947        };
6948        aggregator.handle_trade(one_raw_unit);
6949
6950        let handler_guard = handler.lock();
6951        assert_eq!(handler_guard.len(), 1);
6952        assert_eq!(
6953            handler_guard[0].volume,
6954            Quantity::from("9007199254.000000000")
6955        );
6956        assert_eq!(aggregator.core.builder.volume, Quantity::zero(9));
6957    }
6958
6959    #[rstest]
6960    fn test_value_runs_bar_aggregator_conserves_volume_across_split_bars() {
6961        // step=4, price=1: a same-side buy of 10.000000003 splits into two full bars of value 4 and
6962        // keeps a fractional 2.000000003 as the leftover of the same-side run. Emitted plus pending
6963        // volume must equal the exact input across the several split bars.
6964        let instrument_id = InstrumentId::from("AAPL.XNAS");
6965        let bar_spec = BarSpecification::new(4, BarAggregation::ValueRuns, PriceType::Last);
6966        let bar_type = BarType::new(instrument_id, bar_spec, AggregationSource::Internal);
6967        let (handler, record) = recording_handler();
6968
6969        let mut aggregator = ValueRunsBarAggregator::new(bar_type, 0, 9, record);
6970
6971        let input = Quantity::from("10.000000003");
6972        let trade = TradeTick {
6973            instrument_id,
6974            price: Price::from("1"),
6975            size: input,
6976            aggressor_side: AggressorSide::Buy,
6977            ..TradeTick::default()
6978        };
6979        aggregator.handle_trade(trade);
6980
6981        let handler_guard = handler.lock();
6982        assert_eq!(handler_guard.len(), 2);
6983        for bar in handler_guard.iter() {
6984            assert_eq!(bar.volume, Quantity::from("4.000000000"));
6985        }
6986        assert_eq!(
6987            aggregator.core.builder.volume,
6988            Quantity::from("2.000000003"),
6989        );
6990        let emitted_plus_pending = handler_guard
6991            .iter()
6992            .map(|bar| bar.volume.as_decimal())
6993            .sum::<Decimal>()
6994            + aggregator.core.builder.volume.as_decimal();
6995        assert_eq!(emitted_plus_pending, input.as_decimal());
6996    }
6997
6998    #[rstest]
6999    fn test_value_imbalance_bar_aggregator_no_aggressor_and_zero_price_fall_back_to_plain_volume() {
7000        // NoAggressor and zero-price trades carry no usable side signal, so they bypass imbalance
7001        // splitting and accumulate as plain builder volume without emitting a bar.
7002        let instrument_id = InstrumentId::from("AAPL.XNAS");
7003        let bar_spec = BarSpecification::new(100, BarAggregation::ValueImbalance, PriceType::Last);
7004        let bar_type = BarType::new(instrument_id, bar_spec, AggregationSource::Internal);
7005        let (handler, record) = recording_handler();
7006
7007        let mut aggregator = ValueImbalanceBarAggregator::new(bar_type, 2, 0, record);
7008
7009        let no_aggressor = TradeTick {
7010            instrument_id,
7011            price: Price::from("10.00"),
7012            size: Quantity::from(3),
7013            aggressor_side: AggressorSide::NoAggressor,
7014            ..TradeTick::default()
7015        };
7016        let zero_price = TradeTick {
7017            instrument_id,
7018            price: Price::from("0.00"),
7019            size: Quantity::from(4),
7020            aggressor_side: AggressorSide::Buy,
7021            ts_event: UnixNanos::from(1),
7022            ts_init: UnixNanos::from(1),
7023            ..TradeTick::default()
7024        };
7025        aggregator.handle_trade(no_aggressor);
7026        aggregator.handle_trade(zero_price);
7027
7028        assert!(handler.lock().is_empty());
7029        assert_eq!(aggregator.core.builder.volume, Quantity::from(7));
7030    }
7031
7032    #[rstest]
7033    fn test_value_runs_bar_aggregator_no_aggressor_and_zero_price_fall_back_to_plain_volume() {
7034        // NoAggressor and zero-price trades carry no usable side signal, so they bypass the run
7035        // splitting and accumulate as plain builder volume without emitting a bar or resetting.
7036        let instrument_id = InstrumentId::from("AAPL.XNAS");
7037        let bar_spec = BarSpecification::new(100, BarAggregation::ValueRuns, PriceType::Last);
7038        let bar_type = BarType::new(instrument_id, bar_spec, AggregationSource::Internal);
7039        let (handler, record) = recording_handler();
7040
7041        let mut aggregator = ValueRunsBarAggregator::new(bar_type, 2, 0, record);
7042
7043        let no_aggressor = TradeTick {
7044            instrument_id,
7045            price: Price::from("10.00"),
7046            size: Quantity::from(3),
7047            aggressor_side: AggressorSide::NoAggressor,
7048            ..TradeTick::default()
7049        };
7050        let zero_price = TradeTick {
7051            instrument_id,
7052            price: Price::from("0.00"),
7053            size: Quantity::from(4),
7054            aggressor_side: AggressorSide::Buy,
7055            ts_event: UnixNanos::from(1),
7056            ts_init: UnixNanos::from(1),
7057            ..TradeTick::default()
7058        };
7059        aggregator.handle_trade(no_aggressor);
7060        aggregator.handle_trade(zero_price);
7061
7062        assert!(handler.lock().is_empty());
7063        assert_eq!(aggregator.core.builder.volume, Quantity::from(7));
7064    }
7065
7066    #[rstest]
7067    fn test_value_imbalance_bar_aggregator_conserves_volume_with_indivisible_price() {
7068        // step=1, price=3, size precision 1: the ideal split 1/3 rounds to 0.3, so each emitted bar
7069        // carries a notional of 0.9 (below the step) exactly as the reference ValueBarAggregator
7070        // does with a non-dividing price. Per-bar notional is approximate by design, but total
7071        // volume (emitted plus pending) must still equal the exact input.
7072        let instrument_id = InstrumentId::from("AAPL.XNAS");
7073        let bar_spec = BarSpecification::new(1, BarAggregation::ValueImbalance, PriceType::Last);
7074        let bar_type = BarType::new(instrument_id, bar_spec, AggregationSource::Internal);
7075        let (handler, record) = recording_handler();
7076
7077        let mut aggregator = ValueImbalanceBarAggregator::new(bar_type, 2, 1, record);
7078
7079        let input = Quantity::from("1.0");
7080        let trade = TradeTick {
7081            instrument_id,
7082            price: Price::from("3.00"),
7083            size: input,
7084            aggressor_side: AggressorSide::Buy,
7085            ..TradeTick::default()
7086        };
7087        aggregator.handle_trade(trade);
7088
7089        let handler_guard = handler.lock();
7090        assert_eq!(handler_guard.len(), 3);
7091        for bar in handler_guard.iter() {
7092            assert_eq!(bar.volume, Quantity::from("0.3"));
7093        }
7094        assert_eq!(aggregator.core.builder.volume, Quantity::from("0.1"));
7095        let emitted_plus_pending = handler_guard
7096            .iter()
7097            .map(|bar| bar.volume.as_decimal())
7098            .sum::<Decimal>()
7099            + aggregator.core.builder.volume.as_decimal();
7100        assert_eq!(emitted_plus_pending, input.as_decimal());
7101    }
7102
7103    #[rstest]
7104    #[case::partial("0.1", "0.6", Decimal::new(2, 1), vec![])]
7105    #[case::neutral("0.2", "0.7", Decimal::ZERO, vec![])]
7106    #[case::reversal("0.3", "0.8", Decimal::new(-3, 1), vec![])]
7107    #[case::split("1.0", "0.2", Decimal::new(-6, 1), vec!["1.0", "0.3"])]
7108    fn test_value_imbalance_opposing_trade_preserves_ideal_notional(
7109        #[case] sell_size: &str,
7110        #[case] pending: &str,
7111        #[case] imbalance: Decimal,
7112        #[case] emitted: Vec<&str>,
7113    ) {
7114        let instrument_id = InstrumentId::from("AAPL.XNAS");
7115
7116        let bar_type = BarType::new(
7117            instrument_id,
7118            BarSpecification::new(1, BarAggregation::ValueImbalance, PriceType::Last),
7119            AggregationSource::Internal,
7120        );
7121
7122        let (handler, record) = recording_handler();
7123        let mut aggregator = ValueImbalanceBarAggregator::new(bar_type, 2, 1, record);
7124
7125        let buy = TradeTick {
7126            instrument_id,
7127            price: Price::from("1.00"),
7128            size: Quantity::from("0.5"),
7129            aggressor_side: AggressorSide::Buy,
7130            ..TradeTick::default()
7131        };
7132
7133        let sell = TradeTick {
7134            price: Price::from("3.00"),
7135            size: Quantity::from(sell_size),
7136            aggressor_side: AggressorSide::Sell,
7137            ts_event: UnixNanos::from(1),
7138            ts_init: UnixNanos::from(1),
7139            ..buy
7140        };
7141
7142        aggregator.handle_trade(buy);
7143        aggregator.handle_trade(sell);
7144        let expected: Vec<Bar> = emitted
7145            .iter()
7146            .enumerate()
7147            .map(|(index, volume)| {
7148                let open = if index == 0 { buy.price } else { sell.price };
7149                let volume = Quantity::from(*volume);
7150
7151                Bar::new(
7152                    bar_type,
7153                    open,
7154                    sell.price,
7155                    open,
7156                    sell.price,
7157                    volume,
7158                    sell.ts_init,
7159                    sell.ts_init,
7160                )
7161            })
7162            .collect();
7163
7164        assert_eq!(*handler.lock(), expected);
7165        assert_eq!(aggregator.core.builder.volume, Quantity::from(pending));
7166        assert_eq!(aggregator.imbalance_value, imbalance);
7167    }
7168
7169    #[rstest]
7170    fn test_value_runs_bar_aggregator_conserves_volume_with_indivisible_price() {
7171        // step=1, price=3, size precision 1: the ideal split 1/3 rounds to 0.3, so each emitted bar
7172        // carries a notional of 0.9 (below the step) exactly as the reference ValueBarAggregator
7173        // does with a non-dividing price. Per-bar notional is approximate by design, but total
7174        // volume (emitted plus pending) must still equal the exact input.
7175        let instrument_id = InstrumentId::from("AAPL.XNAS");
7176        let bar_spec = BarSpecification::new(1, BarAggregation::ValueRuns, PriceType::Last);
7177        let bar_type = BarType::new(instrument_id, bar_spec, AggregationSource::Internal);
7178        let (handler, record) = recording_handler();
7179
7180        let mut aggregator = ValueRunsBarAggregator::new(bar_type, 2, 1, record);
7181
7182        let input = Quantity::from("1.0");
7183        let trade = TradeTick {
7184            instrument_id,
7185            price: Price::from("3.00"),
7186            size: input,
7187            aggressor_side: AggressorSide::Buy,
7188            ..TradeTick::default()
7189        };
7190        aggregator.handle_trade(trade);
7191
7192        let handler_guard = handler.lock();
7193        assert_eq!(handler_guard.len(), 3);
7194        for bar in handler_guard.iter() {
7195            assert_eq!(bar.volume, Quantity::from("0.3"));
7196        }
7197        assert_eq!(aggregator.core.builder.volume, Quantity::from("0.1"));
7198        let emitted_plus_pending = handler_guard
7199            .iter()
7200            .map(|bar| bar.volume.as_decimal())
7201            .sum::<Decimal>()
7202            + aggregator.core.builder.volume.as_decimal();
7203        assert_eq!(emitted_plus_pending, input.as_decimal());
7204    }
7205
7206    #[rstest]
7207    #[case(1000_u64)]
7208    #[case(1500_u64)]
7209    fn test_volume_imbalance_bar_aggregator_large_step_no_overflow(
7210        equity_aapl: Equity,
7211        #[case] step: u64,
7212    ) {
7213        let instrument = InstrumentAny::Equity(equity_aapl);
7214        let bar_spec = BarSpecification::new(
7215            step as usize,
7216            BarAggregation::VolumeImbalance,
7217            PriceType::Last,
7218        );
7219        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
7220        let (handler, record) = recording_handler();
7221
7222        let mut aggregator = VolumeImbalanceBarAggregator::new(
7223            bar_type,
7224            instrument.price_precision(),
7225            instrument.size_precision(),
7226            record,
7227        );
7228
7229        let trade = TradeTick {
7230            size: Quantity::from(step * 2),
7231            aggressor_side: AggressorSide::Buy,
7232            ..TradeTick::default()
7233        };
7234
7235        aggregator.handle_trade(trade);
7236
7237        let handler_guard = handler.lock();
7238        assert_eq!(handler_guard.len(), 2);
7239        for bar in handler_guard.iter() {
7240            assert_eq!(bar.volume.as_f64(), step as f64);
7241        }
7242    }
7243
7244    #[rstest]
7245    fn test_volume_imbalance_bar_aggregator_different_large_steps_produce_different_bar_counts(
7246        equity_aapl: Equity,
7247    ) {
7248        let instrument = InstrumentAny::Equity(equity_aapl);
7249        let total_volume = 3000_u64;
7250        let mut results = Vec::new();
7251
7252        for step in [1000_usize, 1500] {
7253            let bar_spec =
7254                BarSpecification::new(step, BarAggregation::VolumeImbalance, PriceType::Last);
7255            let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
7256            let (handler, record) = recording_handler();
7257
7258            let mut aggregator = VolumeImbalanceBarAggregator::new(
7259                bar_type,
7260                instrument.price_precision(),
7261                instrument.size_precision(),
7262                record,
7263            );
7264
7265            let trade = TradeTick {
7266                size: Quantity::from(total_volume),
7267                aggressor_side: AggressorSide::Buy,
7268                ..TradeTick::default()
7269            };
7270
7271            aggregator.handle_trade(trade);
7272
7273            let handler_guard = handler.lock();
7274            results.push(handler_guard.len());
7275        }
7276
7277        assert_eq!(results[0], 3); // 3000 / 1000
7278        assert_eq!(results[1], 2); // 3000 / 1500
7279        assert_ne!(results[0], results[1]);
7280    }
7281
7282    #[rstest]
7283    #[case(1000_u64)]
7284    #[case(1500_u64)]
7285    fn test_volume_runs_bar_aggregator_large_step_no_overflow(
7286        equity_aapl: Equity,
7287        #[case] step: u64,
7288    ) {
7289        let instrument = InstrumentAny::Equity(equity_aapl);
7290        let bar_spec =
7291            BarSpecification::new(step as usize, BarAggregation::VolumeRuns, PriceType::Last);
7292        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
7293        let (handler, record) = recording_handler();
7294
7295        let mut aggregator = VolumeRunsBarAggregator::new(
7296            bar_type,
7297            instrument.price_precision(),
7298            instrument.size_precision(),
7299            record,
7300        );
7301
7302        let trade = TradeTick {
7303            size: Quantity::from(step * 2),
7304            aggressor_side: AggressorSide::Buy,
7305            ..TradeTick::default()
7306        };
7307
7308        aggregator.handle_trade(trade);
7309
7310        let handler_guard = handler.lock();
7311        assert_eq!(handler_guard.len(), 2);
7312        for bar in handler_guard.iter() {
7313            assert_eq!(bar.volume.as_f64(), step as f64);
7314        }
7315    }
7316
7317    #[rstest]
7318    fn test_volume_runs_bar_aggregator_different_large_steps_produce_different_bar_counts(
7319        equity_aapl: Equity,
7320    ) {
7321        let instrument = InstrumentAny::Equity(equity_aapl);
7322        let total_volume = 3000_u64;
7323        let mut results = Vec::new();
7324
7325        for step in [1000_usize, 1500] {
7326            let bar_spec = BarSpecification::new(step, BarAggregation::VolumeRuns, PriceType::Last);
7327            let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
7328            let (handler, record) = recording_handler();
7329
7330            let mut aggregator = VolumeRunsBarAggregator::new(
7331                bar_type,
7332                instrument.price_precision(),
7333                instrument.size_precision(),
7334                record,
7335            );
7336
7337            let trade = TradeTick {
7338                size: Quantity::from(total_volume),
7339                aggressor_side: AggressorSide::Buy,
7340                ..TradeTick::default()
7341            };
7342
7343            aggregator.handle_trade(trade);
7344
7345            let handler_guard = handler.lock();
7346            results.push(handler_guard.len());
7347        }
7348
7349        assert_eq!(results[0], 3); // 3000 / 1000
7350        assert_eq!(results[1], 2); // 3000 / 1500
7351        assert_ne!(results[0], results[1]);
7352    }
7353
7354    #[rstest]
7355    #[case::right_open(BarIntervalType::RightOpen, "100.00", 1)]
7356    #[case::left_open(BarIntervalType::LeftOpen, "102.00", 3)]
7357    fn test_time_bar_historical_boundary_waits_for_equal_timestamp_ticks(
7358        equity_aapl: Equity,
7359        #[case] interval: BarIntervalType,
7360        #[case] close: &str,
7361        #[case] volume: u64,
7362    ) {
7363        let bar_type = BarType::from(format!("{}-1-SECOND-LAST-INTERNAL", equity_aapl.id).as_str());
7364        let (handler, record) = recording_handler();
7365        let clock = Rc::new(RefCell::new(VirtualClock::new()));
7366
7367        let mut agg = TimeBarAggregator::new(
7368            bar_type,
7369            2,
7370            0,
7371            clock,
7372            record,
7373            true,
7374            true,
7375            interval,
7376            None,
7377            TimeZone::UTC,
7378            0,
7379            false,
7380        );
7381        agg.historical_mode = true;
7382        let rc: Rc<RefCell<Box<dyn BarAggregator>>> = Rc::new(RefCell::new(Box::new(agg)));
7383        rc.borrow_mut().set_aggregator_weak(Rc::downgrade(&rc));
7384        for (ts, price) in [
7385            (10_500_000_000_u64, "100.00"),
7386            (11_000_000_000, "101.00"),
7387            (11_000_000_000, "102.00"),
7388            (10_750_000_000, "999.00"),
7389            (11_500_000_000, "103.00"),
7390        ] {
7391            rc.borrow_mut()
7392                .update(Price::from(price), Quantity::from(1), UnixNanos::from(ts));
7393        }
7394
7395        let expected = Bar::new(
7396            bar_type,
7397            Price::from("100.00"),
7398            Price::from(close),
7399            Price::from("100.00"),
7400            Price::from(close),
7401            Quantity::from(volume),
7402            UnixNanos::from(if interval == BarIntervalType::LeftOpen {
7403                11_000_000_000
7404            } else {
7405                10_000_000_000
7406            }),
7407            UnixNanos::from(11_000_000_000),
7408        );
7409
7410        assert_eq!(*handler.lock(), vec![expected]);
7411    }
7412
7413    #[rstest]
7414    #[case(10.03, 10.07, Price::from("10.00"), Price::from("10.10"))]
7415    #[case(-10.07, -10.03, Price::from("-10.10"), Price::from("-10.00"))]
7416    fn test_fixed_tick_scheme_rounder_rounds_bid_and_ask_outward(
7417        #[case] raw_bid: f64,
7418        #[case] raw_ask: f64,
7419        #[case] expected_bid: Price,
7420        #[case] expected_ask: Price,
7421    ) {
7422        let rounder = FixedTickSchemeRounder::new(Price::from("0.05")).unwrap();
7423
7424        let (bid, ask) = rounder.round_prices(raw_bid, raw_ask, 2);
7425
7426        assert_eq!(bid, expected_bid);
7427        assert_eq!(ask, expected_ask);
7428    }
7429
7430    #[rstest]
7431    #[case(
7432        Price::from("9000000000.000000001"),
7433        -1.0,
7434        Price::from("-9000000000.000000001"),
7435        Price::from("0.000000000")
7436    )]
7437    #[case(
7438        Price::from("4000000000.000000001"),
7439        -4_000_000_001.0,
7440        Price::from("-8000000000.000000002"),
7441        Price::from("-4000000000.000000001")
7442    )]
7443    fn test_fixed_tick_scheme_rounder_preserves_exact_negative_prices(
7444        #[case] tick: Price,
7445        #[case] raw: f64,
7446        #[case] expected_bid: Price,
7447        #[case] expected_ask: Price,
7448    ) {
7449        let rounder = FixedTickSchemeRounder::new(tick).unwrap();
7450
7451        let (bid, ask) = rounder.round_prices(raw, raw, tick.precision);
7452
7453        assert_eq!(bid, expected_bid);
7454        assert_eq!(ask, expected_ask);
7455        assert_eq!(bid.precision, expected_bid.precision);
7456        assert_eq!(ask.precision, expected_ask.precision);
7457    }
7458
7459    #[rstest]
7460    fn test_spread_quote_quote_driven_emits_when_all_legs_received(equity_aapl: Equity) {
7461        let instrument = InstrumentAny::Equity(equity_aapl);
7462        let leg1 = instrument.id();
7463        let leg2 = InstrumentId::from("MSFT.XNAS");
7464        let spread_id = InstrumentId::from("SPREAD.XNAS");
7465        let legs = vec![(leg1, 1_i64), (leg2, -1_i64)];
7466        let (handler, record) = recording_handler();
7467        let clock = Rc::new(RefCell::new(VirtualClock::new()));
7468
7469        let mut agg = SpreadQuoteAggregator::new(
7470            spread_id,
7471            &legs,
7472            true,
7473            instrument.price_precision(),
7474            0,
7475            Box::new(record),
7476            clock,
7477            false,
7478            None,
7479            0,
7480            false,
7481            60,
7482            None,
7483            None,
7484        );
7485
7486        let ts = UnixNanos::from(1_000_000_000);
7487        agg.handle_quote_tick(QuoteTick::new(
7488            leg1,
7489            Price::from("100.00"),
7490            Price::from("100.10"),
7491            Quantity::from(10),
7492            Quantity::from(10),
7493            ts,
7494            ts,
7495        ));
7496        assert_eq!(handler.lock().len(), 0);
7497
7498        agg.handle_quote_tick(QuoteTick::new(
7499            leg2,
7500            Price::from("99.00"),
7501            Price::from("99.10"),
7502            Quantity::from(10),
7503            Quantity::from(10),
7504            ts,
7505            ts,
7506        ));
7507        let quotes = handler.lock();
7508        assert_eq!(quotes.len(), 1);
7509        assert_eq!(quotes[0].instrument_id, spread_id);
7510        assert!(quotes[0].bid_price < quotes[0].ask_price);
7511    }
7512
7513    #[rstest]
7514    fn test_spread_quote_futures_pricing_signed_ratios(equity_aapl: Equity) {
7515        let instrument = InstrumentAny::Equity(equity_aapl);
7516        let leg1 = instrument.id();
7517        let leg2 = InstrumentId::from("MSFT.XNAS");
7518        let spread_id = InstrumentId::from("SPREAD.XNAS");
7519        let legs = vec![(leg1, 1_i64), (leg2, -1_i64)];
7520        let (handler, record) = recording_handler();
7521        let clock = Rc::new(RefCell::new(VirtualClock::new()));
7522
7523        let mut agg = SpreadQuoteAggregator::new(
7524            spread_id,
7525            &legs,
7526            true,
7527            instrument.price_precision(),
7528            0,
7529            Box::new(record),
7530            clock,
7531            false,
7532            None,
7533            0,
7534            false,
7535            60,
7536            None,
7537            None,
7538        );
7539
7540        let ts = UnixNanos::from(1_000_000_000);
7541        agg.handle_quote_tick(QuoteTick::new(
7542            leg1,
7543            Price::from("10.00"),
7544            Price::from("10.10"),
7545            Quantity::from(100),
7546            Quantity::from(100),
7547            ts,
7548            ts,
7549        ));
7550        agg.handle_quote_tick(QuoteTick::new(
7551            leg2,
7552            Price::from("20.00"),
7553            Price::from("20.10"),
7554            Quantity::from(100),
7555            Quantity::from(100),
7556            ts,
7557            ts,
7558        ));
7559        let quotes = handler.lock();
7560        assert_eq!(quotes.len(), 1);
7561        let q = &quotes[0];
7562        assert_eq!(q.instrument_id, spread_id);
7563        assert_eq!(q.bid_price, Price::from("-10.10"));
7564        assert_eq!(q.ask_price, Price::from("-9.90"));
7565    }
7566
7567    #[rstest]
7568    fn test_spread_quote_size_calculation_non_unit_ratios(equity_aapl: Equity) {
7569        let instrument = InstrumentAny::Equity(equity_aapl);
7570        let leg1 = instrument.id();
7571        let leg2 = InstrumentId::from("MSFT.XNAS");
7572        let spread_id = InstrumentId::from("SPREAD.XNAS");
7573        let legs = vec![(leg1, 2_i64), (leg2, -1_i64)];
7574        let (handler, record) = recording_handler();
7575        let clock = Rc::new(RefCell::new(VirtualClock::new()));
7576
7577        let mut agg = SpreadQuoteAggregator::new(
7578            spread_id,
7579            &legs,
7580            true,
7581            instrument.price_precision(),
7582            0,
7583            Box::new(record),
7584            clock,
7585            false,
7586            None,
7587            0,
7588            false,
7589            60,
7590            None,
7591            None,
7592        );
7593
7594        let ts = UnixNanos::from(1_000_000_000);
7595        agg.handle_quote_tick(QuoteTick::new(
7596            leg1,
7597            Price::from("10.00"),
7598            Price::from("10.10"),
7599            Quantity::from(100),
7600            Quantity::from(40),
7601            ts,
7602            ts,
7603        ));
7604        agg.handle_quote_tick(QuoteTick::new(
7605            leg2,
7606            Price::from("10.00"),
7607            Price::from("10.10"),
7608            Quantity::from(50),
7609            Quantity::from(30),
7610            ts,
7611            ts,
7612        ));
7613        let quotes = handler.lock();
7614        assert_eq!(quotes.len(), 1);
7615        let q = &quotes[0];
7616        assert_eq!(q.bid_size.as_f64(), 30.0);
7617        assert_eq!(q.ask_size.as_f64(), 20.0);
7618    }
7619
7620    #[rstest]
7621    fn test_spread_quote_timer_driven_emission_cadence(equity_aapl: Equity) {
7622        let instrument = InstrumentAny::Equity(equity_aapl);
7623        let leg1 = instrument.id();
7624        let leg2 = InstrumentId::from("MSFT.XNAS");
7625        let spread_id = InstrumentId::from("SPREAD.XNAS");
7626        let legs = vec![(leg1, 1_i64), (leg2, -1_i64)];
7627        let (handler, record) = recording_handler();
7628        let clock = Rc::new(RefCell::new(VirtualClock::new()));
7629        clock.borrow_mut().set_time(UnixNanos::from(0));
7630
7631        let agg = SpreadQuoteAggregator::new(
7632            spread_id,
7633            &legs,
7634            true,
7635            instrument.price_precision(),
7636            0,
7637            Box::new(record),
7638            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
7639            false,
7640            Some(1),
7641            0,
7642            false,
7643            60,
7644            None,
7645            None,
7646        );
7647        let rc = Rc::new(RefCell::new(agg));
7648        rc.borrow_mut().prepare_for_timer_mode(&rc);
7649        rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
7650
7651        for event in clock.borrow_mut().advance_time(UnixNanos::from(0), true) {
7652            rc.borrow_mut().on_timer_fire(event.ts_event);
7653        }
7654        assert_eq!(handler.lock().len(), 0);
7655
7656        let ts1 = UnixNanos::from(1_000_000_000);
7657        rc.borrow_mut().handle_quote_tick(QuoteTick::new(
7658            leg1,
7659            Price::from("100.00"),
7660            Price::from("100.10"),
7661            Quantity::from(10),
7662            Quantity::from(10),
7663            ts1,
7664            ts1,
7665        ));
7666        rc.borrow_mut().handle_quote_tick(QuoteTick::new(
7667            leg2,
7668            Price::from("99.00"),
7669            Price::from("99.10"),
7670            Quantity::from(10),
7671            Quantity::from(10),
7672            ts1,
7673            ts1,
7674        ));
7675
7676        for event in clock.borrow_mut().advance_time(ts1, true) {
7677            rc.borrow_mut().on_timer_fire(event.ts_event);
7678        }
7679
7680        {
7681            let quotes = handler.lock();
7682            assert_eq!(quotes.len(), 1);
7683            assert_eq!(quotes[0].ts_event, ts1);
7684            assert_eq!(quotes[0].ts_init, ts1);
7685        }
7686
7687        let ts2 = UnixNanos::from(2_000_000_000);
7688        for event in clock.borrow_mut().advance_time(ts2, true) {
7689            rc.borrow_mut().on_timer_fire(event.ts_event);
7690        }
7691
7692        let quotes = handler.lock();
7693        assert_eq!(quotes.len(), 1);
7694    }
7695
7696    #[rstest]
7697    fn test_spread_quote_historical_timer_waits_for_all_legs(equity_aapl: Equity) {
7698        let instrument = InstrumentAny::Equity(equity_aapl);
7699        let leg1 = instrument.id();
7700        let leg2 = InstrumentId::from("MSFT.XNAS");
7701        let spread_id = InstrumentId::from("SPREAD.XNAS");
7702        let legs = vec![(leg1, 1_i64), (leg2, -1_i64)];
7703        let (handler, record) = recording_handler();
7704        let clock = Rc::new(RefCell::new(VirtualClock::new()));
7705
7706        let agg = SpreadQuoteAggregator::new(
7707            spread_id,
7708            &legs,
7709            true,
7710            instrument.price_precision(),
7711            0,
7712            Box::new(record),
7713            // need clock for set_clock after
7714            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
7715            true,
7716            Some(1),
7717            0,
7718            false,
7719            60,
7720            None,
7721            None,
7722        );
7723        let rc = Rc::new(RefCell::new(agg));
7724        rc.borrow_mut().prepare_for_timer_mode(&rc);
7725        rc.borrow_mut().set_clock(clock);
7726
7727        let ts1 = UnixNanos::from(1_000_000_000);
7728        let ts2 = UnixNanos::from(2_000_000_000);
7729        let ts3 = UnixNanos::from(3_000_000_000);
7730        rc.borrow_mut().handle_quote_tick(QuoteTick::new(
7731            leg1,
7732            Price::from("100.00"),
7733            Price::from("100.10"),
7734            Quantity::from(10),
7735            Quantity::from(10),
7736            ts1,
7737            ts1,
7738        ));
7739        assert_eq!(handler.lock().len(), 0);
7740
7741        rc.borrow_mut().handle_quote_tick(QuoteTick::new(
7742            leg2,
7743            Price::from("99.00"),
7744            Price::from("99.10"),
7745            Quantity::from(10),
7746            Quantity::from(10),
7747            ts2,
7748            ts2,
7749        ));
7750        assert_eq!(handler.lock().len(), 0);
7751
7752        rc.borrow_mut().handle_quote_tick(QuoteTick::new(
7753            leg1,
7754            Price::from("100.00"),
7755            Price::from("100.10"),
7756            Quantity::from(10),
7757            Quantity::from(10),
7758            ts3,
7759            ts3,
7760        ));
7761        let quotes = handler.lock();
7762        assert_eq!(
7763            quotes.len(),
7764            1,
7765            "deferred event at ts2 is processed when we have all legs and advance to ts3"
7766        );
7767    }
7768
7769    #[rstest]
7770    fn test_spread_quote_historical_flush_emits_pending_final_quote(equity_aapl: Equity) {
7771        let instrument = InstrumentAny::Equity(equity_aapl);
7772        let leg1 = instrument.id();
7773        let leg2 = InstrumentId::from("MSFT.XNAS");
7774        let spread_id = InstrumentId::from("SPREAD.XNAS");
7775        let legs = vec![(leg1, 1_i64), (leg2, -1_i64)];
7776        let (handler, record) = recording_handler();
7777        let clock = Rc::new(RefCell::new(VirtualClock::new()));
7778
7779        let agg = SpreadQuoteAggregator::new(
7780            spread_id,
7781            &legs,
7782            true,
7783            instrument.price_precision(),
7784            0,
7785            Box::new(record),
7786            // need clock for set_clock after
7787            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
7788            true,
7789            Some(1),
7790            0,
7791            false,
7792            60,
7793            None,
7794            None,
7795        );
7796        let rc = Rc::new(RefCell::new(agg));
7797        rc.borrow_mut().prepare_for_timer_mode(&rc);
7798        rc.borrow_mut().set_clock(clock);
7799
7800        let ts1 = UnixNanos::from(1_000_000_000);
7801        let ts2 = UnixNanos::from(2_000_000_000);
7802        rc.borrow_mut().handle_quote_tick(QuoteTick::new(
7803            leg1,
7804            Price::from("100.00"),
7805            Price::from("100.10"),
7806            Quantity::from(10),
7807            Quantity::from(10),
7808            ts1,
7809            ts1,
7810        ));
7811        rc.borrow_mut().handle_quote_tick(QuoteTick::new(
7812            leg2,
7813            Price::from("99.00"),
7814            Price::from("99.10"),
7815            Quantity::from(10),
7816            Quantity::from(10),
7817            ts2,
7818            ts2,
7819        ));
7820
7821        assert_eq!(handler.lock().len(), 0);
7822
7823        rc.borrow_mut().flush_pending_historical_quote();
7824
7825        let quotes = handler.lock();
7826        assert_eq!(
7827            quotes.len(),
7828            1,
7829            "final historical quote should be emitted when the deferred event is flushed",
7830        );
7831        assert_eq!(quotes[0].ts_event, ts2);
7832    }
7833
7834    #[rstest]
7835    fn test_spread_quote_option_vega_weighting(equity_aapl: Equity) {
7836        let instrument = InstrumentAny::Equity(equity_aapl);
7837        let leg1 = instrument.id();
7838        let leg2 = InstrumentId::from("MSFT.XNAS");
7839        let spread_id = InstrumentId::from("SPREAD.XNAS");
7840        let legs = vec![(leg1, 1_i64), (leg2, -1_i64)];
7841        let (handler, record) = recording_handler();
7842        let clock = Rc::new(RefCell::new(VirtualClock::new()));
7843
7844        let mut vega_provider = MapVegaProvider::new();
7845        vega_provider.insert(leg1, 0.15);
7846        vega_provider.insert(leg2, 0.12);
7847
7848        let mut agg = SpreadQuoteAggregator::new(
7849            spread_id,
7850            &legs,
7851            false,
7852            instrument.price_precision(),
7853            0,
7854            Box::new(record),
7855            clock,
7856            false,
7857            None,
7858            0,
7859            false,
7860            60,
7861            Some(Box::new(vega_provider)),
7862            None,
7863        );
7864
7865        let ts = UnixNanos::from(1_000_000_000);
7866        agg.handle_quote_tick(QuoteTick::new(
7867            leg1,
7868            Price::from("10.00"),
7869            Price::from("10.20"),
7870            Quantity::from(100),
7871            Quantity::from(100),
7872            ts,
7873            ts,
7874        ));
7875        agg.handle_quote_tick(QuoteTick::new(
7876            leg2,
7877            Price::from("11.00"),
7878            Price::from("11.20"),
7879            Quantity::from(100),
7880            Quantity::from(100),
7881            ts,
7882            ts,
7883        ));
7884        let quotes = handler.lock();
7885        assert_eq!(quotes.len(), 1);
7886        let q = &quotes[0];
7887        assert_eq!(q.instrument_id, spread_id);
7888        assert_eq!(q.bid_price, Price::from("-1.02"));
7889        assert_eq!(q.ask_price, Price::from("-0.98"));
7890        assert_eq!(q.bid_size, Quantity::from(100));
7891        assert_eq!(q.ask_size, Quantity::from(100));
7892        assert_eq!(q.ts_event, ts);
7893        assert_eq!(q.ts_init, ts);
7894    }
7895
7896    #[rstest]
7897    fn test_spread_quote_all_zero_vega_fallback(equity_aapl: Equity) {
7898        let instrument = InstrumentAny::Equity(equity_aapl);
7899        let leg1 = instrument.id();
7900        let leg2 = InstrumentId::from("MSFT.XNAS");
7901        let spread_id = InstrumentId::from("SPREAD.XNAS");
7902        let legs = vec![(leg1, 1_i64), (leg2, -1_i64)];
7903        let (handler, record) = recording_handler();
7904        let clock = Rc::new(RefCell::new(VirtualClock::new()));
7905
7906        let mut vega_provider = MapVegaProvider::new();
7907        vega_provider.insert(leg1, 0.0);
7908        vega_provider.insert(leg2, 0.0);
7909
7910        let agg = SpreadQuoteAggregator::new(
7911            spread_id,
7912            &legs,
7913            false,
7914            instrument.price_precision(),
7915            0,
7916            Box::new(record),
7917            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
7918            false,
7919            None,
7920            0,
7921            false,
7922            1,
7923            Some(Box::new(vega_provider)),
7924            None,
7925        );
7926        let rc = Rc::new(RefCell::new(agg));
7927        rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
7928
7929        let ts = UnixNanos::from(1_000_000_000);
7930        rc.borrow_mut().handle_quote_tick(QuoteTick::new(
7931            leg1,
7932            Price::from("10.00"),
7933            Price::from("10.10"),
7934            Quantity::from(100),
7935            Quantity::from(100),
7936            ts,
7937            ts,
7938        ));
7939        rc.borrow_mut().handle_quote_tick(QuoteTick::new(
7940            leg2,
7941            Price::from("20.00"),
7942            Price::from("20.10"),
7943            Quantity::from(100),
7944            Quantity::from(100),
7945            ts,
7946            ts,
7947        ));
7948        {
7949            let quotes = handler.lock();
7950            assert_eq!(quotes.len(), 1);
7951            let q = &quotes[0];
7952            assert_eq!(q.bid_price, Price::from("-10.10"));
7953            assert_eq!(q.ask_price, Price::from("-9.90"));
7954        }
7955        assert!(rc.borrow().vega_pricing_temporarily_disabled);
7956
7957        let timeout_name = rc.borrow().vega_pricing_timeout_timer_name.clone();
7958        assert!(
7959            clock
7960                .borrow()
7961                .timer_names()
7962                .contains(&timeout_name.as_str())
7963        );
7964
7965        let events = clock
7966            .borrow_mut()
7967            .advance_time(UnixNanos::from(2_000_000_000), true);
7968
7969        for handler in clock.borrow().match_handlers(events) {
7970            handler.run();
7971        }
7972
7973        assert!(!rc.borrow().vega_pricing_temporarily_disabled);
7974
7975        let (_cancel_handler, record) = recording_handler();
7976        let mut cancel_vega_provider = MapVegaProvider::new();
7977        cancel_vega_provider.insert(leg1, 0.0);
7978        cancel_vega_provider.insert(leg2, 0.0);
7979        let cancel_agg = SpreadQuoteAggregator::new(
7980            spread_id,
7981            &legs,
7982            false,
7983            instrument.price_precision(),
7984            0,
7985            Box::new(record),
7986            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
7987            false,
7988            None,
7989            0,
7990            false,
7991            10,
7992            Some(Box::new(cancel_vega_provider)),
7993            None,
7994        );
7995        let cancel_rc = Rc::new(RefCell::new(cancel_agg));
7996        cancel_rc
7997            .borrow_mut()
7998            .start_timer(Some(Rc::clone(&cancel_rc)));
7999        cancel_rc.borrow_mut().handle_quote_tick(QuoteTick::new(
8000            leg1,
8001            Price::from("10.00"),
8002            Price::from("10.10"),
8003            Quantity::from(100),
8004            Quantity::from(100),
8005            ts,
8006            ts,
8007        ));
8008        cancel_rc.borrow_mut().handle_quote_tick(QuoteTick::new(
8009            leg2,
8010            Price::from("20.00"),
8011            Price::from("20.10"),
8012            Quantity::from(100),
8013            Quantity::from(100),
8014            ts,
8015            ts,
8016        ));
8017        let cancel_timeout_name = cancel_rc.borrow().vega_pricing_timeout_timer_name.clone();
8018        assert!(
8019            clock
8020                .borrow()
8021                .timer_names()
8022                .contains(&cancel_timeout_name.as_str())
8023        );
8024        cancel_rc.borrow_mut().stop_timer();
8025        assert!(
8026            !clock
8027                .borrow()
8028                .timer_names()
8029                .contains(&cancel_timeout_name.as_str())
8030        );
8031
8032        let (permanent_handler, record) = recording_handler();
8033        let mut permanent_vega_provider = MapVegaProvider::new();
8034        permanent_vega_provider.insert(leg1, 0.15);
8035        permanent_vega_provider.insert(leg2, 0.12);
8036        let mut permanent_agg = SpreadQuoteAggregator::new(
8037            spread_id,
8038            &legs,
8039            false,
8040            instrument.price_precision(),
8041            0,
8042            Box::new(record),
8043            Rc::new(RefCell::new(VirtualClock::new())),
8044            false,
8045            None,
8046            0,
8047            true,
8048            1,
8049            Some(Box::new(permanent_vega_provider)),
8050            None,
8051        );
8052
8053        permanent_agg.handle_quote_tick(QuoteTick::new(
8054            leg1,
8055            Price::from("10.00"),
8056            Price::from("10.10"),
8057            Quantity::from(100),
8058            Quantity::from(100),
8059            ts,
8060            ts,
8061        ));
8062        permanent_agg.handle_quote_tick(QuoteTick::new(
8063            leg2,
8064            Price::from("20.00"),
8065            Price::from("20.10"),
8066            Quantity::from(100),
8067            Quantity::from(100),
8068            ts,
8069            ts,
8070        ));
8071
8072        let permanent_quotes = permanent_handler.lock();
8073        assert_eq!(permanent_quotes.len(), 1);
8074        assert_eq!(permanent_quotes[0].bid_price, Price::from("-10.10"));
8075        assert_eq!(permanent_quotes[0].ask_price, Price::from("-9.90"));
8076        assert!(!permanent_agg.vega_pricing_temporarily_disabled);
8077    }
8078
8079    #[rstest]
8080    fn test_spread_quote_negative_prices_tick_scheme(equity_aapl: Equity) {
8081        let instrument = InstrumentAny::Equity(equity_aapl);
8082        let leg1 = instrument.id();
8083        let leg2 = InstrumentId::from("MSFT.XNAS");
8084        let spread_id = InstrumentId::from("SPREAD.XNAS");
8085        let legs = vec![(leg1, 1_i64), (leg2, -1_i64)];
8086        let (handler, record) = recording_handler();
8087        let clock = Rc::new(RefCell::new(VirtualClock::new()));
8088        let rounder = FixedTickSchemeRounder::new(Price::from("0.01")).unwrap();
8089
8090        let mut agg = SpreadQuoteAggregator::new(
8091            spread_id,
8092            &legs,
8093            true,
8094            2,
8095            0,
8096            Box::new(record),
8097            clock,
8098            false,
8099            None,
8100            0,
8101            false,
8102            60,
8103            None,
8104            Some(Box::new(rounder)),
8105        );
8106
8107        let ts = UnixNanos::from(1_000_000_000);
8108        agg.handle_quote_tick(QuoteTick::new(
8109            leg1,
8110            Price::from("10.00"),
8111            Price::from("10.10"),
8112            Quantity::from(100),
8113            Quantity::from(100),
8114            ts,
8115            ts,
8116        ));
8117        agg.handle_quote_tick(QuoteTick::new(
8118            leg2,
8119            Price::from("20.00"),
8120            Price::from("20.10"),
8121            Quantity::from(100),
8122            Quantity::from(100),
8123            ts,
8124            ts,
8125        ));
8126        let quotes = handler.lock();
8127        assert_eq!(quotes.len(), 1);
8128        let q = &quotes[0];
8129        assert!(q.bid_price.as_f64() < 0.0);
8130        assert!(q.ask_price.as_f64() < 0.0);
8131        assert!(q.bid_price < q.ask_price);
8132    }
8133
8134    #[rstest]
8135    #[case(BarIntervalType::LeftOpen)]
8136    #[case(BarIntervalType::RightOpen)]
8137    fn test_time_bar_skip_first_non_full_bar_noop_on_boundary(
8138        equity_aapl: Equity,
8139        #[case] interval_type: BarIntervalType,
8140    ) {
8141        // When the clock sits on a bar boundary, fire_immediately=true and
8142        // first_close_ns equals that boundary. Every subsequent bar closes
8143        // strictly after first_close_ns, so skip_first_non_full_bar never
8144        // triggers and both bars emit.
8145        let instrument = InstrumentAny::Equity(equity_aapl);
8146        let bar_spec = BarSpecification::new(1, BarAggregation::Second, PriceType::Last);
8147        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
8148        let (handler, record) = recording_handler();
8149        let clock = Rc::new(RefCell::new(VirtualClock::new()));
8150        clock.borrow_mut().set_time(UnixNanos::from(1_000_000_000));
8151        let event_name = Ustr::from(&format!("TIME_BAR_{bar_type}"));
8152
8153        let aggregator = TimeBarAggregator::new(
8154            bar_type,
8155            instrument.price_precision(),
8156            instrument.size_precision(),
8157            clock,
8158            record,
8159            false,
8160            false,
8161            interval_type,
8162            None,
8163            TimeZone::UTC,
8164            0,
8165            true, // skip_first_non_full_bar
8166        );
8167
8168        let boxed: Box<dyn BarAggregator> = Box::new(aggregator);
8169        let rc = Rc::new(RefCell::new(boxed));
8170        rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
8171
8172        rc.borrow_mut().update(
8173            Price::from("100.00"),
8174            Quantity::from(1),
8175            UnixNanos::from(1_000_000_000),
8176        );
8177        rc.borrow_mut().build_bar(&TimeEvent::new(
8178            event_name,
8179            UUID4::new(),
8180            UnixNanos::from(2_000_000_000),
8181            UnixNanos::from(2_000_000_000),
8182        ));
8183        rc.borrow_mut().update(
8184            Price::from("101.00"),
8185            Quantity::from(1),
8186            UnixNanos::from(2_500_000_000),
8187        );
8188        rc.borrow_mut().build_bar(&TimeEvent::new(
8189            event_name,
8190            UUID4::new(),
8191            UnixNanos::from(3_000_000_000),
8192            UnixNanos::from(3_000_000_000),
8193        ));
8194
8195        let bars = handler.lock();
8196        assert_eq!(bars.len(), 2);
8197        assert_eq!(bars[0].close, Price::from("100.00"));
8198        assert_eq!(bars[1].close, Price::from("101.00"));
8199    }
8200
8201    #[rstest]
8202    #[case(BarIntervalType::LeftOpen)]
8203    #[case(BarIntervalType::RightOpen)]
8204    fn test_time_bar_skip_first_non_full_bar_drops_partial_bar(
8205        equity_aapl: Equity,
8206        #[case] interval_type: BarIntervalType,
8207    ) {
8208        // When the clock starts past a boundary (mid-interval), first_close_ns
8209        // is the upcoming boundary. The bar closing at first_close_ns is partial,
8210        // so skip_first_non_full_bar drops it; subsequent full bars emit.
8211        let instrument = InstrumentAny::Equity(equity_aapl);
8212        let bar_spec = BarSpecification::new(1, BarAggregation::Second, PriceType::Last);
8213        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
8214        let (handler, record) = recording_handler();
8215        let clock = Rc::new(RefCell::new(VirtualClock::new()));
8216        clock.borrow_mut().set_time(UnixNanos::from(1_500_000_000));
8217        let event_name = Ustr::from(&format!("TIME_BAR_{bar_type}"));
8218
8219        let aggregator = TimeBarAggregator::new(
8220            bar_type,
8221            instrument.price_precision(),
8222            instrument.size_precision(),
8223            clock,
8224            record,
8225            false,
8226            false,
8227            interval_type,
8228            None,
8229            TimeZone::UTC,
8230            0,
8231            true, // skip_first_non_full_bar
8232        );
8233
8234        let boxed: Box<dyn BarAggregator> = Box::new(aggregator);
8235        let rc = Rc::new(RefCell::new(boxed));
8236        rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
8237
8238        rc.borrow_mut().update(
8239            Price::from("100.00"),
8240            Quantity::from(1),
8241            UnixNanos::from(1_500_000_000),
8242        );
8243        rc.borrow_mut().build_bar(&TimeEvent::new(
8244            event_name,
8245            UUID4::new(),
8246            UnixNanos::from(2_000_000_000),
8247            UnixNanos::from(2_000_000_000),
8248        ));
8249        rc.borrow_mut().update(
8250            Price::from("101.00"),
8251            Quantity::from(1),
8252            UnixNanos::from(2_500_000_000),
8253        );
8254        rc.borrow_mut().build_bar(&TimeEvent::new(
8255            event_name,
8256            UUID4::new(),
8257            UnixNanos::from(3_000_000_000),
8258            UnixNanos::from(3_000_000_000),
8259        ));
8260
8261        let bars = handler.lock();
8262        assert_eq!(bars.len(), 1);
8263        assert_eq!(bars[0].close, Price::from("101.00"));
8264    }
8265
8266    #[rstest]
8267    fn test_time_bar_skip_first_non_full_bar_then_empty_interval_builds_flat_bar(
8268        equity_aapl: Equity,
8269    ) {
8270        // The skipped partial bar's close seeds the flat bar for the following empty interval
8271        let instrument = InstrumentAny::Equity(equity_aapl);
8272        let bar_spec = BarSpecification::new(1, BarAggregation::Second, PriceType::Last);
8273        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
8274        let (handler, record) = recording_handler();
8275        let clock = Rc::new(RefCell::new(VirtualClock::new()));
8276        clock.borrow_mut().set_time(UnixNanos::from(1_500_000_000));
8277        let event_name = Ustr::from(&format!("TIME_BAR_{bar_type}"));
8278
8279        let aggregator = TimeBarAggregator::new(
8280            bar_type,
8281            instrument.price_precision(),
8282            instrument.size_precision(),
8283            clock,
8284            record,
8285            true, // build_with_no_updates
8286            true, // timestamp_on_close
8287            BarIntervalType::LeftOpen,
8288            None,
8289            TimeZone::UTC,
8290            0,
8291            true, // skip_first_non_full_bar
8292        );
8293
8294        let boxed: Box<dyn BarAggregator> = Box::new(aggregator);
8295        let rc = Rc::new(RefCell::new(boxed));
8296        rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
8297
8298        rc.borrow_mut().update(
8299            Price::from("100.00"),
8300            Quantity::from(1),
8301            UnixNanos::from(1_500_000_000),
8302        );
8303        rc.borrow_mut().build_bar(&TimeEvent::new(
8304            event_name,
8305            UUID4::new(),
8306            UnixNanos::from(2_000_000_000),
8307            UnixNanos::from(2_000_000_000),
8308        ));
8309        rc.borrow_mut().build_bar(&TimeEvent::new(
8310            event_name,
8311            UUID4::new(),
8312            UnixNanos::from(3_000_000_000),
8313            UnixNanos::from(3_000_000_000),
8314        ));
8315
8316        let bars = handler.lock();
8317        assert_eq!(bars.len(), 1);
8318        assert_eq!(bars[0].open, Price::from("100.00"));
8319        assert_eq!(bars[0].high, Price::from("100.00"));
8320        assert_eq!(bars[0].low, Price::from("100.00"));
8321        assert_eq!(bars[0].close, Price::from("100.00"));
8322        assert_eq!(bars[0].volume, Quantity::from(0));
8323        assert_eq!(bars[0].ts_event, UnixNanos::from(3_000_000_000));
8324        assert_eq!(bars[0].ts_init, UnixNanos::from(3_000_000_000));
8325    }
8326
8327    #[rstest]
8328    fn test_time_bar_skip_first_non_full_bar_skips_every_call_before_first_close(
8329        equity_aapl: Equity,
8330    ) {
8331        // The flag must remain set across every build_and_send call whose
8332        // ts_init <= first_close_ns, and only flip once a bar actually emits.
8333        // Catches a mutation that flips skip_first_non_full_bar early.
8334        let instrument = InstrumentAny::Equity(equity_aapl);
8335        let bar_spec = BarSpecification::new(10, BarAggregation::Second, PriceType::Last);
8336        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
8337        let (handler, record) = recording_handler();
8338        let clock = Rc::new(RefCell::new(VirtualClock::new()));
8339        clock.borrow_mut().set_time(UnixNanos::from(5_000_000_000));
8340        let event_name = Ustr::from(&format!("TIME_BAR_{bar_type}"));
8341
8342        let aggregator = TimeBarAggregator::new(
8343            bar_type,
8344            instrument.price_precision(),
8345            instrument.size_precision(),
8346            clock,
8347            record,
8348            false,
8349            false,
8350            BarIntervalType::LeftOpen,
8351            None,
8352            TimeZone::UTC,
8353            0,
8354            true, // skip_first_non_full_bar
8355        );
8356
8357        let boxed: Box<dyn BarAggregator> = Box::new(aggregator);
8358        let rc = Rc::new(RefCell::new(boxed));
8359        rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
8360
8361        // first_close_ns is 10_000_000_000 (first 10s boundary after start).
8362        // Drive three build_bar calls at ts <= first_close_ns, each preceded by a
8363        // distinct update. Every one of them must be skipped.
8364        for (price, update_ts, event_ts) in [
8365            ("100.00", 5_500_000_000_u64, 7_000_000_000_u64),
8366            ("101.00", 7_500_000_000_u64, 8_000_000_000_u64),
8367            ("102.00", 9_000_000_000_u64, 10_000_000_000_u64),
8368        ] {
8369            rc.borrow_mut().update(
8370                Price::from(price),
8371                Quantity::from(1),
8372                UnixNanos::from(update_ts),
8373            );
8374            rc.borrow_mut().build_bar(&TimeEvent::new(
8375                event_name,
8376                UUID4::new(),
8377                UnixNanos::from(event_ts),
8378                UnixNanos::from(event_ts),
8379            ));
8380        }
8381
8382        // Final update + build past first_close_ns emits for the first time.
8383        rc.borrow_mut().update(
8384            Price::from("103.00"),
8385            Quantity::from(1),
8386            UnixNanos::from(10_500_000_000),
8387        );
8388        rc.borrow_mut().build_bar(&TimeEvent::new(
8389            event_name,
8390            UUID4::new(),
8391            UnixNanos::from(11_000_000_000),
8392            UnixNanos::from(11_000_000_000),
8393        ));
8394
8395        let bars = handler.lock();
8396        assert_eq!(bars.len(), 1);
8397        assert_eq!(bars[0].close, Price::from("103.00"));
8398    }
8399
8400    #[rstest]
8401    fn test_time_bar_skip_first_non_full_bar_skips_when_build_delay_shifts_start(
8402        equity_aapl: Equity,
8403    ) {
8404        // When bar_build_delay > 0 pushes start_time past a boundary (even if `now` is on a
8405        // boundary), first_close_ns is set and the first bar is skipped. A `now > start_time`
8406        // guard would incorrectly keep this first bar.
8407        let instrument = InstrumentAny::Equity(equity_aapl);
8408        let bar_spec = BarSpecification::new(1, BarAggregation::Second, PriceType::Last);
8409        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
8410        let (handler, record) = recording_handler();
8411        let clock = Rc::new(RefCell::new(VirtualClock::new()));
8412        clock.borrow_mut().set_time(UnixNanos::from(2_000_000_000));
8413        let event_name = Ustr::from(&format!("TIME_BAR_{bar_type}"));
8414
8415        let aggregator = TimeBarAggregator::new(
8416            bar_type,
8417            instrument.price_precision(),
8418            instrument.size_precision(),
8419            clock,
8420            record,
8421            false,
8422            false,
8423            BarIntervalType::LeftOpen,
8424            None,
8425            TimeZone::UTC,
8426            100,  // bar_build_delay (microseconds)
8427            true, // skip_first_non_full_bar
8428        );
8429
8430        let boxed: Box<dyn BarAggregator> = Box::new(aggregator);
8431        let rc = Rc::new(RefCell::new(boxed));
8432        rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
8433
8434        // start_time = 2s + 100us = 2_000_100_000 ns; first_close_ns = 3_000_100_000 ns.
8435        rc.borrow_mut().update(
8436            Price::from("100.00"),
8437            Quantity::from(1),
8438            UnixNanos::from(2_500_000_000),
8439        );
8440        rc.borrow_mut().build_bar(&TimeEvent::new(
8441            event_name,
8442            UUID4::new(),
8443            UnixNanos::from(3_000_100_000),
8444            UnixNanos::from(3_000_100_000),
8445        ));
8446        rc.borrow_mut().update(
8447            Price::from("101.00"),
8448            Quantity::from(1),
8449            UnixNanos::from(3_500_000_000),
8450        );
8451        rc.borrow_mut().build_bar(&TimeEvent::new(
8452            event_name,
8453            UUID4::new(),
8454            UnixNanos::from(4_000_100_000),
8455            UnixNanos::from(4_000_100_000),
8456        ));
8457
8458        let bars = handler.lock();
8459        assert_eq!(bars.len(), 1);
8460        assert_eq!(bars[0].close, Price::from("101.00"));
8461    }
8462
8463    #[rstest]
8464    #[case(
8465        BarAggregation::Month,
8466        1_735_689_600_000_000_000_u64,
8467        1_733_011_200_000_000_000_u64
8468    )]
8469    #[case(
8470        BarAggregation::Year,
8471        1_735_689_600_000_000_000_u64,
8472        1_704_067_200_000_000_000_u64
8473    )]
8474    fn test_time_bar_fire_immediately_month_year_stored_open_points_to_previous_period(
8475        equity_aapl: Equity,
8476        #[case] aggregation: BarAggregation,
8477        #[case] start_ns: u64,
8478        #[case] expected_stored_open_ns: u64,
8479    ) {
8480        // When the clock is exactly on a month/year boundary, fire_immediately=true.
8481        // stored_open_ns must resolve to one step before start_time (close_time - step)
8482        // so the first bar's open timestamp marks the true start of the in-progress interval.
8483        let instrument = InstrumentAny::Equity(equity_aapl);
8484        let bar_spec = BarSpecification::new(1, aggregation, PriceType::Last);
8485        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
8486        let (handler, record) = recording_handler();
8487        let clock = Rc::new(RefCell::new(VirtualClock::new()));
8488        clock.borrow_mut().set_time(UnixNanos::from(start_ns));
8489        let event_name = Ustr::from(&format!("TIME_BAR_{bar_type}"));
8490
8491        let aggregator = TimeBarAggregator::new(
8492            bar_type,
8493            instrument.price_precision(),
8494            instrument.size_precision(),
8495            clock,
8496            record,
8497            false,
8498            false,
8499            BarIntervalType::RightOpen, // ts_event = stored_open_ns
8500            None,
8501            TimeZone::UTC,
8502            0,
8503            false, // skip_first_non_full_bar
8504        );
8505
8506        let boxed: Box<dyn BarAggregator> = Box::new(aggregator);
8507        let rc = Rc::new(RefCell::new(boxed));
8508        rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
8509
8510        rc.borrow_mut().update(
8511            Price::from("100.00"),
8512            Quantity::from(1),
8513            UnixNanos::from(start_ns),
8514        );
8515        rc.borrow_mut().build_bar(&TimeEvent::new(
8516            event_name,
8517            UUID4::new(),
8518            UnixNanos::from(start_ns),
8519            UnixNanos::from(start_ns),
8520        ));
8521
8522        let bars = handler.lock();
8523        assert_eq!(bars.len(), 1);
8524        assert_eq!(bars[0].ts_event, UnixNanos::from(expected_stored_open_ns));
8525        assert_eq!(bars[0].ts_init, UnixNanos::from(start_ns));
8526    }
8527
8528    #[rstest]
8529    fn test_time_bar_historical_prevents_bars_for_timer_before_last_data(equity_aapl: Equity) {
8530        let instrument = InstrumentAny::Equity(equity_aapl);
8531        let bar_spec = BarSpecification::new(1, BarAggregation::Second, PriceType::Last);
8532        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
8533        let (handler, record) = recording_handler();
8534        let clock = Rc::new(RefCell::new(VirtualClock::new()));
8535
8536        let mut agg = TimeBarAggregator::new(
8537            bar_type,
8538            instrument.price_precision(),
8539            instrument.size_precision(),
8540            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
8541            record,
8542            true,
8543            true,
8544            BarIntervalType::LeftOpen,
8545            None,
8546            TimeZone::UTC,
8547            0,
8548            false,
8549        );
8550        agg.historical_mode = true;
8551        agg.set_clock_internal(clock);
8552        let boxed: Box<dyn BarAggregator> = Box::new(agg);
8553        let rc = Rc::new(RefCell::new(boxed));
8554        rc.borrow_mut().set_aggregator_weak(Rc::downgrade(&rc));
8555
8556        let ts1 = UnixNanos::from(2_000_000_000);
8557        rc.borrow_mut()
8558            .update(Price::from("100.00"), Quantity::from(1), ts1);
8559
8560        let ts2 = UnixNanos::from(3_000_000_000);
8561        rc.borrow_mut()
8562            .update(Price::from("101.00"), Quantity::from(1), ts2);
8563
8564        let bars = handler.lock();
8565        assert!(
8566            !bars.is_empty(),
8567            "advancing time from ts1 to ts2 should produce at least one bar"
8568        );
8569        assert_eq!(bars[0].close, Price::from("100.00"));
8570    }
8571
8572    #[rstest]
8573    #[case(BarAggregation::Tick)]
8574    #[case(BarAggregation::TickImbalance)]
8575    #[case(BarAggregation::TickRuns)]
8576    #[case(BarAggregation::Volume)]
8577    #[case(BarAggregation::VolumeImbalance)]
8578    #[case(BarAggregation::VolumeRuns)]
8579    #[case(BarAggregation::Value)]
8580    #[case(BarAggregation::ValueImbalance)]
8581    #[case(BarAggregation::ValueRuns)]
8582    #[case(BarAggregation::Renko)]
8583    fn test_aggregators_standardize_composite_bar_type(
8584        equity_aapl: Equity,
8585        #[case] aggregation: BarAggregation,
8586    ) {
8587        let instrument = InstrumentAny::Equity(equity_aapl);
8588        let bar_type = BarType::new_composite(
8589            instrument.id(),
8590            BarSpecification::new(10, aggregation, PriceType::Last),
8591            AggregationSource::Internal,
8592            1,
8593            BarAggregation::Minute,
8594            AggregationSource::External,
8595        );
8596        let handler = |_: Bar| {};
8597
8598        let aggregator: Box<dyn BarAggregator> = match aggregation {
8599            BarAggregation::Tick => Box::new(TickBarAggregator::new(
8600                bar_type,
8601                instrument.price_precision(),
8602                instrument.size_precision(),
8603                handler,
8604            )),
8605            BarAggregation::TickImbalance => Box::new(TickImbalanceBarAggregator::new(
8606                bar_type,
8607                instrument.price_precision(),
8608                instrument.size_precision(),
8609                handler,
8610            )),
8611            BarAggregation::TickRuns => Box::new(TickRunsBarAggregator::new(
8612                bar_type,
8613                instrument.price_precision(),
8614                instrument.size_precision(),
8615                handler,
8616            )),
8617            BarAggregation::Volume => Box::new(VolumeBarAggregator::new(
8618                bar_type,
8619                instrument.price_precision(),
8620                instrument.size_precision(),
8621                handler,
8622            )),
8623            BarAggregation::VolumeImbalance => Box::new(VolumeImbalanceBarAggregator::new(
8624                bar_type,
8625                instrument.price_precision(),
8626                instrument.size_precision(),
8627                handler,
8628            )),
8629            BarAggregation::VolumeRuns => Box::new(VolumeRunsBarAggregator::new(
8630                bar_type,
8631                instrument.price_precision(),
8632                instrument.size_precision(),
8633                handler,
8634            )),
8635            BarAggregation::Value => Box::new(ValueBarAggregator::new(
8636                bar_type,
8637                instrument.price_precision(),
8638                instrument.size_precision(),
8639                handler,
8640            )),
8641            BarAggregation::ValueImbalance => Box::new(ValueImbalanceBarAggregator::new(
8642                bar_type,
8643                instrument.price_precision(),
8644                instrument.size_precision(),
8645                handler,
8646            )),
8647            BarAggregation::ValueRuns => Box::new(ValueRunsBarAggregator::new(
8648                bar_type,
8649                instrument.price_precision(),
8650                instrument.size_precision(),
8651                handler,
8652            )),
8653            BarAggregation::Renko => Box::new(RenkoBarAggregator::new(
8654                bar_type,
8655                instrument.price_precision(),
8656                instrument.size_precision(),
8657                Price::from("0.01"),
8658                handler,
8659            )),
8660            _ => unreachable!(),
8661        };
8662
8663        assert!(aggregator.bar_type().is_standard());
8664        assert_eq!(aggregator.bar_type(), bar_type.standard());
8665    }
8666
8667    #[rstest]
8668    fn test_composite_tick_bar_aggregator_emits_standard_bar_type(equity_aapl: Equity) {
8669        let instrument = InstrumentAny::Equity(equity_aapl);
8670        let bar_type = BarType::new_composite(
8671            instrument.id(),
8672            BarSpecification::new(1, BarAggregation::Tick, PriceType::Last),
8673            AggregationSource::Internal,
8674            1,
8675            BarAggregation::Minute,
8676            AggregationSource::External,
8677        );
8678        let (handler, record) = recording_handler();
8679
8680        let mut aggregator = TickBarAggregator::new(
8681            bar_type,
8682            instrument.price_precision(),
8683            instrument.size_precision(),
8684            record,
8685        );
8686
8687        let input_bar = Bar::new(
8688            bar_type.composite(),
8689            Price::from("100.00"),
8690            Price::from("101.00"),
8691            Price::from("99.00"),
8692            Price::from("100.50"),
8693            Quantity::from(10),
8694            UnixNanos::from(1_000),
8695            UnixNanos::from(1_000),
8696        );
8697        aggregator.handle_bar(input_bar);
8698
8699        let handler_guard = handler.lock();
8700        assert_eq!(handler_guard.len(), 1);
8701        assert_eq!(handler_guard[0].bar_type, bar_type.standard());
8702    }
8703
8704    #[rstest]
8705    fn test_composite_time_bar_aggregator_uses_standard_timer_name(equity_aapl: Equity) {
8706        let instrument = InstrumentAny::Equity(equity_aapl);
8707        let bar_type = BarType::new_composite(
8708            instrument.id(),
8709            BarSpecification::new(5, BarAggregation::Minute, PriceType::Last),
8710            AggregationSource::Internal,
8711            1,
8712            BarAggregation::Minute,
8713            AggregationSource::External,
8714        );
8715        let clock = Rc::new(RefCell::new(VirtualClock::new()));
8716
8717        let aggregator = TimeBarAggregator::new(
8718            bar_type,
8719            instrument.price_precision(),
8720            instrument.size_precision(),
8721            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
8722            |_: Bar| {},
8723            false,
8724            true,
8725            BarIntervalType::LeftOpen,
8726            None,
8727            TimeZone::UTC,
8728            0,
8729            false,
8730        );
8731
8732        let boxed: Box<dyn BarAggregator> = Box::new(aggregator);
8733        let rc = Rc::new(RefCell::new(boxed));
8734        rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
8735
8736        let expected = format!("TIME_BAR_{}", bar_type.standard());
8737        assert!(
8738            clock.borrow().timer_names().contains(&expected.as_str()),
8739            "timer names {:?} should contain {expected}",
8740            clock.borrow().timer_names(),
8741        );
8742    }
8743
8744    const JAN_15_2024: u64 = 1_705_276_800_000_000_000;
8745    const JAN_20_2024: u64 = 1_705_708_800_000_000_000;
8746    const FEB_01_2024: u64 = 1_706_745_600_000_000_000;
8747    const FEB_10_2024: u64 = 1_707_523_200_000_000_000;
8748    const MAR_01_2024: u64 = 1_709_251_200_000_000_000;
8749    const MAR_10_2024: u64 = 1_710_028_800_000_000_000;
8750    const APR_01_2024: u64 = 1_711_929_600_000_000_000;
8751
8752    #[rstest]
8753    fn test_time_bar_month_alert_rescheduled_after_month_without_updates(equity_aapl: Equity) {
8754        let instrument = InstrumentAny::Equity(equity_aapl);
8755        let bar_spec = BarSpecification::new(1, BarAggregation::Month, PriceType::Last);
8756        let clock = Rc::new(RefCell::new(VirtualClock::new()));
8757        clock.borrow_mut().set_time(UnixNanos::from(JAN_15_2024));
8758        let (rc, handler) = start_time_bar_aggregator(
8759            &instrument,
8760            bar_spec,
8761            &clock,
8762            false, // build_with_no_updates
8763            BarIntervalType::LeftOpen,
8764        );
8765        let timer_name = format!("TIME_BAR_{}", rc.borrow().bar_type());
8766
8767        rc.borrow_mut().update(
8768            Price::from("100.00"),
8769            Quantity::from(1),
8770            UnixNanos::from(JAN_20_2024),
8771        );
8772        advance_and_fire(&clock, UnixNanos::from(FEB_01_2024));
8773        assert_eq!(handler.lock().len(), 1);
8774
8775        // February has no updates, so no bar is built at March 1
8776        advance_and_fire(&clock, UnixNanos::from(MAR_01_2024));
8777        assert_eq!(handler.lock().len(), 1);
8778        let next_alert = clock.borrow().next_time_ns(&timer_name);
8779
8780        rc.borrow_mut().update(
8781            Price::from("101.00"),
8782            Quantity::from(1),
8783            UnixNanos::from(MAR_10_2024),
8784        );
8785        advance_and_fire(&clock, UnixNanos::from(APR_01_2024));
8786
8787        let bars = handler.lock();
8788        assert_eq!(bars.len(), 2);
8789        assert_eq!(bars[1].close, Price::from("101.00"));
8790        assert_eq!(bars[1].ts_event, UnixNanos::from(MAR_01_2024));
8791        assert_eq!(bars[1].ts_init, UnixNanos::from(APR_01_2024));
8792        assert_eq!(next_alert, Some(UnixNanos::from(APR_01_2024)));
8793    }
8794
8795    #[rstest]
8796    fn test_time_bar_month_alert_rescheduled_when_first_month_has_no_data(equity_aapl: Equity) {
8797        let instrument = InstrumentAny::Equity(equity_aapl);
8798        let bar_spec = BarSpecification::new(1, BarAggregation::Month, PriceType::Last);
8799        let clock = Rc::new(RefCell::new(VirtualClock::new()));
8800        clock.borrow_mut().set_time(UnixNanos::from(JAN_15_2024));
8801        let (rc, handler) = start_time_bar_aggregator(
8802            &instrument,
8803            bar_spec,
8804            &clock,
8805            true, // build_with_no_updates
8806            BarIntervalType::LeftOpen,
8807        );
8808        let timer_name = format!("TIME_BAR_{}", rc.borrow().bar_type());
8809
8810        // No data before the first alert, so the builder is not initialized
8811        advance_and_fire(&clock, UnixNanos::from(FEB_01_2024));
8812        assert_eq!(handler.lock().len(), 0);
8813        let next_alert = clock.borrow().next_time_ns(&timer_name);
8814
8815        rc.borrow_mut().update(
8816            Price::from("100.00"),
8817            Quantity::from(1),
8818            UnixNanos::from(FEB_10_2024),
8819        );
8820        advance_and_fire(&clock, UnixNanos::from(MAR_01_2024));
8821
8822        let bars = handler.lock();
8823        assert_eq!(bars.len(), 1);
8824        assert_eq!(bars[0].close, Price::from("100.00"));
8825        assert_eq!(bars[0].ts_event, UnixNanos::from(FEB_01_2024));
8826        assert_eq!(bars[0].ts_init, UnixNanos::from(MAR_01_2024));
8827        assert_eq!(next_alert, Some(UnixNanos::from(MAR_01_2024)));
8828    }
8829
8830    #[rstest]
8831    fn test_time_bar_historical_month_keeps_calendar_alignment_across_gap(equity_aapl: Equity) {
8832        let instrument = InstrumentAny::Equity(equity_aapl);
8833        let bar_spec = BarSpecification::new(1, BarAggregation::Month, PriceType::Last);
8834        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
8835        let (handler, record) = recording_handler();
8836        let clock = Rc::new(RefCell::new(VirtualClock::new()));
8837
8838        let mut agg = TimeBarAggregator::new(
8839            bar_type,
8840            instrument.price_precision(),
8841            instrument.size_precision(),
8842            Rc::clone(&clock) as Rc<RefCell<dyn Clock>>,
8843            record,
8844            true, // build_with_no_updates
8845            true, // timestamp_on_close
8846            BarIntervalType::LeftOpen,
8847            None,
8848            TimeZone::UTC,
8849            0,
8850            false,
8851        );
8852        agg.historical_mode = true;
8853        agg.set_clock_internal(clock);
8854        let boxed: Box<dyn BarAggregator> = Box::new(agg);
8855        let rc = Rc::new(RefCell::new(boxed));
8856        rc.borrow_mut().set_aggregator_weak(Rc::downgrade(&rc));
8857
8858        for (price, ts) in [
8859            ("100.00", "2024-01-15T00:00:00Z"),
8860            ("101.00", "2024-02-01T00:00:00Z"),
8861            ("102.00", "2024-02-01T00:00:00Z"),
8862            ("103.00", "2024-04-01T00:00:00Z"),
8863            ("104.00", "2024-05-10T00:00:00Z"),
8864        ] {
8865            let ts = UnixNanos::from(ts.parse::<jiff::Timestamp>().unwrap());
8866            rc.borrow_mut()
8867                .update(Price::from(price), Quantity::from(1), ts);
8868        }
8869
8870        let expected: Vec<_> = [
8871            ("100.00", "102.00", 3, "2024-02-01T00:00:00Z"),
8872            ("102.00", "102.00", 0, "2024-03-01T00:00:00Z"),
8873            ("103.00", "103.00", 1, "2024-04-01T00:00:00Z"),
8874            ("103.00", "103.00", 0, "2024-05-01T00:00:00Z"),
8875        ]
8876        .into_iter()
8877        .map(|(open, close, volume, ts)| {
8878            let ts = UnixNanos::from(ts.parse::<jiff::Timestamp>().unwrap());
8879
8880            Bar::new(
8881                bar_type,
8882                Price::from(open),
8883                Price::from(close),
8884                Price::from(open),
8885                Price::from(close),
8886                Quantity::from(volume),
8887                ts,
8888                ts,
8889            )
8890        })
8891        .collect();
8892
8893        assert_eq!(*handler.lock(), expected);
8894    }
8895
8896    #[rstest]
8897    fn test_time_bar_right_open_ts_event_after_interval_without_updates(equity_aapl: Equity) {
8898        let instrument = InstrumentAny::Equity(equity_aapl);
8899        let bar_spec = BarSpecification::new(1, BarAggregation::Minute, PriceType::Last);
8900        // A start time of 0 means "now" to the clock, so offset from a real date
8901        let secs = |s: u64| UnixNanos::from(JAN_15_2024 + s * 1_000_000_000);
8902        let clock = Rc::new(RefCell::new(VirtualClock::new()));
8903        clock.borrow_mut().set_time(secs(30));
8904        let (rc, handler) = start_time_bar_aggregator(
8905            &instrument,
8906            bar_spec,
8907            &clock,
8908            false,                      // build_with_no_updates
8909            BarIntervalType::RightOpen, // ts_event = interval open
8910        );
8911
8912        rc.borrow_mut()
8913            .update(Price::from("100.00"), Quantity::from(1), secs(40));
8914        advance_and_fire(&clock, secs(60));
8915
8916        // No updates in [60s, 120s)
8917        advance_and_fire(&clock, secs(120));
8918
8919        rc.borrow_mut()
8920            .update(Price::from("101.00"), Quantity::from(1), secs(130));
8921        advance_and_fire(&clock, secs(180));
8922
8923        let bars = handler.lock();
8924        assert_eq!(bars.len(), 2);
8925        assert_eq!(bars[0].ts_event, secs(0));
8926        assert_eq!(bars[0].ts_init, secs(60));
8927        assert_eq!(bars[1].close, Price::from("101.00"));
8928        assert_eq!(bars[1].ts_event, secs(120));
8929        assert_eq!(bars[1].ts_init, secs(180));
8930    }
8931
8932    // Starts the timer with timestamp_on_close=false so ts_event is the bar open
8933    #[expect(clippy::type_complexity)]
8934    fn start_time_bar_aggregator(
8935        instrument: &InstrumentAny,
8936        bar_spec: BarSpecification,
8937        clock: &Rc<RefCell<VirtualClock>>,
8938        build_with_no_updates: bool,
8939        interval_type: BarIntervalType,
8940    ) -> (Rc<RefCell<Box<dyn BarAggregator>>>, Arc<Mutex<Vec<Bar>>>) {
8941        let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
8942        let (handler, record) = recording_handler();
8943        let aggregator = TimeBarAggregator::new(
8944            bar_type,
8945            instrument.price_precision(),
8946            instrument.size_precision(),
8947            Rc::clone(clock) as Rc<RefCell<dyn Clock>>,
8948            record,
8949            build_with_no_updates,
8950            false, // timestamp_on_close
8951            interval_type,
8952            None,
8953            TimeZone::UTC,
8954            0,
8955            false, // skip_first_non_full_bar
8956        );
8957        let boxed: Box<dyn BarAggregator> = Box::new(aggregator);
8958        let rc = Rc::new(RefCell::new(boxed));
8959        rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
8960        (rc, handler)
8961    }
8962
8963    fn advance_and_fire(clock: &Rc<RefCell<VirtualClock>>, to: UnixNanos) {
8964        let events = clock.borrow_mut().advance_time(to, true);
8965        // Release the clock borrow before month/year handlers reschedule their alerts
8966        let handlers = clock.borrow().match_handlers(events);
8967        for handler in handlers {
8968            handler.run();
8969        }
8970    }
8971
8972    pub(super) fn recording_handler<T: 'static>() -> (Arc<Mutex<Vec<T>>>, impl FnMut(T)) {
8973        let events = Arc::new(Mutex::new(Vec::new()));
8974        let recorded_events = Arc::clone(&events);
8975        (events, move |event| recorded_events.lock().push(event))
8976    }
8977}
8978
8979#[cfg(test)]
8980mod property_tests {
8981    use std::{cell::RefCell, rc::Rc};
8982
8983    use nautilus_common::{clock::VirtualClock, timer::TimeEvent};
8984    use nautilus_core::{UUID4, UnixNanos};
8985    use nautilus_model::{
8986        data::{Bar, BarSpecification, BarType, TradeTick, bar::get_bar_interval_ns},
8987        enums::{AggregationSource, AggressorSide, BarAggregation, BarIntervalType, PriceType},
8988        instruments::{Instrument, InstrumentAny, stubs::equity_aapl},
8989        types::{Price, Quantity},
8990    };
8991    use proptest::prelude::*;
8992    use rstest::rstest;
8993    use ustr::Ustr;
8994
8995    use super::{tests::recording_handler, *};
8996
8997    fn time_bar_spec_strategy() -> impl Strategy<Value = (BarAggregation, usize)> {
8998        prop_oneof![
8999            (Just(BarAggregation::Second), 1usize..=5),
9000            (Just(BarAggregation::Minute), 1usize..=5),
9001            (Just(BarAggregation::Hour), 1usize..=4),
9002        ]
9003    }
9004
9005    fn interval_type_strategy() -> impl Strategy<Value = BarIntervalType> {
9006        prop_oneof![
9007            Just(BarIntervalType::LeftOpen),
9008            Just(BarIntervalType::RightOpen),
9009        ]
9010    }
9011
9012    proptest! {
9013        #[rstest]
9014        fn prop_skip_first_drops_partial_then_emits(
9015            (aggregation, step) in time_bar_spec_strategy(),
9016            interval_type in interval_type_strategy(),
9017            skip_first in any::<bool>(),
9018        ) {
9019            let instrument = InstrumentAny::Equity(equity_aapl());
9020            let bar_spec = BarSpecification::new(step, aggregation, PriceType::Last);
9021            let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
9022            let interval_ns = get_bar_interval_ns(&bar_type);
9023
9024            // Anchor the clock one full interval past epoch plus a half-interval offset
9025            // so start_time lands mid-interval and fire_immediately is false.
9026            let now_ns = UnixNanos::default() + interval_ns + interval_ns / 2;
9027
9028            let (handler, record) = recording_handler();
9029            let clock = Rc::new(RefCell::new(VirtualClock::new()));
9030            clock.borrow_mut().set_time(now_ns);
9031            let event_name = Ustr::from(&format!("TIME_BAR_{bar_type}"));
9032
9033            let aggregator = TimeBarAggregator::new(
9034                bar_type,
9035                instrument.price_precision(),
9036                instrument.size_precision(),
9037                clock,
9038                record,
9039                false,
9040                false,
9041                interval_type,
9042                None,
9043                TimeZone::UTC,
9044                0,
9045                skip_first,
9046            );
9047
9048            let boxed: Box<dyn BarAggregator> = Box::new(aggregator);
9049            let rc = Rc::new(RefCell::new(boxed));
9050            rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
9051
9052            // First tick + first close event. start_time = 1 * interval, first_close
9053            // = 2 * interval. ts_init == first_close_ns: partial bar.
9054            rc.borrow_mut().update(
9055                Price::from("100.00"),
9056                Quantity::from(1),
9057                now_ns,
9058            );
9059            let first_close = UnixNanos::default() + interval_ns * 2;
9060            rc.borrow_mut().build_bar(&TimeEvent::new(
9061                event_name,
9062                UUID4::new(),
9063                first_close,
9064                first_close,
9065            ));
9066
9067            // Second tick + later close; emits unconditionally.
9068            rc.borrow_mut().update(
9069                Price::from("101.00"),
9070                Quantity::from(1),
9071                first_close + interval_ns / 2,
9072            );
9073            let second_close = first_close + interval_ns;
9074            rc.borrow_mut().build_bar(&TimeEvent::new(
9075                event_name,
9076                UUID4::new(),
9077                second_close,
9078                second_close,
9079            ));
9080
9081            let bars = handler.lock();
9082            let expected = if skip_first { 1 } else { 2 };
9083            prop_assert_eq!(bars.len(), expected);
9084            prop_assert_eq!(bars.last().unwrap().close, Price::from("101.00"));
9085            for bar in bars.iter() {
9086                prop_assert!(bar.high >= bar.open);
9087                prop_assert!(bar.high >= bar.close);
9088                prop_assert!(bar.low <= bar.open);
9089                prop_assert!(bar.low <= bar.close);
9090            }
9091        }
9092
9093        #[rstest]
9094        fn prop_skip_first_noop_on_exact_boundary(
9095            (aggregation, step) in time_bar_spec_strategy(),
9096            interval_type in interval_type_strategy(),
9097        ) {
9098            let instrument = InstrumentAny::Equity(equity_aapl());
9099            let bar_spec = BarSpecification::new(step, aggregation, PriceType::Last);
9100            let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
9101            let interval_ns = get_bar_interval_ns(&bar_type);
9102
9103            // Clock exactly on a bar boundary: fire_immediately=true, so the first
9104            // bar that reaches build_and_send must emit regardless of skip_first.
9105            let now_ns = UnixNanos::default() + interval_ns;
9106            let (handler, record) = recording_handler();
9107            let clock = Rc::new(RefCell::new(VirtualClock::new()));
9108            clock.borrow_mut().set_time(now_ns);
9109            let event_name = Ustr::from(&format!("TIME_BAR_{bar_type}"));
9110
9111            let aggregator = TimeBarAggregator::new(
9112                bar_type,
9113                instrument.price_precision(),
9114                instrument.size_precision(),
9115                clock,
9116                record,
9117                false,
9118                false,
9119                interval_type,
9120                None,
9121                TimeZone::UTC,
9122                0,
9123                true, // skip_first_non_full_bar
9124            );
9125
9126            let boxed: Box<dyn BarAggregator> = Box::new(aggregator);
9127            let rc = Rc::new(RefCell::new(boxed));
9128            rc.borrow_mut().start_timer(Some(Rc::clone(&rc)));
9129
9130            rc.borrow_mut().update(
9131                Price::from("100.00"),
9132                Quantity::from(1),
9133                now_ns,
9134            );
9135            let next_close = now_ns + interval_ns;
9136            rc.borrow_mut().build_bar(&TimeEvent::new(
9137                event_name,
9138                UUID4::new(),
9139                next_close,
9140                next_close,
9141            ));
9142
9143            let bars = handler.lock();
9144            prop_assert_eq!(bars.len(), 1);
9145            prop_assert_eq!(bars[0].close, Price::from("100.00"));
9146        }
9147
9148        #[rstest]
9149        fn prop_bar_builder_ohlc_invariants(
9150            updates in prop::collection::vec((1i64..=100_000i64, 1u64..=1_000u64), 1..=50),
9151        ) {
9152            let instrument = InstrumentAny::Equity(equity_aapl());
9153            let bar_spec = BarSpecification::new(1, BarAggregation::Tick, PriceType::Last);
9154            let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
9155            let mut builder = BarBuilder::new(bar_type, 2, 0);
9156
9157            let mut total_volume: u64 = 0;
9158
9159            for (i, (price_cents, size)) in updates.iter().enumerate() {
9160                let price = Price::new((*price_cents as f64) / 100.0, 2);
9161                let qty = Quantity::new(*size as f64, 0);
9162                let ts = UnixNanos::from((i as u64 + 1) * 1_000);
9163                total_volume += *size;
9164                builder.update(price, qty, ts);
9165            }
9166
9167            let bar = builder.build_now();
9168            prop_assert!(bar.low <= bar.open);
9169            prop_assert!(bar.low <= bar.close);
9170            prop_assert!(bar.high >= bar.open);
9171            prop_assert!(bar.high >= bar.close);
9172            prop_assert!(bar.low <= bar.high);
9173            prop_assert_eq!(bar.volume.as_f64(), total_volume as f64);
9174        }
9175
9176        #[rstest]
9177        fn prop_tick_bar_aggregator_volume_conservation(
9178            ticks in prop::collection::vec((1i64..=1_000i64, 1u64..=100u64), 3..=60),
9179            step in 1usize..=5,
9180        ) {
9181            let instrument = InstrumentAny::Equity(equity_aapl());
9182            let bar_spec = BarSpecification::new(step, BarAggregation::Tick, PriceType::Last);
9183            let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
9184            let (handler, record) = recording_handler();
9185
9186            let mut aggregator = TickBarAggregator::new(
9187                bar_type,
9188                instrument.price_precision(),
9189                instrument.size_precision(),
9190                record,
9191            );
9192
9193            let mut total_input: u64 = 0;
9194
9195            for (i, (price_cents, size)) in ticks.iter().enumerate() {
9196                let price = Price::new((*price_cents as f64) / 100.0, 2);
9197                let qty = Quantity::new(*size as f64, 0);
9198                aggregator.update(price, qty, UnixNanos::from((i as u64 + 1) * 1_000));
9199                total_input += *size;
9200            }
9201
9202            let bars = handler.lock();
9203            let emitted_count = bars.len();
9204            prop_assert_eq!(emitted_count, ticks.len() / step);
9205
9206            let mut sum_emitted: f64 = 0.0;
9207
9208            for bar in bars.iter() {
9209                prop_assert!(bar.low <= bar.open);
9210                prop_assert!(bar.low <= bar.close);
9211                prop_assert!(bar.high >= bar.open);
9212                prop_assert!(bar.high >= bar.close);
9213                sum_emitted += bar.volume.as_f64();
9214            }
9215
9216            // Unemitted pending size remains in the builder for the remainder `ticks.len() % step` ticks.
9217            let pending_size: u64 = ticks.iter()
9218                .skip(emitted_count * step)
9219                .map(|(_, s)| *s)
9220                .sum();
9221            prop_assert!((sum_emitted + pending_size as f64 - total_input as f64).abs() < 1e-6);
9222        }
9223
9224        #[rstest]
9225        fn prop_volume_bar_aggregator_conservation(
9226            sizes in prop::collection::vec(1u64..=50u64, 3..=40),
9227            step in 2u64..=10u64,
9228        ) {
9229            let instrument = InstrumentAny::Equity(equity_aapl());
9230            let bar_spec = BarSpecification::new(step as usize, BarAggregation::Volume, PriceType::Last);
9231            let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
9232            let (handler, record) = recording_handler();
9233
9234            let mut aggregator = VolumeBarAggregator::new(
9235                bar_type,
9236                instrument.price_precision(),
9237                instrument.size_precision(),
9238                record,
9239            );
9240
9241            let mut total_input: u64 = 0;
9242
9243            for (i, size) in sizes.iter().enumerate() {
9244                aggregator.update(
9245                    Price::from("100.00"),
9246                    Quantity::new(*size as f64, 0),
9247                    UnixNanos::from((i as u64 + 1) * 1_000),
9248                );
9249                total_input += *size;
9250            }
9251
9252            let bars = handler.lock();
9253
9254            // Every emitted bar has exactly `step` volume and OHLC ordering holds.
9255            for bar in bars.iter() {
9256                prop_assert_eq!(bar.volume, Quantity::from(step));
9257                prop_assert!(bar.low <= bar.open);
9258                prop_assert!(bar.low <= bar.close);
9259                prop_assert!(bar.high >= bar.open);
9260                prop_assert!(bar.high >= bar.close);
9261            }
9262
9263            // Conservation: total emitted + pending builder volume equals total input.
9264            let emitted_total: u64 = bars.len() as u64 * step;
9265            let pending = aggregator.core.builder.volume.as_f64();
9266            prop_assert!((emitted_total as f64 + pending - total_input as f64).abs() < 1e-6);
9267        }
9268
9269        #[rstest]
9270        fn prop_volume_bar_matches_unit_trade_reference(
9271            updates in prop::collection::vec((1i64..=100_000i64, 1u64..=8u64, 0u64..=30u64), 1..=30),
9272            step in 1usize..=5,
9273        ) {
9274            let instrument = InstrumentAny::Equity(equity_aapl());
9275            let bar_spec = BarSpecification::new(step, BarAggregation::Volume, PriceType::Last);
9276            let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
9277            let (handler, record) = recording_handler();
9278            let mut aggregator = VolumeBarAggregator::new(
9279                bar_type,
9280                instrument.price_precision(),
9281                instrument.size_precision(),
9282                record,
9283            );
9284            let price = |cents| {
9285                Price::from_decimal_dp(Decimal::new(cents, 2), 2)
9286                    .expect("bounded cents must produce a valid price")
9287            };
9288            let mut last_timestamp = UnixNanos::default();
9289            let mut pending_units = Vec::new();
9290            let mut expected_bars = Vec::new();
9291
9292            for (price_cents, size, timestamp) in &updates {
9293                let timestamp = UnixNanos::from(*timestamp);
9294                aggregator.update(price(*price_cents), Quantity::from(*size), timestamp);
9295
9296                if timestamp < last_timestamp {
9297                    continue;
9298                }
9299
9300                last_timestamp = timestamp;
9301                for _ in 0..*size {
9302                    pending_units.push((*price_cents, timestamp));
9303                }
9304
9305                while pending_units.len() >= step {
9306                    let units: Vec<_> = pending_units.drain(..step).collect();
9307                    let first = units.first().unwrap();
9308                    let last = units.last().unwrap();
9309                    let low = units.iter().map(|(cents, _)| *cents).min().unwrap();
9310                    let high = units.iter().map(|(cents, _)| *cents).max().unwrap();
9311                    expected_bars.push((
9312                        price(first.0),
9313                        price(high),
9314                        price(low),
9315                        price(last.0),
9316                        Quantity::from(step as u64),
9317                        last.1,
9318                    ));
9319                }
9320            }
9321
9322            let bars = handler.lock();
9323            prop_assert_eq!(bars.len(), expected_bars.len());
9324            for (actual, (open, high, low, close, volume, timestamp))
9325                in bars.iter().zip(expected_bars)
9326            {
9327                prop_assert_eq!(actual.open, open);
9328                prop_assert_eq!(actual.high, high);
9329                prop_assert_eq!(actual.low, low);
9330                prop_assert_eq!(actual.close, close);
9331                prop_assert_eq!(actual.volume, volume);
9332                prop_assert_eq!(actual.ts_event, timestamp);
9333                prop_assert_eq!(actual.ts_init, timestamp);
9334            }
9335
9336            prop_assert_eq!(aggregator.core.builder.volume, Quantity::from(pending_units.len() as u64));
9337            prop_assert_eq!(aggregator.core.builder.ts_last, last_timestamp);
9338
9339            if let Some((first, rest)) = pending_units.split_first() {
9340                let last = rest.last().unwrap_or(first);
9341                let low = pending_units.iter().map(|(cents, _)| *cents).min().unwrap();
9342                let high = pending_units.iter().map(|(cents, _)| *cents).max().unwrap();
9343                prop_assert_eq!(aggregator.core.builder.open, Some(price(first.0)));
9344                prop_assert_eq!(aggregator.core.builder.high, Some(price(high)));
9345                prop_assert_eq!(aggregator.core.builder.low, Some(price(low)));
9346                prop_assert_eq!(aggregator.core.builder.close, Some(price(last.0)));
9347            } else {
9348                prop_assert_eq!(aggregator.core.builder.open, None);
9349                prop_assert_eq!(aggregator.core.builder.high, None);
9350                prop_assert_eq!(aggregator.core.builder.low, None);
9351                prop_assert_eq!(aggregator.core.builder.close, None);
9352            }
9353        }
9354
9355        #[rstest]
9356        fn prop_bar_builder_spread_adjustment_is_additive(
9357            updates in prop::collection::vec((10_000i64..=100_000i64, 1u64..=100u64), 1..=20),
9358            spread_cents in -10_000i64..=10_000i64,
9359            backward in any::<bool>(),
9360        ) {
9361            let instrument = InstrumentAny::Equity(equity_aapl());
9362            let bar_spec = BarSpecification::new(1, BarAggregation::Tick, PriceType::Last);
9363            let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
9364            let mut builder = BarBuilder::new(bar_type, 2, 0);
9365
9366            let spread = Decimal::new(spread_cents, 2);
9367            let mode = if backward {
9368                ContinuousFutureAdjustmentType::BackwardSpread
9369            } else {
9370                ContinuousFutureAdjustmentType::ForwardSpread
9371            };
9372            builder.set_adjustment(spread, mode);
9373
9374            let mut min_cents = i64::MAX;
9375            let mut max_cents = i64::MIN;
9376
9377            for (i, (price_cents, size)) in updates.iter().enumerate() {
9378                if *price_cents < min_cents {
9379                    min_cents = *price_cents;
9380                }
9381
9382                if *price_cents > max_cents {
9383                    max_cents = *price_cents;
9384                }
9385
9386                builder.update(
9387                    Price::new((*price_cents as f64) / 100.0, 2),
9388                    Quantity::new(*size as f64, 0),
9389                    UnixNanos::from((i as u64 + 1) * 1_000),
9390                );
9391            }
9392
9393            let bar = builder.build_now();
9394            let first_decimal = Decimal::new(updates.first().unwrap().0, 2);
9395            let last_decimal = Decimal::new(updates.last().unwrap().0, 2);
9396            let min_decimal = Decimal::new(min_cents, 2);
9397            let max_decimal = Decimal::new(max_cents, 2);
9398
9399            prop_assert_eq!(bar.open.as_decimal(), first_decimal + spread);
9400            prop_assert_eq!(bar.close.as_decimal(), last_decimal + spread);
9401            prop_assert_eq!(bar.low.as_decimal(), min_decimal + spread);
9402            prop_assert_eq!(bar.high.as_decimal(), max_decimal + spread);
9403        }
9404
9405        #[rstest]
9406        fn prop_bar_builder_inactive_adjustment_is_identity(
9407            updates in prop::collection::vec((1i64..=100_000i64, 1u64..=1_000u64), 1..=20),
9408            use_ratio in any::<bool>(),
9409        ) {
9410            let instrument = InstrumentAny::Equity(equity_aapl());
9411            let bar_spec = BarSpecification::new(1, BarAggregation::Tick, PriceType::Last);
9412            let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
9413
9414            let mut adjusted = BarBuilder::new(bar_type, 2, 0);
9415            let mut baseline = BarBuilder::new(bar_type, 2, 0);
9416
9417            // Inactive in either mode: ZERO spread or ONE ratio.
9418            let (input, mode) = if use_ratio {
9419                (Decimal::ONE, ContinuousFutureAdjustmentType::BackwardRatio)
9420            } else {
9421                (Decimal::ZERO, ContinuousFutureAdjustmentType::BackwardSpread)
9422            };
9423            adjusted.set_adjustment(input, mode);
9424
9425            for (i, (price_cents, size)) in updates.iter().enumerate() {
9426                let price = Price::new((*price_cents as f64) / 100.0, 2);
9427                let qty = Quantity::new(*size as f64, 0);
9428                let ts = UnixNanos::from((i as u64 + 1) * 1_000);
9429                adjusted.update(price, qty, ts);
9430                baseline.update(price, qty, ts);
9431            }
9432
9433            let bar_adjusted = adjusted.build_now();
9434            let bar_baseline = baseline.build_now();
9435            prop_assert_eq!(bar_adjusted.open, bar_baseline.open);
9436            prop_assert_eq!(bar_adjusted.high, bar_baseline.high);
9437            prop_assert_eq!(bar_adjusted.low, bar_baseline.low);
9438            prop_assert_eq!(bar_adjusted.close, bar_baseline.close);
9439            prop_assert_eq!(bar_adjusted.volume, bar_baseline.volume);
9440        }
9441
9442        #[rstest]
9443        fn prop_bar_builder_spread_preserves_raw_arithmetic(
9444            updates in prop::collection::vec((10_000i64..=100_000i64, 1u64..=100u64), 1..=20),
9445            // Sub-precision spread: scale 4 versus price precision 2. Locks in that
9446            // spread mode performs raw addition without rounding to price precision.
9447            spread_micro in -10_000i64..=10_000i64,
9448        ) {
9449            let instrument = InstrumentAny::Equity(equity_aapl());
9450            let bar_spec = BarSpecification::new(1, BarAggregation::Tick, PriceType::Last);
9451            let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
9452            let mut builder = BarBuilder::new(bar_type, 2, 0);
9453
9454            let spread = Decimal::new(spread_micro, 4);
9455            builder.set_adjustment(spread, ContinuousFutureAdjustmentType::BackwardSpread);
9456
9457            let adjustment_raw_i128 = mantissa_exponent_to_fixed_i128(
9458                spread.mantissa(),
9459                -(spread.scale() as i8),
9460                FIXED_PRECISION,
9461            )
9462            .expect("scale within range");
9463            #[allow(
9464                clippy::useless_conversion,
9465                reason = "i128 to PriceRaw is real when not high-precision"
9466            )]
9467            let expected_adjustment_raw: PriceRaw =
9468                adjustment_raw_i128.try_into().expect("within PriceRaw range");
9469
9470            let mut min_cents = i64::MAX;
9471            let mut max_cents = i64::MIN;
9472            let mut last_price = Price::new(0.0, 2);
9473            let mut first_price = Price::new(0.0, 2);
9474
9475            for (i, (price_cents, size)) in updates.iter().enumerate() {
9476                if *price_cents < min_cents {
9477                    min_cents = *price_cents;
9478                }
9479
9480                if *price_cents > max_cents {
9481                    max_cents = *price_cents;
9482                }
9483
9484                let price = Price::new((*price_cents as f64) / 100.0, 2);
9485
9486                if i == 0 {
9487                    first_price = price;
9488                }
9489
9490                last_price = price;
9491                builder.update(
9492                    price,
9493                    Quantity::new(*size as f64, 0),
9494                    UnixNanos::from((i as u64 + 1) * 1_000),
9495                );
9496            }
9497
9498            let bar = builder.build_now();
9499            let min_price = Price::new((min_cents as f64) / 100.0, 2);
9500            let max_price = Price::new((max_cents as f64) / 100.0, 2);
9501            prop_assert_eq!(bar.open.raw(), first_price.raw() + expected_adjustment_raw);
9502            prop_assert_eq!(bar.close.raw(), last_price.raw() + expected_adjustment_raw);
9503            prop_assert_eq!(bar.low.raw(), min_price.raw() + expected_adjustment_raw);
9504            prop_assert_eq!(bar.high.raw(), max_price.raw() + expected_adjustment_raw);
9505            prop_assert_eq!(bar.open.precision, 2);
9506            prop_assert_eq!(bar.high.precision, 2);
9507            prop_assert_eq!(bar.low.precision, 2);
9508            prop_assert_eq!(bar.close.precision, 2);
9509        }
9510
9511        #[rstest]
9512        fn prop_bar_builder_active_ratio_scales_each_ohlc(
9513            updates in prop::collection::vec((1_000i64..=100_000i64, 1u64..=100u64), 1..=20),
9514            // Ratio in [0.50, 2.00] excluding exactly 1.00 to stay on the active path.
9515            ratio_centi in prop_oneof![50i64..=99i64, 101i64..=200i64],
9516            backward in any::<bool>(),
9517        ) {
9518            let instrument = InstrumentAny::Equity(equity_aapl());
9519            let bar_spec = BarSpecification::new(1, BarAggregation::Tick, PriceType::Last);
9520            let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
9521            let mut builder = BarBuilder::new(bar_type, 2, 0);
9522
9523            let ratio_decimal = Decimal::new(ratio_centi, 2);
9524            let ratio_f64 = (ratio_centi as f64) / 100.0;
9525            let mode = if backward {
9526                ContinuousFutureAdjustmentType::BackwardRatio
9527            } else {
9528                ContinuousFutureAdjustmentType::ForwardRatio
9529            };
9530            builder.set_adjustment(ratio_decimal, mode);
9531
9532            let mut min_cents = i64::MAX;
9533            let mut max_cents = i64::MIN;
9534            let mut first_cents = 0i64;
9535            let mut last_cents = 0i64;
9536
9537            for (i, (price_cents, size)) in updates.iter().enumerate() {
9538                if *price_cents < min_cents {
9539                    min_cents = *price_cents;
9540                }
9541
9542                if *price_cents > max_cents {
9543                    max_cents = *price_cents;
9544                }
9545
9546                if i == 0 {
9547                    first_cents = *price_cents;
9548                }
9549
9550                last_cents = *price_cents;
9551                builder.update(
9552                    Price::new((*price_cents as f64) / 100.0, 2),
9553                    Quantity::new(*size as f64, 0),
9554                    UnixNanos::from((i as u64 + 1) * 1_000),
9555                );
9556            }
9557
9558            let bar = builder.build_now();
9559            // Recompute via the same float math as the hot path so equality is exact.
9560            let expect = |cents: i64| Price::new((cents as f64) / 100.0 * ratio_f64, 2);
9561            prop_assert_eq!(bar.open, expect(first_cents));
9562            prop_assert_eq!(bar.close, expect(last_cents));
9563            // Ratio with positive ratio_f64 preserves ordering, so min/max map directly.
9564            prop_assert_eq!(bar.low, expect(min_cents));
9565            prop_assert_eq!(bar.high, expect(max_cents));
9566        }
9567
9568        #[rstest]
9569        fn prop_bar_builder_spread_mode_direction_is_metadata_only(
9570            updates in prop::collection::vec((10_000i64..=100_000i64, 1u64..=100u64), 1..=20),
9571            spread_cents in -10_000i64..=10_000i64,
9572        ) {
9573            let instrument = InstrumentAny::Equity(equity_aapl());
9574            let bar_spec = BarSpecification::new(1, BarAggregation::Tick, PriceType::Last);
9575            let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
9576
9577            let spread = Decimal::new(spread_cents, 2);
9578            let mut backward = BarBuilder::new(bar_type, 2, 0);
9579            let mut forward = BarBuilder::new(bar_type, 2, 0);
9580            backward.set_adjustment(spread, ContinuousFutureAdjustmentType::BackwardSpread);
9581            forward.set_adjustment(spread, ContinuousFutureAdjustmentType::ForwardSpread);
9582
9583            for (i, (price_cents, size)) in updates.iter().enumerate() {
9584                let price = Price::new((*price_cents as f64) / 100.0, 2);
9585                let qty = Quantity::new(*size as f64, 0);
9586                let ts = UnixNanos::from((i as u64 + 1) * 1_000);
9587                backward.update(price, qty, ts);
9588                forward.update(price, qty, ts);
9589            }
9590
9591            let bar_backward = backward.build_now();
9592            let bar_forward = forward.build_now();
9593            prop_assert_eq!(bar_backward.open, bar_forward.open);
9594            prop_assert_eq!(bar_backward.high, bar_forward.high);
9595            prop_assert_eq!(bar_backward.low, bar_forward.low);
9596            prop_assert_eq!(bar_backward.close, bar_forward.close);
9597        }
9598
9599        #[rstest]
9600        fn prop_value_bar_aggregator_ohlc_invariants(
9601            ticks in prop::collection::vec((50i64..=500i64, 1u64..=20u64), 2..=30),
9602            step in 100u64..=2_000u64,
9603        ) {
9604            let instrument = InstrumentAny::Equity(equity_aapl());
9605            let bar_spec = BarSpecification::new(step as usize, BarAggregation::Value, PriceType::Last);
9606            let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
9607            let (handler, record) = recording_handler();
9608
9609            let mut aggregator = ValueBarAggregator::new(
9610                bar_type,
9611                instrument.price_precision(),
9612                instrument.size_precision(),
9613                record,
9614            );
9615
9616            for (i, (price_cents, size)) in ticks.iter().enumerate() {
9617                aggregator.update(
9618                    Price::new((*price_cents as f64) / 100.0, 2),
9619                    Quantity::new(*size as f64, 0),
9620                    UnixNanos::from((i as u64 + 1) * 1_000),
9621                );
9622            }
9623
9624            let bars = handler.lock();
9625            for bar in bars.iter() {
9626                prop_assert!(bar.low <= bar.open);
9627                prop_assert!(bar.low <= bar.close);
9628                prop_assert!(bar.high >= bar.open);
9629                prop_assert!(bar.high >= bar.close);
9630                prop_assert!(bar.volume.as_f64() > 0.0);
9631            }
9632        }
9633
9634        #[rstest]
9635        fn prop_renko_brick_chain(
9636            moves in prop::collection::vec(-500i64..=500i64, 1..=60),
9637            step in 1usize..=10,
9638        ) {
9639            let instrument = InstrumentAny::Equity(equity_aapl());
9640            let bar_spec = BarSpecification::new(step, BarAggregation::Renko, PriceType::Last);
9641            let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
9642            let (handler, record) = recording_handler();
9643
9644            let price_increment = Price::from("0.01");
9645            let mut aggregator = RenkoBarAggregator::new(
9646                bar_type,
9647                2,
9648                0,
9649                price_increment,
9650                record,
9651            );
9652            let brick_size = aggregator.brick_size;
9653
9654            let base_raw = Price::from("1000.00").raw();
9655            let mut cum_increments: i64 = 0;
9656            let mut first_price: Option<Price> = None;
9657
9658            for (i, delta) in moves.iter().enumerate() {
9659                cum_increments += delta;
9660                let price = Price::from_raw(
9661                    base_raw + PriceRaw::from(cum_increments) * price_increment.raw(),
9662                    2,
9663                );
9664
9665                if first_price.is_none() {
9666                    first_price = Some(price);
9667                }
9668
9669                aggregator.update(price, Quantity::from(1), UnixNanos::from((i as u64 + 1) * 1_000));
9670            }
9671
9672            let bars = handler.lock();
9673            let mut expected_open = first_price.unwrap();
9674
9675            for bar in bars.iter() {
9676                // Bricks chain: each opens at the previous close.
9677                prop_assert_eq!(bar.open, expected_open);
9678                // Every brick spans exactly one brick size.
9679                let movement = if bar.close >= bar.open { bar.close - bar.open } else { bar.open - bar.close };
9680                prop_assert_eq!(movement, brick_size);
9681                // High/low are the brick endpoints.
9682                prop_assert_eq!(bar.high, bar.open.max(bar.close));
9683                prop_assert_eq!(bar.low, bar.open.min(bar.close));
9684                expected_open = bar.close;
9685            }
9686        }
9687
9688        #[rstest]
9689        fn prop_volume_imbalance_one_sided_conservation(
9690            sizes in prop::collection::vec(1u64..=50u64, 1..=40),
9691            step in 2u64..=10u64,
9692            buyer in any::<bool>(),
9693        ) {
9694            let instrument = InstrumentAny::Equity(equity_aapl());
9695            let bar_spec = BarSpecification::new(
9696                step as usize,
9697                BarAggregation::VolumeImbalance,
9698                PriceType::Last,
9699            );
9700            let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
9701            let (handler, record) = recording_handler();
9702
9703            let mut aggregator = VolumeImbalanceBarAggregator::new(
9704                bar_type,
9705                instrument.price_precision(),
9706                instrument.size_precision(),
9707                record,
9708            );
9709
9710            let side = if buyer { AggressorSide::Buy } else { AggressorSide::Sell };
9711            let mut total_input: u64 = 0;
9712
9713            for (i, size) in sizes.iter().enumerate() {
9714                let trade = TradeTick {
9715                    instrument_id: instrument.id(),
9716                    price: Price::from("100.00"),
9717                    size: Quantity::from(*size),
9718                    aggressor_side: side,
9719                    ts_event: UnixNanos::from((i as u64 + 1) * 1_000),
9720                    ts_init: UnixNanos::from((i as u64 + 1) * 1_000),
9721                    ..TradeTick::default()
9722                };
9723                aggregator.handle_trade(trade);
9724                total_input += *size;
9725            }
9726
9727            let bars = handler.lock();
9728
9729            // One-sided flow: every emitted bar carries exactly `step` volume.
9730            for bar in bars.iter() {
9731                prop_assert_eq!(bar.volume, Quantity::from(step));
9732            }
9733
9734            // Conservation: emitted volume plus pending builder volume equals input.
9735            let emitted: u64 = bars.len() as u64 * step;
9736            let pending = aggregator.core.builder.volume.as_f64();
9737            prop_assert!((emitted as f64 + pending - total_input as f64).abs() < 1e-9);
9738        }
9739
9740        #[rstest]
9741        fn prop_volume_runs_one_sided_conservation(
9742            sizes in prop::collection::vec(1u64..=50u64, 1..=40),
9743            step in 2u64..=10u64,
9744            buyer in any::<bool>(),
9745        ) {
9746            let instrument = InstrumentAny::Equity(equity_aapl());
9747            let bar_spec = BarSpecification::new(
9748                step as usize,
9749                BarAggregation::VolumeRuns,
9750                PriceType::Last,
9751            );
9752            let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
9753            let (handler, record) = recording_handler();
9754
9755            let mut aggregator = VolumeRunsBarAggregator::new(
9756                bar_type,
9757                instrument.price_precision(),
9758                instrument.size_precision(),
9759                record,
9760            );
9761
9762            let side = if buyer { AggressorSide::Buy } else { AggressorSide::Sell };
9763            let mut total_input: u64 = 0;
9764
9765            for (i, size) in sizes.iter().enumerate() {
9766                let trade = TradeTick {
9767                    instrument_id: instrument.id(),
9768                    price: Price::from("100.00"),
9769                    size: Quantity::from(*size),
9770                    aggressor_side: side,
9771                    ts_event: UnixNanos::from((i as u64 + 1) * 1_000),
9772                    ts_init: UnixNanos::from((i as u64 + 1) * 1_000),
9773                    ..TradeTick::default()
9774                };
9775                aggregator.handle_trade(trade);
9776                total_input += *size;
9777            }
9778
9779            let bars = handler.lock();
9780
9781            // A single-sided run never resets, so every bar carries exactly `step` volume.
9782            for bar in bars.iter() {
9783                prop_assert_eq!(bar.volume, Quantity::from(step));
9784            }
9785
9786            let emitted: u64 = bars.len() as u64 * step;
9787            let pending = aggregator.core.builder.volume.as_f64();
9788            prop_assert!((emitted as f64 + pending - total_input as f64).abs() < 1e-9);
9789        }
9790
9791        #[rstest]
9792        fn prop_value_bar_cum_value_stays_below_step(
9793            ticks in prop::collection::vec((50i64..=500i64, 1u64..=20u64), 1..=30),
9794            step in 100u64..=2_000u64,
9795        ) {
9796            let instrument = InstrumentAny::Equity(equity_aapl());
9797            let bar_spec = BarSpecification::new(step as usize, BarAggregation::Value, PriceType::Last);
9798            let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
9799            let step_decimal = Decimal::from(step);
9800
9801            let mut aggregator = ValueBarAggregator::new(
9802                bar_type,
9803                instrument.price_precision(),
9804                instrument.size_precision(),
9805                |_: Bar| {},
9806            );
9807
9808            for (i, (price_cents, size)) in ticks.iter().enumerate() {
9809                aggregator.update(
9810                    Price::new((*price_cents as f64) / 100.0, 2),
9811                    Quantity::new(*size as f64, 0),
9812                    UnixNanos::from((i as u64 + 1) * 1_000),
9813                );
9814
9815                // Invariant: the accumulator is always strictly below the step threshold,
9816                // which also guarantees the loop division never sees a zero divisor.
9817                prop_assert!(aggregator.get_cumulative_value() < step_decimal);
9818            }
9819        }
9820    }
9821}