nanobook
Rust execution layer for Python trading strategies.
nanobook is for traders and researchers who already generate signals or target weights in Python, but want execution mechanics handled by compiled, deterministic Rust code: portfolio accounting, transaction costs, stops, limit-order-book simulation, pre-trade risk checks, and optional IBKR rebalancing.
Keep factor research, sizing, and scheduling in Python. Use nanobook for the stateful execution layer around it.
Architecture
┌─────────────────────────────────────────────────┐
│ Your Python Strategy (private) │
│ Factors · Signals · Sizing · Scheduling │
├─────────────────────────────────────────────────┤
│ nanobook (Rust, open-source) │
│ ┌──────────┬──────────┬──────────┬──────────┐ │
│ │ Broker │ Risk │Portfolio │ LOB │ │
│ │ IBKR │ Engine │Simulator │ Engine │ │
│ │ Binance │ PreTrade │ Backtest │ 6M ops/s │ │
│ └──────────┴──────────┴──────────┴──────────┘ │
│ Rebalancer CLI: weights → diff → execute │
└─────────────────────────────────────────────────┘
Use Cases
- Backtest target-weight strategies from Python with Rust portfolio accounting.
- Simulate rebalances, transaction costs, fixed/trailing stops, and portfolio metrics.
- Test limit-order-book behavior with deterministic matching and event logs.
- Run pre-trade risk checks for concentration, leverage, and short exposure.
- Rebalance an IBKR account from a target-weight file with dry-run and audit logs.
What nanobook is NOT
- Not a full trading platform. For venue breadth, calendars, and operator UIs, see NautilusTrader or LEAN.
- Not a connector zoo. For broad crypto exchange coverage, see CCXT or Hummingbot.
- Not a research framework. For vectorized backtests and factor research, see vectorbt or Riskfolio-Lib.
- Not FIX. No FIX 4.4 / 5.0 adapter and none is planned.
- Not an OMS (yet). Event-sourced OMS with deterministic replay is on the v1.0 roadmap.
nanobook is a compact Rust execution kernel for Python strategies: limit-order-book matching, portfolio simulation, broker abstraction, pre-trade risk, and rebalancer, all in one MIT-licensed workspace.
Python computes what to trade — factor rankings, signals, target weights. nanobook executes how — order routing, risk checks, portfolio simulation, and a deterministic matching engine. Clean separation: strategy logic stays in Python, execution runs in Rust.
Workspace
| Crate | Description |
|---|---|
nanobook |
Core Rust crate: deterministic LOB, portfolio simulator, metrics, backtest bridge, GARCH, optimizers |
nanobook-broker |
Broker trait with IBKR and Binance adapters |
nanobook-risk |
Pre-trade risk engine (position limits, leverage, short exposure) |
nanobook-python |
PyO3 bindings for all layers |
nanobook-rebalancer |
CLI: target weights → IBKR execution with audit trail |
Install
Python:
Rust:
[]
= "0.9.3"
From source:
# Python bindings
&&
# Binance adapter (feature-gated, not in PyPI wheels)
&&
The Bridge: Python Strategy → Rust Execution
The canonical integration pattern — Python computes a weight schedule, Rust simulates the portfolio and returns metrics:
=
# per-period symbol weights
# stop trigger metadata
Your optimizer produces weights. backtest_weights() handles rebalancing,
cost modeling, position tracking, and return computation at compiled speed
with the GIL released.
v0.9 additions: fixed-parameter EWMA-style GARCH forecasting, portfolio optimizers (min-variance, max-Sharpe, risk-parity, inverse CVaR, inverse CDaR), and trailing/fixed stop-loss simulation — all accessible from Python.
Optimizer Example
# Daily returns matrix (T × N)
= * 0.01
=
Layer Examples
LOB Engine (Rust)
use ;
let mut exchange = new;
exchange.submit_limit;
let result = exchange.submit_limit;
assert_eq!;
assert_eq!;
Portfolio + Metrics (Python)
=
=
Broker + Risk (Python)
# Pre-trade risk check
=
=
# Execute through IBKR
=
=
Rebalancer CLI
# Build
# Dry run — show plan without executing
# Execute with confirmation prompt
# Compare actual vs target positions
Performance
Single-threaded benchmarks (macOS arm64, v0.10.0, stock clocks):
| Operation | Latency | Throughput |
|---|---|---|
| Submit (no match) | ~155 ns | ~6.4M ops/sec |
| Submit (with match) | ~197 ns | ~5M ops/sec |
| BBO query | ~1.1 ns | ~900M ops/sec |
| Cancel (tombstone, deep queue) | ~385 ns | ~2.6M ops/sec |
| L2 snapshot (10 levels) | ~255 ns | ~4M ops/sec |
Numbers are criterion medians measured with cargo bench --bench throughput.
Hardware, build flags, and background load all move these ±10-20 %. See
benches/README.md for the methodology and benches/v0.10-comparison.md
for the v0.9.3 → v0.10.0 delta (the v0.10.0 submit path pays a ~20 ns cost
for the new self-trade-prevention field even with STP off — a future
revision will lift the off-path check out of the matching loop).
Single-threaded throughput is roughly equivalent to Numba (both compile to LLVM IR). Where Rust wins: zero cold-start, true parallelism via Rayon with no GIL contention, and deterministic memory without GC pauses.
Feature Flags
| Feature | Default | Description |
|---|---|---|
event-log |
Yes | Event recording for deterministic replay |
serde |
No | Serialize/deserialize all public types |
persistence |
No | File-based event sourcing (JSON Lines) |
portfolio |
No | Portfolio engine, position tracking, metrics, strategy trait |
parallel |
No | Rayon-based parallel parameter sweeps |
itch |
No | NASDAQ ITCH 5.0 binary protocol parser |
Design Constraints
Engineering decisions that keep the system simple and fast:
- Single-threaded — deterministic by design; same inputs always produce same outputs
- In-process — no networking overhead; wrap externally if needed
- No compliance layer — no self-trade prevention or circuit breakers (out of scope)
- No complex order types — no iceberg or pegged orders
Documentation
- Full developer reference is merged below in this README (
## Full Reference (Merged from DOC.md)). - docs.rs — Rust API docs
License
MIT
Full Reference (Merged from DOC.md)
Developer Reference — Full API documentation for the nanobook workspace.
Table of Contents
- Quick Start
- Core Concepts
- Exchange API
- Types Reference
- Book Snapshots
- Stop Orders & Trailing Stops
- Event Replay
- Symbol & MultiExchange
- Portfolio Engine
- Strategy Trait
- Backtest Bridge
- Broker Abstraction
- Risk Engine
- Rebalancer CLI
- Python Bindings
- Book Analytics
- Persistence & Serde
- CLI Reference
- Performance
- Comparison with Other Rust LOBs
- Design Constraints
Quick Start
[]
= "0.9"
use ;
let mut exchange = new;
exchange.submit_limit;
let result = exchange.submit_limit;
assert_eq!;
assert_eq!;
Core Concepts
Prices
Prices are integers in the smallest currency unit (cents for USD), avoiding floating-point errors.
let price = Price; // $100.50
assert!;
Display formats as dollars: Price(10050) prints as $100.50.
Constants: Price::ZERO, Price::MAX (market buys), Price::MIN (market sells).
Quantities and Timestamps
Quantity = u64— shares or contracts, always positive.Timestamp = u64— monotonic nanosecond counter (not system clock), guaranteeing deterministic ordering.
Determinism
No randomness anywhere. Same sequence of operations always produces identical trades. Event replay reconstructs exact state.
Exchange API
Exchange is the main entry point, wrapping an OrderBook with order submission, cancellation, modification, and queries.
Order Submission
// Limit order — matches against opposite side, remainder handled by TIF
let result = exchange.submit_limit;
// Market order — IOC semantics at Price::MAX (buy) or Price::MIN (sell)
let result = exchange.submit_market;
Order Management
// Cancel — O(1) via tombstones
let result = exchange.cancel; // CancelResult { success, cancelled_quantity, error }
// Modify — cancel + replace (loses time priority, gets new OrderId)
let result = exchange.modify;
Queries
let = exchange.best_bid_ask; // L1 — O(1)
let spread = exchange.spread; // Option<i64>
let snap = exchange.depth; // L2 — top 10 levels
let full = exchange.full_book; // L3 — everything
let order = exchange.get_order; // Option<&Order>
let trades = exchange.trades; // &[Trade]
Memory Management
exchange.clear_trades; // Clear trade history
exchange.clear_order_history; // Remove filled/cancelled orders
exchange.compact; // Reclaim tombstone memory
Input Validation
The try_submit_* methods validate inputs before processing:
let err = exchange.try_submit_limit;
assert_eq!;
Time-in-Force Semantics
| TIF | Partial Fill? | Rests on Book? | No Liquidity |
|---|---|---|---|
| GTC | Yes | Yes (remainder) | Rests entirely |
| IOC | Yes | No (remainder cancelled) | Cancelled |
| FOK | No | No (all-or-nothing) | Cancelled |
Types Reference
| Type | Definition | Description | Display |
|---|---|---|---|
Price |
struct Price(pub i64) |
Price in smallest units (cents) | $100.50 |
Quantity |
type Quantity = u64 |
Number of shares/contracts | — |
OrderId |
struct OrderId(pub u64) |
Unique order identifier | O42 |
TradeId |
struct TradeId(pub u64) |
Unique trade identifier | T7 |
Timestamp |
type Timestamp = u64 |
Nanosecond counter (not wall clock) | — |
Result Types
Enums
| Enum | Variants | Key Methods |
|---|---|---|
Side |
Buy, Sell |
opposite() |
TimeInForce |
GTC, IOC, FOK |
can_rest(), allows_partial() |
OrderStatus |
New, PartiallyFilled, Filled, Cancelled |
is_active(), is_terminal() |
Book Snapshots
| Method | Returns |
|---|---|
snap.best_bid() / best_ask() |
Option<Price> |
snap.spread() |
Option<i64> |
snap.mid_price() |
Option<f64> |
snap.total_bid_quantity() / total_ask_quantity() |
Quantity |
snap.imbalance() |
Option<f64> — [-1.0, 1.0], positive = buy pressure |
snap.weighted_mid() |
Option<f64> — leans toward less liquid side |
Stop Orders & Trailing Stops
Stop Orders
// Stop-market: triggers market order when last trade price hits stop
exchange.submit_stop_market;
// Stop-limit: triggers limit order at limit_price when stop hits
exchange.submit_stop_limit;
| Side | Triggers When |
|---|---|
| Buy stop | last_trade_price >= stop_price |
| Sell stop | last_trade_price <= stop_price |
Key behaviors: immediate trigger if price already past stop, cascade up to 100 iterations, cancel via exchange.cancel(stop_id).
Trailing Stops
Three trailing methods — stop price tracks the market and only moves in the favorable direction:
// Fixed: triggers if price drops $2.00 from peak
exchange.submit_trailing_stop_market;
// Percentage: trail by 5% from peak
exchange.submit_trailing_stop_market;
// Adaptive trail: 2x simple moving average of |Δ price| over the last
// 14 trades. NOT Wilder's ATR (no OHLC available at the stop module);
// for true Wilder ATR, pre-compute via `indicators::atr` on bar data
// and pass the result as `TrailMethod::Fixed(offset_cents)`.
exchange.submit_trailing_stop_market;
Trailing stop-limit variant: submit_trailing_stop_limit() — same parameters plus limit_price and TimeInForce.
Event Replay
Feature flag: event-log (enabled by default)
Every operation is recorded as an Event. Replaying events on a fresh exchange produces identical state.
// Save events
let events = exchange.events.to_vec;
// Reconstruct exact state
let replayed = replay;
assert_eq!;
Event types: SubmitLimit, SubmitMarket, Cancel, Modify.
Disable for max performance:
= { = "0.9", = false }
Symbol & MultiExchange
Symbol
Fixed-size instrument identifier. [u8; 8] inline — Copy, no heap allocation, max 8 ASCII bytes.
let sym = new;
assert!;
MultiExchange
Independent per-symbol order books:
let mut multi = new;
let aapl = new;
multi.get_or_create.submit_limit;
for in multi.best_prices
Portfolio Engine
Feature flag: portfolio
Tracks cash, positions, costs, returns, and equity over time.
use ;
let cost = CostModel ;
let mut portfolio = new;
// Rebalance to target weights
portfolio.rebalance_simple;
// Record period return and compute metrics
portfolio.record_return;
let metrics = compute_metrics;
Execution Modes
- SimpleFill — instant at bar prices:
portfolio.rebalance_simple(targets, prices) - LOBFill — route through
Exchangematching engines:portfolio.rebalance_lob(targets, exchanges)
Position
Per-symbol tracking with VWAP entry price and realized PnL:
let mut pos = new;
pos.apply_fill; // buy 100 @ $150
pos.apply_fill; // sell 50 @ $160 → $500 realized PnL
Financial Metrics
compute_metrics(&returns, periods_per_year, risk_free) returns: total_return, cagr, volatility, sharpe, sortino, max_drawdown, calmar, num_periods, winning_periods, losing_periods.
Parallel Sweep
Feature flag: parallel (implies portfolio)
use sweep;
let results = sweep;
Strategy Trait
Feature flag: portfolio
Implement compute_weights() for batch-oriented backtesting:
let result = run_backtest;
Built-in: EqualWeight strategy. Parallel variant: sweep_strategy().
Backtest Bridge
The bridge between Python strategy code and Rust execution. Python computes a weight schedule, Rust simulates the portfolio at compiled speed.
Rust API
use backtest_weights;
let result = backtest_weights;
Returns BacktestBridgeResult:
| Field | Type | Description |
|---|---|---|
returns |
Vec<f64> |
Per-period returns |
equity_curve |
Vec<i64> |
Equity at each period (cents) |
final_cash |
i64 |
Ending cash balance |
metrics |
Option<Metrics> |
Sharpe, Sortino, max drawdown, etc. |
holdings |
Vec<Vec<(Symbol, f64)>> |
Per-period holdings weights |
symbol_returns |
Vec<Vec<(Symbol, f64)>> |
Per-period close-to-close symbol returns |
stop_events |
Vec<BacktestStopEvent> |
Stop trigger metadata (index, symbol, price, reason) |
Python API
=
# result["returns"], result["equity_curve"], result["metrics"],
# result["holdings"], result["symbol_returns"], result["stop_events"]
GIL is released during computation for maximum throughput.
Clean aliases (no py_ prefix) are exported for new integrations:
backtest_weights, capabilities, garch_ewma_forecast,
inverse_cvar_weights, inverse_cdar_weights, and other optimizer helpers.
qtrade v0.4 Bridge Pattern
Capability probing contract used by calc.bridge:
=
return True
=
=
return
Broker Abstraction
Crate: nanobook-broker
Generic trait over brokerages with concrete adapters for IBKR and Binance.
Broker Trait
Key Types
IBKR Adapter
Feature: ibkr
Connects to TWS/Gateway via the ibapi crate (blocking API).
let mut broker = new; // 4002 = paper, 4001 = live
broker.connect?;
let positions = broker.positions?;
let quote = broker.quote?;
Binance Adapter
Feature: binance
REST API via reqwest::blocking. Converts nanobook symbols (e.g., "BTC") to Binance pairs (e.g., "BTCUSDT").
let mut broker = new; // testnet
broker.connect?;
Python
=
= # List[Dict] with symbol, quantity, avg_cost_cents, ...
=
= # Dict with bid_cents, ask_cents, last_cents, volume
=
Risk Engine
Crate: nanobook-risk
Pre-trade risk validation for single orders and rebalance batches.
RiskConfig
Notes:
max_drawdown_pctis validated at engine construction and preserved in config, but not yet used in execution-time checks.
Single Order Check
let engine = new;
let report = engine.check_order;
if report.has_failures
Batch Check
Validates a full rebalance against position limits, leverage, and short exposure:
let report = engine.check_batch;
RiskReport
Python
=
# Single order
=
# Batch (full rebalance)
=
# Each check: {"name": "...", "status": "Pass|Warn|Fail", "detail": "..."}
Rebalancer CLI
Crate: nanobook-rebalancer
CLI tool that bridges target weights to IBKR execution with risk checks, rate limiting, and audit trail.
Pipeline
- Read target weights from
target.json(output of your optimizer) - Connect to IBKR Gateway for live positions, prices, account data
- Compute CURRENT → TARGET diff (share quantities, limit prices)
- Run pre-trade risk checks (position limits, leverage, short exposure)
- Show plan, confirm (or
--forcefor automation) - Execute limit orders with rate limiting and timeout-based cancellation
- Reconcile and log to JSONL audit trail
Commands
target.json
Positive weights are long, negative are short. Symbols absent from the target but present in the account get closed. See rebalancer/config.toml.example for the full configuration reference.
Python Bindings
Install: pip install nanobook or cd python && maturin develop --release
Exchange
=
=
=
, =
=
Stop Orders
Portfolio
=
=
Strategy Callback
=
ITCH Parser
=
Book Analytics
Imbalance
let snap = exchange.depth;
if let Some = snap.imbalance
Weighted Midpoint
if let Some = snap.weighted_mid
VWAP
if let Some = vwap
Persistence & Serde
Persistence
Feature flag: persistence (includes serde and event-log)
// Exchange — JSON Lines event sourcing
exchange.save.unwrap;
let loaded = load.unwrap;
// Portfolio — JSON
portfolio.save_json.unwrap;
let loaded = load_json.unwrap;
Serde
Feature flag: serde
All public types derive Serialize/Deserialize: Price, OrderId, TradeId, Symbol, Side, TimeInForce, OrderStatus, Order, Trade, Event, SubmitResult, CancelResult, ModifyResult, BookSnapshot, LevelSnapshot, StopOrder, Position, CostModel, and more.
CLI Reference
Interactive REPL for the order book:
| Command | Example |
|---|---|
buy <price> <qty> [ioc|fok] |
buy 100.50 100 |
sell <price> <qty> [ioc|fok] |
sell 101.00 50 ioc |
market <buy|sell> <qty> |
market buy 200 |
stop <buy|sell> <price> <qty> |
stop buy 105.00 100 |
cancel <order_id> |
cancel 3 |
book / trades |
Show book or trade history |
save <path> / load <path> |
Persistence (requires feature) |
Performance
Benchmarks
Single-threaded (AMD Ryzen / Intel Core):
| Operation | Latency | Throughput | Complexity |
|---|---|---|---|
| Submit (no match) | ~155 ns | ~6.4M ops/sec | O(log P) |
| Submit (with match) | ~197 ns | ~5M ops/sec | O(log P + M) |
| BBO query | ~1.1 ns | ~900M ops/sec | O(1) |
| Cancel (tombstone, deep queue) | ~385 ns | ~2.6M ops/sec | O(1) |
| L2 snapshot (10 levels) | ~255 ns | ~4M ops/sec | O(D) |
Where P = price levels, M = orders matched, D = depth. Numbers are from
benches/v0.10-comparison.md on macOS arm64; expect ±10-20 % across
hardware and build flags.
Time Breakdown (Submit, No Match)
submit_limit() ~155 ns:
├── FxHashMap insert ~30 ns order storage
├── BTreeMap insert ~30 ns price level (O(log P))
├── VecDeque push ~5 ns FIFO queue
├── Event recording ~10 ns (optional, for replay)
├── STP branch ~20 ns `owner` field + policy read (Off path)
└── Overhead ~60 ns struct creation, dispatch, etc.
Optimizations
- O(1) cancel — Tombstone-based, 350x faster than linear scan
- FxHash — Non-cryptographic hash for OrderId lookups (+25% vs std HashMap)
- Cached BBO — Best bid/ask cached for O(1) access
- Optional event logging — disable
event-logfeature for max throughput
Rust vs Numba
Single-threaded throughput is roughly equivalent (both compile to LLVM IR). Where Rust wins: zero cold-start (vs Numba's ~300 ms JIT), true parallelism via Rayon with no GIL contention, and deterministic memory without GC pauses.
Comparison with Other Rust LOBs
| Library | Throughput | Order Types | Deterministic | Use Case |
|---|---|---|---|---|
| nanobook | ~6M ops/sec | Limit, Market, Stops, GTC/IOC/FOK | Yes | Strategy backtesting |
| limitbook | 3-5M ops/sec | Limit, Market | No | General purpose |
| lobster | ~300K ops/sec | Limit, Market | No | Simple matching |
| OrderBook-rs | 200K ops/sec | Many (iceberg, peg, etc.) | No | Production HFT |
Design Constraints
Engineering decisions that keep the system simple and fast:
| Constraint | Rationale |
|---|---|
| Single-threaded | Deterministic by design — same inputs always produce same outputs |
| In-process | No networking overhead; wrap externally if needed |
| No compliance | No self-trade prevention or circuit breakers (out of scope) |
| No complex orders | No iceberg or pegged orders |
| Integer prices | Fixed-point arithmetic avoids floating-point rounding |
| Statistics in Python | Spearman/IC/t-stat belong in scipy/Polars — proven, mature |