rustrade-data 0.5.0

High performance & normalised WebSocket intergration for leading cryptocurrency exchanges - batteries included.
Documentation
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
use crate::subscription::book::OrderBookEvent;
use chrono::{DateTime, Utc};
use derive_more::Display;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use tracing::debug;

/// Provides a [`OrderBookL2Manager`](manager::OrderBookL2Manager) for maintaining a set of local
/// L2 [`OrderBook`]s.
pub mod manager;

/// Provides an abstract collection of cheaply cloneable shared-state [`OrderBook`].
pub mod map;

/// Venue + local timestamps for an [`OrderBook`] revision.
///
/// Serves double duty as both the constructor argument
/// ([`OrderBook::new`]/[`OrderBook::from_sides`]) and the stored field, so
/// `update`/`snapshot` are one-line copies. The named fields prevent
/// transposition of the two same-typed `Option<DateTime<Utc>>` times.
///
/// Each timestamp carries exactly one honest meaning; staleness *policy* is left
/// to the consumer (compose over the accessors).
#[derive(Copy, Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
pub struct OrderBookTimes {
    /// Matching-engine time (`"T"` on Binance futures). `None` when the venue
    /// doesn't supply it (Binance spot, IBKR, ...). Latency/engine audit — not a
    /// liveness signal.
    pub time_engine: Option<DateTime<Utc>>,
    /// Venue event/broadcast time (`"E"` on Binance, `ts` on Bybit). `None` when
    /// the venue supplies none (IBKR; Binance spot REST seed). Feed-lag-aware
    /// liveness where present.
    pub time_exchange: Option<DateTime<Utc>>,
    /// Local ingestion wall-clock — ALWAYS present once a revision is applied.
    /// Universal liveness floor; use when `time_exchange` is `None` (e.g. IBKR).
    ///
    /// NOTE: a default/pre-population book ([`OrderBook::default`], used as the
    /// manager placeholder before the first event) carries the epoch (1970) here
    /// — desirable for a liveness floor (reads as stale → consumer fail-closes
    /// until the first revision), but it is NOT a real ingestion time.
    pub time_received: DateTime<Utc>,
}

/// Normalised Barter [`OrderBook`] snapshot.
///
/// ### Equality
/// `PartialEq`/`Eq` is derived over **all** fields, including the [`OrderBookTimes`]
/// timestamps. Because `time_received` is stamped per construction, two
/// content-identical books observed at different instants compare **unequal**. For
/// content comparison use the accessors (`sequence()`/`bids()`/`asks()`).
#[derive(Clone, PartialEq, Eq, Debug, Default, Deserialize, Serialize)]
pub struct OrderBook {
    sequence: u64,
    times: OrderBookTimes,
    bids: OrderBookSide<Bids>,
    asks: OrderBookSide<Asks>,
}

impl OrderBook {
    /// Construct a new sorted [`OrderBook`].
    ///
    /// Note that the passed bid and asks levels do not need to be pre-sorted.
    pub fn new<IterBids, IterAsks, L>(
        sequence: u64,
        times: OrderBookTimes,
        bids: IterBids,
        asks: IterAsks,
    ) -> Self
    where
        IterBids: IntoIterator<Item = L>,
        IterAsks: IntoIterator<Item = L>,
        L: Into<Level>,
    {
        Self {
            sequence,
            times,
            bids: OrderBookSide::bids(bids),
            asks: OrderBookSide::asks(asks),
        }
    }

    /// Construct an [`OrderBook`] from pre-sorted [`OrderBookSide`]s.
    ///
    /// Use this when you already have sorted sides to avoid re-sorting overhead.
    /// Caller must ensure sides are correctly sorted (bids descending, asks ascending).
    pub fn from_sides(
        sequence: u64,
        times: OrderBookTimes,
        bids: OrderBookSide<Bids>,
        asks: OrderBookSide<Asks>,
    ) -> Self {
        debug_assert!(
            bids.levels().windows(2).all(|w| w[0].price >= w[1].price),
            "bids must be sorted descending by price"
        );
        debug_assert!(
            asks.levels().windows(2).all(|w| w[0].price <= w[1].price),
            "asks must be sorted ascending by price"
        );
        Self {
            sequence,
            times,
            bids,
            asks,
        }
    }

    /// Current `u64` sequence number associated with the [`OrderBook`].
    pub fn sequence(&self) -> u64 {
        self.sequence
    }

    /// Matching-engine time associated with the [`OrderBook`] (`"T"` on Binance
    /// futures).
    ///
    /// `None` when the venue doesn't supply matching-engine time (Binance spot,
    /// IBKR, ...). This is for latency / engine audit — **not** a liveness signal;
    /// use [`OrderBook::time_exchange`]/[`OrderBook::time_received`] for staleness.
    pub fn time_engine(&self) -> Option<DateTime<Utc>> {
        self.times.time_engine
    }

    /// Venue event/broadcast time associated with the [`OrderBook`] (`"E"` on
    /// Binance, `ts` on Bybit).
    ///
    /// Feed-lag-aware liveness where present: `now - time_exchange` catches data
    /// that is old despite being just received. `None` when the venue supplies no
    /// broadcast timestamp (IBKR; Binance spot REST seed before the first diff).
    /// `None` is a capability signal, not a defect — fall back to
    /// [`OrderBook::time_received`].
    ///
    /// Note the asymmetry with `MarketEvent::time_exchange` (non-`Option`, with a
    /// local fallback): here `None` means "the venue gave nothing".
    pub fn time_exchange(&self) -> Option<DateTime<Utc>> {
        self.times.time_exchange
    }

    /// Local ingestion wall-clock associated with the [`OrderBook`].
    ///
    /// The **universal liveness floor** — always present once a revision is
    /// applied, on every venue (including IBKR, where it is the only liveness
    /// signal). Skew-immune: `now - time_received` is a same-clock comparison.
    /// Prefer it as the fallback when [`OrderBook::time_exchange`] is `None`.
    ///
    /// A default/pre-population book ([`OrderBook::default`]) reports the epoch
    /// (1970) here, so it reads as stale until the first revision — the intended
    /// liveness-floor behaviour.
    pub fn time_received(&self) -> DateTime<Utc> {
        self.times.time_received
    }

    /// All revision timestamps for this [`OrderBook`] as a single
    /// [`OrderBookTimes`].
    ///
    /// Convenience over the individual `time_engine`/`time_exchange`/
    /// `time_received` accessors for forwarding the whole set in one (`Copy`) move
    /// — e.g. reconstructing a book that shares this revision's times.
    pub fn times(&self) -> OrderBookTimes {
        self.times
    }

    /// Generate a sorted [`OrderBook`] snapshot with a maximum depth.
    ///
    /// The returned snapshot carries the same [`OrderBookTimes`] as the source
    /// book (timestamps are not reset).
    pub fn snapshot(&self, depth: usize) -> Self {
        Self {
            sequence: self.sequence,
            times: self.times,
            bids: OrderBookSide::bids(self.bids.levels.iter().take(depth).copied()),
            asks: OrderBookSide::asks(self.asks.levels.iter().take(depth).copied()),
        }
    }

    /// Update the local [`OrderBook`] from a new [`OrderBookEvent`].
    ///
    /// `Update` advances the book's [`OrderBookTimes`] wholesale (alongside
    /// upserting the changed levels); `Snapshot` replaces the book in its
    /// entirety, including its times.
    pub fn update(&mut self, event: &OrderBookEvent) {
        match event {
            OrderBookEvent::Snapshot(snapshot) => {
                *self = snapshot.clone();
            }
            OrderBookEvent::Update(update) => {
                self.sequence = update.sequence;
                self.times = update.times;
                self.upsert_bids(&update.bids);
                self.upsert_asks(&update.asks);
            }
        }
    }

    /// Update the local [`OrderBook`] by upserting the levels in an [`OrderBookSide`].
    fn upsert_bids(&mut self, update: &OrderBookSide<Bids>) {
        self.bids.upsert(&update.levels)
    }

    /// Update the local [`OrderBook`] by upserting the levels in an [`OrderBookSide`].
    fn upsert_asks(&mut self, update: &OrderBookSide<Asks>) {
        self.asks.upsert(&update.levels)
    }

    /// Return a reference to this [`OrderBook`]s bids.
    pub fn bids(&self) -> &OrderBookSide<Bids> {
        &self.bids
    }

    /// Return a reference to this [`OrderBook`]s asks.
    pub fn asks(&self) -> &OrderBookSide<Asks> {
        &self.asks
    }

    /// Calculate the mid-price by taking the average of the best bid and ask prices.
    ///
    /// See Docs: <https://www.quantstart.com/articles/high-frequency-trading-ii-limit-order-book>
    pub fn mid_price(&self) -> Option<Decimal> {
        match (self.bids.best(), self.asks.best()) {
            (Some(best_bid), Some(best_ask)) => Some(mid_price(best_bid.price, best_ask.price)),
            (Some(best_bid), None) => Some(best_bid.price),
            (None, Some(best_ask)) => Some(best_ask.price),
            (None, None) => None,
        }
    }

    /// Calculate the volume weighted mid-price (micro-price), weighing the best bid and ask prices
    /// with their associated amount.
    ///
    /// See Docs: <https://www.quantstart.com/articles/high-frequency-trading-ii-limit-order-book>
    pub fn volume_weighed_mid_price(&self) -> Option<Decimal> {
        match (self.bids.best(), self.asks.best()) {
            (Some(best_bid), Some(best_ask)) => {
                Some(volume_weighted_mid_price(*best_bid, *best_ask))
            }
            (Some(best_bid), None) => Some(best_bid.price),
            (None, Some(best_ask)) => Some(best_ask.price),
            (None, None) => None,
        }
    }
}

/// Normalised Barter [`Level`]s for one `Side` of the [`OrderBook`].
#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
pub struct OrderBookSide<Side> {
    #[serde(skip_serializing)]
    pub side: Side,
    levels: Vec<Level>,
}

/// Unit type to tag an [`OrderBookSide`] as the bid Side (ie/ buyers) of an [`OrderBook`].
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Display)]
pub struct Bids;

/// Unit type to tag an [`OrderBookSide`] as the ask Side (ie/ sellers) of an [`OrderBook`].
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Display)]
pub struct Asks;

impl OrderBookSide<Bids> {
    /// Construct a new [`OrderBookSide<Bids>`] from the provided [`Level`]s.
    pub fn bids<Iter, L>(levels: Iter) -> Self
    where
        Iter: IntoIterator<Item = L>,
        L: Into<Level>,
    {
        let mut levels = levels.into_iter().map(L::into).collect::<Vec<_>>();
        levels.sort_unstable_by(|a, b| a.price.cmp(&b.price).reverse());

        Self { side: Bids, levels }
    }

    /// Upsert bid [`Level`]s into this [`OrderBookSide<Bids>`].
    pub fn upsert<L>(&mut self, levels: &[L])
    where
        L: Into<Level> + Copy,
    {
        levels.iter().for_each(|upsert| {
            let upsert: Level = (*upsert).into();
            self.upsert_single(upsert, |existing| {
                existing.price.cmp(&upsert.price).reverse()
            })
        })
    }
}

impl OrderBookSide<Asks> {
    /// Construct a new [`OrderBookSide<Asks>`] from the provided [`Level`]s.
    pub fn asks<Iter, L>(levels: Iter) -> Self
    where
        Iter: IntoIterator<Item = L>,
        L: Into<Level>,
    {
        let mut levels = levels.into_iter().map(L::into).collect::<Vec<_>>();
        levels.sort_unstable_by_key(|a| a.price);

        Self { side: Asks, levels }
    }

    /// Upsert ask [`Level`]s into this [`OrderBookSide<Asks>`].
    pub fn upsert<L>(&mut self, levels: &[L])
    where
        L: Into<Level> + Copy,
    {
        levels.iter().for_each(|upsert| {
            let upsert = (*upsert).into();
            self.upsert_single(upsert, |existing| existing.price.cmp(&upsert.price))
        })
    }
}

impl<Side> OrderBookSide<Side>
where
    Side: std::fmt::Display + std::fmt::Debug,
{
    /// Get best [`Level`] on the [`OrderBookSide`].
    pub fn best(&self) -> Option<&Level> {
        self.levels.first()
    }

    /// Return a reference to the [`OrderBookSide`] levels.
    pub fn levels(&self) -> &[Level] {
        &self.levels
    }

    /// Upsert a single [`Level`] into this [`OrderBookSide`].
    ///
    /// ### Upsert Scenarios
    /// #### 1 Level Already Exists
    /// 1a) New value is 0, remove the level
    /// 1b) New value is > 0, replace the level
    ///
    /// #### 2 Level Does Not Exist
    /// 2a) New value is 0, log warn and continue
    /// 2b) New value is > 0, insert new level
    pub fn upsert_single<FnOrd>(&mut self, new_level: Level, fn_ord: FnOrd)
    where
        FnOrd: Fn(&Level) -> Ordering,
    {
        match (self.levels.binary_search_by(fn_ord), new_level.amount) {
            (Ok(index), new_amount) => {
                if new_amount.is_zero() {
                    // Scenario 1a: Level exists & new value is 0 => remove level
                    let _removed = self.levels.remove(index);
                } else {
                    // Scenario 1b: Level exists & new value is > 0 => replace level
                    self.levels[index].amount = new_amount;
                }
            }
            (Err(index), new_amount) => {
                if new_amount.is_zero() {
                    // Scenario 2a: Level does not exist & new value is 0 => log & continue
                    debug!(
                        ?new_level,
                        side = %self.side,
                        "received upsert Level with zero amount (to remove) that was not found"
                    );
                } else {
                    // Scenario 2b: Level does not exist & new value > 0 => insert new level
                    self.levels.insert(index, new_level);
                }
            }
        }
    }
}

impl Default for OrderBookSide<Bids> {
    fn default() -> Self {
        Self {
            side: Bids,
            levels: vec![],
        }
    }
}

impl Default for OrderBookSide<Asks> {
    fn default() -> Self {
        Self {
            side: Asks,
            levels: vec![],
        }
    }
}

/// Normalised Barter OrderBook [`Level`].
#[derive(Debug, Copy, Clone, PartialEq, Ord, PartialOrd, Hash, Default, Deserialize, Serialize)]
pub struct Level {
    pub price: Decimal,
    pub amount: Decimal,
}

impl<T> From<(T, T)> for Level
where
    T: Into<Decimal>,
{
    fn from((price, amount): (T, T)) -> Self {
        Self::new(price, amount)
    }
}

impl Eq for Level {}

impl Level {
    pub fn new<T>(price: T, amount: T) -> Self
    where
        T: Into<Decimal>,
    {
        Self {
            price: price.into(),
            amount: amount.into(),
        }
    }
}

/// Calculate the mid-price by taking the average of the best bid and ask prices.
///
/// See Docs: <https://www.quantstart.com/articles/high-frequency-trading-ii-limit-order-book>
pub fn mid_price(best_bid_price: Decimal, best_ask_price: Decimal) -> Decimal {
    (best_bid_price + best_ask_price) / Decimal::TWO
}

/// Calculate the volume weighted mid-price (micro-price), weighing the best bid and ask prices
/// with their associated amount.
///
/// See Docs: <https://www.quantstart.com/articles/high-frequency-trading-ii-limit-order-book>
pub fn volume_weighted_mid_price(best_bid: Level, best_ask: Level) -> Decimal {
    ((best_bid.price * best_ask.amount) + (best_ask.price * best_bid.amount))
        / (best_bid.amount + best_ask.amount)
}

#[cfg(test)]
#[allow(clippy::unwrap_used)] // Test code: panics on bad input are acceptable
mod tests {
    use super::*;

    mod order_book_l1 {
        use super::*;
        use crate::subscription::book::OrderBookL1;
        use rust_decimal_macros::dec;

        #[test]
        fn test_mid_price() {
            struct TestCase {
                input: OrderBookL1,
                expected: Option<Decimal>,
            }

            let tests = vec![
                TestCase {
                    // TC0
                    input: OrderBookL1 {
                        last_update_time: Default::default(),
                        best_bid: Some(Level::new(100, 999999)),
                        best_ask: Some(Level::new(200, 1)),
                    },
                    expected: Some(dec!(150.0)),
                },
                TestCase {
                    // TC1
                    input: OrderBookL1 {
                        last_update_time: Default::default(),
                        best_bid: Some(Level::new(50, 1)),
                        best_ask: Some(Level::new(250, 999999)),
                    },
                    expected: Some(dec!(150.0)),
                },
                TestCase {
                    // TC2
                    input: OrderBookL1 {
                        last_update_time: Default::default(),
                        best_bid: Some(Level::new(10, 999999)),
                        best_ask: Some(Level::new(250, 999999)),
                    },
                    expected: Some(dec!(130.0)),
                },
                TestCase {
                    // TC3
                    input: OrderBookL1 {
                        last_update_time: Default::default(),
                        best_bid: Some(Level::new(10, 999999)),
                        best_ask: None,
                    },
                    expected: None,
                },
                TestCase {
                    // TC4
                    input: OrderBookL1 {
                        last_update_time: Default::default(),
                        best_bid: None,
                        best_ask: Some(Level::new(250, 999999)),
                    },
                    expected: None,
                },
            ];

            for (index, test) in tests.into_iter().enumerate() {
                assert_eq!(test.input.mid_price(), test.expected, "TC{index} failed")
            }
        }

        #[test]
        fn test_volume_weighted_mid_price() {
            struct TestCase {
                input: OrderBookL1,
                expected: Option<Decimal>,
            }

            let tests = vec![
                TestCase {
                    // TC0: volume the same so should be equal to non-weighted mid price
                    input: OrderBookL1 {
                        last_update_time: Default::default(),
                        best_bid: Some(Level::new(100, 100)),
                        best_ask: Some(Level::new(200, 100)),
                    },
                    expected: Some(dec!(150.0)),
                },
                TestCase {
                    // TC1: volume affects mid-price
                    input: OrderBookL1 {
                        last_update_time: Default::default(),
                        best_bid: Some(Level::new(100, 600)),
                        best_ask: Some(Level::new(200, 1000)),
                    },
                    expected: Some(dec!(137.5)),
                },
                TestCase {
                    // TC2: volume the same and price the same
                    input: OrderBookL1 {
                        last_update_time: Default::default(),
                        best_bid: Some(Level::new(1000, 999999)),
                        best_ask: Some(Level::new(1000, 999999)),
                    },
                    expected: Some(dec!(1000.0)),
                },
                TestCase {
                    // TC3: best ask is None
                    input: OrderBookL1 {
                        last_update_time: Default::default(),
                        best_bid: Some(Level::new(1000, 999999)),
                        best_ask: None,
                    },
                    expected: None,
                },
                TestCase {
                    // TC4: best bid is None
                    input: OrderBookL1 {
                        last_update_time: Default::default(),
                        best_bid: None,
                        best_ask: Some(Level::new(1000, 999999)),
                    },
                    expected: None,
                },
            ];

            for (index, test) in tests.into_iter().enumerate() {
                assert_eq!(
                    test.input.volume_weighed_mid_price(),
                    test.expected,
                    "TC{index} failed"
                )
            }
        }
    }

    mod order_book {
        use super::*;
        use rust_decimal_macros::dec;

        fn times(received_ms: i64) -> OrderBookTimes {
            OrderBookTimes {
                time_engine: Some(DateTime::from_timestamp_millis(1).unwrap()),
                time_exchange: Some(DateTime::from_timestamp_millis(2).unwrap()),
                time_received: DateTime::from_timestamp_millis(received_ms).unwrap(),
            }
        }

        #[test]
        fn test_update_replaces_times_wholesale() {
            let mut book = OrderBook::new(1, times(100), vec![Level::new(50, 1)], vec![]);

            let newer = OrderBookTimes {
                time_engine: None,
                time_exchange: Some(DateTime::from_timestamp_millis(999).unwrap()),
                time_received: DateTime::from_timestamp_millis(1000).unwrap(),
            };
            let update = OrderBook::new(2, newer, vec![Level::new(50, 1)], vec![]);
            book.update(&OrderBookEvent::Update(update));

            assert_eq!(book.time_engine(), newer.time_engine);
            assert_eq!(book.time_exchange(), newer.time_exchange);
            assert_eq!(book.time_received(), newer.time_received);
        }

        #[test]
        fn test_update_snapshot_propagates_times_wholesale() {
            // The `Snapshot` arm replaces the live book via `*self = snapshot.clone()`,
            // so it must carry the snapshot's `times` (not retain the old ones).
            let mut book = OrderBook::new(1, times(100), vec![Level::new(50, 1)], vec![]);

            let newer = OrderBookTimes {
                time_engine: None,
                time_exchange: Some(DateTime::from_timestamp_millis(999).unwrap()),
                time_received: DateTime::from_timestamp_millis(1000).unwrap(),
            };
            let snapshot = OrderBook::new(2, newer, vec![Level::new(60, 1)], vec![]);
            book.update(&OrderBookEvent::Snapshot(snapshot));

            assert_eq!(book.time_engine(), newer.time_engine);
            assert_eq!(book.time_exchange(), newer.time_exchange);
            assert_eq!(book.time_received(), newer.time_received);
        }

        #[test]
        fn test_snapshot_copies_times() {
            let book = OrderBook::new(1, times(100), vec![Level::new(50, 1)], vec![]);
            let snap = book.snapshot(10);
            assert_eq!(snap.time_engine(), book.time_engine());
            assert_eq!(snap.time_exchange(), book.time_exchange());
            assert_eq!(snap.time_received(), book.time_received());
        }

        #[test]
        fn test_equality_reflects_timestamps() {
            // Two content-identical books with different `time_received` are unequal.
            let a = OrderBook::new(1, times(100), vec![Level::new(50, 1)], vec![]);
            let b = OrderBook::new(1, times(200), vec![Level::new(50, 1)], vec![]);
            assert_ne!(a, b);
        }

        #[test]
        fn test_mid_price() {
            struct TestCase {
                input: OrderBook,
                expected: Option<Decimal>,
            }

            let tests = vec![
                TestCase {
                    // TC0: no levels so 0.0 mid-price
                    input: OrderBook::new::<Vec<_>, Vec<_>, Level>(
                        0,
                        Default::default(),
                        vec![],
                        vec![],
                    ),
                    expected: None,
                },
                TestCase {
                    // TC1: no asks in the books so take best bid price
                    input: OrderBook::new(
                        0,
                        Default::default(),
                        vec![
                            Level::new(dec!(100.0), dec!(100.0)),
                            Level::new(dec!(50.0), dec!(100.0)),
                        ],
                        vec![],
                    ),
                    expected: Some(dec!(100.0)),
                },
                TestCase {
                    // TC2: no bids in the books so take ask price
                    input: OrderBook::new(
                        0,
                        Default::default(),
                        vec![],
                        vec![
                            Level::new(dec!(50.0), dec!(100.0)),
                            Level::new(dec!(100.0), dec!(100.0)),
                        ],
                    ),
                    expected: Some(dec!(50.0)),
                },
                TestCase {
                    // TC3: best bid and ask amount is the same, so regular mid-price
                    input: OrderBook::new(
                        0,
                        Default::default(),
                        vec![
                            Level::new(dec!(100.0), dec!(100.0)),
                            Level::new(dec!(50.0), dec!(100.0)),
                        ],
                        vec![
                            Level::new(dec!(200.0), dec!(100.0)),
                            Level::new(dec!(300.0), dec!(100.0)),
                        ],
                    ),
                    expected: Some(dec!(150.0)),
                },
            ];

            for (index, test) in tests.into_iter().enumerate() {
                assert_eq!(test.input.mid_price(), test.expected, "TC{index} failed")
            }
        }

        #[test]
        fn test_volume_weighted_mid_price() {
            struct TestCase {
                input: OrderBook,
                expected: Option<Decimal>,
            }

            let tests = vec![
                TestCase {
                    // TC0: no levels so 0.0 mid-price
                    input: OrderBook::new::<Vec<_>, Vec<_>, Level>(
                        0,
                        Default::default(),
                        vec![],
                        vec![],
                    ),
                    expected: None,
                },
                TestCase {
                    // TC1: no asks in the books so take best bid price
                    input: OrderBook::new(
                        0,
                        Default::default(),
                        vec![
                            Level::new(dec!(100.0), dec!(100.0)),
                            Level::new(dec!(50.0), dec!(100.0)),
                        ],
                        vec![],
                    ),
                    expected: Some(dec!(100.0)),
                },
                TestCase {
                    // TC2: no bids in the books so take ask price
                    input: OrderBook::new(
                        0,
                        Default::default(),
                        vec![],
                        vec![
                            Level::new(dec!(50.0), dec!(100.0)),
                            Level::new(dec!(100.0), dec!(100.0)),
                        ],
                    ),
                    expected: Some(dec!(50.0)),
                },
                TestCase {
                    // TC3: best bid and ask amount is the same, so regular mid-price
                    input: OrderBook::new(
                        0,
                        Default::default(),
                        vec![
                            Level::new(dec!(100.0), dec!(100.0)),
                            Level::new(dec!(50.0), dec!(100.0)),
                        ],
                        vec![
                            Level::new(dec!(200.0), dec!(100.0)),
                            Level::new(dec!(300.0), dec!(100.0)),
                        ],
                    ),
                    expected: Some(dec!(150.0)),
                },
                TestCase {
                    // TC4: valid volume weighted mid-price
                    input: OrderBook::new(
                        0,
                        Default::default(),
                        vec![
                            Level::new(dec!(100.0), dec!(3000.0)),
                            Level::new(dec!(50.0), dec!(100.0)),
                        ],
                        vec![
                            Level::new(dec!(200.0), dec!(1000.0)),
                            Level::new(dec!(300.0), dec!(100.0)),
                        ],
                    ),
                    expected: Some(dec!(175.0)),
                },
            ];

            for (index, test) in tests.into_iter().enumerate() {
                assert_eq!(
                    test.input.volume_weighed_mid_price(),
                    test.expected,
                    "TC{index} failed"
                )
            }
        }
    }

    mod order_book_side {
        use super::*;
        use rust_decimal_macros::dec;

        #[test]
        fn test_upsert_single() {
            struct TestCase {
                book_side: OrderBookSide<Bids>,
                new_level: Level,
                expected: OrderBookSide<Bids>,
            }

            let tests = vec![
                TestCase {
                    // TC0: Level exists & new value is 0 => remove Level
                    book_side: OrderBookSide::bids(vec![
                        Level::new(dec!(80), dec!(1)),
                        Level::new(dec!(90), dec!(1)),
                        Level::new(dec!(100), dec!(1)),
                    ]),
                    new_level: Level::new(dec!(100), dec!(0)),
                    expected: OrderBookSide::bids(vec![
                        Level::new(dec!(80), dec!(1)),
                        Level::new(dec!(90), dec!(1)),
                    ]),
                },
                TestCase {
                    // TC1: Level exists & new value is > 0 => replace Level
                    book_side: OrderBookSide::bids(vec![
                        Level::new(dec!(80), dec!(1)),
                        Level::new(dec!(90), dec!(1)),
                        Level::new(dec!(100), dec!(1)),
                    ]),
                    new_level: Level::new(dec!(100), dec!(10)),
                    expected: OrderBookSide::bids(vec![
                        Level::new(dec!(80), dec!(1)),
                        Level::new(dec!(90), dec!(1)),
                        Level::new(dec!(100), dec!(10)),
                    ]),
                },
                TestCase {
                    // TC2: Level does not exist & new value > 0 => insert new Level
                    book_side: OrderBookSide::bids(vec![
                        Level::new(dec!(80), dec!(1)),
                        Level::new(dec!(90), dec!(1)),
                        Level::new(dec!(100), dec!(1)),
                    ]),
                    new_level: Level::new(dec!(110), dec!(1)),
                    expected: OrderBookSide::bids(vec![
                        Level::new(dec!(80), dec!(1)),
                        Level::new(dec!(90), dec!(1)),
                        Level::new(dec!(100), dec!(1)),
                        Level::new(dec!(110), dec!(1)),
                    ]),
                },
                TestCase {
                    // TC3: Level does not exist & new value is 0 => no change
                    book_side: OrderBookSide::bids(vec![
                        Level::new(dec!(80), dec!(1)),
                        Level::new(dec!(90), dec!(1)),
                        Level::new(dec!(100), dec!(1)),
                    ]),
                    new_level: Level::new(dec!(110), dec!(0)),
                    expected: OrderBookSide::bids(vec![
                        Level::new(dec!(80), dec!(1)),
                        Level::new(dec!(90), dec!(1)),
                        Level::new(dec!(100), dec!(1)),
                    ]),
                },
            ];

            for (index, mut test) in tests.into_iter().enumerate() {
                test.book_side.upsert_single(test.new_level, |existing| {
                    existing.price.cmp(&test.new_level.price).reverse()
                });
                assert_eq!(test.book_side, test.expected, "TC{} failed", index);
            }
        }
    }
}