option_chain_orderbook/lib.rs
1//! # Option Chain Order Book - Options Market Making Infrastructure
2//!
3//! A high-performance Rust library for options market making infrastructure,
4//! providing a complete Option Chain Order Book system built on top of
5//! [OrderBook-rs](https://crates.io/crates/orderbook-rs),
6//! [PriceLevel](https://crates.io/crates/pricelevel), and
7//! [OptionStratLib](https://crates.io/crates/optionstratlib).
8//!
9//! ## Key Features
10//!
11//! - **Lock-Free Architecture**: Built on OrderBook-rs's lock-free data structures
12//! for maximum throughput in high-frequency trading scenarios.
13//!
14//! - **Hierarchical Order Book Structure**: Multi-level organization from
15//! underlying assets down to individual option contracts.
16//!
17//! - **Multi-Expiration Option Chain Management**: Handle hundreds of options
18//! across multiple strikes and expirations simultaneously.
19//!
20//! - **Real-Time Order Book per Option**: Individual order books for each option
21//! contract with full depth, powered by OrderBook-rs.
22//!
23//! - **Thread-Safe Concurrent Access**: Uses `DashMap` for concurrent access
24//! to order books across multiple threads.
25//!
26//! - **OptionStratLib Integration**: Use Greeks calculation, `ExpirationDate`,
27//! `OptionStyle`, and pricing models directly from OptionStratLib.
28//!
29//! - **Result-Based Error Handling**: All fallible operations return `Result<T, Error>`
30//! with descriptive error types.
31//!
32//! ## Architecture
33//!
34//! The library follows a hierarchical structure for option chain management:
35//!
36//! ```text
37//! UnderlyingOrderBookManager (manages all underlyings: BTC, ETH, SPX, etc.)
38//! └── UnderlyingOrderBook (per underlying, all expirations for one asset)
39//! └── ExpirationOrderBookManager (manages all expirations for underlying)
40//! └── ExpirationOrderBook (per expiry date)
41//! └── OptionChainOrderBook (per expiration, option chain)
42//! └── StrikeOrderBookManager (manages all strikes)
43//! └── StrikeOrderBook (per strike price, call/put pair)
44//! └── OptionOrderBook (call or put)
45//! └── OrderBook<T> (from OrderBook-rs)
46//! ```
47//!
48//! This architecture enables:
49//! - Efficient aggregation of Greeks and positions at any level
50//! - Fast lookup of specific option contracts
51//! - Scalable management of large option chains
52//! - ATM strike lookup at any level
53//! - Statistics aggregation across the hierarchy
54//!
55//! ## Module Structure
56//!
57//! | Module | Description |
58//! |--------|-------------|
59//! | [`orderbook`] | Hierarchical order book structure with all managers |
60//! | [`error`] | Error types and `Result` type alias |
61//! | [`utils`] | Utility functions (e.g., date formatting) |
62//!
63//! ## Core Components
64//!
65//! ### Order Book Hierarchy ([`orderbook`])
66//!
67//! - [`orderbook::UnderlyingOrderBookManager`]: Top-level manager for all underlyings
68//! - [`orderbook::UnderlyingOrderBook`]: All expirations for a single underlying
69//! - [`orderbook::ExpirationOrderBookManager`]: Manages expirations for an underlying
70//! - [`orderbook::ExpirationOrderBook`]: All strikes for a single expiration
71//! - [`orderbook::OptionChainOrderBook`]: Option chain with strike management
72//! - [`orderbook::StrikeOrderBookManager`]: Manages strikes for an expiration
73//! - [`orderbook::StrikeOrderBook`]: Call/put pair at a strike price
74//! - [`orderbook::OptionOrderBook`]: Single option order book
75//! - [`orderbook::Quote`]: Two-sided market representation
76//! - [`orderbook::QuoteUpdate`]: Quote change tracking
77//!
78//! ## Example Usage
79//!
80//! ### Creating a Hierarchical Order Book
81//!
82//! ```rust
83//! use option_chain_orderbook::orderbook::UnderlyingOrderBookManager;
84//! use optionstratlib::prelude::pos_or_panic;
85//! use optionstratlib::ExpirationDate;
86//! use orderbook_rs::{OrderId, Side};
87//!
88//! let manager = UnderlyingOrderBookManager::new();
89//! let exp_date = ExpirationDate::Days(pos_or_panic!(30.0));
90//!
91//! // Create BTC option chain (use block to drop guards)
92//! {
93//! let btc = manager.get_or_create("BTC");
94//! let exp = btc.get_or_create_expiration(exp_date);
95//! let strike = exp.get_or_create_strike(50000);
96//!
97//! // Add orders to call
98//! strike.call().add_limit_order(OrderId::new(), Side::Buy, 100, 10).unwrap();
99//! strike.call().add_limit_order(OrderId::new(), Side::Sell, 105, 5).unwrap();
100//!
101//! // Get quote
102//! let quote = strike.call().best_quote();
103//! assert!(quote.is_two_sided());
104//! }
105//!
106//! // Get statistics
107//! let stats = manager.stats();
108//! ```
109//!
110//! ### Creating a Single Option Order Book
111//!
112//! ```rust
113//! use option_chain_orderbook::orderbook::OptionOrderBook;
114//! use optionstratlib::OptionStyle;
115//! use orderbook_rs::{OrderId, Side};
116//!
117//! // Create an order book for a specific option
118//! let book = OptionOrderBook::new("BTC-20240329-50000-C", OptionStyle::Call);
119//!
120//! // Add limit orders
121//! book.add_limit_order(OrderId::new(), Side::Buy, 500, 10).unwrap();
122//! book.add_limit_order(OrderId::new(), Side::Sell, 520, 5).unwrap();
123//!
124//! // Get the best quote
125//! let quote = book.best_quote();
126//! assert!(quote.is_two_sided());
127//! ```
128//!
129//! ### Using OptionStratLib for Greeks
130//!
131//! ```rust,ignore
132//! use optionstratlib::prelude::pos_or_panic;
133//! use optionstratlib::{Options, ExpirationDate};
134//! use optionstratlib::model::types::{OptionStyle, OptionType, Side};
135//! use optionstratlib::greeks::{delta, gamma, theta, vega, rho};
136//! use rust_decimal_macros::dec;
137//!
138//! let option = Options {
139//! option_type: OptionType::European,
140//! side: Side::Long,
141//! underlying_symbol: "BTC".to_string(),
142//! strike_price: pos_or_panic!(50000.0),
143//! expiration_date: ExpirationDate::Days(pos_or_panic!(30.0)),
144//! implied_volatility: pos_or_panic!(0.6),
145//! quantity: pos_or_panic!(1.0),
146//! underlying_price: pos_or_panic!(48000.0),
147//! risk_free_rate: dec!(0.05),
148//! option_style: OptionStyle::Call,
149//! dividend_yield: pos_or_panic!(0.0),
150//! exotic_params: None,
151//! };
152//!
153//! let delta_value = delta(&option).unwrap();
154//! let gamma_value = gamma(&option).unwrap();
155//! ```
156//!
157//! ## Examples
158//!
159//! The library includes comprehensive examples demonstrating each level of the hierarchy:
160//!
161//! | Example | Description |
162//! |---------|-------------|
163//! | `01_option_orderbook` | Single option order book operations |
164//! | `02_strike_orderbook` | Strike level with call/put pairs |
165//! | `03_chain_orderbook` | Option chain (all strikes for one expiration) |
166//! | `04_expiration_orderbook` | Expiration level with term structure |
167//! | `05_underlying_orderbook` | Underlying level (all expirations) |
168//! | `06_full_hierarchy` | Complete hierarchy with trading scenarios |
169//!
170//! Run examples with:
171//! ```bash
172//! cargo run --example 01_option_orderbook
173//! cargo run --example 06_full_hierarchy
174//! ```
175//!
176//! ## Benchmarks
177//!
178//! Comprehensive benchmarks are available for all components:
179//!
180//! - **orderbook_bench**: Single option order book operations
181//! - **strike_bench**: Strike order book and manager operations
182//! - **chain_bench**: Option chain order book operations
183//! - **expiration_bench**: Expiration order book operations
184//! - **underlying_bench**: Underlying order book operations
185//! - **hierarchy_bench**: Full hierarchy traversal and trading scenarios
186//!
187//! Run benchmarks with:
188//! ```bash
189//! cargo bench
190//! cargo bench -- orderbook_benches
191//! cargo bench -- hierarchy_benches
192//! ```
193//!
194//! ## Performance Characteristics
195//!
196//! Built on OrderBook-rs's lock-free architecture:
197//!
198//! - **Order Operations**: O(log N) for add/cancel operations
199//! - **Best Quote Lookup**: O(1) with caching
200//! - **Thread Safety**: Lock-free operations for concurrent access
201//! - **Hierarchy Traversal**: O(1) access via `DashMap`
202//!
203//! ## Dependencies
204//!
205//! - **orderbook-rs** (0.4): Lock-free order book engine
206//! - **optionstratlib** (0.13): Options pricing, Greeks, and strategy analysis
207//! - **dashmap** (6.1): Concurrent hash map for thread-safe access
208//! - **rust_decimal** (1.39): Precise decimal arithmetic
209//! - **thiserror** (2.0): Error handling
210//! - **serde** (1.0): Serialization support
211
212pub mod error;
213pub mod orderbook;
214pub mod utils;
215
216pub use error::{Error, Result};