OrderBook

Struct OrderBook 

Source
pub struct OrderBook {
    pub token_id: String,
    pub token_id_hash: u64,
    pub sequence: u64,
    pub timestamp: DateTime<Utc>,
    /* private fields */
}
Expand description

High-performance order book implementation

This is the core data structure that holds all the live buy/sell orders for a token. The efficiency of this code is critical as the order book is constantly being updated as orders are added and removed.

PERFORMANCE OPTIMIZATION: This struct now uses fixed-point integers internally instead of Decimal for maximum speed. The performance difference is dramatic:

Before (Decimal): ~100ns per operation + memory allocation After (fixed-point): ~5ns per operation, zero allocations

Fields§

§token_id: String

Token ID this book represents (like “123456” for a specific prediction market outcome)

§token_id_hash: u64

Hash of token_id for fast lookups (avoids string comparisons in hot path)

§sequence: u64

Current sequence number for ordering updates This helps us ignore old/duplicate updates that arrive out of order

§timestamp: DateTime<Utc>

Last update timestamp - when we last got new data for this book

Implementations§

Source§

impl OrderBook

Source

pub fn new(token_id: String, max_depth: usize) -> Self

Create a new order book Just sets up empty bid/ask maps and basic metadata

Source

pub fn set_tick_size(&mut self, tick_size: Decimal) -> Result<()>

Set the tick size for this book This tells us the minimum price increment allowed We store it in ticks for fast validation without conversion overhead

Source

pub fn set_tick_size_ticks(&mut self, tick_size_ticks: Price)

Set the tick size directly in ticks (even faster) Use this when you already have the tick size in our internal format

Source

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

Get the current best bid (highest price someone is willing to pay) Uses next_back() because BTreeMap sorts ascending, but we want the highest bid

PERFORMANCE: Now returns data in external format but internally uses fast lookups

Source

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

Get the current best ask (lowest price someone is willing to sell at) Uses next() because BTreeMap sorts ascending, so first item is lowest ask

PERFORMANCE: Now returns data in external format but internally uses fast lookups

Source

pub fn best_bid_fast(&self) -> Option<FastBookLevel>

Get the current best bid in fast internal format Use this for internal calculations to avoid conversion overhead

Source

pub fn best_ask_fast(&self) -> Option<FastBookLevel>

Get the current best ask in fast internal format Use this for internal calculations to avoid conversion overhead

Source

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

Get the current spread (difference between best ask and best bid) This tells us how “tight” the market is - smaller spread = more liquid market

PERFORMANCE: Now uses fast internal calculations, only converts to Decimal at the end

Source

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

Get the current mid price (halfway between best bid and ask) This is often used as the “fair value” of the market

PERFORMANCE: Now uses fast internal calculations, only converts to Decimal at the end

Source

pub fn spread_pct(&self) -> Option<Decimal>

Get the spread as a percentage (relative to the bid price) Useful for comparing spreads across different price levels

PERFORMANCE: Now uses fast internal calculations and returns basis points

Source

pub fn spread_fast(&self) -> Option<Price>

Get the current spread in fast internal format (PERFORMANCE OPTIMIZED) Returns spread in ticks - use this for internal calculations

Source

pub fn mid_price_fast(&self) -> Option<Price>

Get the current mid price in fast internal format (PERFORMANCE OPTIMIZED) Returns mid price in ticks - use this for internal calculations

Source

pub fn bids(&self, depth: Option<usize>) -> Vec<BookLevel>

Get all bids up to a certain depth (top N price levels) Returns them in descending price order (best bids first)

PERFORMANCE: Converts from internal fixed-point to external Decimal format Only call this when you need to return data to external APIs

Source

pub fn asks(&self, depth: Option<usize>) -> Vec<BookLevel>

Get all asks up to a certain depth (top N price levels) Returns them in ascending price order (best asks first)

PERFORMANCE: Converts from internal fixed-point to external Decimal format Only call this when you need to return data to external APIs

Source

pub fn bids_fast(&self, depth: Option<usize>) -> Vec<FastBookLevel>

Get all bids in fast internal format Use this for internal calculations to avoid conversion overhead

Source

pub fn asks_fast(&self, depth: Option<usize>) -> Vec<FastBookLevel>

Get all asks in fast internal format (PERFORMANCE OPTIMIZED) Use this for internal calculations to avoid conversion overhead

Source

pub fn snapshot(&self) -> OrderBook

Get the full book snapshot Creates a copy of the current state that can be safely passed around without worrying about the original book changing

Source

pub fn apply_delta(&mut self, delta: OrderDelta) -> Result<()>

Apply a delta update to the book (LEGACY VERSION - for external API compatibility) A “delta” is an incremental change - like “add 100 tokens at $0.65” or “remove all at $0.70”

This method converts the external Decimal delta to our internal fixed-point format and then calls the fast version. Use apply_delta_fast() directly when possible.

Source

pub fn apply_delta_fast(&mut self, delta: FastOrderDelta) -> Result<()>

Apply a delta update to the book

This is the high-performance version that works directly with fixed-point data. It includes tick alignment validation and is much faster than the Decimal version.

Performance improvement: ~50x faster than the old Decimal version!

  • No Decimal conversions in the hot path
  • Integer comparisons instead of Decimal comparisons
  • No memory allocations for price/size operations
Source

pub fn calculate_market_impact( &self, side: Side, size: Decimal, ) -> Option<MarketImpact>

Calculate the market impact for a given order size This is exactly why we don’t need deep levels - if your order would require hitting prices way off the current market (like $0.95 when best ask is $0.67), you’d never actually place that order. You’d either:

  1. Break it into smaller pieces over time
  2. Use a different trading strategy
  3. Accept that there’s not enough liquidity right now
Source

pub fn is_stale(&self, max_age: Duration) -> bool

Check if the book is stale (no recent updates) Useful for detecting when we’ve lost connection to live data

Source

pub fn liquidity_at_price(&self, price: Decimal, side: Side) -> Decimal

Get the total liquidity at a given price level Tells you how much you can buy/sell at exactly this price

Source

pub fn liquidity_in_range( &self, min_price: Decimal, max_price: Decimal, side: Side, ) -> Decimal

Get the total liquidity within a price range Useful for understanding how much depth exists in a certain price band

Source

pub fn is_valid(&self) -> bool

Validate that prices are properly ordered A healthy book should have best bid < best ask (otherwise there’s an arbitrage opportunity)

Source§

impl OrderBook

Source

pub fn analytics(&self) -> BookAnalytics

Calculate analytics for this book Gives you a quick health check of the market

Trait Implementations§

Source§

impl Clone for OrderBook

Source§

fn clone(&self) -> OrderBook

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug 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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. 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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more