### Build All Examples Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/examples/README.md Compile all example binaries. Use the --release flag for optimized builds. ```bash cd examples cargo build --bins ``` ```bash cargo build --bins --release ``` -------------------------------- ### Run Prometheus Export Example with Metrics Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/README.md Demonstrates installing the metrics-exporter-prometheus recorder and dumping the exposition payload. Requires the 'metrics' feature to be enabled. ```bash cargo run --features metrics --bin prometheus_export ``` -------------------------------- ### Run OrderBook-rs Examples Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/examples/README.md Examples can be run from the `examples` directory using `cargo run --bin `. Use the `--release` flag for better performance. ```bash cd examples cargo run --bin ``` ```bash cargo run --bin --release ``` -------------------------------- ### Run Examples with Logging Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/examples/README.md Examples support logging via the tracing framework. Adjust log levels using the RUST_LOG environment variable. ```bash # Show only warnings and errors RUST_LOG=warn cargo run --bin depth_analysis ``` ```bash # Show debug information RUST_LOG=debug cargo run --bin depth_analysis ``` ```bash # Show everything including trace RUST_LOG=trace cargo run --bin depth_analysis ``` -------------------------------- ### Run Market Order by Amount Example Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/README.md Execute the market order by amount example using Cargo. This demonstrates the new quote-notional market order functionality. ```bash cargo run -p examples --bin market_order_by_amount ``` -------------------------------- ### Run Basic OrderBook Example Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/examples/README.md Execute the basic_orderbook binary for a comprehensive introduction to fundamental OrderBook API operations. It covers order creation, matching, and management. ```bash cargo run --bin basic_orderbook ``` -------------------------------- ### Run Market Trades Demo with market_trades_demo.rs Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/examples/README.md Demonstrate market order execution, trade generation, and the TradeListener event system. This example shows how to capture and display real-time trade information. ```bash cargo run --bin market_trades_demo ``` -------------------------------- ### Run Enriched Snapshots Example Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/examples/README.md Execute the enriched_snapshots binary to see pre-calculated metrics in order book snapshots. This is useful for high-frequency trading and market data distribution. ```bash cargo run --bin enriched_snapshots ``` -------------------------------- ### Risk Limits Example Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/README.md Example demonstrating the implementation and usage of risk limits within the order book system. ```rust examples/src/bin/risk_limits.rs ``` -------------------------------- ### Market Metrics Example Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/examples/README.md Demonstrates market metrics for algorithmic trading and risk management. Useful for assessing market liquidity, execution planning, and signal generation. ```bash cargo run --bin market_metrics ``` -------------------------------- ### Run Multi-threaded OrderBook Example Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/examples/README.md Execute the multi_threaded_orderbook binary to test the OrderBook's thread-safe operations and lock-free architecture under concurrent load. It demonstrates performance under high contention. ```bash cargo run --bin multi_threaded_orderbook ``` -------------------------------- ### Wire Protocol Roundtrip Example Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/README.md Example demonstrating the roundtrip functionality of the wire protocol. This requires the 'wire' feature to be enabled. ```rust examples/src/bin/wire_roundtrip.rs (`required-features = ["wire"]`). ``` -------------------------------- ### Run Snapshot and Restore with orderbook_snapshot_restore.rs Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/examples/README.md Demonstrate OrderBook state persistence using snapshots with checksum validation and JSON serialization. This example covers creating, validating, and restoring OrderBook states. ```bash cargo run --bin orderbook_snapshot_restore ``` -------------------------------- ### Depth Analysis Example Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/examples/README.md Demonstrates depth analysis methods for market making and liquidity analysis. Use cases include market making strategies, order execution planning, and liquidity analysis. ```bash cargo run --bin depth_analysis ``` -------------------------------- ### Enable and Use Counting Allocator Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/README.md Opt into the 'alloc-counters' feature to use the CountingAllocator. This wraps a GlobalAlloc and tracks allocation statistics. It is not installed by the library rlib. ```rust #[global_allocator] static A: CountingAllocator = ...; ``` -------------------------------- ### Run HFT Simulation with orderbook_hft_simulation.rs Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/examples/README.md Execute a realistic high-frequency trading simulation. This example models real exchange behavior with makers, takers, and cancellers across 30 concurrent threads. ```bash cargo run --bin orderbook_hft_simulation ``` -------------------------------- ### Run Prelude Demo Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/examples/README.md Execute the prelude demo to showcase the convenience of the prelude module for streamlined imports and quick prototyping. It demonstrates single-line imports and immediate access to commonly used types. ```bash cargo run --bin prelude_demo ``` -------------------------------- ### Get Current Engine Sequence Number Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/README.md Use engine_seq() to retrieve the current engine sequence number. This accessor is backed by an AtomicU64 counter. ```rust OrderBook::engine_seq() ``` -------------------------------- ### Build and Run Makefile Commands Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/README.md Compile the project, build in release mode, or run the main binary using these Makefile commands. ```makefile make build # Compile the project make release # Build in release mode make run # Run the main binary ``` -------------------------------- ### Run Trade Listener Channels Demo Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/examples/README.md Run the trade listener channels demo to explore advanced trade listener patterns with channel-based communication for multi-book management and asynchronous processing. Suitable for real-world trading system architectures. ```bash cargo run --bin trade_listener_channels ``` -------------------------------- ### Packaging and Documentation Makefile Commands Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/README.md Manage documentation, generate READMEs, and prepare for publishing to crates.io using these Makefile commands. ```makefile 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 ``` -------------------------------- ### Run Price Level Transition Demo Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/examples/README.md Execute the price level transition demo to test OrderBook behavior during price level transitions and varying distributions. This helps verify state consistency across different configurations. ```bash cargo run --bin price_level_transition ``` -------------------------------- ### Configure and Test Pre-Trade Risk Limits Source: https://context7.com/joaquinbejar/orderbook-rs/llms.txt Shows how to set up `RiskConfig` for per-account guardrails including maximum open orders, notional exposure, and price bands. Breaches result in specific `OrderBookError` variants. ```rust use orderbook_rs::OrderBook; use orderbook_rs::orderbook::risk::{ReferencePriceSource, RiskConfig}; use orderbook_rs::OrderBookError; use pricelevel::{Hash32, Id, Side, TimeInForce}; let mut book = OrderBook::<()>::new("BTC/USD"); // Seed a reference trade so LastTrade resolves to 100 book.add_limit_order_with_user(Id::from_u64(1), 100, 1, Side::Sell, TimeInForce::Gtc, Hash32::new([99u8;32]), None).unwrap(); book.submit_market_order_with_user(Id::from_u64(2), 1, Side::Buy, Hash32::new([98u8;32])).unwrap(); book.set_risk_config( RiskConfig::new() .with_max_open_orders_per_account(2) .with_max_notional_per_account(5_000) .with_price_band_bps(1_000, ReferencePriceSource::LastTrade), // ±10% ); let acct = Hash32::new([1u8; 32]); // First two bids admitted book.add_limit_order_with_user(Id::from_u64(10), 100, 1, Side::Buy, TimeInForce::Gtc, acct, None).unwrap(); book.add_limit_order_with_user(Id::from_u64(11), 100, 1, Side::Buy, TimeInForce::Gtc, acct, None).unwrap(); // Third bid violates max_open_orders let err = book .add_limit_order_with_user(Id::from_u64(12), 100, 1, Side::Buy, TimeInForce::Gtc, acct, None) .unwrap_err(); assert!(matches!(err, OrderBookError::RiskMaxOpenOrders { current: 2, limit: 2, .. })); // Price too far from reference (50 is 50% away, limit is 10%) let other = Hash32::new([2u8; 32]); let err = book .add_limit_order_with_user(Id::from_u64(13), 50, 1, Side::Buy, TimeInForce::Gtc, other, None) .unwrap_err(); assert!(matches!(err, OrderBookError::RiskPriceBand { submitted: 50, .. })); ``` -------------------------------- ### Run Trade Listener Demo Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/examples/README.md Execute the trade listener demo to monitor trades in real-time using the TradeListener callback system. This is useful for immediate trade notifications and understanding order execution. ```bash cargo run --bin trade_listener_demo ``` -------------------------------- ### Integrate Prometheus Metrics with Orderbook-rs Source: https://context7.com/joaquinbejar/orderbook-rs/llms.txt Install a Prometheus recorder and use orderbook-rs to generate metrics. Metrics are exposed on the default Prometheus endpoint. Ensure the 'metrics' feature is enabled in your Cargo.toml. ```rust // Cargo.toml // orderbook-rs = { version = "0.8", features = ["metrics"] } use metrics_exporter_prometheus::PrometheusBuilder; use orderbook_rs::OrderBook; use pricelevel::{Id, Side, TimeInForce}; // Install a Prometheus recorder (e.g. expose on :9090/metrics) let _handle = PrometheusBuilder::new() .install_recorder() .expect("install prometheus recorder"); let book: OrderBook<()> = OrderBook::new("BTC/USD"); book.add_limit_order(Id::new_uuid(), 9_900, 10, Side::Buy, TimeInForce::Gtc, None).unwrap(); book.add_limit_order(Id::new_uuid(), 10_000, 5, Side::Sell, TimeInForce::Gtc, None).unwrap(); // Trigger a market fill → orderbook_trades_total increments book.submit_market_order(Id::new_uuid(), 5, Side::Buy).unwrap(); // Trigger a rejection → orderbook_rejects_total{reason="InsufficientLiquidity"} increments let _ = book.submit_market_order(Id::new_uuid(), 1_000_000, Side::Buy); // Metrics are now queryable from the Prometheus endpoint: // orderbook_depth_levels_bid 1 // orderbook_depth_levels_ask 1 // orderbook_trades_total 1 // orderbook_rejects_total{reason="InsufficientLiquidity"} 1 ``` -------------------------------- ### Implement Simple Market Maker Strategy in Rust Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/doc/USER_GUIDE.md Use this strategy to place bid and ask orders when the spread is sufficiently tight. Requires the `orderbook_rs::prelude::*` import. ```rust use orderbook_rs::prelude::*; fn market_maker_strategy(book: &OrderBook) -> Result<(), OrderBookError> { // Get current market state let snapshot = book.enriched_snapshot(5); if let (Some(mid), Some(spread_bps)) = (snapshot.mid_price, snapshot.spread_bps) { // Only make markets if spread is tight enough if spread_bps < 20.0 { let offset = 5.0; let bid_price = (mid - offset) as u64; let ask_price = (mid + offset) as u64; // Place orders book.add_limit_order( OrderId::new(), bid_price, 10, Side::Buy, TimeInForce::Gtc, None )?; book.add_limit_order( OrderId::new(), ask_price, 10, Side::Sell, TimeInForce::Gtc, None )?; println!("Market making: bid @ {}, ask @ {}", bid_price, ask_price); } else { println!("Spread too wide: {:.2} bps", spread_bps); } } Ok(()) } ``` -------------------------------- ### Get Next Engine Sequence Number Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/README.md Use next_engine_seq() to obtain the next available sequence number for outbound emissions. This is backed by an AtomicU64 counter and ensures a unique sequence for each event. ```rust OrderBook::next_engine_seq() ``` -------------------------------- ### Create and Add Limit Orders Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/doc/USER_GUIDE.md Initialize an OrderBook and add limit buy and sell orders. Retrieves the best bid and ask prices after addition. ```rust use orderbook_rs::prelude::*; // Create order book let book = OrderBook::<()>::new("BTC/USD"); // Add buy order let order_id = OrderId::new(); let result = book.add_limit_order( order_id, 50000, // price 10, // quantity Side::Buy, TimeInForce::Gtc, None // no extra data ); // Add sell order let order_id2 = OrderId::new(); book.add_limit_order( order_id2, 50100, // price 10, // quantity Side::Sell, TimeInForce::Gtc, None )?; // Get best bid/ask if let Some(best_bid) = book.best_bid() { println!("Best bid: {}", best_bid); } if let Some(best_ask) = book.best_ask() { println!("Best ask: {}", best_ask); } ``` -------------------------------- ### Efficiently Get Multiple Order Book Metrics Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/doc/USER_GUIDE.md Utilize `enriched_snapshot` to retrieve multiple order book metrics in a single pass, which is more efficient than calling individual metric functions multiple times. ```rust // ❌ Inefficient: Multiple passes let mid = book.mid_price(); let spread = book.spread_bps(); let depth = book.total_depth_at_levels(Side::Buy, 10); let vwap = book.vwap(Side::Buy, 10); // ✅ Efficient: Single pass let snapshot = book.enriched_snapshot(10); let mid = snapshot.mid_price; let spread = snapshot.spread_bps; let depth = snapshot.bid_depth_total; let vwap = snapshot.vwap_bid; ``` -------------------------------- ### Add Limit Order with User Identity for STP Source: https://context7.com/joaquinbejar/orderbook-rs/llms.txt Use `add_limit_order_with_user` to attach a user identity for Self-Trade Prevention (STP). This is required when STP is enabled and optional otherwise. The example shows STP preventing a self-match and a successful match with a different user. ```rust use orderbook_rs::OrderBook; use orderbook_rs::orderbook::stp::STPMode; use pricelevel::{Hash32, Id, Side, TimeInForce}; let book: OrderBook<()> = OrderBook::new("BTC/USD"); book.set_stp_mode(STPMode::CancelTaker); let user_a = Hash32::new([1u8; 32]); let user_b = Hash32::new([2u8; 32]); // Resting ask from user A book.add_limit_order_with_user( Id::from_u64(1), 10_000, 5, Side::Sell, TimeInForce::Gtc, user_a, None, ).unwrap(); // Incoming bid from user A — STP fires, taker cancelled let err = book .add_limit_order_with_user( Id::from_u64(2), 10_000, 5, Side::Buy, TimeInForce::Gtc, user_a, None, ) .unwrap_err(); println!("{err}"); // self-trade prevented (CancelTaker): taker , user // Incoming bid from user B — matches normally book.add_limit_order_with_user( Id::from_u64(3), 10_000, 5, Side::Buy, TimeInForce::Gtc, user_b, None, ).unwrap(); ``` -------------------------------- ### Manage Multiple Order Books with BookManagerStd Source: https://context7.com/joaquinbejar/orderbook-rs/llms.txt Use BookManagerStd to manage a collection of order books keyed by symbol. It supports adding books, starting a trade processor, adding orders to specific books, and performing mass cancellations across all books. ```rust use orderbook_rs::orderbook::manager::{BookManager, BookManagerStd}; use pricelevel::{Hash32, Id, Side, TimeInForce}; let mut mgr: BookManagerStd<()> = BookManagerStd::new(); mgr.add_book("BTC/USD"); mgr.add_book("ETH/USD"); // Start the trade processor in a background thread let _handle = mgr.start_trade_processor().unwrap(); // Add orders to individual books if let Some(book) = mgr.get_book("BTC/USD") { book.add_limit_order(Id::new_uuid(), 100, 10, Side::Buy, TimeInForce::Gtc, None).unwrap(); book.add_limit_order(Id::new_uuid(), 110, 5, Side::Sell, TimeInForce::Gtc, None).unwrap(); } // Mass cancel across all books (e.g. emergency halt) let results = mgr.cancel_all_across_books(); for (symbol, result) in &results { println!("{symbol}: cancelled {}", result.cancelled_count()); } // Cancel a specific user across all books let user = Hash32::new([1u8; 32]); let by_user = mgr.cancel_by_user_across_books(user); println!("books: {}", mgr.book_count()); // 2 ``` -------------------------------- ### Coverage and Benchmarks Makefile Commands Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/README.md Generate code coverage reports (XML and HTML), run benchmarks with Criterion, and manage benchmark data using these Makefile commands. ```makefile make coverage # Generate code coverage report (XML) make coverage-html # Generate HTML coverage report make open-coverage # Open HTML report make bench # Run benchmarks using Criterion make bench-show # Open benchmark report make bench-save # Save benchmark history snapshot make bench-compare # Compare benchmark runs make bench-json # Output benchmarks in JSON make bench-clean # Remove benchmark data ``` -------------------------------- ### Run Allocation Benchmarks Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/BENCH.md Execute the allocation counter benchmark to measure allocs/op and bytes_alloc/op. Also run integration tests to catch order-of-magnitude regressions in CI. ```bash cargo bench --features alloc-counters --bench alloc_count ``` ```bash cargo test --features alloc-counters alloc_budget ``` -------------------------------- ### Run HDR Benchmarks Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/BENCH.md Execute all HDR benchmark scenarios or a single scenario for detailed tail-latency analysis. Bench results are stored in target/bench-hdr/. ```bash make bench-hdr ``` ```bash cargo bench --bench mixed_70_20_10_hdr ``` -------------------------------- ### Create and Restore OrderBook Snapshots Source: https://context7.com/joaquinbejar/orderbook-rs/llms.txt Generate lightweight snapshots of the top N bid/ask levels or perform full state round-trips using JSON or binary serialization. Use `create_snapshot` for market data feeds and `to_snapshot_package`/`restore_from_snapshot_package` for full state persistence. ```rust use orderbook_rs::OrderBook; use pricelevel::{Id, Side, TimeInForce}; let book: OrderBook<()> = OrderBook::new("BTC/USD"); book.add_limit_order(Id::new_uuid(), 9_900, 10, Side::Buy, TimeInForce::Gtc, None).unwrap(); book.add_limit_order(Id::new_uuid(), 10_000, 5, Side::Sell, TimeInForce::Gtc, None).unwrap(); // Lightweight top-3 snapshot (for market-data feeds) let snap = book.create_snapshot(3); println!("symbol={} bids={} asks={}", snap.symbol, snap.bids.len(), snap.asks.len()); for level in &snap.bids { println!(" bid price={} qty={}", level.price(), level.visible_quantity()); } // Full round-trip snapshot let pkg = book.to_snapshot_package().expect("serialize"); let json = serde_json::to_string(&pkg).unwrap(); let restored: OrderBook<()> = OrderBook::restore_from_snapshot_package( serde_json::from_str(&json).unwrap(), ).expect("restore"); assert_eq!(restored.best_bid(), book.best_bid()); assert_eq!(restored.best_ask(), book.best_ask()); ``` -------------------------------- ### Intelligent Order Placement with Orderbook-rs Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/doc/USER_GUIDE.md Optimize order placement by calculating queue position, finding prices within specific ticks, and adjusting for depth. Ideal for market makers and smart routing. ```rust // Get queue position at specific price let queue_ahead = book.queue_ahead_at_price(50000, Side::Buy); println!("Orders ahead: {}", queue_ahead); // Calculate price N ticks inside let price = book.price_n_ticks_inside(Side::Buy, 3); // 3 ticks inside best bid // Find price for queue position let target_price = book.price_for_queue_position(Side::Buy, 100); // Get depth-adjusted price let adjusted_price = book.price_at_depth_adjusted(Side::Buy, 1000, 0.95); ``` -------------------------------- ### GitHub Actions Simulation Makefile Commands Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/README.md Simulate GitHub Actions workflows for build, lint, test, and coverage directly from your local machine using these Makefile commands. Requires 'act' and 'cargo-tarpaulin'. ```makefile make workflow-build # Simulate build workflow make workflow-lint # Simulate lint workflow make workflow-test # Simulate test workflow make workflow-coverage # Simulate coverage workflow make workflow # Run all workflows ``` -------------------------------- ### Test and Quality Makefile Commands Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/README.md Execute tests, format code, check formatting, run clippy, auto-fix lint issues, and apply Rust compiler suggestions with these Makefile commands. ```makefile make test # Run all tests make fmt # Format code make fmt-check # Check formatting without applying make lint # Run clippy with warnings as errors make lint-fix # Auto-fix lint issues make fix # Auto-fix Rust compiler suggestions make check # Run fmt-check + lint + test ``` -------------------------------- ### Run HDR Benchmarks Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/BENCH.md Executes the HDR benchmark suite. Raw histogram data is saved to target/bench-hdr/*.hgrm. ```bash git checkout issue-56-hdr-bench # or main once merged make bench-hdr cat target/bench-hdr/*.hgrm # raw histograms ``` -------------------------------- ### Run Benchmarks Locally Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/BENCHMARKS.md Execute all benchmarks for the project locally using Cargo. Ensure all features are enabled for a comprehensive test. ```sh cargo bench --all-features ``` -------------------------------- ### RiskConfig Builder Pattern Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/README.md Demonstrates the builder pattern for configuring the pre-trade risk layer, allowing opt-in guard-rails like max open orders and price bands. ```rust New [`RiskConfig`] with three opt-in guard-rails: `max_open_orders_per_account`, `max_notional_per_account`, and `price_band_bps` against a configurable [`ReferencePriceSource`] (`LastTrade` / `Mid` / `FixedPrice`). Builder pattern — `RiskConfig::new().with_*(...)` chained. ``` -------------------------------- ### Add Various Order Types Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/doc/USER_GUIDE.md Demonstrates adding limit, iceberg, and market orders to the order book. Ensure TimeInForce and Side are correctly specified. ```rust // Limit order let order_id = OrderId::new(); book.add_limit_order( order_id, 50000, // price 100, // quantity Side::Buy, TimeInForce::Gtc, None )?; // Iceberg order (visible: 10, total: 100) let order_id = OrderId::new(); book.add_iceberg_order( order_id, 50000, // price 100, // total quantity 10, // visible quantity Side::Buy, TimeInForce::Gtc, None )?; // Market order let order_id = OrderId::new(); book.add_market_order( order_id, 50, // quantity Side::Buy, None )?; ``` -------------------------------- ### Persist and Restore Order Book State with Snapshots Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/doc/USER_GUIDE.md Create a snapshot of the order book's current state for persistence, serialize it to JSON, and save it. Later, deserialize the JSON and restore the book from the snapshot. ```rust // Create snapshot for persistence let snapshot = book.create_snapshot(10); let json = serde_json::to_string(&snapshot)?; // Save to file/database std::fs::write("orderbook_snapshot.json", json)?; // Restore later let json = std::fs::read_to_string("orderbook_snapshot.json")?; let snapshot: OrderBookSnapshot = serde_json::from_str(&json)?; book.restore_from_snapshot(snapshot)?; ``` -------------------------------- ### Git and Workflow Helper Makefile Commands Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/README.md Utilize Git log, check for specific language usage, create zip archives, and visualize the project tree with these Makefile commands. ```makefile make git-log # Show commits on current branch vs main make check-spanish # Check for Spanish words in code make zip # Create zip without target/ and temp files make tree # Visualize project tree (excludes common clutter) ``` -------------------------------- ### Use u64 for Prices and Quantities Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/doc/USER_GUIDE.md Employ u64 for representing prices and quantities in base units to ensure precision and performance. Use f64 only for calculated metrics like VWAP. ```rust // Use u64 for prices and quantities (base units) let price: u64 = 50000; // $500.00 in cents let quantity: u64 = 100; // Use f64 only for calculated metrics let vwap: f64 = book.vwap(Side::Buy, 10).unwrap_or(0.0); ``` -------------------------------- ### Generate Enriched Snapshots with Metrics Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/doc/USER_GUIDE.md Obtain pre-calculated metrics like mid-price and spread in a single pass. Optionally select specific metrics using MetricFlags for performance. The resulting snapshot can be serialized for distribution. ```rust let snapshot = book.enriched_snapshot(10); println!("Mid price: {:?}", snapshot.mid_price); println!("Spread: {:?} bps", snapshot.spread_bps); println!("Bid depth: {}", snapshot.bid_depth_total); println!("Ask depth: {}", snapshot.ask_depth_total); println!("Imbalance: {}", snapshot.order_book_imbalance); println!("VWAP bid: {:?}", snapshot.vwap_bid); println!("VWAP ask: {:?}", snapshot.vwap_ask); ``` ```rust use orderbook_rs::MetricFlags; let snapshot = book.enriched_snapshot_with_metrics( 10, MetricFlags::MID_PRICE | MetricFlags::SPREAD ); // Serialize for distribution let json = serde_json::to_string(&snapshot)?; ``` -------------------------------- ### Replay Engine with Deterministic Clock Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/README.md ReplayEngine::replay_from_with_clock enables byte-identical replay tests and disaster-recovery pipelines by using a deterministic clock. ```rust ReplayEngine::replay_from_with_clock ``` -------------------------------- ### Configure Exchange Fees with FeeSchedule Source: https://context7.com/joaquinbejar/orderbook-rs/llms.txt Use FeeSchedule to configure maker and taker fees in basis points. Negative maker values represent rebates. Fees are calculated and attached to TradeResult objects. ```rust use orderbook_rs::FeeSchedule; use orderbook_rs::OrderBook; use pricelevel::{Id, Side, TimeInForce}; // -2 bps maker rebate, +5 bps taker fee let schedule = FeeSchedule::new(-2, 5); let notional: u128 = 10_000_000; // $10,000 let taker_fee = schedule.calculate_fee(notional, false); // +5_000 let maker_rebate = schedule.calculate_fee(notional, true); // -2_000 println!("taker_fee={taker_fee} maker_rebate={maker_rebate}"); // taker_fee=5000 maker_rebate=-2000 assert!(schedule.has_maker_rebate()); assert!(!schedule.is_zero_fee()); // Attach to a book — fees appear on every TradeResult let mut book = OrderBook::<()>::new("BTC/USD"); book.set_fee_schedule(Some(schedule)); ``` -------------------------------- ### Import OrderBook Prelude Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/doc/USER_GUIDE.md Use the prelude for simplified imports of common OrderBook-rs types and functions. ```rust use orderbook_rs::prelude::*; ``` -------------------------------- ### Enable Logging and Inspect Order Book State in Rust Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/doc/USER_GUIDE.md Enable debug logging by setting the RUST_LOG environment variable and initializing the tracing subscriber. Inspect the order book's state by printing bid/ask levels and order counts. ```rust // Enable logging std::env::set_var("RUST_LOG", "debug"); tracing_subscriber::fmt::init(); // Check order book state println!("Bid levels: {}", book.bid_levels()); println!("Ask levels: {}", book.ask_levels()); println!("Total orders: {}", book.bid_levels() + book.ask_levels()); ``` -------------------------------- ### Submit Notional Market Order by Amount Source: https://context7.com/joaquinbejar/orderbook-rs/llms.txt Submits a market order to sweep the book and spend up to a specified amount in quote-asset units. Quantity is computed per price level and rounded down to the nearest lot size. Returns an error if insufficient liquidity is available to fund a complete lot. ```rust use orderbook_rs::OrderBook; use pricelevel::{Id, Side, TimeInForce}; // lot_size = 10 base units let book: OrderBook<()> = OrderBook::with_lot_size("BTC/USDT", 10); book.add_limit_order(Id::new_uuid(), 100, 50, Side::Sell, TimeInForce::Gtc, None).unwrap(); book.add_limit_order(Id::new_uuid(), 101, 50, Side::Sell, TimeInForce::Gtc, None).unwrap(); // Spend up to 5_000 USDT — buys 50 units at price 100 let result = book.submit_market_order_by_amount(Id::new_uuid(), 5_000, Side::Buy).unwrap(); println!( "trades={} executed_qty={:?} executed_value={:?}", result.trades().len(), result.executed_quantity(), result.executed_value(), ); // Amount too small to buy even one lot → error let err = book .submit_market_order_by_amount(Id::new_uuid(), 50, Side::Buy) .unwrap_err(); println!("{err}"); // Insufficient liquidity by notional for Buy order: ... ``` -------------------------------- ### HDR-Histogram Benchmarking Command Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/README.md Convenience command to run the HDR-histogram based benchmarking suite for the order book. ```bash make bench-hdr ``` -------------------------------- ### Add OrderBook Dependency Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/doc/USER_GUIDE.md Add the orderbook-rs and pricelevel crates to your Cargo.toml file to include the library in your project. ```toml [dependencies] orderbook-rs = "0.4" pricelevel = "0.4" ``` -------------------------------- ### Simulate Order Execution with Orderbook-rs Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/doc/USER_GUIDE.md Simulate market order execution to assess pre-trade impact on price and cost. Helps in deciding between market and limit orders based on impact. ```rust // Simulate market order let simulation = book.simulate_market_order(Side::Buy, 1000); println!("Average price: {}", simulation.average_price); println!("Total cost: {}", simulation.total_cost); println!("Price impact: {:.2}%", simulation.price_impact_percentage); println!("Levels consumed: {}", simulation.levels_consumed); // Decide based on impact if simulation.price_impact_percentage < 0.5 { // Execute order book.add_market_order(order_id, 1000, Side::Buy, None)?; } else { // Impact too high, use limit order instead book.add_limit_order( order_id, simulation.average_price as u64, 1000, Side::Buy, TimeInForce::Gtc, None )?; } ``` -------------------------------- ### Track Order Lifecycle with OrderStateTracker Source: https://context7.com/joaquinbejar/orderbook-rs/llms.txt Enable OrderStateTracker to record the full lifecycle of orders, including timestamps. Terminal entries are evicted by FIFO when retention capacity is exceeded. ```rust use orderbook_rs::OrderBook; use orderbook_rs::orderbook::order_state::{OrderStateTracker, OrderStatus}; use pricelevel::{Id, Side, TimeInForce}; use std::sync::Arc; let mut book = OrderBook::<()>::new("BTC/USD"); book.enable_order_state_tracker(OrderStateTracker::new()); let id = Id::new_uuid(); book.add_limit_order(id, 9_900, 10, Side::Buy, TimeInForce::Gtc, None).unwrap(); // Check state let status = book.order_state(id); assert_eq!(status, Some(OrderStatus::Open)); // Fill it with a sell market order book.add_limit_order(Id::new_uuid(), 9_900, 10, Side::Sell, TimeInForce::Gtc, None).unwrap(); let status_after = book.order_state(id); assert!(matches!(status_after, Some(OrderStatus::Filled { .. }))); // Retrieve full history if let Some(history) = book.order_history(id) { for (ts_ms, st) in &history { println!("{ts_ms}ms → {st}"); } } // 1700000000000ms → Open // 1700000000001ms → Filled(10) ``` -------------------------------- ### Bincode 2.x Wire-Format Differences Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/README.md Note that bincode 1.x and 2.x produce different byte layouts. The on-disk journal using serde_json is unaffected, and the snapshot format version remains 1. ```rust ORDERBOOK_SNAPSHOT_FORMAT_VERSION ``` -------------------------------- ### Monitor Liquidity with Orderbook Statistics in Rust Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/doc/USER_GUIDE.md This function provides a liquidity report by calculating depth statistics and checking for thin books or imbalances. It uses `Side::Buy` and `Side::Sell` for analysis. ```rust fn monitor_liquidity(book: &OrderBook) { let stats_bid = book.depth_statistics(Side::Buy, 10); let stats_ask = book.depth_statistics(Side::Sell, 10); println!("Liquidity Report:"); println!(" Bid side:"); println!(" Total volume: {}", stats_bid.total_volume); println!(" Std dev: {:.2}", stats_bid.std_dev_level_size); println!(" Ask side:"); println!(" Total volume: {}", stats_ask.total_volume); println!(" Std dev: {:.2}", stats_ask.std_dev_level_size); // Check for thin book if book.is_thin_book(1000, 5) { println!("⚠️ WARNING: Thin book detected!"); println!(" Recommendation: Reduce position sizes"); } // Check for imbalance let imbalance = book.order_book_imbalance(5); if imbalance.abs() > 0.3 { if imbalance > 0.0 { println!("📈 Strong buy pressure detected"); } else { println!("📉 Strong sell pressure detected"); } } } ``` -------------------------------- ### Check Liquidity Before Market Order in Rust Source: https://github.com/joaquinbejar/orderbook-rs/blob/main/doc/USER_GUIDE.md Before executing a market order, verify if sufficient liquidity is available. If not, consider using a limit order instead. ```rust // Check available liquidity first let depth = book.total_depth_at_levels(Side::Sell, 0); // All levels if depth < quantity { println!("Insufficient liquidity: {} available, {} needed", depth, quantity); // Use limit order instead book.add_limit_order(order_id, price, quantity, Side::Buy, TimeInForce::Gtc, None)?; } else { book.add_market_order(order_id, quantity, Side::Buy, None)?; } ```