Expand description
§Option Chain Order Book - Options Market Making Infrastructure
A high-performance Rust library for options market making infrastructure, providing a complete Option Chain Order Book system built on top of OrderBook-rs, PriceLevel, and OptionStratLib.
§Key Features
-
Lock-Free Architecture: Built on OrderBook-rs’s lock-free data structures for maximum throughput in high-frequency trading scenarios.
-
Hierarchical Order Book Structure: Multi-level organization from underlying assets down to individual option contracts.
-
Multi-Expiration Option Chain Management: Handle hundreds of options across multiple strikes and expirations simultaneously.
-
Real-Time Order Book per Option: Individual order books for each option contract with full depth, powered by OrderBook-rs.
-
Thread-Safe Concurrent Access: Uses
SkipMapfor lock-free concurrent access to order books across multiple threads. -
OptionStratLib Integration: Use Greeks calculation,
ExpirationDate,OptionStyle, and pricing models directly from OptionStratLib. -
Result-Based Error Handling: All fallible operations return
Result<T, Error>with descriptive error types.
§Architecture
The library follows a hierarchical structure for option chain management:
UnderlyingOrderBookManager (manages all underlyings: BTC, ETH, SPX, etc.)
└── UnderlyingOrderBook (per underlying, all expirations for one asset)
└── ExpirationOrderBookManager (manages all expirations for underlying)
└── ExpirationOrderBook (per expiry date)
└── OptionChainOrderBook (per expiration, option chain)
└── StrikeOrderBookManager (manages all strikes)
└── StrikeOrderBook (per strike price, call/put pair)
└── OptionOrderBook (call or put)
└── OrderBook<T> (from OrderBook-rs)This architecture enables:
- Efficient aggregation of Greeks and positions at any level
- Fast lookup of specific option contracts
- Scalable management of large option chains
- ATM strike lookup at any level
- Statistics aggregation across the hierarchy
§Module Structure
| Module | Description |
|---|---|
orderbook | Hierarchical order book structure with all managers |
error | Error types and Result type alias |
utils | Utility functions (e.g., date formatting) |
§Re-export Convention
Every public item is available at the crate root and under
orderbook: option_chain_orderbook::OptionOrderBook and
option_chain_orderbook::orderbook::OptionOrderBook resolve to the same
type. Prefer the shorter crate-root path; the orderbook:: path remains
valid.
The boundary newtypes — OrderId, OrderType, Side, TimeInForce,
Hash32, Price, Quantity, and TimestampMs — are re-exported here from
orderbook_rs / pricelevel, so consumers need no direct orderbook_rs
/ pricelevel dependency to use the hierarchy. Quote exposes prices,
sizes, and timestamps through Price / Quantity / TimestampMs; the leaf
add_limit_order* submission path still takes plain u128 / u64 (that is
what orderbook_rs accepts there).
§Core Components
§Order Book Hierarchy (orderbook)
orderbook::UnderlyingOrderBookManager: Top-level manager for all underlyingsorderbook::UnderlyingOrderBook: All expirations for a single underlyingorderbook::ExpirationOrderBookManager: Manages expirations for an underlyingorderbook::ExpirationOrderBook: All strikes for a single expirationorderbook::OptionChainOrderBook: Option chain with strike managementorderbook::StrikeOrderBookManager: Manages strikes for an expirationorderbook::StrikeOrderBook: Call/put pair at a strike priceorderbook::OptionOrderBook: Single option order bookorderbook::Quote: Two-sided market representationorderbook::QuoteUpdate: Quote change tracking
§Microstructure Coverage
This crate is the option-chain organization and aggregation layer; the
matching engine itself is orderbook-rs. On top of that engine it provides:
- Hierarchical option chain: underlying → expiration → chain → strike →
contract, where each leaf
orderbook::OptionOrderBookwraps oneorderbook_rs::OrderBook<T>.get_or_create_*traversal is idempotent and returns shared handles. - Two-sided quotes:
orderbook::Quote/orderbook::QuoteUpdateexpose top-of-book per side; a one-sided book yields a one-sided quote. - Mark price:
orderbook::MarkPriceCalculatorcomputes a configurable weighted average of index / mid / last-trade prices withDecimaldampening to bound per-update movement. - Greeks (
clockfeature):orderbook::GreeksEngineprices each contract throughoptionstratlibfrom a supplied implied volatility (read from aorderbook::VolSurfaceby the integrator and passed in — the engine takes the IV directly, it does not query the surface itself), andorderbook::GreeksAggregatorsums per-position Greeks across the hierarchy intoorderbook::AggregatedGreeksusingDecimal. - Expiry lifecycle:
orderbook::ExpiryCycleConfig/orderbook::CycleRule,orderbook::ExpiryLifecycleManager, andorderbook::ExpirySchedulerdrive roll/expiry transitions with listeners. - Scoped mass-cancel: contract / strike / chain / expiration /
underlying / global, each returning a typed result counting what it
cancelled, iterated deterministically from the ordered
SkipMap. - Instrument & symbol services:
orderbook::SymbolIndex,orderbook::InstrumentRegistry,orderbook::InstrumentStatus,orderbook::ContractSpecs,orderbook::StrikeGenerator, andorderbook::StrikeRangeConfigfor fast lookup and strike management. - Order policy hooks: a crate-local
orderbook::ValidationConfig(order/qty limits and an inclusive[min_price, max_price]price band) plus the upstreamorderbook::FeeScheduleand self-trade preventionorderbook::STPMode. Tick/lot/size limits, fees, and STP are applied byorderbook-rsat the leaf engine; the price band is enforced crate-side (the engine has no price-bound hook) and, when both aorderbook::ContractSpecsband and a validation band apply to the same contract, they are merged tightest-wins. - Optional eventing: NATS publishing (
natsfeature) and a command/event/journal/replay sequencer (sequencerfeature). The sequenced add path carries order-kind variety — limit, post-only, and iceberg (OrderKind) — through the journal so replay reconstructs the exact order shape.
§Limitations
- Not a matching engine. Order placement, matching, fills, fees, and STP
at the leaf are
orderbook-rsbehavior. This crate organizes and aggregates manyOrderBook<T>instances; it does not reimplement matching, and options math is delegated tooptionstratlib(no hand-rolled Black-Scholes here). - Async is opt-in.
tokiois pulled in only by thenatsandsequencerfeatures. The default build, the hierarchy traversal, and the order-submission / quote path are fully synchronous — there is no.awaiton the hot path. The matching engine underneath (orderbook-rs) is lock-free, and the hierarchy itself is lock-free skip-maps + atomics; the only mutexes are around rarely-contended state (e.g. opt-in trade capture, config holders), not the matching path. ExpirationDate::Daysis wall-clock-relative. ADays(n)expiry is a moving relative day-count: it is resolved against the current clock when materialized into a contract date or time-to-expiry, so the sameDaysvalue maps to different calendar dates as time passes. UseExpirationDate::DateTimefor an absolute, replay-stable expiry; lifecycle transitions operate only on theDateTimeform.- Mark price is a derived, non-journaled value. It is computed from
current inputs and is not part of the
sequencerjournal; replay reconstructs order-book state, not historical mark prices. - Deterministic trade IDs require an injected namespace + clock. By
default each leaf’s trade-ID namespace is a random
Uuid::new_v4(), so trade IDs and timestamps differ from run to run. Inject a root namespace via the sequencer’sset_trade_id_namespace(each leaf then derives a namespace fromrootand its full path, expiration instant included) together with a deterministic clock viaset_clock, both before the first submit: two identically-seeded sequenced runs on fresh instances then produce identical trade payloads (ids, engine trade timestamps,engine_seq). Additionally injecting an event-envelope timestamp source viaset_timestamp_ns_sourcemakes the two journals fully byte-identical (with only namespace + clock injected, the trade payloads are identical but the wall-clock envelopetimestamp_nsstill differs). Without namespace and clock the old caveat applies. Either waySequencedUnderlyingOrderBook::replaydiscards journaled results, so the replay oracle compares book state and never diffs trade payloads. - Time-in-force replay determinism requires an injected clock.
GTD/Dayadmission is decided by each leaf’s engine clock. Inject a deterministic clock (e.g.orderbook::StubClock) via the hierarchy’sset_clockbefore the first order, and configure the replaying instance with an identically-behaving clock; otherwise leaves stamp and admit against the wall clock. - Pricing inputs are supplied by the integrator. The crate ships only a
trivial
orderbook::FlatVolSurfaceand mock / static index feeds (orderbook::MockPriceFeed,orderbook::StaticPriceFeed); a production volatility surface and a live index price feed are the caller’s responsibility.
§Example Usage
§Creating a Hierarchical Order Book
use option_chain_orderbook::{OrderId, Side, UnderlyingOrderBookManager, Uuid};
use optionstratlib::prelude::pos_or_panic;
use optionstratlib::ExpirationDate;
let manager = UnderlyingOrderBookManager::new();
let exp_date = ExpirationDate::Days(pos_or_panic!(30.0));
// Create BTC option chain (use block to drop guards)
{
let btc = manager.get_or_create("BTC");
let exp = btc.get_or_create_expiration(exp_date);
let strike = exp.get_or_create_strike(50000);
// Add orders to call
strike.call().add_limit_order(OrderId::from_uuid(Uuid::new_v4()), Side::Buy, 100, 10)
.expect("add order should succeed");
strike.call().add_limit_order(OrderId::from_uuid(Uuid::new_v4()), Side::Sell, 105, 5)
.expect("add order should succeed");
// Get quote
let quote = strike.call().best_quote().expect("best quote");
assert!(quote.is_two_sided());
}
// Get statistics
let stats = manager.stats();§Creating a Single Option Order Book
use option_chain_orderbook::{OptionOrderBook, OrderId, Side, Uuid};
use optionstratlib::OptionStyle;
// Create an order book for a specific option
let book = OptionOrderBook::new("BTC-20240329-50000-C", OptionStyle::Call);
// Add limit orders
book.add_limit_order(OrderId::from_uuid(Uuid::new_v4()), Side::Buy, 500, 10)
.expect("add order should succeed");
book.add_limit_order(OrderId::from_uuid(Uuid::new_v4()), Side::Sell, 520, 5)
.expect("add order should succeed");
// Get the best quote
let quote = book.best_quote().expect("best quote");
assert!(quote.is_two_sided());§Using OptionStratLib for Greeks
use optionstratlib::prelude::pos_or_panic;
use optionstratlib::{Options, ExpirationDate};
use optionstratlib::model::types::{OptionStyle, OptionType, Side};
use optionstratlib::greeks::{delta, gamma, theta, vega, rho};
use rust_decimal_macros::dec;
let option = Options {
option_type: OptionType::European,
side: Side::Long,
underlying_symbol: "BTC".to_string(),
strike_price: pos_or_panic!(50000.0),
expiration_date: ExpirationDate::Days(pos_or_panic!(30.0)),
implied_volatility: pos_or_panic!(0.6),
quantity: pos_or_panic!(1.0),
contract_size: pos_or_panic!(1.0),
underlying_price: pos_or_panic!(48000.0),
risk_free_rate: dec!(0.05),
option_style: OptionStyle::Call,
dividend_yield: pos_or_panic!(0.0),
exotic_params: None,
};
let delta_value = delta(&option).expect("delta calculation should succeed");
let gamma_value = gamma(&option).expect("gamma calculation should succeed");§Examples
The library includes comprehensive examples demonstrating each level of the hierarchy:
| Example | Description |
|---|---|
01_option_orderbook | Single option order book operations |
02_strike_orderbook | Strike level with call/put pairs |
03_chain_orderbook | Option chain (all strikes for one expiration) |
04_expiration_orderbook | Expiration level with term structure |
05_underlying_orderbook | Underlying level (all expirations) |
06_full_hierarchy | Complete hierarchy with trading scenarios |
07_mass_cancel | Hierarchical mass cancel operations |
08_order_lifecycle | Order state tracking and lifecycle queries |
Run examples with:
cargo run --example 01_option_orderbook
cargo run --example 06_full_hierarchy§Benchmarks
Comprehensive benchmarks are available for all components:
- orderbook_bench: Single option order book operations
- strike_bench: Strike order book and manager operations
- chain_bench: Option chain order book operations
- expiration_bench: Expiration order book operations
- underlying_bench: Underlying order book operations
- hierarchy_bench: Full hierarchy traversal and trading scenarios
Run benchmarks with:
cargo bench
cargo bench -- orderbook_benches
cargo bench -- hierarchy_benches§Performance Characteristics
Built on OrderBook-rs’s lock-free architecture:
- Order Operations: O(log N) for add/cancel operations
- Best Quote Lookup: small bounded top-of-book read (best price per side plus the aggregate size at that single best level); no caching and no full-book scan or heap allocation
- Thread Safety: Lock-free operations for concurrent access
- Hierarchy Traversal: O(log N) access via
SkipMap
§Dependencies
See Cargo.toml for the exact pinned versions (kept there so this list
cannot go stale). The core dependencies are:
- orderbook-rs: lock-free matching engine and price levels — the actual
order book this crate organizes (
special_ordersfeature on) - pricelevel: per-level engine and boundary newtypes (
OrderId,Price,Quantity,Side,OrderType,TimeInForce,Hash32) - optionstratlib: options pricing, Greeks,
ExpirationDate,OptionStyle, andPositive - crossbeam-skiplist: ordered lock-free skip list (manager children)
- dashmap: lock-free concurrent hash map (secondary indexes)
- rust_decimal: exact decimal arithmetic for mark price and Greeks
- thiserror: typed error handling
- serde / serde_json: serialization for events and config DTOs
- tracing: structured logging (no global subscriber installed by the library)
- tokio (optional): async runtime, pulled in only by the
natsandsequencerfeatures
Re-exports§
pub use error::Error;pub use error::Result;pub use orderbook::AggregatedGreeks;pub use orderbook::ChainEvictExpiredResult;pub use orderbook::ChainMassCancelResult;pub use orderbook::CleanupResult;pub use orderbook::ContractSpecs;pub use orderbook::ContractSpecsBuilder;pub use orderbook::CycleRule;pub use orderbook::ExerciseStyle;pub use orderbook::ExpirationCallback;pub use orderbook::ExpirationEvictExpiredResult;pub use orderbook::ExpirationManagerStats;pub use orderbook::ExpirationMassCancelResult;pub use orderbook::ExpirationOrderBook;pub use orderbook::ExpirationOrderBookManager;pub use orderbook::ExpiryCycleConfig;pub use orderbook::ExpiryLifecycleManager;pub use orderbook::ExpiryScheduler;pub use orderbook::ExpiryType;pub use orderbook::GlobalEvictExpiredResult;pub use orderbook::GlobalMassCancelResult;pub use orderbook::GlobalStats;pub use orderbook::GreeksAggregator;pub use orderbook::IndexPriceFeed;pub use orderbook::InstrumentInfo;pub use orderbook::InstrumentRegistry;pub use orderbook::InstrumentStatus;pub use orderbook::LifecycleConfig;pub use orderbook::LifecycleEvent;pub use orderbook::LifecycleListener;pub use orderbook::LifecycleResult;pub use orderbook::MarkPriceCalculator;pub use orderbook::MarkPriceConfig;pub use orderbook::MarkPriceConfigBuilder;pub use orderbook::MockPriceFeed;pub use orderbook::OptionChainOrderBook;pub use orderbook::OptionChainOrderBookManager;pub use orderbook::OptionChainStats;pub use orderbook::OptionOrderBook;pub use orderbook::Position;pub use orderbook::PriceUpdate;pub use orderbook::PriceUpdateListener;pub use orderbook::Quote;pub use orderbook::QuoteUpdate;pub use orderbook::RefreshResult;pub use orderbook::SettlementType;pub use orderbook::StaticPriceFeed;pub use orderbook::StrikeEvictExpiredResult;pub use orderbook::StrikeGenerator;pub use orderbook::StrikeMassCancelResult;pub use orderbook::StrikeOrderBook;pub use orderbook::StrikeOrderBookManager;pub use orderbook::StrikeRangeConfig;pub use orderbook::StrikeRangeConfigBuilder;pub use orderbook::SubscriptionId;pub use orderbook::SymbolIndex;pub use orderbook::SymbolRef;pub use orderbook::TerminalOrderSummary;pub use orderbook::UnderlyingEvictExpiredResult;pub use orderbook::UnderlyingMassCancelResult;pub use orderbook::UnderlyingOrderBook;pub use orderbook::UnderlyingOrderBookManager;pub use orderbook::UnderlyingStats;pub use orderbook::ValidationConfig;pub use orderbook::wire_feed_to_calculator;pub use utils::ParsedSymbol;pub use utils::SymbolParser;
Modules§
- error
- Error types for the Option-Chain-OrderBook library.
- orderbook
- Order book integration module.
- utils
- Utility functions for the Option-Chain-OrderBook library.
Structs§
- FeeSchedule
- Configurable fee schedule for maker and taker fees
- Hash32
- A 32-byte hash value used for user identification.
- Mass
Cancel Result - Result of a mass cancel operation.
- Monotonic
Clock - Production clock wrapping
crate::utils::current_time_millis. - Order
State Tracker - Thread-safe tracker for order lifecycle states.
- Price
- Domain value type representing a price.
- Quantity
- Domain value type representing a quantity.
- Stub
Clock - Deterministic stub clock. Each call to
Clock::now_millisadvances an internal counter bystep(default1millisecond). Intended for sequencer replay, proptests, and snapshot tests that require byte-identical timestamps across runs. - Timestamp
Ms - Domain value type representing a timestamp in milliseconds.
- Trade
Result - Enhanced trade result that includes symbol information and fee details
- Uuid
- A Universally Unique Identifier (UUID).
Enums§
- Cancel
Reason - Reason for order cancellation.
- Order
Status - Explicit order status for lifecycle tracking.
- Order
Type - Represents different types of limit orders
- STPMode
- Self-Trade Prevention mode for the order book.
- Side
- Represents the side of an order
- Time
InForce - Specifies how long an order remains active before it is executed or expires.
Traits§
- Clock
- A source of wall-clock or logical millisecond timestamps for the matching core.
Type Aliases§
- OrderId
- Legacy type alias for backward compatibility with code using
OrderId.