Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
67 commits
Select commit Hold shift + click to select a range
9c3ca9e
docs: add VERIFICATION.md and a headline box in the README
jac-made[bot] Nov 13, 2026
9ec1d33
docs(changelog): structure the 0.20.0 notes around the verification
jac-made[bot] Nov 13, 2026
37e616f
docs: security policy and a supply-chain section in the README
jac-made[bot] Nov 13, 2026
0f97e1a
ci(release): SHA256SUMS and build-provenance attestation for release …
jac-made[bot] Nov 13, 2026
741c43b
fix(itch): read the Stock Directory symbol from its real offset
jac-made[bot] Nov 14, 2026
6b53377
fix(broker): report an IBKR connection loss during an order
jac-made[bot] Nov 14, 2026
d7484f4
fix(stats): deflated_sharpe follows Bailey and Lopez de Prado (2014)
jac-made[bot] Nov 14, 2026
3fa3ef4
style: rustfmt and clippy fixes for the IBKR guard and the DSR tests
jac-made[bot] Nov 14, 2026
3722970
refactor: forbid unsafe code in the four Rust crates
jac-made[bot] Nov 14, 2026
eb0ecf9
docs: make six ignored doctests compile and run; document equity_curv…
jac-made[bot] Nov 14, 2026
90904ea
test: pin the exact answers of the book queries and setters
jac-made[bot] Nov 14, 2026
122d450
docs(changelog): security, ITCH, IBKR and deflated Sharpe entries for…
jac-made[bot] Nov 14, 2026
f3c3d68
fix(rebalancer): six order-safety bugs, and tests for every mutation gap
jac-made[bot] Nov 14, 2026
83b69fb
docs(changelog): rebalancer fixes and known issues for 0.20.0
jac-made[bot] Nov 14, 2026
9ab3ee8
docs: a five-scene tour of nanobook, run in CI
jac-made[bot] Nov 14, 2026
74e7533
docs(readme): 'See it work' section with the tour's real output and c…
jac-made[bot] Nov 14, 2026
16dbbd0
docs: a 'check every claim yourself' table with the real 0.20.0 outputs
jac-made[bot] Nov 14, 2026
3627568
test(rebalancer): kill or explain every remaining mutation survivor
jac-made[bot] Nov 14, 2026
453f6e7
test(python): run the deflated Sharpe tests in CI
jac-made[bot] Nov 14, 2026
1eff14b
build: ship only sources, tests, examples and user docs in the crate
jac-made[bot] Nov 14, 2026
852645d
docs(changelog): note the new BacktestBridgeOptions field for struct …
jac-made[bot] Nov 14, 2026
a7f4125
rebalancer: test order pacing, retry backoff, EPERM message, zero-qua…
jac-made[bot] Nov 14, 2026
44f51b4
ci(release): write SHA256SUMS with the release file names
jac-made[bot] Nov 16, 2026
419a7a0
build: ship the replay fixture that corpus-replay reads
jac-made[bot] Nov 16, 2026
2211be7
docs: say which events advance the timestamp and when Lean CI runs
jac-made[bot] Nov 16, 2026
6c87ae7
test(kill): probe pid 1 with signal 0 before sending SIGTERM
jac-made[bot] Nov 16, 2026
e127e52
fix(pid_file): hold an exclusive lock on the PID file
jac-made[bot] Nov 16, 2026
d6f9ee7
fix(recovery): match open orders by filled plus remaining shares
jac-made[bot] Nov 16, 2026
7275461
fix(rebalancer): PID lock and log-dir checks behave the same on Windows
jac-made[bot] Nov 16, 2026
223f0b4
fix(pid_file): lock a separate .lock file so --kill can read the PID …
jac-made[bot] Nov 16, 2026
43f6dd2
test(rebalancer): write the log dir as a TOML literal string
jac-made[bot] Nov 19, 2026
9cca4fa
test(risk): pin limit boundaries, short logic and config checks
jac-made[bot] Nov 20, 2026
a352d05
test(portfolio): pin rebalance, stop and bridge values exactly
jac-made[bot] Nov 20, 2026
4b3eaea
test(broker): build the binance tests only with the binance feature
jac-made[bot] Nov 20, 2026
ccadf8f
test(metrics): pin exact values in portfolio metrics
jac-made[bot] Nov 20, 2026
fd99b7d
test(broker): pin Binance, mock and directly reachable IBKR behaviour
jac-made[bot] Nov 20, 2026
a5c64f9
fix(broker): IBKR reconcile uses the order's side; Binance websocket …
jac-made[bot] Nov 20, 2026
b8bf8d0
refactor(broker): pull pure helpers out of the IBKR client methods
jac-made[bot] Nov 20, 2026
2ab684c
refactor(broker): pull pure helpers out of IBKR order and reconcile code
jac-made[bot] Nov 20, 2026
73de01d
test(broker): pin IBKR account, quote, order-event, cancel and reconc…
jac-made[bot] Nov 20, 2026
c1057d5
test(risk): pin worst-weight tie, weight allocation split and Display…
jac-made[bot] Nov 20, 2026
895d13c
test(portfolio): pin sizing guards, median shortcut, lower-tail limit…
jac-made[bot] Nov 20, 2026
2b872ea
test(broker): pin mock open-order rows and websocket flag, buffer, co…
jac-made[bot] Nov 20, 2026
98e17e7
refactor(rebalancer): pull the lock-error classification out of PidFi…
jac-made[bot] Nov 20, 2026
44ca3ab
test(rebalancer): pin PID lock errors, guard-drop warning and reconci…
jac-made[bot] Nov 20, 2026
dfdde48
fix(broker): Binance websocket reconnect stops after its attempt limit
jac-made[bot] Nov 20, 2026
dce499b
test(stp): an STP-cancelled incoming order's record holds nothing
jac-made[bot] Nov 20, 2026
56f8f78
docs: 0.20.0 mutation-testing results and two known issues
jac-made[bot] Nov 20, 2026
dcb23e5
docs(changelog): BacktestBridgeResult also gains three fields
jac-made[bot] Nov 20, 2026
6201236
Merge main into feat/execution-records-rebased
jac-made[bot] Nov 20, 2026
4751a26
fix(broker): MockBroker::cancel_order also removes configured open-or…
jac-made[bot] Nov 20, 2026
2a590f4
fix(broker): clamp the Binance websocket backoff exponent before pow
jac-made[bot] Nov 20, 2026
a4de469
fix(rebalancer): write the PID file atomically; stop the holder child…
jac-made[bot] Nov 20, 2026
43fb11e
fix(rebalancer): take the PID guard before the cron completed-window …
jac-made[bot] Nov 20, 2026
05b1de5
fix(rebalancer): name the cause when the logging directory check fails
jac-made[bot] Nov 20, 2026
3643edd
test(rebalancer): escape the logging dir as TOML; reverse the broker …
jac-made[bot] Nov 20, 2026
de9dc4e
docs(portfolio): fix the mean return in the Sortino test comment
jac-made[bot] Nov 20, 2026
5f28b16
docs: correct the Timestamp table, the IBKR connection-loss and recov…
jac-made[bot] Nov 20, 2026
9368404
docs: IBKR connection-loss fix is partial; Timestamp is an event counter
jac-made[bot] Nov 20, 2026
62dfc82
fix(broker): reconcile_partial_fill counts only the change since the …
jac-made[bot] Nov 20, 2026
144a4e1
fix(broker): read Binance open orders from GET /api/v3/openOrders
jac-made[bot] Nov 20, 2026
ac0f321
fix(rebalancer): recovery matches open orders on symbol and quantity
jac-made[bot] Nov 20, 2026
98407dd
fix(broker): reconcile_partial_fill reads a symbol missing from the p…
jac-made[bot] Nov 20, 2026
7ed72c0
fix(broker): execute_limit_order reads IBKR connection notices from t…
jac-made[bot] Nov 20, 2026
a2986ab
docs: BrokerOrderStatus has a symbol
jac-made[bot] Nov 20, 2026
6b38bd5
docs(changelog): broker and rebalancer go to 0.11.0, risk to 0.8.2
jac-made[bot] Nov 20, 2026
a90931f
test(rebalancer): a log path through a file is reported as unreadable
jac-made[bot] Nov 20, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: write
id-token: write # sign the build-provenance attestation
attestations: write # store it on GitHub

steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
Expand All @@ -104,6 +106,21 @@ jobs:
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
path: artifacts
# One directory, so SHA256SUMS names match the release asset names.
merge-multiple: true

# Users can check a download with `sha256sum -c SHA256SUMS` and its origin with
# `gh attestation verify <file> --repo BoringQuantSystems/nanobook`.
- name: Checksums
run: |
cd artifacts
find . -type f ! -name SHA256SUMS -print0 | sort -z | xargs -0 sha256sum > SHA256SUMS
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
cat SHA256SUMS

- name: Attest build provenance
uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2
with:
subject-path: 'artifacts/**/*'

- name: Extract changelog for this version
run: |
Expand Down
219 changes: 212 additions & 7 deletions CHANGELOG.md

Large diffs are not rendered by default.

16 changes: 16 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,22 @@ readme = "README.md"
keywords = ["orderbook", "trading", "matching-engine", "risk-management", "formal-verification"]
categories = ["simulation", "algorithms"]
authors = ["Ricardo Frantz"]
# Ship only what a Rust user builds and reads. The 0.19.3 crate was 6.3 MB because it
# also carried the OCaml oracle, docs, mockups and CI files; those stay in the repository.
include = [
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
"/src/**",
"/benches/**",
"/tests/**",
"/examples/*.rs",
"/examples/itch-replay/replay.rs",
"/README.md",
"/CHANGELOG.md",
"/LICENSE",
"/SECURITY.md",
"/SEMVER.md",
"/VERIFICATION.md",
"/oracle-ocaml/test/corpus/01-simple-cross/input.jsonl",
]

[dependencies]
rustc-hash = "2.1" # FxHash - fast non-cryptographic hash
Expand Down
92 changes: 85 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,15 @@
[![Lean proofs](https://github.com/BoringQuantSystems/nanobook/actions/workflows/lean.yml/badge.svg)](https://github.com/BoringQuantSystems/nanobook/actions/workflows/lean.yml)
[![OCaml oracle](https://github.com/BoringQuantSystems/nanobook/actions/workflows/oracle.yml/badge.svg)](https://github.com/BoringQuantSystems/nanobook/actions/workflows/oracle.yml)
[![docs.rs](https://docs.rs/nanobook/badge.svg)](https://docs.rs/nanobook)
[![cargo-deny](https://img.shields.io/badge/cargo--deny-audited-brightgreen)](https://github.com/BoringQuantSystems/nanobook/actions/workflows/ci.yml)
[![cargo-deny](https://img.shields.io/badge/cargo--deny-audited-brightgreen)](https://github.com/BoringQuantSystems/nanobook/actions/workflows/audit.yml)
[![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/BoringQuantSystems/nanobook/badge)](https://scorecard.dev/viewer/?uri=github.com/BoringQuantSystems/nanobook)
[![Socket crate](https://socket.dev/api/badge/cargo/package/nanobook)](https://socket.dev/cargo/package/nanobook)
[![Socket PyPI](https://socket.dev/api/badge/pypi/package/nanobook)](https://socket.dev/pypi/package/nanobook)

> **Order matching proved in Lean 4.** Eleven laws of the order book are
> machine-checked on a model of the engine, and CI runs the Rust engine against
> that model on every push. No `sorry`, three standard axioms, 12 000 lines.
> [How it is verified](VERIFICATION.md).

`nanobook` is a small execution kernel for the part of a trading system that is
easy to underestimate: state. Your Python code can keep doing research,
Expand All @@ -16,13 +24,61 @@ that strategy: portfolio accounting, transaction costs, stops, deterministic
limit-order-book simulation, pre-trade risk checks, and optional IBKR
rebalancing.

Eleven laws of its order-book matching are proved in Lean, on a model of the
engine that CI tests against the Rust code on every change.

Use it when you want to ask: "if my strategy emits these target weights, what
exactly happens to cash, holdings, risk checks, order-book events, and audit
logs?"

## See it work

`python/examples/tour.py` shows what nanobook does in five short scenes. It runs offline in
under a second, with no API keys:

From a clone of this repository, with nanobook 0.20 or later installed:

```bash
pip install "nanobook>=0.20"
python python/examples/tour.py # add --figure (with matplotlib) to draw the chart below
```

Trimmed output of one run (synthetic, seeded prices):

```text
=== Scene 1: From weights to a backtest ===
3 synthetic stocks, 252 daily bars, inverse-volatility weights, rebalanced every 21 days,
10 bps commission + 5 bps slippage.
final equity $1,127,584.21 (start $1,000,000.00)
Sharpe 1.22
max drawdown 9.88 %
backtest time 0.70 ms
cost effect: trading costs took $4,182.84 of final equity.

=== Scene 2: The order book does the right thing ===
fill-or-kill buy 100 @ $102.00, only 20 are available:
result Cancelled, filled 0, trades 0
book unchanged: True; stored record: None
immediate-or-cancel buy 100 @ $102.00, 20 fill and the rest cannot rest:
get_order -> status 'cancelled', filled 20, remaining 0

=== Scene 3: Risk checks stop bad orders ===
batch B: buy $90,000 AAA + $95,000 BBB (1.85x):
FAIL Leverage 1.85x > 1.50x limit
order C: sell 10 CCC @ $50.00 while holding none (a short):
FAIL Short selling short selling not allowed

=== Scene 4: What a rebalance does, without a broker ===
period 21, second rebalance (the change from drifted holdings):
sell 550.0000 CCC @ $217.91 notional $119,850.50 cost $119.85

=== Scene 5: Proof, not promises ===
law 7: A fill-or-kill submit trades its whole quantity, or trades nothing and leaves
every order and level unchanged.
... eleven laws, and the command that rechecks them: verification/lean/check.sh 0
```

<p align="center">
<img src="assets/tour-equity.png" alt="Equity of the tour backtest, gross and net of trading costs" width="700">
</p>

## Matching rules proved in Lean

The matching engine at the heart of nanobook comes with machine-checked proofs.
Expand Down Expand Up @@ -71,7 +127,8 @@ The model uses unbounded integers, so overflow is covered by Rust tests and chec
arithmetic, not by the proofs. The portfolio, risk, broker and rebalancer layers are
tested, not proved.

Check it yourself:
The full write-up, with the Lean statements, the deliberate-break results and the
mutation-testing numbers, is in [VERIFICATION.md](VERIFICATION.md). Check it yourself:

```bash
verification/lean/check.sh 1000 # proofs, axioms, kernel recheck, corpus, 1000 random logs
Expand All @@ -83,6 +140,26 @@ compares its trades with Rust byte for byte. To run it locally, build `corpus-re
(`cargo build --release --features serde --bin corpus-replay`), run the loop in
`oracle-ocaml/test/corpus/README.md`, and fix any divergence before merging.

## Security and supply chain

This is what installing nanobook asks you to trust. Each point can be checked in the
repository or on a public service:

- **No `unsafe` code** in the Rust crates: each one starts with `#![forbid(unsafe_code)]`.
- **One runtime dependency.** The `nanobook` crate with default features depends only on
`rustc-hash`; everything else is behind an opt-in feature. The Python package has no
Python runtime dependencies and downloads nothing at install time.
- **Network code is opt-in.** The broker adapters live in `nanobook-broker` behind the
`ibkr` and `binance` features and are not in the PyPI wheels.
- **Audited dependencies.** `cargo deny` and `cargo audit` run on every dependency
change and weekly; Dependabot keeps them current; Socket scans every pull request.
- **Hardened CI.** Every GitHub Action is pinned to a commit hash, workflows get
read-only tokens by default, and the OpenSSF Scorecard rates the setup publicly.
- **Verifiable releases.** PyPI releases use trusted publishing with PEP 740
attestations: you can check that a wheel was built by this repository's workflow.

Report a vulnerability privately as described in [SECURITY.md](SECURITY.md).

## Architecture

```
Expand Down Expand Up @@ -133,8 +210,9 @@ compares its trades with Rust byte for byte. To run it locally, build `corpus-re
- Fallible risk-engine construction instead of config-time panics.
- `rustls` default TLS backend, zeroize-on-drop for Binance credentials, and scrubbed broker logs.
- Audit logs constrained to the working directory, with `0o600` permissions on Unix.
- cargo-fuzz harnesses for matching and ITCH, plus an 89.76 % mutation-testing
baseline for the matcher.
- cargo-fuzz harnesses for matching and ITCH, and mutation testing of the risk,
broker, portfolio and rebalancer code: every surviving change is killed by a test
or explained ([VERIFICATION.md](VERIFICATION.md#mutation-testing-does-all-of-this-catch-real-bugs-in-the-rust-code)).

## Competitive Positioning

Expand Down
84 changes: 84 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# Security policy

## Reporting a vulnerability

Please report security problems privately, through GitHub:
**Security → Report a vulnerability** on this repository
([direct link](https://github.com/BoringQuantSystems/nanobook/security/advisories/new)).
Do not open a public issue for a security problem.

Include what you found, how to reproduce it, and which version and features you
used. We aim to acknowledge a report within 7 days and to publish a fix and a
GitHub security advisory once it is ready, crediting you unless you ask otherwise.

## Supported versions

| Version | Security fixes |
|---------|----------------|
| 0.20.x | yes |
| < 0.20 | no; please upgrade |

nanobook is pre-1.0; see [SEMVER.md](SEMVER.md) for what that means for upgrades.

## Check every claim yourself

Each row is a claim, the command that checks it from a clone of this repository, and the
output we got when preparing 0.20.0.

| Claim | Command | Output for 0.20.0 |
|---|---|---|
| No `unsafe` code in the Rust crates | `grep -rn 'unsafe' src broker/src risk/src rebalancer/src` | the five `#![forbid(unsafe_code)]` lines, one comment and one error message that contain the word; no `unsafe` block |
| One runtime dependency | `cargo tree -p nanobook -e normal --depth 1` | `nanobook` → `rustc-hash` |
| Dependencies pass the policy | `cargo deny check` | `advisories ok, bans ok, licenses ok, sources ok` |
| No known vulnerable dependency | `cargo audit` | no findings (348 crates scanned) |
| The matching laws are proved | `verification/lean/check.sh 0` | 11 laws on `propext`, `Classical.choice`, `Quot.sound` only; `leanchecker accepted Nanobook`; `corpus matches (25 cases)` |
| The Rust engine matches the model | `verification/lean/differential.sh 1000` | `zero mismatches in 1000 seeds` |
| The tour's numbers are real | `python python/examples/tour.py` | the output shown in the README |
| A release binary was built here | `gh attestation verify <file> --repo BoringQuantSystems/nanobook` | `Verification succeeded` (from 0.20.0 on) |
| The tests catch planted bugs | `cargo mutants` (see VERIFICATION.md for the exact setup) | see "Mutation testing" in VERIFICATION.md |

## What we check, and where you can verify it

Every claim below can be checked in this repository or on a public service.

**The code**

- No `unsafe` code in `nanobook`, `nanobook-broker`, `nanobook-risk` or
`nanobook-rebalancer`: each crate root has `#![forbid(unsafe_code)]`. The Python
bindings (`nanobook-python`) call into Python through PyO3, which needs `unsafe`
by nature; that crate has no hand-written `unsafe` blocks.
- The order-matching rules are proved in Lean 4 on a model of the engine, and CI
runs the Rust engine against that model on every push
([VERIFICATION.md](VERIFICATION.md)).
- Property tests, regression tests, fuzz targets (`fuzz/`) and mutation testing
(`fuzz/mutants-baseline.md`).

**What you install**

- The `nanobook` crate with default features has one runtime dependency,
`rustc-hash`. Every other dependency is behind an opt-in feature.
- The Python package declares no Python runtime dependencies. Its only build script
sets linker flags for the extension module; nothing is downloaded at install time.
- The network-facing code (IBKR and Binance adapters) lives in `nanobook-broker`,
behind the `ibkr` and `binance` features, and is not in the PyPI wheels.

**Dependencies**

- `cargo deny` (licences, bans, sources, advisories; `deny.toml`) and `cargo audit`
run on every change to a manifest or lock file and every Monday
(`.github/workflows/audit.yml`).
- Dependabot opens update pull requests for Cargo, pip and GitHub Actions.
- [Socket](https://socket.dev) scans every pull request for supply-chain risks.

**Build and release**

- Every GitHub Action is pinned to a full commit hash, and every workflow runs with
read-only permissions unless a job needs more.
- PyPI releases use trusted publishing (no stored token) and carry PEP 740
attestations, so you can check that a wheel was built by this repository's
workflow.
- GitHub Releases carry a `SHA256SUMS` file and a signed build-provenance attestation
for every `lob` binary. Check a download with `sha256sum -c SHA256SUMS` and its origin
with `gh attestation verify <file> --repo BoringQuantSystems/nanobook`.
- The [OpenSSF Scorecard](https://scorecard.dev/viewer/?uri=github.com/BoringQuantSystems/nanobook)
rates the repository's security practices weekly.
2 changes: 1 addition & 1 deletion UBIQUITOUS_LANGUAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
| **Symbol** | A ticker identifier for a financial instrument (max 8 ASCII bytes) | Ticker, instrument |
| **Quantity** | The number of shares or contracts in an order or trade | Size, volume, amount |
| **Price** | The monetary value per unit, stored as fixed-point integer in cents | Rate, quote |
| **Timestamp** | A monotonic nanosecond counter for deterministic ordering | Time, sequence number |
| **Timestamp** | An event sequence number assigned by the exchange (starts at 1; not wall-clock time) | Time, nanoseconds |

## Risk

Expand Down
Loading
Loading