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
- Options Market Making: Greeks-aware quoting with delta hedging
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
- OrderBook-rs Connector: Integration with lock-free order book
Options Market Making (Feature: options)
- Greeks Calculation: Delta, gamma, theta, vega, rho via OptionStratLib
- Portfolio Greeks: Aggregation across multiple positions
- Greeks-Aware Quoting: Spread adjustment based on gamma exposure
- Delta Hedging: Automatic hedge order generation
- Risk Management: Greeks-based limits and circuit breakers
- Auto-Hedging: Configurable triggers for delta neutralization
Option Chain Integration (Feature: chain)
- Multi-Strike Quoting: Quote all strikes in an expiration
- Chain-Level Risk: Aggregate Greeks across the chain
- ATM Detection: Automatic spread adjustment for ATM options
- Chain Risk Manager: Chain-wide limits and hedging
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
r = s - q × γ × σ² × (T - t)
Optimal Spread
spread = γ × σ² × (T - t) + (2/γ) × ln(1 + γ/k)
Where:
s: Mid priceq: Current inventoryγ: Risk aversion parameterσ: VolatilityT - t: Time remainingk: 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 options: Options pricing, Greeks, and market making (feature:options)chain: Option chain integration and multi-strike quoting (feature:chain)api: REST/WebSocket API layer (feature:api)persistence: Data persistence layer (feature:persistence)multi_underlying: Multi-asset management (feature:multi-underlying)events: Event broadcasting system (feature:events)data_feeds: Real-time market data feeds (feature:data-feeds)
Quick Start
use *;
// Calculate optimal quotes using Avellaneda-Stoikov
let mid_price = dec!;
let inventory = dec!;
let risk_aversion = dec!; // γ
let volatility = dec!;
let time_to_terminal_ms = 3600_000; // 1 hour
let order_intensity = dec!; // k
let = calculate_optimal_quotes.unwrap;
println!;
Feature Flags
prometheus: Enable Prometheus metrics export (addsprometheus,hyper,tokiodependencies)serde: Enable serialization/deserialization for all typesoptions: Enable OptionStratLib integration for options pricing and Greeks calculationchain: Enable Option-Chain-OrderBook integration (includesoptions)api: Enable REST/WebSocket API layer with OpenAPI documentationpersistence: Enable persistence layer for market maker datamulti-underlying: Enable multi-asset management with correlation trackingevents: Enable event broadcasting system for real-time updatesdata-feeds: Enable real-time market data feed abstractions
Examples
Risk Management
use *;
// Set up position limits
let limits = new.unwrap;
// Check if order is allowed
let allowed = limits.check_order.unwrap;
// Circuit breaker for automatic trading halts
let config = new.unwrap;
let breaker = new;
Backtesting
use *;
// Configure backtest
let config = default
.with_initial_capital
.with_fee_rate
.with_slippage;
// Run backtest with your strategy
let mut engine = new;
let result = engine.run;
println!;
println!;
println!;
Portfolio Risk
use *;
use dec;
// Create correlation matrix
let btc = new;
let eth = new;
let mut matrix = new;
matrix.set_correlation.unwrap;
// Calculate portfolio risk
let mut portfolio = new;
portfolio.set_position;
portfolio.set_position;
let calculator = new;
let vol = calculator.portfolio_volatility.unwrap;
Options Greeks (Feature: options)
use ;
use Options;
// Calculate Greeks for an option
let greeks = calculate_greeks.unwrap;
println!;
// Aggregate portfolio Greeks
let mut portfolio = new;
portfolio.add; // 10 contracts
// Check delta neutrality
let shares_to_hedge = portfolio.shares_to_hedge;
Options Market Making (Feature: options)
use ;
// Create market maker with Greeks-aware quoting
let config = default;
let market_maker = new;
// Calculate Greeks-adjusted quotes
let = market_maker.calculate_greeks_adjusted_quotes.unwrap;
// Get delta hedge suggestions
let hedges = market_maker.calculate_delta_hedge.unwrap;
Greeks Risk Management (Feature: options)
use ;
// Create risk manager with auto-hedging
let limits = default;
let hedger_config = default;
let mut risk_manager = new;
// Check if order is allowed
let decision = risk_manager.check_order;
match decision
// Check if hedging is needed
if risk_manager.needs_hedge
Option Chain Market Making (Feature: chain)
use ;
use ExpirationOrderBook;
use Arc;
// Create chain market maker
let chain = new;
let config = default;
let mm = new;
// Refresh all quotes across the chain
let quotes = mm.refresh_all_quotes.unwrap;
// Check chain risk status
let status = mm.check_chain_risk;
if !status.can_quote
Multi-Underlying Management (Feature: multi-underlying)
use ;
use dec;
// Create manager with $1M capital
let mut manager = new
.with_allocation_strategy
.with_max_total_delta;
// Add underlyings with target weights
manager.add_underlying.unwrap;
manager.add_underlying.unwrap;
// Set correlations
manager.set_correlation;
// Update market data
manager.update_price;
manager.update_greeks;
// Get unified risk view
let risk = manager.get_unified_risk;
println!;
// Get cross-asset hedge suggestions
let hedges = manager.get_cross_asset_hedges;
Event Broadcasting (Feature: events)
use ;
use Arc;
// Create broadcaster
let config = default;
let broadcaster = new;
// Subscribe to all events
let mut all_rx = broadcaster.subscribe;
// Subscribe with filter (fills only)
let filter = new
.with_event_types
.with_symbols;
let mut filtered_rx = broadcaster.subscribe_filtered;
// Broadcast an event
broadcaster.broadcast.await;
// Get history for reconnection
let missed = broadcaster.get_reconnection_history.await;
🛠 Makefile Commands
This project includes a Makefile with common tasks to simplify development. Here's a list of useful commands:
🔧 Build & Run
🧪 Test & Quality
📦 Packaging & Docs
📈 Coverage & Benchmarks
🧪 Git & Workflow Helpers
🤖 GitHub Actions (via act)
ℹ️ Requires act for local workflow simulation and cargo-tarpaulin for coverage.
Contribution and Contact
We welcome contributions to this project! If you would like to contribute, please follow these steps:
- Fork the repository.
- Create a new branch for your feature or bug fix.
- Make your changes and ensure that the project still builds and all tests pass.
- Commit your changes and push your branch to your forked repository.
- Submit a pull request to the main repository.
If you have any questions, issues, or would like to provide feedback, please feel free to contact the project maintainer:
Contact Information
- Author: Joaquín Béjar García
- Email: jb@taunais.com
- Telegram: @joaquin_bejar
- Repository: https://github.com/joaquinbejar/market-maker-rs
- Documentation: https://docs.rs/market-maker-rs
We appreciate your interest and look forward to your contributions!
License: MIT