Skip to main content

Crate option_chain_orderbook

Crate option_chain_orderbook 

Source
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 SkipMap for 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

ModuleDescription
orderbookHierarchical order book structure with all managers
errorError types and Result type alias
utilsUtility 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)

§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:

§Limitations

  • Not a matching engine. Order placement, matching, fills, fees, and STP at the leaf are orderbook-rs behavior. This crate organizes and aggregates many OrderBook<T> instances; it does not reimplement matching, and options math is delegated to optionstratlib (no hand-rolled Black-Scholes here).
  • Async is opt-in. tokio is pulled in only by the nats and sequencer features. The default build, the hierarchy traversal, and the order-submission / quote path are fully synchronous — there is no .await on 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::Days is wall-clock-relative. A Days(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 same Days value maps to different calendar dates as time passes. Use ExpirationDate::DateTime for an absolute, replay-stable expiry; lifecycle transitions operate only on the DateTime form.
  • Mark price is a derived, non-journaled value. It is computed from current inputs and is not part of the sequencer journal; 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’s set_trade_id_namespace (each leaf then derives a namespace from root and its full path, expiration instant included) together with a deterministic clock via set_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 via set_timestamp_ns_source makes the two journals fully byte-identical (with only namespace + clock injected, the trade payloads are identical but the wall-clock envelope timestamp_ns still differs). Without namespace and clock the old caveat applies. Either way SequencedUnderlyingOrderBook::replay discards journaled results, so the replay oracle compares book state and never diffs trade payloads.
  • Time-in-force replay determinism requires an injected clock. GTD / Day admission is decided by each leaf’s engine clock. Inject a deterministic clock (e.g. orderbook::StubClock) via the hierarchy’s set_clock before 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::FlatVolSurface and 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:

ExampleDescription
01_option_orderbookSingle option order book operations
02_strike_orderbookStrike level with call/put pairs
03_chain_orderbookOption chain (all strikes for one expiration)
04_expiration_orderbookExpiration level with term structure
05_underlying_orderbookUnderlying level (all expirations)
06_full_hierarchyComplete hierarchy with trading scenarios
07_mass_cancelHierarchical mass cancel operations
08_order_lifecycleOrder 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_orders feature on)
  • pricelevel: per-level engine and boundary newtypes (OrderId, Price, Quantity, Side, OrderType, TimeInForce, Hash32)
  • optionstratlib: options pricing, Greeks, ExpirationDate, OptionStyle, and Positive
  • 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 nats and sequencer features

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.
MassCancelResult
Result of a mass cancel operation.
MonotonicClock
Production clock wrapping crate::utils::current_time_millis.
OrderStateTracker
Thread-safe tracker for order lifecycle states.
Price
Domain value type representing a price.
Quantity
Domain value type representing a quantity.
StubClock
Deterministic stub clock. Each call to Clock::now_millis advances an internal counter by step (default 1 millisecond). Intended for sequencer replay, proptests, and snapshot tests that require byte-identical timestamps across runs.
TimestampMs
Domain value type representing a timestamp in milliseconds.
TradeResult
Enhanced trade result that includes symbol information and fee details
Uuid
A Universally Unique Identifier (UUID).

Enums§

CancelReason
Reason for order cancellation.
OrderStatus
Explicit order status for lifecycle tracking.
OrderType
Represents different types of limit orders
STPMode
Self-Trade Prevention mode for the order book.
Side
Represents the side of an order
TimeInForce
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.