OrderBook

Struct OrderBook 

Source
pub struct OrderBook {
    pub instrument_id: InstrumentId,
    pub book_type: BookType,
    pub sequence: u64,
    pub ts_last: UnixNanos,
    pub update_count: u64,
    /* private fields */
}
Expand description

Provides a high-performance, versatile order book.

Maintains buy (bid) and sell (ask) orders in price-time priority, supporting multiple market data formats:

  • L3 (MBO): Market By Order - tracks individual orders with unique IDs.
  • L2 (MBP): Market By Price - aggregates orders at each price level.
  • L1 (MBP): Top-of-Book - maintains only the best bid and ask prices.

Fields§

§instrument_id: InstrumentId

The instrument ID for the order book.

§book_type: BookType

The order book type (MBP types will aggregate orders).

§sequence: u64

The last event sequence number for the order book.

§ts_last: UnixNanos

The timestamp of the last event applied to the order book.

§update_count: u64

The current count of updates applied to the order book.

Implementations§

Source§

impl OrderBook

Source

pub fn new(instrument_id: InstrumentId, book_type: BookType) -> Self

Creates a new OrderBook instance.

Source

pub fn reset(&mut self)

Resets the order book to its initial empty state.

Source

pub fn add( &mut self, order: BookOrder, flags: u8, sequence: u64, ts_event: UnixNanos, )

Adds an order to the book after preprocessing based on book type.

Source

pub fn update( &mut self, order: BookOrder, flags: u8, sequence: u64, ts_event: UnixNanos, )

Updates an existing order in the book after preprocessing based on book type.

Source

pub fn delete( &mut self, order: BookOrder, flags: u8, sequence: u64, ts_event: UnixNanos, )

Deletes an order from the book after preprocessing based on book type.

Source

pub fn clear(&mut self, sequence: u64, ts_event: UnixNanos)

Clears all orders from both sides of the book.

Source

pub fn clear_bids(&mut self, sequence: u64, ts_event: UnixNanos)

Clears all bid orders from the book.

Source

pub fn clear_asks(&mut self, sequence: u64, ts_event: UnixNanos)

Clears all ask orders from the book.

Source

pub fn clear_stale_levels( &mut self, side: Option<OrderSide>, ) -> Option<Vec<BookLevel>>

Removes overlapped bid/ask levels when the book is strictly crossed (best bid > best ask)

  • Acts only when both sides exist and the book is crossed.
  • Deletes by removing whole price levels via the ladder API to preserve invariants.
  • side=None or NoOrderSide clears both overlapped ranges (conservative, may widen spread).
  • side=Buy clears crossed bids only; side=Sell clears crossed asks only.
  • Returns removed price levels (crossed bids first, then crossed asks), or None if nothing removed.
Source

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

Applies a single order book delta operation.

§Errors

Returns an error if:

  • An Add is given with NoOrderSide (either explicitly or because the cache lookup failed).
  • After resolution the delta still has NoOrderSide but its action is not Clear.
Source

pub fn apply_deltas( &mut self, deltas: &OrderBookDeltas, ) -> Result<(), BookIntegrityError>

Applies multiple order book delta operations.

§Errors

Returns the first error encountered when applying deltas.

Source

pub fn apply_depth(&mut self, depth: &OrderBookDepth10)

Replaces current book state with a depth snapshot.

Source

pub fn bids(&self, depth: Option<usize>) -> impl Iterator<Item = &BookLevel>

Returns an iterator over bid price levels.

Source

pub fn asks(&self, depth: Option<usize>) -> impl Iterator<Item = &BookLevel>

Returns an iterator over ask price levels.

Source

pub fn bids_as_map(&self, depth: Option<usize>) -> IndexMap<Decimal, Decimal>

Returns bid price levels as a map of price to size.

Source

pub fn asks_as_map(&self, depth: Option<usize>) -> IndexMap<Decimal, Decimal>

Returns ask price levels as a map of price to size.

Source

pub fn group_bids( &self, group_size: Decimal, depth: Option<usize>, ) -> IndexMap<Decimal, Decimal>

Groups bid quantities by price into buckets, limited by depth.

Source

pub fn group_asks( &self, group_size: Decimal, depth: Option<usize>, ) -> IndexMap<Decimal, Decimal>

Groups ask quantities by price into buckets, limited by depth.

Source

pub fn bids_filtered_as_map( &self, depth: Option<usize>, own_book: Option<&OwnOrderBook>, status: Option<HashSet<OrderStatus>>, accepted_buffer_ns: Option<u64>, now: Option<u64>, ) -> IndexMap<Decimal, Decimal>

Maps bid prices to total public size per level, excluding own orders up to a depth limit.

With own_book, subtracts own order sizes, filtered by status if provided. Uses accepted_buffer_ns to include only orders accepted at least that many nanoseconds before now (defaults to now).

Source

pub fn asks_filtered_as_map( &self, depth: Option<usize>, own_book: Option<&OwnOrderBook>, status: Option<HashSet<OrderStatus>>, accepted_buffer_ns: Option<u64>, now: Option<u64>, ) -> IndexMap<Decimal, Decimal>

Maps ask prices to total public size per level, excluding own orders up to a depth limit.

With own_book, subtracts own order sizes, filtered by status if provided. Uses accepted_buffer_ns to include only orders accepted at least that many nanoseconds before now (defaults to now).

Source

pub fn group_bids_filtered( &self, group_size: Decimal, depth: Option<usize>, own_book: Option<&OwnOrderBook>, status: Option<HashSet<OrderStatus>>, accepted_buffer_ns: Option<u64>, now: Option<u64>, ) -> IndexMap<Decimal, Decimal>

Groups bid quantities into price buckets, truncating to a maximum depth, excluding own orders.

With own_book, subtracts own order sizes, filtered by status if provided. Uses accepted_buffer_ns to include only orders accepted at least that many nanoseconds before now (defaults to now).

Source

pub fn group_asks_filtered( &self, group_size: Decimal, depth: Option<usize>, own_book: Option<&OwnOrderBook>, status: Option<HashSet<OrderStatus>>, accepted_buffer_ns: Option<u64>, now: Option<u64>, ) -> IndexMap<Decimal, Decimal>

Groups ask quantities into price buckets, truncating to a maximum depth, excluding own orders.

With own_book, subtracts own order sizes, filtered by status if provided. Uses accepted_buffer_ns to include only orders accepted at least that many nanoseconds before now (defaults to now).

Source

pub fn has_bid(&self) -> bool

Returns true if the book has any bid orders.

Source

pub fn has_ask(&self) -> bool

Returns true if the book has any ask orders.

Source

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

Returns the best bid price if available.

Source

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

Returns the best ask price if available.

Source

pub fn best_bid_size(&self) -> Option<Quantity>

Returns the size at the best bid price if available.

Source

pub fn best_ask_size(&self) -> Option<Quantity>

Returns the size at the best ask price if available.

Source

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

Returns the spread between best ask and bid prices if both exist.

Source

pub fn midpoint(&self) -> Option<f64>

Returns the midpoint between best ask and bid prices if both exist.

Source

pub fn get_avg_px_for_quantity( &self, qty: Quantity, order_side: OrderSide, ) -> f64

Calculates the average price to fill the specified quantity.

Source

pub fn get_avg_px_qty_for_exposure( &self, target_exposure: Quantity, order_side: OrderSide, ) -> (f64, f64, f64)

Calculates average price and quantity for target exposure. Returns (price, quantity, executed_exposure).

Source

pub fn get_quantity_for_price(&self, price: Price, order_side: OrderSide) -> f64

Returns the total quantity available at specified price level.

Source

pub fn simulate_fills(&self, order: &BookOrder) -> Vec<(Price, Quantity)>

Simulates fills for an order, returning list of (price, quantity) tuples.

Source

pub fn pprint(&self, num_levels: usize, group_size: Option<Decimal>) -> String

Return a formatted string representation of the order book.

Source

pub fn update_quote_tick( &mut self, quote: &QuoteTick, ) -> Result<(), InvalidBookOperation>

Updates L1 book state from a quote tick. Only valid for L1_MBP book type.

§Errors

Returns an error if the book type is not L1_MBP (operation is invalid).

Source

pub fn update_trade_tick( &mut self, trade: &TradeTick, ) -> Result<(), InvalidBookOperation>

Updates L1 book state from a trade tick. Only valid for L1_MBP book type.

§Errors

Returns an error if the book type is not L1_MBP (operation is invalid).

Source§

impl OrderBook

Source

pub fn py_group_bids( &self, group_size: Decimal, depth: Option<usize>, ) -> IndexMap<Decimal, Decimal>

Source

pub fn py_group_asks( &self, group_size: Decimal, depth: Option<usize>, ) -> IndexMap<Decimal, Decimal>

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

impl Display for OrderBook

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<'py> IntoPyObject<'py> for OrderBook

Source§

type Target = OrderBook

The Python output type
Source§

type Output = Bound<'py, <OrderBook as IntoPyObject<'py>>::Target>

The smart pointer type to use. Read more
Source§

type Error = PyErr

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

fn into_pyobject( self, py: Python<'py>, ) -> Result<<Self as IntoPyObject<'_>>::Output, <Self as IntoPyObject<'_>>::Error>

Performs the conversion.
Source§

impl PartialEq for OrderBook

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl PyClass for OrderBook

Source§

type Frozen = False

Whether the pyclass is frozen. Read more
Source§

impl PyClassImpl for OrderBook

Source§

const IS_BASETYPE: bool = false

#[pyclass(subclass)]
Source§

const IS_SUBCLASS: bool = false

#[pyclass(extends=…)]
Source§

const IS_MAPPING: bool = false

#[pyclass(mapping)]
Source§

const IS_SEQUENCE: bool = false

#[pyclass(sequence)]
Source§

const IS_IMMUTABLE_TYPE: bool = false

#[pyclass(immutable_type)]
Source§

const RAW_DOC: &'static CStr = /// Provides a high-performance, versatile order book. /// /// Maintains buy (bid) and sell (ask) orders in price-time priority, supporting multiple /// market data formats: /// - L3 (MBO): Market By Order - tracks individual orders with unique IDs. /// - L2 (MBP): Market By Price - aggregates orders at each price level. /// - L1 (MBP): Top-of-Book - maintains only the best bid and ask prices.

Docstring for the class provided on the struct or enum. Read more
Source§

const DOC: &'static CStr

Fully rendered class doc, including the text_signature if a constructor is defined. Read more
Source§

type BaseType = PyAny

Base class
Source§

type ThreadChecker = SendablePyClass<OrderBook>

This handles following two situations: Read more
Source§

type PyClassMutability = <<PyAny as PyClassBaseType>::PyClassMutability as PyClassMutability>::MutableChild

Immutable or mutable
Source§

type Dict = PyClassDummySlot

Specify this class has #[pyclass(dict)] or not.
Source§

type WeakRef = PyClassDummySlot

Specify this class has #[pyclass(weakref)] or not.
Source§

type BaseNativeType = PyAny

The closest native ancestor. This is PyAny by default, and when you declare #[pyclass(extends=PyDict)], it’s PyDict.
Source§

fn items_iter() -> PyClassItemsIter

Source§

fn lazy_type_object() -> &'static LazyTypeObject<Self>

§

fn dict_offset() -> Option<isize>

§

fn weaklist_offset() -> Option<isize>

Source§

impl PyClassNewTextSignature for OrderBook

Source§

const TEXT_SIGNATURE: &'static str = "(instrument_id, book_type)"

Source§

impl PyMethods<OrderBook> for PyClassImplCollector<OrderBook>

Source§

fn py_methods(self) -> &'static PyClassItems

Source§

impl PyTypeInfo for OrderBook

Source§

const NAME: &'static str = "OrderBook"

Class name.
Source§

const MODULE: Option<&'static str>

Module name, if any.
Source§

fn type_object_raw(py: Python<'_>) -> *mut PyTypeObject

Returns the PyTypeObject instance for this type.
§

fn type_object(py: Python<'_>) -> Bound<'_, PyType>

Returns the safe abstraction over the type object.
§

fn is_type_of(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type or a subclass of this type.
§

fn is_exact_type_of(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of this type.
Source§

impl DerefToPyAny for OrderBook

Source§

impl Eq for OrderBook

Source§

impl ExtractPyClassWithClone for OrderBook

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
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<'a, 'py, T> FromPyObject<'a, 'py> for T
where T: PyClass + Clone + ExtractPyClassWithClone,

§

type Error = PyClassGuardError<'a, 'py>

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

fn extract( obj: Borrowed<'a, 'py, PyAny>, ) -> Result<T, <T as FromPyObject<'a, 'py>>::Error>

Extracts Self from the bound smart pointer obj. Read more
§

impl<T> Instrument for T

§

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

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

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
§

impl<'py, T> IntoPyObjectExt<'py> for T
where T: IntoPyObject<'py>,

§

fn into_bound_py_any(self, py: Python<'py>) -> Result<Bound<'py, PyAny>, PyErr>

Converts self into an owned Python object, dropping type information.
§

fn into_py_any(self, py: Python<'py>) -> Result<Py<PyAny>, PyErr>

Converts self into an owned Python object, dropping type information and unbinding it from the 'py lifetime.
§

fn into_pyobject_or_pyerr(self, py: Python<'py>) -> Result<Self::Output, PyErr>

Converts self into a Python object. Read more
Source§

impl<'py, T> IntoPyObjectNautilusExt<'py> for T
where T: IntoPyObjectExt<'py>,

Source§

fn into_py_any_unwrap(self, py: Python<'py>) -> Py<PyAny>

Convert self into a [Py<PyAny>] while panicking if the conversion fails. Read more
§

impl<T> PyErrArguments for T
where T: for<'py> IntoPyObject<'py> + Send + Sync,

§

fn arguments(self, py: Python<'_>) -> Py<PyAny>

Arguments for exception
§

impl<T> PyTypeCheck for T
where T: PyTypeInfo,

§

const NAME: &'static str = T::NAME

👎Deprecated since 0.27.0: Use ::classinfo_object() instead and format the type name at runtime. Note that using built-in cast features is often better than manual PyTypeCheck usage.
Name of self. This is used in error messages, for example.
§

fn type_check(object: &Bound<'_, PyAny>) -> bool

Checks if object is an instance of Self, which may include a subtype. Read more
§

fn classinfo_object(py: Python<'_>) -> Bound<'_, PyAny>

Returns the expected type as a possible argument for the isinstance and issubclass function. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Separable for T
where T: Display,

Source§

fn separate_by_policy(&self, policy: SeparatorPolicy<'_>) -> String

Adds separators according to the given SeparatorPolicy. Read more
Source§

fn separate_with_commas(&self) -> String

Inserts a comma every three digits from the right. Read more
Source§

fn separate_with_spaces(&self) -> String

Inserts a space every three digits from the right. Read more
Source§

fn separate_with_dots(&self) -> String

Inserts a period every three digits from the right. Read more
Source§

fn separate_with_underscores(&self) -> String

Inserts an underscore every three digits from the right. Read more
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> 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.
§

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

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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

impl<'py, T> FromPyObjectOwned<'py> for T
where T: for<'a> FromPyObject<'a, 'py>,

§

impl<T> Ungil for T
where T: Send,