nautilus_data/
aggregation.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2024 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Bar aggregation machinery.

// Under development
#![allow(dead_code)]
#![allow(unused_variables)]

use std::{cell::RefCell, ops::Add, rc::Rc};

use chrono::TimeDelta;
use nautilus_common::{
    clock::Clock,
    timer::{RustTimeEventCallback, TimeEvent},
};
use nautilus_core::{
    correctness::{self, FAILED},
    nanos::UnixNanos,
};
use nautilus_model::{
    data::{
        bar::{get_bar_interval, get_bar_interval_ns, get_time_bar_start, Bar, BarType},
        quote::QuoteTick,
        trade::TradeTick,
    },
    enums::AggregationSource,
    instruments::any::InstrumentAny,
    types::{fixed::FIXED_SCALAR, price::Price, quantity::Quantity},
};

pub trait BarAggregator {
    /// The [`BarType`] to be aggregated.
    fn bar_type(&self) -> BarType;
    /// Updates theaggregator  with the given price and size.
    fn update(&mut self, price: Price, size: Quantity, ts_event: UnixNanos);
    /// Updates the aggregator with the given quote.
    fn handle_quote_tick(&mut self, quote: QuoteTick) {
        let spec = self.bar_type().spec();

        self.update(
            quote.extract_price(spec.price_type),
            quote.extract_size(spec.price_type),
            quote.ts_event,
        );
    }
    /// Updates the aggregator with the given trade.
    fn handle_trade_tick(&mut self, trade: TradeTick) {
        self.update(trade.price, trade.size, trade.ts_event);
    }
}

/// Provides a generic bar builder for aggregation.
pub struct BarBuilder {
    bar_type: BarType,
    size_precision: u8,
    initialized: bool,
    ts_last: UnixNanos,
    count: usize,
    partial_set: bool,
    last_close: Option<Price>,
    open: Option<Price>,
    high: Option<Price>,
    low: Option<Price>,
    close: Option<Price>,
    volume: Quantity,
}

impl BarBuilder {
    /// Creates a new [`BarBuilder`] instance.
    ///
    /// # Panics
    ///
    /// This function panics:
    /// - If `instrument.id` is not equal to the `bar_type.instrument_id`.
    /// - If `bar_type.aggregation_source` is not equal to `AggregationSource::Internal`.
    #[must_use]
    pub fn new(instrument: &InstrumentAny, bar_type: BarType) -> Self {
        correctness::check_equal(
            instrument.id(),
            bar_type.instrument_id(),
            "instrument.id",
            "bar_type.instrument_id",
        )
        .expect(FAILED);
        correctness::check_equal(
            bar_type.aggregation_source(),
            AggregationSource::Internal,
            "bar_type.aggregation_source",
            "AggregationSource::Internal",
        )
        .expect(FAILED);

        Self {
            bar_type,
            size_precision: instrument.size_precision(),
            initialized: false,
            ts_last: UnixNanos::default(),
            count: 0,
            partial_set: false,
            last_close: None,
            open: None,
            high: None,
            low: None,
            close: None,
            volume: Quantity::zero(instrument.size_precision()),
        }
    }

    /// Set the initial values for a partially completed bar.
    pub fn set_partial(&mut self, partial_bar: Bar) {
        if self.partial_set {
            return; // Already updated
        }

        self.open = Some(partial_bar.open);

        if self.high.is_none() || partial_bar.high > self.high.unwrap() {
            self.high = Some(partial_bar.high);
        }

        if self.low.is_none() || partial_bar.low < self.low.unwrap() {
            self.low = Some(partial_bar.low);
        }

        if self.close.is_none() {
            self.close = Some(partial_bar.close);
        }

        self.volume = partial_bar.volume;

        if self.ts_last == 0 {
            self.ts_last = partial_bar.ts_init;
        }

        self.partial_set = true;
        self.initialized = true;
    }

    /// Update the bar builder.
    pub fn update(&mut self, price: Price, size: Quantity, ts_event: UnixNanos) {
        if ts_event < self.ts_last {
            return; // Not applicable
        }

        if self.open.is_none() {
            self.open = Some(price);
            self.high = Some(price);
            self.low = Some(price);
            self.initialized = true;
        } else {
            if price > self.high.unwrap() {
                self.high = Some(price);
            }
            if price < self.low.unwrap() {
                self.low = Some(price);
            }
        }

        self.close = Some(price);
        self.volume = self.volume.add(size);
        self.count += 1;
        self.ts_last = ts_event;
    }

    /// Reset the bar builder.
    ///
    /// All stateful fields are reset to their initial value.
    pub fn reset(&mut self) {
        self.open = None;
        self.high = None;
        self.low = None;
        self.volume = Quantity::zero(self.size_precision);
        self.count = 0;
    }

    /// Return the aggregated bar and reset.
    pub fn build_now(&mut self) -> Bar {
        self.build(self.ts_last, self.ts_last)
    }

    /// Return the aggregated bar with the given closing timestamp, and reset.
    pub fn build(&mut self, ts_event: UnixNanos, ts_init: UnixNanos) -> Bar {
        if self.open.is_none() {
            self.open = self.last_close;
            self.high = self.last_close;
            self.low = self.last_close;
            self.close = self.last_close;
        }

        // SAFETY: The open was checked, so we can assume all prices are Some
        let bar = Bar::new(
            self.bar_type,
            self.open.unwrap(),
            self.high.unwrap(),
            self.low.unwrap(),
            self.close.unwrap(),
            self.volume,
            ts_event,
            ts_init,
        )
        .unwrap();

        self.last_close = self.close;
        self.reset();
        bar
    }
}

/// Provides a means of aggregating specified bar types and sending to a registered handler.
pub struct BarAggregatorCore {
    bar_type: BarType,
    builder: BarBuilder,
    handler: fn(Bar),
    await_partial: bool,
}

impl BarAggregatorCore {
    /// Creates a new [`BarAggregatorCore`] instance.
    ///
    /// # Panics
    ///
    /// This function panics:
    /// - If `instrument.id` is not equal to the `bar_type.instrument_id`.
    /// - If `bar_type.aggregation_source` is not equal to `AggregationSource::Internal`.
    pub fn new(
        instrument: &InstrumentAny,
        bar_type: BarType,
        handler: fn(Bar),
        await_partial: bool,
    ) -> Self {
        Self {
            bar_type,
            builder: BarBuilder::new(instrument, bar_type),
            handler,
            await_partial,
        }
    }

    pub fn set_await_partial(&mut self, value: bool) {
        self.await_partial = value;
    }

    /// Set the initial values for a partially completed bar.
    pub fn set_partial(&mut self, partial_bar: Bar) {
        self.builder.set_partial(partial_bar);
    }

    fn apply_update(&mut self, price: Price, size: Quantity, ts_event: UnixNanos) {
        self.builder.update(price, size, ts_event);
    }

    fn build_now_and_send(&mut self) {
        let bar = self.builder.build_now();
        (self.handler)(bar);
    }

    fn build_and_send(&mut self, ts_event: UnixNanos, ts_init: UnixNanos) {
        let bar = self.builder.build(ts_event, ts_init);
        (self.handler)(bar);
    }
}

/// Provides a means of building tick bars aggregated from quote and trade ticks.
///
/// When received tick count reaches the step threshold of the bar
/// specification, then a bar is created and sent to the handler.
pub struct TickBarAggregator {
    core: BarAggregatorCore,
}

impl TickBarAggregator {
    /// Creates a new [`TickBarAggregator`] instance.
    ///
    /// # Panics
    ///
    /// This function panics:
    /// - If `instrument.id` is not equal to the `bar_type.instrument_id`.
    /// - If `bar_type.aggregation_source` is not equal to `AggregationSource::Internal`.
    pub fn new(
        instrument: &InstrumentAny,
        bar_type: BarType,
        handler: fn(Bar),
        await_partial: bool,
    ) -> Self {
        Self {
            core: BarAggregatorCore::new(instrument, bar_type, handler, await_partial),
        }
    }
}

impl BarAggregator for TickBarAggregator {
    fn bar_type(&self) -> BarType {
        self.core.bar_type
    }

    /// Apply the given update to the aggregator.
    fn update(&mut self, price: Price, size: Quantity, ts_event: UnixNanos) {
        self.core.apply_update(price, size, ts_event);
        let spec = self.core.bar_type.spec();

        if self.core.builder.count >= spec.step {
            self.core.build_now_and_send();
        }
    }
}

/// Provides a means of building volume bars aggregated from quote and trade ticks.
pub struct VolumeBarAggregator {
    core: BarAggregatorCore,
}

impl VolumeBarAggregator {
    /// Creates a new [`VolumeBarAggregator`] instance.
    ///
    /// # Panics
    ///
    /// This function panics:
    /// - If `instrument.id` is not equal to the `bar_type.instrument_id`.
    /// - If `bar_type.aggregation_source` is not equal to `AggregationSource::Internal`.
    pub fn new(
        instrument: &InstrumentAny,
        bar_type: BarType,
        handler: fn(Bar),
        await_partial: bool,
    ) -> Self {
        Self {
            core: BarAggregatorCore::new(instrument, bar_type, handler, await_partial),
        }
    }
}

impl BarAggregator for VolumeBarAggregator {
    fn bar_type(&self) -> BarType {
        self.core.bar_type
    }

    /// Apply the given update to the aggregator.
    #[allow(unused_assignments)] // Temp for development
    fn update(&mut self, price: Price, size: Quantity, ts_event: UnixNanos) {
        let mut raw_size_update = size.raw;
        let spec = self.core.bar_type.spec();
        let raw_step = (spec.step as f64 * FIXED_SCALAR) as u64;
        let mut raw_size_diff = 0;

        while raw_size_update > 0 {
            if self.core.builder.volume.raw + raw_size_update < raw_step {
                self.core.apply_update(
                    price,
                    Quantity::from_raw(raw_size_update, size.precision),
                    ts_event,
                );
                break;
            }

            raw_size_diff = raw_step - self.core.builder.volume.raw;
            self.core.apply_update(
                price,
                Quantity::from_raw(raw_size_update, size.precision),
                ts_event,
            );

            self.core.build_now_and_send();
            raw_size_update -= raw_size_diff;
        }
    }
}

/// Provides a means of building value bars aggregated from quote and trade ticks.
///
/// When received value reaches the step threshold of the bar
/// specification, then a bar is created and sent to the handler.
pub struct ValueBarAggregator {
    core: BarAggregatorCore,
    cum_value: f64,
}

impl ValueBarAggregator {
    /// Creates a new [`ValueBarAggregator`] instance.
    ///
    /// # Panics
    ///
    /// This function panics:
    /// - If `instrument.id` is not equal to the `bar_type.instrument_id`.
    /// - If `bar_type.aggregation_source` is not equal to `AggregationSource::Internal`.
    pub fn new(
        instrument: &InstrumentAny,
        bar_type: BarType,
        handler: fn(Bar),
        await_partial: bool,
    ) -> Self {
        Self {
            core: BarAggregatorCore::new(instrument, bar_type, handler, await_partial),
            cum_value: 0.0,
        }
    }

    #[must_use]
    /// Returns the cumulative value for the aggregator.
    pub const fn get_cumulative_value(&self) -> f64 {
        self.cum_value
    }
}

impl BarAggregator for ValueBarAggregator {
    fn bar_type(&self) -> BarType {
        self.core.bar_type
    }

    /// Apply the given update to the aggregator.
    fn update(&mut self, price: Price, size: Quantity, ts_event: UnixNanos) {
        let mut size_update = size.as_f64();
        let spec = self.core.bar_type.spec();

        while size_update > 0.0 {
            let value_update = price.as_f64() * size_update;
            if self.cum_value + value_update < spec.step as f64 {
                self.cum_value += value_update;
                self.core
                    .apply_update(price, Quantity::new(size_update, size.precision), ts_event);
                break;
            }

            let value_diff = spec.step as f64 - self.cum_value;
            let size_diff = size_update * (value_diff / value_update);
            self.core
                .apply_update(price, Quantity::new(size_diff, size.precision), ts_event);

            self.core.build_now_and_send();
            self.cum_value = 0.0;
            size_update -= size_diff;
        }
    }
}

/// Provides a means of building time bars aggregated from quote and trade ticks.
///
/// At each aggregation time interval, a bar is created and sent to the handler.
pub struct TimeBarAggregator<C>
where
    C: Clock,
{
    core: BarAggregatorCore,
    clock: C,
    build_with_no_updates: bool,
    timestamp_on_close: bool,
    is_left_open: bool,
    build_on_next_tick: bool,
    stored_open_ns: UnixNanos,
    stored_close_ns: UnixNanos,
    cached_update: Option<(Price, Quantity, u64)>,
    timer_name: String,
    interval: TimeDelta,
    interval_ns: UnixNanos,
    next_close_ns: UnixNanos,
}

#[derive(Clone)]
pub struct NewBarCallback<C: Clock> {
    aggregator: Rc<RefCell<TimeBarAggregator<C>>>,
}

impl<C: Clock> NewBarCallback<C> {
    pub const fn new(aggregator: Rc<RefCell<TimeBarAggregator<C>>>) -> Self {
        Self { aggregator }
    }
}

impl<C: Clock + 'static> RustTimeEventCallback for NewBarCallback<C> {
    fn call(&self, event: TimeEvent) {
        self.aggregator.borrow_mut().build_bar(event);
    }
}

impl<C> TimeBarAggregator<C>
where
    C: Clock + 'static,
{
    /// Creates a new [`TimeBarAggregator`] instance.
    ///
    /// # Panics
    ///
    /// This function panics:
    /// - If `instrument.id` is not equal to the `bar_type.instrument_id`.
    /// - If `bar_type.aggregation_source` is not equal to `AggregationSource::Internal`.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        instrument: &InstrumentAny,
        bar_type: BarType,
        handler: fn(Bar),
        await_partial: bool,
        clock: C,
        build_with_no_updates: bool,
        timestamp_on_close: bool,
        interval_type: &str, // TODO: Make this an enum
    ) -> Self {
        Self {
            core: BarAggregatorCore::new(instrument, bar_type, handler, await_partial),
            clock,
            build_with_no_updates,
            timestamp_on_close,
            is_left_open: false,
            build_on_next_tick: false,
            stored_open_ns: UnixNanos::default(),
            stored_close_ns: UnixNanos::default(),
            cached_update: None,
            timer_name: bar_type.to_string(),
            interval: get_bar_interval(&bar_type),
            interval_ns: get_bar_interval_ns(&bar_type),
            next_close_ns: UnixNanos::default(),
        }
    }

    /// Starts the time bar aggregator.
    pub fn start(&mut self, callback: NewBarCallback<C>) -> anyhow::Result<()> {
        let now = self.clock.utc_now();
        let start_time = get_time_bar_start(now, &self.bar_type());
        let start_time_ns = UnixNanos::from(start_time.timestamp_nanos_opt().unwrap() as u64);
        let callback: Rc<dyn RustTimeEventCallback> = Rc::new(callback);

        self.clock.set_timer_ns(
            &self.timer_name,
            self.interval_ns.as_u64(),
            start_time_ns,
            None,
            Some(callback.into()),
        );

        log::debug!("Started timer {}", self.timer_name);
        Ok(())
    }

    /// Stops the time bar aggregator.
    pub fn stop(&mut self) {
        self.clock.cancel_timer(&self.timer_name);
    }

    fn build_bar(&mut self, event: TimeEvent) {
        if !self.core.builder.initialized {
            self.build_on_next_tick = true;
            self.stored_close_ns = self.next_close_ns;
            return;
        }

        if !self.build_with_no_updates && self.core.builder.count == 0 {
            return;
        }

        let ts_init = event.ts_event;
        let ts_event = if self.is_left_open {
            if self.timestamp_on_close {
                event.ts_event
            } else {
                self.stored_open_ns
            }
        } else {
            self.stored_open_ns
        };

        self.core.build_and_send(ts_event, ts_init);
        self.stored_open_ns = event.ts_event;
        self.next_close_ns = self.clock.next_time_ns(&self.timer_name);
    }
}

impl<C> BarAggregator for TimeBarAggregator<C>
where
    C: Clock,
{
    fn bar_type(&self) -> BarType {
        self.core.bar_type
    }

    fn update(&mut self, price: Price, size: Quantity, ts_event: UnixNanos) {
        self.core.apply_update(price, size, ts_event);
        if self.build_on_next_tick {
            let ts_init = ts_event;

            let ts_event = if self.is_left_open {
                if self.timestamp_on_close {
                    self.stored_close_ns
                } else {
                    self.stored_open_ns
                }
            } else {
                self.stored_open_ns
            };

            self.core.build_and_send(ts_event, ts_init);
            self.build_on_next_tick = false;
            self.stored_close_ns = UnixNanos::default();
        }
    }
}

////////////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////////////
#[cfg(test)]
mod tests {
    use nautilus_model::{
        data::bar::{BarSpecification, BarType},
        enums::{AggregationSource, BarAggregation, PriceType},
        instruments::{any::InstrumentAny, equity::Equity, stubs::*},
        types::{price::Price, quantity::Quantity},
    };
    use rstest::rstest;

    use super::*;

    #[rstest]
    fn test_bar_builder_instantiate(equity_aapl: Equity) {
        let instrument = InstrumentAny::Equity(equity_aapl);
        let bar_type = BarType::new(
            instrument.id(),
            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
            AggregationSource::Internal,
        );
        let builder = BarBuilder::new(&instrument, bar_type);
        assert!(!builder.initialized);
        assert_eq!(builder.ts_last, 0);
        assert_eq!(builder.count, 0);
    }

    #[rstest]
    fn test_bar_builder_set_partial_updates_bar_to_expected_properties(equity_aapl: Equity) {
        let instrument = InstrumentAny::Equity(equity_aapl);
        let bar_type = BarType::new(
            instrument.id(),
            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
            AggregationSource::Internal,
        );
        let mut builder = BarBuilder::new(&instrument, bar_type);

        let partial_bar = Bar::new(
            bar_type,
            Price::new(1.00001, 8),
            Price::new(1.00010, 8),
            Price::new(1.00000, 8),
            Price::new(1.00002, 8),
            Quantity::new(1.0, 0),
            UnixNanos::from(1_000_000_000),
            UnixNanos::from(2_000_000_000),
        )
        .unwrap();

        builder.set_partial(partial_bar);
        let bar = builder.build_now();

        assert_eq!(bar.open, Price::new(1.00001, 8));
        assert_eq!(bar.high, Price::new(1.00010, 8));
        assert_eq!(bar.low, Price::new(1.00000, 8));
        assert_eq!(bar.close, Price::new(1.00002, 8));
        assert_eq!(bar.volume, Quantity::new(1.0, 0));
        assert_eq!(bar.ts_init, 2_000_000_000);
        assert_eq!(builder.ts_last, 2_000_000_000);
    }

    #[rstest]
    fn test_bar_builder_set_partial_when_already_set_does_not_update(equity_aapl: Equity) {
        let instrument = InstrumentAny::Equity(equity_aapl);
        let bar_type = BarType::new(
            instrument.id(),
            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
            AggregationSource::Internal,
        );
        let mut builder = BarBuilder::new(&instrument, bar_type);

        let partial_bar1 = Bar::new(
            bar_type,
            Price::new(1.00001, 8),
            Price::new(1.00010, 8),
            Price::new(1.00000, 8),
            Price::new(1.00002, 8),
            Quantity::new(1.0, 0),
            UnixNanos::from(1_000_000_000),
            UnixNanos::from(1_000_000_000),
        )
        .unwrap();

        let partial_bar2 = Bar::new(
            bar_type,
            Price::new(2.00001, 8),
            Price::new(2.00010, 8),
            Price::new(2.00000, 8),
            Price::new(2.00002, 8),
            Quantity::new(2.0, 0),
            UnixNanos::from(3_000_000_000),
            UnixNanos::from(3_000_000_000),
        )
        .unwrap();

        builder.set_partial(partial_bar1);
        builder.set_partial(partial_bar2);
        let bar = builder.build(
            UnixNanos::from(4_000_000_000),
            UnixNanos::from(4_000_000_000),
        );

        assert_eq!(bar.open, Price::new(1.00001, 8));
        assert_eq!(bar.high, Price::new(1.00010, 8));
        assert_eq!(bar.low, Price::new(1.00000, 8));
        assert_eq!(bar.close, Price::new(1.00002, 8));
        assert_eq!(bar.volume, Quantity::new(1.0, 0));
        assert_eq!(bar.ts_init, 4_000_000_000);
        assert_eq!(builder.ts_last, 1_000_000_000);
    }

    #[rstest]
    fn test_bar_builder_single_update_results_in_expected_properties(equity_aapl: Equity) {
        let instrument = InstrumentAny::Equity(equity_aapl);
        let bar_type = BarType::new(
            instrument.id(),
            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
            AggregationSource::Internal,
        );
        let mut builder = BarBuilder::new(&instrument, bar_type);

        builder.update(
            Price::new(1.00000, 8),
            Quantity::new(1.0, 0),
            UnixNanos::from(0),
        );

        assert!(builder.initialized);
        assert_eq!(builder.ts_last, 0);
        assert_eq!(builder.count, 1);
    }

    #[rstest]
    fn test_bar_builder_single_update_when_timestamp_less_than_last_update_ignores(
        equity_aapl: Equity,
    ) {
        let instrument = InstrumentAny::Equity(equity_aapl);
        let bar_type = BarType::new(
            instrument.id(),
            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
            AggregationSource::Internal,
        );
        let mut builder = BarBuilder::new(&instrument, bar_type);

        builder.update(
            Price::new(1.00000, 8),
            Quantity::new(1.0, 0),
            UnixNanos::from(1_000),
        );
        builder.update(
            Price::new(1.00001, 8),
            Quantity::new(1.0, 0),
            UnixNanos::from(500),
        );

        assert!(builder.initialized);
        assert_eq!(builder.ts_last, 1_000);
        assert_eq!(builder.count, 1);
    }

    #[rstest]
    fn test_bar_builder_multiple_updates_correctly_increments_count(equity_aapl: Equity) {
        let instrument = InstrumentAny::Equity(equity_aapl);
        let bar_type = BarType::new(
            instrument.id(),
            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
            AggregationSource::Internal,
        );
        let mut builder = BarBuilder::new(&instrument, bar_type);

        for _ in 0..5 {
            builder.update(
                Price::new(1.00000, 8),
                Quantity::new(1.0, 0),
                UnixNanos::from(1_000),
            );
        }

        assert_eq!(builder.count, 5);
    }

    #[rstest]
    #[should_panic]
    fn test_bar_builder_build_when_no_updates_panics(equity_aapl: Equity) {
        let instrument = InstrumentAny::Equity(equity_aapl);
        let bar_type = BarType::new(
            instrument.id(),
            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
            AggregationSource::Internal,
        );
        let mut builder = BarBuilder::new(&instrument, bar_type);
        let _ = builder.build_now();
    }

    #[rstest]
    fn test_bar_builder_build_when_received_updates_returns_expected_bar(equity_aapl: Equity) {
        let instrument = InstrumentAny::Equity(equity_aapl);
        let bar_type = BarType::new(
            instrument.id(),
            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
            AggregationSource::Internal,
        );
        let mut builder = BarBuilder::new(&instrument, bar_type);

        builder.update(
            Price::new(1.00001, 8),
            Quantity::new(2.0, 0),
            UnixNanos::from(0),
        );
        builder.update(
            Price::new(1.00002, 8),
            Quantity::new(2.0, 0),
            UnixNanos::from(0),
        );
        builder.update(
            Price::new(1.00000, 8),
            Quantity::new(1.0, 0),
            UnixNanos::from(1_000_000_000),
        );

        let bar = builder.build_now();

        assert_eq!(bar.open, Price::new(1.00001, 8));
        assert_eq!(bar.high, Price::new(1.00002, 8));
        assert_eq!(bar.low, Price::new(1.00000, 8));
        assert_eq!(bar.close, Price::new(1.00000, 8));
        assert_eq!(bar.volume, Quantity::new(5.0, 0));
        assert_eq!(bar.ts_init, 1_000_000_000);
        assert_eq!(builder.ts_last, 1_000_000_000);
        assert_eq!(builder.count, 0);
    }

    #[rstest]
    fn test_bar_builder_build_with_previous_close(equity_aapl: Equity) {
        let instrument = InstrumentAny::Equity(equity_aapl);
        let bar_type = BarType::new(
            instrument.id(),
            BarSpecification::new(3, BarAggregation::Tick, PriceType::Last),
            AggregationSource::Internal,
        );
        let mut builder = BarBuilder::new(&instrument, bar_type);

        builder.update(
            Price::new(1.00001, 8),
            Quantity::new(1.0, 0),
            UnixNanos::from(0),
        );
        builder.build_now(); // This close should become the next open

        builder.update(
            Price::new(1.00000, 8),
            Quantity::new(1.0, 0),
            UnixNanos::from(0),
        );
        builder.update(
            Price::new(1.00003, 8),
            Quantity::new(1.0, 0),
            UnixNanos::from(0),
        );
        builder.update(
            Price::new(1.00002, 8),
            Quantity::new(1.0, 0),
            UnixNanos::from(0),
        );

        let bar = builder.build_now();

        assert_eq!(bar.open, Price::new(1.00000, 8));
        assert_eq!(bar.high, Price::new(1.00003, 8));
        assert_eq!(bar.low, Price::new(1.00000, 8));
        assert_eq!(bar.close, Price::new(1.00002, 8));
        assert_eq!(bar.volume, Quantity::new(3.0, 0));
    }

    // #[rstest]
    // fn test_tick_bar_aggregator_handle_quote_tick_when_count_below_threshold_updates(
    //     equity_aapl: Equity,
    // ) {
    //     let instrument = InstrumentAny::Equity(equity_aapl);
    //     let bar_spec = BarSpecification::new(3, BarAggregation::Tick, PriceType::Mid);
    //     let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
    //     let handler = Arc::new(Mutex::new(Vec::new()));
    //     let mut aggregator = TickBarAggregator::new(&instrument, bar_type, Arc::clone(&handler));
    //
    //     let tick = QuoteTick::new(
    //         instrument.id(),
    //         Price::new(1.00001, 8),
    //         Price::new(1.00004, 8),
    //         Quantity::new(1.0, 0),
    //         Quantity::new(1.0, 0),
    //         UnixNanos::from(0),
    //         UnixNanos::from(0),
    //     );
    //
    //     aggregator.handle_quote_tick(tick);
    //
    //     let handler_guard = handler.lock().unwrap();
    //     assert_eq!(handler_guard.len(), 0);
    // }

    //
    // #[rstest]
    // fn test_tick_bar_aggregator_handle_trade_tick_when_count_below_threshold_updates(
    //     equity_aapl: Equity,
    // ) {
    //     let instrument = InstrumentAny::Equity(equity_aapl);
    //     let bar_spec = BarSpecification::new(3, BarAggregation::Tick, PriceType::Last);
    //     let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
    //     let handler = Arc::new(Mutex::new(Vec::new()));
    //     let mut aggregator = TickBarAggregator::new(&instrument, bar_type, Arc::clone(&handler));
    //
    //     let tick = TradeTick::new(
    //         instrument.id(),
    //         Price::new(1.00001, 8),
    //         Quantity::new(1.0, 0),
    //         AggressorSide::Buyer,
    //         TradeId::new("123456"),
    //         UnixNanos::from(0),
    //         UnixNanos::from(0),
    //     );
    //
    //     aggregator.handle_trade_tick(tick);
    //
    //     let handler_guard = handler.lock().unwrap();
    //     assert_eq!(handler_guard.len(), 0);
    // }
    //
    // #[rstest]
    // fn test_tick_bar_aggregator_handle_quote_tick_when_count_at_threshold_sends_bar_to_handler(
    //     equity_aapl: Equity,
    // ) {
    //     let instrument = InstrumentAny::Equity(equity_aapl);
    //     let bar_spec = BarSpecification::new(3, BarAggregation::Tick, PriceType::Mid);
    //     let bar_type = BarType::new(instrument.id(), bar_spec, AggregationSource::Internal);
    //     let handler = Arc::new(Mutex::new(Vec::new()));
    //     let mut aggregator = TickBarAggregator::new(&instrument, bar_type, Arc::clone(&handler));
    //
    //     let tick1 = QuoteTick::new(
    //         instrument.id(),
    //         Price::new(1.00001, 8),
    //         Price::new(1.00004, 8),
    //         Quantity::new(1.0, 0),
    //         Quantity::new(1.0, 0),
    //         UnixNanos::from(0),
    //         UnixNanos::from(0),
    //     );
    //
    //     let tick2 = QuoteTick::new(
    //         instrument.id(),
    //         Price::new(1.00002, 8),
    //         Price::new(1.00005, 8),
    //         Quantity::new(1.0, 0),
    //         Quantity::new(1.0, 0),
    //         UnixNanos::from(0),
    //         UnixNanos::from(0),
    //     );
    //
    //     let tick3 = QuoteTick::new(
    //         instrument.id(),
    //         Price::new(1.00000, 8),
    //         Price::new(1.00003, 8),
    //         Quantity::new(1.0, 0),
    //         Quantity::new(1.0, 0),
    //         UnixNanos::from(0),
    //         UnixNanos::from(0),
    //     );
    //
    //     aggregator.handle_quote_tick(tick1);
    //     aggregator.handle_quote_tick(tick2);
    //     aggregator.handle_quote_tick(tick3);
    //
    //     let handler_guard = handler.lock().unwrap();
    //     assert_eq!(handler_guard.len(), 1);
    //     let bar = &handler_guard[0];
    //     assert_eq!(bar.open, Price::new(1.000025, 8));
    //     assert_eq!(bar.high, Price::new(1.000035, 8));
    //     assert_eq!(bar.low, Price::new(1.000015, 8));
    //     assert_eq!(bar.close, Price::new(1.000015, 8));
    //     assert_eq!(bar.volume, Quantity::new(3.0, 0));
    // }
}