order_book/
types.rs

1use rust_decimal::Decimal;
2use std::collections::BTreeMap;
3
4/// Represents the side of an order in the order book.
5///
6/// - `Bid` represents buy orders (demand side)
7/// - `Ask` represents sell orders (supply side)
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub enum Side {
10    /// Buy side: traders willing to purchase at a given price
11    Bid,
12    /// Sell side: traders willing to sell at a given price
13    Ask,
14}
15
16/// Represents a single order in the order book.
17///
18/// Each order contains a price, quantity, and side (bid or ask).
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct Order {
21    /// The price level at which this order is placed (using fixed-point arithmetic)
22    pub price: Decimal,
23    /// The quantity of the asset being bought or sold
24    pub quantity: u64,
25    /// Whether this is a buy (`Bid`) or sell (`Ask`) order
26    pub side: Side,
27}
28
29impl Order {
30    /// Creates a new order with the given price, quantity, and side.
31    pub fn new(price: f64, quantity: u64, side: Side) -> Self {
32        Self {
33            price: Decimal::try_from(price).unwrap(),
34            quantity,
35            side,
36        }
37    }
38}
39
40/// Represents an event published by the `OrderBook` when its state changes.
41///
42/// This event is consumed by downstream services (like `MarketDepthCache`) to update
43/// their own state without blocking the core order book operations.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct OrderEvent {
46    /// The exact price level where the change occurred
47    pub price: Decimal,
48    /// The change in quantity at this price level (positive for additions)
49    pub quantity_delta: u64,
50    /// Whether this event affects the bid or ask side
51    pub side: Side,
52}
53
54/// Type alias for a price level in the order book.
55///
56/// Maps each price (`Decimal`) to a list of orders at that price.
57/// Orders within a price level maintain time priority (FIFO).
58pub type ExactPriceLevelMap = BTreeMap<Decimal, Vec<Order>>;
59
60/// Type alias for aggregated market depth cache.
61///
62/// Maps each aggregated price level (`Decimal`) to the total quantity (`u64`)
63/// available at that level across all individual orders.
64pub type AggregatedDepthMap = BTreeMap<Decimal, u64>;