OrderBook

Struct OrderBook 

Source
pub struct OrderBook { /* private fields */ }
Expand description

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.

Implementations§

Source§

impl OrderBook

Source

pub fn new(symbol: &str, opts: OrderBookOptions) -> Self

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());
Source

pub fn symbol(&self) -> &str

Get the symbol of this order book

Source

pub fn market( &mut self, options: MarketOrderOptions, ) -> Result<ExecutionReport, OrderBookError>

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
§Returns

An ExecutionReport with fill information and remaining quantity, if any.

§Errors

Returns Err if the input is invalid (e.g., size is zero).

Source

pub fn limit( &mut self, options: LimitOrderOptions, ) -> Result<ExecutionReport, OrderBookError>

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
§Returns

An ExecutionReport with match information and resting status.

§Errors

Returns Err if the input is invalid.

Source

pub fn cancel(&mut self, id: u64) -> Result<ExecutionReport, OrderBookError>

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.

Source

pub fn modify( &mut self, id: u64, price: Option<u64>, quantity: Option<u64>, ) -> Result<ExecutionReport, OrderBookError>

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.

Source

pub fn get_orders_at_price(&self, price: u64, side: Side) -> Vec<LimitOrder>

Get all orders at a specific price level

Source

pub fn get_order(&self, id: u64) -> Result<LimitOrder, OrderBookError>

Source

pub fn best_bid(&self) -> Option<u64>

Get the best bid price, if any

Source

pub fn best_ask(&self) -> Option<u64>

Get the best ask price, if any

Source

pub fn mid_price(&self) -> Option<u64>

Get the mid price (average of best bid and best ask)

Source

pub fn spread(&self) -> Option<u64>

Get the spread (best ask - best bid)

Source

pub fn snapshot(&self) -> Snapshot

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.

Source

pub fn restore_snapshot(&mut self, snapshot: Snapshot)

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.
Source

pub fn replay_logs( &mut self, logs: Vec<JournalLog>, ) -> Result<(), OrderBookError>

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.

Source

pub fn depth(&self, limit: Option<usize>) -> Depth

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.

Trait Implementations§

Source§

impl Display for OrderBook

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.