nanobook 0.9.2

Production-grade Rust execution infrastructure for automated trading: LOB engine, portfolio simulator, broker abstraction, risk engine
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
//! PriceLevels: One side of the order book (bids or asks).
//!
//! Maintains a sorted collection of price levels with cached best price
//! for O(1) BBO (best bid/offer) queries.

use std::collections::BTreeMap;

use crate::{Level, OrderId, Price, Quantity, Side};

/// One side of the order book (all bids or all asks).
///
/// - **Bids**: Sorted high → low, best = highest price
/// - **Asks**: Sorted low → high, best = lowest price
///
/// The `BTreeMap` provides O(log n) insert/remove with sorted iteration.
/// Best price is cached for O(1) access.
#[derive(Clone, Debug)]
pub struct PriceLevels {
    /// Price levels, sorted by price
    levels: BTreeMap<Price, Level>,
    /// Cached best price for O(1) access
    best_price: Option<Price>,
    /// Which side this represents (determines "best" direction)
    side: Side,
}

impl PriceLevels {
    /// Create a new empty price levels collection for the given side.
    pub fn new(side: Side) -> Self {
        Self {
            levels: BTreeMap::new(),
            best_price: None,
            side,
        }
    }

    /// Returns which side this collection represents.
    #[inline]
    pub fn side(&self) -> Side {
        self.side
    }

    /// Returns true if there are no orders on this side.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.levels.is_empty()
    }

    /// Returns the number of distinct price levels.
    #[inline]
    pub fn level_count(&self) -> usize {
        self.levels.len()
    }

    /// Returns the best price (highest for bids, lowest for asks).
    ///
    /// O(1) - cached value.
    #[inline]
    pub fn best_price(&self) -> Option<Price> {
        self.best_price
    }

    /// Returns a reference to the best level.
    ///
    /// O(1) - uses cached best price.
    pub fn best_level(&self) -> Option<&Level> {
        self.best_price.and_then(|p| self.levels.get(&p))
    }

    /// Returns a mutable reference to the best level.
    ///
    /// O(1) - uses cached best price.
    pub fn best_level_mut(&mut self) -> Option<&mut Level> {
        self.best_price.and_then(|p| self.levels.get_mut(&p))
    }

    /// Returns a reference to the level at the given price, if it exists.
    pub fn get_level(&self, price: Price) -> Option<&Level> {
        self.levels.get(&price)
    }

    /// Returns a mutable reference to the level at the given price, if it exists.
    pub fn get_level_mut(&mut self, price: Price) -> Option<&mut Level> {
        self.levels.get_mut(&price)
    }

    /// Gets or creates a level at the given price.
    ///
    /// If the level is newly created, updates the best price cache if needed.
    pub fn get_or_create_level(&mut self, price: Price) -> &mut Level {
        // Check if we need to update best price before borrowing levels
        let is_new = !self.levels.contains_key(&price);

        if is_new {
            // Update best price cache before inserting
            self.update_best_price_after_insert(price);
            self.levels.insert(price, Level::new(price));
        }

        self.levels.get_mut(&price).unwrap()
    }

    /// Add an order at the given price.
    ///
    /// Creates the level if it doesn't exist.
    /// Returns the position index within the level.
    pub fn insert_order(&mut self, price: Price, order_id: OrderId, quantity: Quantity) -> usize {
        let level = self.get_or_create_level(price);
        // Actually, VecDeque index is just the length before push.
        let actual_index = level.orders.len();
        level.push_back(order_id, quantity);
        actual_index
    }

    /// Mark an order as a tombstone.
    pub fn mark_tombstone(&mut self, price: Price, index: usize, quantity: Quantity) {
        if let Some(level) = self.levels.get_mut(&price) {
            level.mark_tombstone(index, quantity);
            if level.is_empty() {
                self.remove_level(price);
            }
        }
    }

    /// Remove all tombstones from all levels.
    pub fn compact(&mut self) {
        for level in self.levels.values_mut() {
            level.compact();
        }
    }

    /// Remove an order from the given price level.
    ///
    /// Returns `true` if the order was found and removed.
    /// Removes the level entirely if it becomes empty.
    pub fn remove_order(&mut self, price: Price, order_id: OrderId, quantity: Quantity) -> bool {
        if let Some(level) = self.levels.get_mut(&price) {
            if level.remove(order_id, quantity) {
                if level.is_empty() {
                    self.remove_level(price);
                }
                return true;
            }
        }
        false
    }

    /// Remove a price level entirely.
    ///
    /// Updates the best price cache if the removed level was the best.
    pub fn remove_level(&mut self, price: Price) {
        if self.levels.remove(&price).is_some() {
            // Update best price if we removed it
            if self.best_price == Some(price) {
                self.recompute_best_price();
            }
        }
    }

    /// Remove the best level and return it.
    ///
    /// Useful when a level is fully consumed during matching.
    pub fn pop_best_level(&mut self) -> Option<Level> {
        let price = self.best_price?;
        let level = self.levels.remove(&price);
        self.recompute_best_price();
        level
    }

    /// Returns an iterator over levels from best to worst price.
    ///
    /// - Bids: highest to lowest
    /// - Asks: lowest to highest
    pub fn iter_best_to_worst(&self) -> impl Iterator<Item = (&Price, &Level)> {
        BestToWorstIter {
            inner: if self.side == Side::Buy {
                IterDirection::Reverse(self.levels.iter().rev())
            } else {
                IterDirection::Forward(self.levels.iter())
            },
        }
    }

    /// Returns the total quantity across all levels.
    pub fn total_quantity(&self) -> Quantity {
        self.levels.values().map(|l| l.total_quantity()).sum()
    }

    /// Returns the total quantity available at prices that would cross with the given price.
    ///
    /// For bids: quantity at prices >= given price
    /// For asks: quantity at prices <= given price
    pub fn quantity_at_or_better(&self, price: Price) -> Quantity {
        match self.side {
            Side::Buy => {
                // Bids: want prices >= given (higher is better for buyer)
                self.levels
                    .range(price..)
                    .map(|(_, l)| l.total_quantity())
                    .sum()
            }
            Side::Sell => {
                // Asks: want prices <= given (lower is better for seller's counterparty)
                self.levels
                    .range(..=price)
                    .map(|(_, l)| l.total_quantity())
                    .sum()
            }
        }
    }

    // === Private helpers ===

    /// Recompute best price from scratch (O(1) for BTreeMap).
    fn recompute_best_price(&mut self) {
        self.best_price = match self.side {
            Side::Buy => self.levels.keys().next_back().copied(), // Highest
            Side::Sell => self.levels.keys().next().copied(),     // Lowest
        };
    }

    /// Update best price after inserting a new level.
    fn update_best_price_after_insert(&mut self, new_price: Price) {
        match self.best_price {
            None => {
                self.best_price = Some(new_price);
            }
            Some(current_best) => {
                let is_better = match self.side {
                    Side::Buy => new_price > current_best, // Higher is better for bids
                    Side::Sell => new_price < current_best, // Lower is better for asks
                };
                if is_better {
                    self.best_price = Some(new_price);
                }
            }
        }
    }
}

/// Direction wrapper for the iterator.
enum IterDirection<F, R> {
    Forward(F),
    Reverse(R),
}

type BTreeIter<'a> = std::collections::btree_map::Iter<'a, Price, Level>;

/// Iterator that yields levels from best to worst price.
struct BestToWorstIter<'a> {
    inner: IterDirection<BTreeIter<'a>, std::iter::Rev<BTreeIter<'a>>>,
}

impl<'a> Iterator for BestToWorstIter<'a> {
    type Item = (&'a Price, &'a Level);

    fn next(&mut self) -> Option<Self::Item> {
        match &mut self.inner {
            IterDirection::Forward(iter) => iter.next(),
            IterDirection::Reverse(iter) => iter.next(),
        }
    }
}

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

    // === Bid side tests (best = highest) ===

    #[test]
    fn new_bids_is_empty() {
        let bids = PriceLevels::new(Side::Buy);

        assert!(bids.is_empty());
        assert_eq!(bids.level_count(), 0);
        assert_eq!(bids.best_price(), None);
        assert!(bids.best_level().is_none());
    }

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

        bids.insert_order(Price(100_00), OrderId(1), 100);
        assert_eq!(bids.best_price(), Some(Price(100_00)));

        bids.insert_order(Price(99_00), OrderId(2), 100);
        assert_eq!(bids.best_price(), Some(Price(100_00))); // Still 100

        bids.insert_order(Price(101_00), OrderId(3), 100);
        assert_eq!(bids.best_price(), Some(Price(101_00))); // Now 101
    }

    #[test]
    fn bids_remove_best_updates_cache() {
        let mut bids = PriceLevels::new(Side::Buy);
        bids.insert_order(Price(100_00), OrderId(1), 100);
        bids.insert_order(Price(99_00), OrderId(2), 100);
        bids.insert_order(Price(101_00), OrderId(3), 100);

        assert_eq!(bids.best_price(), Some(Price(101_00)));

        bids.remove_level(Price(101_00));
        assert_eq!(bids.best_price(), Some(Price(100_00)));

        bids.remove_level(Price(100_00));
        assert_eq!(bids.best_price(), Some(Price(99_00)));

        bids.remove_level(Price(99_00));
        assert_eq!(bids.best_price(), None);
    }

    // === Ask side tests (best = lowest) ===

    #[test]
    fn new_asks_is_empty() {
        let asks = PriceLevels::new(Side::Sell);

        assert!(asks.is_empty());
        assert_eq!(asks.best_price(), None);
    }

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

        asks.insert_order(Price(100_00), OrderId(1), 100);
        assert_eq!(asks.best_price(), Some(Price(100_00)));

        asks.insert_order(Price(101_00), OrderId(2), 100);
        assert_eq!(asks.best_price(), Some(Price(100_00))); // Still 100

        asks.insert_order(Price(99_00), OrderId(3), 100);
        assert_eq!(asks.best_price(), Some(Price(99_00))); // Now 99
    }

    #[test]
    fn asks_remove_best_updates_cache() {
        let mut asks = PriceLevels::new(Side::Sell);
        asks.insert_order(Price(100_00), OrderId(1), 100);
        asks.insert_order(Price(101_00), OrderId(2), 100);
        asks.insert_order(Price(99_00), OrderId(3), 100);

        assert_eq!(asks.best_price(), Some(Price(99_00)));

        asks.remove_level(Price(99_00));
        assert_eq!(asks.best_price(), Some(Price(100_00)));
    }

    // === Order operations ===

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

        bids.insert_order(Price(100_00), OrderId(1), 100);
        bids.insert_order(Price(100_00), OrderId(2), 200);
        bids.insert_order(Price(100_00), OrderId(3), 150);

        assert_eq!(bids.level_count(), 1);
        let level = bids.best_level().unwrap();
        assert_eq!(level.order_count(), 3);
        assert_eq!(level.total_quantity(), 450);
    }

    #[test]
    fn remove_order_removes_empty_level() {
        let mut bids = PriceLevels::new(Side::Buy);
        bids.insert_order(Price(100_00), OrderId(1), 100);
        bids.insert_order(Price(99_00), OrderId(2), 200);

        assert_eq!(bids.level_count(), 2);

        // Remove the only order at 100
        assert!(bids.remove_order(Price(100_00), OrderId(1), 100));
        assert_eq!(bids.level_count(), 1);
        assert_eq!(bids.best_price(), Some(Price(99_00)));
    }

    #[test]
    fn remove_order_keeps_nonempty_level() {
        let mut bids = PriceLevels::new(Side::Buy);
        bids.insert_order(Price(100_00), OrderId(1), 100);
        bids.insert_order(Price(100_00), OrderId(2), 200);

        assert!(bids.remove_order(Price(100_00), OrderId(1), 100));
        assert_eq!(bids.level_count(), 1);

        let level = bids.best_level().unwrap();
        assert_eq!(level.order_count(), 1);
        assert_eq!(level.total_quantity(), 200);
    }

    #[test]
    fn remove_nonexistent_order() {
        let mut bids = PriceLevels::new(Side::Buy);
        bids.insert_order(Price(100_00), OrderId(1), 100);

        assert!(!bids.remove_order(Price(100_00), OrderId(999), 100));
        assert!(!bids.remove_order(Price(999_00), OrderId(1), 100));
    }

    // === Iteration ===

    #[test]
    fn iter_bids_best_to_worst() {
        let mut bids = PriceLevels::new(Side::Buy);
        bids.insert_order(Price(99_00), OrderId(1), 100);
        bids.insert_order(Price(101_00), OrderId(2), 100);
        bids.insert_order(Price(100_00), OrderId(3), 100);

        let prices: Vec<_> = bids.iter_best_to_worst().map(|(p, _)| *p).collect();
        assert_eq!(prices, vec![Price(101_00), Price(100_00), Price(99_00)]);
    }

    #[test]
    fn iter_asks_best_to_worst() {
        let mut asks = PriceLevels::new(Side::Sell);
        asks.insert_order(Price(99_00), OrderId(1), 100);
        asks.insert_order(Price(101_00), OrderId(2), 100);
        asks.insert_order(Price(100_00), OrderId(3), 100);

        let prices: Vec<_> = asks.iter_best_to_worst().map(|(p, _)| *p).collect();
        assert_eq!(prices, vec![Price(99_00), Price(100_00), Price(101_00)]);
    }

    // === Quantity queries ===

    #[test]
    fn total_quantity() {
        let mut bids = PriceLevels::new(Side::Buy);
        bids.insert_order(Price(100_00), OrderId(1), 100);
        bids.insert_order(Price(100_00), OrderId(2), 200);
        bids.insert_order(Price(99_00), OrderId(3), 150);

        assert_eq!(bids.total_quantity(), 450);
    }

    #[test]
    fn quantity_at_or_better_bids() {
        let mut bids = PriceLevels::new(Side::Buy);
        bids.insert_order(Price(100_00), OrderId(1), 100);
        bids.insert_order(Price(99_00), OrderId(2), 200);
        bids.insert_order(Price(98_00), OrderId(3), 150);

        // Bids at or above $99 (prices >= 99_00)
        assert_eq!(bids.quantity_at_or_better(Price(99_00)), 300); // 100 + 200

        // Bids at or above $100
        assert_eq!(bids.quantity_at_or_better(Price(100_00)), 100);

        // Bids at or above $98
        assert_eq!(bids.quantity_at_or_better(Price(98_00)), 450);
    }

    #[test]
    fn quantity_at_or_better_asks() {
        let mut asks = PriceLevels::new(Side::Sell);
        asks.insert_order(Price(100_00), OrderId(1), 100);
        asks.insert_order(Price(101_00), OrderId(2), 200);
        asks.insert_order(Price(102_00), OrderId(3), 150);

        // Asks at or below $101 (prices <= 101_00)
        assert_eq!(asks.quantity_at_or_better(Price(101_00)), 300); // 100 + 200

        // Asks at or below $100
        assert_eq!(asks.quantity_at_or_better(Price(100_00)), 100);

        // Asks at or below $102
        assert_eq!(asks.quantity_at_or_better(Price(102_00)), 450);
    }

    // === Best level mutation ===

    #[test]
    fn best_level_mut_allows_modification() {
        let mut bids = PriceLevels::new(Side::Buy);
        bids.insert_order(Price(100_00), OrderId(1), 100);

        if let Some(level) = bids.best_level_mut() {
            level.decrease_quantity(30);
        }

        assert_eq!(bids.best_level().unwrap().total_quantity(), 70);
    }

    #[test]
    fn pop_best_level() {
        let mut asks = PriceLevels::new(Side::Sell);
        asks.insert_order(Price(100_00), OrderId(1), 100);
        asks.insert_order(Price(101_00), OrderId(2), 200);

        let popped = asks.pop_best_level().unwrap();
        assert_eq!(popped.price(), Price(100_00));
        assert_eq!(asks.best_price(), Some(Price(101_00)));
    }
}