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
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
//! OrderBook: The complete order book with both sides and order storage.
//!
//! This is the core data structure that combines:
//! - Bids (buy orders) sorted high → low
//! - Asks (sell orders) sorted low → high
//! - Central order storage for O(1) lookup by OrderId

use rustc_hash::FxHashMap;

use crate::{Order, OrderId, Price, PriceLevels, Quantity, Side, TimeInForce, Timestamp, TradeId};

// Re-import for tests only
#[cfg(test)]
use crate::OrderStatus;

/// The complete order book.
///
/// Maintains both sides of the book plus a central index of all orders
/// (active and historical) for O(1) lookup.
#[derive(Clone, Debug)]
pub struct OrderBook {
    /// Buy orders, sorted by price descending (best = highest)
    bids: PriceLevels,
    /// Sell orders, sorted by price ascending (best = lowest)
    asks: PriceLevels,
    /// All orders indexed by ID (includes filled/cancelled for history)
    pub(crate) orders: FxHashMap<OrderId, Order>,
    /// Next order ID to assign
    next_order_id: u64,
    /// Next trade ID to assign
    next_trade_id: u64,
    /// Next timestamp to assign (monotonic counter)
    next_timestamp: u64,
}

impl OrderBook {
    /// Create a new empty order book.
    pub fn new() -> Self {
        Self {
            bids: PriceLevels::new(Side::Buy),
            asks: PriceLevels::new(Side::Sell),
            orders: FxHashMap::default(),
            next_order_id: 1,
            next_trade_id: 1,
            next_timestamp: 1,
        }
    }

    // === ID and timestamp generation ===

    /// Generate the next order ID (monotonically increasing).
    pub fn next_order_id(&mut self) -> OrderId {
        let id = OrderId(self.next_order_id);
        self.next_order_id += 1;
        id
    }

    /// Generate the next trade ID (monotonically increasing).
    pub fn next_trade_id(&mut self) -> TradeId {
        let id = TradeId(self.next_trade_id);
        self.next_trade_id += 1;
        id
    }

    /// Generate the next timestamp (monotonically increasing).
    pub fn next_timestamp(&mut self) -> Timestamp {
        let ts = self.next_timestamp;
        self.next_timestamp += 1;
        ts
    }

    /// Peek at what the next order ID would be (without consuming it).
    pub fn peek_next_order_id(&self) -> OrderId {
        OrderId(self.next_order_id)
    }

    // === Order access ===

    /// Get an order by ID (includes historical filled/cancelled orders).
    pub fn get_order(&self, order_id: OrderId) -> Option<&Order> {
        self.orders.get(&order_id)
    }

    /// Get a mutable reference to an order by ID.
    pub fn get_order_mut(&mut self, order_id: OrderId) -> Option<&mut Order> {
        self.orders.get_mut(&order_id)
    }

    /// Check if an order exists.
    pub fn contains_order(&self, order_id: OrderId) -> bool {
        self.orders.contains_key(&order_id)
    }

    /// Returns the total number of orders (including historical).
    pub fn order_count(&self) -> usize {
        self.orders.len()
    }

    /// Returns the number of active orders (on the book).
    pub fn active_order_count(&self) -> usize {
        self.orders.values().filter(|o| o.is_active()).count()
    }

    // === Book access ===

    /// Get the bids side (buy orders).
    pub fn bids(&self) -> &PriceLevels {
        &self.bids
    }

    /// Get the asks side (sell orders).
    pub fn asks(&self) -> &PriceLevels {
        &self.asks
    }

    /// Get mutable access to bids.
    pub fn bids_mut(&mut self) -> &mut PriceLevels {
        &mut self.bids
    }

    /// Get mutable access to asks.
    pub fn asks_mut(&mut self) -> &mut PriceLevels {
        &mut self.asks
    }

    /// Get the appropriate side for an order.
    pub fn side(&self, side: Side) -> &PriceLevels {
        match side {
            Side::Buy => &self.bids,
            Side::Sell => &self.asks,
        }
    }

    /// Get mutable access to the appropriate side.
    pub fn side_mut(&mut self, side: Side) -> &mut PriceLevels {
        match side {
            Side::Buy => &mut self.bids,
            Side::Sell => &mut self.asks,
        }
    }

    /// Get the opposite side (for matching).
    pub fn opposite_side(&self, side: Side) -> &PriceLevels {
        self.side(side.opposite())
    }

    /// Get mutable access to the opposite side.
    pub fn opposite_side_mut(&mut self, side: Side) -> &mut PriceLevels {
        self.side_mut(side.opposite())
    }

    // === Best prices ===

    /// Get the best bid price (highest buy price).
    pub fn best_bid(&self) -> Option<Price> {
        self.bids.best_price()
    }

    /// Get the best ask price (lowest sell price).
    pub fn best_ask(&self) -> Option<Price> {
        self.asks.best_price()
    }

    /// Get both best bid and best ask.
    pub fn best_bid_ask(&self) -> (Option<Price>, Option<Price>) {
        (self.best_bid(), self.best_ask())
    }

    /// Get the spread (best ask - best bid), if both exist.
    pub fn spread(&self) -> Option<i64> {
        match (self.best_bid(), self.best_ask()) {
            (Some(bid), Some(ask)) => Some(ask.0 - bid.0),
            _ => None,
        }
    }

    /// Check if the book is crossed (best bid >= best ask).
    /// This should never happen after matching is complete.
    pub fn is_crossed(&self) -> bool {
        match (self.best_bid(), self.best_ask()) {
            (Some(bid), Some(ask)) => bid >= ask,
            _ => false,
        }
    }

    // === Order management ===

    /// Add a new order to the book.
    ///
    /// The order must have a unique ID (typically from `next_order_id()`).
    /// The order is stored in the central index and added to the appropriate
    /// price level based on its side and price.
    ///
    /// # Panics
    ///
    /// Panics if an order with the same ID already exists.
    pub fn add_order(&mut self, mut order: Order) {
        assert!(
            !self.orders.contains_key(&order.id),
            "order {} already exists",
            order.id
        );

        let side = order.side;
        let price = order.price;
        let quantity = order.remaining_quantity;
        let order_id = order.id;

        // Add to appropriate price level and get its index
        let index = self.side_mut(side).insert_order(price, order_id, quantity);
        order.position_in_level = index;

        // Store in central index
        self.orders.insert(order_id, order);
    }

    /// Remove an order from the book (for cancellation).
    ///
    /// Updates the order's status to Cancelled and marks it as a tombstone
    /// in the price level queue for O(1) performance.
    pub fn cancel_order(&mut self, order_id: OrderId) -> Option<Quantity> {
        let order = self.orders.get_mut(&order_id)?;

        if !order.is_active() {
            return None;
        }

        let side = order.side;
        let price = order.price;
        let remaining = order.remaining_quantity;
        let index = order.position_in_level;

        // Cancel the order (updates status)
        order.cancel();

        // Mark as tombstone in price level (O(1))
        self.side_mut(side).mark_tombstone(price, index, remaining);

        Some(remaining)
    }

    /// Create a new order with auto-generated ID and timestamp.
    ///
    /// This is a convenience method that:
    /// 1. Generates the next order ID
    /// 2. Generates the next timestamp
    /// 3. Creates the Order struct
    ///
    /// The order is NOT added to the book — use `add_order()` for that.
    pub fn create_order(
        &mut self,
        side: Side,
        price: Price,
        quantity: Quantity,
        time_in_force: TimeInForce,
    ) -> Order {
        let id = self.next_order_id();
        let timestamp = self.next_timestamp();
        Order::new(id, side, price, quantity, timestamp, time_in_force)
    }

    /// Remove filled and cancelled orders from history to free memory.
    ///
    /// Active orders (on the book) are preserved. Returns the number of
    /// orders removed.
    ///
    /// Use this periodically for long-running instances to prevent
    /// unbounded memory growth.
    pub fn clear_history(&mut self) -> usize {
        let before = self.orders.len();
        self.orders.retain(|_, order| order.is_active());
        before - self.orders.len()
    }

    /// Remove all tombstones from the book.
    pub fn compact(&mut self) {
        self.bids.compact();
        self.asks.compact();
    }
}

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

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

    #[test]
    fn new_book_is_empty() {
        let book = OrderBook::new();

        assert_eq!(book.order_count(), 0);
        assert_eq!(book.active_order_count(), 0);
        assert_eq!(book.best_bid(), None);
        assert_eq!(book.best_ask(), None);
        assert_eq!(book.spread(), None);
        assert!(!book.is_crossed());
    }

    #[test]
    fn id_generation_is_monotonic() {
        let mut book = OrderBook::new();

        assert_eq!(book.next_order_id(), OrderId(1));
        assert_eq!(book.next_order_id(), OrderId(2));
        assert_eq!(book.next_order_id(), OrderId(3));

        assert_eq!(book.next_trade_id(), TradeId(1));
        assert_eq!(book.next_trade_id(), TradeId(2));

        assert_eq!(book.next_timestamp(), 1);
        assert_eq!(book.next_timestamp(), 2);
    }

    #[test]
    fn peek_order_id_does_not_consume() {
        let mut book = OrderBook::new();

        assert_eq!(book.peek_next_order_id(), OrderId(1));
        assert_eq!(book.peek_next_order_id(), OrderId(1));
        assert_eq!(book.next_order_id(), OrderId(1));
        assert_eq!(book.peek_next_order_id(), OrderId(2));
    }

    #[test]
    fn add_and_get_order() {
        let mut book = OrderBook::new();

        let order = book.create_order(Side::Buy, Price(100_00), 100, TimeInForce::GTC);
        let order_id = order.id;
        book.add_order(order);

        assert!(book.contains_order(order_id));
        assert_eq!(book.order_count(), 1);
        assert_eq!(book.active_order_count(), 1);

        let retrieved = book.get_order(order_id).unwrap();
        assert_eq!(retrieved.id, order_id);
        assert_eq!(retrieved.price, Price(100_00));
        assert_eq!(retrieved.remaining_quantity, 100);
    }

    #[test]
    fn add_order_updates_best_prices() {
        let mut book = OrderBook::new();

        // Add a bid
        let bid = book.create_order(Side::Buy, Price(100_00), 100, TimeInForce::GTC);
        book.add_order(bid);
        assert_eq!(book.best_bid(), Some(Price(100_00)));
        assert_eq!(book.best_ask(), None);

        // Add an ask
        let ask = book.create_order(Side::Sell, Price(101_00), 100, TimeInForce::GTC);
        book.add_order(ask);
        assert_eq!(book.best_bid(), Some(Price(100_00)));
        assert_eq!(book.best_ask(), Some(Price(101_00)));
    }

    #[test]
    fn spread_calculation() {
        let mut book = OrderBook::new();

        // No spread without both sides
        assert_eq!(book.spread(), None);

        let bid = book.create_order(Side::Buy, Price(100_00), 100, TimeInForce::GTC);
        book.add_order(bid);
        assert_eq!(book.spread(), None);

        let ask = book.create_order(Side::Sell, Price(101_50), 100, TimeInForce::GTC);
        book.add_order(ask);
        assert_eq!(book.spread(), Some(150)); // 101.50 - 100.00 = 1.50 = 150 cents
    }

    #[test]
    fn cancel_order() {
        let mut book = OrderBook::new();

        let order = book.create_order(Side::Buy, Price(100_00), 100, TimeInForce::GTC);
        let order_id = order.id;
        book.add_order(order);

        assert_eq!(book.active_order_count(), 1);
        assert_eq!(book.best_bid(), Some(Price(100_00)));

        // Cancel it
        let cancelled = book.cancel_order(order_id);
        assert_eq!(cancelled, Some(100));

        // Order still exists but is not active
        assert_eq!(book.order_count(), 1);
        assert_eq!(book.active_order_count(), 0);
        assert_eq!(
            book.get_order(order_id).unwrap().status,
            OrderStatus::Cancelled
        );

        // Best bid is now gone
        assert_eq!(book.best_bid(), None);
    }

    #[test]
    fn cancel_nonexistent_order() {
        let mut book = OrderBook::new();
        assert_eq!(book.cancel_order(OrderId(999)), None);
    }

    #[test]
    fn cancel_already_cancelled() {
        let mut book = OrderBook::new();

        let order = book.create_order(Side::Buy, Price(100_00), 100, TimeInForce::GTC);
        let order_id = order.id;
        book.add_order(order);

        book.cancel_order(order_id);
        assert_eq!(book.cancel_order(order_id), None); // Already cancelled
    }

    #[test]
    fn multiple_orders_same_price() {
        let mut book = OrderBook::new();

        let o1 = book.create_order(Side::Buy, Price(100_00), 100, TimeInForce::GTC);
        let o2 = book.create_order(Side::Buy, Price(100_00), 200, TimeInForce::GTC);
        let o3 = book.create_order(Side::Buy, Price(100_00), 150, TimeInForce::GTC);

        book.add_order(o1);
        book.add_order(o2);
        book.add_order(o3);

        assert_eq!(book.active_order_count(), 3);
        assert_eq!(book.bids().level_count(), 1);
        assert_eq!(book.bids().total_quantity(), 450);
    }

    #[test]
    fn multiple_price_levels() {
        let mut book = OrderBook::new();

        let o1 = book.create_order(Side::Buy, Price(100_00), 100, TimeInForce::GTC);
        let o2 = book.create_order(Side::Buy, Price(99_00), 200, TimeInForce::GTC);
        let o3 = book.create_order(Side::Sell, Price(101_00), 150, TimeInForce::GTC);
        let o4 = book.create_order(Side::Sell, Price(102_00), 175, TimeInForce::GTC);

        book.add_order(o1);
        book.add_order(o2);
        book.add_order(o3);
        book.add_order(o4);

        assert_eq!(book.bids().level_count(), 2);
        assert_eq!(book.asks().level_count(), 2);
        assert_eq!(book.best_bid(), Some(Price(100_00)));
        assert_eq!(book.best_ask(), Some(Price(101_00)));
    }

    #[test]
    fn is_crossed() {
        let mut book = OrderBook::new();

        // Not crossed when empty
        assert!(!book.is_crossed());

        // Not crossed with normal spread
        let bid = book.create_order(Side::Buy, Price(100_00), 100, TimeInForce::GTC);
        let ask = book.create_order(Side::Sell, Price(101_00), 100, TimeInForce::GTC);
        book.add_order(bid);
        book.add_order(ask);
        assert!(!book.is_crossed());

        // Would be crossed if we add a higher bid (in practice, matching prevents this)
        let high_bid = book.create_order(Side::Buy, Price(102_00), 100, TimeInForce::GTC);
        book.add_order(high_bid);
        assert!(book.is_crossed());
    }

    #[test]
    fn opposite_side() {
        let mut book = OrderBook::new();

        let bid = book.create_order(Side::Buy, Price(100_00), 100, TimeInForce::GTC);
        let ask = book.create_order(Side::Sell, Price(101_00), 100, TimeInForce::GTC);
        book.add_order(bid);
        book.add_order(ask);

        // Opposite of buy is sell (asks)
        assert_eq!(
            book.opposite_side(Side::Buy).best_price(),
            Some(Price(101_00))
        );
        // Opposite of sell is buy (bids)
        assert_eq!(
            book.opposite_side(Side::Sell).best_price(),
            Some(Price(100_00))
        );
    }

    #[test]
    #[should_panic(expected = "already exists")]
    fn add_duplicate_order_panics() {
        let mut book = OrderBook::new();

        let order = book.create_order(Side::Buy, Price(100_00), 100, TimeInForce::GTC);
        let order_clone = order.clone();

        book.add_order(order);
        book.add_order(order_clone); // Panic: duplicate ID
    }

    #[test]
    fn get_order_mut() {
        let mut book = OrderBook::new();

        let order = book.create_order(Side::Buy, Price(100_00), 100, TimeInForce::GTC);
        let order_id = order.id;
        book.add_order(order);

        // Modify via mutable reference
        {
            let order = book.get_order_mut(order_id).unwrap();
            order.fill(30);
        }

        // Verify change persisted
        let order = book.get_order(order_id).unwrap();
        assert_eq!(order.remaining_quantity, 70);
        assert_eq!(order.filled_quantity, 30);
    }

    #[test]
    fn clear_history_removes_inactive_orders() {
        let mut book = OrderBook::new();

        // Add some orders
        let o1 = book.create_order(Side::Buy, Price(100_00), 100, TimeInForce::GTC);
        let o2 = book.create_order(Side::Buy, Price(99_00), 100, TimeInForce::GTC);
        let o3 = book.create_order(Side::Sell, Price(101_00), 100, TimeInForce::GTC);
        let o1_id = o1.id;
        let o2_id = o2.id;
        let o3_id = o3.id;

        book.add_order(o1);
        book.add_order(o2);
        book.add_order(o3);

        assert_eq!(book.order_count(), 3);

        // Cancel one order (becomes inactive but stays in history)
        book.cancel_order(o1_id);
        assert_eq!(book.order_count(), 3);
        assert_eq!(book.active_order_count(), 2);

        // Clear history - should remove the cancelled order
        let removed = book.clear_history();
        assert_eq!(removed, 1);
        assert_eq!(book.order_count(), 2);
        assert_eq!(book.active_order_count(), 2);

        // Cancelled order should no longer be accessible
        assert!(book.get_order(o1_id).is_none());
        // Active orders should still be there
        assert!(book.get_order(o2_id).is_some());
        assert!(book.get_order(o3_id).is_some());
    }
}