rust-order-book 0.0.2

A Rust Lmit Order Book for high-frequency trading (HFT).
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
//! Core module for the OrderBook engine.
//!
//! This module defines the [`OrderBook`] struct, which provides the main interface
//! for submitting, canceling, modifying, and querying orders.
//!
//! Use [`OrderBookBuilder`](crate::OrderBookBuilder) to create a new instance.
//!
//! # Example
//! ```rust
//! use rust_order_book::{OrderBookBuilder, Side, MarketOrderOptions};
//!
//! let mut ob = OrderBookBuilder::new("BTCUSD").with_journaling(true).build();
//!
//! let result = ob.market(MarketOrderOptions::new(Side::Buy, 10_000));
//! ```
use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::ops::{Add, Div, Sub};

use crate::enums::{JournalOp, OrderOptions};
use crate::journal::Snapshot;
use crate::order::{OrderId, Price, Quantity};
use crate::report::ExecutionReportParams;
use crate::utils::{current_timestamp_millis, safe_add};
use crate::{
    error::{make_error, ErrorType, Result},
    journal::JournalLog,
    order::{LimitOrder, LimitOrderOptions, MarketOrder, MarketOrderOptions},
    {OrderStatus, OrderType, Side, TimeInForce},
};
use crate::{ExecutionReport, FillReport};
use std::collections::VecDeque;

/// Configuration options for initializing a new [`OrderBook`].
///
/// # Fields
/// - `journaling`: If `true`, the order book will return a journal log for each operations.
///   Defaults to `false`.
/// - `snapshot`: A previously captured [`Snapshot`] representing the full state
///   of an order book at a given point in time.
/// - `replay_logs`: A vector of [`JournalLog`] entries to replay. Logs should ideally be in
///   chronological order (`op_id` ascending), but `replay_logs` will sort them internally.
#[derive(Debug, Clone, Default)]
pub struct OrderBookOptions {
    pub journaling: bool,
    pub snapshot: Option<Snapshot>,
    pub replay_logs: Option<Vec<JournalLog>>,
}

#[derive(Debug, PartialEq)]
pub struct Depth {
    pub asks: Vec<(Price, Quantity)>, // (price, volume)
    pub bids: Vec<(Price, Quantity)>, // (price, volume)
}

/// A limit order book implementation with support for market orders,
/// limit orders, cancellation, modification and real-time depth.
///
/// Use [`crate::OrderBookBuilder`] to create an instance with optional features
/// like journaling or snapshot restoration.
pub struct OrderBook {
    pub(crate) last_op: u64,
    pub(crate) symbol: String,
    pub(crate) next_order_id: OrderId,
    pub(crate) orders: HashMap<OrderId, LimitOrder>,
    pub(crate) asks: BTreeMap<Price, VecDeque<OrderId>>,
    pub(crate) bids: BTreeMap<Price, VecDeque<OrderId>>,
    pub(crate) journaling: bool,
}

impl OrderBook {
    /// Creates a new `OrderBook` instance with the given symbol and options.
    ///
    /// Prefer using [`crate::OrderBookBuilder`] for clarity and flexibility.
    ///
    /// # Parameters
    /// - `symbol`: Market symbol (e.g., `"BTCUSD"`)
    /// - `opts`: Configuration options (e.g., journaling, snapshot)
    ///
    /// # Example
    /// ```
    /// use rust_order_book::{OrderBook, OrderBookOptions};
    /// let ob = OrderBook::new("BTCUSD", OrderBookOptions::default());
    /// ```
    pub fn new(symbol: &str, opts: OrderBookOptions) -> Self {
        Self {
            symbol: symbol.to_string(),
            last_op: 0,
            next_order_id: OrderId(0),
            orders: HashMap::with_capacity(100_000),
            asks: BTreeMap::new(),
            bids: BTreeMap::new(),
            journaling: opts.journaling,
        }
    }

    /// Get the symbol of this order book
    pub fn symbol(&self) -> &str {
        &self.symbol
    }

    /// Executes a market order against the order book.
    ///
    /// The order will immediately match with the best available opposite orders
    /// until the quantity is filled or the book is exhausted.
    ///
    /// # Parameters
    /// - `options`: A [`MarketOrderOptions`] struct specifying the side and size.
    ///
    /// # Returns
    /// An [`ExecutionReport`] with fill information and remaining quantity, if any.
    ///
    /// # Errors
    /// Returns `Err` if the input is invalid (e.g., size is zero).
    pub fn market(&mut self, options: MarketOrderOptions) -> Result<ExecutionReport> {
        self.validate_market_order(&options)?;

        let mut order = MarketOrder::new(self.new_order_id(), options);
        let mut report = ExecutionReport::new(ExecutionReportParams {
            id: order.id,
            order_type: OrderType::Market,
            side: order.side,
            quantity: order.remaining_qty(),
            status: order.status,
            time_in_force: None,
            price: None,
            post_only: false,
        });

        let mut fills = Vec::new();
        let remaining_qty = match order.side {
            Side::Buy => self.match_with_asks(order.remaining_qty(), &mut fills, None),
            Side::Sell => self.match_with_bids(order.remaining_qty(), &mut fills, None),
        };
        order.executed_qty = order.orig_qty.sub(remaining_qty);
        order.status = if order.remaining_qty().value() > 0 {
            OrderStatus::PartiallyFilled
        } else {
            OrderStatus::Filled
        };

        report.remaining_qty = order.remaining_qty();
        report.executed_qty = order.executed_qty;
        report.status = order.status;
        report.taker_qty = order.executed_qty;

        if self.journaling {
            self.last_op = safe_add(self.last_op, 1);
            report.log = Some(JournalLog {
                op_id: self.last_op,
                ts: current_timestamp_millis(),
                op: JournalOp::Market,
                o: OrderOptions::Market(options),
            })
        }

        Ok(report)
    }
    pub fn market_raw(&mut self, side: Side, quantity: u64) -> Result<ExecutionReport> {
        self.market(MarketOrderOptions { side, quantity: Quantity(quantity) })
    }

    /// Submits a new limit order to the order book.
    ///
    /// The order will be matched partially or fully if opposing liquidity exists,
    /// otherwise it will rest in the book until matched or canceled.
    ///
    /// # Parameters
    /// - `options`: A [`LimitOrderOptions`] with side, price, size, time-in-force and post_only.
    ///
    /// # Returns
    /// An [`ExecutionReport`] with match information and resting status.
    ///
    /// # Errors
    /// Returns `Err` if the input is invalid.
    pub fn limit(&mut self, options: LimitOrderOptions) -> Result<ExecutionReport> {
        self.validate_limit_order(&options)?;

        let mut order = LimitOrder::new(self.new_order_id(), options);
        let mut report = ExecutionReport::new(ExecutionReportParams {
            id: order.id,
            order_type: OrderType::Limit,
            side: order.side,
            quantity: order.orig_qty,
            status: order.status,
            time_in_force: Some(order.time_in_force),
            price: Some(order.price), // here order price is Some because we have already validated in validate_limit_order
            post_only: order.post_only,
        });

        let mut fills = Vec::new();
        let remaining_qty = match order.side {
            Side::Buy => self.match_with_asks(order.remaining_qty(), &mut fills, Some(order.price)),
            Side::Sell => {
                self.match_with_bids(order.remaining_qty(), &mut fills, Some(order.price))
            }
        };
        order.executed_qty = order.orig_qty.sub(remaining_qty);
        order.taker_qty = order.orig_qty.sub(order.remaining_qty());
        order.maker_qty = order.remaining_qty();

        if order.remaining_qty().value() > 0 {
            if order.time_in_force == TimeInForce::IOC {
                // If IOC order was not matched completely so set as canceled
                // and don't insert the order in the order book
                order.status = OrderStatus::Canceled;
            } else {
                order.status = OrderStatus::PartiallyFilled;
                self.orders.insert(order.id, order);
                if order.side == Side::Buy {
                    self.bids.entry(order.price).or_default().push_back(order.id);
                } else {
                    self.asks.entry(order.price).or_default().push_back(order.id);
                }
            }
        } else {
            order.status = OrderStatus::Filled;
        }

        report.remaining_qty = order.remaining_qty();
        report.executed_qty = order.executed_qty;
        report.taker_qty = order.taker_qty;
        report.maker_qty = order.maker_qty;
        report.status = order.status;

        if self.journaling {
            self.last_op = safe_add(self.last_op, 1);
            report.log = Some(JournalLog {
                op_id: self.last_op,
                ts: current_timestamp_millis(),
                op: JournalOp::Limit,
                o: OrderOptions::Limit(options),
            })
        }

        Ok(report)
    }
    pub fn limit_raw(
        &mut self,
        side: Side,
        quantity: u64,
        price: u64,
        time_in_force: Option<TimeInForce>,
        post_only: Option<bool>,
    ) -> Result<ExecutionReport> {
        self.limit(LimitOrderOptions {
            side,
            quantity: Quantity(quantity),
            price: Price(price),
            time_in_force,
            post_only,
        })
    }

    /// Cancels an existing order by ID.
    ///
    /// # Parameters
    /// - `id`: UUID of the order to cancel
    ///
    /// # Returns
    /// An [`ExecutionReport`] with order info if successfully canceled.
    ///
    /// # Errors
    /// Returns `Err` if the order is not found.
    pub fn cancel(&mut self, id: OrderId) -> Result<ExecutionReport> {
        let mut order = match self.orders.remove(&id) {
            Some(o) => o,
            None => return Err(make_error(ErrorType::OrderNotFound)),
        };

        let book_side = match order.side {
            Side::Buy => &mut self.bids,
            Side::Sell => &mut self.asks,
        };

        if let Some(queue) = book_side.get_mut(&order.price) {
            if let Some(pos) = queue.iter().position(|x| *x == id) {
                queue.remove(pos);
            }
            if queue.is_empty() {
                book_side.remove(&order.price);
            }
        }

        order.status = OrderStatus::Canceled;

        let mut report = ExecutionReport {
            order_id: order.id,
            orig_qty: order.orig_qty,
            executed_qty: order.executed_qty,
            remaining_qty: order.remaining_qty(),
            taker_qty: order.taker_qty,
            maker_qty: order.maker_qty,
            order_type: order.order_type,
            side: order.side,
            price: order.price,
            status: order.status,
            time_in_force: order.time_in_force,
            post_only: order.post_only,
            fills: Vec::new(),
            log: None,
        };

        if self.journaling {
            self.last_op = safe_add(self.last_op, 1);
            report.log = Some(JournalLog {
                op_id: self.last_op,
                ts: current_timestamp_millis(),
                op: JournalOp::Cancel,
                o: OrderOptions::Cancel(order.id),
            })
        }

        Ok(report)
    }

    pub fn cancel_raw(&mut self, id: u64) -> Result<ExecutionReport> {
        self.cancel(OrderId(id))
    }

    /// Modifies an existing order by cancelling it and submitting a new one.
    ///
    /// This function cancels the existing order with the given ID and replaces it
    /// with a new one that has the updated price and/or quantity. The new order will
    /// receive a **new unique ID** and will be placed at the end of the queue,
    /// losing its original time priority.
    ///
    /// # Parameters
    /// - `id`: UUID of the existing order to modify
    /// - `price`: Optional new price
    /// - `quantity`: Optional new quantity
    ///
    /// # Returns
    /// An [`ExecutionReport`] describing the new order created.
    ///
    /// # Errors
    /// Returns `Err` if the order is not found or if the modification parameters are invalid.
    ///
    /// # Note
    /// This is a full replacement: time-priority is reset and the order ID changes.
    pub fn modify(
        &mut self,
        id: OrderId,
        price: Option<Price>,
        quantity: Option<Quantity>,
    ) -> Result<ExecutionReport> {
        let old_journaling = self.journaling;
        // Temporary disable journaling
        self.journaling = false;
        let report = match self.cancel(id) {
            Ok(o) => o,
            Err(e) => {
                // Restore previous journaling value before returning
                self.journaling = old_journaling;
                return Err(e);
            }
        };

        let mut report = match (price, quantity) {
            (None, Some(quantity)) => self.limit(LimitOrderOptions {
                side: report.side,
                quantity,
                price: report.price,
                time_in_force: Some(report.time_in_force),
                post_only: Some(report.post_only),
            }),
            (Some(price), None) => self.limit(LimitOrderOptions {
                side: report.side,
                quantity: report.remaining_qty,
                price,
                time_in_force: Some(report.time_in_force),
                post_only: Some(report.post_only),
            }),
            (Some(price), Some(quantity)) => self.limit(LimitOrderOptions {
                side: report.side,
                quantity,
                price,
                time_in_force: Some(report.time_in_force),
                post_only: Some(report.post_only),
            }),
            (None, None) => {
                // Restore previous journaling value before returning
                self.journaling = old_journaling;
                return Err(make_error(ErrorType::InvalidPriceOrQuantity));
            }
        };

        // Restore previous journaling value
        self.journaling = old_journaling;

        if let Ok(r) = report.as_mut() {
            if self.journaling {
                self.last_op = safe_add(self.last_op, 1);
                r.log = Some(JournalLog {
                    op_id: self.last_op,
                    ts: current_timestamp_millis(),
                    op: JournalOp::Modify,
                    o: OrderOptions::Modify { id, price, quantity },
                });
            }
        }
        report
    }

    pub fn modify_raw(
        &mut self,
        id: u64,
        price: Option<u64>,
        quantity: Option<u64>,
    ) -> Result<ExecutionReport> {
        self.modify(OrderId(id), price.map(Price), quantity.map(Quantity))
    }

    /// Get all orders at a specific price level
    pub fn get_orders_at_price(&self, price: Price, side: Side) -> Vec<LimitOrder> {
        let mut orders = Vec::new();
        let queue = match side {
            Side::Buy => self.bids.get(&price),
            Side::Sell => self.asks.get(&price),
        };

        if let Some(q) = queue {
            for id in q {
                if let Some(order) = self.orders.get(id) {
                    orders.push(*order);
                }
            }
        }
        orders
    }

    pub fn get_order(&self, id: OrderId) -> Result<LimitOrder> {
        match self.orders.get(&id) {
            Some(o) => Ok(*o),
            None => Err(make_error(ErrorType::OrderNotFound)),
        }
    }

    /// Get the best bid price, if any
    pub fn best_bid(&self) -> Option<Price> {
        self.bids.last_key_value().map(|(price, _)| *price)
    }

    /// Get the best ask price, if any
    pub fn best_ask(&self) -> Option<Price> {
        self.asks.first_key_value().map(|(price, _)| *price)
    }

    /// Get the mid price (average of best bid and best ask)
    pub fn mid_price(&self) -> Option<Price> {
        match (self.best_bid(), self.best_ask()) {
            (Some(bid), Some(ask)) => Some(bid.add(ask).div(Price(2))),
            _ => None,
        }
    }

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

    /// Creates a complete snapshot of the current order book state.
    ///
    /// The snapshot includes all internal data necessary to fully restore the order book:
    /// - `orders`: a mapping of `OrderId` to `LimitOrder`
    /// - `bids` and `asks`: BTreeMaps representing the price levels and associated order IDs
    /// - `last_op`: the ID of the last operation performed
    /// - `next_order_id`: the next available order ID
    /// - `ts`: a timestamp representing when the snapshot was taken
    ///
    /// This function **does not fail** and can be called at any time.
    /// It returns a [`Snapshot`] struct, which can later be used with [`OrderBook::restore_snapshot`]
    /// to recreate the order book state exactly as it was at the moment of the snapshot.
    pub fn snapshot(&self) -> Snapshot {
        Snapshot {
            orders: self.orders.clone(),
            bids: self.bids.clone(),
            asks: self.asks.clone(),
            last_op: self.last_op,
            next_order_id: self.next_order_id,
            ts: current_timestamp_millis(),
        }
    }

    /// Restores the internal state of this [`OrderBook`] from a given [`Snapshot`].
    ///
    /// This replaces any existing orders and it is typically used when reconstructing
    /// an order book from persistent storage.
    ///
    /// # Parameters
    /// - `snapshot`: The snapshot to load into the order book.
    pub fn restore_snapshot(&mut self, snapshot: Snapshot) {
        self.orders = snapshot.orders;
        self.bids = snapshot.bids;
        self.asks = snapshot.asks;
        self.last_op = snapshot.last_op;
        self.next_order_id = snapshot.next_order_id;
    }

    /// Replays a sequence of journal logs to reconstruct the order book state.
    ///
    /// Each log entry represents a previously executed operation, such as a market order,
    /// limit order, cancel, or modify. This function applies each operation in order.
    ///
    /// # Parameters
    ///
    /// - `logs`: A vector of [`JournalLog`] entries to be applied. Logs must be in chronological
    ///   order to correctly reconstruct the state.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if all operations are successfully applied.
    /// Returns `Err(OrderBookError)` if any operation fails; the replay stops at the first error.
    pub fn replay_logs(&mut self, mut logs: Vec<JournalLog>) -> Result<()> {
        // sort logs by op_id ascending
        logs.sort_by_key(|log| log.op_id);

        for log in &logs {
            match &log.o {
                OrderOptions::Market(opts) => self.market(*opts)?,
                OrderOptions::Limit(opts) => self.limit(*opts)?,
                OrderOptions::Cancel(id) => self.cancel(*id)?,
                OrderOptions::Modify { id, price, quantity } => {
                    self.modify(*id, *price, *quantity)?
                }
            };
        }
        Ok(())
    }

    /// Returns the current depth of the order book.
    ///
    /// The depth includes aggregated quantities at each price level
    /// for both the bid and ask sides.
    ///
    /// # Parameters
    /// - `limit`: Optional maximum number of price levels per side
    ///
    /// # Returns
    /// A [`Depth`] struct containing the order book snapshot.
    pub fn depth(&self, limit: Option<usize>) -> Depth {
        let levels = limit.unwrap_or(100);
        Depth {
            asks: self.get_asks_prices_and_volume(levels),
            bids: self.get_bids_prices_and_volume(levels),
        }
    }

    fn get_asks_prices_and_volume(&self, levels: usize) -> Vec<(Price, Quantity)> {
        let mut asks = Vec::with_capacity(levels);
        for (ask_price, queue) in self.asks.iter() {
            let volume: Quantity = queue
                .iter()
                .filter_map(|id| self.orders.get(id))
                .map(|order| order.remaining_qty())
                .sum();
            asks.push((*ask_price, volume));
        }
        asks
    }

    fn get_bids_prices_and_volume(&self, levels: usize) -> Vec<(Price, Quantity)> {
        let mut bids = Vec::with_capacity(levels);
        for (bid_price, queue) in self.bids.iter().rev() {
            let volume: Quantity = queue
                .iter()
                .filter_map(|id| self.orders.get(id))
                .map(|order| order.remaining_qty())
                .sum();
            bids.push((*bid_price, volume));
        }
        bids
    }

    fn match_with_asks(
        &mut self,
        quantity_to_fill: Quantity,
        fills: &mut Vec<FillReport>,
        limit_price: Option<Price>,
    ) -> Quantity {
        // Early exit if the side is empty
        if self.asks.is_empty() {
            return quantity_to_fill;
        }
        let mut remaining_qty = quantity_to_fill;
        let mut filled_prices = Vec::new();
        for (ask_price, queue) in self.asks.iter_mut() {
            if remaining_qty.value() == 0 {
                break;
            }
            if let Some(limit_price) = limit_price {
                if limit_price < *ask_price {
                    break;
                }
            }
            remaining_qty = Self::process_queue(&mut self.orders, queue, remaining_qty, fills);
            if queue.is_empty() {
                filled_prices.push(*ask_price);
            }
        }
        for price in filled_prices {
            self.asks.remove(&price);
        }
        remaining_qty
    }

    fn match_with_bids(
        &mut self,
        quantity_to_fill: Quantity,
        fills: &mut Vec<FillReport>,
        limit_price: Option<Price>,
    ) -> Quantity {
        // Early exit if the side is empty
        if self.bids.is_empty() {
            return quantity_to_fill;
        }
        let mut remaining_qty = quantity_to_fill;
        let mut filled_prices = Vec::new();
        for (bid_price, queue) in self.bids.iter_mut().rev() {
            if remaining_qty.value() == 0 {
                break;
            }
            if let Some(limit_price) = limit_price {
                if limit_price > *bid_price {
                    break;
                }
            }
            remaining_qty = Self::process_queue(&mut self.orders, queue, remaining_qty, fills);
            if queue.is_empty() {
                filled_prices.push(*bid_price);
            }
        }
        for price in filled_prices {
            self.bids.remove(&price);
        }
        remaining_qty
    }

    fn process_queue(
        orders: &mut HashMap<OrderId, LimitOrder>,
        order_queue: &mut VecDeque<OrderId>,
        remaining_qty: Quantity,
        fills: &mut Vec<FillReport>,
    ) -> Quantity {
        let mut quantity_left = remaining_qty;
        while !order_queue.is_empty() && quantity_left.value() > 0 {
            let Some(head_order_uuid) = order_queue.front() else { break };
            let Some(mut head_order) = orders.remove(head_order_uuid) else { break };

            if quantity_left < head_order.remaining_qty() {
                head_order.executed_qty = head_order.executed_qty.add(quantity_left);
                head_order.status = OrderStatus::PartiallyFilled;
                fills.push(FillReport {
                    order_id: head_order.id,
                    price: head_order.price,
                    quantity: quantity_left,
                    status: head_order.status,
                });
                orders.insert(head_order.id, head_order);

                quantity_left = Quantity(0);
            } else {
                order_queue.pop_front();
                quantity_left = quantity_left.sub(head_order.remaining_qty());

                head_order.executed_qty = head_order.executed_qty.add(head_order.remaining_qty());
                head_order.status = OrderStatus::Filled;
                fills.push(FillReport {
                    order_id: head_order.id,
                    price: head_order.price,
                    quantity: head_order.executed_qty,
                    status: head_order.status,
                });
            }
        }
        quantity_left
    }

    fn validate_market_order(&self, options: &MarketOrderOptions) -> Result<()> {
        if options.quantity.value() == 0 {
            return Err(make_error(ErrorType::InvalidQuantity));
        }
        if (options.side == Side::Buy && self.asks.is_empty())
            || (options.side == Side::Sell && self.bids.is_empty())
        {
            return Err(make_error(ErrorType::OrderBookEmpty));
        }
        Ok(())
    }

    fn validate_limit_order(&self, options: &LimitOrderOptions) -> Result<()> {
        if options.quantity.value() == 0 {
            return Err(make_error(ErrorType::InvalidQuantity));
        }
        if options.price.value() == 0 {
            return Err(make_error(ErrorType::InvalidPrice));
        }
        let time_in_force = options.time_in_force.unwrap_or(TimeInForce::GTC);
        if time_in_force == TimeInForce::FOK
            && !self.limit_order_is_fillable(options.side, options.quantity, options.price)
        {
            return Err(make_error(ErrorType::OrderFOK));
        }
        if options.post_only.unwrap_or(false) {
            let crosses = match options.side {
                Side::Buy => {
                    if let Some((best_ask, _)) = self.asks.first_key_value() {
                        options.price >= *best_ask
                    } else {
                        false
                    }
                }
                Side::Sell => {
                    if let Some((best_bid, _)) = self.bids.last_key_value() {
                        options.price <= *best_bid
                    } else {
                        false
                    }
                }
            };

            if crosses {
                return Err(make_error(ErrorType::OrderPostOnly));
            }
        }
        Ok(())
    }

    fn limit_order_is_fillable(&self, side: Side, quantity: Quantity, price: Price) -> bool {
        if side == Side::Buy {
            self.limit_buy_order_is_fillable(quantity, price)
        } else {
            self.limit_sell_order_is_fillable(quantity, price)
        }
    }

    fn limit_buy_order_is_fillable(&self, quantity: Quantity, price: Price) -> bool {
        let mut cumulative_qty = Quantity(0);
        for (ask_price, queue) in self.asks.iter() {
            if price >= *ask_price && cumulative_qty < quantity {
                for id in queue.iter() {
                    if let Some(order) = self.orders.get(id) {
                        cumulative_qty += order.remaining_qty().value();
                    }
                }
            } else {
                break;
            }
        }
        cumulative_qty >= quantity
    }

    fn limit_sell_order_is_fillable(&self, quantity: Quantity, price: Price) -> bool {
        let mut cumulative_qty = Quantity(0);
        for (bid_price, queue) in self.bids.iter().rev() {
            if price <= *bid_price && cumulative_qty < quantity {
                for id in queue.iter() {
                    if let Some(order) = self.orders.get(id) {
                        cumulative_qty += order.remaining_qty().value()
                    }
                }
            } else {
                break;
            }
        }
        cumulative_qty >= quantity
    }

    fn new_order_id(&mut self) -> OrderId {
        let id = self.next_order_id;
        self.next_order_id += 1;
        id
    }
}

impl fmt::Display for OrderBook {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // --- ASKs ---
        for (price, order_ids) in self.asks.iter().rev() {
            let volume: Quantity = order_ids
                .iter()
                .filter_map(|id| self.orders.get(id))
                .map(|order| order.remaining_qty())
                .sum();

            writeln!(f, "{} -> {}", price.value(), volume.value())?;
        }

        writeln!(f, "------------------------------------")?;

        // --- BIDs ---
        for (price, order_ids) in self.bids.iter().rev() {
            let volume: Quantity = order_ids
                .iter()
                .filter_map(|id| self.orders.get(id))
                .map(|order| order.remaining_qty())
                .sum();

            writeln!(f, "{} -> {}", price.value(), volume.value())?;
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests;