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 DashMap for 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)

§Core Components

§Order Book Hierarchy (orderbook)

§Example Usage

§Creating a Hierarchical Order Book

use option_chain_orderbook::orderbook::UnderlyingOrderBookManager;
use optionstratlib::prelude::pos_or_panic;
use optionstratlib::ExpirationDate;
use orderbook_rs::{OrderId, Side};

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::new(), Side::Buy, 100, 10).unwrap();
    strike.call().add_limit_order(OrderId::new(), Side::Sell, 105, 5).unwrap();

    // Get quote
    let quote = strike.call().best_quote();
    assert!(quote.is_two_sided());
}

// Get statistics
let stats = manager.stats();

§Creating a Single Option Order Book

use option_chain_orderbook::orderbook::OptionOrderBook;
use optionstratlib::OptionStyle;
use orderbook_rs::{OrderId, Side};

// 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::new(), Side::Buy, 500, 10).unwrap();
book.add_limit_order(OrderId::new(), Side::Sell, 520, 5).unwrap();

// Get the best quote
let quote = book.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),
    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).unwrap();
let gamma_value = gamma(&option).unwrap();

§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

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: O(1) with caching
  • Thread Safety: Lock-free operations for concurrent access
  • Hierarchy Traversal: O(1) access via DashMap

§Dependencies

  • orderbook-rs (0.4): Lock-free order book engine
  • optionstratlib (0.13): Options pricing, Greeks, and strategy analysis
  • dashmap (6.1): Concurrent hash map for thread-safe access
  • rust_decimal (1.39): Precise decimal arithmetic
  • thiserror (2.0): Error handling
  • serde (1.0): Serialization support

Re-exports§

pub use error::Error;
pub use error::Result;

Modules§

error
Error types for the Option-Chain-OrderBook library.
orderbook
Order book integration module.
utils
Utility functions for the Option-Chain-OrderBook library.