How joaquinbejar/orderbook-rs works
Purpose and entry points
orderbook-rs is a Rust library for a concurrent, lock-free limit-order-book and matching engine. The public crate surface originates at src/lib.rs, with convenient exports in src/prelude.rs. There is no primary service binary; consumers embed OrderBook or multi-book managers. Runnable integration patterns are provided through binaries under examples/src/bin/.
Core book and concurrent storage
OrderBook owns bid/ask price-level topology, book configuration, listeners, caches, indices, clocks, and operational state. Price-level operations are designed for concurrent access using atomics and lock-free/concurrent structures supplied by the pricelevel dependency; the book coordinates cross-level behavior.
• src/orderbook/book.rs
• src/orderbook/cache.rs
• src/orderbook/pool.rs
The cache accelerates best-price access, while reusable matching resources reduce allocation pressure. Snapshots are the consistency boundary for consumers needing a coherent view rather than advisory concurrent reads.
Admission, validation, and mutations
Order submission and updates flow through operational gates and validation before matching or resting: kill switch, risk controls, self-trade prevention, fees, tick/lot and size constraints, then mutation. This stage handles limit, market, iceberg, post-only, FOK/IOC, GTD/DAY, pegged, trailing-stop, reserve, and replacement semantics.
• src/orderbook/operations.rs
• src/orderbook/modifications.rs
• src/orderbook/risk.rs
Risk state, user/order-location indexes, special-order repricing, and explicit cancellation/mass-cancel paths must stay synchronized with every mutation.
• src/orderbook/mass_cancel.rs
• src/orderbook/stp.rs
• src/orderbook/repricing.rs
Matching and execution events
Aggressive orders walk opposing price levels in price-time/FIFO order, produce private per-call match results, update resting state, and emit trades and price-level-change events. Book-level coordination preserves atomic PostOnly and multi-level FOK behavior without making the matching core globally blocking.
• src/orderbook/matching.rs
• src/orderbook/trade.rs
• src/orderbook/book_change_event.rs
An atomic engine sequence orders outbound event streams for downstream gap detection. Fees and typed rejection errors are attached at this boundary.
• src/orderbook/fees.rs
• src/orderbook/error.rs
• src/orderbook/reject_reason.rs
Persistence, ordering, and recovery
The sequencer models commands/results and journals a total order of book operations. ReplayEngine rebuilds deterministic book state from journals, optionally using injected clock and trade-ID namespace. File journals add segmented, checksummed durable storage; in-memory journals support tests and low-overhead workflows.
• src/orderbook/sequencer/mod.rs
• src/orderbook/sequencer/file_journal.rs
• src/orderbook/sequencer/replay.rs
Snapshots serialize book state/configuration and restore it validate-first, rebuilding indexes and special-order tracking before replacing live state.
• src/orderbook/snapshot.rs
• src/orderbook/serialization.rs
Integration boundaries
Optional NATS/JetStream integration publishes trade and book-change streams, with serializers abstracting JSON and optional bincode payloads. Optional metrics emit through the Rust metrics facade, keeping observability outside matching outcomes.
• src/orderbook/nats.rs
• src/orderbook/nats_book_change.rs
• src/orderbook/metrics.rs
The optional binary wire protocol is a separate transport boundary: framed inbound commands decode into engine orders; outbound execution, trade, and book updates encode for clients.
• src/wire/framing.rs
• src/wire/inbound/new_order.rs
• src/wire/outbound/exec_report.rs
Multi-book and analytical layer
Managers route operations/listeners across symbols, with standard and Tokio-oriented variants. Read-side analytics provide depth, statistics, market impact, implied volatility, and lazy iterators without changing matching state.
• src/orderbook/manager.rs
• src/orderbook/statistics.rs
• src/orderbook/implied_volatility/integration.rs
Runtime is Rust/Cargo; Tokio is material for async manager/integration use, NATS is optional external infrastructure, and Prometheus/OpenTelemetry-compatible recorders can consume optional metrics.
Main entry points: book.rs OrderBook · operations.rs Admission & operations · matching.rs Matching engine · trade.rs Trades & book events
Components 22
Matching Core
Concurrent order-book state and mutation pipeline.
- OrderBook · Coordinates price levels, state, listeners, indexes, and clocks.
src/orderbook/book.rs - Best-price cache
src/orderbook/cache.rs - Matching resource pool
src/orderbook/pool.rs - Admission & operations · Applies order semantics and mutation gates.
src/orderbook/operations.rs - Risk controls
src/orderbook/risk.rs - Order modifications
src/orderbook/modifications.rs - Cancel, STP & repricing · Keeps special-order and cancellation state synchronized.
src/orderbook/mass_cancel.rs - Matching engine · Walks opposing levels and updates resting orders.
src/orderbook/matching.rs - Trades & book events
src/orderbook/trade.rs - Engine event sequence · Orders outbound streams for gap detection.
src/orderbook/book_change_event.rs
Ordering & Recovery
Durable command ordering and state restoration.
- Command sequencer · Models commands and total operation order.
src/orderbook/sequencer/mod.rs - File journal · Segmented, checksummed operation storage.
src/orderbook/sequencer/file_journal.rs - Replay engine · Deterministically rebuilds book state from journals.
src/orderbook/sequencer/replay.rs - Snapshots · Serialize and validate-first restore book state.
src/orderbook/snapshot.rs
Integration Boundaries
Optional transport, messaging, and observability adapters.
- NATS / JetStream · Optional trade and book-change stream integration.
src/orderbook/nats.rs - Binary wire protocol · Frames commands and encodes execution updates.
src/wire/framing.rs - Metrics facade · Optional metrics emission outside matching outcomes.
src/orderbook/metrics.rs
Multi-book & Analytics
Routing and non-mutating market views.
- Multi-book managers · Standard and Tokio-oriented book management.
src/orderbook/manager.rs - Market analytics · Depth, statistics, impact, and implied-volatility views.
src/orderbook/statistics.rs
Other components
- Public crate API
src/lib.rs - Convenience prelude
src/prelude.rs - Integration examples
Connections 24
- Public crate API → Convenience prelude: exports
- Public crate API → OrderBook: exposes
- Integration examples → Public crate API: embeds
- OrderBook → Best-price cache: maintains
- OrderBook → Matching resource pool: reuses
- Admission & operations → Risk controls: validates through
- Admission & operations → Order modifications: applies
- Admission & operations → Cancel, STP & repricing: coordinates
- Admission & operations → Matching engine: submits aggressive orders
- Order modifications → OrderBook: mutates
- Cancel, STP & repricing → OrderBook: updates state
- Matching engine → OrderBook: updates levels
- Matching engine → Trades & book events: produces
- Trades & book events → Engine event sequence: ordered by
- OrderBook → Snapshots: captures/restores
- Command sequencer → File journal: persists
- File journal → Replay engine: replays
- Replay engine → OrderBook: rebuilds
- Engine event sequence → NATS / JetStream: publishes streams
- Binary wire protocol → Admission & operations: decodes inbound commands
- Trades & book events → Binary wire protocol: encodes outbound updates
- OrderBook → Metrics facade: emits metrics
- Multi-book managers → OrderBook: routes by symbol
- Market analytics → OrderBook: reads without mutation