pub struct Book { /* private fields */ }Expand description
A single-instrument limit order book on one tick grid.
Implementations§
Source§impl Book
impl Book
Sourcepub fn capture_snapshot_state(&self) -> SnapshotState
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.
Sourcepub fn from_snapshot_state(state: SnapshotState) -> Result<Self, BookError>
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
impl Book
Sourcepub fn new(config: BookConfig) -> Result<Self, BookError>
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.
Sourcepub const fn config(&self) -> BookConfig
pub const fn config(&self) -> BookConfig
The configuration this book was built with.
Sourcepub const fn live_order_count(&self) -> u32
pub const fn live_order_count(&self) -> u32
Number of live orders.
Sourcepub const fn free_order_count(&self) -> u32
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).
Sourcepub fn best_bid(&self) -> Option<(u64, u64)>
pub fn best_bid(&self) -> Option<(u64, u64)>
Best bid as (price, aggregate qty), or None when no bid
rests.
Sourcepub fn best_ask(&self) -> Option<(u64, u64)>
pub fn best_ask(&self) -> Option<(u64, u64)>
Best ask as (price, aggregate qty), or None when no ask
rests.
Sourcepub fn spread(&self) -> Option<u64>
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.
Sourcepub fn contains_order(&self, order_id: OrderId) -> bool
pub fn contains_order(&self, order_id: OrderId) -> bool
True when order_id currently rests live on the book.
Sourcepub fn get_order(&self, order_id: OrderId) -> Option<OrderInfo>
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);Sourcepub fn level_at(
&self,
price: u64,
) -> Result<Option<(Side, DepthLevel)>, BookError>
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.
Sourcepub fn orders_at(&self, price: u64) -> Result<OrdersAt<'_>, BookError>
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.
Sourcepub 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>
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.
Sourcepub fn cancel_order(
&mut self,
order_id: OrderId,
events: &mut EventBuffer<'_>,
) -> Result<usize, BookError>
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.
Sourcepub fn cancel_by_participant(
&mut self,
participant: ParticipantId,
events: &mut EventBuffer<'_>,
) -> Result<usize, BookError>
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.
Sourcepub fn amend_order(
&mut self,
order_id: OrderId,
new_price: u64,
new_qty: u64,
events: &mut EventBuffer<'_>,
) -> Result<usize, BookError>
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.
Sourcepub fn depth(
&self,
side: Side,
max_levels: usize,
out: &mut [DepthLevel],
) -> usize
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 });Sourcepub fn debug_assert_invariants(&self)
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.