Overview
NanoARB is organized as a Cargo workspace with 7 crates, each responsible for a distinct layer of the trading system. This modular design enables:- Independent development - Crates can be tested and benchmarked in isolation
- Clear dependencies - One-way dependency graph prevents circular references
- Reusability - Core types and traits shared across all crates
- Fast compilation - Changes to one crate don’t require rebuilding unrelated code
Dependency Graph
Dependency rule: All crates depend onnano-core, and dependencies only flow downward in the stack.
nano-core
Location:crates/nano-core/
Description: Foundation crate providing domain types, traits, constants, and error handling for the entire system.
Key Types
Price (types/price.rs:1)
Fixed-point decimal representation to avoid floating-point errors:
Price::from_ticks(50000, 25) represents $5000.00 with 0.25 tick size.
Quantity (types/quantity.rs:1)
Side (types/side.rs:1)
Timestamp (types/timestamp.rs:1)
Nanosecond-precision timestamp:
Order (types/order.rs:1)
Core Traits
Defines interfaces for all major system components (seetraits.rs:1):
Strategy (traits.rs:48)
OrderBook (traits.rs:6)
ModelInference (traits.rs:160)
Dependencies
rust_decimal- Decimal arithmeticserde/bincode/rkyv- Serializationchrono- Time handlingthiserror- Error types
nano-feed
Location:crates/nano-feed/
Description: CME MDP 3.0 binary protocol parser and synthetic data generator.
Features
- SBE Decoder - Parses Simple Binary Encoding messages from CME
- Zero-copy parsing - Uses
nomcombinator library for allocation-free parsing - Message types - Book updates, trades, channel resets, security status
- Synthetic generator - Creates realistic market data for development and testing
Key Modules
MdpParser (parser.rs:1)
Parses raw CME MDP 3.0 packets:
messages.rs:1):
MDIncrementalRefreshBook(Template 46) - Order book updatesMDIncrementalRefreshTrade(Template 42) - Executed tradesChannelReset(Template 4) - Channel state resetSecurityStatus(Template 30) - Trading status changes
Synthetic Data Generator (synthetic.rs:1)
Generates realistic market microstructure:
- Geometric Brownian Motion for price drift
- Poisson arrivals for order events
- Realistic bid/ask spread and depth
- Correlated buy/sell pressure
Dependencies
nano-core- Core typesnom- Parser combinatorsbytes- Byte manipulationrand/rand_distr- Random number generation
nano-lob
Location:crates/nano-lob/
Description: High-performance limit order book with 20-level depth and HFT feature extraction.
Key Modules
OrderBook (orderbook.rs:1)
benches/orderbook.rs):
- Update operation: 45ns median (P95: 62ns)
- BBO query: 5ns (read-only, no allocation)
- 20-level iteration: 180ns
LobFeatureExtractor (features.rs:1)
Extracts HFT features for ML models:
-
Microprice - Volume-weighted mid:
-
Order Flow Imbalance (OFI):
-
VPIN - Volume-Synchronized Probability of Informed Trading:
-
Book Imbalance:
SnapshotRingBuffer (snapshot.rs:1)
Fixed-size circular buffer for LOB history:
Dependencies
nano-core- Core types and traitsnano-feed- Market data messagesndarray- Tensor operationssmallvec- Stack-allocated vectorsparking_lot- Fast mutexes
nano-model
Location:crates/nano-model/
Description: ONNX-based ML model inference for trading signals.
Features
- ONNX Runtime - Cross-platform inference engine
- Model types - Mamba, Transformer, Decision Transformer, IQL
- Batched inference - Process multiple instruments simultaneously
- Latency tracking - Built-in performance monitoring
Key Types
SignalModel
-
Mamba-LOB - State Space Model (see README.md:295)
- Input: (batch, seq=100, features=40)
- Hidden: 128 dimensions, 4 Mamba blocks
- Output: (batch, horizons=3, classes=3)
- Parameters: ~500K
- Inference: <800ns
-
Decision Transformer - Offline RL
- Predicts optimal actions given past trajectory
- Context window: 20 timesteps
-
IQL - Implicit Q-Learning
- Value-based RL with expectile regression
- Used for market-making policy
Training
Models are trained in Python (seepython/training/) and exported to ONNX:
models/ directory.
Dependencies
nano-core- Core typesnano-lob- Feature extractionndarray- Tensor operationsort(optional) - ONNX Runtime
nano-strategy
Location:crates/nano-strategy/
Description: Trading strategy implementations and RL environment.
Key Modules
MarketMakerStrategy (market_maker.rs:1)
Classic market-making with ML signals:
market_maker.rs:15):
RL Environment (rl_env.rs:1)
Gym-style interface for reinforcement learning:
- Bid offset: {-5, -4, …, 0, …, +4, +5} ticks
- Ask offset: {-5, -4, …, 0, …, +4, +5} ticks
- Total: 11 × 11 = 121 discrete actions
Signal Strategies (signals.rs:1)
ML-driven directional trading:
Dependencies
nano-core- Strategy traitnano-lob- Order book accessnano-model- ML inferencerand- Action sampling
nano-backtest
Location:crates/nano-backtest/
Description: Event-driven backtesting engine with realistic latency and fill simulation.
Architecture
See detailed explanation in Architecture Overview.Key Modules
BacktestEngine (engine.rs:33)
Core simulation loop:
EventQueue (events.rs:186)
Priority queue implementation:
events.rs:10):
MarketData- Book update receivedOrderSubmit- Order sent to exchangeOrderAck- Order acknowledgedOrderFill- Order executedOrderCancel- Cancellation confirmed
LatencySimulator (latency.rs:1)
Models network and processing delays:
SimulatedExchange (execution.rs:1)
Fill simulation with queue position model:
- Limit orders matched only if price crosses
- Queue position estimated from book depth
- Fill probability:
P = min(1, volume_traded / queue_position) - Adverse selection: Market orders get worse average price
PositionTracker (position.rs:1)
Tracks inventory and P&L:
RiskManager (risk.rs:1)
Enforces trading limits:
Dependencies
nano-core- Types and traitsnano-feed- Market datanano-lob- Order booksnano-model- ML modelsstatrs- Statistical functionsrand- Random number generation
nano-gateway
Location:crates/nano-gateway/
Description: System entry point with REST API, metrics export, and configuration management.
Features
- Axum web server - REST API for backtests and state queries
- Server-Sent Events - Real-time streaming to web UI
- Prometheus metrics - Time-series monitoring
- Configuration - TOML-based system config
API Endpoints
Served at http://localhost:9090:| Endpoint | Method | Description |
|---|---|---|
/health | GET | Health check |
/metrics | GET | Prometheus metrics |
/api/state | GET | Full engine state (JSON) |
/api/stream | GET | SSE event stream |
/api/backtest | POST | Run backtest |
Binary Target
nanoarb (src/main.rs)
Main executable:
Dependencies
- All NanoARB crates
axum- Web frameworktokio- Async runtimeprometheus-client- Metricsclap- CLI argument parsingconfig/toml- Configuration
Build Configuration
The workspaceCargo.toml defines shared dependencies:
Compilation Profiles
Testing Strategy
Each crate includes:- Unit tests -
#[cfg(test)]modules in source files - Integration tests -
tests/directory - Benchmarks -
benches/with Criterion.rs - Property tests -
proptestfor randomized testing
Next Steps
- Data Flow - Trace a tick through the system
- Strategy Development - Build custom strategies
- Backtesting Guide - Configure simulations