Skip to main content

Book

Struct Book 

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

A single-instrument limit order book on one tick grid.

Implementations§

Source§

impl Book

Source

pub fn capture_snapshot_state(&self) -> SnapshotState

Capture the complete structural state of this book for persistence. Live orders are reported in ascending slot order; the free list is reported exactly, head and per-slot links, so a restore allocates slots in the same order this book would have.

Source

pub fn from_snapshot_state(state: SnapshotState) -> Result<Self, BookError>

Rebuild a book from a captured state. Every structural invariant (configuration, sequence number, section lengths, generations, live record bounds and uniqueness, free-list exactness and cycle-freedom, symmetric acyclic level lists, exact level aggregates, single side per level, and an uncrossed book) is validated unconditionally in both debug and release builds before returning the rebuilt book.

§Errors

Returns BookError::InvalidConfig when the state’s own configuration fails validation, BookError::LookupCapacityFull if the lookup load cap is exceeded, and BookError::InvalidSnapshot when any structural invariant of SnapshotState fails.

Source§

impl Book

Source

pub fn new(config: BookConfig) -> Result<Self, BookError>

Build an empty book.

§Examples
use chronicle_core::{Book, BookConfig, StpPolicy};

let book = Book::new(BookConfig {
    max_orders: 16,
    grid_len: 640,
    tick_size: 1,
    grid_start_tick: 1,
    default_stp: StpPolicy::CancelIncoming,
})
.unwrap();
assert_eq!(book.live_order_count(), 0);
assert_eq!(book.best_bid(), None);
§Errors

Returns BookError::InvalidConfig when the configuration fails any rule in ARCHITECTURE.md section 3.2.

Source

pub const fn config(&self) -> BookConfig

The configuration this book was built with.

Source

pub const fn live_order_count(&self) -> u32

Number of live orders.

Source

pub const fn free_order_count(&self) -> u32

Number of arena slots currently available on the free list.

Accounts for any slots permanently retired on generation overflow (INV-ARENA-4), so callers can inspect exact remaining resting capacity in O(1).

Source

pub const fn next_seq(&self) -> u64

Sequence number the next accepted command will take.

Source

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

Best bid as (price, aggregate qty), or None when no bid rests.

Source

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

Best ask as (price, aggregate qty), or None when no ask rests.

Source

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

Current top-of-book spread (best_ask - best_bid) in quote units, or None when either side is empty.

Source

pub fn contains_order(&self, order_id: OrderId) -> bool

True when order_id currently rests live on the book.

Source

pub fn get_order(&self, order_id: OrderId) -> Option<OrderInfo>

Look up one live resting order by id in O(1) without allocating.

§Examples
use chronicle_core::{
    Book, BookConfig, EventBuffer, ExecutionEvent, OrderId, OrderInfo, OrderType,
    ParticipantId, Side, StpPolicy,
};

let mut book = Book::new(BookConfig {
    max_orders: 16,
    grid_len: 640,
    tick_size: 1,
    grid_start_tick: 1,
    default_stp: StpPolicy::CancelIncoming,
})
.unwrap();
let mut storage: Vec<ExecutionEvent> = Vec::with_capacity(8);
let mut events = EventBuffer::new(&mut storage);
book.add_order(
    OrderId(7),
    ParticipantId(2),
    Side::Bid,
    OrderType::Limit,
    100,
    15,
    None,
    &mut events,
)
.unwrap();
assert_eq!(
    book.get_order(OrderId(7)),
    Some(OrderInfo {
        order_id: OrderId(7),
        participant: ParticipantId(2),
        side: Side::Bid,
        price: 100,
        qty: 15,
    })
);
assert_eq!(book.get_order(OrderId(999)), None);
Source

pub fn level_at( &self, price: u64, ) -> Result<Option<(Side, DepthLevel)>, BookError>

Query the aggregated side and L2 summary at price, returning Ok(None) when the price is on-grid and currently empty.

§Errors

Returns BookError::InvalidPriceTick when price is not on the configured tick grid.

Source

pub fn orders_at(&self, price: u64) -> Result<OrdersAt<'_>, BookError>

Return a zero-allocation FIFO iterator over the resting orders at price, from oldest (head) to newest (tail).

§Errors

Returns BookError::InvalidPriceTick when price is not on the configured tick grid.

Source

pub fn add_order( &mut self, order_id: OrderId, participant: ParticipantId, side: Side, order_type: OrderType, price: u64, qty: u64, stp: Option<StpPolicy>, events: &mut EventBuffer<'_>, ) -> Result<usize, BookError>

Add an order. The order sweeps the opposite side in price-time priority under its self-trade prevention policy (stp, falling back to the book default when None), then the order type decides the remainder: Limit rests it, Ioc expires it, Fok was already proven fillable in preflight, and PostOnly rests in full because preflight proved it does not cross.

Returns the number of events written into events.

§Examples
use chronicle_core::{
    Book, BookConfig, EventBuffer, ExecutionEvent, OrderId, OrderType, ParticipantId,
    Side, StpPolicy,
};

let mut book = Book::new(BookConfig {
    max_orders: 16,
    grid_len: 640,
    tick_size: 1,
    grid_start_tick: 1,
    default_stp: StpPolicy::CancelIncoming,
})
.unwrap();
let mut storage = Vec::with_capacity(8);
let mut events = EventBuffer::new(&mut storage);
let written = book
    .add_order(
        OrderId(1),
        ParticipantId(1),
        Side::Bid,
        OrderType::Limit,
        100,
        10,
        None,
        &mut events,
    )
    .unwrap();
assert_eq!(written, 1);
assert!(matches!(storage[0], ExecutionEvent::Accepted { .. }));
assert_eq!(book.best_bid(), Some((100, 10)));
§Errors

Returns a BookError before mutating anything when validation or preflight fails: invalid or duplicate order id, zero quantity, invalid price tick, capacity, a PostOnly price that would cross, a Fok quantity the book cannot fill, or an event buffer below the exact preflight bound.

Source

pub fn cancel_order( &mut self, order_id: OrderId, events: &mut EventBuffer<'_>, ) -> Result<usize, BookError>

Cancel a live order by id.

Returns the number of events written into events (one Cancelled event on success).

§Examples
use chronicle_core::{
    Book, BookConfig, CancelReason, EventBuffer, ExecutionEvent, OrderId, OrderType,
    ParticipantId, Side, StpPolicy,
};

let mut book = Book::new(BookConfig {
    max_orders: 16,
    grid_len: 640,
    tick_size: 1,
    grid_start_tick: 1,
    default_stp: StpPolicy::CancelIncoming,
})
.unwrap();
let mut storage: Vec<ExecutionEvent> = Vec::with_capacity(8);
let mut events = EventBuffer::new(&mut storage);
book.add_order(
    OrderId(1),
    ParticipantId(1),
    Side::Bid,
    OrderType::Limit,
    100,
    10,
    None,
    &mut events,
)
.unwrap();
events.clear();
book.cancel_order(OrderId(1), &mut events).unwrap();
assert_eq!(
    events.written(),
    &[ExecutionEvent::Cancelled {
        seq: 2,
        order_id: OrderId(1),
        reason: CancelReason::Requested,
    }]
);
assert_eq!(book.live_order_count(), 0);
§Errors

Returns BookError::OrderNotFound with no side effects when the id is missing, filled, or already cancelled, and BookError::EventBufferFull when the buffer has no free slot.

Source

pub fn cancel_by_participant( &mut self, participant: ParticipantId, events: &mut EventBuffer<'_>, ) -> Result<usize, BookError>

Cancel every live order belonging to one participant (ARCHITECTURE.md section 7.8). Events are emitted in ascending slot order, one Cancelled with reason CancelReason::ByParticipant per order. A participant with no live orders succeeds with zero events; the command still consumes a sequence number, as every accepted command does.

Returns the number of events written into events.

§Errors

Returns BookError::EventBufferFull before mutating anything when the buffer holds fewer free slots than the participant has live orders.

Source

pub fn amend_order( &mut self, order_id: OrderId, new_price: u64, new_qty: u64, events: &mut EventBuffer<'_>, ) -> Result<usize, BookError>

Amend a live order to a new price and a new remaining quantity (ARCHITECTURE.md section 7.4). A smaller quantity at the same price, or an identical price and quantity, preserves the order’s exact FIFO position; a larger quantity or any price change moves it to the tail of the target level. An amend never triggers a match. Every accepted amend emits one Amended event and consumes one sequence number, including the identical no-op.

Returns the number of events written into events (one on success).

§Examples
use chronicle_core::{
    Book, BookConfig, EventBuffer, ExecutionEvent, OrderId, OrderType, ParticipantId,
    Side, StpPolicy,
};

let mut book = Book::new(BookConfig {
    max_orders: 16,
    grid_len: 640,
    tick_size: 1,
    grid_start_tick: 1,
    default_stp: StpPolicy::CancelIncoming,
})
.unwrap();
let mut storage: Vec<ExecutionEvent> = Vec::with_capacity(8);
let mut events = EventBuffer::new(&mut storage);
book.add_order(
    OrderId(1),
    ParticipantId(1),
    Side::Bid,
    OrderType::Limit,
    100,
    10,
    None,
    &mut events,
)
.unwrap();
events.clear();
book.amend_order(OrderId(1), 101, 6, &mut events).unwrap();
assert_eq!(book.best_bid(), Some((101, 6)));
§Errors

Returns BookError::OrderNotFound when the id is not live, BookError::InvalidPriceTick or BookError::InvalidQuantity for an off-grid price or a zero quantity, BookError::AmendWouldCross when the new price would leave the book crossed, and BookError::EventBufferFull when the buffer has no free slot. Every error is returned before any mutation.

Source

pub fn depth( &self, side: Side, max_levels: usize, out: &mut [DepthLevel], ) -> usize

Write up to max_levels aggregated levels for one side into out, best price first, and return how many were written. Mutates nothing and allocates nothing.

§Examples
use chronicle_core::{
    Book, BookConfig, DepthLevel, EventBuffer, ExecutionEvent, OrderId, OrderType,
    ParticipantId, Side, StpPolicy,
};

let mut book = Book::new(BookConfig {
    max_orders: 16,
    grid_len: 640,
    tick_size: 1,
    grid_start_tick: 1,
    default_stp: StpPolicy::CancelIncoming,
})
.unwrap();
let mut storage: Vec<ExecutionEvent> = Vec::with_capacity(8);
let mut events = EventBuffer::new(&mut storage);
book.add_order(OrderId(1), ParticipantId(1), Side::Bid, OrderType::Limit, 99, 4, None, &mut events).unwrap();
book.add_order(OrderId(2), ParticipantId(1), Side::Bid, OrderType::Limit, 100, 6, None, &mut events).unwrap();
let mut levels = [DepthLevel { price: 0, total_qty: 0, order_count: 0 }; 4];
let count = book.depth(Side::Bid, 4, &mut levels);
assert_eq!(count, 2);
assert_eq!(levels[0], DepthLevel { price: 100, total_qty: 6, order_count: 1 });
assert_eq!(levels[1], DepthLevel { price: 99, total_qty: 4, order_count: 1 });
Source

pub fn debug_assert_invariants(&self)

Full structural self-check (ARCHITECTURE.md section 11): crossed book, per-level aggregates recomputed from the arena, bitmap summaries recomputed from level counts, lookup reachability and generation agreement for every live order, free list exactness, and level list link symmetry. Intended for tests and debug builds; it is O(capacity + grid).

§Panics

Panics on the first invariant violation found, with a message naming the broken invariant and the offending slot or level. That is the intended behaviour: this is a checker, and a failed check must never be mistaken for a passing one.

Trait Implementations§

Source§

impl Debug for Book

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Forget for Book

§

impl Freeze for Book

§

impl Move for Book

§

impl RefUnwindSafe for Book

§

impl Send for Book

§

impl Sync for Book

§

impl Unpin for Book

§

impl UnsafeUnpin for Book

§

impl UnwindSafe for Book

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, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

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.