### Comprehensive Risk Setup Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/risk-management.md Demonstrates setting up and using various risk management components including position limits, circuit breaker, drawdown tracking, and alerts. This example shows how to integrate these components into a trading loop. ```rust use market_maker_rs::prelude::*; use market_maker_rs::dec; // Set up position limits let limits = RiskLimits::new( dec!(100.0), // max 100 units dec!(10000.0), // max $10,000 notional dec!(0.5), // 50% scaling )?; // Set up circuit breaker let cb_config = CircuitBreakerConfig::new( dec!(1000.0), // max $1000 daily loss dec!(0.05), // 5% max per trade 5, // 5 consecutive losses dec!(0.10), // 10% max drawdown 300_000, // 5 min cooldown 60_000, // 1 min loss window )?; let mut breaker = CircuitBreaker::new(cb_config); // Set up drawdown tracking let mut drawdown = DrawdownTracker::new(dec!(10000.0), dec!(0.20))?; // Set up alerts let mut alert_manager = AlertManager::new(); alert_manager.add_handler(Box::new(LogAlertHandler::new())); // Use in trading loop let mut position = InventoryPosition::new(); position.update_fill(dec!(10.0), dec!(100.0), 1000); // Check limits before order if limits.check_order(position.quantity, dec!(5.0), dec!(101.0))? { // Can place order } // After trade breaker.record_trade(dec!(50.0), 2000)?; drawdown.update(dec!(10050.0), 2000); if !breaker.is_trading_allowed() { println!("Circuit breaker activated!"); } ``` -------------------------------- ### Analytics Integration Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/analytics.md Demonstrates how to integrate and use various analytics components like OrderFlowAnalyzer, VPINCalculator, OrderIntensityEstimator, and LiveMetrics. This example shows creating analyzers, adding trade data, retrieving statistics, tracking live metrics, and getting a metrics snapshot. ```rust use market_maker_rs::analytics:: { order_flow::{OrderFlowAnalyzer, Trade, TradeSide}, vpin::VPINCalculator, intensity::OrderIntensityEstimator, live_metrics::LiveMetrics, }; use market_maker_rs::dec; // Create analyzers let mut flow_analyzer = OrderFlowAnalyzer::new(5000); let mut vpin_calc = VPINCalculator::new(vpin::VPINConfig { bucket_volume: dec!(1000000.0), num_buckets: 20, }); let mut intensity_est = OrderIntensityEstimator::new(intensity::OrderIntensityConfig { window_ms: 300000, min_observations: 50, }); let metrics = LiveMetrics::new(); // Add trade data let trade = Trade::new(dec!(100.0), dec!(10.0), TradeSide::Buy, 1000); flow_analyzer.add_trade(trade.clone()); // Get order flow stats let stats = flow_analyzer.get_stats(2000); println!("Order flow imbalance: {}", stats.imbalance); // Track metrics metrics.increment_counter("trades_processed", 1); metrics.set_gauge("bid_ask_spread", dec!(0.05)); // Get snapshot let snapshot = metrics.get_snapshot(); println!("Metrics: {:?}", snapshot.counters); ``` -------------------------------- ### Run Basic Examples Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/examples/README.md Execute fundamental examples that do not require specific features. ```bash cargo run --example basic_quoting cargo run --example inventory_management cargo run --example inventory_skew cargo run --example parameter_sensitivity cargo run --example error_handling cargo run --example real_time_simulation cargo run --example config_comparison cargo run --example full_strategy ``` -------------------------------- ### Run Examples with Serde Feature Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/examples/README.md Execute examples that utilize the 'serde' feature for enhanced display formatting. ```bash cargo run --example display_example --features serde ``` -------------------------------- ### Run Example: Custom Strategy with Traits Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/doc/USER_GUIDE.md Executes an example demonstrating how to implement a custom trading strategy by extending the base implementation using traits. ```bash cargo run --example trait_sync_example ``` -------------------------------- ### Run Example: Volatility Estimation Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/doc/USER_GUIDE.md Executes an example that compares different volatility estimation methods and analyzes their impact on trading spreads. ```bash cargo run --example volatility_estimation ``` -------------------------------- ### VecDataSource Initialization Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/backtest.md Example demonstrating how to create a VecDataSource with sample market tick data. Requires importing necessary types and macros. ```rust use market_maker_rs::backtest::{VecDataSource, MarketTick}; use market_maker_rs::dec; let data = vec![ MarketTick { timestamp: 1000, bid: dec!(99.5), ask: dec!(100.5), last_trade_price: dec!(100.0), volume: dec!(1000.0), }, // ... more ticks ]; let source = VecDataSource::new(data); ``` -------------------------------- ### Run All Market Maker RS Examples Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/doc/USER_GUIDE.md Executes all available examples for the market-maker-rs project, covering various functionalities and strategies. ```bash cargo run --example basic_quoting cargo run --example config_comparison cargo run --example display_example --features serde cargo run --example error_handling cargo run --example full_strategy cargo run --example inventory_management cargo run --example inventory_skew cargo run --example parameter_sensitivity cargo run --example real_time_simulation cargo run --example trait_sync_example cargo run --example trait_async_example cargo run --example volatility_estimation ``` -------------------------------- ### Run All Examples Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/examples/README.md Executes all market maker Rust examples using cargo run to verify library functionality. This script checks each example individually and reports success or failure. ```bash # Run all examples (bash) for example in basic_quoting inventory_management inventory_skew \ parameter_sensitivity error_handling real_time_simulation \ config_comparison full_strategy; do echo "Running $example..." cargo run --example $example > /dev/null 2>&1 && echo "✓ $example" || echo "✗ $example" done # Run serde example cargo run --example display_example --features serde > /dev/null 2>&1 && echo "✓ display_example" || echo "✗ display_example" ``` -------------------------------- ### OrderRequest Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/execution.md Example demonstrating how to create an OrderRequest for a buy limit order on BTC-USD. ```rust use market_maker_rs::execution::{OrderRequest, Side, OrderType}; use market_maker_rs::dec; let request = OrderRequest::new( "BTC-USD", Side::Buy, OrderType::Limit, Some(dec!(50000.0)), dec!(0.1), ); ``` -------------------------------- ### Run Example: Async Strategy with External Data Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/doc/USER_GUIDE.md Executes an example showcasing async trait usage with simulated external API calls for real-time data integration into trading strategies. ```bash cargo run --example trait_async_example ``` -------------------------------- ### Quick Start: Calculate Optimal Quotes Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/doc/USER_GUIDE.md A basic example demonstrating how to calculate optimal bid and ask quotes using the Avellaneda-Stoikov model. Ensure market parameters like mid-price, inventory, risk aversion, volatility, time to terminal, and order intensity are correctly set. ```rust use market_maker_rs::prelude::*; use market_maker_rs::strategy::avellaneda_stoikov::calculate_optimal_quotes; fn main() { // Market parameters let mid_price = dec!(100.0); let inventory = dec!(0.0); // Flat position let risk_aversion = dec!(0.1); let volatility = dec!(0.2); // 20% annualized let time_to_terminal = 3600000; // 1 hour in ms let order_intensity = dec!(1.5); // Calculate optimal quotes let (bid, ask) = calculate_optimal_quotes( mid_price, inventory, risk_aversion, volatility, time_to_terminal, order_intensity, ).expect("Failed to calculate quotes"); println!("Optimal Bid: ${:.2}", bid); println!("Optimal Ask: ${:.2}", ask); println!("Spread: ${:.4}", ask - bid); } ``` -------------------------------- ### Setup EventBroadcaster for Real-time Updates Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/configuration.md Initialize an EventBroadcaster with default configuration and create a subscriber to receive real-time market maker events. ```rust use market_maker_rs::events::{ EventBroadcaster, EventBroadcasterConfig, EventFilter, EventType }; let broadcaster = EventBroadcaster::new(EventBroadcasterConfig::default()); let mut subscriber = broadcaster.subscribe(); // Listen for all events if let Some(event) = subscriber.recv().await { println!("Event: {:?}", event); } ``` -------------------------------- ### Backtesting Integration Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/backtest.md Demonstrates how to set up and run a backtest using the `BacktestEngine`. This includes creating sample market data, configuring backtest parameters like initial capital and fees, and initializing the engine with a custom strategy and data source. ```rust use market_maker_rs::backtest::{ BacktestEngine, BacktestConfig, BacktestStrategy, VecDataSource, MarketTick, SlippageModel, Side, }; use market_maker_rs::dec; // Create sample data let data = vec![ MarketTick { timestamp: 1000, bid: dec!(99.5), ask: dec!(100.5), last_trade_price: dec!(100.0), volume: dec!(1000.0), }, // ... more ticks ]; // 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))); // Create engine let source = VecDataSource::new(data); let mut engine = BacktestEngine::new(config, my_strategy, source); // Run backtest let result = engine.run().await?; println!("Net PnL: {}", result.net_pnl); println!("Sharpe Ratio: {:?}", result.sharpe_ratio); println!("Max Drawdown: {}", result.max_drawdown); println!("Win Rate: {}", result.win_rate); ``` -------------------------------- ### Backtest Engine Initialization Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/backtest.md Demonstrates how to initialize the BacktestEngine with custom configuration, including initial capital, fee rate, and slippage model. Ensure your strategy and data source are defined elsewhere. ```rust use market_maker_rs::backtest::{ BacktestEngine, BacktestConfig, BacktestStrategy, VecDataSource, MarketTick, SlippageModel }; use market_maker_rs::dec; let config = BacktestConfig::default() .with_initial_capital(dec!(100000.0)) .with_fee_rate(dec!(0.001)) .with_slippage(SlippageModel::Fixed(dec!(0.01))); // Create engine with your strategy and data let engine = BacktestEngine::new(config, strategy, data_source); ``` -------------------------------- ### Integration Example: Decimal Calculations Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/types.md An integration example demonstrating the use of `Decimal` types and helper functions for complex financial calculations, including exponentiation and logarithms, with error handling for results. ```rust use market_maker_rs::{Decimal, dec}; use market_maker_rs::types::primitives::*; use market_maker_rs::types::decimal::*; use market_maker_rs::types::error::*; // Calculate using decimals and helper functions let mid: Price = dec!(100.0); let vol: Volatility = dec!(0.2); let gamma: RiskAversion = dec!(0.5); let k: OrderIntensity = dec!(1.5); // Use decimal functions let vol_squared = decimal_powi(vol, 2)?; let ln_term = decimal_ln(dec!(1.0) + gamma / k)?; // Combine for results let result: MMResult = Ok(vol_squared + ln_term); // Handle results match result { Ok(val) => println!("Result: {}", val), Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Complete End-to-End Workflow Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/examples/README.md Demonstrates a complete market making workflow, including configuration, quote generation, trade execution, position updates, and PnL tracking. Covers full integration of library features. ```bash cargo run --example full_strategy ``` -------------------------------- ### OrderManager Integration Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/execution.md Demonstrates how to create and configure an OrderManager, define an order request, and interact with the exchange connector. Assumes a connector is available. ```rust use market_maker_rs::execution:: OrderRequest, Side, OrderType, ExchangeConnector, OrderManager, OrderManagerConfig; use market_maker_rs::dec; // Create order manager let config = OrderManagerConfig { max_order_age_ms: 60000, polling_interval_ms: 100, }; let mut manager = OrderManager::new(config); // Create order request let request = OrderRequest::new( "BTC-USD", Side::Buy, OrderType::Limit, Some(dec!(50000.0)), dec!(0.1), ); // Submit to exchange (assuming connector is available) // let response = connector.submit_order(request.clone()).await?; // Track the order // manager.track_order(response.order_id.clone(), request)?; // Poll for updates periodically // let stats = manager.get_stats(); // println!("Active orders: {}", stats.active_orders); ``` -------------------------------- ### Position Tracking Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/examples/README.md Illustrates building and managing positions (long/short), calculating entry prices, and tracking PnL. Focuses on `InventoryPosition` and `PnL` updates. ```bash cargo run --example inventory_management ``` -------------------------------- ### OrderManager Constructor Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/execution.md Creates a new OrderManager instance with specified configuration. Use this to initialize order tracking. ```rust use market_maker_rs::execution::{OrderManager, OrderManagerConfig}; use market_maker_rs::dec; let config = OrderManagerConfig { max_order_age_ms: 60000, polling_interval_ms: 100, }; let manager = OrderManager::new(config); ``` -------------------------------- ### Initialize REST API Server Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/configuration.md Starts the REST API server for interacting with the market maker. Requires the 'api' feature and the 'serde' feature. ```rust use market_maker_rs::api::{ApiServer, ApiServerConfig}; let config = ApiServerConfig::default(); let server = ApiServer::new(config).await?; server.run(8080).await?; // API available at http://localhost:8080 // OpenAPI docs at http://localhost:8080/swagger-ui/ ``` -------------------------------- ### Example Usage of Price Type Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/types.md Demonstrates how to declare and initialize a Price variable using the dec! macro. ```rust use market_maker_rs::types::primitives::Price; use market_maker_rs::dec; let price: Price = dec!(100.0); ``` -------------------------------- ### Strategy Configuration Comparison Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/examples/README.md Compares different strategy configurations (Conservative, Moderate, Aggressive, HFT) and their impact on quote behavior. Illustrates trade-offs between various approaches. ```bash cargo run --example config_comparison ``` -------------------------------- ### Development Setup for Market Maker RS Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/doc/USER_GUIDE.md Provides commands for setting up the development environment for the market-maker-rs project, including cloning, testing, linting, and building documentation. ```bash # Clone repository git clone https://github.com/joaquinbejar/market-maker-rs cd market-maker-rs # Run tests cargo test # Check code make lint # Build documentation cargo doc --open # Run all quality checks make pre-push ``` -------------------------------- ### Options Market Maker Integration Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/options-feature.md Demonstrates how to integrate the GreeksRiskManager and OptionsMarketMaker to manage options trading, calculate quotes, and determine hedging needs. ```rust use market_maker_rs::options::*; use optionstratlib::model::option::Options; // Create risk manager let limits = GreeksLimits::default(); let hedger_config = AutoHedgerConfig::default(); let mut risk_manager = GreeksRiskManager::new("BTC", limits, hedger_config); // Create market maker let config = OptionsMarketMakerConfig::default(); let mm = OptionsMarketMakerImpl::new(config); // For each option let greeks = OptionsAdapter::calculate_greeks(&option)?; // Check if we can trade it match risk_manager.check_order(&greeks, dec!(10.0)) { OrderDecision::Allowed => { // Get Greeks-adjusted quotes let mut portfolio = PortfolioGreeks::new(); let (bid, ask) = mm.calculate_greeks_adjusted_quotes( &option, &portfolio, &limits, )?; println!("Quotes: {} / {}", bid, ask); } OrderDecision::Rejected { reason } => { println!("Cannot trade: {}", reason); } _ => {} } // Check if hedging is needed if risk_manager.needs_hedge() { let hedge = risk_manager.calculate_hedge_order(underlying_price); println!("Hedge: {:?} {} @{}", hedge.side, hedge.quantity, hedge.symbol); } ``` -------------------------------- ### MetricsServer::new Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/analytics.md Creates and starts an HTTP server for exporting metrics in Prometheus format on a specified port. Requires the 'prometheus' feature to be enabled. ```APIDOC ## MetricsServer::new ### Description Creates and starts an HTTP server for exporting metrics in Prometheus format on a specified port. Requires the 'prometheus' feature to be enabled. ### Signature ```rust pub async fn new(port: u16, metrics: Arc) -> MMResult ``` ### Parameters #### Path Parameters - **port** (u16) - Required - The port number on which the metrics server will listen. - **metrics** (Arc) - Required - An Arc-wrapped PrometheusMetrics instance to expose. ### Example ```rust use market_maker_rs::analytics::prometheus_export::{ MetricsServer, PrometheusMetrics }; use std::sync::Arc; let metrics = Arc::new(PrometheusMetrics::new()); let server = MetricsServer::new(9090, metrics).await?; ``` ``` -------------------------------- ### Market Maker RS Integration Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/position-and-market-state.md Demonstrates creating and updating market state and inventory positions, calculating unrealized PnL, and determining optimal bid/ask quotes using the Avellaneda-Stoikov strategy. ```rust use market_maker_rs::prelude::*; use market_maker_rs::dec; // Create market state let market = MarketState::new(dec!(100.0), dec!(0.2), 1234567890); // Create and update inventory position let mut position = InventoryPosition::new(); position.update_fill(dec!(10.0), dec!(100.0), 1000); // Calculate unrealized PnL let current_pnl = position.unrealized_pnl(market.mid_price); println!("Unrealized PnL: {}", current_pnl); // Calculate quotes using current market state let (bid, ask) = market_maker_rs::strategy::avellaneda_stoikov::calculate_optimal_quotes( market.mid_price, position.quantity, dec!(0.1), // risk_aversion market.volatility, 3600000, dec!(1.5), // order_intensity )?; println!("Quotes - Bid: {}, Ask: {}", bid, ask); ``` -------------------------------- ### Set Capital Allocation Strategy Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/multi-underlying-feature.md Configure the capital allocation strategy for the MultiUnderlyingManager. This example sets the strategy to RiskParity. ```rust let manager = MultiUnderlyingManager::new(dec!(1_000_000.0)) .with_allocation_strategy(CapitalAllocationStrategy::RiskParity); ``` -------------------------------- ### Example Usage of decimal_sqrt Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/types.md Demonstrates calculating the square root of a Decimal, returning an MMResult. ```rust use market_maker_rs::types::decimal::decimal_sqrt; use market_maker_rs::dec; let result = decimal_sqrt(dec!(9))?; // sqrt(9) = 3 let irrational = decimal_sqrt(dec!(2))?; // sqrt(2) ≈ 1.414 ``` -------------------------------- ### Example Usage of Quantity Type Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/types.md Shows how to define both long and short positions using the Quantity type. ```rust use market_maker_rs::types::primitives::Quantity; use market_maker_rs::dec; let long_position: Quantity = dec!(10.0); let short_position: Quantity = dec!(-5.0); ``` -------------------------------- ### Example Usage of decimal_ln Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/types.md Demonstrates calculating the natural logarithm of a Decimal, returning an MMResult. ```rust use market_maker_rs::types::decimal::decimal_ln; use market_maker_rs::dec; let result = decimal_ln(dec!(2.718281828))?; // ln(e) ≈ 1.0 ``` -------------------------------- ### Typical Portfolio Setup for Crypto Options Market Making Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/multi-underlying-feature.md Sets up a MultiUnderlyingManager for crypto options market making, focusing on major assets like BTC, ETH, SOL, and AVAX. It configures conservative weights, realistic correlations, and specific risk constraints. ```rust use market_maker_rs::multi_underlying:: MultiUnderlyingManager, UnderlyingConfig, CapitalAllocationStrategy ; use market_maker_rs::dec; let mut manager = MultiUnderlyingManager::new(dec!(1_000_000.0)) .with_allocation_strategy(CapitalAllocationStrategy::RiskParity); // Add major assets with conservative weights manager.add_underlying(UnderlyingConfig::new("BTC", dec!(0.50)))?; manager.add_underlying(UnderlyingConfig::new("ETH", dec!(0.30)))?; manager.add_underlying(UnderlyingConfig::new("SOL", dec!(0.15)))?; manager.add_underlying(UnderlyingConfig::new("AVAX", dec!(0.05)))?; // Set realistic correlations // BTC leads the market manager.set_correlation("BTC", "ETH", dec!(0.75))?; manager.set_correlation("BTC", "SOL", dec!(0.65))?; manager.set_correlation("BTC", "AVAX", dec!(0.60))?; // Altcoins correlate with ETH manager.set_correlation("ETH", "SOL", dec!(0.70))?; manager.set_correlation("ETH", "AVAX", dec!(0.68))?; // Low correlation between SOL and AVAX manager.set_correlation("SOL", "AVAX", dec!(0.55))?; // Set constraints let mut constraints = MultiUnderlyingConstraints::default(); constraints.max_total_delta = dec!(100000.0); // $100K total delta exposure constraints.max_total_gamma = dec!(5000.0); // Gamma exposure constraints.max_per_underlying_notional = dec!(500000.0); // $500K per asset // Result: Coordinated market making across BTC, ETH, SOL, AVAX // with diversified correlation exposure ``` -------------------------------- ### LatencyTracker Constructor Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/execution.md Initializes a new LatencyTracker with a maximum sample count. Use this to begin tracking operation latencies. ```rust use market_maker_rs::execution::{LatencyTracker, LatencyTrackerConfig}; let config = LatencyTrackerConfig { max_samples: 10000, }; let tracker = LatencyTracker::new(config); ``` -------------------------------- ### Create Prometheus Metrics Server Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/analytics.md Initializes and starts an HTTP server for exporting metrics in Prometheus format. This requires an instance of PrometheusMetrics and a specified port. ```rust use market_maker_rs::analytics::prometheus_export::{ MetricsServer, PrometheusMetrics }; use std::sync::Arc; let metrics = Arc::new(PrometheusMetrics::new()); let server = MetricsServer::new(9090, metrics).await?; ``` -------------------------------- ### BacktestConfig Builder Methods Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/backtest.md Provides builder-style methods to configure the BacktestEngine, allowing for flexible setup of initial capital, fees, slippage, and other parameters. ```APIDOC ## BacktestConfig Builder Methods ### Description These methods allow for fluent configuration of `BacktestConfig` parameters. ### Methods #### `with_initial_capital` Sets the initial capital for the backtest. - **Signature**: `pub fn with_initial_capital(mut self, capital: Decimal) -> Self` - **Parameters**: `capital` (Decimal) - The starting capital amount. #### `with_fee_rate` Sets the trading fee rate applied to each trade. - **Signature**: `pub fn with_fee_rate(mut self, rate: Decimal) -> Self` - **Parameters**: `rate` (Decimal) - The fee rate as a fraction (e.g., 0.001 for 0.1%). #### `with_slippage` Sets the slippage model to simulate execution price deviations. - **Signature**: `pub fn with_slippage(mut self, model: SlippageModel) -> Self` - **Parameters**: `model` (SlippageModel) - The slippage model to use. #### `with_max_position_size` Sets the maximum allowed position size during the backtest. - **Signature**: `pub fn with_max_position_size(mut self, size: Decimal) -> Self` - **Parameters**: `size` (Decimal) - The maximum position size. ``` -------------------------------- ### Minimal Market Maker RS Dependency Setup Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/configuration.md Add the market-maker-rs crate with its core functionality for strategy calculations, position tracking, risk management, and backtesting. ```toml [dependencies] market-maker-rs = "0.3" ``` -------------------------------- ### Parameter Sensitivity Analysis Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/examples/README.md Demonstrates the impact of key parameters like risk aversion, volatility, and order intensity on quote spreads. Analyzes how these factors influence market making strategy. ```bash cargo run --example parameter_sensitivity ``` -------------------------------- ### Market Making Session Simulation Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/examples/README.md Simulates a market making session with order flow, market price movements, and position management over time. Integrates all components for a realistic workflow. ```bash cargo run --example real_time_simulation ``` -------------------------------- ### Production Market Maker RS Dependency Setup with Features Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/configuration.md Configure market-maker-rs for production by enabling features like serde for serialization, prometheus for metrics, api for monitoring, and events for real-time updates. ```toml [dependencies] market-maker-rs = { version = "0.3", features = [ "serde", "prometheus", "api", "events" ]} ``` -------------------------------- ### Basic Quote Generation Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/examples/README.md Demonstrates fundamental quote calculation using the Avellaneda-Stoikov model, including reservation price and optimal spread calculation. Understand spread composition. ```bash cargo run --example basic_quoting ``` -------------------------------- ### Decimal Arithmetic Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/doc/USER_GUIDE.md Demonstrates the difference between floating-point arithmetic and exact decimal arithmetic for financial calculations. Use `rust_decimal` for precise financial operations. ```rust // ❌ Floating point error let price = 0.1 + 0.2; // 0.30000000000000004 // ✅ Exact decimal arithmetic let price = dec!(0.1) + dec!(0.2); // 0.3 ``` -------------------------------- ### Example Usage of OrderIntensity Type Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/types.md Demonstrates setting the order intensity parameter, which relates to the rate of market orders. ```rust use market_maker_rs::types::primitives::OrderIntensity; use market_maker_rs::dec; let k: OrderIntensity = dec!(1.5); // 1.5 orders/hour ``` -------------------------------- ### Validation and Error Handling Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/examples/README.md Covers configuration validation, market state validation, and numerical error detection. Highlights proper error handling patterns and input validation for robustness. ```bash cargo run --example error_handling ``` -------------------------------- ### Options Trading Market Maker RS Dependency Setup Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/configuration.md Enable features for options trading, including Greeks calculation, multi-strike quoting, cross-asset coordination, and full monitoring capabilities. ```toml [dependencies] market-maker-rs = { version = "0.3", features = [ "serde", "options", "chain", "multi-underlying", "api", "prometheus" ]} ``` -------------------------------- ### Example Usage of MMResult Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/types.md Shows how to use the MMResult type in a function that might return an error, and how to handle the Ok and Err variants. ```rust use market_maker_rs::types::error::MMResult; use market_maker_rs::dec; fn calculate_spread() -> MMResult { Ok(dec!(0.5)) } match calculate_spread() { Ok(spread) => println!("Spread: {}", spread), Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Inventory Impact Analysis Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/examples/README.md Shows how inventory position affects quote placement and reservation price, demonstrating quote skewing behavior. Analyzes the impact of long/short positions on quotes. ```bash cargo run --example inventory_skew ``` -------------------------------- ### Get Default GreeksLimits Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/options-feature.md Provides a default set of GreeksLimits with sensible values for max_delta, max_gamma, max_vega, max_theta, and max_rho. Use this for initial setup when specific limits are not yet defined. ```rust pub fn default() -> Self ``` -------------------------------- ### Get Cross-Asset Hedges and Rebalance Capital Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/multi-underlying-feature.md Illustrates how to obtain cross-asset hedge recommendations and trigger a capital rebalancing based on the current strategy and market conditions. The output shows suggested hedge actions and rebalancing adjustments. ```rust // Get cross-asset hedges if needed let hedges = manager.get_cross_asset_hedges(); for hedge in hedges { println!("Hedge {} with {}: {} qty", hedge.from_symbol, hedge.to_symbol, hedge.quantity); } // Rebalance if needed let actions = manager.rebalance_capital()?; for action in actions { println!("{}: {} -> {}", action.symbol, action.current_weight, action.target_weight); } ``` -------------------------------- ### InvalidConfiguration Error Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/errors.md Demonstrates how to handle an `InvalidConfiguration` error, typically arising from incorrect input parameters like negative risk aversion. This snippet shows error matching and message extraction. ```rust use market_maker_rs::strategy::avellaneda_stoikov::calculate_optimal_quotes; use market_maker_rs::dec; let result = calculate_optimal_quotes( dec!(100.0), dec!(10.0), dec!(-0.1), // ← Invalid: negative risk aversion dec!(0.2), 3600000, dec!(1.5), ); match result { Err(MMError::InvalidConfiguration(msg)) => { println!("Config error: {}", msg); // Output: "Config error: invalid configuration: risk_aversion must be positive" } _ => {} } ``` -------------------------------- ### Create a New GreeksRiskManager Instance Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/options-feature.md Initializes a GreeksRiskManager for a specific underlying symbol with defined risk limits and hedging configuration. Use default limits and hedger config for sensible starting values. ```rust use market_maker_rs::options::{GreeksRiskManager, GreeksLimits, AutoHedgerConfig}; let limits = GreeksLimits::default(); let hedger_config = AutoHedgerConfig::default(); let mut risk_manager = GreeksRiskManager::new("BTC", limits, hedger_config); ``` -------------------------------- ### Configure and Run Backtest Engine Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/README.md Sets up a backtesting engine with initial capital, fee rate, and slippage model, then runs the simulation with a provided strategy and data source. ```rust 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); ``` -------------------------------- ### OrderId Struct Definition and Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/types.md Defines the `OrderId` struct, used to uniquely identify orders on an exchange. An example shows its instantiation with a string identifier. ```rust pub struct OrderId(pub String); use market_maker_rs::execution::OrderId; let order_id = OrderId("BTC-001".to_string()); ``` -------------------------------- ### Initialize and Configure MultiUnderlyingManager Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/multi-underlying-feature.md Demonstrates initializing the MultiUnderlyingManager with capital, setting an allocation strategy, and defining maximum total delta. It also shows how to add underlyings with target weights and set correlations between them. ```rust use market_maker_rs::multi_underlying:: MultiUnderlyingManager, UnderlyingConfig, CapitalAllocationStrategy ; use market_maker_rs::dec; // Initialize with $1M capital let mut manager = MultiUnderlyingManager::new(dec!(1_000_000.0)) .with_allocation_strategy(CapitalAllocationStrategy::RiskParity) .with_max_total_delta(dec!(50000.0)); // Add underlyings with target weights manager.add_underlying(UnderlyingConfig::new("BTC", dec!(0.40)))?; manager.add_underlying(UnderlyingConfig::new("ETH", dec!(0.35)))?; manager.add_underlying(UnderlyingConfig::new("SOL", dec!(0.25)))?; // Set correlations between assets manager.set_correlation("BTC", "ETH", dec!(0.85))?; manager.set_correlation("BTC", "SOL", dec!(0.70))?; manager.set_correlation("ETH", "SOL", dec!(0.75))?; ``` -------------------------------- ### InvalidMarketState Error Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/errors.md Illustrates handling of an `InvalidMarketState` error, which occurs when market data is inconsistent, such as a negative mid-price. The example shows how to catch this specific error variant. ```rust use market_maker_rs::strategy::avellaneda_stoikov::calculate_optimal_quotes; use market_maker_rs::dec; let result = calculate_optimal_quotes( dec!(-100.0), // ← Invalid: negative price dec!(10.0), dec!(0.1), dec!(0.2), 3600000, dec!(1.5), ); match result { Err(MMError::InvalidMarketState(msg)) => { println!("Market error: {}", msg); // Output: "Market error: invalid market state: mid_price must be positive" } _ => {} } ``` -------------------------------- ### NumericalError Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/errors.md Demonstrates catching a `NumericalError`, which arises from failed numerical computations like taking the logarithm of a negative number. The example shows how to match this error and print its message. ```rust use market_maker_rs::types::decimal::decimal_ln; use market_maker_rs::dec; // Logarithm of negative number let result = decimal_ln(dec!(-1.0)); match result { Err(MMError::NumericalError(msg)) => { println!("Numerical error: {}", msg); // Output: "Numerical error: decimal_ln: conversion error" } _ => {} } ``` -------------------------------- ### Configure Backtest Environment Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/configuration.md Set up backtesting configuration with initial capital, fee rates, slippage model, and maximum position size. ```rust use market_maker_rs::backtest::{BacktestConfig, SlippageModel}; let config = BacktestConfig::default() .with_initial_capital(dec!(100000.0)) .with_fee_rate(dec!(0.001)) // 0.1% fees .with_slippage(SlippageModel::Fixed(dec!(0.01))) // $0.01 slippage .with_max_position_size(dec!(100.0)); ``` -------------------------------- ### Example Usage of Volatility Type Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/types.md Demonstrates initializing a Volatility variable, typically ranging from 0.01 to 2.0. ```rust use market_maker_rs::types::primitives::Volatility; use market_maker_rs::dec; let vol: Volatility = dec!(0.25); // 25% annualized ``` -------------------------------- ### Example Usage of decimal_powi Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/types.md Shows calculating powers of a Decimal, including positive and negative exponents, returning an MMResult. ```rust use market_maker_rs::types::decimal::decimal_powi; use market_maker_rs::dec; let result = decimal_powi(dec!(2), 3)?; // 2^3 = 8 let inverse = decimal_powi(dec!(2), -2)?; // 2^-2 = 0.25 ``` -------------------------------- ### Example Usage of Timestamp Type Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/types.md Shows how to declare a Timestamp variable, representing milliseconds since the Unix epoch. ```rust use market_maker_rs::types::primitives::Timestamp; let ts: Timestamp = 1693526400000; // milliseconds since epoch ``` -------------------------------- ### Initialize and Run Backtest Engine Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/INDEX.md Sets up and runs a backtest simulation for a trading strategy. Requires a BacktestConfig, strategy implementation, and data source. ```rust let config = BacktestConfig::default().with_initial_capital(dec!(100000.0)); let mut engine = BacktestEngine::new(config, strategy, data_source); let result = engine.run().await?; ``` -------------------------------- ### Initialize Prometheus Metrics Server Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/configuration.md Sets up a Prometheus metrics server to export library metrics. Requires the 'prometheus' feature and a Tokio runtime. ```rust use market_maker_rs::analytics::prometheus_export::{ PrometheusMetrics, MetricsServer }; use std::sync::Arc; let metrics = Arc::new(PrometheusMetrics::new()); let server = MetricsServer::new(9090, metrics.clone()).await?; // Metrics available at http://localhost:9090/metrics ``` -------------------------------- ### Connection Error Handling Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/errors.md Shows how to handle a ConnectionError when submitting an order asynchronously using the ExchangeConnector trait. ```rust use market_maker_rs::execution::ExchangeConnector; // In practice, when submitting orders asynchronously: async fn submit_order_example(connector: &dyn ExchangeConnector) { match connector.submit_order(order_request).await { Ok(response) => println!("Order submitted: {:?}", response), Err(MMError::ConnectionError(msg)) => { eprintln!("Connection failed: {}", msg); // Output: "Connection failed: connection error: timeout connecting to exchange" } Err(e) => eprintln!("Other error: {}", e), } } ``` -------------------------------- ### Initialize VPINCalculator Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/analytics.md Creates a VPINCalculator with custom configuration for bucket volume and number of buckets. This is used for detecting informed trading and market toxicity. ```rust use market_maker_rs::analytics::vpin::VPINCalculator; use market_maker_rs::dec; let config = VPINConfig { bucket_volume: dec!(1000000.0), // 1M volume per bucket num_buckets: 20, }; let calculator = VPINCalculator::new(config); ``` -------------------------------- ### Example Usage of RiskAversion Type Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/types.md Shows how to set the risk aversion parameter, where higher values indicate a more conservative strategy. ```rust use market_maker_rs::types::primitives::RiskAversion; use market_maker_rs::dec; let gamma: RiskAversion = dec!(0.5); ``` -------------------------------- ### Initialize Options Market Maker Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/configuration.md Sets up an OptionsMarketMaker for calculating Greeks-aware quotes. Requires the 'options' feature. ```rust use market_maker_rs::options::{ OptionsMarketMaker, OptionsMarketMakerImpl, PortfolioGreeks }; let mut portfolio = PortfolioGreeks::new(); let mm = OptionsMarketMakerImpl::new(Default::default()); // Calculate Greeks-aware quotes ``` -------------------------------- ### Compile Project Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/README.md Compile the project. Use `make release` for a release build. ```sh make build # Compile the project make release # Build in release mode make run # Run the main binary ``` -------------------------------- ### Invalid Timestamp Example Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/errors.md Illustrates a scenario where the current time has already passed the terminal time, leading to an InvalidTimestamp error. ```rust use market_maker_rs::strategy::avellaneda_stoikov::calculate_optimal_quotes; // If current time is already past terminal time let terminal_time = 1000000u64; let current_time = 2000000u64; // Already past terminal let time_remaining = 0u64; // Invalid: no time left // Strategy calculations would fail with this scenario ``` -------------------------------- ### Create Options Market Maker Implementation Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/options-feature.md Instantiate the standard OptionsMarketMakerImpl with a default configuration to begin Greeks-aware market making. ```rust use market_maker_rs::options::{OptionsMarketMakerImpl, OptionsMarketMakerConfig}; let config = OptionsMarketMakerConfig::default(); let mm = OptionsMarketMakerImpl::new(config); ``` -------------------------------- ### BacktestStrategy `reset` Method Signature Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/backtest.md The `reset` method is used to reinitialize the strategy's internal state when starting a new backtest run. ```rust fn reset(&mut self) ``` -------------------------------- ### Packaging and Documentation Generation Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/README.md Commands for checking documentation, building docs, and publishing the crate. `make readme` regenerates the README. ```sh make doc # Check for missing docs via clippy make doc-open # Build and open Rust documentation make create-doc # Generate internal docs make readme # Regenerate README using cargo-readme make publish # Prepare and publish crate to crates.io ``` -------------------------------- ### Decimal Construction and Usage Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/types.md Demonstrates how to create and use `Decimal` types for precise numerical calculations, recommended for financial applications to avoid floating-point errors. Includes construction via macro, `from`, and string parsing. ```rust use market_maker_rs::{Decimal, dec}; // Using dec! macro (recommended) let price = dec!(100.50); // Using Decimal::from let qty = Decimal::from(10); // Parsing from strings let vol = Decimal::from_str("0.2").unwrap(); ``` -------------------------------- ### reset Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/chain-feature.md Resets all tracked positions and Greeks to zero, effectively clearing the current risk state. This is useful for starting fresh or during specific operational procedures. ```APIDOC ## reset ### Description Resets all tracked positions and Greeks to zero. ### Method (Not specified, likely internal or part of a larger struct method) ### Parameters (None) ### Returns (None) ``` -------------------------------- ### Initialize Portfolio Greeks Tracker Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/options-feature.md Create a new, empty PortfolioGreeks tracker to aggregate Greeks across multiple option positions. ```rust use market_maker_rs::options::PortfolioGreeks; let mut portfolio = PortfolioGreeks::new(); ``` -------------------------------- ### Get Price Update from Mock Data Feed Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/configuration.md Demonstrates fetching a price update using the MockDataFeed for testing purposes. Requires the 'data-feeds' feature. ```rust use market_maker_rs::data_feeds::{MarketDataFeed, MockDataFeed}; let feed = MockDataFeed::new(); let price_update = feed.get_price_update("BTC").await?; ``` -------------------------------- ### Market Maker RS Module Structure Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/doc/USER_GUIDE.md Displays the directory and file structure of the market-maker-rs project, outlining the organization of source code, examples, tests, and documentation. ```text market-maker-rs/ ├── src/ │ ├── lib.rs # Main library entry │ ├── market_state/ │ │ ├── mod.rs │ │ ├── snapshot.rs # Market state snapshots │ │ └── volatility.rs # Volatility estimators │ ├── position/ │ │ ├── mod.rs │ │ ├── inventory.rs # Inventory tracking │ │ └── pnl.rs # PnL calculation │ ├── strategy/ │ │ ├── mod.rs │ │ ├── avellaneda_stoikov.rs # Core strategy implementation │ │ ├── config.rs # Strategy configuration │ │ ├── interface.rs # Trait definitions │ │ └── quote.rs # Quote representation │ └── types/ │ ├── mod.rs │ ├── decimal.rs # Decimal math helpers │ └── error.rs # Error types ├── examples/ # 12 complete examples ├── tests/ # Integration tests └── doc/ # Documentation ``` -------------------------------- ### Initialize and Use Order Manager Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/QUICK_REFERENCE.md Set up an OrderManager with configuration for order age and polling intervals. Track new orders and retrieve statistics on active orders. ```rust let mut manager = OrderManager::new(OrderManagerConfig { max_order_age_ms: 60000, polling_interval_ms: 100, }); manager.track_order(order_id.clone(), request)?; let stats = manager.get_stats(); println!("Active orders: {}", stats.active_orders); ``` -------------------------------- ### OrderBook-rs Exchange Connector Implementation Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/doc/INTEGRATION_ROADMAP.md Example implementation of the ExchangeConnector trait for OrderBook-rs. This enables market making strategies to interact with the lock-free order book infrastructure. ```rust // Example: OrderBook-rs connector pub struct OrderBookConnector { orderbook: Arc, } #[async_trait] impl ExchangeConnector for OrderBookConnector { async fn submit_order(&self, request: OrderRequest) -> MMResult; async fn cancel_order(&self, order_id: &OrderId) -> MMResult<()>; async fn get_order_book(&self, symbol: &str) -> MMResult; } ``` -------------------------------- ### Import Prelude Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/QUICK_REFERENCE.md Import necessary items from the market_maker_rs prelude and core modules. ```rust use market_maker_rs::prelude::*; use market_maker_rs::{dec, Decimal}; ``` -------------------------------- ### Initialize ChainMarketMaker Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/chain-feature.md Create a new `ChainMarketMaker` instance by providing an `ExpirationOrderBook` and a `ChainMarketMakerConfig`. The `ExpirationOrderBook` should be wrapped in an `Arc`. ```rust use market_maker_rs::chain::{ChainMarketMaker, ChainMarketMakerConfig}; use option_chain_orderbook::orderbook::ExpirationOrderBook; use std::sync::Arc; let chain = Arc::new(ExpirationOrderBook::new("BTC", expiration)); let config = ChainMarketMakerConfig::default(); let mm = ChainMarketMaker::new(chain, config); ``` -------------------------------- ### MarketDataStream Trait Definition Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/api-reference/execution.md Defines the interface for real-time market data streaming. Implementations should provide methods to get order book snapshots and subscribe to trades. ```rust pub trait MarketDataStream: Send + Sync { async fn get_order_book(&self, symbol: &str) -> MMResult; async fn subscribe_to_trades(&self, symbol: &str) -> MMResult>; } ``` -------------------------------- ### Initialize MultiUnderlyingManager for Portfolio Management Source: https://github.com/joaquinbejar/market-maker-rs/blob/main/_autodocs/configuration.md Create a new MultiUnderlyingManager with initial capital and add underlying assets with their respective capital allocations. ```rust use market_maker_rs::multi_underlying::{ MultiUnderlyingManager, UnderlyingConfig }; let mut manager = MultiUnderlyingManager::new(dec!(1_000_000.0)); manager.add_underlying(UnderlyingConfig::new("BTC", dec!(0.40)))?; ```