Skip to content

Ahaif/order_book

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🚀 Rust Order Book

A real-time, concurrent, fault-tolerant Order Book built in Rust.
Supports order matching, order insert/cancel, WebSocket API, structured logging, stress testing, and benchmarking.
Designed with Rust best practices, SOLID principles, security, and fault tolerance.


📦 Architecture

  • src/main.rs — WebSocket server bootstrap & logging initialization
  • src/order.rsOrder model and Side enum (Buy/Sell)
  • src/order_book.rs — core matching engine (insert, cancel, match; price/size book)
  • src/messages.rs — JSON commands: Insert { order }, Cancel { id, price, side }
  • src/ws.rs — WebSocket routing and per-connection async session handling
  • src/bin/client_test.rs — load/stress client (simulates inserts/cancels)
  • benches/ — Criterion benches (insert, cancel, match, integration)

🛠️ How to Run

git clone <repo>
cd order_book

# start server (WebSocket on ws://127.0.0.1:3000/ws)
cargo run --bin ord_book

# run simulated clients (optional)
cargo run --bin client_test

📡 WebSocket API

// Insert order
{ "action": "insert", "order": { "id": 1, "price": 101, "quantity": 10, "side": "Buy" } }

// Cancel order
{ "action": "cancel", "id": 1, "price": 101, "side": "Buy" }

🧪 Testing

cargo test                 # run all tests
cargo test -- --nocapture  # show println!/tracing output
# examples:
#   cargo test partial_match
#   cargo test -- --list
  • Unit tests: insert / cancel / match logic
  • Integration tests: multi-threaded insert + cancel behavior
  • Load tests: client_test simulating concurrent clients

📊 Benchmarking (Criterion)

cargo bench                                # run all benches
cargo bench --bench insert                 # run only the insert bench file
cargo bench --bench insert -- --list       # list benchmarks in the file
cargo bench --bench insert -- --bench "insert 1M orders"  # run by exact name

Reports: target/criterion/<bench_id>/report/index.html (SVG/HTML charts).
Example (1M orders, indicative): Insert ~35–40 ms • Cancel ~12 ms • Match ~40 ms


🧠 Concepts & Patterns

  • Concurrency: async/await on Tokio; one async task per WebSocket connection
  • Shared state: Arc<Mutex<OrderBook>> (short lock scopes)
  • Deterministic structure: BTreeMap for ordered price levels (price-time priority)
  • Serialization: serde for JSON I/O
  • Observability: tracing with daily-rotating file logs (ANSI disabled for clean files)
  • Design: Command pattern (Insert/Cancel), actor-like sessions, repository-style mutation boundary, SOLID module boundaries

🔒 Security & Fault Tolerance

  • Validate incoming JSON commands and side values (Buy/Sell)
  • Isolate each client session; a misbehaving client won’t affect others
  • Bound message sizes and consider timeouts/rate limits if exposed publicly
  • Avoid long-held locks; keep OrderBook critical sections minimal
  • Fail-fast on unrecoverable states; log structured context for analysis

✅ Features

  • Price priority matching (best price wins)
  • Partial fills; limit order fallback when no match
  • Cancel by id/price/side
  • Structured logs for inserts, cancels, and matches
  • Concurrent client handling via WebSockets
  • Benchmarked core operations (Criterion)

🧭 Roadmap

  • Live visualization (React or TUI)
  • Persistence (Postgres/SQLite) for orders & trades
  • Broadcast matched trades to all clients
  • Sharded/lock-free design for high-throughput (HFT) workloads

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages