# joaquinbejar/orderbook-rs architecture

> Architecture diagram of the GitHub repository joaquinbejar/orderbook-rs, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-09-01). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/joaquinbejar/orderbook-rs
- Repository: https://github.com/joaquinbejar/orderbook-rs

## Overview

#### 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: [`src/orderbook/book.rs`](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/book.rs) (OrderBook), [`src/orderbook/operations.rs`](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/operations.rs) (Admission & operations), [`src/orderbook/matching.rs`](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/matching.rs) (Matching engine), [`src/orderbook/trade.rs`](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/trade.rs) (Trades & book events)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_core["Matching Core"]
  node_book["OrderBook<br/>concurrent book<br/>[book.rs]"]
  node_cache["Best-price cache<br/>[cache.rs]"]
  node_pool["Matching resource pool<br/>[pool.rs]"]
  node_operations["Admission &amp; operations<br/>command pipeline<br/>[operations.rs]"]
  node_risk["Risk controls<br/>validation<br/>[risk.rs]"]
  node_modifications["Order modifications<br/>mutation<br/>[modifications.rs]"]
  node_special["Cancel, STP &amp; repricing<br/>state controls<br/>[mass_cancel.rs]"]
  node_matching["Matching engine<br/>FIFO matcher<br/>[matching.rs]"]
  node_trade["Trades &amp; book events<br/>event model<br/>[trade.rs]"]
  node_sequence["Engine event sequence<br/>ordering"]
end

subgraph group_recovery["Ordering &amp; Recovery"]
  node_sequencer["Command sequencer<br/>journal orchestration<br/>[mod.rs]"]
  node_journal[("File journal<br/>durable journal<br/>[file_journal.rs]")]
  node_replay["Replay engine<br/>recovery<br/>[replay.rs]"]
  node_snapshot["Snapshots<br/>consistent state<br/>[snapshot.rs]"]
end

subgraph group_integration["Integration Boundaries"]
  node_nats["NATS / JetStream<br/>event publisher<br/>[nats.rs]"]
  node_wire["Binary wire protocol<br/>transport<br/>[framing.rs]"]
  node_metrics["Metrics facade<br/>observability<br/>[metrics.rs]"]
end

subgraph group_readside["Multi-book &amp; Analytics"]
  node_manager["Multi-book managers<br/>symbol routing<br/>[manager.rs]"]
  node_analytics["Market analytics<br/>read-side analysis<br/>[statistics.rs]"]
end

node_crate["Public crate API<br/>Rust library<br/>[lib.rs]"]
node_prelude["Convenience prelude<br/>exports<br/>[prelude.rs]"]
node_examples["Integration examples<br/>binaries"]

node_crate -->|"exports"| node_prelude
node_crate -->|"exposes"| node_book
node_examples -->|"embeds"| node_crate
node_book -->|"maintains"| node_cache
node_book -->|"reuses"| node_pool
node_operations -->|"validates through"| node_risk
node_operations -->|"applies"| node_modifications
node_operations -->|"coordinates"| node_special
node_operations -->|"submits aggressive orders"| node_matching
node_modifications -->|"mutates"| node_book
node_special -->|"updates state"| node_book
node_matching -->|"updates levels"| node_book
node_matching -->|"produces"| node_trade
node_trade -->|"ordered by"| node_sequence
node_book -->|"captures/restores"| node_snapshot
node_sequencer -->|"persists"| node_journal
node_journal -->|"replays"| node_replay
node_replay -->|"rebuilds"| node_book
node_sequence -.->|"publishes streams"| node_nats
node_wire -->|"decodes inbound commands"| node_operations
node_trade -->|"encodes outbound updates"| node_wire
node_book -.->|"emits metrics"| node_metrics
node_manager -->|"routes by symbol"| node_book
node_analytics -->|"reads without mutation"| node_book

click node_crate "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/lib.rs"
click node_prelude "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/prelude.rs"
click node_book "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/book.rs"
click node_cache "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/cache.rs"
click node_pool "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/pool.rs"
click node_operations "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/operations.rs"
click node_risk "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/risk.rs"
click node_modifications "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/modifications.rs"
click node_special "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/mass_cancel.rs"
click node_matching "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/matching.rs"
click node_trade "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/trade.rs"
click node_sequence "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/book_change_event.rs"
click node_sequencer "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/sequencer/mod.rs"
click node_journal "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/sequencer/file_journal.rs"
click node_replay "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/sequencer/replay.rs"
click node_snapshot "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/snapshot.rs"
click node_nats "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/nats.rs"
click node_wire "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/wire/framing.rs"
click node_metrics "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/metrics.rs"
click node_manager "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/manager.rs"
click node_analytics "https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/statistics.rs"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_book,node_cache,node_pool,node_operations,node_risk,node_modifications,node_special,node_matching,node_trade,node_sequence toneBlue
class node_sequencer,node_journal,node_replay,node_snapshot toneAmber
class node_nats,node_wire,node_metrics toneMint
class node_manager,node_analytics toneRose
class node_crate,node_prelude,node_examples toneNeutral
```

## Components

### Matching Core

Concurrent order-book state and mutation pipeline.

- [OrderBook](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/book.rs): concurrent book · Coordinates price levels, state, listeners, indexes, and clocks. · `src/orderbook/book.rs`
- [Best-price cache](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/cache.rs): cache · `src/orderbook/cache.rs`
- [Matching resource pool](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/pool.rs): resource pool · `src/orderbook/pool.rs`
- [Admission & operations](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/operations.rs): command pipeline · Applies order semantics and mutation gates. · `src/orderbook/operations.rs`
- [Risk controls](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/risk.rs): validation · `src/orderbook/risk.rs`
- [Order modifications](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/modifications.rs): mutation · `src/orderbook/modifications.rs`
- [Cancel, STP & repricing](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/mass_cancel.rs): state controls · Keeps special-order and cancellation state synchronized. · `src/orderbook/mass_cancel.rs`
- [Matching engine](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/matching.rs): FIFO matcher · Walks opposing levels and updates resting orders. · `src/orderbook/matching.rs`
- [Trades & book events](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/trade.rs): event model · `src/orderbook/trade.rs`
- [Engine event sequence](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/book_change_event.rs): ordering · Orders outbound streams for gap detection. · `src/orderbook/book_change_event.rs`

### Ordering & Recovery

Durable command ordering and state restoration.

- [Command sequencer](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/sequencer/mod.rs): journal orchestration · Models commands and total operation order. · `src/orderbook/sequencer/mod.rs`
- [File journal](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/sequencer/file_journal.rs): durable journal · Segmented, checksummed operation storage. · `src/orderbook/sequencer/file_journal.rs`
- [Replay engine](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/sequencer/replay.rs): recovery · Deterministically rebuilds book state from journals. · `src/orderbook/sequencer/replay.rs`
- [Snapshots](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/snapshot.rs): consistent state · Serialize and validate-first restore book state. · `src/orderbook/snapshot.rs`

### Integration Boundaries

Optional transport, messaging, and observability adapters.

- [NATS / JetStream](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/nats.rs): event publisher · Optional trade and book-change stream integration. · `src/orderbook/nats.rs`
- [Binary wire protocol](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/wire/framing.rs): transport · Frames commands and encodes execution updates. · `src/wire/framing.rs`
- [Metrics facade](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/metrics.rs): observability · Optional metrics emission outside matching outcomes. · `src/orderbook/metrics.rs`

### Multi-book & Analytics

Routing and non-mutating market views.

- [Multi-book managers](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/manager.rs): symbol routing · Standard and Tokio-oriented book management. · `src/orderbook/manager.rs`
- [Market analytics](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/orderbook/statistics.rs): read-side analysis · Depth, statistics, impact, and implied-volatility views. · `src/orderbook/statistics.rs`

### Other components

- [Public crate API](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/lib.rs): Rust library · `src/lib.rs`
- [Convenience prelude](https://github.com/joaquinbejar/orderbook-rs/blob/main/src/prelude.rs): exports · `src/prelude.rs`
- **Integration examples**: binaries

## Connections

- 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
