1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
//! # Market Making Library
//!
//! A comprehensive Rust library implementing quantitative market making strategies based on
//! the Avellaneda-Stoikov model and extensions. This library provides production-ready
//! components for building automated market making systems for financial markets.
//!
//! ## Overview
//!
//! Market making is the practice of simultaneously providing buy (bid) and sell (ask) quotes
//! in a financial market. The market maker profits from the bid-ask spread while providing
//! liquidity to the market.
//!
//! ### Key Challenges Addressed
//!
//! - **Inventory Risk**: Dynamic quote skewing based on position
//! - **Adverse Selection**: Order flow toxicity detection with VPIN
//! - **Optimal Pricing**: Stochastic control theory for spread optimization
//! - **Risk Management**: Circuit breakers, drawdown limits, and position controls
//! - **Multi-Asset**: Correlation-aware portfolio risk management
//!
//! ## Features
//!
//! ### Strategy Models
//!
//! - **Avellaneda-Stoikov**: Classic optimal market making with reservation price
//! - **GLFT Extension**: Guéant-Lehalle-Fernandez-Tapia with terminal penalties
//! - **Grid Trading**: Multi-level order placement with geometric/arithmetic spacing
//! - **Adaptive Spread**: Dynamic spread adjustment based on order book imbalance
//! - **Depth-Based Offering**: Size adjustment based on market depth
//!
//! ### Risk Management
//!
//! - **Position Limits**: Maximum inventory size controls
//! - **Notional Limits**: Maximum value at risk
//! - **Circuit Breakers**: Automatic trading halts on adverse conditions
//! - **Drawdown Tracking**: Peak-to-trough monitoring with configurable limits
//! - **Alert System**: Configurable alerts for critical events
//! - **Portfolio Risk**: Correlation matrix and multi-asset VaR
//!
//! ### Analytics
//!
//! - **Order Flow Analysis**: Trade flow imbalance and toxicity metrics
//! - **VPIN Calculator**: Volume-synchronized probability of informed trading
//! - **Order Intensity Estimation**: Fill rate modeling for parameter calibration
//! - **Live Metrics**: Real-time operational metrics with atomic counters
//! - **Prometheus Export**: Optional metrics export with Grafana dashboard
//!
//! ### Backtesting
//!
//! - **Event-Driven Engine**: Tick-by-tick simulation
//! - **Fill Models**: Immediate, queue position, probabilistic, market impact
//! - **Performance Metrics**: Sharpe, Sortino, Calmar, max drawdown, profit factor
//! - **Slippage Models**: Fixed, percentage, volatility-based
//!
//! ### Execution
//!
//! - **Exchange Connector Trait**: Abstract interface for any exchange
//! - **Order Manager**: Order lifecycle management with state tracking
//! - **Latency Tracking**: Histogram-based latency measurement
//! - **Mock Connector**: Testing without real exchange connectivity
//!
//! ### Parameter Calibration
//!
//! - **Risk Aversion (γ)**: Calibration from inventory half-life
//! - **Order Intensity (k)**: Estimation from historical fill rates
//! - **Volatility Regimes**: Automatic detection and parameter adjustment
//!
//! ## The Avellaneda-Stoikov Model
//!
//! The Avellaneda-Stoikov model (2008) solves the optimal market making problem using
//! stochastic control theory. Key formulas:
//!
//! ### Reservation Price
//! ```text
//! r = s - q × γ × σ² × (T - t)
//! ```
//!
//! ### Optimal Spread
//! ```text
//! spread = γ × σ² × (T - t) + (2/γ) × ln(1 + γ/k)
//! ```
//!
//! Where:
//! - `s`: Mid price
//! - `q`: Current inventory
//! - `γ`: Risk aversion parameter
//! - `σ`: Volatility
//! - `T - t`: Time remaining
//! - `k`: Order arrival intensity
//!
//! ## Modules
//!
//! - [`strategy`]: Quote generation algorithms (A-S, GLFT, Grid, Adaptive)
//! - [`position`]: Inventory tracking and PnL management
//! - [`market_state`]: Market data and volatility estimation
//! - [`risk`]: Limits, circuit breakers, alerts, and portfolio risk
//! - [`analytics`]: Order flow, VPIN, intensity estimation, live metrics
//! - [`execution`]: Exchange connectivity, order management, latency tracking
//! - [`backtest`]: Historical simulation with fill models and metrics
//! - [`types`]: Common types, decimals, and error definitions
//! - [`prelude`]: Convenient re-exports of commonly used types
//!
//! ## Quick Start
//!
//! ```rust
//! use market_maker_rs::prelude::*;
//!
//! // Calculate optimal quotes using Avellaneda-Stoikov
//! let mid_price = dec!(100.0);
//! let inventory = dec!(5.0);
//! let risk_aversion = dec!(0.5); // γ
//! let volatility = dec!(0.02);
//! let time_to_terminal_ms = 3600_000; // 1 hour
//! let order_intensity = dec!(1.5); // k
//!
//! let (bid, ask) = market_maker_rs::strategy::avellaneda_stoikov::calculate_optimal_quotes(
//! mid_price,
//! inventory,
//! risk_aversion,
//! volatility,
//! time_to_terminal_ms,
//! order_intensity,
//! ).unwrap();
//!
//! println!("Bid: {}, Ask: {}", bid, ask);
//! ```
//!
//! ## Feature Flags
//!
//! - `prometheus`: Enable Prometheus metrics export (adds `prometheus`, `hyper`, `tokio` dependencies)
//! - `serde`: Enable serialization/deserialization for all types (enabled by default)
//!
//! ## Examples
//!
//! ### Risk Management
//!
//! ```rust
//! use market_maker_rs::prelude::*;
//!
//! // Set up position limits
//! let limits = RiskLimits::new(
//! dec!(100.0), // max 100 units position
//! dec!(10000.0), // max $10,000 notional
//! dec!(0.5), // 50% scaling factor
//! ).unwrap();
//!
//! // Check if order is allowed
//! let allowed = limits.check_order(dec!(50.0), dec!(10.0), dec!(100.0)).unwrap();
//!
//! // Circuit breaker for automatic trading halts
//! let config = CircuitBreakerConfig::new(
//! dec!(1000.0), // max daily loss
//! dec!(0.05), // max loss per trade (5%)
//! 5, // max consecutive losses
//! dec!(0.10), // max drawdown (10%)
//! 300_000, // cooldown period (5 min)
//! 60_000, // loss window (1 min)
//! ).unwrap();
//! let breaker = CircuitBreaker::new(config);
//! ```
//!
//! ### Backtesting
//!
//! ```rust,ignore
//! use market_maker_rs::prelude::*;
//!
//! // Configure backtest
//! let config = BacktestConfig::default()
//! .with_initial_capital(dec!(100000.0))
//! .with_fee_rate(dec!(0.001))
//! .with_slippage(SlippageModel::Fixed(dec!(0.01)));
//!
//! // Run backtest with your strategy
//! let mut engine = BacktestEngine::new(config, strategy, data_source);
//! let result = engine.run();
//!
//! println!("Net PnL: {}", result.net_pnl);
//! println!("Sharpe Ratio: {:?}", result.sharpe_ratio);
//! println!("Max Drawdown: {}", result.max_drawdown);
//! ```
//!
//! ### Portfolio Risk
//!
//! ```rust
//! use market_maker_rs::risk::portfolio::*;
//! use market_maker_rs::dec;
//!
//! // Create correlation matrix
//! let btc = AssetId::new("BTC");
//! let eth = AssetId::new("ETH");
//! let mut matrix = CorrelationMatrix::new(vec![btc.clone(), eth.clone()]);
//! matrix.set_correlation(&btc, ð, dec!(0.8)).unwrap();
//!
//! // Calculate portfolio risk
//! let mut portfolio = PortfolioPosition::new();
//! portfolio.set_position(btc, dec!(1.0), dec!(0.05));
//! portfolio.set_position(eth, dec!(10.0), dec!(0.08));
//!
//! let calculator = PortfolioRiskCalculator::new(matrix);
//! let vol = calculator.portfolio_volatility(&portfolio).unwrap();
//! ```
// Re-export Decimal for use throughout the library
pub use Decimal;
pub use dec;
/// Market state module containing market data representations.
///
/// Provides:
/// - Market snapshots with bid/ask prices
/// - Volatility estimation (simple, EWMA, Parkinson)
/// Position tracking module for inventory and PnL management.
///
/// Provides:
/// - Inventory position tracking with average cost
/// - Realized and unrealized PnL calculation
/// Strategy module containing quote generation algorithms.
///
/// Implements multiple market making strategies:
/// - **Avellaneda-Stoikov**: Optimal quotes using stochastic control
/// - **GLFT**: Extension with terminal inventory penalties
/// - **Grid Trading**: Multi-level orders with configurable spacing
/// - **Adaptive Spread**: Dynamic adjustment based on order book imbalance
/// - **Depth-Based**: Size adjustment based on market depth
/// - **Parameter Calibration**: Tools for γ and k estimation
/// Risk management module for comprehensive risk control.
///
/// Provides:
/// - **Position Limits**: Maximum inventory size controls
/// - **Notional Limits**: Maximum value at risk
/// - **Circuit Breakers**: Automatic trading halts on adverse conditions
/// - **Drawdown Tracking**: Peak-to-trough monitoring
/// - **Alert System**: Configurable alerts with multiple handlers
/// - **Portfolio Risk**: Correlation matrix and multi-asset VaR
/// - **Hedge Calculator**: Cross-asset hedging ratios
/// Common types and error definitions.
///
/// Provides:
/// - Decimal helper functions (ln, sqrt, powi)
/// - Error types with thiserror
/// - Primitive type aliases
/// Analytics module for market microstructure analysis.
///
/// Provides:
/// - **Order Flow Analysis**: Trade flow imbalance and toxicity
/// - **VPIN Calculator**: Volume-synchronized probability of informed trading
/// - **Order Intensity**: Fill rate estimation for parameter calibration
/// - **Live Metrics**: Real-time operational metrics with atomic counters
/// - **Prometheus Export**: Optional metrics server with Grafana dashboard
/// Execution module for exchange connectivity and order management.
///
/// Provides:
/// - **Exchange Connector**: Abstract trait for any exchange
/// - **Order Manager**: Order lifecycle with state tracking
/// - **Latency Tracking**: Histogram-based measurement
/// - **Mock Connector**: Testing without real connectivity
/// Backtesting module for strategy validation on historical data.
///
/// Provides:
/// - **Event-Driven Engine**: Tick-by-tick simulation
/// - **Data Sources**: Ticks and OHLCV bars
/// - **Fill Models**: Immediate, queue position, probabilistic, market impact
/// - **Performance Metrics**: Sharpe, Sortino, Calmar, profit factor
/// - **Slippage Models**: Fixed, percentage, volatility-based
/// Prelude module for convenient imports.
///
/// Import all commonly used types with:
/// ```rust
/// use market_maker_rs::prelude::*;
/// ```