depthbook 0.7.0

In-process L2 order book store with fixed-capacity sorted sides, scale-9 integer prices, and sequence-gap detection
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
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
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
//! The book itself: levels, sides, and a full book.

use crate::decimal::Scale9;
use crate::intern::InternedString;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// Maximum number of levels held on one side of a book.
pub const MAX_LEVELS: usize = 200;

/// How many levels from the best are scanned linearly before falling back to binary search.
const SCAN_LEVELS: usize = 16;

/// A single price level: a price and the quantity resting at it.
///
/// Both fields are [`Scale9`] fixed-point values, so there is no floating-point error and
/// an unscaled number cannot be passed by mistake.
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Level {
    /// Price of this level.
    pub price: Scale9,
    /// Quantity resting at this price. Zero means the level should be removed.
    pub qty: Scale9,
}

impl Level {
    /// Create a level.
    ///
    /// # Examples
    /// ```
    /// use depthbook::{f64_to_scale9, Level};
    ///
    /// let level = Level::new(f64_to_scale9(50_000.5), f64_to_scale9(1.5));
    /// assert_eq!(level.price, f64_to_scale9(50_000.5));
    /// assert_eq!(level.qty, f64_to_scale9(1.5));
    /// ```
    #[inline]
    pub const fn new(price: Scale9, qty: Scale9) -> Self {
        Self { price, qty }
    }

    /// Whether this level has zero quantity, meaning it should be removed.
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.qty.is_zero()
    }
}

/// One side of a book: a fixed-capacity array of levels kept in price order.
///
/// Levels are stored worst-first, so the best level is at the end and an update near the
/// top of the book, where nearly all updates land, moves almost nothing. [`Side::levels`]
/// still yields best-first. The array is pre-allocated, so applying an update never
/// allocates.
///
/// Capacity is [`MAX_LEVELS`]. Inserting into a full side drops the worst level.
#[repr(C)]
#[derive(Debug, Clone)]
pub struct Side {
    levels: [Level; MAX_LEVELS],
    count: usize,
}

/// What [`Side::insert_outcome`] did to the side.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Insertion {
    /// A new price level was added.
    Inserted,
    /// An existing price level had its quantity replaced.
    Updated,
    /// An existing price level was removed, the incoming quantity being zero.
    Removed,
    /// Nothing changed: a zero quantity at a price the side does not hold.
    Ignored,
    /// The side was full, so a level was discarded to keep the book sorted: either the
    /// worst resting level, evicted to make room, or the incoming level itself when it
    /// was worse than everything present.
    ///
    /// The book is no longer a faithful copy of the venue's below the top
    /// [`MAX_LEVELS`] levels. Counted in `Stats::levels_dropped`.
    Dropped,
}

impl Side {
    /// Create an empty side.
    ///
    /// # Examples
    /// ```
    /// use depthbook::Side;
    ///
    /// let side = Side::new();
    /// assert_eq!(side.count(), 0);
    /// assert!(side.is_empty());
    /// ```
    pub const fn new() -> Self {
        Self {
            levels: [Level {
                price: Scale9::ZERO,
                qty: Scale9::ZERO,
            }; MAX_LEVELS],
            count: 0,
        }
    }

    /// Number of levels currently held.
    #[inline]
    pub const fn count(&self) -> usize {
        self.count
    }

    /// Whether this side holds no levels.
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.count == 0
    }

    /// The levels currently held, best first.
    ///
    /// # Examples
    /// ```
    /// use depthbook::{f64_to_scale9, Level, Side};
    ///
    /// let mut side = Side::new();
    /// side.insert(Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)), false);
    /// assert_eq!(side.levels().len(), 1);
    /// ```
    #[inline]
    pub fn levels(&self) -> impl DoubleEndedIterator<Item = &Level> + ExactSizeIterator {
        self.levels[..self.count].iter().rev()
    }

    /// Insert a level, or update the quantity if that price is already present.
    ///
    /// A level with zero quantity removes that price. `is_bid` selects the sort order:
    /// descending for bids, ascending for asks.
    ///
    /// Returns `true` if a new level was inserted, `false` if an existing one was updated,
    /// removed, or the side was full and the level was dropped. Those last cases are not
    /// distinguishable from the return value; use [`Side::insert_outcome`] when the
    /// difference matters.
    ///
    /// # Examples
    /// ```
    /// use depthbook::{f64_to_scale9, Level, Side};
    ///
    /// let mut bids = Side::new();
    /// let level = Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0));
    /// assert!(bids.insert(level, true));
    /// assert_eq!(bids.count(), 1);
    ///
    /// let updated = Level::new(f64_to_scale9(50_000.0), f64_to_scale9(2.0));
    /// assert!(!bids.insert(updated, true));
    /// assert_eq!(bids.count(), 1);
    /// assert_eq!(bids.best().unwrap().qty, f64_to_scale9(2.0));
    /// ```
    pub fn insert(&mut self, level: Level, is_bid: bool) -> bool {
        self.insert_outcome(level, is_bid) == Insertion::Inserted
    }

    /// Insert a level and report exactly what happened.
    ///
    /// Same behaviour as [`Side::insert`], but distinguishes an update from a removal and
    /// from a level lost to the side being full, which the boolean cannot.
    ///
    /// # Examples
    /// ```
    /// use depthbook::{f64_to_scale9, Insertion, Level, Side, MAX_LEVELS};
    ///
    /// let mut bids = Side::new();
    /// let level = Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0));
    /// assert_eq!(bids.insert_outcome(level, true), Insertion::Inserted);
    ///
    /// let deeper = Level::new(f64_to_scale9(50_000.0), f64_to_scale9(2.0));
    /// assert_eq!(bids.insert_outcome(deeper, true), Insertion::Updated);
    ///
    /// // Fill the side, then add one more: something has to go.
    /// for i in 1..MAX_LEVELS {
    ///     bids.insert(Level::new(f64_to_scale9(50_000.0 - i as f64), f64_to_scale9(1.0)), true);
    /// }
    /// assert_eq!(bids.count(), MAX_LEVELS);
    /// let extra = Level::new(f64_to_scale9(50_001.0), f64_to_scale9(1.0));
    /// assert_eq!(bids.insert_outcome(extra, true), Insertion::Dropped);
    /// ```
    pub fn insert_outcome(&mut self, level: Level, is_bid: bool) -> Insertion {
        let insert_pos = self.find_insert_position(level.price, is_bid);

        if insert_pos < self.count && self.levels[insert_pos].price == level.price {
            if level.is_empty() {
                self.remove_at(insert_pos);
                return Insertion::Removed;
            }
            self.levels[insert_pos] = level;
            return Insertion::Updated;
        }

        if level.is_empty() {
            return Insertion::Ignored;
        }

        if self.count == MAX_LEVELS {
            // The worst level sits at index 0. Drop it to make room, unless the incoming
            // level is itself worse than everything here, in which case it is the one lost.
            if insert_pos == 0 {
                return Insertion::Dropped;
            }
            self.levels.copy_within(1..insert_pos, 0);
            self.levels[insert_pos - 1] = level;
            return Insertion::Dropped;
        }

        self.levels
            .copy_within(insert_pos..self.count, insert_pos + 1);
        self.levels[insert_pos] = level;
        self.count += 1;

        Insertion::Inserted
    }

    /// Remove the level at `price`, returning whether it was found.
    ///
    /// # Examples
    /// ```
    /// use depthbook::{f64_to_scale9, Level, Side};
    ///
    /// let mut bids = Side::new();
    /// bids.insert(Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)), true);
    ///
    /// assert!(bids.remove(f64_to_scale9(50_000.0), true));
    /// assert_eq!(bids.count(), 0);
    /// assert!(!bids.remove(f64_to_scale9(50_000.0), true));
    /// ```
    pub fn remove(&mut self, price: Scale9, is_bid: bool) -> bool {
        let pos = self.find_insert_position(price, is_bid);

        if pos < self.count && self.levels[pos].price == price {
            self.remove_at(pos);
            true
        } else {
            false
        }
    }

    /// Set the quantity at `price`, inserting or removing the level as needed.
    ///
    /// # Examples
    /// ```
    /// use depthbook::{f64_to_scale9, Side};
    ///
    /// let mut bids = Side::new();
    /// bids.update(f64_to_scale9(50_000.0), f64_to_scale9(1.0), true);
    /// assert_eq!(bids.count(), 1);
    ///
    /// bids.update(f64_to_scale9(50_000.0), f64_to_scale9(2.0), true);
    /// assert_eq!(bids.best().unwrap().qty, f64_to_scale9(2.0));
    ///
    /// bids.update(f64_to_scale9(50_000.0), f64_to_scale9(0.0), true);
    /// assert_eq!(bids.count(), 0);
    /// ```
    pub fn update(&mut self, price: Scale9, qty: Scale9, is_bid: bool) {
        self.insert(Level::new(price, qty), is_bid);
    }

    /// The best level: highest price for bids, lowest for asks.
    ///
    /// # Examples
    /// ```
    /// use depthbook::{f64_to_scale9, Level, Side};
    ///
    /// let mut bids = Side::new();
    /// assert!(bids.best().is_none());
    ///
    /// bids.insert(Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)), true);
    /// bids.insert(Level::new(f64_to_scale9(49_999.0), f64_to_scale9(2.0)), true);
    ///
    /// assert_eq!(bids.best().unwrap().price, f64_to_scale9(50_000.0));
    /// ```
    #[inline]
    pub fn best(&self) -> Option<Level> {
        if self.count > 0 {
            Some(self.levels[self.count - 1])
        } else {
            None
        }
    }

    /// Total quantity resting within `bps` basis points of the best price.
    ///
    /// One basis point is 0.01%. Returns zero if the side is empty.
    ///
    /// # Examples
    /// ```
    /// use depthbook::{f64_to_scale9, Level, Side};
    ///
    /// let mut bids = Side::new();
    /// bids.insert(Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)), true);
    /// bids.insert(Level::new(f64_to_scale9(49_000.0), f64_to_scale9(2.0)), true);
    ///
    /// assert_eq!(bids.depth_within_bps(2500, true), f64_to_scale9(3.0));
    /// assert_eq!(bids.depth_within_bps(50, true), f64_to_scale9(1.0));
    /// ```
    pub fn depth_within_bps(&self, bps: u32, is_bid: bool) -> Scale9 {
        if self.count == 0 {
            return Scale9::ZERO;
        }

        let best = self.levels[self.count - 1].price.raw();
        if best == 0 {
            return Scale9::ZERO;
        }

        let margin = i64::try_from(i128::from(best) * i128::from(bps) / 10_000).unwrap_or(i64::MAX);
        let threshold = if is_bid {
            best.saturating_sub(margin)
        } else {
            best.saturating_add(margin)
        };

        let mut total = Scale9::ZERO;
        for level in self.levels() {
            let within = if is_bid {
                level.price.raw() >= threshold
            } else {
                level.price.raw() <= threshold
            };

            if !within {
                // Levels are sorted, so everything further out is also outside the range.
                break;
            }
            total = total.saturating_add(level.qty);
        }

        total
    }

    /// Remove every level.
    pub fn clear(&mut self) {
        self.count = 0;
    }

    /// Keep at most `n` levels, dropping the worst ones.
    ///
    /// This keeps the top of the book. Truncating to more levels than are present does
    /// nothing.
    ///
    /// # Examples
    /// ```
    /// use depthbook::{f64_to_scale9, Level, Side};
    ///
    /// let mut bids = Side::new();
    /// bids.insert(Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)), true);
    /// bids.insert(Level::new(f64_to_scale9(49_999.0), f64_to_scale9(2.0)), true);
    ///
    /// bids.truncate(1);
    /// assert_eq!(bids.count(), 1);
    /// assert_eq!(bids.best().unwrap().price, f64_to_scale9(50_000.0));
    /// ```
    pub fn truncate(&mut self, n: usize) {
        if n < self.count {
            self.levels.copy_within(self.count - n..self.count, 0);
            self.count = n;
        }
    }

    /// Where `price` belongs in storage order, worst at 0 and best at `count - 1`.
    ///
    /// The best [`SCAN_LEVELS`] are scanned linearly, since that is where nearly every
    /// update lands and a short sequential scan beats a binary search there; anything
    /// deeper falls back to a binary search. See `benches/side_layout.rs`.
    #[inline]
    fn find_insert_position(&self, price: Scale9, is_bid: bool) -> usize {
        // Two monomorphised copies so the side comparison is not a branch inside the loop.
        if is_bid {
            self.position_by(|p| p < price)
        } else {
            self.position_by(|p| p > price)
        }
    }

    /// `worse` reports whether a stored price is further from the top of the book than
    /// the one being placed.
    #[inline]
    fn position_by(&self, worse: impl Fn(Scale9) -> bool) -> usize {
        let active = &self.levels[..self.count];
        let scan_from = self.count.saturating_sub(SCAN_LEVELS);
        match active[scan_from..].iter().rposition(|l| worse(l.price)) {
            Some(i) => scan_from + i + 1,
            None if scan_from == 0 => 0,
            None => active[..scan_from].partition_point(|l| worse(l.price)),
        }
    }

    #[inline]
    fn remove_at(&mut self, pos: usize) {
        if pos < self.count {
            self.levels.copy_within(pos + 1..self.count, pos);
            self.count -= 1;
        }
    }
}

impl Default for Side {
    fn default() -> Self {
        Self::new()
    }
}

// Serialize only the active levels; the rest of the array is padding.
impl Serialize for Side {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        use serde::ser::SerializeStruct;
        let mut state = serializer.serialize_struct("Side", 2)?;
        struct BestFirst<'a>(&'a Side);
        impl Serialize for BestFirst<'_> {
            fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
                s.collect_seq(self.0.levels())
            }
        }
        state.serialize_field("levels", &BestFirst(self))?;
        state.serialize_field("count", &self.count)?;
        state.end()
    }
}

impl<'de> Deserialize<'de> for Side {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::{self, MapAccess, Visitor};
        use std::fmt;

        #[derive(Deserialize)]
        #[serde(field_identifier, rename_all = "lowercase")]
        enum Field {
            Levels,
            Count,
        }

        struct SideVisitor;

        impl<'de> Visitor<'de> for SideVisitor {
            type Value = Side;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("struct Side")
            }

            fn visit_map<V>(self, mut map: V) -> Result<Side, V::Error>
            where
                V: MapAccess<'de>,
            {
                let mut levels: Option<Vec<Level>> = None;
                let mut count: Option<usize> = None;

                while let Some(key) = map.next_key()? {
                    match key {
                        Field::Levels => {
                            if levels.is_some() {
                                return Err(de::Error::duplicate_field("levels"));
                            }
                            levels = Some(map.next_value()?);
                        }
                        Field::Count => {
                            if count.is_some() {
                                return Err(de::Error::duplicate_field("count"));
                            }
                            count = Some(map.next_value()?);
                        }
                    }
                }

                let levels_vec = levels.ok_or_else(|| de::Error::missing_field("levels"))?;
                let count = count.ok_or_else(|| de::Error::missing_field("count"))?;

                if count != levels_vec.len() {
                    return Err(de::Error::custom("count does not match levels"));
                }
                if count > MAX_LEVELS {
                    return Err(de::Error::custom("more than MAX_LEVELS levels"));
                }
                // The book relies on binary search, so a side must be strictly monotonic.
                // Either direction is accepted since `Side` does not know if it is a bid.
                let strictly = |ok: fn(&Level, &Level) -> bool| {
                    levels_vec.windows(2).all(|w| ok(&w[0], &w[1]))
                };
                if !strictly(|a, b| a.price > b.price) && !strictly(|a, b| a.price < b.price) {
                    return Err(de::Error::custom("levels are not strictly sorted by price"));
                }
                if levels_vec.iter().any(|l| l.price.raw() < 0) {
                    return Err(de::Error::custom("level price must not be negative"));
                }
                if levels_vec.iter().any(|l| l.qty.raw() <= 0) {
                    return Err(de::Error::custom("level quantity must be positive"));
                }

                let mut side = Side::new();
                for (slot, level) in side.levels[..count].iter_mut().zip(levels_vec.iter().rev()) {
                    *slot = *level;
                }
                side.count = count;

                Ok(side)
            }
        }

        deserializer.deserialize_struct("Side", &["levels", "count"], SideVisitor)
    }
}

/// A complete order book for one instrument at one venue.
///
/// Deserialisation checks that bids are strictly descending and asks strictly ascending.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(try_from = "BookRepr")]
pub struct Book {
    /// Venue identifier, for example `binance`.
    pub venue: InternedString,
    /// Instrument identifier, for example `BTC-USDT`.
    pub inst: InternedString,
    /// Exchange timestamp in nanoseconds since the Unix epoch.
    pub ts: u64,
    /// Sequence number of the last update applied.
    pub seq: u64,
    /// Bid side, highest price first.
    pub bids: Side,
    /// Ask side, lowest price first.
    pub asks: Side,
    /// Whether a delta was rejected for a sequence gap since the last snapshot.
    ///
    /// A gapped book is the last good state, which is behind the venue by an unknown
    /// amount. Cleared by the next snapshot.
    #[serde(default)]
    pub gapped: bool,
}

/// Wire shape of [`Book`]; converting into a `Book` validates side orientation.
#[derive(Deserialize)]
struct BookRepr {
    venue: InternedString,
    inst: InternedString,
    ts: u64,
    seq: u64,
    bids: Side,
    asks: Side,
    #[serde(default)]
    gapped: bool,
}

impl TryFrom<BookRepr> for Book {
    type Error = String;

    fn try_from(r: BookRepr) -> Result<Self, String> {
        let descending = |side: &Side| side.levels().is_sorted_by(|a, b| a.price > b.price);
        let ascending = |side: &Side| side.levels().is_sorted_by(|a, b| a.price < b.price);
        if !descending(&r.bids) {
            return Err("bids must be strictly descending by price".into());
        }
        if !ascending(&r.asks) {
            return Err("asks must be strictly ascending by price".into());
        }
        Ok(Book {
            venue: r.venue,
            inst: r.inst,
            ts: r.ts,
            seq: r.seq,
            bids: r.bids,
            asks: r.asks,
            gapped: r.gapped,
        })
    }
}

impl Book {
    /// Create an empty book.
    ///
    /// # Examples
    /// ```
    /// use depthbook::{Book, InternedString};
    ///
    /// let book = Book::new(
    ///     InternedString::new("binance"),
    ///     InternedString::new("BTC-USDT"),
    ///     1_700_000_000_000_000_000,
    ///     42,
    /// );
    /// assert_eq!(book.venue.as_str(), "binance");
    /// ```
    pub const fn new(venue: InternedString, inst: InternedString, ts: u64, seq: u64) -> Self {
        Self {
            venue,
            inst,
            ts,
            seq,
            bids: Side::new(),
            asks: Side::new(),
            gapped: false,
        }
    }

    /// Whether the best bid is at or above the best ask.
    ///
    /// A book in that state should not be priced from: [`Book::mid_price`] returns a
    /// value outside both sides and [`Book::spread`] a negative one, and neither is an
    /// error the caller can otherwise see. It is the ordinary symptom of a delta applied
    /// out of order, or of a venue publishing a bad update, which is exactly what the
    /// rest of this crate works to surface.
    ///
    /// Equality counts: a locked book, where bid and ask meet, is reported as crossed,
    /// because a zero spread is no more tradeable than a negative one.
    ///
    /// A book with an empty side is not crossed; there is nothing to compare.
    ///
    /// # Examples
    /// ```
    /// use depthbook::{f64_to_scale9, Book, InternedString, Level};
    ///
    /// let mut book = Book::new(
    ///     InternedString::new("binance"),
    ///     InternedString::new("BTC-USDT"),
    ///     1_700_000_000_000_000_000,
    ///     42,
    /// );
    /// book.bids.insert(Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)), true);
    /// book.asks.insert(Level::new(f64_to_scale9(50_010.0), f64_to_scale9(1.0)), false);
    /// assert!(!book.is_crossed());
    ///
    /// // A late delta lifts the bid through the ask.
    /// book.bids.insert(Level::new(f64_to_scale9(50_020.0), f64_to_scale9(1.0)), true);
    /// assert!(book.is_crossed());
    /// ```
    pub fn is_crossed(&self) -> bool {
        match (self.bids.best(), self.asks.best()) {
            (Some(bid), Some(ask)) => bid.price >= ask.price,
            _ => false,
        }
    }

    /// Midpoint of the best bid and the best ask.
    ///
    /// Returns `None` if either side is empty. A crossed book yields a midpoint outside
    /// both sides rather than an error, so check [`Book::is_crossed`] before trusting it.
    ///
    /// # Examples
    /// ```
    /// use depthbook::{f64_to_scale9, Book, InternedString, Level};
    ///
    /// let mut book = Book::new(
    ///     InternedString::new("binance"),
    ///     InternedString::new("BTC-USDT"),
    ///     1_700_000_000_000_000_000,
    ///     42,
    /// );
    /// book.bids.insert(Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)), true);
    /// book.asks.insert(Level::new(f64_to_scale9(50_010.0), f64_to_scale9(1.0)), false);
    ///
    /// assert_eq!(book.mid_price(), Some(f64_to_scale9(50_005.0)));
    /// ```
    pub fn mid_price(&self) -> Option<Scale9> {
        let bid = self.bids.best()?.price;
        let ask = self.asks.best()?.price;
        // Computed in i128 so the sum cannot overflow; the mean of two i64s fits an i64.
        Some(Scale9::from_raw(
            ((i128::from(bid.raw()) + i128::from(ask.raw())) / 2) as i64,
        ))
    }

    /// Difference between the best ask and the best bid.
    ///
    /// Returns `None` if either side is empty or the difference overflows. A crossed book
    /// yields a negative spread rather than an error, so check [`Book::is_crossed`] before
    /// trusting it.
    ///
    /// # Examples
    /// ```
    /// use depthbook::{f64_to_scale9, Book, InternedString, Level};
    ///
    /// let mut book = Book::new(
    ///     InternedString::new("binance"),
    ///     InternedString::new("BTC-USDT"),
    ///     1_700_000_000_000_000_000,
    ///     42,
    /// );
    /// book.bids.insert(Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)), true);
    /// book.asks.insert(Level::new(f64_to_scale9(50_010.0), f64_to_scale9(1.0)), false);
    ///
    /// assert_eq!(book.spread(), Some(f64_to_scale9(10.0)));
    /// ```
    pub fn spread(&self) -> Option<Scale9> {
        let bid = self.bids.best()?.price;
        let ask = self.asks.best()?.price;
        ask.checked_sub(bid)
    }

    /// Serialise to JSON.
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }

    /// Serialise to indented JSON.
    pub fn to_json_pretty(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::decimal::f64_to_scale9;

    const TS: u64 = 1_700_000_000_000_000_000;

    fn book() -> Book {
        Book::new(
            InternedString::new("binance"),
            InternedString::new("BTC-USDT"),
            TS,
            42,
        )
    }

    #[test]
    fn level_reports_empty_on_zero_qty() {
        let level = Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.5));
        assert_eq!(level.price, f64_to_scale9(50_000.0));
        assert!(!level.is_empty());

        assert!(Level::new(f64_to_scale9(50_000.0), Scale9::ZERO).is_empty());
    }

    #[test]
    fn new_side_is_empty() {
        let side = Side::new();
        assert_eq!(side.count(), 0);
        assert!(side.is_empty());
        assert!(side.best().is_none());
    }

    #[test]
    fn bids_sort_descending() {
        let mut bids = Side::new();

        assert!(bids.insert(
            Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)),
            true
        ));
        assert!(bids.insert(
            Level::new(f64_to_scale9(49_999.0), f64_to_scale9(2.0)),
            true
        ));
        assert!(bids.insert(
            Level::new(f64_to_scale9(50_001.0), f64_to_scale9(0.5)),
            true
        ));

        assert_eq!(bids.count(), 3);
        assert_eq!(bids.levels().next().unwrap().price, f64_to_scale9(50_001.0));
        assert_eq!(bids.levels().nth(1).unwrap().price, f64_to_scale9(50_000.0));
        assert_eq!(bids.levels().nth(2).unwrap().price, f64_to_scale9(49_999.0));
    }

    #[test]
    fn asks_sort_ascending() {
        let mut asks = Side::new();

        assert!(asks.insert(
            Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)),
            false
        ));
        assert!(asks.insert(
            Level::new(f64_to_scale9(50_001.0), f64_to_scale9(2.0)),
            false
        ));
        assert!(asks.insert(
            Level::new(f64_to_scale9(49_999.0), f64_to_scale9(0.5)),
            false
        ));

        assert_eq!(asks.count(), 3);
        assert_eq!(asks.levels().next().unwrap().price, f64_to_scale9(49_999.0));
        assert_eq!(asks.levels().nth(1).unwrap().price, f64_to_scale9(50_000.0));
        assert_eq!(asks.levels().nth(2).unwrap().price, f64_to_scale9(50_001.0));
    }

    #[test]
    fn inserting_a_known_price_updates_it() {
        let mut bids = Side::new();

        bids.insert(
            Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)),
            true,
        );
        assert_eq!(bids.count(), 1);

        assert!(!bids.insert(
            Level::new(f64_to_scale9(50_000.0), f64_to_scale9(2.0)),
            true
        ));
        assert_eq!(bids.count(), 1);
        assert_eq!(bids.levels().next().unwrap().qty, f64_to_scale9(2.0));
    }

    #[test]
    fn remove_takes_a_level_out() {
        let mut bids = Side::new();

        bids.insert(
            Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)),
            true,
        );
        bids.insert(
            Level::new(f64_to_scale9(49_999.0), f64_to_scale9(2.0)),
            true,
        );
        assert_eq!(bids.count(), 2);

        assert!(bids.remove(f64_to_scale9(50_000.0), true));
        assert_eq!(bids.count(), 1);
        assert_eq!(bids.levels().next().unwrap().price, f64_to_scale9(49_999.0));

        assert!(!bids.remove(f64_to_scale9(50_000.0), true));
    }

    #[test]
    fn update_inserts_then_removes() {
        let mut bids = Side::new();

        bids.update(f64_to_scale9(50_000.0), f64_to_scale9(1.0), true);
        assert_eq!(bids.count(), 1);

        bids.update(f64_to_scale9(50_000.0), f64_to_scale9(2.0), true);
        assert_eq!(bids.count(), 1);
        assert_eq!(bids.levels().next().unwrap().qty, f64_to_scale9(2.0));

        bids.update(f64_to_scale9(50_000.0), Scale9::ZERO, true);
        assert_eq!(bids.count(), 0);
    }

    #[test]
    fn best_is_the_top_of_book() {
        let mut bids = Side::new();

        bids.insert(
            Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)),
            true,
        );
        bids.insert(
            Level::new(f64_to_scale9(49_999.0), f64_to_scale9(2.0)),
            true,
        );

        let best = bids.best().unwrap();
        assert_eq!(best.price, f64_to_scale9(50_000.0));
        assert_eq!(best.qty, f64_to_scale9(1.0));
    }

    #[test]
    fn depth_within_bps_sums_nearby_levels() {
        let mut bids = Side::new();

        bids.insert(
            Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)),
            true,
        );
        bids.insert(
            Level::new(f64_to_scale9(49_000.0), f64_to_scale9(2.0)),
            true,
        );
        bids.insert(
            Level::new(f64_to_scale9(40_000.0), f64_to_scale9(3.0)),
            true,
        );

        assert_eq!(bids.depth_within_bps(3000, true), f64_to_scale9(6.0));
        assert_eq!(bids.depth_within_bps(50, true), f64_to_scale9(1.0));
        assert_eq!(bids.depth_within_bps(1900, true), f64_to_scale9(3.0));
    }

    #[test]
    fn depth_within_bps_on_empty_side_is_zero() {
        assert_eq!(Side::new().depth_within_bps(100, true), Scale9::ZERO);
    }

    #[test]
    fn book_reports_mid_and_spread() {
        let mut snapshot = book();

        snapshot.bids.insert(
            Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)),
            true,
        );
        snapshot.asks.insert(
            Level::new(f64_to_scale9(50_010.0), f64_to_scale9(1.0)),
            false,
        );

        assert_eq!(snapshot.mid_price(), Some(f64_to_scale9(50_005.0)));
        assert_eq!(snapshot.spread(), Some(f64_to_scale9(10.0)));
    }

    #[test]
    fn mid_and_spread_need_both_sides() {
        let mut snapshot = book();
        assert_eq!(snapshot.mid_price(), None);

        snapshot.bids.insert(
            Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)),
            true,
        );
        assert_eq!(snapshot.mid_price(), None);
        assert_eq!(snapshot.spread(), None);
    }

    #[test]
    fn book_round_trips_through_json() {
        let mut snapshot = book();

        snapshot.bids.insert(
            Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)),
            true,
        );
        snapshot.asks.insert(
            Level::new(f64_to_scale9(50_010.0), f64_to_scale9(1.0)),
            false,
        );

        let json = snapshot.to_json().unwrap();
        assert!(json.contains("binance"));
        assert!(json.contains("BTC-USDT"));

        let back: Book = serde_json::from_str(&json).unwrap();
        assert_eq!(back.bids.count(), 1);
        assert_eq!(back.bids.best().unwrap().price, f64_to_scale9(50_000.0));
        assert_eq!(back.asks.best().unwrap().price, f64_to_scale9(50_010.0));
    }

    #[test]
    fn is_crossed_detects_crossed_and_locked_books() {
        let mut b = book();
        // Empty sides cannot be compared, so they are not crossed.
        assert!(!b.is_crossed());
        b.bids.insert(
            Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)),
            true,
        );
        assert!(!b.is_crossed(), "one empty side is still not crossed");

        b.asks.insert(
            Level::new(f64_to_scale9(50_010.0), f64_to_scale9(1.0)),
            false,
        );
        assert!(!b.is_crossed());

        // Locked: bid meets ask.
        b.asks.insert(
            Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)),
            false,
        );
        assert!(b.is_crossed());
        assert_eq!(b.spread(), Some(Scale9::ZERO));

        // Crossed: bid through ask. mid_price sits outside both sides and spread is
        // negative, which is exactly why the flag exists.
        b.bids.insert(
            Level::new(f64_to_scale9(50_020.0), f64_to_scale9(1.0)),
            true,
        );
        assert!(b.is_crossed());
        assert_eq!(b.spread(), Some(f64_to_scale9(-20.0)));
        assert_eq!(b.mid_price(), Some(f64_to_scale9(50_010.0)));
    }

    #[test]
    fn insert_outcome_distinguishes_what_the_bool_cannot() {
        let mut bids = Side::new();
        let at = |p: f64, q: f64| Level::new(f64_to_scale9(p), f64_to_scale9(q));

        assert_eq!(
            bids.insert_outcome(at(50_000.0, 1.0), true),
            Insertion::Inserted
        );
        assert_eq!(
            bids.insert_outcome(at(50_000.0, 2.0), true),
            Insertion::Updated
        );
        assert_eq!(
            bids.insert_outcome(at(50_000.0, 0.0), true),
            Insertion::Removed
        );
        assert_eq!(
            bids.insert_outcome(at(50_000.0, 0.0), true),
            Insertion::Ignored
        );
        assert_eq!(bids.count(), 0);

        // Fill the side, then push at both ends.
        for i in 0..MAX_LEVELS {
            bids.insert(at(50_000.0 - i as f64, 1.0), true);
        }
        assert_eq!(bids.count(), MAX_LEVELS);

        // Better than everything: the worst resting level is evicted.
        assert_eq!(
            bids.insert_outcome(at(50_001.0, 1.0), true),
            Insertion::Dropped
        );
        assert_eq!(bids.count(), MAX_LEVELS);
        assert_eq!(bids.best().unwrap().price, f64_to_scale9(50_001.0));

        // Worse than everything: the incoming level is the one discarded.
        assert_eq!(bids.insert_outcome(at(1.0, 1.0), true), Insertion::Dropped);
        assert_eq!(bids.count(), MAX_LEVELS);
        assert!(bids.levels().all(|l| l.price != f64_to_scale9(1.0)));

        // A full side still updates in place without reporting a drop.
        let resting = bids.best().unwrap().price;
        assert_eq!(
            bids.insert_outcome(Level::new(resting, f64_to_scale9(9.0)), true),
            Insertion::Updated
        );
    }

    #[test]
    fn deserialize_rejects_reversed_book_sides() {
        let mut snapshot = book();
        snapshot
            .bids
            .insert(Level::new(f64_to_scale9(2.0), f64_to_scale9(1.0)), true);
        snapshot
            .bids
            .insert(Level::new(f64_to_scale9(1.0), f64_to_scale9(1.0)), true);
        snapshot
            .asks
            .insert(Level::new(f64_to_scale9(3.0), f64_to_scale9(1.0)), false);
        snapshot
            .asks
            .insert(Level::new(f64_to_scale9(4.0), f64_to_scale9(1.0)), false);
        let json = snapshot.to_json().unwrap();
        assert!(serde_json::from_str::<Book>(&json).is_ok());

        // Swap the sides' payloads: bids ascending, asks descending.
        let bids = serde_json::to_string(&snapshot.bids).unwrap();
        let asks = serde_json::to_string(&snapshot.asks).unwrap();
        let swapped = json
            .replace(&bids, "@@")
            .replace(&asks, &bids)
            .replace("@@", &asks);
        let err = serde_json::from_str::<Book>(&swapped)
            .unwrap_err()
            .to_string();
        assert!(err.contains("bids must be strictly descending"), "{err}");
    }

    #[test]
    fn depth_within_bps_saturates_on_huge_margins() {
        let mut bids = Side::new();
        bids.insert(
            Level::new(Scale9::from_raw(i64::MAX), f64_to_scale9(1.0)),
            true,
        );
        bids.insert(Level::new(Scale9::from_raw(1), f64_to_scale9(2.0)), true);
        assert_eq!(bids.depth_within_bps(u32::MAX, true), f64_to_scale9(3.0));
    }

    #[test]
    fn deserialize_rejects_invalid_sides() {
        let level = |p: f64, q: f64| {
            format!(
                r#"{{"price":{},"qty":{}}}"#,
                f64_to_scale9(p).raw(),
                f64_to_scale9(q).raw()
            )
        };
        let side = |levels: &[String], count: usize| {
            format!(r#"{{"levels":[{}],"count":{count}}}"#, levels.join(","))
        };

        let ok = side(&[level(2.0, 1.0), level(1.0, 1.0)], 2);
        assert_eq!(serde_json::from_str::<Side>(&ok).unwrap().count(), 2);

        let bad = [
            side(&[level(1.0, 1.0)], 2), // count mismatch
            side(&[level(1.0, 1.0), level(2.0, 1.0), level(1.5, 1.0)], 3), // unsorted
            side(&[level(1.0, 1.0), level(1.0, 2.0)], 2), // duplicate price
            side(&[level(1.0, 0.0)], 1), // zero qty
            side(&[level(1.0, -1.0)], 1), // negative qty
            side(&[level(-1.0, 1.0)], 1), // negative price
        ];
        for json in bad {
            assert!(serde_json::from_str::<Side>(&json).is_err(), "{json}");
        }
    }

    #[test]
    fn clear_empties_a_side() {
        let mut bids = Side::new();
        bids.insert(
            Level::new(f64_to_scale9(50_000.0), f64_to_scale9(1.0)),
            true,
        );
        bids.insert(
            Level::new(f64_to_scale9(49_999.0), f64_to_scale9(2.0)),
            true,
        );
        assert_eq!(bids.count(), 2);

        bids.clear();
        assert!(bids.is_empty());
    }

    #[test]
    fn a_full_side_drops_the_worst_level() {
        let mut bids = Side::new();

        for i in 0..MAX_LEVELS {
            let price = f64_to_scale9(50_000.0 - i as f64);
            bids.insert(Level::new(price, f64_to_scale9(1.0)), true);
        }
        assert_eq!(bids.count(), MAX_LEVELS);

        bids.insert(
            Level::new(f64_to_scale9(50_001.0), f64_to_scale9(1.0)),
            true,
        );
        assert_eq!(bids.count(), MAX_LEVELS);
        assert_eq!(bids.levels().next().unwrap().price, f64_to_scale9(50_001.0));
    }

    #[test]
    fn truncate_keeps_the_best_levels() {
        let mut bids = Side::new();
        for i in 0..10 {
            bids.insert(
                Level::new(f64_to_scale9(50_000.0 - i as f64), f64_to_scale9(1.0)),
                true,
            );
        }

        bids.truncate(3);
        assert_eq!(bids.count(), 3);
        assert_eq!(bids.best().unwrap().price, f64_to_scale9(50_000.0));

        bids.truncate(100);
        assert_eq!(bids.count(), 3);
    }
}