From 9c3ca9e536c342c99f075afa16613005d8ae7f87 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 23:49:19 +0100 Subject: [PATCH 01/66] docs: add VERIFICATION.md and a headline box in the README VERIFICATION.md is a standalone page on the Lean model, the eleven laws (two quoted in Lean), the axiom and kernel checks, the deliberate-break results, how CI ties Rust to the model, the bugs found, and the limits. The README gains a short headline box linking to it. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- README.md | 11 +-- VERIFICATION.md | 181 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 188 insertions(+), 4 deletions(-) create mode 100644 VERIFICATION.md diff --git a/README.md b/README.md index fabfe8b..35b216f 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,11 @@ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) [![cargo-deny](https://img.shields.io/badge/cargo--deny-audited-brightgreen)](https://github.com/BoringQuantSystems/nanobook/actions/workflows/ci.yml) +> **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, signals, sizing, and scheduling. nanobook handles the execution mechanics around @@ -17,9 +22,6 @@ 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?" @@ -72,7 +74,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 diff --git a/VERIFICATION.md b/VERIFICATION.md new file mode 100644 index 0000000..c1e5a12 --- /dev/null +++ b/VERIFICATION.md @@ -0,0 +1,181 @@ +# How nanobook's matching engine is verified + +nanobook's order-matching core is checked in three independent ways: + +1. **Proofs in Lean 4.** Eleven laws of the order book are proved about an executable + Lean model of the engine. +2. **Rust against the Lean model.** On every push and pull request, the Rust engine and + the Lean model replay the same event logs, and their trade logs must match byte for + byte. +3. **Rust against an OCaml oracle.** A separate OCaml matching engine replays the + golden corpus, and CI compares its trades with Rust. + +This page explains what each layer covers, what it found, and what it does not cover. + +## The model + +`verification/lean/Nanobook/Spec.lean` is the matching engine written as plain Lean +functions. Levels are lists sorted best price first; each level is a price and a FIFO +list of order ids. It handles the operations the golden corpus uses: + +- limit and market submits, with good-till-cancelled, immediate-or-cancel or + fill-or-kill; +- cancels; +- an optional owner per order, with the four self-trade policies (`Off`, + `CancelNewest`, `CancelOldest`, `DecrementAndCancel`). + +`verification/lean/Nanobook/Queue.lean` models the queue the Rust engine uses for +speed: cancelled slots kept as tombstones, stored queue positions, +`popped_from_front`, and compaction. That is the layer where the worst bug lived (see +below). + +The model is executable. `verification/lean/Main.lean` builds `nanobook-replay`, which +reads the same JSON Lines events as the Rust `corpus-replay` and writes trades in the +same format. + +## The laws + +The statements are in `verification/lean/Nanobook/Laws.lean`, with a plain-language +comment above each. Laws 1 to 9 hold for every book reachable from the empty book; +law 10 holds for every sequence of queue operations the engine can perform. + +| Law | Statement in plain words | Proof file | +|-----|--------------------------|------------| +| 1 | Bids descend, asks ascend, no level is empty, each queued id is one active order at that price, and each active order is queued exactly once. | `BookShape.lean`, `WellFormed.lean` | +| 2 | The best bid is strictly below the best ask. | `Uncrossed.lean` | +| 3 | Trades of a submit sum to its filled quantity, which does not exceed the submit; each trade takes exactly its size off the resting order. | `Conservation.lean` | +| 4 | A submit trades resting orders in price-time order. An order skipped before the last trade was cancelled by self-trade prevention. | `Priority.lean` | +| 5 | Every trade prints at the resting level's price, at or inside the incoming limit. | `Price.lean` | +| 6 | The matching loop's step bound is always enough: more steps never change the result. | `Fuel.lean` | +| 7 | A fill-or-kill submit trades its whole quantity, or trades nothing and leaves every order and level unchanged. | `FillOrKill.lean` | +| 8 | Each self-trade policy does exactly what `src/matching.rs` documents. With any policy other than `Off`, no trade has the same owner on both sides. | `SelfTrade.lean` | +| 9 | A cancel changes only the cancelled order and drops only it from its level. Cancelling a missing or finished order changes nothing. | `CancelLocal.lean` | +| 10 | The tombstone queue always holds the same live orders, in the same order, as the plain lists. Every stored position points at its own order, and the totals and tombstone counts are exact. | `QueueRefines.lean` | +| 11 | A submitted order's stored record matches its status: filled means fully filled; resting means filled plus remaining equals the submit; cancelled means nothing remains; no record means a rejected fill-or-kill with no trades. | `StatusAccounting.lean` | + +Two of the statements, quoted from `Laws.lean`: + +```lean +/-- The best bid stays strictly below the best ask. -/ +def law2 : Prop := + ∀ book, Reachable book → + ∀ bid ask, + bestPrice book.bids = some bid → + bestPrice book.asks = some ask → + bid < ask + +/-- A fill-or-kill submit trades its whole quantity, or it trades nothing. +A rejected fill-or-kill leaves orders and levels unchanged. +Only the id counter and the timestamp counter advance. -/ +def law7 : Prop := + ∀ book, Reachable book → + ∀ side price quantity owner policy, + let result := apply book (.submitLimit side price quantity .fok owner policy) + tradeQtySum result.2 = quantity ∨ + (result.2 = [] ∧ + result.1.bids = book.bids ∧ + result.1.asks = book.asks ∧ + result.1.orders = book.orders ∧ + result.1.nextTradeId = book.nextTradeId ∧ + result.1.nextOrderId = book.nextOrderId + 1 ∧ + result.1.nextTimestamp = book.nextTimestamp + 1) +``` + +### What the proofs rest on + +- Lean 4.35.0, core library only: no Mathlib, no other package. +- No `sorry`, `admit`, `axiom`, `partial`, `unsafe`, `implemented_by` or + `native_decide`; `check.sh` rejects them. +- Every `lawN_holds` theorem depends only on `propext`, `Classical.choice` and + `Quot.sound` (checked with `#print axioms`). +- `leanchecker --fresh` re-checks every declaration with an independent kernel + replay. +- Size: about 12 000 lines (model 1 200, laws 300, proofs 10 700). + +### Did the proofs catch broken models? + +A proof that would also go through for a wrong model protects nothing. So, as each law +was proved, the model was deliberately broken in the way the law is meant to catch, +and the proof had to fail to build. Examples: + +| Law | Deliberate break | Result | +|-----|------------------|--------| +| 6 | the step bound counts only the incoming remainder | proof fails | +| 7 | the old fill-or-kill check that counts the owner's own orders | proof fails | +| 10 | insert returns the raw slot index instead of the stored position | proof fails (`QueueRefines.lean:1255`) | +| 10 | compaction keeps stale positions | proof fails (`QueueRefines.lean:2216`) | +| 11 | a self-trade stop keeps the remainder | proof fails (`StatusAccounting.lean:10`) | +| 11 | an immediate-or-cancel cancel keeps the remainder | caught first by the law 1 proof | + +These runs were done by hand when each law was proved and are recorded in the pull +request of each proof; CI does not repeat them. + +## How the Rust code is tied to the model + +The proofs cover the Lean model, not the Rust code. Two checks tie the two together: + +- **Golden corpus.** 25 hand-checked cases in `oracle-ocaml/test/corpus/`, each with the + trades Rust produced for it. The Lean replay must reproduce every one. +- **Random differential replay.** `verification/lean/differential.sh N` generates N + random event logs of 64 events (`examples/corpus_gen.rs`), with random sides, prices, + quantities, time-in-force, owners and self-trade policies, and runs both engines on + each. The trade logs must be identical. CI runs 1000 seeds on every push; for + 0.20.0 we also ran 100 000. + +Both checks compare trades only, not every order's state. A difference that never +changes a trade would not be seen; the Rust property and regression tests cover that +part. + +## Mutation testing: does all of this catch real bugs in the Rust code? + + + +## What this work found + +Four bugs in the Rust engine, none caught by the earlier tests, fuzzing or the 89.76 % +mutation baseline. All are fixed in 0.20.0, each with a regression test. + +| Bug | Effect | Found by | Now covered by | +|-----|--------|----------|----------------| +| A cancel after a partial fill or a compaction used a stale queue index | the wrong order was cancelled; matching could stall | the verification work (model and property tests) | law 10, `tests/regression_cancel_targets_own_order.rs` | +| Level totals saturated at `u64::MAX` | orders above the limit were lost; debug builds panicked | the verification work (model and property tests) | `tests/regression_level_quantity_overflow.rs` | +| A finished immediate-or-cancel or self-trade-stopped order stayed active | it could be cancelled again; status was wrong | the verification work (model and property tests) | law 11 | +| Fill-or-kill counted the owner's own orders under self-trade prevention | the order could cancel resting orders, partly fill, then be rejected | the law 7 proof failed | law 7, `tests/regression_fok_self_trade.rs` | + +One mistake in the specification was also found. Law 10 was first stated without +requiring the price levels to be sorted, and in that form it is false: a book with a +worse bid level ahead of a better one breaks it after an insert. The engine never +builds such a book. The proof attempt produced the counterexample, and the invariant +gained the sorting condition. A wrong law that happens to be provable would not show +up this way, so the statements are reviewed by people as well. + +## What is not covered + +- Modify orders and stop orders are not in the model. +- The model uses unbounded integers. Overflow is covered by Rust tests and checked + arithmetic, not by the proofs. +- The portfolio, risk, broker and rebalancer layers are tested, not proved. +- The bridge between Rust and the model is testing (corpus and random replay), not + proof. + +## Reproduce it + +From the repository root: + +```bash +verification/lean/check.sh 1000 +``` + +It builds the model and proofs, rejects unchecked constructs, checks the axioms of all +eleven laws, runs `leanchecker --fresh`, replays the corpus in Lean, and compares Rust +and Lean on 1000 random logs. `check.sh 0` skips the Rust comparison for a machine +without Rust. It needs Lean 4.35.0 (`verification/lean/lean-toolchain`) and takes about +3 minutes in CI. + +## Method and credit + +The approach is an executable specification plus differential testing against the +production code, the method AWS uses for the Cedar authorization language: prove +properties about a model small enough to reason about, then check the real +implementation against the model on many inputs. The OCaml oracle was there first; the +Lean model adds proofs on top. From 9ec1d33dd288be92e711265f23dc8e32b2637919 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 23:49:19 +0100 Subject: [PATCH 02/66] docs(changelog): structure the 0.20.0 notes around the verification Highlight section with the eleven laws and their limits; behaviour changes with what users must check; fixes linked to the law and the regression test that cover them; additions, security and docs. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- CHANGELOG.md | 100 +++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 93 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index da4926e..daaf1cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,19 +7,105 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased -- Added machine-checked proofs of the matching engine in Lean 4 (`verification/lean/`). Eleven laws of the order book are proved about a Lean model of the engine: book shape, no crossed book, quantity conservation, price-time priority, trade prices, termination, all-or-nothing fill-or-kill, the four self-trade policies, local cancels, the tombstone queue matching plain FIFO lists, and order records matching their status. CI (`.github/workflows/lean.yml`) rebuilds the proofs, restricts them to Lean's three standard axioms, rechecks them with `leanchecker --fresh`, replays the golden corpus in Lean against the recorded Rust trades, and runs both engines on 1000 random event logs. The fixes below came out of this work. +nanobook and the Python package move from 0.19.3 to 0.20.0. nanobook-broker, +nanobook-risk and nanobook-rebalancer do not change and are not republished. + +### Highlight: matching rules proved in Lean 4 + +The order-matching core now comes with machine-checked proofs. Eleven laws of the +order book are stated and proved in Lean 4 about a model of the engine +(`verification/lean/`, about 12 000 lines, Lean core only, no `sorry`): + +1. every reachable book is well formed: bids descend, asks ascend, no empty level, + each active order queued exactly once at its own price; +2. the book is never crossed; +3. a submit conserves quantity; +4. trades follow price-time priority; +5. every trade prints at the resting price, at or inside the incoming limit; +6. matching always stops; +7. fill-or-kill is all or nothing; +8. each self-trade policy does what its documentation says; +9. a cancel changes only the cancelled order; +10. the tombstone queue always holds the same orders, in the same order, as a plain + FIFO list; +11. a submitted order's stored record matches its status. + +The proofs are about the model, not the Rust code itself. On every push and pull +request, CI (`.github/workflows/lean.yml`) rebuilds them, allows only Lean's three +standard axioms, rechecks everything with `leanchecker --fresh`, replays the golden +corpus in Lean against the trades Rust recorded for it, and runs the Rust engine and +the Lean model on 1000 random event logs whose trade logs must match byte for byte. +Not covered: modify and stop orders, integer overflow, and the portfolio, risk, +broker and rebalancer layers. See [VERIFICATION.md](VERIFICATION.md). + +The four engine bugs below were found by this work. None was caught by the earlier +tests, fuzzing or mutation testing. -- Moved the developer reference from the README to `docs/reference.md`. The README now leads with the verification and keeps the overview, install, examples, and performance sections. +### Changed + +- **Fill-or-kill under self-trade prevention is rejected with no effect.** The + fill-or-kill check now counts only the size the order could actually trade under + its self-trade policy. Before, it counted the owner's own resting orders, so the + order could pass the check and then be partly filled, cancel the owner's resting + order, or be stored as cancelled. *Check your code if* you submit fill-or-kill + orders with an owner and a policy other than `Off`: an order that used to trade + partly is now rejected. Covered by law 7 and `tests/regression_fok_self_trade.rs`. +- **Finished IOC and self-trade-stopped orders read `Cancelled`.** `get_order` now + returns status `Cancelled` with no remaining quantity for an immediate-or-cancel + order with an unfilled rest, and for an order stopped by self-trade prevention; + such orders can no longer be cancelled. `SubmitResult.status` is unchanged. + *Check your code if* you read order status through `get_order` after an IOC + submit. Covered by law 11. +- **Level and book totals are exact.** `total_quantity`, `quantity_at_or_better` + and snapshot totals cap at `u64::MAX` instead of wrapping or panicking, and + `BookSnapshot::imbalance` uses exact side sums. -- Fixed fill-or-kill orders under self-trade prevention. The fill-or-kill check counted the owner's own resting orders, so the order could pass the check and then be stopped by self-trade prevention: it could be partly filled, cancel the owner's resting order without trading, or be stored as cancelled. The check now counts only size the order could trade under its self-trade policy, and a short order is rejected without changing the book. `OrderBook::can_fully_fill` is unchanged; the new `OrderBook::can_fully_fill_under` takes the owner and the policy. +### Fixed -- Fixed cancels that removed the wrong order. After the front of a price queue had filled, or after `compact`, cancelling an order could mark a different order at that price, leaving queued orders that could not match and could stall matching. A partially filled IOC or self-trade-cancelled order now reads as `Cancelled` with no remaining quantity from `get_order` and can no longer be cancelled; `SubmitResult.status` is unchanged. +- **Cancels could remove a different order.** After the front of a price queue had + filled, or after `compact`, cancelling an order could mark another order at that + price. The queue then held orders that could not match, and matching could stall. + Covered by law 10 and `tests/regression_cancel_targets_own_order.rs`. +- **Price levels holding more than `u64::MAX` in total lost orders.** A level + dropped its remaining orders after its total saturated, and sums across levels + overflowed: debug builds panicked and release builds made wrong fill-or-kill + decisions. Covered by `tests/regression_level_quantity_overflow.rs`. +- **Finished IOC and self-trade-stopped orders stayed active** (see Changed). +- **Fill-or-kill under self-trade prevention could change the book before + rejecting** (see Changed). +- `Trade::vwap` returns `None` when the quantity sum does not fit, instead of + overflowing. +- The OCaml reference oracle mishandled a cancel after a partial fill and could hang + on corpus case 21; CI now has a 60 s timeout per corpus case. -- Fixed resting quantities whose sum exceeds `u64::MAX`. A level dropped its remaining orders after its total saturated, and sums across levels overflowed, which panicked in debug builds and made fill-or-kill checks wrong in release builds. Level totals are now exact; `total_quantity`, `quantity_at_or_better`, and snapshot totals cap at `u64::MAX`, `BookSnapshot::imbalance` uses exact side sums, and `Trade::vwap` returns `None` when the quantity sum does not fit. +### Added -- Added `reference_price` (unimpacted cents per share) and `reference_notional` (cents at the final filled quantity, using the engine's truncation and i64 clamp) to Rust and Python execution records. Stop references use the current close, including on hold days without rebalance fill bars. Slippage cost is `notional - reference_notional` for buys and `reference_notional - notional` for sells, up to truncation; `cost` remains commission only. The extra calculation runs only when recording is enabled; execution arithmetic and existing outputs are unchanged. +- **`OrderBook::can_fully_fill_under(side, price, quantity, owner, policy)`**, the + fill-or-kill check under a self-trade policy. `OrderBook::can_fully_fill` is + unchanged. +- **Reference prices in execution records.** `reference_price` (unimpacted cents per share) and `reference_notional` (cents at the final filled quantity, using the engine's truncation and i64 clamp) are added to Rust and Python execution records. Stop references use the current close, including on hold days without rebalance fill bars. Slippage cost is `notional - reference_notional` for buys and `reference_notional - notional` for sells, up to truncation; `cost` remains commission only. The extra calculation runs only when recording is enabled; execution arithmetic and existing outputs are unchanged. +- **Opt-in backtest execution records** through Rust's `BacktestBridgeOptions.record_executions` and Python's `record_executions=True`. Results include `initial_cash`, actual `executions` (including stop exits and trimmed buys), and period-close `cash_snapshots`. Quantity is signed raw micro-shares (1 share = 1,000,000; positive buys, negative sells), with Python `side` (`buy`/`sell`); price is effective cents per share; all other monetary fields are cents. Notional truncates toward zero after scaling and clamps to i64; cash fields reflect actual balance changes, including saturation. Ledgers are `None` by default and empty for enabled empty/rejected runs. Existing calls and financial calculations are unchanged. The Python stubs for `backtest_weights` now match the runtime signature. +- **Lean verification.** The Lean model, proofs and replay tools (`verification/lean/`), the corpus + generator (`examples/corpus_gen.rs`), the Rust-versus-Lean replay + (`verification/lean/differential.sh`), and golden corpus cases 19 to 25. + +### Security -- Added opt-in backtest execution records through Rust's `BacktestBridgeOptions.record_executions` and Python's `record_executions=True`. Results include `initial_cash`, actual `executions` (including stop exits and trimmed buys), and period-close `cash_snapshots`. Quantity is signed raw micro-shares (1 share = 1,000,000; positive buys, negative sells), with Python `side` (`buy`/`sell`); price is effective cents per share; all other monetary fields are cents. Notional truncates toward zero after scaling and clamps to i64; cash fields reflect actual balance changes, including saturation. Ledgers are `None` by default and empty for enabled empty/rejected runs. Existing calls and financial calculations are unchanged. The Python stubs for `backtest_weights` now match the runtime signature. +- **Dependency updates for RustSec advisories.** The lock file now pins rustix + 1.1.6 (RUSTSEC-2026-0486; only in tests, through tempfile) and quinn-udp 0.5.16 + (RUSTSEC-2026-0538; only in nanobook-broker built with the `binance` feature). + +### Documentation + +- The README leads with the verification. The developer reference moved to + `docs/reference.md`, and its examples were brought in line with the current API; + every changed Rust example was compiled and run. +- The Python type stubs match the runtime: `CostModel(commission_bps: float, + slippage_bps: float, min_commission: int)`, and no `open_orders` on the Python + brokers. +- `Timestamp` is documented as what it is: an event counter starting at 1, not + nanoseconds. `Portfolio::equity_curve` documents its initial entry. Six doctests + that were marked `ignore` now compile and run. ## [0.19.3] - 2026-10-31 From 37e616f72bc2f5f0adcbc0f50db5a415bcb9fce2 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 23:52:57 +0100 Subject: [PATCH 03/66] docs: security policy and a supply-chain section in the README SECURITY.md covers private reporting, supported versions, and each supply-chain check with where to verify it. The README gains Scorecard and Socket badges and a short section listing what installing nanobook asks the user to trust. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- README.md | 25 ++++++++++++++++++++- SECURITY.md | 64 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 1 deletion(-) create mode 100644 SECURITY.md diff --git a/README.md b/README.md index 35b216f..5e34043 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,10 @@ [![crates.io](https://img.shields.io/crates/v/nanobook.svg)](https://crates.io/crates/nanobook) [![docs.rs](https://docs.rs/nanobook/badge.svg)](https://docs.rs/nanobook) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) -[![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 @@ -87,6 +90,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 ``` diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..ef0b6d2 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,64 @@ +# 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. + +## 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. +- The [OpenSSF Scorecard](https://scorecard.dev/viewer/?uri=github.com/BoringQuantSystems/nanobook) + rates the repository's security practices weekly. From 0f97e1a4ae1781a7638edda97bd86d52ab7fbd36 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 13 Nov 2026 23:53:36 +0100 Subject: [PATCH 04/66] ci(release): SHA256SUMS and build-provenance attestation for release binaries The release job writes SHA256SUMS over every lob archive and signs a GitHub build-provenance attestation for them, so a user can check both the bytes and that this repository's workflow built them. The job gains id-token and attestations write; the others stay read-only. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- .github/workflows/release.yml | 15 +++++++++++++++ SECURITY.md | 3 +++ 2 files changed, 18 insertions(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2b10f3f..9e3fce8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -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 @@ -105,6 +107,19 @@ jobs: with: path: artifacts + # Users can check a download with `sha256sum -c SHA256SUMS` and its origin with + # `gh attestation verify --repo BoringQuantSystems/nanobook`. + - name: Checksums + run: | + cd artifacts + find . -type f ! -name SHA256SUMS -print0 | sort -z | xargs -0 sha256sum > SHA256SUMS + 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: | VERSION=${GITHUB_REF_NAME#v} diff --git a/SECURITY.md b/SECURITY.md index ef0b6d2..666186b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -60,5 +60,8 @@ Every claim below can be checked in this repository or on a public service. - 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 --repo BoringQuantSystems/nanobook`. - The [OpenSSF Scorecard](https://scorecard.dev/viewer/?uri=github.com/BoringQuantSystems/nanobook) rates the repository's security practices weekly. From 741c43b7109970a0df0b3a45e10695413aea8232 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 07:14:49 +0100 Subject: [PATCH 05/66] fix(itch): read the Stock Directory symbol from its real offset ITCH 5.0 puts the 8-byte stock after the locate, the tracking number and the 6-byte timestamp: payload[10..18] after the type byte. The parser read payload[2..10], so StockDirectory carried tracking and timestamp bytes instead of the symbol. Found by cargo-mutants triage. The new test builds a full 39-byte message and fails on the old offset. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- src/itch.rs | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src/itch.rs b/src/itch.rs index 20f540f..23c3129 100644 --- a/src/itch.rs +++ b/src/itch.rs @@ -173,7 +173,7 @@ impl ItchParser { 'D' => 18, // ..payload[10..18] 'U' => 34, // ..payload[30..34] 'P' => 43, // ..payload[35..43] - 'R' => 10, // ..payload[2..10] + 'R' => 18, // ..payload[10..18] _ => 0, }; if payload.len() < min_payload { @@ -289,8 +289,10 @@ impl ItchParser { })) } 'R' => { + // Stock Directory: locate [0..2], tracking number [2..4], + // timestamp [4..10], stock [10..18] (ITCH 5.0, offsets after the type byte). let locate = read_u16_be(&payload[0..2], "R.locate")?; - let stock = String::from_utf8_lossy(&payload[2..10]).trim().to_string(); + let stock = String::from_utf8_lossy(&payload[10..18]).trim().to_string(); self.stock_locates.insert(locate, stock.clone()); Ok(Some(ItchMessage::StockDirectory { stock, locate })) } @@ -406,6 +408,30 @@ mod tests { // Parser: malformed input surfaces as Err, never as panic // ------------------------------------------------------------------ + /// A full-length Stock Directory message (ITCH 5.0: 39 bytes with the type byte). + /// The symbol sits after the 2-byte tracking number and the 6-byte timestamp. + #[test] + fn stock_directory_reads_symbol_after_timestamp() { + let mut msg = vec![b'R']; + msg.extend_from_slice(&7u16.to_be_bytes()); // stock locate + msg.extend_from_slice(&[0x12, 0x34]); // tracking number + msg.extend_from_slice(&[0xAB; 6]); // timestamp + msg.extend_from_slice(b"AAPL "); // stock, space padded + msg.extend_from_slice(&[b'Q'; 20]); // remaining directory fields + assert_eq!(msg.len(), 39); + let mut bytes = (msg.len() as u16).to_be_bytes().to_vec(); + bytes.extend_from_slice(&msg); + + let mut parser = ItchParser::new(&bytes[..]); + match parser.next_message().unwrap() { + Some(ItchMessage::StockDirectory { stock, locate }) => { + assert_eq!(stock, "AAPL"); + assert_eq!(locate, 7); + } + other => panic!("expected StockDirectory, got {other:?}"), + } + } + /// EOF at a message boundary is the happy-stream-end signal. #[test] fn empty_stream_yields_ok_none() { From 6b533779749c0622180420e2a8670fa1a58dc5e2 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:42:30 +0100 Subject: [PATCH 06/66] fix(broker): report an IBKR connection loss during an order The check for codes 1100-1102 sat inside a guard that admitted only codes below 0 or from 2000, so it never ran and a connection loss while waiting on an order was not returned as ConnectionLost. The guard and the connection check are now small functions; a unit test covers both and fails on the old guard. Found by cargo-mutants triage. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- broker/src/ibkr/orders.rs | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/broker/src/ibkr/orders.rs b/broker/src/ibkr/orders.rs index 46fd73d..48fdf93 100644 --- a/broker/src/ibkr/orders.rs +++ b/broker/src/ibkr/orders.rs @@ -84,6 +84,20 @@ use log::{debug, info, warn}; use crate::error::BrokerError; use crate::types::*; +/// IBKR system codes 1100 (connectivity lost), 1101 and 1102 (connectivity +/// restored, data lost or kept). During an order they end the wait with +/// `ConnectionLost`, so the caller reconciles the partial fill. +fn is_connection_lost(code: i32) -> bool { + (1100..=1102).contains(&code) +} + +/// Notices the order loop acts on: errors (code < 0), warnings (>= 2000) and +/// the connection codes. Before 0.20.0 the guard admitted only the first two, +/// so the connection check below it could never run. +fn is_order_notice(code: i32) -> bool { + code < 0 || code >= 2000 || is_connection_lost(code) +} + pub fn map_ibkr_order_status(status: &str) -> OrderState { match status { "Submitted" | "PreSubmitted" | "PendingSubmit" | "ApiPending" => OrderState::Submitted, @@ -510,10 +524,9 @@ pub fn execute_limit_order( commission = comm.commission; debug!("Commission: ${:.4}", commission); } - PlaceOrder::Message(notice) if notice.code < 0 || notice.code >= 2000 => { + PlaceOrder::Message(notice) if is_order_notice(notice.code) => { warn!("Order {order_id} error {}: {}", notice.code, notice.message); - // Detect disconnect errors (IBKR error code 1100, 1101, 1102) - if notice.code == 1100 || notice.code == 1101 || notice.code == 1102 { + if is_connection_lost(notice.code) { warn!( "AUDIT: Connection lost during order {order_id} execution (filled={})", filled @@ -942,6 +955,19 @@ mod tests { assert_eq!(ib_order.limit_price, Some(181.00)); } + #[test] + fn connection_codes_reach_the_order_loop() { + for code in [1100, 1101, 1102] { + assert!(is_order_notice(code), "code {code} must reach the order loop"); + assert!(is_connection_lost(code), "code {code} is a connection loss"); + } + for code in [1099, 1103, 2104, -1, 0, 201] { + assert!(!is_connection_lost(code), "code {code} is not a connection loss"); + } + assert!(is_order_notice(-1) && is_order_notice(2104)); + assert!(!is_order_notice(201) && !is_order_notice(1099)); + } + #[test] fn test_dedup_cache_detects_duplicates() { let cache = CallbackDedupCache::default(); From d7484f44f42f9a1685df6282f7a93c828c4c333b Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:45:06 +0100 Subject: [PATCH 07/66] fix(stats): deflated_sharpe follows Bailey and Lopez de Prado (2014) The function used n_trials as the sample length T and the Sharpe ratio's own standard error as the spread of the trials' Sharpe ratios, so it did not match the paper. It now takes n_observations (T) and trials_sharpe_variance (V), in Rust and Python. With one trial it returns the probabilistic Sharpe ratio against zero instead of the raw Sharpe ratio. Tests reproduce the paper's worked example (p. 99): DSR 0.9004 at N=100, 0.9505 at N=46, 0.9505 at N=88 with normal returns. The two old single-trial tests asserted the raw-Sharpe return and are replaced by an exact PSR value. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- python/src/stats.rs | 45 ++++-- python/tests/reference/test_ref_stats.py | 29 ++-- src/stats.rs | 169 ++++++++++++----------- 3 files changed, 135 insertions(+), 108 deletions(-) diff --git a/python/src/stats.rs b/python/src/stats.rs index c1c0387..5e1434c 100644 --- a/python/src/stats.rs +++ b/python/src/stats.rs @@ -45,28 +45,43 @@ pub fn py_quintile_spread(scores: Vec, returns: Vec, n_quantiles: usiz stats::quintile_spread(&scores, &returns, n_quantiles) } -/// Compute the Deflated Sharpe Ratio. +/// Compute the Deflated Sharpe Ratio (Bailey and López de Prado, 2014). /// -/// Lopez de Prado's Deflated Sharpe Ratio adjusts an observed Sharpe ratio for -/// multiple testing and non-normal return distributions. The result is a -/// standard-normal probability after subtracting the expected maximum Sharpe -/// under the null across ``n_trials``. +/// The probability that the true Sharpe ratio is above zero after correcting the +/// observed one for selection across ``n_trials`` strategies and for non-normal +/// returns. With one trial it is the probabilistic Sharpe ratio against zero. /// /// Args: -/// sharpe: Observed Sharpe ratio. -/// n_trials: Number of independent strategy trials. -/// skewness: Skewness of the returns distribution. -/// kurtosis: Kurtosis of the returns distribution. +/// sharpe: Observed Sharpe ratio, per period (not annualized). +/// n_trials: Number of independent strategy trials (N). +/// n_observations: Number of returns behind ``sharpe`` (T), at least 2. +/// trials_sharpe_variance: Variance of the per-period Sharpe ratios across +/// the trials (V). +/// skewness: Skewness of the returns. +/// kurtosis: Raw kurtosis of the returns (3 for normal returns). /// /// Returns: -/// Float: Deflated Sharpe Ratio probability. Returns NaN for invalid -/// inputs. For one trial, returns ``sharpe`` unchanged. +/// Float: probability in [0, 1]. NaN for invalid inputs. /// -/// Example:: +/// Example (the paper's worked example, p. 99; returns about 0.9004):: /// -/// dsr = nanobook.py_deflated_sharpe(1.5, 20, 0.0, 3.0) +/// dsr = nanobook.py_deflated_sharpe(2.5 / 250**0.5, 100, 1250, 0.5 / 250, -3.0, 10.0) /// #[pyfunction] -pub fn py_deflated_sharpe(sharpe: f64, n_trials: usize, skewness: f64, kurtosis: f64) -> f64 { - stats::deflated_sharpe(sharpe, n_trials, skewness, kurtosis) +pub fn py_deflated_sharpe( + sharpe: f64, + n_trials: usize, + n_observations: usize, + trials_sharpe_variance: f64, + skewness: f64, + kurtosis: f64, +) -> f64 { + stats::deflated_sharpe( + sharpe, + n_trials, + n_observations, + trials_sharpe_variance, + skewness, + kurtosis, + ) } diff --git a/python/tests/reference/test_ref_stats.py b/python/tests/reference/test_ref_stats.py index efa9061..4d789bd 100644 --- a/python/tests/reference/test_ref_stats.py +++ b/python/tests/reference/test_ref_stats.py @@ -89,17 +89,22 @@ def test_inverse_scores(self): class TestDeflatedSharpe: - """Basic coverage for Deflated Sharpe Ratio binding.""" - - def test_basic(self): - got = nanobook.py_deflated_sharpe(1.5, 20, 0.0, 3.0) - assert np.isfinite(got) - assert 0.0 <= got <= 1.0 - - def test_single_trial(self): - got = nanobook.py_deflated_sharpe(1.25, 1, 0.0, 3.0) - assert got == pytest.approx(1.25) + """Deflated Sharpe Ratio against the worked example of Bailey and + López de Prado (2014), p. 99.""" + + def test_paper_example(self): + sr = 2.5 / 250**0.5 + v = 0.5 / 250 + assert nanobook.py_deflated_sharpe(sr, 100, 1250, v, -3.0, 10.0) == pytest.approx(0.9004, abs=5e-5) + assert nanobook.py_deflated_sharpe(sr, 46, 1250, v, -3.0, 10.0) == pytest.approx(0.9505, abs=5e-5) + assert nanobook.py_deflated_sharpe(sr, 88, 1250, v, 0.0, 3.0) == pytest.approx(0.9505, abs=5e-5) + + def test_single_trial_is_psr_against_zero(self): + from statistics import NormalDist + want = NormalDist().cdf(0.1 * 10.0 / (1.0 + 0.5 * 0.01) ** 0.5) + got = nanobook.py_deflated_sharpe(0.1, 1, 101, 0.0, 0.0, 3.0) + assert got == pytest.approx(want, abs=1e-12) def test_invalid_inputs(self): - got = nanobook.py_deflated_sharpe(1.0, 0, 0.0, 3.0) - assert np.isnan(got) + assert np.isnan(nanobook.py_deflated_sharpe(0.1, 0, 100, 0.01, 0.0, 3.0)) + assert np.isnan(nanobook.py_deflated_sharpe(0.1, 10, 1, 0.01, 0.0, 3.0)) diff --git a/src/stats.rs b/src/stats.rs index 39ef35e..6178936 100644 --- a/src/stats.rs +++ b/src/stats.rs @@ -398,65 +398,78 @@ pub fn spearman(x: &[f64], y: &[f64]) -> (f64, f64) { (r_clamped, p_value) } -/// Deflated Sharpe Ratio after Lopez de Prado (2018). +/// Deflated Sharpe Ratio (Bailey and López de Prado, 2014). /// -/// Returns the probability that an observed Sharpe ratio remains positive -/// after adjusting for selection across multiple trials and non-normal return -/// moments. The implementation follows the common deflated-Sharpe structure: +/// The probability that the true Sharpe ratio is above zero, after correcting the +/// observed one for selection across `n_trials` strategies and for non-normal +/// returns: /// -/// `DSR = Phi((SR - E[max SR]) / sigma[SR])` +/// `DSR = Phi((SR - SR0) * sqrt(T - 1) / sqrt(1 - skewness * SR + (kurtosis - 1) / 4 * SR^2))` /// -/// where `Phi` is the standard normal CDF, `E[max SR]` is the expected maximum -/// Sharpe under the null across `n_trials`, and `sigma[SR]` uses the -/// skewness/kurtosis-adjusted finite-sample standard error: +/// `SR0 = sqrt(V) * ((1 - g) * Phi^-1(1 - 1/N) + g * Phi^-1(1 - 1/(N e)))` /// -/// `sqrt((1 - skewness * SR + (kurtosis - 1) / 4 * SR^2) / (n_trials - 1))`. +/// where `Phi` is the standard normal CDF, `g` the Euler-Mascheroni constant, +/// `N = n_trials`, `T = n_observations` (the number of returns behind `sharpe`) and +/// `V = trials_sharpe_variance` (the variance of the Sharpe ratios across the +/// trials). `SR0` is the expected maximum Sharpe ratio of `N` unskilled trials. +/// With one trial there is nothing to deflate: `SR0 = 0` and the result is the +/// probabilistic Sharpe ratio against zero. /// -/// Returns `NaN` for invalid inputs. A single trial returns the input Sharpe -/// unchanged because there is no multiple-testing adjustment. +/// Units: `sharpe` and `V` are per period (not annualized), in the same period as +/// the returns; `kurtosis` is raw kurtosis (3 for normal returns). +/// +/// Returns `NaN` for invalid inputs: `n_trials == 0`, `n_observations < 2`, a +/// negative or non-finite variance, non-finite moments, `kurtosis <= 0`, or a +/// non-positive variance term. /// /// # References /// -/// - López de Prado, M. (2018), "Advances in Financial Machine Learning", -/// Chapter 3: "The Deflated Sharpe Ratio". -pub fn deflated_sharpe(sharpe: f64, n_trials: usize, skewness: f64, kurtosis: f64) -> f64 { - if n_trials == 0 { +/// - Bailey, D. H., and López de Prado, M. (2014), "The Deflated Sharpe Ratio: +/// Correcting for Selection Bias, Backtest Overfitting, and Non-Normality", +/// Journal of Portfolio Management 40(5), 94-107; definition p. 98, worked +/// example p. 99. +pub fn deflated_sharpe( + sharpe: f64, + n_trials: usize, + n_observations: usize, + trials_sharpe_variance: f64, + skewness: f64, + kurtosis: f64, +) -> f64 { + if n_trials == 0 || n_observations < 2 { return f64::NAN; } - if n_trials == 1 { - return sharpe; - } if !sharpe.is_finite() + || !trials_sharpe_variance.is_finite() + || trials_sharpe_variance < 0.0 || !skewness.is_finite() || !kurtosis.is_finite() - || sharpe < 0.0 || kurtosis <= 0.0 { return f64::NAN; } - let n = n_trials as f64; let variance_term = 1.0 - skewness * sharpe + 0.25 * (kurtosis - 1.0) * sharpe * sharpe; if !variance_term.is_finite() || variance_term <= 0.0 { return f64::NAN; } - let sharpe_se = (variance_term / (n - 1.0)).sqrt(); - if !sharpe_se.is_finite() || sharpe_se <= 0.0 { - return f64::NAN; - } - - let euler_gamma = 0.577_215_664_901_532_9_f64; - let p1 = (1.0 - 1.0 / n).clamp(f64::EPSILON, 1.0 - f64::EPSILON); - let p2 = (1.0 - 1.0 / (n * std::f64::consts::E)).clamp(f64::EPSILON, 1.0 - f64::EPSILON); - let expected_max_standard = (1.0 - euler_gamma) * inverse_standard_normal_cdf(p1) - + euler_gamma * inverse_standard_normal_cdf(p2); - if !expected_max_standard.is_finite() { - return f64::NAN; - } + let threshold = if n_trials == 1 { + 0.0 + } else { + let n = n_trials as f64; + let euler_gamma = 0.577_215_664_901_532_9_f64; + let expected_max_standard = (1.0 - euler_gamma) + * inverse_standard_normal_cdf(1.0 - 1.0 / n) + + euler_gamma * inverse_standard_normal_cdf(1.0 - 1.0 / (n * std::f64::consts::E)); + if !expected_max_standard.is_finite() { + return f64::NAN; + } + trials_sharpe_variance.sqrt() * expected_max_standard + }; - let expected_max_sharpe = sharpe_se * expected_max_standard; - standard_normal_cdf((sharpe - expected_max_sharpe) / sharpe_se) + let t = n_observations as f64; + standard_normal_cdf((sharpe - threshold) * (t - 1.0).sqrt() / variance_term.sqrt()) } /// Quintile spread: mean of top quintile returns minus mean of bottom quintile returns. @@ -744,69 +757,63 @@ mod tests { // --- Deflated Sharpe Ratio tests ---------------------------------------- + /// Worked example of Bailey and López de Prado (2014), p. 99: annualized SR 2.5 + /// on 1250 daily returns (250 per year), N = 100 trials whose annualized SRs have + /// variance 1/2, skewness -3, kurtosis 10. The paper reports SR0 = 0.1132 and + /// DSR = 0.9004; with N = 46 the DSR is 0.9505, and with normal returns + /// (skewness 0, kurtosis 3) it is 0.9505 at N = 88. #[test] - fn test_deflated_sharpe_basic() { - let dsr = deflated_sharpe(1.5, 20, 0.0, 3.0); - assert!(dsr.is_finite(), "expected finite DSR, got {dsr}"); - assert!( - (0.0..=1.0).contains(&dsr), - "expected probability, got {dsr}" - ); - } - - #[test] - fn test_deflated_sharpe_single_trial() { - let sharpe = 1.25; - let dsr = deflated_sharpe(sharpe, 1, 0.0, 3.0); - assert_eq!(dsr, sharpe); + fn deflated_sharpe_matches_the_paper_example() { + let sr = 2.5 / 250f64.sqrt(); + let v = 0.5 / 250.0; + let cases = [(100, -3.0, 10.0, 0.9004), (46, -3.0, 10.0, 0.9505), (88, 0.0, 3.0, 0.9505)]; + for (n, skew, kurt, want) in cases { + let dsr = deflated_sharpe(sr, n, 1250, v, skew, kurt); + assert!((dsr - want).abs() < 5e-5, "N={n}: got {dsr}, paper {want}"); + } } + /// One trial: no deflation, the probabilistic Sharpe ratio against zero, + /// Phi(SR * sqrt(T - 1)) for normal returns. SR 0.1 on 101 returns gives Phi(1). #[test] - fn test_deflated_sharpe_zero_skewness_kurtosis() { - let dsr = deflated_sharpe(1.0, 10, 0.0, 3.0); - assert!( - dsr.is_finite(), - "expected finite normal-case DSR, got {dsr}" - ); - assert!( - (0.0..=1.0).contains(&dsr), - "expected probability, got {dsr}" - ); + fn deflated_sharpe_single_trial_is_psr_against_zero() { + let dsr = deflated_sharpe(0.1, 1, 101, 0.0, 0.0, 3.0); + let normal_term = (1.0 + 0.5 * 0.01_f64).sqrt(); + let want = standard_normal_cdf(0.1 * 10.0 / normal_term); + assert!((dsr - want).abs() < 1e-12, "got {dsr}, want {want}"); + assert!((0.0..=1.0).contains(&dsr)); } #[test] - fn test_deflated_sharpe_invalid_inputs() { - assert!(deflated_sharpe(1.0, 0, 0.0, 3.0).is_nan()); - assert!(deflated_sharpe(-1.0, 10, 0.0, 3.0).is_nan()); - assert!(deflated_sharpe(1.0, 10, 0.0, -3.0).is_nan()); - assert!(deflated_sharpe(f64::INFINITY, 10, 0.0, 3.0).is_nan()); + fn deflated_sharpe_falls_as_trials_grow() { + let sr = 0.15; + let v = 0.002; + let few = deflated_sharpe(sr, 10, 1000, v, 0.0, 3.0); + let many = deflated_sharpe(sr, 1000, 1000, v, 0.0, 3.0); + assert!(many < few, "more trials must deflate more: {many} >= {few}"); } #[test] - fn test_deflated_sharpe_extreme_values() { - let large = deflated_sharpe(10.0, 1_000, 0.0, 3.0); - let small = deflated_sharpe(1.0e-12, 1_000, 0.0, 3.0); - assert!( - large.is_finite(), - "large Sharpe should stay finite, got {large}" - ); - assert!( - small.is_finite(), - "small Sharpe should stay finite, got {small}" - ); - assert!((0.0..=1.0).contains(&large)); - assert!((0.0..=1.0).contains(&small)); + fn deflated_sharpe_invalid_inputs() { + assert!(deflated_sharpe(0.1, 0, 100, 0.01, 0.0, 3.0).is_nan()); + assert!(deflated_sharpe(0.1, 10, 1, 0.01, 0.0, 3.0).is_nan()); + assert!(deflated_sharpe(0.1, 10, 100, -0.01, 0.0, 3.0).is_nan()); + assert!(deflated_sharpe(0.1, 10, 100, 0.01, 0.0, -3.0).is_nan()); + assert!(deflated_sharpe(f64::INFINITY, 10, 100, 0.01, 0.0, 3.0).is_nan()); + assert!(deflated_sharpe(0.1, 10, 100, f64::NAN, 0.0, 3.0).is_nan()); } proptest::proptest! { #[test] - fn prop_deflated_sharpe_does_not_exceed_unadjusted_probability( - sharpe in 0.01f64..10.0, - n_trials in 2usize..1000, + fn prop_deflated_sharpe_is_a_probability( + sharpe in -2.0f64..2.0, + n_trials in 1usize..1000, + n_observations in 2usize..5000, + variance in 0.0f64..0.1, skewness in -5.0f64..5.0, kurtosis in 0.1f64..10.0, ) { - let dsr = deflated_sharpe(sharpe, n_trials, skewness, kurtosis); + let dsr = deflated_sharpe(sharpe, n_trials, n_observations, variance, skewness, kurtosis); if dsr.is_finite() { proptest::prop_assert!((0.0..=1.0).contains(&dsr), "DSR must be in [0, 1], got {dsr}"); } From 3fa3ef47336473fbe886e28f8aed1da654c57f31 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:46:53 +0100 Subject: [PATCH 08/66] style: rustfmt and clippy fixes for the IBKR guard and the DSR tests Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- broker/src/ibkr/orders.rs | 12 +++++++++--- src/stats.rs | 6 +++++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/broker/src/ibkr/orders.rs b/broker/src/ibkr/orders.rs index 48fdf93..92644a2 100644 --- a/broker/src/ibkr/orders.rs +++ b/broker/src/ibkr/orders.rs @@ -95,7 +95,7 @@ fn is_connection_lost(code: i32) -> bool { /// the connection codes. Before 0.20.0 the guard admitted only the first two, /// so the connection check below it could never run. fn is_order_notice(code: i32) -> bool { - code < 0 || code >= 2000 || is_connection_lost(code) + !(0..2000).contains(&code) || is_connection_lost(code) } pub fn map_ibkr_order_status(status: &str) -> OrderState { @@ -958,11 +958,17 @@ mod tests { #[test] fn connection_codes_reach_the_order_loop() { for code in [1100, 1101, 1102] { - assert!(is_order_notice(code), "code {code} must reach the order loop"); + assert!( + is_order_notice(code), + "code {code} must reach the order loop" + ); assert!(is_connection_lost(code), "code {code} is a connection loss"); } for code in [1099, 1103, 2104, -1, 0, 201] { - assert!(!is_connection_lost(code), "code {code} is not a connection loss"); + assert!( + !is_connection_lost(code), + "code {code} is not a connection loss" + ); } assert!(is_order_notice(-1) && is_order_notice(2104)); assert!(!is_order_notice(201) && !is_order_notice(1099)); diff --git a/src/stats.rs b/src/stats.rs index 6178936..0568797 100644 --- a/src/stats.rs +++ b/src/stats.rs @@ -766,7 +766,11 @@ mod tests { fn deflated_sharpe_matches_the_paper_example() { let sr = 2.5 / 250f64.sqrt(); let v = 0.5 / 250.0; - let cases = [(100, -3.0, 10.0, 0.9004), (46, -3.0, 10.0, 0.9505), (88, 0.0, 3.0, 0.9505)]; + let cases = [ + (100, -3.0, 10.0, 0.9004), + (46, -3.0, 10.0, 0.9505), + (88, 0.0, 3.0, 0.9505), + ]; for (n, skew, kurt, want) in cases { let dsr = deflated_sharpe(sr, n, 1250, v, skew, kurt); assert!((dsr - want).abs() < 5e-5, "N={n}: got {dsr}, paper {want}"); From 3722970a399538f62957a7adba5328d74ce14c13 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:46:53 +0100 Subject: [PATCH 09/66] refactor: forbid unsafe code in the four Rust crates Symbol::as_str now uses a checked UTF-8 conversion (at most 8 bytes) instead of from_utf8_unchecked, the only unsafe block in the workspace. Each crate root forbids unsafe code. types.rs also documents Timestamp as what it is: an event counter starting at 1, not nanoseconds. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- broker/src/lib.rs | 2 ++ rebalancer/src/lib.rs | 2 ++ rebalancer/src/main.rs | 2 ++ risk/src/lib.rs | 2 ++ src/lib.rs | 1 + src/types.rs | 17 +++++++++-------- 6 files changed, 18 insertions(+), 8 deletions(-) diff --git a/broker/src/lib.rs b/broker/src/lib.rs index 218c334..a4f53d5 100644 --- a/broker/src/lib.rs +++ b/broker/src/lib.rs @@ -6,6 +6,8 @@ //! - **IBKR** (feature `ibkr`): Interactive Brokers via TWS API //! - **Binance** (feature `binance`): Binance spot REST API +#![forbid(unsafe_code)] + pub mod error; pub mod mock; pub mod types; diff --git a/rebalancer/src/lib.rs b/rebalancer/src/lib.rs index 6c46e2d..c36d04d 100644 --- a/rebalancer/src/lib.rs +++ b/rebalancer/src/lib.rs @@ -4,6 +4,8 @@ //! and prices, computes the diff, and executes limit orders with risk checks //! and an audit trail. +#![forbid(unsafe_code)] + pub mod audit; pub mod broker; pub mod clock_skew; diff --git a/rebalancer/src/main.rs b/rebalancer/src/main.rs index 1ef61ef..f1a3772 100644 --- a/rebalancer/src/main.rs +++ b/rebalancer/src/main.rs @@ -1,5 +1,7 @@ //! CLI entry point for the nanobook rebalancer. +#![forbid(unsafe_code)] + use std::path::PathBuf; use std::process; diff --git a/risk/src/lib.rs b/risk/src/lib.rs index 4c204b4..4e54e18 100644 --- a/risk/src/lib.rs +++ b/risk/src/lib.rs @@ -3,6 +3,8 @@ //! Validates orders against configurable risk limits before execution. //! Uses generic broker types so it can be called from Python or any broker adapter. +#![forbid(unsafe_code)] + pub mod checks; pub mod config; pub mod error; diff --git a/src/lib.rs b/src/lib.rs index 6a2281e..d750dec 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ +#![forbid(unsafe_code)] // Allow our dollar.cents digit grouping convention (e.g., 100_00 = $100.00) #![allow(clippy::inconsistent_digit_grouping)] diff --git a/src/types.rs b/src/types.rs index 0587b28..feeadf0 100644 --- a/src/types.rs +++ b/src/types.rs @@ -32,8 +32,8 @@ impl fmt::Display for Price { /// Quantity of shares/contracts. Always positive. pub type Quantity = u64; -/// Timestamp in nanoseconds since exchange start. -/// Monotonically increasing, assigned by exchange. +/// Event sequence number assigned by the exchange. +/// Starts at 1 and increases by 1 per stamped event; it is not wall-clock time. pub type Timestamp = u64; /// Unique order identifier assigned by exchange. @@ -121,12 +121,13 @@ impl Symbol { /// Returns the symbol as a string slice. #[inline] pub fn as_str(&self) -> &str { - // SAFETY: `Symbol` fields are private. The only constructors copy bytes from - // valid `str` inputs, and `from_str_truncated` backs up to `valid_up_to()` - // when an 8-byte prefix would split a multi-byte UTF-8 scalar. Therefore - // `buf[..len]` is always valid UTF-8 for every safe `Symbol` value. - debug_assert!(std::str::from_utf8(&self.buf[..self.len as usize]).is_ok()); - unsafe { std::str::from_utf8_unchecked(&self.buf[..self.len as usize]) } + // `Symbol` fields are private. The only constructors copy bytes from valid + // `str` inputs, and `from_str_truncated` backs up to `valid_up_to()` when an + // 8-byte prefix would split a multi-byte UTF-8 scalar, so `buf[..len]` is + // always valid UTF-8. The check costs at most 8 bytes and keeps the crate + // free of `unsafe`. + std::str::from_utf8(&self.buf[..self.len as usize]) + .expect("Symbol always holds valid UTF-8") } } From eb0ecf9055e28c24bd6f52dc1778dcc2a9b43e1b Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:46:53 +0100 Subject: [PATCH 10/66] docs: make six ignored doctests compile and run; document equity_curve's first entry The examples in persistence, strategy, sweep (two), cost_model and the broker mock were marked ignore, so nothing checked them. They now compile and run (persistence is no_run: it writes a file). The reference documents Timestamp as an event counter. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- broker/src/mock.rs | 2 +- docs/reference.md | 4 ++-- src/persistence.rs | 7 +++++-- src/portfolio/cost_model.rs | 2 +- src/portfolio/mod.rs | 2 +- src/portfolio/strategy.rs | 11 +++++++++-- src/portfolio/sweep.rs | 17 ++++++++++++++--- 7 files changed, 33 insertions(+), 12 deletions(-) diff --git a/broker/src/mock.rs b/broker/src/mock.rs index 6f2f471..4e4ed0e 100644 --- a/broker/src/mock.rs +++ b/broker/src/mock.rs @@ -2,7 +2,7 @@ //! //! Use this in integration tests to simulate broker responses without network calls. //! -//! ```ignore +//! ``` //! use nanobook_broker::mock::{MockBroker, FillMode}; //! use nanobook::Symbol; //! diff --git a/docs/reference.md b/docs/reference.md index 5dd199b..07bfe8e 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -66,7 +66,7 @@ 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. +- `Timestamp = u64` — event counter assigned by the exchange, starting at 1 and increasing by 1 (not wall-clock time), guaranteeing deterministic ordering. ### Determinism @@ -144,7 +144,7 @@ assert_eq!(err.unwrap_err(), ValidationError::ZeroPrice); | `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) | — | +| `Timestamp` | `type Timestamp = u64` | Event counter, +1 per event (not wall clock) | — | ### Result Types diff --git a/src/persistence.rs b/src/persistence.rs index 025a353..f74de37 100644 --- a/src/persistence.rs +++ b/src/persistence.rs @@ -5,10 +5,13 @@ //! //! # Usage //! -//! ```ignore -//! use nanobook::persistence; +//! ```no_run +//! use nanobook::{Exchange, Price, Side, TimeInForce}; //! use std::path::Path; //! +//! let mut exchange = Exchange::new(); +//! exchange.submit_limit(Side::Buy, Price(100_00), 100, TimeInForce::GTC); +//! //! // Save exchange state //! exchange.save(Path::new("orders.jsonl")).unwrap(); //! diff --git a/src/portfolio/cost_model.rs b/src/portfolio/cost_model.rs index f7070ae..374e6d4 100644 --- a/src/portfolio/cost_model.rs +++ b/src/portfolio/cost_model.rs @@ -6,7 +6,7 @@ /// plus a minimum per-fill commission. Slippage is modeled as price impact by /// portfolio execution, not by [`CostModel::compute_cost`]. /// -/// ```ignore +/// ``` /// use nanobook::portfolio::CostModel; /// /// let model = CostModel { commission_bps: 10.0, slippage_bps: 5.0, min_commission: 1_00 }; diff --git a/src/portfolio/mod.rs b/src/portfolio/mod.rs index 8be6909..d1ad57d 100644 --- a/src/portfolio/mod.rs +++ b/src/portfolio/mod.rs @@ -466,7 +466,7 @@ impl Portfolio { &self.returns } - /// The equity curve (one entry per `record_return` call). + /// The equity curve: the initial cash, then one entry per `record_return` call. pub fn equity_curve(&self) -> &[i64] { &self.equity_curve } diff --git a/src/portfolio/strategy.rs b/src/portfolio/strategy.rs index 180c714..22139e7 100644 --- a/src/portfolio/strategy.rs +++ b/src/portfolio/strategy.rs @@ -6,8 +6,8 @@ //! //! # Example //! -//! ```ignore -//! use nanobook::portfolio::strategy::{Strategy, run_backtest, BacktestResult}; +//! ``` +//! use nanobook::portfolio::strategy::{Strategy, run_backtest}; //! use nanobook::portfolio::CostModel; //! use nanobook::Symbol; //! @@ -24,6 +24,13 @@ //! prices.iter().map(|&(sym, _)| (sym, 1.0 / n)).collect() //! } //! } +//! +//! let prices = vec![ +//! vec![(Symbol::new("AAPL"), 185_00), (Symbol::new("MSFT"), 370_00)], +//! vec![(Symbol::new("AAPL"), 187_00), (Symbol::new("MSFT"), 368_00)], +//! ]; +//! let result = run_backtest(&EqualWeight, &prices, 1_000_000_00, CostModel::zero(), 252.0, 0.0); +//! assert_eq!(result.portfolio.equity_curve().len(), prices.len() + 1); //! ``` use crate::portfolio::{CostModel, Metrics, Portfolio}; diff --git a/src/portfolio/sweep.rs b/src/portfolio/sweep.rs index ce485f1..7d671c6 100644 --- a/src/portfolio/sweep.rs +++ b/src/portfolio/sweep.rs @@ -17,8 +17,8 @@ use super::strategy::{BacktestResult, Strategy, run_backtest}; /// /// # Example /// -/// ```ignore -/// use nanobook::portfolio::sweep; +/// ``` +/// use nanobook::portfolio::sweep::sweep; /// /// let params = vec![0.5_f64, 1.0, 1.5, 2.0]; // e.g., leverage levels /// let results = sweep(¶ms, 12.0, 0.0, |&leverage| { @@ -55,9 +55,20 @@ where /// /// # Example /// -/// ```ignore +/// ``` /// use nanobook::portfolio::sweep::sweep_strategy; +/// use nanobook::portfolio::{CostModel, Portfolio, Strategy}; +/// use nanobook::Symbol; +/// +/// struct MyStrategy { weight: f64 } +/// impl Strategy for MyStrategy { +/// fn compute_weights(&self, _bar: usize, prices: &[(Symbol, i64)], _p: &Portfolio) -> Vec<(Symbol, f64)> { +/// prices.iter().map(|&(sym, _)| (sym, self.weight)).collect() +/// } +/// } /// +/// let prices = vec![vec![(Symbol::new("AAPL"), 185_00)], vec![(Symbol::new("AAPL"), 187_00)]]; +/// let (initial_cash, cost_model) = (1_000_000_00, CostModel::zero()); /// let params = vec![0.5_f64, 1.0, 1.5]; /// let results = sweep_strategy(¶ms, &prices, initial_cash, cost_model, 12.0, 0.0, |&weight| { /// MyStrategy { weight } From 90904ea4e1184c09f452c7f8739e7f02d4988c68 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:46:53 +0100 Subject: [PATCH 11/66] test: pin the exact answers of the book queries and setters cargo-mutants showed best_bid_ask, spread, full_book, contains_order, set_stp_policy, clear_order_history, book_mut and stop_book could return wrong values unnoticed. Seven tests pin each to exact values. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- tests/book_queries.rs | 129 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 tests/book_queries.rs diff --git a/tests/book_queries.rs b/tests/book_queries.rs new file mode 100644 index 0000000..4ba853c --- /dev/null +++ b/tests/book_queries.rs @@ -0,0 +1,129 @@ +//! Exact answers of the read-only book queries and the history and policy setters. +//! +//! cargo-mutants (0.20.0 run) showed these could return wrong values without any +//! test noticing: most tests check trades and order status, not the queries +//! themselves. Each test pins one query to an exact value. + +#![allow(clippy::inconsistent_digit_grouping)] // prices in cents: 100_00 = 100.00 + +use nanobook::{Exchange, OrderId, OrderOwner, OrderStatus, Price, Side, StpPolicy, TimeInForce}; + +/// Bid 100.00 x 10, ask 101.00 x 20 (a second bid at 99.00 x 5 behind it). +fn two_sided() -> Exchange { + let mut ex = Exchange::new(); + ex.submit_limit(Side::Buy, Price(100_00), 10, TimeInForce::GTC); + ex.submit_limit(Side::Buy, Price(99_00), 5, TimeInForce::GTC); + ex.submit_limit(Side::Sell, Price(101_00), 20, TimeInForce::GTC); + ex +} + +#[test] +fn best_bid_ask_and_spread_are_exact() { + let ex = two_sided(); + assert_eq!( + ex.best_bid_ask(), + (Some(Price(100_00)), Some(Price(101_00))) + ); + assert_eq!( + ex.book().best_bid_ask(), + (Some(Price(100_00)), Some(Price(101_00))) + ); + assert_eq!(ex.spread(), Some(1_00)); +} + +#[test] +fn one_sided_and_empty_books_report_missing_sides() { + let mut ex = Exchange::new(); + assert_eq!(ex.best_bid_ask(), (None, None)); + assert_eq!(ex.spread(), None); + + ex.submit_limit(Side::Buy, Price(100_00), 10, TimeInForce::GTC); + assert_eq!(ex.best_bid_ask(), (Some(Price(100_00)), None)); + assert_eq!(ex.spread(), None); + + let mut ex = Exchange::new(); + ex.submit_limit(Side::Sell, Price(101_00), 10, TimeInForce::GTC); + assert_eq!(ex.best_bid_ask(), (None, Some(Price(101_00)))); + assert_eq!(ex.book().best_bid_ask(), (None, Some(Price(101_00)))); +} + +#[test] +fn full_book_lists_every_level_best_first() { + let snap = two_sided().full_book(); + let bids: Vec<_> = snap + .bids + .iter() + .map(|l| (l.price, l.quantity, l.order_count)) + .collect(); + let asks: Vec<_> = snap + .asks + .iter() + .map(|l| (l.price, l.quantity, l.order_count)) + .collect(); + assert_eq!(bids, vec![(Price(100_00), 10, 1), (Price(99_00), 5, 1)]); + assert_eq!(asks, vec![(Price(101_00), 20, 1)]); +} + +#[test] +fn contains_order_is_false_for_unknown_ids() { + let mut ex = Exchange::new(); + let id = ex + .submit_limit(Side::Buy, Price(100_00), 10, TimeInForce::GTC) + .order_id; + assert!(ex.book().contains_order(id)); + assert!(!ex.book().contains_order(OrderId(id.0 + 1_000))); +} + +#[test] +fn stp_policy_setter_takes_effect() { + let mut ex = Exchange::new(); + assert_eq!(ex.stp_policy(), StpPolicy::Off); + ex.set_stp_policy(StpPolicy::CancelNewest); + assert_eq!(ex.stp_policy(), StpPolicy::CancelNewest); + + // The setter changes matching: the same owner no longer trades with itself. + let owner = OrderOwner(7); + ex.submit_limit_with_owner(Side::Sell, Price(100_00), 10, TimeInForce::GTC, owner); + let buy = ex.submit_limit_with_owner(Side::Buy, Price(100_00), 10, TimeInForce::GTC, owner); + assert!(ex.trades().is_empty()); + assert_eq!( + ex.get_order(buy.order_id).unwrap().status, + OrderStatus::Cancelled + ); +} + +#[test] +fn clear_order_history_returns_the_number_removed() { + let mut ex = Exchange::new(); + let resting = ex + .submit_limit(Side::Buy, Price(99_00), 10, TimeInForce::GTC) + .order_id; + let filled = ex + .submit_limit(Side::Sell, Price(101_00), 5, TimeInForce::GTC) + .order_id; + ex.submit_limit(Side::Buy, Price(101_00), 5, TimeInForce::GTC); // fills `filled` and itself + let cancelled = ex + .submit_limit(Side::Sell, Price(102_00), 5, TimeInForce::GTC) + .order_id; + ex.cancel(cancelled); + + // Four orders: one active, three finished (two filled, one cancelled). + assert_eq!(ex.clear_order_history(), 3); + assert!(ex.get_order(resting).is_some()); + assert!(ex.get_order(filled).is_none()); + assert_eq!(ex.clear_order_history(), 0); +} + +#[test] +fn book_mut_and_stop_book_reach_the_exchange_state() { + let mut ex = Exchange::new(); + let id = ex + .submit_limit(Side::Buy, Price(100_00), 10, TimeInForce::GTC) + .order_id; + assert_eq!(ex.book_mut().cancel_order(id), Some(10)); + assert_eq!(ex.best_bid_ask(), (None, None)); + + ex.submit_stop_market(Side::Buy, Price(105_00), 10); + assert_eq!(ex.stop_book().pending_count(), 1); + assert_eq!(ex.pending_stop_count(), 1); +} From 122d4507412078f4be7680ebd586223551a44e4c Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:46:53 +0100 Subject: [PATCH 12/66] docs(changelog): security, ITCH, IBKR and deflated Sharpe entries for 0.20.0 Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- CHANGELOG.md | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index daaf1cc..83c99a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased -nanobook and the Python package move from 0.19.3 to 0.20.0. nanobook-broker, -nanobook-risk and nanobook-rebalancer do not change and are not republished. +nanobook and the Python package move from 0.19.3 to 0.20.0, and nanobook-broker +from 0.10.1 to 0.10.2. nanobook-risk and nanobook-rebalancer are republished only if +their code changes before the release. ### Highlight: matching rules proved in Lean 4 @@ -43,6 +44,16 @@ tests, fuzzing or mutation testing. ### Changed +- **`deflated_sharpe` follows Bailey and López de Prado (2014).** It now takes the + sample length `n_observations` (T) and the variance of the Sharpe ratios across the + trials `trials_sharpe_variance` (V): `deflated_sharpe(sharpe, n_trials, + n_observations, trials_sharpe_variance, skewness, kurtosis)`, and the same in + Python. Before, `n_trials` stood in for T and the Sharpe ratio's own standard error + for √V, so results did not match the paper. One trial now returns the + probabilistic Sharpe ratio against zero, a probability, instead of the raw Sharpe + ratio; negative Sharpe ratios are accepted. The tests reproduce the paper's worked + example (DSR 0.9004, p. 99). *Check your code if* you call `deflated_sharpe` or + `py_deflated_sharpe`: the call needs the two new arguments. - **Fill-or-kill under self-trade prevention is rejected with no effect.** The fill-or-kill check now counts only the size the order could actually trade under its self-trade policy. Before, it counted the owner's own resting orders, so the @@ -75,6 +86,13 @@ tests, fuzzing or mutation testing. rejecting** (see Changed). - `Trade::vwap` returns `None` when the quantity sum does not fit, instead of overflowing. +- **nanobook-broker: an IBKR connection loss during an order was not reported.** + Codes 1100 to 1102 never reached their check, so `execute_limit_order` did not + return `ConnectionLost` with the partial fill. It does now. Found by mutation + testing. +- The ITCH parser read the Stock Directory (`R`) symbol from the tracking-number + and timestamp bytes. `ItchMessage::StockDirectory` now carries the real symbol + (ITCH 5.0 offset 11). Found by mutation testing. - The OCaml reference oracle mishandled a cancel after a partial fill and could hang on corpus case 21; CI now has a 60 s timeout per corpus case. @@ -91,6 +109,17 @@ tests, fuzzing or mutation testing. ### Security +- **No `unsafe` code in the Rust crates.** The one `unsafe` block (`Symbol::as_str`) + now uses a checked UTF-8 conversion of at most 8 bytes, and `nanobook`, + `nanobook-broker`, `nanobook-risk` and `nanobook-rebalancer` start with + `#![forbid(unsafe_code)]`. +- **Security policy and public rating.** `SECURITY.md` explains private reporting + (GitHub private vulnerability reporting is enabled), supported versions, and every + supply-chain check with where to verify it. An OpenSSF Scorecard workflow publishes + the repository's security rating weekly. +- **Verifiable release binaries.** GitHub Releases now carry a `SHA256SUMS` file and a + signed build-provenance attestation for every `lob` binary + (`gh attestation verify --repo BoringQuantSystems/nanobook`). - **Dependency updates for RustSec advisories.** The lock file now pins rustix 1.1.6 (RUSTSEC-2026-0486; only in tests, through tempfile) and quinn-udp 0.5.16 (RUSTSEC-2026-0538; only in nanobook-broker built with the `binance` feature). From f3c3d68c03ba87bb31f4dd08fb79242146e41a03 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 12:57:23 +0100 Subject: [PATCH 13/66] fix(rebalancer): six order-safety bugs, and tests for every mutation gap Bugs, each with a test that failed on the old code: - orders closing a dropped position were priced on the passive side of mid (close long now sells at mid - offset, close short buys at mid + offset, as all other orders); - kill-switch and confirmation-prompt failures exited 0; Error::Aborted now exits 3 (exit_code(), documented in the CLI help and README); - recovery and kill read the audit log's dollar limit as cents (160.25 became 160); it is converted with rounding; - the runner never wrote its PID file, so 'rebalancer kill' could not find it; run_with_client writes it and removes it on exit; - a zero or negative quote produced a close order with limit 0; it is now skipped with a warning; - reconcile_order_intent took the first open order with quantity left; it now requires the remaining quantity to match (the broker status carries no symbol or side). Tests cover all 31 gap groups from the cargo-mutants triage, plus a run_with_client seam (injectable broker and confirmation) so --force, yes, no, prompt failure and shutdown are tested without a network. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- rebalancer/README.md | 27 ++ rebalancer/src/audit.rs | 44 ++ rebalancer/src/clock_skew.rs | 22 + rebalancer/src/config.rs | 68 +++ rebalancer/src/diff.rs | 259 ++++++++++- rebalancer/src/error.rs | 29 ++ rebalancer/src/execution.rs | 159 ++++++- rebalancer/src/kill.rs | 198 ++++++++- rebalancer/src/main.rs | 5 +- rebalancer/src/pid_file.rs | 27 +- rebalancer/src/reconcile.rs | 57 +++ rebalancer/src/recovery.rs | 422 +++++++++++++++++- rebalancer/src/risk.rs | 123 ++++++ rebalancer/src/target.rs | 56 +++ rebalancer/src/validator.rs | 41 +- rebalancer/tests/audit_writers.rs | 242 +++++++++++ rebalancer/tests/cli_smoke.rs | 60 +++ rebalancer/tests/entry_points.rs | 103 +++++ rebalancer/tests/fetch_wrappers.rs | 283 +++++++++++++ rebalancer/tests/recovery_integration.rs | 361 ++++++++++++++++ rebalancer/tests/run_orchestration.rs | 448 ++++++++++++++++++++ rebalancer/tests/write_ahead_integration.rs | 15 +- 22 files changed, 3000 insertions(+), 49 deletions(-) create mode 100644 rebalancer/tests/audit_writers.rs create mode 100644 rebalancer/tests/cli_smoke.rs create mode 100644 rebalancer/tests/entry_points.rs create mode 100644 rebalancer/tests/fetch_wrappers.rs create mode 100644 rebalancer/tests/run_orchestration.rs diff --git a/rebalancer/README.md b/rebalancer/README.md index d1bbd0e..060bc50 100644 --- a/rebalancer/README.md +++ b/rebalancer/README.md @@ -43,6 +43,33 @@ selects another file. `config.toml.example` in this crate lists every setting: connection, account, order pacing, risk limits, costs and logging. Port 4002 is the IB Gateway paper-trading account. +## Exit codes + +- `0` — success +- `1` — general error (config, connection, order, and the rest) +- `2` — a pre-trade risk check failed +- `3` — aborted: kill-switch failure, or the confirmation prompt could not run + +`rebalancer kill` exits 3 when the PID file is missing, the process does not +exit in time, or dangling orders remain. + +## PID file + +`rebalancer run` writes `rebalancer.pid` in the working directory when it starts +and removes that file when it exits, including after an error. `rebalancer kill` +reads the PID from that file. + +## Limit prices + +A buy, including covering a short, is limited at mid plus the offset in +`limit_offset_bps`. A sell, including closing a long, is limited at mid minus +the offset. A close with a quote price of 0 or less is skipped. + +## Audit money fields + +`limit`, `avg_cost` and `equity` in the audit JSONL are dollars. Recovery and +kill convert them back to cents with rounding (`160.25` → `16025`). + ## target.json ```json diff --git a/rebalancer/src/audit.rs b/rebalancer/src/audit.rs index 7cabda7..8a06cb0 100644 --- a/rebalancer/src/audit.rs +++ b/rebalancer/src/audit.rs @@ -3011,4 +3011,48 @@ mod tests { let mut log = AuditLog::open_in(&path, dir.path()).unwrap(); assert!(log.validate_checkpoints().is_ok()); } + + #[test] + fn max_checkpoint_sequence_missing_file_is_zero() { + let dir = tempfile::tempdir().unwrap(); + assert_eq!( + max_checkpoint_sequence(&dir.path().join("missing.jsonl")).unwrap(), + 0 + ); + assert!(max_checkpoint_sequence(dir.path()).is_err()); + } + + #[cfg(feature = "write_ahead_logging")] + #[test] + fn cancel_result_must_follow_cancel_intent() { + let ok = parse_audit_events_from_str( + r#"{"event":"run_started","ts":"2026-01-01T00:00:00Z","sequence_number":1,"checkpoint":"RunStarted"} +{"event":"positions_intent","ts":"2026-01-01T00:00:00Z","sequence_number":2,"checkpoint":"PositionsIntent"} +{"event":"positions_result","ts":"2026-01-01T00:00:00Z","sequence_number":3,"checkpoint":"PositionsResult"} +{"event":"diff_computed","ts":"2026-01-01T00:00:00Z","sequence_number":4,"checkpoint":"DiffComputed","orders":[]} +{"event":"cancel_intent","ts":"2026-01-01T00:00:00Z","sequence_number":5,"checkpoint":"CancelIntent"} +{"event":"cancel_result","ts":"2026-01-01T00:00:00Z","sequence_number":6,"checkpoint":"CancelResult"} +"#, + ) + .unwrap(); + assert!(validate_checkpoints_from_parsed(&ok).is_ok()); + + let swapped = parse_audit_events_from_str( + r#"{"event":"run_started","ts":"2026-01-01T00:00:00Z","sequence_number":1,"checkpoint":"RunStarted"} +{"event":"positions_intent","ts":"2026-01-01T00:00:00Z","sequence_number":2,"checkpoint":"PositionsIntent"} +{"event":"positions_result","ts":"2026-01-01T00:00:00Z","sequence_number":3,"checkpoint":"PositionsResult"} +{"event":"diff_computed","ts":"2026-01-01T00:00:00Z","sequence_number":4,"checkpoint":"DiffComputed","orders":[]} +{"event":"cancel_result","ts":"2026-01-01T00:00:00Z","sequence_number":5,"checkpoint":"CancelResult"} +{"event":"cancel_intent","ts":"2026-01-01T00:00:00Z","sequence_number":6,"checkpoint":"CancelIntent"} +"#, + ) + .unwrap(); + let err = validate_checkpoints_from_parsed(&swapped).unwrap_err(); + match err { + Error::AuditValidation(m) => { + assert!(m.contains("CancelResult must come after CancelIntent")); + } + other => panic!("expected AuditValidation, got {other:?}"), + } + } } diff --git a/rebalancer/src/clock_skew.rs b/rebalancer/src/clock_skew.rs index 65ea640..4dc493b 100644 --- a/rebalancer/src/clock_skew.rs +++ b/rebalancer/src/clock_skew.rs @@ -250,4 +250,26 @@ mod tests { other => panic!("Expected BackwardJump, got {:?}", other), } } + + #[test] + fn boundary_equal_to_thresholds_is_ok() { + let ts1 = Utc::now(); + let mut backward = ClockSkewDetector::with_thresholds(30, 2.0); + backward.check(ts1); + assert_eq!(backward.check(ts1 - Duration::seconds(30)), SkewResult::Ok); + + let mut forward_rate = ClockSkewDetector::with_thresholds(30, 0.5); + forward_rate.check(ts1); + assert_eq!( + forward_rate.check(ts1 + Duration::seconds(30)), + SkewResult::Ok + ); + + let mut equal_rate = ClockSkewDetector::with_thresholds(30, 2.0); + equal_rate.check(ts1); + assert_eq!( + equal_rate.check(ts1 + Duration::seconds(60)), + SkewResult::Ok + ); + } } diff --git a/rebalancer/src/config.rs b/rebalancer/src/config.rs index f4b6993..c1267fc 100644 --- a/rebalancer/src/config.rs +++ b/rebalancer/src/config.rs @@ -400,4 +400,72 @@ max_jump_rate_sec_per_sec = 2.0 let config: Config = toml::from_str(&toml).unwrap(); assert_eq!(config.account.account_type, AccountType::Cash); } + + #[test] + fn omitted_keys_use_documented_defaults() { + let config: Config = toml::from_str( + r#" +[connection] +host = "127.0.0.1" +port = 4002 +client_id = 1 +[account] +id = "DU1" +type = "cash" +[execution] +[risk] +[cost] +[logging] +"#, + ) + .unwrap(); + assert_eq!(config.connection.timeout_secs, 30); + assert_eq!(config.execution.order_interval_ms, 100); + assert_eq!(config.execution.limit_offset_bps, 5); + assert_eq!(config.execution.order_timeout_secs, 300); + assert_eq!(config.execution.max_orders_per_run, 50); + assert_eq!(config.execution.quote_staleness_threshold_sec, 30); + assert_eq!(config.risk.max_position_pct, 0.25); + assert_eq!(config.risk.max_leverage, 1.5); + assert_eq!(config.risk.min_trade_usd, 100.0); + assert_eq!(config.risk.max_trade_usd, 100_000.0); + assert!(config.risk.allow_short); + assert_eq!(config.risk.max_short_pct, 0.30); + assert_eq!(config.cost.commission_per_share, 0.0035); + assert_eq!(config.cost.commission_min, 0.35); + assert_eq!(config.cost.slippage_bps, 5); + assert_eq!(config.logging.dir, "./logs"); + assert_eq!(config.logging.audit_file, "audit.jsonl"); + assert_eq!(config.logging.clock_skew_threshold_sec, 30); + assert_eq!(config.logging.max_jump_rate_sec_per_sec, 2.0); + assert_eq!(config.kill.timeout_secs, 30); + assert!(config.validate().is_ok()); + let risk = RiskConfig::default(); + assert_eq!(risk.max_position_pct, 0.25); + assert_eq!(risk.max_leverage, 1.5); + assert_eq!(risk.min_trade_usd, 100.0); + assert_eq!(risk.max_trade_usd, 100_000.0); + assert!(risk.allow_short); + assert_eq!(risk.max_short_pct, 0.30); + } + + #[test] + fn validate_boundary_values() { + let mut config: Config = toml::from_str(example_toml()).unwrap(); + config.risk.max_position_pct = 1.0; + assert!(config.validate().is_ok()); + config.risk.min_trade_usd = 0.0; + assert!(config.validate().is_ok()); + config.risk.min_trade_usd = -0.01; + assert!(config.validate().is_err()); + config.risk.min_trade_usd = 0.0; + config.risk.max_short_pct = 0.0; + assert!(config.validate().is_ok()); + config.risk.max_short_pct = 1.0; + assert!(config.validate().is_ok()); + config.risk.max_short_pct = -0.01; + assert!(config.validate().is_err()); + config.risk.max_short_pct = 1.01; + assert!(config.validate().is_err()); + } } diff --git a/rebalancer/src/diff.rs b/rebalancer/src/diff.rs index bd81b8c..9896066 100644 --- a/rebalancer/src/diff.rs +++ b/rebalancer/src/diff.rs @@ -85,8 +85,17 @@ pub fn compute_diff( continue; } if let Some(&price) = price_map.get(&pos.symbol) { + if price <= 0 { + tracing::warn!( + symbol = %pos.symbol, + quantity = pos.quantity, + price, + "skip close order: quote price is not positive" + ); + continue; + } let shares = pos.quantity.abs(); - let limit = compute_limit_price(price, pos.quantity < 0, limit_offset_bps); + let limit = compute_limit_price(price, pos.quantity > 0, limit_offset_bps); let notional = shares * price; let (action, desc) = if pos.quantity > 0 { @@ -242,6 +251,77 @@ mod tests { Symbol::new("SPY") } + #[test] + fn classify_trade_table() { + assert_eq!(classify_trade(0, 5), (Action::Buy, "open")); + assert_eq!(classify_trade(0, -5), (Action::SellShort, "open short")); + assert_eq!(classify_trade(4, 5), (Action::Buy, "increase")); + assert_eq!(classify_trade(4, -3), (Action::Sell, "decrease")); + assert_eq!(classify_trade(4, -4), (Action::Sell, "decrease")); + assert_eq!(classify_trade(4, -6), (Action::Sell, "flip to short")); + assert_eq!(classify_trade(-4, 3), (Action::BuyCover, "decrease short")); + assert_eq!(classify_trade(-4, 4), (Action::BuyCover, "decrease short")); + assert_eq!(classify_trade(-4, 6), (Action::BuyCover, "flip to long")); + assert_eq!( + classify_trade(-4, -3), + (Action::SellShort, "increase short") + ); + } + + #[test] + fn compute_diff_classify_end_to_end() { + let decrease = compute_diff( + 100_000_000, + &[CurrentPosition { + symbol: aapl(), + quantity: 4000, + avg_cost_cents: 10_000, + }], + &[(aapl(), 0.25)], + &[(aapl(), 10_000)], + 0, + 0, + ); + assert_eq!(decrease.len(), 1); + assert_eq!(decrease[0].action, Action::Sell); + assert_eq!(decrease[0].shares, 1500); + assert_eq!(decrease[0].description, "decrease"); + + let flip_short = compute_diff( + 100_000_000, + &[CurrentPosition { + symbol: aapl(), + quantity: 1000, + avg_cost_cents: 10_000, + }], + &[(aapl(), -0.25)], + &[(aapl(), 10_000)], + 0, + 0, + ); + assert_eq!(flip_short.len(), 1); + assert_eq!(flip_short[0].action, Action::Sell); + assert_eq!(flip_short[0].shares, 3500); + assert_eq!(flip_short[0].description, "flip to short"); + + let flip_long = compute_diff( + 100_000_000, + &[CurrentPosition { + symbol: aapl(), + quantity: -1000, + avg_cost_cents: 10_000, + }], + &[(aapl(), 0.25)], + &[(aapl(), 10_000)], + 0, + 0, + ); + assert_eq!(flip_long.len(), 1); + assert_eq!(flip_long[0].action, Action::BuyCover); + assert_eq!(flip_long[0].shares, 3500); + assert_eq!(flip_long[0].description, "flip to long"); + } + #[test] fn basic_buy() { let orders = compute_diff( @@ -404,4 +484,181 @@ mod tests { assert_eq!(orders[0].shares, 100); assert_eq!(orders[0].description, "close short"); } + + #[test] + fn close_long_limit_is_mid_minus_offset() { + let orders = compute_diff( + 100_000_000, + &[CurrentPosition { + symbol: msft(), + quantity: 200, + avg_cost_cents: 40_000, + }], + &[(aapl(), 0.5)], + &[(aapl(), 18_500), (msft(), 41_000)], + 10, + 0, + ); + let close = orders.iter().find(|o| o.symbol == msft()).unwrap(); + assert_eq!(close.action, Action::Sell); + assert_eq!(close.shares, 200); + assert_eq!(close.description, "close long"); + assert_eq!(close.limit_price_cents, 40_959); + assert_eq!(close.notional_cents, 8_200_000); + } + + #[test] + fn close_short_limit_is_mid_plus_offset() { + let orders = compute_diff( + 100_000_000, + &[CurrentPosition { + symbol: spy(), + quantity: -100, + avg_cost_cents: 43_000, + }], + &[], + &[(spy(), 43_000)], + 10, + 0, + ); + assert_eq!(orders.len(), 1); + assert_eq!(orders[0].action, Action::BuyCover); + assert_eq!(orders[0].shares, 100); + assert_eq!(orders[0].description, "close short"); + assert_eq!(orders[0].limit_price_cents, 43_043); + assert_eq!(orders[0].notional_cents, 4_300_000); + } + + #[test] + fn close_skips_non_positive_quote() { + let orders = compute_diff( + 100_000_000, + &[CurrentPosition { + symbol: msft(), + quantity: 200, + avg_cost_cents: 40_000, + }], + &[(aapl(), 0.5)], + &[(aapl(), 18_500), (msft(), 0)], + 0, + 0, + ); + assert!(orders.iter().all(|o| o.symbol != msft())); + } + + #[test] + fn close_notional_with_zero_offset() { + let orders = compute_diff( + 100_000_000, + &[CurrentPosition { + symbol: msft(), + quantity: 200, + avg_cost_cents: 40_000, + }], + &[(aapl(), 0.5)], + &[(aapl(), 18_500), (msft(), 41_000)], + 0, + 0, + ); + let close = orders.iter().find(|o| o.symbol == msft()).unwrap(); + assert_eq!(close.notional_cents, 8_200_000); + assert_eq!(close.shares, 200); + } + + #[test] + fn compute_diff_skips_non_positive_rebalance_price() { + let orders = compute_diff( + 100_000_000, + &[], + &[(aapl(), 0.5), (msft(), 0.25)], + &[(aapl(), 0), (msft(), -100)], + 0, + 0, + ); + assert!(orders.is_empty()); + } + + #[test] + fn min_trade_filter_at_exact_notional() { + let at_min = compute_diff( + 1_048_576, + &[], + &[(aapl(), 0.015625)], + &[(aapl(), 8192)], + 0, + 16_384, + ); + assert_eq!(at_min.len(), 1); + assert_eq!(at_min[0].action, Action::Buy); + assert_eq!(at_min[0].shares, 2); + assert_eq!(at_min[0].description, "open"); + assert_eq!(at_min[0].notional_cents, 16_384); + + let below = compute_diff( + 1_048_576, + &[], + &[(aapl(), 0.015625)], + &[(aapl(), 8192)], + 0, + 16_385, + ); + assert!(below.is_empty()); + } + + #[test] + fn sell_limit_is_mid_minus_offset() { + let orders = compute_diff( + 100_000_000, + &[CurrentPosition { + symbol: aapl(), + quantity: 4000, + avg_cost_cents: 10_000, + }], + &[(aapl(), 0.25), (msft(), 0.25)], + &[(aapl(), 10_000), (msft(), 20_000)], + 10, + 0, + ); + let aapl_order = orders.iter().find(|o| o.symbol == aapl()).unwrap(); + assert_eq!(aapl_order.action, Action::Sell); + assert_eq!(aapl_order.shares, 1500); + assert_eq!(aapl_order.description, "decrease"); + assert_eq!(aapl_order.limit_price_cents, 9_990); + assert_eq!(aapl_order.notional_cents, 15_000_000); + let msft_order = orders.iter().find(|o| o.symbol == msft()).unwrap(); + assert_eq!(msft_order.action, Action::Buy); + assert_eq!(msft_order.shares, 1250); + assert_eq!(msft_order.description, "open"); + assert_eq!(msft_order.limit_price_cents, 20_020); + } + + #[test] + fn estimate_cost_commission_and_slippage() { + let orders = [ + RebalanceOrder { + symbol: aapl(), + action: Action::Buy, + shares: 1000, + limit_price_cents: 20_000, + notional_cents: 20_000_000, + description: "open", + }, + RebalanceOrder { + symbol: msft(), + action: Action::Buy, + shares: 2, + limit_price_cents: 20_000, + notional_cents: 40_000, + description: "open", + }, + ]; + let cost = estimate_cost(&orders, 0.5, 2.0, 10); + assert_eq!(cost.commission_cents, 50_200); + assert_eq!(cost.slippage_cents, 20_040); + assert_eq!(cost.total_cents(), 70_240); + assert_eq!( + format!("{cost}"), + "$502.00 commission + $200.40 slippage = $702.40" + ); + } } diff --git a/rebalancer/src/error.rs b/rebalancer/src/error.rs index 867cc87..d9b9915 100644 --- a/rebalancer/src/error.rs +++ b/rebalancer/src/error.rs @@ -80,4 +80,33 @@ pub enum Error { Recovery(String), } +/// Return the process exit code for this error. +pub fn exit_code(error: &Error) -> i32 { + match error { + Error::RiskFailed(_) => 2, + Error::Aborted(_) => 3, + _ => 1, + } +} + pub type Result = std::result::Result; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn exit_code_maps_risk_failed_to_2() { + assert_eq!(exit_code(&Error::RiskFailed("x".into())), 2); + } + + #[test] + fn exit_code_maps_config_to_1() { + assert_eq!(exit_code(&Error::Config("x".into())), 1); + } + + #[test] + fn exit_code_maps_aborted_to_3() { + assert_eq!(exit_code(&Error::Aborted("x".into())), 3); + } +} diff --git a/rebalancer/src/execution.rs b/rebalancer/src/execution.rs index 7b898b3..c546c8c 100644 --- a/rebalancer/src/execution.rs +++ b/rebalancer/src/execution.rs @@ -2,6 +2,7 @@ //! //! This is the main workflow that ties together all components. +use std::path::{Path, PathBuf}; use std::sync::{ Arc, atomic::{AtomicBool, Ordering}, @@ -227,10 +228,52 @@ pub fn run(config: &Config, target: &TargetSpec, opts: &RunOptions) -> Result<() connect_ibkr(config)? }; + let workdir = std::env::current_dir()?; + run_with_client( + config, + target, + opts, + client.as_ref(), + &shutdown, + &workdir, + &mut prompt_yes_no, + ) +} + +fn prompt_yes_no() -> Result { + dialoguer::Confirm::new() + .with_prompt("Execute?") + .default(false) + .interact() + .map_err(|e| Error::Aborted(format!("confirmation prompt failed: {e}"))) +} + +fn resolve_audit_path(config: &Config, workdir: &Path) -> PathBuf { + let path = config.audit_path(); + if path.is_absolute() { + path + } else { + workdir.join(path) + } +} + +/// Run steps 2 to 13 with an injected broker and confirmation callback. +pub fn run_with_client( + config: &Config, + target: &TargetSpec, + opts: &RunOptions, + client: &dyn BrokerGateway, + shutdown: &ShutdownFlag, + workdir: &Path, + confirm: &mut dyn FnMut() -> Result, +) -> Result<()> { + let _pid_guard = + crate::pid_file::PidFileGuard::create(workdir.join(crate::pid_file::DEFAULT_PID_FILE))?; + // 2. Open audit log - let audit_path = config.audit_path(); + let audit_path = resolve_audit_path(config, workdir); let existing_checkpoint_sequence = audit::max_checkpoint_sequence(&audit_path)?; - let mut audit = AuditLog::open(&audit_path)?; + let mut audit = AuditLog::open_in(&audit_path, workdir)?; let run_sequence_number = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_err(|e| Error::Config(format!("clock error: {e}")))? @@ -263,7 +306,7 @@ pub fn run(config: &Config, target: &TargetSpec, opts: &RunOptions) -> Result<() let _span = tracing::info_span!("fetch_account_summary", account = %config.account.id).entered(); fetch_account_summary_with_write_ahead( - client.as_ref(), + client, &mut audit, &mut checkpoint_sequence, &target_spec_ref, @@ -282,7 +325,7 @@ pub fn run(config: &Config, target: &TargetSpec, opts: &RunOptions) -> Result<() let _span = tracing::info_span!("fetch_positions", equity_cents = summary.equity_cents).entered(); fetch_positions_with_write_ahead( - client.as_ref(), + client, &mut audit, &mut checkpoint_sequence, &target_spec_ref, @@ -309,7 +352,7 @@ pub fn run(config: &Config, target: &TargetSpec, opts: &RunOptions) -> Result<() let quotes = { let _span = tracing::info_span!("fetch_quotes", symbol_count = all_symbols.len()).entered(); fetch_quotes_with_write_ahead( - client.as_ref(), + client, &mut audit, &mut checkpoint_sequence, &target_spec_ref, @@ -426,11 +469,7 @@ pub fn run(config: &Config, target: &TargetSpec, opts: &RunOptions) -> Result<() // 10. Confirm execution if !opts.force { - let confirmed = dialoguer::Confirm::new() - .with_prompt("Execute?") - .default(false) - .interact() - .map_err(|e| Error::Aborted(format!("confirmation prompt failed: {e}")))?; + let confirmed = confirm()?; if !confirmed { println!("Aborted."); @@ -494,7 +533,7 @@ pub fn run(config: &Config, target: &TargetSpec, opts: &RunOptions) -> Result<() let order_sequence = next_checkpoint_sequence(&mut checkpoint_sequence); let execution_result = execute_order_with_write_ahead( - client.as_ref(), + client, &mut audit, order, &client_order_id, @@ -557,7 +596,7 @@ pub fn run(config: &Config, target: &TargetSpec, opts: &RunOptions) -> Result<() let mut cancelled = remaining_orders_after(i, orders.len()); if let Some(order_id) = current_order_to_cancel { cancel_order_with_write_ahead( - client.as_ref(), + client, &mut audit, &mut checkpoint_sequence, u64::try_from(order_id).unwrap_or_default(), @@ -591,7 +630,7 @@ pub fn run(config: &Config, target: &TargetSpec, opts: &RunOptions) -> Result<() let _reconcile_span = tracing::info_span!("reconcile", submitted, filled, failed).entered(); info!("Running post-execution reconciliation..."); let final_broker_positions = fetch_positions_with_write_ahead( - client.as_ref(), + client, &mut audit, &mut checkpoint_sequence, &target_spec_ref, @@ -601,7 +640,7 @@ pub fn run(config: &Config, target: &TargetSpec, opts: &RunOptions) -> Result<() // Fetch final quotes and extract mid prices let final_quotes = fetch_quotes_with_write_ahead( - client.as_ref(), + client, &mut audit, &mut checkpoint_sequence, &target_spec_ref, @@ -611,7 +650,7 @@ pub fn run(config: &Config, target: &TargetSpec, opts: &RunOptions) -> Result<() let final_prices = quote_mid_prices(&final_quotes); let final_summary = fetch_account_summary_with_write_ahead( - client.as_ref(), + client, &mut audit, &mut checkpoint_sequence, &target_spec_ref, @@ -651,7 +690,7 @@ pub fn run(config: &Config, target: &TargetSpec, opts: &RunOptions) -> Result<() println!( "\n{submitted} submitted, {filled} filled, {failed} failed. Audit logged to {}", - config.audit_path().display() + audit_path.display() ); Ok(()) @@ -1304,4 +1343,92 @@ mod tests { assert!(enforce_max_orders_per_run(3, 5).is_ok()); assert!(enforce_max_orders_per_run(10, 5).is_err()); } + + fn quote(symbol: &str, bid: i64, ask: i64, last: i64) -> Quote { + Quote { + symbol: Symbol::new(symbol), + bid_cents: bid, + ask_cents: ask, + last_cents: last, + volume: 0, + timestamp: std::time::SystemTime::now(), + } + } + + #[test] + fn quote_mid_cents_uses_bid_ask_then_sides_then_last() { + assert_eq!( + quote_mid_cents("e("AAPL", 10_000, 10_004, 9_000)), + 10_002 + ); + assert_eq!(quote_mid_cents("e("AAPL", 10_000, 0, 9_000)), 10_000); + assert_eq!(quote_mid_cents("e("AAPL", 0, 10_004, 9_000)), 10_004); + assert_eq!(quote_mid_cents("e("AAPL", 0, 0, 9_000)), 9_000); + } + + #[test] + fn quote_mid_prices_preserves_input_order() { + let q1 = quote("AAPL", 10_000, 10_004, 9_000); + let q2 = quote("MSFT", 39_990, 40_010, 40_000); + let prices = quote_mid_prices(&[q1, q2]); + assert_eq!( + prices, + vec![(Symbol::new("AAPL"), 10_002), (Symbol::new("MSFT"), 40_000)] + ); + } + + #[test] + #[cfg(unix)] + fn sigterm_sets_shutdown_flag() { + let flag = ShutdownFlag::new(); + flag.install_sigterm_handler().unwrap(); + assert!(!flag.is_requested()); + signal_hook::low_level::raise(signal_hook::consts::SIGTERM).unwrap(); + let start = std::time::Instant::now(); + while !flag.is_requested() && start.elapsed() < Duration::from_secs(2) { + std::thread::sleep(Duration::from_millis(10)); + } + assert!(flag.is_requested()); + } + + #[test] + fn enforce_max_orders_equal_limit_is_ok() { + assert!(enforce_max_orders_per_run(5, 5).is_ok()); + let err = enforce_max_orders_per_run(6, 5).unwrap_err(); + match err { + Error::RiskFailed(m) => { + assert_eq!(m, "6 orders generated, but max_orders_per_run is 5"); + } + other => panic!("expected RiskFailed, got {other:?}"), + } + } + + #[test] + fn to_current_positions_copies_symbol_qty_and_avg_cost() { + let input = vec![ + Position { + symbol: Symbol::new("AAPL"), + quantity: 100, + avg_cost_cents: 15_025, + market_value_cents: 0, + unrealized_pnl_cents: 0, + }, + Position { + symbol: Symbol::new("MSFT"), + quantity: -30, + avg_cost_cents: 40_000, + market_value_cents: 0, + unrealized_pnl_cents: 0, + }, + ]; + let out = to_current_positions(&input); + assert_eq!(out.len(), 2); + assert_eq!(out[0].symbol, Symbol::new("AAPL")); + assert_eq!(out[0].quantity, 100); + assert_eq!(out[0].avg_cost_cents, 15_025); + assert_eq!(out[1].symbol, Symbol::new("MSFT")); + assert_eq!(out[1].quantity, -30); + assert_eq!(out[1].avg_cost_cents, 40_000); + assert!(to_current_positions(&[]).is_empty()); + } } diff --git a/rebalancer/src/kill.rs b/rebalancer/src/kill.rs index 320538d..5b20f54 100644 --- a/rebalancer/src/kill.rs +++ b/rebalancer/src/kill.rs @@ -58,7 +58,7 @@ use crate::pid_file::{self, pid_file_exists, read_pid_file}; use nanobook_broker::Broker; #[cfg(feature = "guaranteed_kill_switch")] use nanobook_broker::ibkr::IbkrBroker; -use nanobook_broker::types::{BrokerOrderStatus, OrderState}; +use nanobook_broker::types::{BrokerOrderStatus, OrderState, f64_cents_checked}; use serde_json::Value; use std::path::Path; use std::thread; @@ -128,7 +128,9 @@ pub fn verify_no_dangling_orders(audit_path: &Path) -> Result .unwrap_or("unknown") .to_string(); let shares = event.get("shares").and_then(|s| s.as_i64()).unwrap_or(0); - let limit = event.get("limit").and_then(|l| l.as_f64()).unwrap_or(0.0) as i64; + let limit_dollars = event.get("limit").and_then(|l| l.as_f64()).unwrap_or(0.0); + let limit = f64_cents_checked(limit_dollars, "limit") + .unwrap_or_else(|_| (limit_dollars * 100.0).round() as i64); // Parse timestamp let ts_str = event.get("ts").and_then(|t| t.as_str()).unwrap_or(""); @@ -563,7 +565,7 @@ where } } -#[cfg(not(feature = "guaranteed_kill_switch"))] +#[cfg_attr(feature = "guaranteed_kill_switch", allow(dead_code))] fn run_graceful_kill(config: &Config, timeout: Duration) -> Result<()> { let pid_path = Path::new(pid_file::DEFAULT_PID_FILE); let audit_path = config.audit_path(); @@ -640,7 +642,6 @@ mod tests { Account, BrokerOrder, BrokerOrderStatus, OrderId, OrderState, Position, Quote, }; use std::cell::{Cell, RefCell}; - #[cfg(feature = "guaranteed_kill_switch")] use std::sync::{Mutex, OnceLock}; use std::time::SystemTime; use tempfile::NamedTempFile; @@ -766,7 +767,6 @@ mod tests { assert_eq!(active_kill_workflow(), KillWorkflow::TwoPhase); } - #[cfg(feature = "guaranteed_kill_switch")] fn process_state_lock() -> &'static Mutex<()> { static LOCK: OnceLock> = OnceLock::new(); LOCK.get_or_init(|| Mutex::new(())) @@ -1309,4 +1309,192 @@ timeout_secs = {timeout_secs} assert!(symbols.contains(&"AAPL")); assert!(symbols.contains(&"MSFT")); } + + #[test] + fn kill_timeout_cli_overrides_config() { + let config = test_config_with_kill_timeout(17); + assert_eq!( + kill_timeout_from_sources(&config, Some(23)), + Duration::from_secs(23) + ); + } + + #[test] + #[cfg(unix)] + fn wait_for_live_process_times_out() { + let mut child = std::process::Command::new("sleep") + .arg("30") + .spawn() + .unwrap(); + let result = wait_for_process_exit(child.id(), Duration::from_millis(100)); + let _ = child.kill(); + let _ = child.wait(); + assert!(!result.unwrap()); + } + + #[test] + #[cfg(unix)] + fn wait_for_reaped_process_reports_exited() { + let mut child = std::process::Command::new("sleep") + .arg("1") + .spawn() + .unwrap(); + let pid = child.id(); + let handle = std::thread::spawn(move || { + let _ = child.wait(); + }); + let result = wait_for_process_exit(pid, Duration::from_secs(10)); + handle.join().unwrap(); + assert!(result.unwrap()); + } + + #[test] + fn forceful_cancel_sleeps_between_failed_attempts_only() { + let broker = TestBroker::with_orders(&[1]); + broker.fail_cancel.set(true); + let mut sleeps = Vec::new(); + let report = forceful_cancel_open_orders_with_retry(&broker, 2, |a| sleeps.push(a)); + assert_eq!(report.attempts, 3); + assert_eq!(sleeps, vec![0, 1]); + assert_eq!(report.remaining_order_ids, vec![1]); + assert_eq!(report.errors.len(), 3); + assert!(!report.succeeded()); + } + + struct CwdGuard(std::path::PathBuf); + impl Drop for CwdGuard { + fn drop(&mut self) { + let _ = std::env::set_current_dir(&self.0); + } + } + + #[test] + fn run_kill_without_pid_file_is_aborted() { + let _lock = match process_state_lock().lock() { + Ok(guard) => guard, + Err(poisoned) => poisoned.into_inner(), + }; + let dir = tempfile::tempdir().unwrap(); + let _cwd = CwdGuard(std::env::current_dir().unwrap()); + std::env::set_current_dir(dir.path()).unwrap(); + let mut config = test_config_with_kill_timeout(30); + config.logging.dir = dir.path().join("logs").display().to_string(); + let err = run_kill(&config).unwrap_err(); + match err { + Error::Aborted(m) => assert!(m.contains("PID file not found")), + other => panic!("expected Aborted, got {other:?}"), + } + } + + #[test] + #[cfg(unix)] + fn graceful_kill_clean_exit() { + let _lock = match process_state_lock().lock() { + Ok(guard) => guard, + Err(poisoned) => poisoned.into_inner(), + }; + let dir = tempfile::tempdir().unwrap(); + let _cwd = CwdGuard(std::env::current_dir().unwrap()); + std::env::set_current_dir(dir.path()).unwrap(); + let mut config = test_config_with_kill_timeout(30); + config.logging.dir = dir.path().join("logs").display().to_string(); + let mut child = std::process::Command::new("sleep") + .arg("30") + .spawn() + .unwrap(); + std::fs::write("rebalancer.pid", child.id().to_string()).unwrap(); + let handle = std::thread::spawn(move || { + let _ = child.wait(); + }); + run_graceful_kill(&config, Duration::from_secs(10)).unwrap(); + handle.join().unwrap(); + let events = crate::audit::parse_audit_events(&config.audit_path()).unwrap(); + let completed = events.iter().find(|e| e.event == "kill_completed").unwrap(); + assert_eq!( + completed.data.get("method").and_then(|v| v.as_str()), + Some("graceful") + ); + assert_eq!( + completed + .data + .get("orders_remaining_count") + .and_then(|v| v.as_u64()), + Some(0) + ); + } + + #[test] + #[cfg(unix)] + fn graceful_kill_dangling_orders() { + let _lock = match process_state_lock().lock() { + Ok(guard) => guard, + Err(poisoned) => poisoned.into_inner(), + }; + let dir = tempfile::tempdir().unwrap(); + let _cwd = CwdGuard(std::env::current_dir().unwrap()); + std::env::set_current_dir(dir.path()).unwrap(); + let mut config = test_config_with_kill_timeout(30); + let logs = dir.path().join("logs"); + std::fs::create_dir_all(&logs).unwrap(); + config.logging.dir = logs.display().to_string(); + std::fs::write( + logs.join("audit.jsonl"), + r#"{"event":"order_submitted","ts":"2024-01-01T00:00:00Z","symbol":"AAPL","action":"Buy","shares":100,"limit":150.00,"ibkr_id":1} +"#, + ) + .unwrap(); + let mut child = std::process::Command::new("sleep") + .arg("30") + .spawn() + .unwrap(); + std::fs::write("rebalancer.pid", child.id().to_string()).unwrap(); + let handle = std::thread::spawn(move || { + let _ = child.wait(); + }); + let err = run_graceful_kill(&config, Duration::from_secs(10)).unwrap_err(); + handle.join().unwrap(); + match err { + Error::Aborted(m) => assert!(m.contains("dangling orders")), + other => panic!("expected Aborted, got {other:?}"), + } + } + + #[test] + #[cfg(unix)] + fn graceful_kill_timeout() { + let _lock = match process_state_lock().lock() { + Ok(guard) => guard, + Err(poisoned) => poisoned.into_inner(), + }; + let dir = tempfile::tempdir().unwrap(); + let _cwd = CwdGuard(std::env::current_dir().unwrap()); + std::env::set_current_dir(dir.path()).unwrap(); + let mut config = test_config_with_kill_timeout(30); + config.logging.dir = dir.path().join("logs").display().to_string(); + let mut child = std::process::Command::new("sh") + .args(["-c", "trap \"\" TERM; sleep 30"]) + .spawn() + .unwrap(); + std::fs::write("rebalancer.pid", child.id().to_string()).unwrap(); + let err = run_graceful_kill(&config, Duration::from_secs(1)).unwrap_err(); + let _ = child.kill(); + let _ = child.wait(); + match err { + Error::Aborted(m) => assert!(m.contains("did not exit within 1 seconds")), + other => panic!("expected Aborted, got {other:?}"), + } + } + + #[test] + fn dangling_limit_converts_dollars_to_cents() { + let temp_file = NamedTempFile::new().unwrap(); + std::fs::write( + temp_file.path(), + r#"{"event":"order_submitted","ts":"2024-01-01T00:00:00Z","symbol":"AAPL","action":"Buy","shares":100,"limit":160.25,"ibkr_id":1}"#, + ) + .unwrap(); + let dangling = verify_no_dangling_orders(temp_file.path()).unwrap(); + assert_eq!(dangling.len(), 1); + assert_eq!(dangling[0].limit_price_cents, 16_025); + } } diff --git a/rebalancer/src/main.rs b/rebalancer/src/main.rs index f1a3772..ecdedce 100644 --- a/rebalancer/src/main.rs +++ b/rebalancer/src/main.rs @@ -20,6 +20,7 @@ use nanobook_rebalancer::validator; #[command(name = "rebalancer")] #[command(about = "Portfolio rebalancer: nanobook → Interactive Brokers")] #[command(version)] +#[command(after_help = "Exit codes: 0 success. 1 general error. 2 risk check failed. 3 aborted.")] struct Cli { /// Path to config.toml #[arg(long, default_value = "config.toml")] @@ -194,16 +195,14 @@ fn main() { match &e { Error::RiskFailed(msg) => { eprintln!("\nAborted: {msg}"); - process::exit(2); } Error::Aborted(msg) => { eprintln!("{msg}"); - process::exit(0); } _ => { eprintln!("Error: {e}"); - process::exit(1); } } + process::exit(nanobook_rebalancer::error::exit_code(&e)); } } diff --git a/rebalancer/src/pid_file.rs b/rebalancer/src/pid_file.rs index 04fe772..b853ae2 100644 --- a/rebalancer/src/pid_file.rs +++ b/rebalancer/src/pid_file.rs @@ -32,7 +32,7 @@ use crate::error::{Error, Result}; use std::fs; -use std::path::Path; +use std::path::{Path, PathBuf}; /// Default PID file path. pub const DEFAULT_PID_FILE: &str = "rebalancer.pid"; @@ -77,6 +77,31 @@ pub fn remove_pid_file(path: &Path) -> Result<()> { Ok(()) } +/// Write a PID file and remove it when this guard drops. +pub struct PidFileGuard { + path: PathBuf, +} + +impl PidFileGuard { + /// Write `path` with the current process id. + pub fn create(path: PathBuf) -> Result { + write_pid_file(&path)?; + Ok(Self { path }) + } +} + +impl Drop for PidFileGuard { + fn drop(&mut self) { + if let Err(error) = remove_pid_file(&self.path) { + tracing::warn!( + path = %self.path.display(), + error = %error, + "failed to remove PID file" + ); + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/rebalancer/src/reconcile.rs b/rebalancer/src/reconcile.rs index 3cfafea..2ea3562 100644 --- a/rebalancer/src/reconcile.rs +++ b/rebalancer/src/reconcile.rs @@ -145,6 +145,63 @@ mod tests { assert!(report.tracking_error_pct < 1.0); } + #[test] + fn two_symbol_weights_and_tracking_error() { + let positions = vec![ + CurrentPosition { + symbol: aapl(), + quantity: 2000, + avg_cost_cents: 18_500, + }, + CurrentPosition { + symbol: msft(), + quantity: 100, + avg_cost_cents: 40_000, + }, + ]; + let report = reconcile( + &positions, + &[(aapl(), 0.5), (msft(), 0.125)], + &[(aapl(), 18_500), (msft(), 40_000)], + 100_000_000, + ); + let aapl_entry = report.entries.iter().find(|e| e.symbol == "AAPL").unwrap(); + assert!((aapl_entry.actual_weight - 0.37).abs() < 1e-12); + assert!((aapl_entry.diff_weight + 0.13).abs() < 1e-12); + assert_eq!(aapl_entry.target_shares, 2702); + assert_eq!(aapl_entry.diff_shares, -702); + let msft_entry = report.entries.iter().find(|e| e.symbol == "MSFT").unwrap(); + assert!((msft_entry.actual_weight - 0.04).abs() < 1e-12); + assert!((msft_entry.diff_weight + 0.085).abs() < 1e-12); + assert_eq!(msft_entry.target_shares, 312); + assert_eq!(msft_entry.diff_shares, -212); + assert!((report.tracking_error_pct - 10.982941318244398).abs() < 1e-9); + } + + #[test] + fn zero_equity_gives_zero_weight() { + let report = reconcile( + &[CurrentPosition { + symbol: aapl(), + quantity: 10, + avg_cost_cents: 18_500, + }], + &[(aapl(), 0.5)], + &[(aapl(), 18_500)], + 0, + ); + assert_eq!(report.entries[0].actual_weight, 0.0); + assert_eq!(report.entries[0].target_shares, 0); + assert_eq!(report.tracking_error_pct, 50.0); + } + + #[test] + fn missing_price_gives_zero_target_shares() { + let qqq = Symbol::new("QQQ"); + let report = reconcile(&[], &[(qqq, 0.25)], &[], 100_000_000); + assert_eq!(report.entries[0].target_shares, 0); + } + #[test] fn missing_position() { let positions = vec![]; // no positions diff --git a/rebalancer/src/recovery.rs b/rebalancer/src/recovery.rs index 36fd53c..9632f6e 100644 --- a/rebalancer/src/recovery.rs +++ b/rebalancer/src/recovery.rs @@ -302,6 +302,12 @@ pub fn compare_broker_state( }) } +/// Convert an audit `limit` dollar amount to cents. +fn audit_dollars_to_cents(limit_dollars: f64) -> i64 { + f64_cents_checked(limit_dollars, "limit") + .unwrap_or_else(|_| (limit_dollars * 100.0).round() as i64) +} + /// Query the broker for an order matching the given criteria with retry logic. /// /// This function attempts to find an order in the broker's open orders @@ -323,41 +329,59 @@ pub fn compare_broker_state( #[cfg(feature = "write_ahead_logging")] pub fn reconcile_order_intent( broker: &dyn Broker, - _symbol: &Symbol, - _quantity: i64, + symbol: &Symbol, + quantity: i64, +) -> Result> { + reconcile_order_intent_with(broker, symbol, quantity, &mut std::thread::sleep) +} + +/// Query the broker for an open order whose remaining quantity matches `quantity`. +/// +/// `BrokerOrderStatus` has no symbol or side, so remaining quantity is the +/// match key. `symbol` is recorded in the log line. +#[cfg(feature = "write_ahead_logging")] +pub fn reconcile_order_intent_with( + broker: &dyn Broker, + symbol: &Symbol, + quantity: i64, + sleep: &mut dyn FnMut(Duration), ) -> Result> { const MAX_RETRIES: usize = 5; - const BASE_DELAY_MS: u64 = 1000; // 1 second + const BASE_DELAY_MS: u64 = 1000; + + let expected_remaining = u64::try_from(quantity).unwrap_or(0); for attempt in 0..MAX_RETRIES { match broker.open_orders() { Ok(orders) => { - // Search for order with matching symbol and quantity - // Note: This is a heuristic match since broker API doesn't provide client_order_id for order in &orders { - // We can only match by order ID since BrokerOrderStatus doesn't include symbol - // In a real implementation, we would need to maintain a local order cache - // For now, we return the first open order as a best-effort match - // This is a limitation of the current broker API - if order.remaining_quantity > 0 { + if order.remaining_quantity > 0 + && order.remaining_quantity == expected_remaining + { + tracing::debug!( + symbol = %symbol, + quantity, + broker_order_id = order.id.0, + remaining = order.remaining_quantity, + "matched open order by remaining quantity" + ); return Ok(Some(order.id.0)); } } - // Order not found return Ok(None); } Err(e) => { - // Retry on network failures if attempt < MAX_RETRIES - 1 { let delay_ms = BASE_DELAY_MS * 2_u64.pow(attempt as u32); tracing::warn!( + symbol = %symbol, "Broker query failed (attempt {}/{}), retrying in {}ms: {}", attempt + 1, MAX_RETRIES, delay_ms, e ); - std::thread::sleep(Duration::from_millis(delay_ms)); + sleep(Duration::from_millis(delay_ms)); } else { return Err(Error::Recovery(format!( "Broker query failed after {} attempts: {}", @@ -368,7 +392,6 @@ pub fn reconcile_order_intent( } } - // This should never be reached, but required for type checking Err(Error::Recovery( "Unexpected error in broker reconciliation".to_string(), )) @@ -741,14 +764,13 @@ pub fn reconstruct_state( let symbol = o.get("symbol").and_then(|s| s.as_str()).unwrap_or(""); let action = o.get("action").and_then(|a| a.as_str()).unwrap_or(""); let shares = o.get("shares").and_then(|s| s.as_i64()).unwrap_or(0); - let limit = - o.get("limit").and_then(|l| l.as_f64()).unwrap_or(0.0) as i64; + let limit = o.get("limit").and_then(|l| l.as_f64()).unwrap_or(0.0); RecoveredOrder { symbol: Symbol::try_new(symbol) .unwrap_or(Symbol::try_new("UNKNOWN").unwrap()), action: action.to_string(), shares, - limit_price_cents: limit, + limit_price_cents: audit_dollars_to_cents(limit), ibkr_id: 0, client_order_id: None, submitted: false, @@ -797,7 +819,7 @@ pub fn reconstruct_state( .unwrap_or(Symbol::try_new("UNKNOWN").unwrap()), action: action.to_string(), shares, - limit_price_cents: limit as i64, + limit_price_cents: audit_dollars_to_cents(limit), ibkr_id: 0, client_order_id, submitted: false, @@ -1227,6 +1249,61 @@ mod tests { assert_eq!(action, RecoveryAction::Restart); } + #[test] + fn reconstruct_diff_limit_converts_dollars_to_cents() { + let dir = tempdir().unwrap(); + let path = dir.path().join("limit_audit.jsonl"); + let workdir = dir.path(); + { + let mut log = AuditLog::open_in(&path, workdir).unwrap(); + log.log_checkpoint( + Checkpoint::DiffComputed, + 1, + serde_json::json!({ + "orders": [{ + "symbol": "AAPL", + "action": "Buy", + "shares": 50, + "limit": 160.25, + "description": "open" + }] + }), + ) + .unwrap(); + } + let (state, _) = reconstruct_state(&path).unwrap(); + assert_eq!(state.orders.len(), 1); + assert_eq!(state.orders[0].limit_price_cents, 16_025); + } + + #[cfg(feature = "write_ahead_logging")] + #[test] + fn reconcile_order_intent_matches_quantity() { + use nanobook::Price; + use nanobook_broker::mock::{FillMode, MockBroker}; + use nanobook_broker::types::{BrokerOrder, BrokerOrderType}; + use nanobook_broker::{Broker, BrokerSide}; + + let mut broker = MockBroker::builder() + .fill_mode(FillMode::ImmediatePartial(0.5)) + .build(); + broker.connect().unwrap(); + broker + .submit_order(&BrokerOrder { + symbol: Symbol::new("AAPL"), + side: BrokerSide::Buy, + quantity: 50, + order_type: BrokerOrderType::Limit(Price(16_000)), + client_order_id: None, + }) + .unwrap(); + + let matched = reconcile_order_intent(&broker, &Symbol::new("AAPL"), 50).unwrap(); + let other = reconcile_order_intent(&broker, &Symbol::new("MSFT"), 25).unwrap(); + assert_eq!(matched, Some(1)); + assert_eq!(other, None); + } + #[test] fn reconstruct_state_with_checkpoints() { let dir = tempdir().unwrap(); @@ -2313,4 +2390,313 @@ mod tests { Some("test_client_order_123".to_string()) ); } + + #[cfg(feature = "write_ahead_logging")] + fn recovered_order( + symbol: &str, + ibkr_id: i32, + client_order_id: Option<&str>, + submitted: bool, + filled: bool, + failed: bool, + ) -> RecoveredOrder { + RecoveredOrder { + symbol: Symbol::new(symbol), + action: "Buy".into(), + shares: 50, + limit_price_cents: 16_000, + ibkr_id, + client_order_id: client_order_id.map(str::to_string), + submitted, + filled, + failed, + failure_reason: None, + } + } + + #[cfg(feature = "write_ahead_logging")] + #[test] + fn determine_recovery_action_sequence_comparisons() { + let mut state = RecoveredState::new(); + state.last_cancel_intent_sequence = Some(5); + state.last_cancel_result_sequence = Some(6); + assert_eq!(state.determine_recovery_action(), RecoveryAction::Restart); + state.last_cancel_intent_sequence = Some(7); + state.last_cancel_result_sequence = Some(6); + assert_eq!( + state.determine_recovery_action(), + RecoveryAction::ManualReview + ); + + let live = recovered_order("AAPL", 1, Some("a"), true, false, false); + let mut positions = RecoveredState::new(); + positions.orders = vec![live.clone()]; + positions.last_positions_intent_sequence = Some(5); + positions.last_positions_result_sequence = Some(6); + assert_eq!( + positions.determine_recovery_action(), + RecoveryAction::ManualReview + ); + positions.last_positions_intent_sequence = Some(7); + positions.last_positions_result_sequence = Some(6); + assert_eq!( + positions.determine_recovery_action(), + RecoveryAction::Restart + ); + + let mut quotes = RecoveredState::new(); + quotes.orders = vec![live.clone()]; + quotes.last_quotes_intent_sequence = Some(5); + quotes.last_quotes_result_sequence = Some(6); + assert_eq!( + quotes.determine_recovery_action(), + RecoveryAction::ManualReview + ); + quotes.last_quotes_intent_sequence = Some(7); + quotes.last_quotes_result_sequence = Some(6); + assert_eq!(quotes.determine_recovery_action(), RecoveryAction::Restart); + + let mut account = RecoveredState::new(); + account.orders = vec![live]; + account.last_account_summary_intent_sequence = Some(5); + account.last_account_summary_result_sequence = Some(6); + assert_eq!( + account.determine_recovery_action(), + RecoveryAction::ManualReview + ); + account.last_account_summary_intent_sequence = Some(7); + account.last_account_summary_result_sequence = Some(6); + assert_eq!(account.determine_recovery_action(), RecoveryAction::Restart); + } + + #[cfg(feature = "write_ahead_logging")] + #[test] + fn compare_broker_state_orphans_missing_and_incomplete() { + use nanobook::Price; + use nanobook_broker::mock::{FillMode, MockBroker}; + use nanobook_broker::types::{BrokerOrder, BrokerOrderType}; + use nanobook_broker::{Broker, BrokerSide}; + + let mut broker = MockBroker::builder() + .fill_mode(FillMode::ImmediatePartial(0.5)) + .build(); + broker.connect().unwrap(); + for symbol in ["AAPL", "MSFT"] { + broker + .submit_order(&BrokerOrder { + symbol: Symbol::new(symbol), + side: BrokerSide::Buy, + quantity: 50, + order_type: BrokerOrderType::Limit(Price(16_000)), + client_order_id: None, + }) + .unwrap(); + } + + let mut recovered = RecoveredState::new(); + recovered.orders = vec![ + recovered_order("AAPL", 1, Some("a"), true, false, false), + recovered_order("MSFT", 7, Some("m"), true, false, false), + recovered_order("SPY", 9, Some("s"), true, true, false), + recovered_order("QQQ", 0, Some("q"), false, false, false), + recovered_order("IWM", 0, Some("i"), false, false, true), + recovered_order("DIA", 0, None, false, false, false), + ]; + let report = compare_broker_state(&broker, &recovered).unwrap(); + assert_eq!(report.discrepancies.len(), 3); + assert!(matches!( + &report.discrepancies[0], + Discrepancy::OrphanOrder { + broker_order_id: 2, + .. + } + )); + assert!(matches!( + &report.discrepancies[1], + Discrepancy::MissingOrder { symbol, .. } if symbol == "MSFT" + )); + assert!(matches!( + &report.discrepancies[2], + Discrepancy::IncompleteIntent { symbol, .. } if symbol == "QQQ" + )); + assert!(report.has_critical_issues); + + let mut empty_broker = MockBroker::builder() + .fill_mode(FillMode::ImmediatePartial(0.5)) + .build(); + empty_broker.connect().unwrap(); + let mut flags = RecoveredState::new(); + flags.positions_intent_logged = true; + flags.quotes_intent_logged = true; + flags.account_summary_intent_logged = true; + flags.cancel_intent_logged = true; + let report = compare_broker_state(&empty_broker, &flags).unwrap(); + assert_eq!(report.discrepancies.len(), 4); + assert!(matches!( + report.discrepancies[0], + Discrepancy::IncompletePositionsIntent { .. } + )); + assert!(matches!( + report.discrepancies[1], + Discrepancy::IncompleteQuotesIntent { .. } + )); + assert!(matches!( + report.discrepancies[2], + Discrepancy::IncompleteAccountSummaryIntent { .. } + )); + assert!(matches!( + report.discrepancies[3], + Discrepancy::IncompleteCancelIntent { .. } + )); + + flags.positions_result_logged = true; + flags.quotes_result_logged = true; + flags.account_summary_result_logged = true; + flags.cancel_result_logged = true; + let report = compare_broker_state(&empty_broker, &flags).unwrap(); + assert!(report.discrepancies.is_empty()); + assert!(!report.has_critical_issues); + } + + #[cfg(feature = "write_ahead_logging")] + struct FailOpenBroker { + calls: std::cell::Cell, + } + + #[cfg(feature = "write_ahead_logging")] + impl nanobook_broker::Broker for FailOpenBroker { + fn connect(&mut self) -> std::result::Result<(), nanobook_broker::error::BrokerError> { + Ok(()) + } + fn disconnect(&mut self) -> std::result::Result<(), nanobook_broker::error::BrokerError> { + Ok(()) + } + fn positions( + &self, + ) -> std::result::Result< + Vec, + nanobook_broker::error::BrokerError, + > { + Ok(Vec::new()) + } + fn account( + &self, + ) -> std::result::Result + { + Ok(nanobook_broker::types::Account { + equity_cents: 0, + buying_power_cents: 0, + cash_cents: 0, + gross_position_value_cents: 0, + }) + } + fn submit_order( + &self, + _order: &nanobook_broker::types::BrokerOrder, + ) -> std::result::Result + { + Ok(nanobook_broker::types::OrderId(1)) + } + fn order_status( + &self, + id: nanobook_broker::types::OrderId, + ) -> std::result::Result< + nanobook_broker::types::BrokerOrderStatus, + nanobook_broker::error::BrokerError, + > { + Ok(nanobook_broker::types::BrokerOrderStatus { + id, + status: nanobook_broker::types::OrderState::Submitted, + filled_quantity: 0, + remaining_quantity: 1, + avg_fill_price_cents: 0, + }) + } + fn open_orders( + &self, + ) -> std::result::Result< + Vec, + nanobook_broker::error::BrokerError, + > { + self.calls.set(self.calls.get() + 1); + Err(nanobook_broker::error::BrokerError::Connection( + "open orders unavailable".into(), + )) + } + fn cancel_order( + &self, + _id: nanobook_broker::types::OrderId, + ) -> std::result::Result<(), nanobook_broker::error::BrokerError> { + Ok(()) + } + fn quote( + &self, + symbol: &Symbol, + ) -> std::result::Result + { + Ok(nanobook_broker::types::Quote { + symbol: *symbol, + bid_cents: 0, + ask_cents: 0, + last_cents: 0, + volume: 0, + timestamp: std::time::SystemTime::now(), + }) + } + } + + #[cfg(feature = "write_ahead_logging")] + #[test] + fn reconcile_order_intent_ignores_filled_remaining_zero() { + use nanobook::Price; + use nanobook_broker::mock::{FillMode, MockBroker}; + use nanobook_broker::types::{BrokerOrder, BrokerOrderType}; + use nanobook_broker::{Broker, BrokerSide}; + + let mut broker = MockBroker::builder() + .fill_mode(FillMode::ImmediateFull) + .build(); + broker.connect().unwrap(); + broker + .submit_order(&BrokerOrder { + symbol: Symbol::new("AAPL"), + side: BrokerSide::Buy, + quantity: 50, + order_type: BrokerOrderType::Limit(Price(16_000)), + client_order_id: None, + }) + .unwrap(); + assert_eq!( + reconcile_order_intent(&broker, &Symbol::new("AAPL"), 50).unwrap(), + None + ); + } + + #[cfg(feature = "write_ahead_logging")] + #[test] + fn reconcile_order_intent_retries_five_times() { + let broker = FailOpenBroker { + calls: std::cell::Cell::new(0), + }; + let mut sleeps = Vec::new(); + let err = + reconcile_order_intent_with(&broker, &Symbol::new("AAPL"), 50, &mut |d| sleeps.push(d)) + .unwrap_err(); + match err { + Error::Recovery(m) => { + assert!(m.starts_with("Broker query failed after 5 attempts")); + } + other => panic!("expected Recovery, got {other:?}"), + } + assert_eq!(broker.calls.get(), 5); + assert_eq!( + sleeps, + vec![ + Duration::from_millis(1000), + Duration::from_millis(2000), + Duration::from_millis(4000), + Duration::from_millis(8000), + ] + ); + } } diff --git a/rebalancer/src/risk.rs b/rebalancer/src/risk.rs index 6d3d6b3..d92132e 100644 --- a/rebalancer/src/risk.rs +++ b/rebalancer/src/risk.rs @@ -140,6 +140,9 @@ mod tests { fn spy() -> Symbol { Symbol::new("SPY") } + fn msft() -> Symbol { + Symbol::new("MSFT") + } #[test] fn all_pass_simple() { @@ -258,4 +261,124 @@ mod tests { let s = format!("{report}"); assert!(s.contains("[PASS]")); } + + #[test] + fn invalid_adapted_fields_fail_order_validation() { + let cases = [ + { + let mut cfg = default_risk_config(); + cfg.max_leverage = 0.5; + cfg + }, + { + let mut cfg = default_risk_config(); + cfg.min_trade_usd = -1.0; + cfg + }, + { + let mut cfg = default_risk_config(); + cfg.max_trade_usd = -1.0; + cfg + }, + { + let mut cfg = default_risk_config(); + cfg.max_short_pct = -0.1; + cfg + }, + ]; + for cfg in cases { + let report = check_risk(&[], 10_000_000, &[], &[], &FxHashMap::default(), &cfg); + assert_eq!(report.checks.len(), 1); + assert_eq!(report.checks[0].name, "Order validation"); + assert_eq!(report.checks[0].status, RiskStatus::Fail); + } + } + + #[test] + fn disabled_batch_cap_does_not_fail_large_order() { + let orders = vec![RebalanceOrder { + symbol: aapl(), + action: Action::Buy, + shares: 10_000, + limit_price_cents: 18_500, + notional_cents: 185_000_000, + description: "open", + }]; + let cfg = RiskConfig { + max_position_pct: 0.25, + max_leverage: 1.5, + min_trade_usd: 100.0, + max_trade_usd: 10_000_000.0, + allow_short: true, + max_short_pct: 0.30, + }; + let report = check_risk( + &orders, + 1_000_000_000, + &[(aapl(), 0.185)], + &[(aapl(), 18_500)], + &FxHashMap::default(), + &cfg, + ); + assert!(!report.has_failures()); + assert!(!report.has_warnings()); + } + + #[test] + fn held_short_is_seeded_as_sell() { + let mut cfg = default_risk_config(); + cfg.allow_short = false; + let orders = vec![RebalanceOrder { + symbol: aapl(), + action: Action::Buy, + shares: 10, + limit_price_cents: 18_500, + notional_cents: 185_000, + description: "open", + }]; + let mut current = FxHashMap::default(); + current.insert(spy(), -50); + let report = check_risk( + &orders, + 100_000_000, + &[(aapl(), 0.1)], + &[(aapl(), 18_500), (spy(), 43_000)], + ¤t, + &cfg, + ); + assert!( + report + .checks + .iter() + .any(|c| c.name == "Short selling" && c.status == RiskStatus::Fail) + ); + } + + #[test] + fn held_long_is_seeded_into_leverage() { + let orders = vec![RebalanceOrder { + symbol: msft(), + action: Action::Buy, + shares: 1, + limit_price_cents: 100, + notional_cents: 100, + description: "open", + }]; + let mut current = FxHashMap::default(); + current.insert(aapl(), 1000); + let report = check_risk( + &orders, + 10_000_000, + &[(msft(), 0.001)], + &[(msft(), 100), (aapl(), 18_500)], + ¤t, + &default_risk_config(), + ); + assert!( + report + .checks + .iter() + .any(|c| c.name == "Leverage" && c.status == RiskStatus::Fail) + ); + } } diff --git a/rebalancer/src/target.rs b/rebalancer/src/target.rs index 3e17306..90aa297 100644 --- a/rebalancer/src/target.rs +++ b/rebalancer/src/target.rs @@ -370,4 +370,60 @@ mod tests { let spec2 = TargetSpec::from_json(json2).unwrap(); assert_ne!(spec1.window_id(), spec2.window_id()); } + + #[test] + fn eight_byte_symbol_is_valid() { + let json = r#"{ + "timestamp": "2026-02-08T15:30:00Z", + "targets": [ + { "symbol": "ABCDEFGH", "weight": 0.5 } + ] + }"#; + assert!(TargetSpec::from_json(json).is_ok()); + } + + #[test] + fn weight_magnitude_boundaries() { + let too_short = r#"{ + "timestamp": "2026-02-08T15:30:00Z", + "targets": [ + { "symbol": "AAPL", "weight": -1.5 } + ] + }"#; + assert!(TargetSpec::from_json(too_short).is_err()); + let long_one = r#"{ + "timestamp": "2026-02-08T15:30:00Z", + "targets": [ + { "symbol": "AAPL", "weight": 1.0 } + ] + }"#; + assert!(TargetSpec::from_json(long_one).is_ok()); + let short_one = r#"{ + "timestamp": "2026-02-08T15:30:00Z", + "targets": [ + { "symbol": "AAPL", "weight": -1.0 } + ] + }"#; + assert!(TargetSpec::from_json(short_one).is_ok()); + } + + #[test] + fn long_weights_sum_to_one() { + let json = r#"{ + "timestamp": "2026-02-08T15:30:00Z", + "targets": [ + { "symbol": "AAPL", "weight": 0.5 }, + { "symbol": "MSFT", "weight": 0.5 } + ] + }"#; + assert!(TargetSpec::from_json(json).is_ok()); + let over = r#"{ + "timestamp": "2026-02-08T15:30:00Z", + "targets": [ + { "symbol": "AAPL", "weight": 0.6 }, + { "symbol": "MSFT", "weight": 0.5 } + ] + }"#; + assert!(TargetSpec::from_json(over).is_err()); + } } diff --git a/rebalancer/src/validator.rs b/rebalancer/src/validator.rs index f5c99c9..7ee05cc 100644 --- a/rebalancer/src/validator.rs +++ b/rebalancer/src/validator.rs @@ -304,9 +304,10 @@ fn _path_exists(path: &Path) -> bool { mod tests { use super::{ ValidationIssue, format_validation_issues, should_run_startup_validation, - validate_available_log_space, validate_broker_connectivity, validate_file_permissions, - validate_network_timeout, validate_required_fields, validate_risk_limits, validate_static, - validate_static_or_error, validate_static_with_source, + validate_available_log_space, validate_broker_connectivity, validate_disk_space, + validate_file_permissions, validate_network_timeout, validate_required_fields, + validate_risk_limits, validate_static, validate_static_or_error, + validate_static_with_source, }; use crate::config::{ AccountConfig, AccountType, Config, ConnectionConfig, CostConfig, ExecutionConfig, @@ -519,4 +520,38 @@ mod tests { assert!(text.contains("20 is too high")); assert!(text.contains("fix: use <= 10")); } + + #[test] + fn min_trade_usd_rejects_negative_and_accepts_zero() -> std::io::Result<()> { + let dir = tempfile::tempdir()?; + let mut config = valid_config(dir.path()); + config.risk.min_trade_usd = -1.0; + let issues = validate_risk_limits(&config); + assert!(issues.iter().any(|i| i.field == "risk.min_trade_usd")); + config.risk.min_trade_usd = 0.0; + let issues = validate_risk_limits(&config); + assert!(issues.iter().all(|i| i.field != "risk.min_trade_usd")); + Ok(()) + } + + #[test] + fn disk_space_reports_missing_log_directory() { + let config = valid_config(Path::new("/nonexistent-nanobook-test-dir/logs")); + let issues = validate_disk_space(&config); + assert_eq!(issues.len(), 1); + assert_eq!(issues[0].field, "logging.dir"); + assert!( + issues[0] + .message + .starts_with("cannot determine available space for") + ); + } + + #[test] + fn available_log_space_boundary() { + let dir = tempfile::tempdir().unwrap(); + let config = valid_config(dir.path()); + assert!(validate_available_log_space(1_000_000_000, &config).is_empty()); + assert_eq!(validate_available_log_space(999_999_999, &config).len(), 1); + } } diff --git a/rebalancer/tests/audit_writers.rs b/rebalancer/tests/audit_writers.rs new file mode 100644 index 0000000..fb36b42 --- /dev/null +++ b/rebalancer/tests/audit_writers.rs @@ -0,0 +1,242 @@ +//! G24: audit convenience writers. + +use nanobook::Symbol; +use nanobook_broker::ibkr::orders::{OrderOutcome, OrderResult}; +use nanobook_rebalancer::audit::{ + AuditLog, log_cron_completed, log_cron_start, log_diff, log_diff_checkpoint, + log_idempotency_rejection, log_order_filled, log_order_filled_checkpoint, + log_order_submitted_checkpoint, log_positions, log_risk_check, + log_risk_check_passed_checkpoint, log_run_completed, log_run_completed_checkpoint, + log_run_started, log_run_started_checkpoint, parse_audit_events, +}; +use nanobook_rebalancer::diff::{Action, CurrentPosition, RebalanceOrder}; +use nanobook_rebalancer::kill::verify_no_dangling_orders; +use nanobook_rebalancer::risk::{RiskCheck, RiskReport, RiskStatus}; + +fn order() -> RebalanceOrder { + RebalanceOrder { + symbol: Symbol::new("AAPL"), + action: Action::Buy, + shares: 10, + limit_price_cents: 18_502, + notional_cents: 185_020, + description: "open", + } +} + +fn find<'a>( + events: &'a [nanobook_rebalancer::audit::AuditEvent], + name: &str, +) -> &'a nanobook_rebalancer::audit::AuditEvent { + events.iter().find(|e| e.event == name).unwrap() +} + +#[test] +fn convenience_writers_round_trip_audit_fields() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + let mut a = AuditLog::open_in(&path, dir.path()).unwrap(); + let order = order(); + + log_cron_completed(&mut a, 1_700_000_001, "w1", 3, 2, 1).unwrap(); + let events = parse_audit_events(&path).unwrap(); + let cron = events.last().unwrap(); + assert_eq!(cron.event, "cron_completed"); + assert_eq!(cron.sequence_number, Some(1_700_000_001)); + assert_eq!(cron.window_id.as_deref(), Some("w1")); + assert_eq!(cron.data.get("submitted").and_then(|v| v.as_u64()), Some(3)); + assert_eq!(cron.data.get("filled").and_then(|v| v.as_u64()), Some(2)); + assert_eq!(cron.data.get("failed").and_then(|v| v.as_u64()), Some(1)); + assert_eq!( + a.check_window_already_complete("w1").unwrap(), + Some(1_700_000_001) + ); + + log_cron_start(&mut a, 1_700_000_000, "w1").unwrap(); + log_idempotency_rejection(&mut a, "w1", 1_700_000_001).unwrap(); + + log_order_submitted_checkpoint(&mut a, 8, &order, 4242).unwrap(); + let dangling = verify_no_dangling_orders(&path).unwrap(); + assert_eq!(dangling.len(), 1); + assert_eq!(dangling[0].ibkr_id, 4242); + assert_eq!(dangling[0].symbol, "AAPL"); + + let result = OrderResult { + symbol: Symbol::new("AAPL"), + order_id: 4242, + filled_shares: 10, + avg_fill_price: 185.01, + commission: 1.0, + status: OrderOutcome::PartialFill, + }; + log_order_filled(&mut a, &result).unwrap(); + assert!(verify_no_dangling_orders(&path).unwrap().is_empty()); + + log_order_filled_checkpoint(&mut a, 12, &result).unwrap(); + log_run_started(&mut a, "t.json", "DU1").unwrap(); + log_run_started_checkpoint(&mut a, 7, "t.json", "DU1").unwrap(); + log_run_completed(&mut a, 2, 1, 1).unwrap(); + log_run_completed_checkpoint(&mut a, 13, 2, 1, 1).unwrap(); + log_positions( + &mut a, + &[CurrentPosition { + symbol: Symbol::new("AAPL"), + quantity: 100, + avg_cost_cents: 15_025, + }], + 100_000_000, + ) + .unwrap(); + log_diff(&mut a, std::slice::from_ref(&order)).unwrap(); + log_diff_checkpoint(&mut a, 9, std::slice::from_ref(&order)).unwrap(); + let report = RiskReport { + checks: vec![ + RiskCheck { + name: "Max position", + status: RiskStatus::Pass, + detail: "ok".into(), + }, + RiskCheck { + name: "Leverage", + status: RiskStatus::Fail, + detail: "bad".into(), + }, + ], + }; + log_risk_check(&mut a, &report).unwrap(); + log_risk_check_passed_checkpoint(&mut a, 11, &report).unwrap(); + + let events = parse_audit_events(&path).unwrap(); + let start = events.iter().find(|e| e.event == "cron_start").unwrap(); + assert_eq!(start.sequence_number, Some(1_700_000_000)); + assert_eq!(start.window_id.as_deref(), Some("w1")); + let rejection = find(&events, "idempotency_rejection"); + assert_eq!(rejection.sequence_number, Some(1_700_000_001)); + assert_eq!(rejection.window_id.as_deref(), Some("w1")); + + let filled = events + .iter() + .find(|e| e.event == "order_filled" && e.checkpoint.is_none()) + .unwrap(); + assert_eq!( + filled.data.get("symbol").and_then(|v| v.as_str()), + Some("AAPL") + ); + assert_eq!( + filled.data.get("ibkr_id").and_then(|v| v.as_i64()), + Some(4242) + ); + assert_eq!(filled.data.get("filled").and_then(|v| v.as_i64()), Some(10)); + assert_eq!( + filled.data.get("avg_price").and_then(|v| v.as_f64()), + Some(185.01) + ); + assert_eq!( + filled.data.get("commission").and_then(|v| v.as_f64()), + Some(1.0) + ); + assert_eq!( + filled.data.get("status").and_then(|v| v.as_str()), + Some("PartialFill") + ); + let filled_cp = events + .iter() + .find(|e| e.event == "order_filled" && e.sequence_number == Some(12)) + .unwrap(); + assert_eq!(filled_cp.checkpoint.as_deref(), Some("OrderFilled")); + + let run_started = events + .iter() + .find(|e| e.event == "run_started" && e.checkpoint.is_none()) + .unwrap(); + assert_eq!( + run_started.data.get("target_file").and_then(|v| v.as_str()), + Some("t.json") + ); + assert_eq!( + run_started.data.get("account").and_then(|v| v.as_str()), + Some("DU1") + ); + let run_started_cp = events + .iter() + .find(|e| e.event == "run_started" && e.sequence_number == Some(7)) + .unwrap(); + assert_eq!(run_started_cp.checkpoint.as_deref(), Some("RunStarted")); + + let completed = events + .iter() + .find(|e| e.event == "run_completed" && e.checkpoint.is_none()) + .unwrap(); + assert_eq!( + completed.data.get("submitted").and_then(|v| v.as_u64()), + Some(2) + ); + assert_eq!( + completed.data.get("filled").and_then(|v| v.as_u64()), + Some(1) + ); + assert_eq!( + completed.data.get("failed").and_then(|v| v.as_u64()), + Some(1) + ); + let completed_cp = events + .iter() + .find(|e| e.event == "run_completed" && e.sequence_number == Some(13)) + .unwrap(); + assert_eq!(completed_cp.checkpoint.as_deref(), Some("RunCompleted")); + + let positions = find(&events, "positions_fetched"); + let pos0 = &positions.data["positions"][0]; + assert_eq!(pos0.get("symbol").and_then(|v| v.as_str()), Some("AAPL")); + assert_eq!(pos0.get("qty").and_then(|v| v.as_i64()), Some(100)); + assert_eq!(pos0.get("avg_cost").and_then(|v| v.as_f64()), Some(150.25)); + assert_eq!( + positions.data.get("equity").and_then(|v| v.as_f64()), + Some(1_000_000.0) + ); + + let diff = events + .iter() + .find(|e| e.event == "diff_computed" && e.checkpoint.is_none()) + .unwrap(); + let d0 = &diff.data["orders"][0]; + assert_eq!(d0.get("symbol").and_then(|v| v.as_str()), Some("AAPL")); + assert_eq!(d0.get("action").and_then(|v| v.as_str()), Some("BUY")); + assert_eq!(d0.get("shares").and_then(|v| v.as_i64()), Some(10)); + assert_eq!(d0.get("limit").and_then(|v| v.as_f64()), Some(185.02)); + assert_eq!(d0.get("description").and_then(|v| v.as_str()), Some("open")); + let diff_cp = events + .iter() + .find(|e| e.event == "diff_computed" && e.sequence_number == Some(9)) + .unwrap(); + assert_eq!(diff_cp.checkpoint.as_deref(), Some("DiffComputed")); + + let risk = events.iter().find(|e| e.event == "risk_check").unwrap(); + assert_eq!( + risk.data.get("passed").and_then(|v| v.as_bool()), + Some(false) + ); + assert_eq!( + risk.data["checks"][1].get("name").and_then(|v| v.as_str()), + Some("Leverage") + ); + assert_eq!( + risk.data["checks"][1] + .get("status") + .and_then(|v| v.as_str()), + Some("FAIL") + ); + assert_eq!( + risk.data["checks"][1] + .get("detail") + .and_then(|v| v.as_str()), + Some("bad") + ); + let risk_cp = events + .iter() + .find(|e| e.event == "risk_check_passed") + .unwrap(); + assert_eq!(risk_cp.sequence_number, Some(11)); + assert_eq!(risk_cp.checkpoint.as_deref(), Some("RiskCheckPassed")); + assert_eq!(risk_cp.data["checks"].as_array().unwrap().len(), 2); +} diff --git a/rebalancer/tests/cli_smoke.rs b/rebalancer/tests/cli_smoke.rs new file mode 100644 index 0000000..c1a9745 --- /dev/null +++ b/rebalancer/tests/cli_smoke.rs @@ -0,0 +1,60 @@ +//! G29 CLI entry and S2 exit codes. + +use std::process::Command; + +fn bin() -> &'static str { + env!("CARGO_BIN_EXE_rebalancer") +} + +fn sample_config() -> &'static str { + r#" +[connection] +host = "127.0.0.1" +port = 4002 +client_id = 1 +[account] +id = "DU1" +type = "cash" +[execution] +[risk] +[cost] +[logging] +dir = "./logs" +audit_file = "audit.jsonl" +"# +} + +#[test] +fn missing_config_creates_log_dir_and_exits_1() { + let dir = tempfile::tempdir().unwrap(); + let output = Command::new(bin()) + .current_dir(dir.path()) + .args(["--config", "missing.toml", "status"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("Error loading config"), + "stderr was: {stderr}" + ); + assert!(dir.path().join("logs").is_dir()); +} + +#[test] +fn kill_without_pid_file_exits_nonzero() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("config.toml"), sample_config()).unwrap(); + let output = Command::new(bin()) + .current_dir(dir.path()) + .args(["--config", "config.toml", "--skip-validation", "kill"]) + .output() + .unwrap(); + assert_ne!(output.status.code(), Some(0)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("PID file not found"), + "stderr was: {stderr}" + ); + assert_eq!(output.status.code(), Some(3)); +} diff --git a/rebalancer/tests/entry_points.rs b/rebalancer/tests/entry_points.rs new file mode 100644 index 0000000..8e5e0a3 --- /dev/null +++ b/rebalancer/tests/entry_points.rs @@ -0,0 +1,103 @@ +//! G12: run, positions, status and reconcile against a closed port. + +use std::net::TcpListener; +use std::sync::mpsc; +use std::thread; +use std::time::Duration; + +use nanobook_rebalancer::config::Config; +use nanobook_rebalancer::error::Error; +use nanobook_rebalancer::execution::{self, RunOptions}; +use nanobook_rebalancer::target::TargetSpec; + +fn closed_port() -> u16 { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.local_addr().unwrap().port() +} + +fn config_for_port(port: u16) -> Config { + toml::from_str(&format!( + r#" +[connection] +host = "127.0.0.1" +port = {port} +client_id = 1 +[account] +id = "DU1" +type = "cash" +[execution] +[risk] +[cost] +[logging] +"# + )) + .unwrap() +} + +fn spec() -> TargetSpec { + TargetSpec::from_json( + r#"{ + "timestamp": "2026-02-08T15:30:00Z", + "targets": [{ "symbol": "AAPL", "weight": 0.5 }] + }"#, + ) + .unwrap() +} + +fn call_with_timeout(f: F) -> T +where + T: Send + 'static, + F: FnOnce() -> T + Send + 'static, +{ + let (tx, rx) = mpsc::channel(); + thread::spawn(move || { + let _ = tx.send(f()); + }); + rx.recv_timeout(Duration::from_secs(8)) + .expect("IBKR connect to a closed port hung; G12 falls back to S1 for run") +} + +fn assert_connection(result: nanobook_rebalancer::error::Result<()>) { + match result { + Err(Error::Connection(_)) => {} + other => panic!("expected Connection, got {other:?}"), + } +} + +#[test] +fn run_against_closed_port_is_connection_error() { + let config = config_for_port(closed_port()); + let spec = spec(); + let opts = RunOptions { + dry_run: true, + force: true, + target_file: "t.json".into(), + cron_mode: false, + }; + assert_connection(call_with_timeout(move || { + execution::run(&config, &spec, &opts) + })); +} + +#[test] +fn show_positions_against_closed_port_is_connection_error() { + let config = config_for_port(closed_port()); + assert_connection(call_with_timeout(move || { + execution::show_positions(&config) + })); +} + +#[test] +fn check_status_against_closed_port_is_connection_error() { + let config = config_for_port(closed_port()); + assert_connection(call_with_timeout(move || execution::check_status(&config))); +} + +#[test] +fn run_reconcile_against_closed_port_is_connection_error() { + let config = config_for_port(closed_port()); + let spec = spec(); + assert_connection(call_with_timeout(move || { + execution::run_reconcile(&config, &spec) + })); +} diff --git a/rebalancer/tests/fetch_wrappers.rs b/rebalancer/tests/fetch_wrappers.rs new file mode 100644 index 0000000..fce7807 --- /dev/null +++ b/rebalancer/tests/fetch_wrappers.rs @@ -0,0 +1,283 @@ +//! G16 WAL fetch wrappers and T2 non-WAL wrappers. + +use std::cell::Cell; +use std::time::{Duration, SystemTime}; + +use nanobook::Symbol; +use nanobook_broker::error::BrokerError; +use nanobook_broker::ibkr::orders::{OrderOutcome, OrderResult}; +use nanobook_broker::types::{Account, Position, Quote}; +use nanobook_broker::{BrokerSide, ClientOrderId}; +use nanobook_rebalancer::audit::AuditLog; +use nanobook_rebalancer::broker::BrokerGateway; +use nanobook_rebalancer::diff::{Action, RebalanceOrder}; +use nanobook_rebalancer::error::Error; +use nanobook_rebalancer::execution::{ + cancel_order_with_write_ahead, execute_order_with_write_ahead, + fetch_positions_with_write_ahead, fetch_quotes_with_write_ahead, +}; + +struct FetchStub { + fail_connection: bool, + cancel_ok: bool, + cancel_calls: Cell, + execute_calls: Cell, + execute_ok: bool, +} + +impl FetchStub { + fn ok() -> Self { + Self { + fail_connection: false, + cancel_ok: true, + cancel_calls: Cell::new(0), + execute_calls: Cell::new(0), + execute_ok: true, + } + } + + fn connection_fail() -> Self { + Self { + fail_connection: true, + cancel_ok: true, + cancel_calls: Cell::new(0), + execute_calls: Cell::new(0), + execute_ok: true, + } + } +} + +fn sample_positions() -> Vec { + vec![ + Position { + symbol: Symbol::new("AAPL"), + quantity: 100, + avg_cost_cents: 15_000, + market_value_cents: 0, + unrealized_pnl_cents: 0, + }, + Position { + symbol: Symbol::new("MSFT"), + quantity: -30, + avg_cost_cents: 40_000, + market_value_cents: 0, + unrealized_pnl_cents: 0, + }, + ] +} + +fn sample_quotes() -> Vec { + vec![ + Quote { + symbol: Symbol::new("AAPL"), + bid_cents: 14_990, + ask_cents: 15_010, + last_cents: 15_000, + volume: 0, + timestamp: SystemTime::now(), + }, + Quote { + symbol: Symbol::new("MSFT"), + bid_cents: 39_990, + ask_cents: 40_010, + last_cents: 40_000, + volume: 0, + timestamp: SystemTime::now(), + }, + ] +} + +impl BrokerGateway for FetchStub { + fn account_summary(&self) -> nanobook_rebalancer::broker::BrokerResult { + if self.fail_connection { + return Err(BrokerError::Connection("down".into())); + } + Ok(Account { + equity_cents: 100_000_000, + buying_power_cents: 0, + cash_cents: 100_000_000, + gross_position_value_cents: 0, + }) + } + + fn positions(&self) -> nanobook_rebalancer::broker::BrokerResult> { + if self.fail_connection { + return Err(BrokerError::Connection("down".into())); + } + Ok(sample_positions()) + } + + fn prices( + &self, + _symbols: &[Symbol], + ) -> nanobook_rebalancer::broker::BrokerResult> { + Ok(Vec::new()) + } + + fn quotes(&self, _symbols: &[Symbol]) -> nanobook_rebalancer::broker::BrokerResult> { + if self.fail_connection { + return Err(BrokerError::Connection("down".into())); + } + Ok(sample_quotes()) + } + + fn execute_limit_order( + &self, + symbol: Symbol, + _side: BrokerSide, + shares: u64, + _limit_price_cents: i64, + _client_order_id: Option<&ClientOrderId>, + _timeout: Duration, + ) -> nanobook_rebalancer::broker::BrokerResult { + self.execute_calls.set(self.execute_calls.get() + 1); + if !self.execute_ok { + return Err(BrokerError::Order("boom".into())); + } + Ok(OrderResult { + symbol, + order_id: 1, + filled_shares: shares as i64, + avg_fill_price: 1.0, + commission: 0.0, + status: OrderOutcome::Filled, + }) + } + + fn cancel_order(&self, _order_id: u64) -> nanobook_rebalancer::broker::BrokerResult<()> { + self.cancel_calls.set(self.cancel_calls.get() + 1); + if self.cancel_ok { + Ok(()) + } else { + Err(BrokerError::Other("boom".into())) + } + } +} + +#[test] +fn fetch_wrappers_return_stub_positions_and_quotes() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + let mut audit = AuditLog::open_in(&path, dir.path()).unwrap(); + let stub = FetchStub::ok(); + let mut seq = 100u64; + let positions = + fetch_positions_with_write_ahead(&stub, &mut audit, &mut seq, "ref", 100_000_000).unwrap(); + assert_eq!(positions.len(), 2); + assert_eq!(positions[1].quantity, -30); + + #[cfg(feature = "write_ahead_logging")] + { + assert_eq!(seq, 102); + let events = nanobook_rebalancer::audit::parse_audit_events(&path).unwrap(); + assert_eq!(events[0].event, "positions_intent"); + assert_eq!(events[0].sequence_number, Some(101)); + assert_eq!(events[1].event, "positions_result"); + assert_eq!(events[1].sequence_number, Some(102)); + assert_eq!( + events[1].data["positions"][1] + .get("qty") + .and_then(|v| v.as_i64()), + Some(-30) + ); + assert_eq!( + events[1].data.get("equity").and_then(|v| v.as_f64()), + Some(1_000_000.0) + ); + } + + let symbols = [Symbol::new("AAPL"), Symbol::new("MSFT")]; + let quotes = + fetch_quotes_with_write_ahead(&stub, &mut audit, &mut seq, "ref", &symbols, 30).unwrap(); + assert_eq!(quotes.len(), 2); + assert_eq!(quotes[1].ask_cents, 40_010); + + #[cfg(feature = "write_ahead_logging")] + { + assert_eq!(seq, 104); + let events = nanobook_rebalancer::audit::parse_audit_events(&path).unwrap(); + let intent = events.iter().find(|e| e.event == "quotes_intent").unwrap(); + assert_eq!( + intent + .data + .get("symbols") + .and_then(|v| v.as_array()) + .map(|a| { + a.iter() + .filter_map(|s| s.as_str().map(str::to_string)) + .collect::>() + }), + Some(vec!["AAPL".into(), "MSFT".into()]) + ); + assert_eq!( + intent + .data + .get("staleness_threshold_sec") + .and_then(|v| v.as_u64()), + Some(30) + ); + assert!(events.iter().any(|e| e.event == "quotes_result")); + } +} + +#[test] +fn fetch_wrappers_map_connection_errors() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + let mut audit = AuditLog::open_in(&path, dir.path()).unwrap(); + let stub = FetchStub::connection_fail(); + let mut seq = 1u64; + match fetch_positions_with_write_ahead(&stub, &mut audit, &mut seq, "ref", 0) { + Err(Error::Connection(_)) => {} + other => panic!("expected Connection, got {other:?}"), + } +} + +#[test] +fn cancel_wrapper_maps_broker_error() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + let mut audit = AuditLog::open_in(&path, dir.path()).unwrap(); + let mut fail = FetchStub::ok(); + fail.cancel_ok = false; + let mut seq = 1u64; + match cancel_order_with_write_ahead(&fail, &mut audit, &mut seq, 42, "r") { + Err(Error::Order(m)) => assert!(m.starts_with("cancel failed for order 42")), + other => panic!("expected Order, got {other:?}"), + } + + let ok = FetchStub::ok(); + cancel_order_with_write_ahead(&ok, &mut audit, &mut seq, 42, "r").unwrap(); + assert_eq!(ok.cancel_calls.get(), 1); +} + +#[test] +fn execute_wrapper_maps_order_error() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + let mut audit = AuditLog::open_in(&path, dir.path()).unwrap(); + let mut stub = FetchStub::ok(); + stub.execute_ok = false; + let order = RebalanceOrder { + symbol: Symbol::new("AAPL"), + action: Action::Buy, + shares: 10, + limit_price_cents: 18_500, + notional_cents: 185_000, + description: "open", + }; + let cid = ClientOrderId::derive("scope", "AAPL", BrokerSide::Buy, 10); + match execute_order_with_write_ahead( + &stub, + &mut audit, + &order, + &cid, + Duration::from_secs(1), + 1, + "ref", + ) { + Err(Error::Order(_)) => {} + other => panic!("expected Order, got {other:?}"), + } + assert_eq!(stub.execute_calls.get(), 1); +} diff --git a/rebalancer/tests/recovery_integration.rs b/rebalancer/tests/recovery_integration.rs index 921af30..289e7a1 100644 --- a/rebalancer/tests/recovery_integration.rs +++ b/rebalancer/tests/recovery_integration.rs @@ -3,9 +3,13 @@ use nanobook::Symbol; use nanobook_broker::mock::{FillMode, MockBroker}; use nanobook_broker::{Broker, BrokerOrder, BrokerOrderType, BrokerSide}; +#[cfg(feature = "write_ahead_logging")] +use nanobook_rebalancer::audit::parse_audit_events; use nanobook_rebalancer::audit::{AuditLog, log_positions_checkpoint}; use nanobook_rebalancer::config::Config; use nanobook_rebalancer::diff::CurrentPosition; +#[cfg(feature = "write_ahead_logging")] +use nanobook_rebalancer::error::Error; use nanobook_rebalancer::recovery::{RecoveryAction, reconstruct_state, run_recover}; use nanobook_rebalancer::target::TargetSpec; use tempfile::tempdir; @@ -860,3 +864,360 @@ fn test_recovery_with_golden_fixture_mixed_intents() { // Should require manual review due to unfilled submitted order assert_eq!(action, RecoveryAction::ManualReview); } + +#[cfg(feature = "write_ahead_logging")] +fn log_run_started_and_intents(audit_path: &std::path::Path, workdir: &std::path::Path) { + let mut log = AuditLog::open_in(audit_path, workdir).unwrap(); + log.log_checkpoint( + nanobook_rebalancer::audit::Checkpoint::RunStarted, + 1, + serde_json::json!({"target": "test"}), + ) + .unwrap(); + log.log_checkpoint( + nanobook_rebalancer::audit::Checkpoint::OrderIntent, + 2, + serde_json::json!({ + "symbol": "AAPL", + "action": "Buy", + "shares": 50, + "limit": 160.0, + "client_order_id": "a", + }), + ) + .unwrap(); + log.log_checkpoint( + nanobook_rebalancer::audit::Checkpoint::OrderIntent, + 3, + serde_json::json!({ + "symbol": "MSFT", + "action": "Buy", + "shares": 25, + "limit": 310.0, + "client_order_id": "b", + }), + ) + .unwrap(); +} + +#[cfg(feature = "write_ahead_logging")] +#[test] +fn reconcile_skips_already_submitted_intents() { + use nanobook_rebalancer::recovery::reconcile_incomplete_intents; + + let dir = tempfile::tempdir().unwrap(); + let audit_path = dir.path().join("audit.jsonl"); + { + let mut log = AuditLog::open_in(&audit_path, dir.path()).unwrap(); + log.log_checkpoint( + nanobook_rebalancer::audit::Checkpoint::RunStarted, + 1, + serde_json::json!({"target": "test"}), + ) + .unwrap(); + log.log_checkpoint( + nanobook_rebalancer::audit::Checkpoint::DiffComputed, + 2, + serde_json::json!({ + "orders": [ + {"symbol": "AAPL", "action": "Buy", "shares": 50, "limit": 160.0}, + {"symbol": "MSFT", "action": "Buy", "shares": 25, "limit": 310.0} + ] + }), + ) + .unwrap(); + log.log_checkpoint( + nanobook_rebalancer::audit::Checkpoint::OrderIntent, + 3, + serde_json::json!({ + "symbol": "AAPL", + "action": "Buy", + "shares": 50, + "limit": 160.0, + "client_order_id": "a", + }), + ) + .unwrap(); + log.log_checkpoint( + nanobook_rebalancer::audit::Checkpoint::OrderSubmitted, + 4, + serde_json::json!({ + "symbol": "AAPL", + "ibkr_id": 111, + }), + ) + .unwrap(); + } + let mut broker = MockBroker::builder().build(); + broker.connect().unwrap(); + let (state, _) = reconstruct_state(&audit_path).unwrap(); + reconcile_incomplete_intents(&broker, &state, &audit_path).unwrap(); + assert_eq!(parse_audit_events(&audit_path).unwrap().len(), 4); +} + +#[cfg(feature = "write_ahead_logging")] +#[test] +fn reconcile_appends_submitted_and_failed_in_sequence() { + use nanobook::Price; + use nanobook_rebalancer::recovery::reconcile_incomplete_intents; + + let dir = tempfile::tempdir().unwrap(); + let audit_path = dir.path().join("audit.jsonl"); + log_run_started_and_intents(&audit_path, dir.path()); + let mut broker = MockBroker::builder() + .fill_mode(FillMode::ImmediatePartial(0.5)) + .build(); + broker.connect().unwrap(); + broker + .submit_order(&BrokerOrder { + symbol: Symbol::new("AAPL"), + side: BrokerSide::Buy, + quantity: 50, + order_type: BrokerOrderType::Limit(Price(16_000)), + client_order_id: None, + }) + .unwrap(); + let (state, _) = reconstruct_state(&audit_path).unwrap(); + reconcile_incomplete_intents(&broker, &state, &audit_path).unwrap(); + let events = parse_audit_events(&audit_path).unwrap(); + assert_eq!( + events[3..] + .iter() + .map(|e| e.sequence_number.unwrap()) + .collect::>(), + vec![4, 5] + ); + assert_eq!(events[3].event, "order_submitted"); + assert_eq!( + events[3].data.get("symbol").and_then(|v| v.as_str()), + Some("AAPL") + ); + assert_eq!(events[4].event, "order_failed"); + assert_eq!( + events[4].data.get("symbol").and_then(|v| v.as_str()), + Some("MSFT") + ); +} + +#[cfg(feature = "write_ahead_logging")] +#[test] +fn reconcile_appends_failed_when_broker_has_no_open_orders() { + use nanobook_rebalancer::recovery::reconcile_incomplete_intents; + + let dir = tempfile::tempdir().unwrap(); + let audit_path = dir.path().join("audit.jsonl"); + log_run_started_and_intents(&audit_path, dir.path()); + let mut broker = MockBroker::builder() + .fill_mode(FillMode::ImmediateFull) + .build(); + broker.connect().unwrap(); + let (state, _) = reconstruct_state(&audit_path).unwrap(); + reconcile_incomplete_intents(&broker, &state, &audit_path).unwrap(); + let events = parse_audit_events(&audit_path).unwrap(); + assert_eq!( + events[3..] + .iter() + .map(|e| e.sequence_number.unwrap()) + .collect::>(), + vec![4, 5] + ); + assert_eq!(events[3].event, "order_failed"); + assert_eq!(events[4].event, "order_failed"); +} + +#[cfg(feature = "write_ahead_logging")] +struct FailOpenBroker { + calls: std::cell::Cell, +} + +#[cfg(feature = "write_ahead_logging")] +impl Broker for FailOpenBroker { + fn connect(&mut self) -> std::result::Result<(), nanobook_broker::error::BrokerError> { + Ok(()) + } + fn disconnect(&mut self) -> std::result::Result<(), nanobook_broker::error::BrokerError> { + Ok(()) + } + fn positions( + &self, + ) -> std::result::Result< + Vec, + nanobook_broker::error::BrokerError, + > { + Ok(Vec::new()) + } + fn account( + &self, + ) -> std::result::Result + { + Ok(nanobook_broker::types::Account { + equity_cents: 0, + buying_power_cents: 0, + cash_cents: 0, + gross_position_value_cents: 0, + }) + } + fn submit_order( + &self, + _order: &BrokerOrder, + ) -> std::result::Result + { + Ok(nanobook_broker::types::OrderId(1)) + } + fn order_status( + &self, + id: nanobook_broker::types::OrderId, + ) -> std::result::Result< + nanobook_broker::types::BrokerOrderStatus, + nanobook_broker::error::BrokerError, + > { + Ok(nanobook_broker::types::BrokerOrderStatus { + id, + status: nanobook_broker::types::OrderState::Submitted, + filled_quantity: 0, + remaining_quantity: 1, + avg_fill_price_cents: 0, + }) + } + fn open_orders( + &self, + ) -> std::result::Result< + Vec, + nanobook_broker::error::BrokerError, + > { + self.calls.set(self.calls.get() + 1); + Err(nanobook_broker::error::BrokerError::Connection( + "open orders unavailable".into(), + )) + } + fn cancel_order( + &self, + _id: nanobook_broker::types::OrderId, + ) -> std::result::Result<(), nanobook_broker::error::BrokerError> { + Ok(()) + } + fn quote( + &self, + symbol: &Symbol, + ) -> std::result::Result + { + Ok(nanobook_broker::types::Quote { + symbol: *symbol, + bid_cents: 0, + ask_cents: 0, + last_cents: 0, + volume: 0, + timestamp: std::time::SystemTime::now(), + }) + } +} + +#[cfg(feature = "write_ahead_logging")] +#[test] +fn reconcile_incomplete_intents_counts_broker_failures() { + use nanobook_rebalancer::recovery::reconcile_incomplete_intents; + + let dir = tempfile::tempdir().unwrap(); + let audit_path = dir.path().join("audit.jsonl"); + { + let mut log = AuditLog::open_in(&audit_path, dir.path()).unwrap(); + log.log_checkpoint( + nanobook_rebalancer::audit::Checkpoint::RunStarted, + 1, + serde_json::json!({"target": "test"}), + ) + .unwrap(); + log.log_checkpoint( + nanobook_rebalancer::audit::Checkpoint::OrderIntent, + 2, + serde_json::json!({ + "symbol": "AAPL", + "action": "Buy", + "shares": 50, + "limit": 160.0, + "client_order_id": "a", + }), + ) + .unwrap(); + } + let broker = FailOpenBroker { + calls: std::cell::Cell::new(0), + }; + let (state, _) = reconstruct_state(&audit_path).unwrap(); + match reconcile_incomplete_intents(&broker, &state, &audit_path) { + Err(Error::Recovery(m)) => { + assert!(m.contains("Failed to reconcile 1 incomplete intents")); + } + other => panic!("expected Recovery, got {other:?}"), + } + assert_eq!(parse_audit_events(&audit_path).unwrap().len(), 2); + assert_eq!(broker.calls.get(), 5); +} + +#[cfg(feature = "write_ahead_logging")] +#[test] +fn run_recover_reconciles_incomplete_intent() { + let dir = tempfile::tempdir().unwrap(); + let config: Config = toml::from_str(&format!( + r#" +[connection] +host = "127.0.0.1" +port = 4002 +client_id = 1 +[account] +id = "DU1" +type = "cash" +[execution] +[risk] +[cost] +[logging] +dir = "{}" +audit_file = "audit.jsonl" +"#, + dir.path().display() + )) + .unwrap(); + let spec = TargetSpec::from_json( + r#"{ + "timestamp": "2026-02-08T15:30:00Z", + "targets": [{ "symbol": "AAPL", "weight": 0.5 }] + }"#, + ) + .unwrap(); + { + let mut log = AuditLog::open_in(&config.audit_path(), dir.path()).unwrap(); + log.log_checkpoint( + nanobook_rebalancer::audit::Checkpoint::RunStarted, + 1, + serde_json::json!({"target": "test"}), + ) + .unwrap(); + log.log_checkpoint( + nanobook_rebalancer::audit::Checkpoint::OrderIntent, + 2, + serde_json::json!({ + "symbol": "AAPL", + "action": "Buy", + "shares": 50, + "limit": 160.0, + "client_order_id": "c", + }), + ) + .unwrap(); + } + let mut broker = MockBroker::builder().build(); + broker.connect().unwrap(); + run_recover(&config, &spec, true, Some(&broker)).unwrap(); + let events = parse_audit_events(&config.audit_path()).unwrap(); + assert_eq!(events.len(), 3); + let last = events.last().unwrap(); + assert_eq!(last.event, "order_failed"); + assert_eq!( + last.data.get("reason").and_then(|v| v.as_str()), + Some("not_found_at_broker") + ); + assert_eq!( + last.data.get("reconciled").and_then(|v| v.as_bool()), + Some(true) + ); +} diff --git a/rebalancer/tests/run_orchestration.rs b/rebalancer/tests/run_orchestration.rs new file mode 100644 index 0000000..a5cbf87 --- /dev/null +++ b/rebalancer/tests/run_orchestration.rs @@ -0,0 +1,448 @@ +//! S1: run_with_client confirmation, counters, PID file, and min-trade filter. + +use std::cell::RefCell; +use std::time::{Duration, SystemTime}; + +use nanobook::Symbol; +use nanobook_broker::error::BrokerError; +use nanobook_broker::ibkr::orders::{OrderOutcome, OrderResult}; +use nanobook_broker::types::{Account, Position, Quote}; +use nanobook_broker::{BrokerSide, ClientOrderId}; +use nanobook_rebalancer::audit::parse_audit_events; +use nanobook_rebalancer::broker::BrokerGateway; +use nanobook_rebalancer::config::Config; +use nanobook_rebalancer::error::{Error, Result}; +use nanobook_rebalancer::execution::{RunOptions, ShutdownFlag, run_with_client}; +use nanobook_rebalancer::pid_file::DEFAULT_PID_FILE; +use nanobook_rebalancer::target::TargetSpec; + +struct ScriptedBroker { + executes: RefCell>, + cancels: RefCell>, + pid_during_execute: RefCell>, + pid_path: std::path::PathBuf, + shutdown: ShutdownFlag, + shutdown_on_first: bool, + outcomes: Vec, +} + +enum ExecOutcome { + Filled, + Partial { filled: i64, id: i32 }, + Cancelled, + Failed, + Err, +} + +impl ScriptedBroker { + fn new(workdir: &std::path::Path, shutdown: ShutdownFlag, outcomes: Vec) -> Self { + Self { + executes: RefCell::new(Vec::new()), + cancels: RefCell::new(Vec::new()), + pid_during_execute: RefCell::new(None), + pid_path: workdir.join(DEFAULT_PID_FILE), + shutdown, + shutdown_on_first: false, + outcomes, + } + } +} + +impl BrokerGateway for ScriptedBroker { + fn account_summary(&self) -> nanobook_rebalancer::broker::BrokerResult { + Ok(Account { + equity_cents: 100_000_000, + buying_power_cents: 100_000_000, + cash_cents: 100_000_000, + gross_position_value_cents: 0, + }) + } + + fn positions(&self) -> nanobook_rebalancer::broker::BrokerResult> { + Ok(Vec::new()) + } + + fn prices( + &self, + _symbols: &[Symbol], + ) -> nanobook_rebalancer::broker::BrokerResult> { + Ok(Vec::new()) + } + + fn quotes(&self, symbols: &[Symbol]) -> nanobook_rebalancer::broker::BrokerResult> { + Ok(symbols + .iter() + .map(|symbol| { + let (bid, ask, last) = if symbol.as_str() == "PENNY" { + (1_999, 2_001, 2_000) + } else { + (9_999, 10_001, 10_000) + }; + Quote { + symbol: *symbol, + bid_cents: bid, + ask_cents: ask, + last_cents: last, + volume: 0, + timestamp: SystemTime::now(), + } + }) + .collect()) + } + + fn execute_limit_order( + &self, + symbol: Symbol, + side: BrokerSide, + shares: u64, + limit_price_cents: i64, + _client_order_id: Option<&ClientOrderId>, + _timeout: Duration, + ) -> nanobook_rebalancer::broker::BrokerResult { + if let Ok(contents) = std::fs::read_to_string(&self.pid_path) + && let Ok(pid) = contents.trim().parse::() + { + *self.pid_during_execute.borrow_mut() = Some(pid); + } + self.executes.borrow_mut().push(( + symbol.as_str().to_string(), + side, + shares, + limit_price_cents, + )); + let index = self.executes.borrow().len() - 1; + if self.shutdown_on_first { + self.shutdown.request_shutdown(); + } + let outcome = self.outcomes.get(index).unwrap_or(&ExecOutcome::Filled); + match outcome { + ExecOutcome::Filled => Ok(OrderResult { + symbol, + order_id: (index as i32) + 1, + filled_shares: shares as i64, + avg_fill_price: limit_price_cents as f64 / 100.0, + commission: 0.0, + status: OrderOutcome::Filled, + }), + ExecOutcome::Partial { filled, id } => Ok(OrderResult { + symbol, + order_id: *id, + filled_shares: *filled, + avg_fill_price: limit_price_cents as f64 / 100.0, + commission: 0.0, + status: OrderOutcome::PartialFill, + }), + ExecOutcome::Cancelled => Ok(OrderResult { + symbol, + order_id: 30, + filled_shares: 0, + avg_fill_price: 0.0, + commission: 0.0, + status: OrderOutcome::Cancelled, + }), + ExecOutcome::Failed => Ok(OrderResult { + symbol, + order_id: 40, + filled_shares: 0, + avg_fill_price: 0.0, + commission: 0.0, + status: OrderOutcome::Failed, + }), + ExecOutcome::Err => Err(BrokerError::Order("rej".into())), + } + } + + fn cancel_order(&self, order_id: u64) -> nanobook_rebalancer::broker::BrokerResult<()> { + self.cancels.borrow_mut().push(order_id); + Ok(()) + } +} + +fn config(workdir: &std::path::Path) -> Config { + toml::from_str(&format!( + r#" +[connection] +host = "127.0.0.1" +port = 4002 +client_id = 1 +[account] +id = "DU1" +type = "cash" +[execution] +order_interval_ms = 0 +limit_offset_bps = 5 +order_timeout_secs = 1 +max_orders_per_run = 50 +quote_staleness_threshold_sec = 30 +[risk] +max_position_pct = 1.0 +max_leverage = 2.0 +min_trade_usd = 100.0 +max_trade_usd = 1000000.0 +allow_short = true +max_short_pct = 1.0 +[cost] +[logging] +dir = "{}" +audit_file = "audit.jsonl" +"#, + workdir.join("logs").display() + )) + .unwrap() +} + +fn spec_seven() -> TargetSpec { + TargetSpec::from_json( + r#"{ + "timestamp": "2026-02-08T15:30:00Z", + "targets": [ + { "symbol": "T1", "weight": 0.1 }, + { "symbol": "T2", "weight": 0.1 }, + { "symbol": "T3", "weight": 0.1 }, + { "symbol": "T4", "weight": 0.1 }, + { "symbol": "T5", "weight": 0.1 }, + { "symbol": "T6", "weight": 0.1 }, + { "symbol": "PENNY", "weight": 0.00008 } + ] + }"#, + ) + .unwrap() +} + +fn spec_three() -> TargetSpec { + TargetSpec::from_json( + r#"{ + "timestamp": "2026-02-08T15:30:00Z", + "targets": [ + { "symbol": "T1", "weight": 0.1 }, + { "symbol": "T2", "weight": 0.1 }, + { "symbol": "T3", "weight": 0.1 } + ] + }"#, + ) + .unwrap() +} + +fn opts(force: bool, dry_run: bool, cron_mode: bool) -> RunOptions { + RunOptions { + dry_run, + force, + target_file: "t.json".into(), + cron_mode, + } +} + +fn t1_outcomes() -> Vec { + vec![ + ExecOutcome::Filled, + ExecOutcome::Partial { + filled: 400, + id: 22, + }, + ExecOutcome::Cancelled, + ExecOutcome::Failed, + ExecOutcome::Err, + ExecOutcome::Filled, + ] +} + +fn assert_six_buys(executes: &[(String, BrokerSide, u64, i64)]) { + assert_eq!(executes.len(), 6); + for (i, (symbol, side, shares, limit)) in executes.iter().enumerate() { + assert_eq!(symbol, &format!("T{}", i + 1)); + assert_eq!(*side, BrokerSide::Buy); + assert_eq!(*shares, 1000); + assert_eq!(*limit, 10_005); + } +} + +fn completed_counts(path: &std::path::Path, event: &str) -> (u64, u64, u64) { + let events = parse_audit_events(path).unwrap(); + let e = events.iter().find(|ev| ev.event == event).unwrap(); + ( + e.data.get("submitted").and_then(|v| v.as_u64()).unwrap(), + e.data.get("filled").and_then(|v| v.as_u64()).unwrap(), + e.data.get("failed").and_then(|v| v.as_u64()).unwrap(), + ) +} + +#[test] +fn force_cron_places_six_orders_and_skips_penny() { + let dir = tempfile::tempdir().unwrap(); + let config = config(dir.path()); + let spec = spec_seven(); + let shutdown = ShutdownFlag::new(); + let broker = ScriptedBroker::new(dir.path(), shutdown.clone(), t1_outcomes()); + let mut confirm = || -> Result { panic!("confirm must not be called") }; + run_with_client( + &config, + &spec, + &opts(true, false, true), + &broker, + &shutdown, + dir.path(), + &mut confirm, + ) + .unwrap(); + assert_six_buys(&broker.executes.borrow()); + assert!( + !broker + .executes + .borrow() + .iter() + .any(|(s, _, _, _)| s == "PENNY") + ); + assert_eq!( + broker.pid_during_execute.borrow().as_ref(), + Some(&std::process::id()) + ); + assert!(!dir.path().join(DEFAULT_PID_FILE).exists()); + let audit = config.audit_path(); + assert_eq!(completed_counts(&audit, "run_completed"), (6, 3, 3)); + assert_eq!(completed_counts(&audit, "cron_completed"), (6, 3, 3)); +} + +#[test] +fn confirm_yes_places_orders() { + let dir = tempfile::tempdir().unwrap(); + let config = config(dir.path()); + let spec = spec_seven(); + let shutdown = ShutdownFlag::new(); + let broker = ScriptedBroker::new(dir.path(), shutdown.clone(), t1_outcomes()); + let mut calls = 0; + let mut confirm = || { + calls += 1; + Ok(true) + }; + run_with_client( + &config, + &spec, + &opts(false, false, false), + &broker, + &shutdown, + dir.path(), + &mut confirm, + ) + .unwrap(); + assert_eq!(calls, 1); + assert_eq!(broker.executes.borrow().len(), 6); + let events = parse_audit_events(&config.audit_path()).unwrap(); + let confirmed = events.iter().find(|e| e.event == "user_confirmed").unwrap(); + assert_eq!( + confirmed.data.get("approved").and_then(|v| v.as_bool()), + Some(true) + ); +} + +#[test] +fn confirm_no_places_no_orders() { + let dir = tempfile::tempdir().unwrap(); + let config = config(dir.path()); + let spec = spec_seven(); + let shutdown = ShutdownFlag::new(); + let broker = ScriptedBroker::new(dir.path(), shutdown.clone(), t1_outcomes()); + let mut confirm = || Ok(false); + run_with_client( + &config, + &spec, + &opts(false, false, false), + &broker, + &shutdown, + dir.path(), + &mut confirm, + ) + .unwrap(); + assert!(broker.executes.borrow().is_empty()); + let events = parse_audit_events(&config.audit_path()).unwrap(); + let confirmed = events.iter().find(|e| e.event == "user_confirmed").unwrap(); + assert_eq!( + confirmed.data.get("approved").and_then(|v| v.as_bool()), + Some(false) + ); +} + +#[test] +fn dry_run_places_no_orders_and_skips_confirm() { + let dir = tempfile::tempdir().unwrap(); + let config = config(dir.path()); + let spec = spec_seven(); + let shutdown = ShutdownFlag::new(); + let broker = ScriptedBroker::new(dir.path(), shutdown.clone(), t1_outcomes()); + let mut confirm = || -> Result { panic!("confirm must not be called") }; + run_with_client( + &config, + &spec, + &opts(false, true, false), + &broker, + &shutdown, + dir.path(), + &mut confirm, + ) + .unwrap(); + assert!(broker.executes.borrow().is_empty()); +} + +#[test] +fn shutdown_after_partial_cancels_current_and_skips_rest() { + let dir = tempfile::tempdir().unwrap(); + let config = config(dir.path()); + let spec = spec_three(); + let shutdown = ShutdownFlag::new(); + let mut broker = ScriptedBroker::new( + dir.path(), + shutdown.clone(), + vec![ExecOutcome::Partial { + filled: 400, + id: 55, + }], + ); + broker.shutdown_on_first = true; + let mut confirm = || Ok(true); + run_with_client( + &config, + &spec, + &opts(true, false, false), + &broker, + &shutdown, + dir.path(), + &mut confirm, + ) + .unwrap(); + assert_eq!(broker.executes.borrow().len(), 1); + assert_eq!(*broker.cancels.borrow(), vec![55]); + let events = parse_audit_events(&config.audit_path()).unwrap(); + let kill = events.iter().find(|e| e.event == "kill_completed").unwrap(); + assert_eq!( + kill.data.get("method").and_then(|v| v.as_str()), + Some("graceful") + ); + assert_eq!( + kill.data + .get("orders_cancelled_count") + .and_then(|v| v.as_u64()), + Some(3) + ); +} + +#[test] +fn confirm_error_is_aborted() { + let dir = tempfile::tempdir().unwrap(); + let config = config(dir.path()); + let spec = spec_seven(); + let shutdown = ShutdownFlag::new(); + let broker = ScriptedBroker::new(dir.path(), shutdown.clone(), t1_outcomes()); + let mut confirm = || Err(Error::Aborted("prompt failed".into())); + match run_with_client( + &config, + &spec, + &opts(false, false, false), + &broker, + &shutdown, + dir.path(), + &mut confirm, + ) { + Err(Error::Aborted(m)) => assert!(m.contains("prompt failed")), + other => panic!("expected Aborted, got {other:?}"), + } + assert!(broker.executes.borrow().is_empty()); +} diff --git a/rebalancer/tests/write_ahead_integration.rs b/rebalancer/tests/write_ahead_integration.rs index bbda3ab..289c9c7 100644 --- a/rebalancer/tests/write_ahead_integration.rs +++ b/rebalancer/tests/write_ahead_integration.rs @@ -9,6 +9,7 @@ use nanobook_broker::{BrokerSide, ClientOrderId}; use nanobook_rebalancer::audit::{AuditLog, parse_audit_events}; use nanobook_rebalancer::broker::BrokerGateway; use nanobook_rebalancer::diff::{Action, RebalanceOrder}; +use nanobook_rebalancer::error::Error; use nanobook_rebalancer::execution::execute_order_with_write_ahead; use std::time::Duration; @@ -224,8 +225,18 @@ fn test_write_ahead_transient_error_classification() { ); assert!(result.is_err()); - // Should have attempted retries (call count > 1) - assert!(broker.call_count() > 1); + assert_eq!(broker.call_count(), 5); + match result { + Err(Error::Order(m)) => assert!(m.contains("after 5 retries")), + other => panic!("expected Order, got {other:?}"), + } + let events = parse_audit_events(&audit_path).unwrap(); + let last = events.last().unwrap(); + assert_eq!(last.event, "order_failed"); + assert_eq!( + last.data.get("error_type").and_then(|v| v.as_str()), + Some("max_retries_exceeded") + ); } } From 83b69fbcb9411d02de8f201b5e1c5c835f539473 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 12:57:24 +0100 Subject: [PATCH 14/66] docs(changelog): rebalancer fixes and known issues for 0.20.0 Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- CHANGELOG.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 83c99a7..57feda5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -95,6 +95,12 @@ tests, fuzzing or mutation testing. (ITCH 5.0 offset 11). Found by mutation testing. - The OCaml reference oracle mishandled a cancel after a partial fill and could hang on corpus case 21; CI now has a 60 s timeout per corpus case. +- **nanobook-rebalancer: closing a long sold above mid.** Closing a long now uses mid minus offset. Closing a short now uses mid plus offset. +- **nanobook-rebalancer: `Error::Aborted` exited with code 0.** Kill-switch failures and a failed confirm prompt now exit with code 3. A risk failure still exits with code 2. +- **nanobook-rebalancer: recovery and kill read audit `limit` as cents.** The writers store dollars. A 160.25 limit now reconstructs as 16025 cents. +- **nanobook-rebalancer: the runner did not write `rebalancer.pid`.** `run` now writes the PID file at start and removes it on every exit path. +- **nanobook-rebalancer: the close loop sent a limit-0 order when the quote was 0.** It now skips that symbol. +- **nanobook-rebalancer: recovery matched the first open order with remaining quantity.** It now matches remaining quantity of the incomplete intent. ### Added @@ -106,6 +112,14 @@ tests, fuzzing or mutation testing. - **Lean verification.** The Lean model, proofs and replay tools (`verification/lean/`), the corpus generator (`examples/corpus_gen.rs`), the Rust-versus-Lean replay (`verification/lean/differential.sh`), and golden corpus cases 19 to 25. +- **nanobook-rebalancer `run_with_client`.** The run path now accepts an injected broker and confirm callback. Tests cover confirmation, `--force`, and PID-file lifetime. +- **nanobook-rebalancer tests for mutation groups G1 to G31, seams S1 and S2, and gated paths T1 and T2.** + +### Known issues + +- **nanobook-rebalancer: `constraints.min_trade_usd` in target.json does not change the run minimum.** The run still reads `config.risk.min_trade_usd`. +- **nanobook-rebalancer: `TargetSpec::window_id` hashes with `DefaultHasher`.** The id can change after a Rust upgrade, so a cron window can fire twice. +- **nanobook-rebalancer: without `write_ahead_logging`, the runner does not write `order_submitted`.** Graceful kill then cannot report a dangling order. ### Security From 9ab3ee81257398ed21d0546ce8c1349547e8c08d Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:01:56 +0100 Subject: [PATCH 15/66] docs: a five-scene tour of nanobook, run in CI python/examples/tour.py runs offline in under a second: a weights-to- backtest run with and without costs, the order book's fill-or-kill and IOC behaviour, risk checks failing a 1.85x leverage batch and a short, the orders a rebalance places, and the eleven proved matching laws. test_tour.py runs it and checks its key numbers, so CI keeps it working. --figure draws assets/tour-equity.png (synthetic prices). Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- assets/tour-equity.png | Bin 0 -> 290606 bytes python/examples/tour.py | 353 ++++++++++++++++++++++++++++++++++++++ python/tests/test_tour.py | 100 +++++++++++ 3 files changed, 453 insertions(+) create mode 100644 assets/tour-equity.png create mode 100644 python/examples/tour.py create mode 100644 python/tests/test_tour.py diff --git a/assets/tour-equity.png b/assets/tour-equity.png new file mode 100644 index 0000000000000000000000000000000000000000..8cec1b660185abb6b8bcf75ea54f58787790c3d6 GIT binary patch literal 290606 zcmeFZcUaWdw>^w4CN^ROQBX)?1t|&w(vuiLrAhCgAieiGV2PqAUzyocVGIjaoh3sGLM}AXLnpk$1^N#+R<_Lx8oQdfrsN%ae{#oJ z^6CHcpWNTSH2(BI|APFPwr86gp67r4!}sbM%m4Zd28M~>|L@oS*OL6-g8Z-L_`ehK zer=VpE^D3I@8xps{qCOUdSRPViM z0J}tdn22MG_%V~putD;&kS}kp6v#DdQI=*VowXUfMrfVh0(nB>O9N4Kg|dF#W?mLv z-AfVT?p8tJC$HS_6+lIJKYF~0q|OIVDNBQ~EpJV$X4j{`RV1vfE-#-vR7_c!EVihL zE}dOJCim>cSbNTJgy-1g6?H7gM9dM{pw}8H`l5DS*HTnAtaPy1=Ds|kk*vF(@4dR@ zfmiBT2pleVmF+eY~2Anc3@vge|{r&vqJo6vStcoNn1@(O(%Z>hSeWWrRe+!h%~2mCB_U zA?|nozAD{ok-S#W?8_gs!;KoZwlQPDyM|{rFxZ89Elv%FyLMDx+psCQ7!MMAEW+(C z_vvr5S4{9VN-XwWM@e85vG4ik_O62#d)Us{y_ou1+8g>$nA7^|e8RbVdmGnGQ^+T^zy+kv?l# zIt~^s@8aS{`y+ii96CZ}%%l5~V~XpK{SW$kI<$>xp8;c{anE@&CV?*4T*GneXlMe)ghr2ScA^4FGRb6iGiZf$3I^5DUXuV1g8J9o}} zydzKht%-k8AV&(XUiNF{n2TI0)cd!0vQbrH6|#8vurQ7I)5{lDS_4B_+M+!eI#(4Ft_ zOewJ5fBWS)eOcitms-t4cY*V_^8K;X7cX9{iC0UQ8Os@uS5MMzd1wB(&+Dx3E;R(E z+$62TL$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zD*)*~wl%<;6+q5Nic6j-8efPYJ-dK5I#6v{vN7sf-aXCI z;-SI)+PtYt*>zlfvPgPTCOdel+|p$`Mgprm-m z0Mevl)C#(e_8>?k-wh`@8Tto`qF2N=q|!H56YSZBRd0t+SRWCpwm+FX)|YNM|LSI3 yb>io#VEynvU(K!=h4P=3_|HoGf9!&;nK|Qn!%ip56b#8)$sJXaO*(S+`u_vvAVzfn literal 0 HcmV?d00001 diff --git a/python/examples/tour.py b/python/examples/tour.py new file mode 100644 index 0000000..03c4624 --- /dev/null +++ b/python/examples/tour.py @@ -0,0 +1,353 @@ +"""A five-scene tour of nanobook: what it does, and why its matching rules can be trusted. + +Offline, no API keys, plain printed output, under 10 s. + +Run from the python/ directory: + + uv run python examples/tour.py # print the five scenes + uv run --with matplotlib python examples/tour.py --figure + # also save assets/tour-equity.png + +Scenes: + 1. Target weights to a backtest, with and without trading costs. + 2. The order book: crossing orders, a rejected fill-or-kill, an IOC that reads Cancelled. + 3. Pre-trade risk checks on an order batch and on a short sale. + 4. The orders a rebalance makes, read from the backtest's execution records. + 5. The eleven matching laws proved in Lean, and the command that rechecks them. +""" + +import time + +_T0 = time.perf_counter() # measured from before the nanobook import + +import math +import random +import sys +import textwrap +from pathlib import Path + +import nanobook as nb + +SYMBOLS = ("AAA", "BBB", "CCC") +START_PRICES_USD = (100.0, 50.0, 200.0) +N_DAYS = 252 +REBALANCE_EVERY = 21 # trading days, about one month +INITIAL_CASH_CENTS = 1_000_000_00 +SEED = 20261114 +COSTS = dict(commission_bps=10.0, slippage_bps=5.0) + +# Plain-language statements, copied from VERIFICATION.md (python/tests/test_tour.py checks they still match). +LAWS = [ + "Bids descend, asks ascend, no level is empty, each queued id is one active order at that price, and each active order is queued exactly once.", + "The best bid is strictly below the best ask.", + "Trades of a submit sum to its filled quantity, which does not exceed the submit; each trade takes exactly its size off the resting order.", + "A submit trades resting orders in price-time order. An order skipped before the last trade was cancelled by self-trade prevention.", + "Every trade prints at the resting level's price, at or inside the incoming limit.", + "The matching loop's step bound is always enough: more steps never change the result.", + "A fill-or-kill submit trades its whole quantity, or trades nothing and leaves every order and level unchanged.", + "Each self-trade policy does exactly what `src/matching.rs` documents. With any policy other than `Off`, no trade has the same owner on both sides.", + "A cancel changes only the cancelled order and drops only it from its level. Cancelling a missing or finished order changes nothing.", + "The tombstone queue always holds the same live orders, in the same order, as the plain lists. Every stored position points at its own order, and the totals and tombstone counts are exact.", + "A submitted order's stored record matches its status: filled means fully filled; resting means filled plus remaining equals the submit; cancelled means nothing remains; no record means a rejected fill-or-kill with no trades.", +] + + +def usd(cents): + return f"${cents / 100:,.2f}" + + +def heading(n, title, what): + print() + print(f"=== Scene {n}: {title} ===") + print(what) + print() + + +# --------------------------------------------------------------------------- scene 1 + + +def make_bars(seed=SEED): + """Daily bars (cents) for three symbols: geometric random walks from a fixed seed.""" + rng = random.Random(seed) + + def normal(): # Box-Muller from random(), whose stream is fixed across Python versions + return math.sqrt(-2.0 * math.log(1.0 - rng.random())) * math.cos(2.0 * math.pi * rng.random()) + + closes = [[p * 100.0] for p in START_PRICES_USD] + bars = [] # bars[t][i] = BarPrices + for _ in range(N_DAYS): + day = [] + for i in range(len(SYMBOLS)): + prev = closes[i][-1] + op = prev * (1.0 + 0.002 * normal()) + cl = op * math.exp(0.0004 + 0.012 * normal()) + hi = max(op, cl) * (1.0 + 0.003 * abs(normal())) + lo = min(op, cl) * (1.0 - 0.003 * abs(normal())) + closes[i].append(cl) + day.append(nb.BarPrices(round(op), round(hi), round(lo), round(cl))) + bars.append(day) + return bars + + +def inverse_vol_weights(bars, t): + """Weights proportional to 1 / volatility of the last 20 daily closes, summing to 1.""" + inv = [] + for i in range(len(SYMBOLS)): + c = [bars[k][i].close for k in range(t - 20, t + 1)] + r = [c[k + 1] / c[k] - 1.0 for k in range(20)] + m = sum(r) / len(r) + sd = math.sqrt(sum((x - m) ** 2 for x in r) / (len(r) - 1)) + inv.append(1.0 / sd) + s = sum(inv) + return [w / s for w in inv] + + +def build_schedules(bars): + """Return (weights, prices, fills) per period. Rebalance every 21 days, filled at the next bar's open. + + On days without a rebalance the fill entry is empty, which the engine reads as "no fill". + """ + weights, prices, fills = [], [], [] + current = [1.0 / len(SYMBOLS)] * len(SYMBOLS) + for t in range(N_DAYS): + rebalance = t % REBALANCE_EVERY == 0 + if rebalance and t > 0: + current = inverse_vol_weights(bars, t) + weights.append(list(zip(SYMBOLS, current))) + prices.append(list(zip(SYMBOLS, bars[t]))) + fills.append(list(zip(SYMBOLS, bars[t + 1])) if rebalance and t + 1 < N_DAYS else []) + return weights, prices, fills + + +def run_backtest(schedules, cost_model): + weights, prices, fills = schedules + t0 = time.perf_counter() + result = nb.backtest_weights( + weights, + prices, + INITIAL_CASH_CENTS, + cost_model, + nb.FillPolicy.NextBarOpen, + 252.0, + 0.0, + fill_schedule=fills, + record_executions=True, + ) + ms = (time.perf_counter() - t0) * 1e3 + return result, ms + + +def scene1(): + heading( + 1, + "From weights to a backtest", + f"{len(SYMBOLS)} synthetic stocks, {N_DAYS} daily bars (seed {SEED}), inverse-volatility weights,\n" + f"rebalanced every {REBALANCE_EVERY} days at the next bar's open, " + f"{COSTS['commission_bps']:.0f} bps commission + {COSTS['slippage_bps']:.0f} bps slippage.", + ) + schedules = build_schedules(make_bars()) + net, net_ms = run_backtest(schedules, nb.CostModel(**COSTS)) + gross, gross_ms = run_backtest(schedules, nb.CostModel.zero()) + + out = {"net": net, "gross": gross, "net_ms": net_ms, "gross_ms": gross_ms} + for label, res, ms in (("with costs", net, net_ms), ("zero cost", gross, gross_ms)): + m = res["metrics"] + print(f"{label}:") + print(f" final equity {usd(res['equity_curve'][-1])} (start {usd(INITIAL_CASH_CENTS)})") + print(f" CAGR {m.cagr * 100:.2f} %") + print(f" Sharpe {m.sharpe:.2f}") + print(f" max drawdown {m.max_drawdown * 100:.2f} %") + print(f" executions {len(res['executions'])}") + print(f" backtest time {ms:.2f} ms") + cost = gross["equity_curve"][-1] - net["equity_curve"][-1] + print(f"cost effect: trading costs took {usd(cost)} of final equity.") + out["cost_cents"] = cost + return out + + +# --------------------------------------------------------------------------- scene 2 + + +def book_state(ex): + depth = ex.depth(10) + return ( + ex.best_bid_ask(), + [(l.price, l.quantity) for l in depth.bids], + [(l.price, l.quantity) for l in depth.asks], + ) + + +def fmt_bba(bba): + bid, ask = bba + f = lambda p: "none" if p is None else usd(p) + return f"best bid {f(bid)} / best ask {f(ask)}" + + +def scene2(): + heading( + 2, + "The order book does the right thing", + "Rest orders, cross them, then two cases the Lean proofs cover (laws 7 and 11).", + ) + ex = nb.Exchange() + ex.submit_limit("sell", 10100, 50) + ex.submit_limit("sell", 10200, 50) + ex.submit_limit("buy", 9900, 100) + print("resting: sell 50 @ $101.00, sell 50 @ $102.00, buy 100 @ $99.00") + print(f" {fmt_bba(ex.best_bid_ask())}") + + cross = ex.submit_limit("buy", 10200, 80) + print("buy 80 @ $102.00 crosses the asks:") + for tr in cross.trades: + print(f" trade {tr.quantity} @ {usd(tr.price)} (aggressor: {tr.aggressor_side})") + print(f" order status {cross.status}; {fmt_bba(ex.best_bid_ask())}; ask left at $102.00: " + f"{ex.depth(1).asks[0].quantity}") + + before = book_state(ex) + fok = ex.submit_limit("buy", 10200, 100, "fok") + after = book_state(ex) + print("fill-or-kill buy 100 @ $102.00, only 20 are available:") + print(f" result {fok.status}, filled {fok.filled_quantity}, trades {len(fok.trades)}") + print(f" before: {fmt_bba(before[0])}") + print(f" after: {fmt_bba(after[0])}") + print(f" book unchanged: {before == after}; stored record: {ex.get_order(fok.order_id)}") + + ioc = ex.submit_limit("buy", 10200, 100, "ioc") + order = ex.get_order(ioc.order_id) + print("immediate-or-cancel buy 100 @ $102.00, 20 fill and the rest cannot rest:") + print(f" result {ioc.status}: filled {ioc.filled_quantity}, cancelled {ioc.cancelled_quantity}") + print(f" get_order -> status {order.status!r}, filled {order.filled_quantity}, remaining {order.remaining_quantity}") + return { + "cross_trades": [(tr.price, tr.quantity) for tr in cross.trades], + "fok_status": fok.status, + "fok_filled": fok.filled_quantity, + "book_unchanged": before == after, + "fok_record": ex.get_order(fok.order_id), + "ioc_order_status": order.status, + "ioc_filled": order.filled_quantity, + "ioc_remaining": order.remaining_quantity, + } + + +# --------------------------------------------------------------------------- scene 3 + + +def print_report(title, report): + print(title) + for c in report: + print(f" {c['status']:<4} {c['name']:<18} {c['detail']}") + + +def scene3(): + heading( + 3, + "Risk checks stop bad orders", + "RiskEngine(allow_short=False, max_leverage=1.5, max_position_pct=1.0), equity $100,000.00.", + ) + equity = 10_000_000 + risk = nb.RiskEngine(max_leverage=1.5, max_position_pct=1.0, allow_short=False) + + ok = risk.check_batch( + [("AAA", "buy", 300, 10_000), ("BBB", "buy", 400, 10_000)], + equity, [], [("AAA", 0.30), ("BBB", 0.40)], + ) + print_report("batch A: buy $30,000 AAA + $40,000 BBB (0.70x):", ok) + + bad = risk.check_batch( + [("AAA", "buy", 900, 10_000), ("BBB", "buy", 950, 10_000)], + equity, [], [("AAA", 0.90), ("BBB", 0.95)], + ) + print_report("batch B: buy $90,000 AAA + $95,000 BBB (1.85x):", bad) + + short = risk.check_order("CCC", "sell", 10, 5000, equity, []) + print_report("order C: sell 10 CCC @ $50.00 while holding none (a short):", short) + + return {"ok": ok, "bad": bad, "short": short} + + +# --------------------------------------------------------------------------- scene 4 + + +def scene4(net): + heading( + 4, + "What a rebalance does, without a broker", + "The orders the portfolio rebalance placed, read from the backtest's execution records\n" + "(record_executions=True). No network, no broker object.", + ) + ex = net["executions"] + periods = sorted({e["period_index"] for e in ex})[:2] + for p in periods: + label = "first rebalance" if p == periods[0] else "second rebalance (the change from drifted holdings)" + print(f"period {p}, {label}:") + for e in ex: + if e["period_index"] == p: + print(f" {e['side']:<4} {abs(e['quantity']) / 1e6:>9.4f} {e['symbol']} @ {usd(e['price'])}" + f" notional {usd(e['notional'])} cost {usd(e['cost'])}") + return {"periods": periods, "first": [e for e in ex if e["period_index"] == periods[0]]} + + +# --------------------------------------------------------------------------- scene 5 + + +def scene5(): + heading( + 5, + "Proof, not promises", + "Eleven laws of the matching engine are proved in Lean 4 on an executable model;\n" + "CI replays the same event logs through the Rust engine and the model and compares trades.", + ) + for n, text in enumerate(LAWS, 1): + print(textwrap.fill(text, width=100, initial_indent=f" law {n:>2}: ", subsequent_indent=" " * 11)) + print() + print("recheck the proofs yourself, from the repository root:") + print(" verification/lean/check.sh 0") + print("mutation score: see VERIFICATION.md") # placeholder until the 0.20.0 score is final + + +# --------------------------------------------------------------------------- figure + + +def save_figure(s1): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + import matplotlib.ticker + + path = Path(__file__).resolve().parents[2] / "assets" / "tour-equity.png" + gross = [c / 100 for c in s1["gross"]["equity_curve"]] + net = [c / 100 for c in s1["net"]["equity_curve"]] + days = list(range(len(net))) + fig, ax = plt.subplots(figsize=(7, 4.2)) + ax.plot(days, gross, marker="o", markersize=4, markevery=12, linewidth=4.0, color="tab:blue", + label=f"gross of costs ({s1['gross_ms']:.2f} ms)") + ax.plot(days, net, marker="s", markersize=4, markevery=(6, 12), linewidth=1.6, color="tab:orange", + label=f"net of costs ({s1['net_ms']:.2f} ms)") + ax.set_xlabel("trading day") + ax.yaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(lambda v, _: f"{v:,.0f}")) + ax.set_ylabel("equity (USD)") + ax.set_title("(a) equity, net vs gross of costs (SYNTHETIC prices, seeded)", loc="left", fontsize=10) + ax.legend(frameon=True) + ax.grid(alpha=0.3) + fig.tight_layout() + path.parent.mkdir(exist_ok=True) + fig.savefig(path, dpi=400) + plt.close(fig) + print(f"\nfigure saved: {path}") + + +def main(argv=None): + argv = sys.argv[1:] if argv is None else argv + s1 = scene1() + scene2() + scene3() + scene4(s1["net"]) + scene5() + if "--figure" in argv: + save_figure(s1) + print(f"\ntour finished in {time.perf_counter() - _T0:.2f} s (includes import)") + + +if __name__ == "__main__": + main() diff --git a/python/tests/test_tour.py b/python/tests/test_tour.py new file mode 100644 index 0000000..e9f8be3 --- /dev/null +++ b/python/tests/test_tour.py @@ -0,0 +1,100 @@ +"""Run examples/tour.py as a newcomer would and check its key printed numbers.""" + +import re +import subprocess +import sys +from pathlib import Path + +import pytest + +PYTHON_DIR = Path(__file__).resolve().parents[1] +TOUR = PYTHON_DIR / "examples" / "tour.py" +VERIFICATION = PYTHON_DIR.parent / "VERIFICATION.md" + + +@pytest.fixture(scope="module") +def output(): + proc = subprocess.run( + [sys.executable, str(TOUR)], capture_output=True, text=True, timeout=60, check=True + ) + return proc.stdout + + +def money(text): + return float(text.replace("$", "").replace(",", "")) + + +def scene(output, n): + parts = re.split(r"^=== Scene (\d): .* ===$", output, flags=re.M) + return dict(zip(parts[1::2], parts[2::2]))[str(n)] + + +def test_five_scenes_and_runtime(output): + assert re.findall(r"^=== Scene (\d):", output, flags=re.M) == ["1", "2", "3", "4", "5"] + seconds = float(re.search(r"tour finished in ([\d.]+) s", output).group(1)) + assert seconds < 10.0 + + +def test_scene1_backtest_numbers(output): + s = scene(output, 1) + net, gross = re.search(r"with costs:(.*?)zero cost:(.*)", s, flags=re.S).groups() + net_eq = money(re.search(r"final equity\s+(\$[\d,.]+)", net).group(1)) + gross_eq = money(re.search(r"final equity\s+(\$[\d,.]+)", gross).group(1)) + assert net_eq == pytest.approx(1_127_584.21, rel=1e-4) + assert gross_eq == pytest.approx(1_131_767.05, rel=1e-4) + assert gross_eq > net_eq # costs reduce final equity + assert float(re.search(r"Sharpe\s+([\d.-]+)", net).group(1)) == pytest.approx(1.22, abs=0.02) + assert float(re.search(r"CAGR\s+([\d.-]+) %", net).group(1)) == pytest.approx(12.76, abs=0.1) + assert float(re.search(r"max drawdown\s+([\d.]+) %", net).group(1)) == pytest.approx(9.88, abs=0.1) + assert int(re.search(r"executions\s+(\d+)", net).group(1)) == 31 + assert float(re.search(r"backtest time\s+([\d.]+) ms", net).group(1)) > 0.0 + cost = money(re.search(r"took (\$[\d,.]+) of final equity", s).group(1)) + assert cost == pytest.approx(gross_eq - net_eq, abs=0.02) + + +def test_scene2_order_book(output): + s = scene(output, 2) + assert "trade 50 @ $101.00 (aggressor: buy)" in s + assert "trade 30 @ $102.00 (aggressor: buy)" in s + assert "result Cancelled, filled 0, trades 0" in s + assert "book unchanged: True; stored record: None" in s + before = re.search(r"before: (.*)", s).group(1) + after = re.search(r"after: (.*)", s).group(1) + assert before == after == "best bid $99.00 / best ask $102.00" + assert "result PartiallyFilled: filled 20, cancelled 80" in s + assert "status 'cancelled', filled 20, remaining 0" in s + + +def test_scene3_risk_checks(output): + s = scene(output, 3) + batch_a, rest = s.split("batch B:") + batch_b, order_c = rest.split("order C:") + assert "FAIL" not in batch_a + assert re.search(r"FAIL\s+Leverage\s+1\.85x > 1\.50x limit", batch_b) + assert re.search(r"PASS\s+Short exposure", batch_b) + assert re.search(r"FAIL\s+Short selling\s+short selling not allowed", order_c) + + +def test_scene4_first_rebalance_orders(output): + s = scene(output, 4) + first = s.split("period 21")[0] + lines = re.findall(r"^\s+(buy|sell)\s+([\d.]+) (\w+) @ (\$[\d,.]+)\s+notional (\$[\d,.]+)", first, flags=re.M) + assert [l[2] for l in lines] == ["AAA", "BBB", "CCC"] + assert all(l[0] == "buy" for l in lines) # starting from cash + total = sum(money(l[4]) for l in lines) + assert total == pytest.approx(1_000_000.0, rel=0.01) # three roughly equal thirds of the cash + assert "period 21" in s + + +def test_scene5_laws_match_verification_md(output): + s = scene(output, 5) + assert len(re.findall(r"^\s+law\s+\d+:", s, flags=re.M)) == 11 + assert "verification/lean/check.sh 0" in s + assert "mutation score: see VERIFICATION.md" in s + if not VERIFICATION.exists(): + pytest.skip("VERIFICATION.md not next to python/ (installed layout)") + table = re.findall(r"^\| (\d+) \| (.*?) \| `", VERIFICATION.read_text(), flags=re.M) + assert len(table) == 11 + flat = " ".join(s.split()) + for _, statement in table: + assert " ".join(statement.split()) in flat From 74e753325e4483888c9229e5a8d554c8e6063d5e Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:01:56 +0100 Subject: [PATCH 16/66] docs(readme): 'See it work' section with the tour's real output and chart Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- README.md | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/README.md b/README.md index 5e34043..beaa405 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,57 @@ 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 +``` + +

+ Equity of the tour backtest, gross and net of trading costs +

+ ## Matching rules proved in Lean The matching engine at the heart of nanobook comes with machine-checked proofs. From 16dbbd006cb75a2341dec51150f8aa0254cafe75 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:03:13 +0100 Subject: [PATCH 17/66] docs: a 'check every claim yourself' table with the real 0.20.0 outputs SECURITY.md lists each safety claim with the command that checks it and the output we got: no unsafe code, one runtime dependency, cargo deny and cargo audit clean, the Lean laws and kernel check, zero Rust-versus- Lean mismatches in 1000 seeds, the tour, release attestations, and the mutation tests. VERIFICATION.md links to it. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- SECURITY.md | 17 +++++++++++++++++ VERIFICATION.md | 5 +++++ 2 files changed, 22 insertions(+) diff --git a/SECURITY.md b/SECURITY.md index 666186b..812227b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -20,6 +20,23 @@ GitHub security advisory once it is ready, crediting you unless you ask otherwis 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 --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. diff --git a/VERIFICATION.md b/VERIFICATION.md index c1e5a12..2eaa1a9 100644 --- a/VERIFICATION.md +++ b/VERIFICATION.md @@ -158,6 +158,11 @@ up this way, so the statements are reviewed by people as well. - The bridge between Rust and the model is testing (corpus and random replay), not proof. +## Check every claim yourself + +The table of claims, commands and the outputs we got for 0.20.0 is in +[SECURITY.md](SECURITY.md#check-every-claim-yourself). + ## Reproduce it From the repository root: From 3627568df1270704ca419755eaf47c1506e8fa2d Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:49:33 +0100 Subject: [PATCH 18/66] test(rebalancer): kill or explain every remaining mutation survivor 81 mutants survived the post-fix run in both builds. 51 are now killed by new tests (checkpoint validation, audit writers, printed plan and recovery hints, reconcile counters, classify_trade zero and i64::MIN cases, dollar-to-cents saturation, kill backoff, TOML lookup); each test was shown to fail with its mutant applied. 29 are equivalent and 1 only changes an error message; the reasons are recorded. The unused validator helper _path_exists is deleted instead of tested. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- rebalancer/src/clock_skew.rs | 11 + rebalancer/src/diff.rs | 22 ++ rebalancer/src/kill.rs | 36 +++ rebalancer/src/recovery.rs | 9 + rebalancer/src/validator.rs | 29 ++- rebalancer/tests/cli_smoke.rs | 24 ++ rebalancer/tests/common/mod.rs | 79 +++++++ rebalancer/tests/mutation_audit.rs | 258 +++++++++++++++++++++ rebalancer/tests/mutation_recovery.rs | 134 +++++++++++ rebalancer/tests/mutation_stdout.rs | 321 ++++++++++++++++++++++++++ 10 files changed, 917 insertions(+), 6 deletions(-) create mode 100644 rebalancer/tests/common/mod.rs create mode 100644 rebalancer/tests/mutation_audit.rs create mode 100644 rebalancer/tests/mutation_recovery.rs create mode 100644 rebalancer/tests/mutation_stdout.rs diff --git a/rebalancer/src/clock_skew.rs b/rebalancer/src/clock_skew.rs index 4dc493b..19b0b46 100644 --- a/rebalancer/src/clock_skew.rs +++ b/rebalancer/src/clock_skew.rs @@ -272,4 +272,15 @@ mod tests { SkewResult::Ok ); } + + #[test] + fn identical_timestamps_are_never_skew_even_with_negative_thresholds() { + // A zero difference is neither a backward nor a forward jump. With a + // negative threshold and a negative rate limit, a `<=` or `>=` boundary + // would classify it as a jump, because 0 > -1 and -0.0 > -1.0. + let ts = Utc::now(); + let mut detector = ClockSkewDetector::with_thresholds(-1, -1.0); + assert_eq!(detector.check(ts), SkewResult::Ok); + assert_eq!(detector.check(ts), SkewResult::Ok); + } } diff --git a/rebalancer/src/diff.rs b/rebalancer/src/diff.rs index 9896066..1d5b350 100644 --- a/rebalancer/src/diff.rs +++ b/rebalancer/src/diff.rs @@ -661,4 +661,26 @@ mod tests { "$502.00 commission + $200.40 slippage = $702.40" ); } + + #[test] + fn classify_trade_zero_change_falls_through_to_rebalance() { + // No arm matches a zero change, whatever the current position is. + for current in [0, 4, -4, i64::MIN] { + assert_eq!( + classify_trade(current, 0), + (Action::Buy, "rebalance"), + "classify_trade({current}, 0)" + ); + } + } + + #[test] + fn classify_trade_short_arms_do_not_take_abs_of_min() { + // The "flip to long" arm must stop at its sign tests before calling + // `c.abs()`, which overflows for i64::MIN. + assert_eq!( + classify_trade(i64::MIN, -1), + (Action::SellShort, "increase short") + ); + } } diff --git a/rebalancer/src/kill.rs b/rebalancer/src/kill.rs index 5b20f54..e278bc6 100644 --- a/rebalancer/src/kill.rs +++ b/rebalancer/src/kill.rs @@ -1497,4 +1497,40 @@ timeout_secs = {timeout_secs} assert_eq!(dangling.len(), 1); assert_eq!(dangling[0].limit_price_cents, 16_025); } + + #[test] + fn forceful_cancel_default_backoff_doubles_between_attempts() { + // open_orders fails on attempts 0 and 1, then succeeds with nothing open. + // The default backoff sleeps 1 s after attempt 0 and 2 s after attempt 1. + let broker = TestBroker::with_orders(&[]); + broker.fail_open_attempts.set(2); + let started = std::time::Instant::now(); + let report = forceful_cancel_open_orders(&broker); + let elapsed = started.elapsed(); + + assert_eq!(report.attempts, 3); + assert_eq!(report.errors.len(), 2); + assert!(report.succeeded()); + assert!( + elapsed >= Duration::from_millis(2_900), + "expected about 3 s of backoff, slept {elapsed:?}" + ); + } + + #[test] + fn dangling_order_limit_outside_cents_range_saturates() { + // 1e17 dollars is 1e19 cents, above i64::MAX, so the checked conversion + // fails and the saturating fallback `(dollars * 100.0).round() as i64` + // is used. A different operator in the fallback gives another value. + let temp_file = NamedTempFile::new().unwrap(); + let audit_log = r#"{"event":"order_submitted","ts":"2024-01-01T00:00:00Z","symbol":"AAPL","action":"Buy","shares":1,"limit":1e17,"ibkr_id":1} +{"event":"order_submitted","ts":"2024-01-01T00:00:01Z","symbol":"MSFT","action":"Sell","shares":1,"limit":-1e17,"ibkr_id":2}"#; + std::fs::write(temp_file.path(), audit_log).unwrap(); + + let mut dangling = verify_no_dangling_orders(temp_file.path()).unwrap(); + dangling.sort_by_key(|order| order.ibkr_id); + assert_eq!(dangling.len(), 2); + assert_eq!(dangling[0].limit_price_cents, i64::MAX); + assert_eq!(dangling[1].limit_price_cents, i64::MIN); + } } diff --git a/rebalancer/src/recovery.rs b/rebalancer/src/recovery.rs index 9632f6e..3950ff1 100644 --- a/rebalancer/src/recovery.rs +++ b/rebalancer/src/recovery.rs @@ -2699,4 +2699,13 @@ mod tests { ] ); } + + #[test] + fn audit_dollars_to_cents_converts_and_saturates() { + assert_eq!(audit_dollars_to_cents(160.25), 16_025); + assert_eq!(audit_dollars_to_cents(0.0), 0); + // Out of the checked range: saturating fallback. + assert_eq!(audit_dollars_to_cents(1e17), i64::MAX); + assert_eq!(audit_dollars_to_cents(-1e17), i64::MIN); + } } diff --git a/rebalancer/src/validator.rs b/rebalancer/src/validator.rs index 7ee05cc..63ae3a2 100644 --- a/rebalancer/src/validator.rs +++ b/rebalancer/src/validator.rs @@ -295,15 +295,10 @@ pub fn validate_broker_connectivity(config: &Config) -> Vec { } } -#[allow(dead_code)] -fn _path_exists(path: &Path) -> bool { - path.exists() -} - #[cfg(test)] mod tests { use super::{ - ValidationIssue, format_validation_issues, should_run_startup_validation, + ValidationIssue, find_toml_field, format_validation_issues, should_run_startup_validation, validate_available_log_space, validate_broker_connectivity, validate_disk_space, validate_file_permissions, validate_network_timeout, validate_required_fields, validate_risk_limits, validate_static, validate_static_or_error, @@ -554,4 +549,26 @@ mod tests { assert!(validate_available_log_space(1_000_000_000, &config).is_empty()); assert_eq!(validate_available_log_space(999_999_999, &config).len(), 1); } + + #[test] + fn find_toml_field_matches_section_and_key_together() { + let contents = "[a]\nx = 1\ny = 2\n[b]\nx = 3\n"; + assert_eq!(find_toml_field(contents, "a.x"), Some((2, "1"))); + assert_eq!(find_toml_field(contents, "a.y"), Some((3, "2"))); + // Same key in another section must not match section a, and a key + // present only in another section must not match at all. + assert_eq!(find_toml_field(contents, "b.x"), Some((5, "3"))); + assert_eq!(find_toml_field(contents, "b.y"), None); + assert_eq!(find_toml_field(contents, "c.x"), None); + assert_eq!(find_toml_field(contents, "nodot"), None); + } + + #[test] + fn find_toml_field_does_not_take_an_array_value_for_a_section_header() { + // `ports = [1, 2]` ends with `]` but does not start with `[`: it is a + // key line, and the fields after it still belong to section a. + let contents = "[a]\nports = [1, 2]\nx = 3\n"; + assert_eq!(find_toml_field(contents, "a.ports"), Some((2, "[1, 2]"))); + assert_eq!(find_toml_field(contents, "a.x"), Some((3, "3"))); + } } diff --git a/rebalancer/tests/cli_smoke.rs b/rebalancer/tests/cli_smoke.rs index c1a9745..0d3a39d 100644 --- a/rebalancer/tests/cli_smoke.rs +++ b/rebalancer/tests/cli_smoke.rs @@ -58,3 +58,27 @@ fn kill_without_pid_file_exits_nonzero() { ); assert_eq!(output.status.code(), Some(3)); } + +#[test] +fn aborted_error_is_printed_as_its_bare_message() { + // `Error::Aborted` has its own arm in main: the message is printed as is, + // without the "Error: execution aborted:" prefix of the generic arm. + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("config.toml"), sample_config()).unwrap(); + let output = Command::new(bin()) + .current_dir(dir.path()) + .args(["--config", "config.toml", "--skip-validation", "kill"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(3)); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.lines().any(|l| l.starts_with("PID file not found")), + "stderr was: {stderr}" + ); + assert!(!stderr.contains("Error: "), "stderr was: {stderr}"); + assert!( + !stderr.contains("execution aborted"), + "stderr was: {stderr}" + ); +} diff --git a/rebalancer/tests/common/mod.rs b/rebalancer/tests/common/mod.rs new file mode 100644 index 0000000..a91668c --- /dev/null +++ b/rebalancer/tests/common/mod.rs @@ -0,0 +1,79 @@ +//! Helpers shared by the mutation-gap tests: capture of `tracing` output and +//! capture of the standard output of a test run in a child process. + +#![allow(dead_code)] + +use std::io; +use std::process::Command; +use std::sync::{Arc, Mutex}; + +use tracing_subscriber::fmt::MakeWriter; + +/// Collects everything a scoped `tracing` subscriber writes. +#[derive(Clone, Default)] +pub struct LogCapture(Arc>>); + +pub struct CaptureWriter(Arc>>); + +impl io::Write for CaptureWriter { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl<'a> MakeWriter<'a> for LogCapture { + type Writer = CaptureWriter; + + fn make_writer(&'a self) -> Self::Writer { + CaptureWriter(Arc::clone(&self.0)) + } +} + +impl LogCapture { + /// Run `f` with a subscriber that records every event at any level. + pub fn run(&self, f: impl FnOnce() -> T) -> T { + let subscriber = tracing_subscriber::fmt() + .with_ansi(false) + .with_max_level(tracing::Level::TRACE) + .with_writer(self.clone()) + .finish(); + tracing::subscriber::with_default(subscriber, f) + } + + pub fn text(&self) -> String { + String::from_utf8(self.0.lock().unwrap().clone()).unwrap() + } +} + +const CHILD_ENV: &str = "NANOBOOK_TEST_CHILD_SCENARIO"; + +/// Inside a child process started by [`run_child`], the scenario name. +/// `None` in the normal (parent) run. +pub fn child_scenario() -> Option { + std::env::var(CHILD_ENV).ok() +} + +/// `println!` output cannot be read back inside the test process, because the +/// test harness captures it. Run the test `test_name` of the current test +/// binary again in a child process with `--nocapture` and return its standard +/// output. The test body must call [`child_scenario`] and run the named +/// scenario when it returns `Some`. +pub fn run_child(test_name: &str, scenario: &str) -> String { + let output = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", test_name, "--nocapture", "--test-threads=1"]) + .env(CHILD_ENV, scenario) + .output() + .unwrap(); + assert!( + output.status.success(), + "child {test_name}/{scenario} failed:\nstdout:\n{}\nstderr:\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap() +} diff --git a/rebalancer/tests/mutation_audit.rs b/rebalancer/tests/mutation_audit.rs new file mode 100644 index 0000000..382f14f --- /dev/null +++ b/rebalancer/tests/mutation_audit.rs @@ -0,0 +1,258 @@ +//! Mutation-gap tests for audit.rs: checkpoint-order warnings and the +//! `log_*` convenience writers. + +mod common; + +use common::LogCapture; +use nanobook::Symbol; +use nanobook_rebalancer::audit::{ + AuditLog, parse_audit_events, parse_audit_events_from_str, validate_checkpoints_from_parsed, +}; +use nanobook_rebalancer::diff::{Action, RebalanceOrder}; + +/// Build a parsed audit log from event names. Event `i` gets sequence number +/// `i + 1`. `diff_computed` carries one order so the later checkpoints are +/// required. +fn events(names: &[&str]) -> Vec { + let mut text = String::new(); + for (i, name) in names.iter().enumerate() { + let extra = if *name == "diff_computed" { + r#","orders":[{"symbol":"AAPL","action":"BUY","shares":1,"limit":1.0,"description":"open"}]"# + } else { + "" + }; + text.push_str(&format!( + r#"{{"event":"{name}","ts":"2026-01-01T00:00:00Z","sequence_number":{}{extra}}}"#, + i + 1 + )); + text.push('\n'); + } + parse_audit_events_from_str(&text).unwrap() +} + +#[cfg(feature = "write_ahead_logging")] +const POSITIONS: &[&str] = &["positions_intent", "positions_result"]; +#[cfg(not(feature = "write_ahead_logging"))] +const POSITIONS: &[&str] = &["positions_fetched"]; + +/// run_started, positions, diff_computed, risk_check_passed, then `tail`. +fn run_with_tail(tail: &[&str]) -> Vec { + let mut names = vec!["run_started"]; + names.extend_from_slice(POSITIONS); + names.extend_from_slice(&["diff_computed", "risk_check_passed"]); + names.extend_from_slice(tail); + events(&names) +} + +fn validate_and_capture(log: &[nanobook_rebalancer::audit::AuditEvent]) -> String { + let capture = LogCapture::default(); + capture + .run(|| validate_checkpoints_from_parsed(log)) + .unwrap(); + capture.text() +} + +const ORDER_WARNING: &str = "Found OrderIntent checkpoint without OrderSubmitted or OrderFailed"; + +#[test] +fn order_intent_without_followup_warns_even_when_submissions_precede_it() { + // An order_submitted directly before the intent, and none after it. + // The warning must look only at events after the first order_intent. + let text = validate_and_capture(&run_with_tail(&["order_submitted", "order_intent"])); + assert!(text.contains(ORDER_WARNING), "log was: {text}"); + + // The plain case: an intent and nothing after it. + let text = validate_and_capture(&run_with_tail(&["order_intent"])); + assert!(text.contains(ORDER_WARNING), "log was: {text}"); +} + +#[test] +fn order_intent_with_submitted_or_failed_followup_does_not_warn() { + for followup in ["order_submitted", "order_failed"] { + let text = validate_and_capture(&run_with_tail(&["order_intent", followup])); + assert!( + !text.contains(ORDER_WARNING), + "{followup} after the intent still warned: {text}" + ); + } +} + +#[cfg(feature = "write_ahead_logging")] +mod wal_checkpoints { + use super::*; + + /// A write-ahead log in which every intent has its result. + fn complete_log() -> Vec { + events(&[ + "run_started", + "account_summary_intent", + "account_summary_result", + "positions_intent", + "positions_result", + "quotes_intent", + "quotes_result", + "diff_computed", + "risk_check_passed", + "order_intent", + "order_submitted", + "cancel_intent", + "cancel_result", + "order_filled", + "run_completed", + ]) + } + + #[test] + fn complete_intent_result_pairs_do_not_warn() { + let text = validate_and_capture(&complete_log()); + for message in [ + "without PositionsResult", + "without QuotesResult", + "without AccountSummaryResult", + "without CancelResult", + "without OrderSubmitted or OrderFailed", + ] { + assert!(!text.contains(message), "unexpected {message:?} in: {text}"); + } + } + + #[test] + fn logs_without_quotes_account_or_cancel_events_do_not_warn_about_them() { + let log = events(&[ + "run_started", + "positions_intent", + "positions_result", + "diff_computed", + "risk_check_passed", + "order_intent", + "order_submitted", + ]); + let text = validate_and_capture(&log); + for message in [ + "without PositionsResult", + "without QuotesResult", + "without AccountSummaryResult", + "without CancelResult", + "without OrderSubmitted or OrderFailed", + ] { + assert!(!text.contains(message), "unexpected {message:?} in: {text}"); + } + } + + #[test] + fn incomplete_quotes_account_and_cancel_intents_warn() { + let log = events(&[ + "run_started", + "account_summary_intent", + "positions_intent", + "positions_result", + "quotes_intent", + "diff_computed", + "risk_check_passed", + "order_intent", + "order_submitted", + "cancel_intent", + ]); + let text = validate_and_capture(&log); + assert!( + text.contains("Found QuotesIntent checkpoint without QuotesResult"), + "log was: {text}" + ); + assert!( + text.contains("Found AccountSummaryIntent checkpoint without AccountSummaryResult"), + "log was: {text}" + ); + assert!( + text.contains("Found CancelIntent checkpoint without CancelResult"), + "log was: {text}" + ); + assert!(!text.contains("without PositionsResult"), "log was: {text}"); + assert!( + !text.contains("without OrderSubmitted or OrderFailed"), + "log was: {text}" + ); + } +} + +fn buy_order() -> RebalanceOrder { + RebalanceOrder { + symbol: Symbol::new("AAPL"), + action: Action::Buy, + shares: 10, + limit_price_cents: 18_502, + notional_cents: 185_020, + description: "open", + } +} + +#[test] +fn log_order_submitted_writes_the_event_fields() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + let mut audit = AuditLog::open_in(&path, dir.path()).unwrap(); + + nanobook_rebalancer::audit::log_order_submitted(&mut audit, &buy_order(), 4242).unwrap(); + + let events = parse_audit_events(&path).unwrap(); + assert_eq!(events.len(), 1); + let event = &events[0]; + assert_eq!(event.event, "order_submitted"); + assert_eq!(event.checkpoint, None); + assert_eq!(event.data["symbol"], "AAPL"); + assert_eq!(event.data["action"], "BUY"); + assert_eq!(event.data["shares"], 10); + assert_eq!(event.data["limit"], 185.02); + assert_eq!(event.data["ibkr_id"], 4242); +} + +#[cfg(feature = "write_ahead_logging")] +#[test] +fn account_summary_and_cancel_writers_write_the_event_fields() { + use chrono::{TimeZone, Utc}; + use nanobook_rebalancer::audit::{ + log_account_summary_intent, log_account_summary_result, log_cancel_intent, + log_cancel_result, + }; + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + let mut audit = AuditLog::open_in(&path, dir.path()).unwrap(); + let when = Utc.with_ymd_and_hms(2026, 3, 4, 5, 6, 7).unwrap(); + + log_account_summary_intent(&mut audit, when, "scope-1").unwrap(); + log_account_summary_result(&mut audit, 123_456_789, 98_765).unwrap(); + log_cancel_intent(&mut audit, 77, "operator", when).unwrap(); + log_cancel_result(&mut audit, 77, false, Some("no such order")).unwrap(); + log_cancel_result(&mut audit, 78, true, None).unwrap(); + + let events = parse_audit_events(&path).unwrap(); + assert_eq!( + events.iter().map(|e| e.event.as_str()).collect::>(), + [ + "account_summary_intent", + "account_summary_result", + "cancel_intent", + "cancel_result", + "cancel_result", + ] + ); + assert!(events.iter().all(|e| e.checkpoint.is_none())); + + assert_eq!(events[0].data["timestamp"], when.to_rfc3339()); + assert_eq!(events[0].data["target_spec_reference"], "scope-1"); + + assert_eq!(events[1].data["equity"], 1_234_567.89); + assert_eq!(events[1].data["cash"], 987.65); + + assert_eq!(events[2].data["order_id"], 77); + assert_eq!(events[2].data["cancellation_reason"], "operator"); + assert_eq!(events[2].data["timestamp"], when.to_rfc3339()); + + assert_eq!(events[3].data["order_id"], 77); + assert_eq!(events[3].data["success"], false); + assert_eq!(events[3].data["error_message"], "no such order"); + + assert_eq!(events[4].data["order_id"], 78); + assert_eq!(events[4].data["success"], true); + assert!(events[4].data["error_message"].is_null()); +} diff --git a/rebalancer/tests/mutation_recovery.rs b/rebalancer/tests/mutation_recovery.rs new file mode 100644 index 0000000..1413da4 --- /dev/null +++ b/rebalancer/tests/mutation_recovery.rs @@ -0,0 +1,134 @@ +//! Mutation-gap tests for write-ahead recovery: reconciliation counters and +//! the cancel-intent boundary of `determine_recovery_action`. + +#![cfg(feature = "write_ahead_logging")] + +mod common; + +use common::LogCapture; +use nanobook::Symbol; +use nanobook_broker::Broker; +use nanobook_broker::mock::{FillMode, MockBroker}; +use nanobook_broker::{BrokerOrder, BrokerOrderType, BrokerSide}; +use nanobook_rebalancer::audit::{AuditLog, Checkpoint, parse_audit_events}; +use nanobook_rebalancer::recovery::{ + RecoveredState, RecoveryAction, reconcile_incomplete_intents, reconstruct_state, +}; + +/// run_started, then one 50-share order intent for AAPL and one for MSFT. +fn write_two_incomplete_intents(path: &std::path::Path, workdir: &std::path::Path) { + let mut log = AuditLog::open_in(path, workdir).unwrap(); + log.log_checkpoint(Checkpoint::RunStarted, 1, serde_json::json!({"t": 1})) + .unwrap(); + for (sequence, symbol) in [(2, "AAPL"), (3, "MSFT")] { + log.log_checkpoint( + Checkpoint::OrderIntent, + sequence, + serde_json::json!({ + "symbol": symbol, + "action": "Buy", + "shares": 50, + "limit": 160.0, + "client_order_id": format!("c-{symbol}"), + }), + ) + .unwrap(); + } +} + +#[test] +fn reconciliation_summary_counts_intents_found_at_the_broker() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + write_two_incomplete_intents(&path, dir.path()); + + // The broker holds one open order with 50 shares remaining. + let mut broker = MockBroker::builder() + .fill_mode(FillMode::ImmediatePartial(0.5)) + .build(); + broker.connect().unwrap(); + broker + .submit_order(&BrokerOrder { + symbol: Symbol::new("AAPL"), + side: BrokerSide::Buy, + quantity: 50, + order_type: BrokerOrderType::Market, + client_order_id: None, + }) + .unwrap(); + + let (state, _) = reconstruct_state(&path).unwrap(); + let capture = LogCapture::default(); + capture + .run(|| reconcile_incomplete_intents(&broker, &state, &path)) + .unwrap(); + + let events = parse_audit_events(&path).unwrap(); + assert_eq!(events.len(), 5); + assert_eq!(events[3].event, "order_submitted"); + assert_eq!(events[3].sequence_number, Some(4)); + assert_eq!(events[4].event, "order_submitted"); + assert_eq!(events[4].sequence_number, Some(5)); + let text = capture.text(); + assert!( + text.contains("Broker reconciliation complete: 2 reconciled, 0 failed"), + "log was: {text}" + ); +} + +#[test] +fn reconciliation_summary_counts_intents_missing_at_the_broker() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + write_two_incomplete_intents(&path, dir.path()); + + let mut broker = MockBroker::builder() + .fill_mode(FillMode::ImmediateFull) + .build(); + broker.connect().unwrap(); + + let (state, _) = reconstruct_state(&path).unwrap(); + let capture = LogCapture::default(); + capture + .run(|| reconcile_incomplete_intents(&broker, &state, &path)) + .unwrap(); + + let events = parse_audit_events(&path).unwrap(); + assert_eq!(events.len(), 5); + assert_eq!(events[3].event, "order_failed"); + assert_eq!(events[4].event, "order_failed"); + let text = capture.text(); + assert!( + text.contains("Broker reconciliation complete: 2 reconciled, 0 failed"), + "log was: {text}" + ); +} + +#[test] +fn cancel_result_with_the_intent_sequence_completes_the_cancel() { + let state_with = |intent: u64, result: Option| { + let mut state = RecoveredState::new(); + state.last_cancel_intent_sequence = Some(intent); + state.last_cancel_result_sequence = result; + state + }; + + // A result older than the intent, or none, leaves the cancel incomplete. + assert_eq!( + state_with(5, None).determine_recovery_action(), + RecoveryAction::ManualReview + ); + assert_eq!( + state_with(5, Some(4)).determine_recovery_action(), + RecoveryAction::ManualReview + ); + // A result with the same sequence number as the intent is not older. + assert_eq!( + state_with(5, Some(5)).determine_recovery_action(), + RecoveryAction::Restart + ); + assert_eq!( + state_with(5, Some(6)).determine_recovery_action(), + RecoveryAction::Restart + ); +} diff --git a/rebalancer/tests/mutation_stdout.rs b/rebalancer/tests/mutation_stdout.rs new file mode 100644 index 0000000..3c0fc72 --- /dev/null +++ b/rebalancer/tests/mutation_stdout.rs @@ -0,0 +1,321 @@ +//! Mutation-gap tests for output that only reaches standard output: +//! the portfolio and plan tables of a run, and the guidance of `recover`. +//! Each test re-runs itself in a child process with `--nocapture` to read the +//! output (see `common::run_child`). + +mod common; + +use std::time::{Duration, SystemTime}; + +use common::{child_scenario, run_child}; +use nanobook::Symbol; +use nanobook_broker::error::BrokerError; +use nanobook_broker::ibkr::orders::OrderResult; +use nanobook_broker::types::{Account, Position, Quote}; +use nanobook_broker::{BrokerSide, ClientOrderId}; +use nanobook_rebalancer::broker::{BrokerGateway, BrokerResult}; +use nanobook_rebalancer::config::Config; +use nanobook_rebalancer::execution::{CronMode, RunOptions, ShutdownFlag, run_with_client}; +use nanobook_rebalancer::recovery::run_recover; +use nanobook_rebalancer::target::TargetSpec; + +fn config(logs_dir: &std::path::Path) -> Config { + toml::from_str(&format!( + r#" +[connection] +host = "127.0.0.1" +port = 4002 +client_id = 1 +[account] +id = "DU1" +type = "cash" +[execution] +order_interval_ms = 0 +limit_offset_bps = 5 +order_timeout_secs = 1 +max_orders_per_run = 50 +quote_staleness_threshold_sec = 30 +[risk] +max_position_pct = 1.0 +max_leverage = 2.0 +min_trade_usd = 100.0 +max_trade_usd = 1000000.0 +allow_short = true +max_short_pct = 1.0 +[cost] +[logging] +dir = "{}" +audit_file = "audit.jsonl" +"#, + logs_dir.display() + )) + .unwrap() +} + +fn spec() -> TargetSpec { + TargetSpec::from_json( + r#"{ + "timestamp": "2026-02-08T15:30:00Z", + "targets": [{ "symbol": "AAPL", "weight": 0.1 }] + }"#, + ) + .unwrap() +} + +/// Holds 10 AAPL at an average cost of $150.00; every quote has mid $100.00. +struct StubBroker { + equity_cents: i64, +} + +impl BrokerGateway for StubBroker { + fn account_summary(&self) -> BrokerResult { + Ok(Account { + equity_cents: self.equity_cents, + buying_power_cents: self.equity_cents, + cash_cents: self.equity_cents, + gross_position_value_cents: 0, + }) + } + + fn positions(&self) -> BrokerResult> { + Ok(vec![Position { + symbol: Symbol::new("AAPL"), + quantity: 10, + avg_cost_cents: 15_000, + market_value_cents: 0, + unrealized_pnl_cents: 0, + }]) + } + + fn prices(&self, _symbols: &[Symbol]) -> BrokerResult> { + Ok(Vec::new()) + } + + fn quotes(&self, symbols: &[Symbol]) -> BrokerResult> { + Ok(symbols + .iter() + .map(|symbol| Quote { + symbol: *symbol, + bid_cents: 9_999, + ask_cents: 10_001, + last_cents: 10_000, + volume: 0, + timestamp: SystemTime::now(), + }) + .collect()) + } + + fn execute_limit_order( + &self, + _symbol: Symbol, + _side: BrokerSide, + _shares: u64, + _limit_price_cents: i64, + _client_order_id: Option<&ClientOrderId>, + _timeout: Duration, + ) -> BrokerResult { + Err(BrokerError::Order("dry run only".into())) + } +} + +fn child_display(scenario: &str) { + let equity_cents = match scenario { + "equity_100k" => 10_000_000, + "equity_zero" => 0, + other => panic!("unknown scenario {other}"), + }; + let dir = tempfile::tempdir().unwrap(); + let options = RunOptions { + dry_run: true, + force: true, + target_file: "t.json".into(), + cron_mode: false, + }; + // The result is not part of what is checked here; the run may stop at the + // risk check. + let _ = run_with_client( + &config(&dir.path().join("logs")), + &spec(), + &options, + &StubBroker { equity_cents }, + &ShutdownFlag::new(), + dir.path(), + &mut || Ok(false), + ); +} + +#[test] +fn run_prints_portfolio_weights_and_the_plan() { + if let Some(scenario) = child_scenario() { + child_display(&scenario); + return; + } + + // 10 shares x $150.00 average cost = $1500.00 = 1.5 % of $100000.00. + let out = run_child("run_prints_portfolio_weights_and_the_plan", "equity_100k"); + assert!(out.contains("CURRENT PORTFOLIO:"), "stdout:\n{out}"); + let line = out + .lines() + .find(|l| l.contains("AAPL") && l.contains(" avg = $")) + .unwrap_or_else(|| panic!("no position line in:\n{out}")); + assert!( + line.contains("@ $ 150.00 avg = $ 1500.00 (1.5%)"), + "{line}" + ); + + // The plan table: 90 shares to reach $10000 from $1000 at mid $100.00. + assert!(out.contains("REBALANCE ORDERS:"), "stdout:\n{out}"); + let order = out + .lines() + .find(|l| l.contains("BUY") && l.contains("(increase)")) + .unwrap_or_else(|| panic!("no order line in:\n{out}")); + assert!(order.contains("$ 100.05 $ 9000.00"), "{order}"); + assert!(out.contains("Est. cost: $"), "stdout:\n{out}"); +} + +#[test] +fn run_prints_zero_weight_when_equity_is_zero() { + if let Some(scenario) = child_scenario() { + child_display(&scenario); + return; + } + + let out = run_child("run_prints_zero_weight_when_equity_is_zero", "equity_zero"); + let line = out + .lines() + .find(|l| l.contains("AAPL") && l.contains(" avg = $")) + .unwrap_or_else(|| panic!("no position line in:\n{out}")); + assert!(line.ends_with("avg = $ 1500.00 (0.0%)"), "{line}"); +} + +#[test] +fn cron_mode_reports_enabled() { + assert!(CronMode::new(1_700_000_000).is_enabled()); +} + +fn child_recover(scenario: &str) { + let dir = tempfile::tempdir().unwrap(); + let config = config(dir.path()); + let audit_path = config.audit_path(); + let dry_run = scenario.ends_with("_dry"); + match scenario { + "restart" | "restart_dry" => { + std::fs::write(&audit_path, "").unwrap(); + let _ = run_recover(&config, &spec(), dry_run, None); + } + #[cfg(feature = "write_ahead_logging")] + "reconcile_not_needed" | "reconcile_needed" => child_recover_with_broker(&config, scenario), + other => panic!("unknown scenario {other}"), + } +} + +#[cfg(feature = "write_ahead_logging")] +fn child_recover_with_broker(config: &Config, scenario: &str) { + use nanobook_broker::Broker; + use nanobook_broker::mock::{FillMode, MockBroker}; + use nanobook_rebalancer::audit::{AuditLog, Checkpoint}; + + let dir = config.audit_path().parent().unwrap().to_path_buf(); + { + let mut log = AuditLog::open_in(&config.audit_path(), &dir).unwrap(); + log.log_checkpoint(Checkpoint::RunStarted, 1, serde_json::json!({"t": 1})) + .unwrap(); + match scenario { + // Orders known only from the diff carry no client order id, so + // none of them is an incomplete intent. + "reconcile_not_needed" => log + .log_checkpoint( + Checkpoint::DiffComputed, + 2, + serde_json::json!({"orders": [{ + "symbol": "AAPL", "action": "BUY", "shares": 50, "limit": 160.0 + }]}), + ) + .unwrap(), + "reconcile_needed" => log + .log_checkpoint( + Checkpoint::OrderIntent, + 2, + serde_json::json!({ + "symbol": "AAPL", "action": "Buy", "shares": 50, "limit": 160.0, + "client_order_id": "c1" + }), + ) + .unwrap(), + _ => unreachable!(), + } + } + let mut broker = MockBroker::builder() + .fill_mode(FillMode::ImmediateFull) + .build(); + broker.connect().unwrap(); + let _ = run_recover(config, &spec(), true, Some(&broker)); +} + +#[test] +fn recover_prints_run_hint_only_when_not_a_dry_run() { + if let Some(scenario) = child_scenario() { + child_recover(&scenario); + return; + } + + let real = run_child("recover_prints_run_hint_only_when_not_a_dry_run", "restart"); + assert!( + real.contains("Safe to restart the entire rebalance from the beginning."), + "stdout:\n{real}" + ); + assert!( + real.contains("Run: rebalancer run "), + "stdout:\n{real}" + ); + assert!(!real.contains("Dry Run"), "stdout:\n{real}"); + + let dry = run_child( + "recover_prints_run_hint_only_when_not_a_dry_run", + "restart_dry", + ); + assert!( + dry.contains("Safe to restart the entire rebalance from the beginning."), + "stdout:\n{dry}" + ); + assert!(!dry.contains("Run: rebalancer run"), "stdout:\n{dry}"); + assert!( + dry.contains("=== Dry Run - No Action Taken ==="), + "stdout:\n{dry}" + ); +} + +#[cfg(feature = "write_ahead_logging")] +#[test] +fn recover_reconciles_only_incomplete_intents() { + if let Some(scenario) = child_scenario() { + child_recover(&scenario); + return; + } + + let not_needed = run_child( + "recover_reconciles_only_incomplete_intents", + "reconcile_not_needed", + ); + assert!( + not_needed.contains("=== Broker State Comparison ==="), + "stdout:\n{not_needed}" + ); + assert!( + !not_needed.contains("=== Broker Reconciliation ==="), + "stdout:\n{not_needed}" + ); + + let needed = run_child( + "recover_reconciles_only_incomplete_intents", + "reconcile_needed", + ); + assert!( + needed.contains("=== Broker Reconciliation ==="), + "stdout:\n{needed}" + ); + assert!( + needed.contains("Broker reconciliation completed successfully."), + "stdout:\n{needed}" + ); +} From 453f6e76007ec68975a31d3945d039cb34bcd1f9 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:50:47 +0100 Subject: [PATCH 19/66] test(python): run the deflated Sharpe tests in CI They lived in tests/reference/test_ref_stats.py, which skips without scipy and is not in any CI job, so they ran nowhere. They need no third-party package and now sit in tests/test_deflated_sharpe.py. The single-trial check compares against the exact normal CDF with a 1e-7 tolerance, matching the Abramowitz-Stegun approximation used in Rust (about 7.5e-8). Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- python/tests/reference/test_ref_stats.py | 21 -------------- python/tests/test_deflated_sharpe.py | 36 ++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 21 deletions(-) create mode 100644 python/tests/test_deflated_sharpe.py diff --git a/python/tests/reference/test_ref_stats.py b/python/tests/reference/test_ref_stats.py index 4d789bd..71cab4c 100644 --- a/python/tests/reference/test_ref_stats.py +++ b/python/tests/reference/test_ref_stats.py @@ -87,24 +87,3 @@ def test_inverse_scores(self): got = nanobook.py_quintile_spread(scores, returns, 5) assert got < 0.0 # inverse → negative spread - -class TestDeflatedSharpe: - """Deflated Sharpe Ratio against the worked example of Bailey and - López de Prado (2014), p. 99.""" - - def test_paper_example(self): - sr = 2.5 / 250**0.5 - v = 0.5 / 250 - assert nanobook.py_deflated_sharpe(sr, 100, 1250, v, -3.0, 10.0) == pytest.approx(0.9004, abs=5e-5) - assert nanobook.py_deflated_sharpe(sr, 46, 1250, v, -3.0, 10.0) == pytest.approx(0.9505, abs=5e-5) - assert nanobook.py_deflated_sharpe(sr, 88, 1250, v, 0.0, 3.0) == pytest.approx(0.9505, abs=5e-5) - - def test_single_trial_is_psr_against_zero(self): - from statistics import NormalDist - want = NormalDist().cdf(0.1 * 10.0 / (1.0 + 0.5 * 0.01) ** 0.5) - got = nanobook.py_deflated_sharpe(0.1, 1, 101, 0.0, 0.0, 3.0) - assert got == pytest.approx(want, abs=1e-12) - - def test_invalid_inputs(self): - assert np.isnan(nanobook.py_deflated_sharpe(0.1, 0, 100, 0.01, 0.0, 3.0)) - assert np.isnan(nanobook.py_deflated_sharpe(0.1, 10, 1, 0.01, 0.0, 3.0)) diff --git a/python/tests/test_deflated_sharpe.py b/python/tests/test_deflated_sharpe.py new file mode 100644 index 0000000..4026016 --- /dev/null +++ b/python/tests/test_deflated_sharpe.py @@ -0,0 +1,36 @@ +"""Deflated Sharpe Ratio against Bailey and López de Prado (2014). + +Needs no third-party package, so it runs in every CI job (with and without numpy). +""" + +import math +from statistics import NormalDist + +import pytest + +import nanobook + + +def test_paper_worked_example(): + """Worked example, p. 99: DSR 0.9004 (N=100), 0.9505 (N=46), 0.9505 (N=88, normal).""" + sr = 2.5 / math.sqrt(250) + v = 0.5 / 250 + assert nanobook.py_deflated_sharpe(sr, 100, 1250, v, -3.0, 10.0) == pytest.approx(0.9004, abs=5e-5) + assert nanobook.py_deflated_sharpe(sr, 46, 1250, v, -3.0, 10.0) == pytest.approx(0.9505, abs=5e-5) + assert nanobook.py_deflated_sharpe(sr, 88, 1250, v, 0.0, 3.0) == pytest.approx(0.9505, abs=5e-5) + + +def test_single_trial_is_psr_against_zero(): + """One trial: Phi(SR * sqrt(T - 1) / sqrt(1 + SR^2 / 2)) for normal returns. + + The Rust normal CDF (Abramowitz and Stegun 7.1.26) is accurate to about 7.5e-8, + hence the 1e-7 tolerance against the exact CDF. + """ + want = NormalDist().cdf(0.1 * 10.0 / math.sqrt(1.0 + 0.5 * 0.01)) + got = nanobook.py_deflated_sharpe(0.1, 1, 101, 0.0, 0.0, 3.0) + assert got == pytest.approx(want, abs=1e-7) + + +def test_invalid_inputs_are_nan(): + assert math.isnan(nanobook.py_deflated_sharpe(0.1, 0, 100, 0.01, 0.0, 3.0)) + assert math.isnan(nanobook.py_deflated_sharpe(0.1, 10, 1, 0.01, 0.0, 3.0)) From 1eff14bb73bc962a2d10ee83e55205ea7fc5f195 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:05:36 +0100 Subject: [PATCH 20/66] build: ship only sources, tests, examples and user docs in the crate The 0.19.3 crate was 6.3 MB compressed: it carried the OCaml oracle, docs, mockups, CI workflows and a stray benchmark log. An anchored include list keeps src, benches, tests, the Rust examples and the top-level user documents: 78 files, 441 KB. cargo package builds the packaged crate. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- Cargo.toml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index 7116683..44cc5f7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,21 @@ 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 = [ + "/src/**", + "/benches/**", + "/tests/**", + "/examples/*.rs", + "/examples/itch-replay/replay.rs", + "/README.md", + "/CHANGELOG.md", + "/LICENSE", + "/SECURITY.md", + "/SEMVER.md", + "/VERIFICATION.md", +] [dependencies] rustc-hash = "2.1" # FxHash - fast non-cryptographic hash From 852645dc89aa676cee346d68b060c9cba6b9571c Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:09:41 +0100 Subject: [PATCH 21/66] docs(changelog): note the new BacktestBridgeOptions field for struct literals cargo semver-checks against 0.19.3 reports two breaking changes, both intended for 0.20.0: deflated_sharpe's new arguments (already noted) and the record_executions field, which breaks exhaustive struct literals. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 57feda5..c268dca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -108,7 +108,7 @@ tests, fuzzing or mutation testing. fill-or-kill check under a self-trade policy. `OrderBook::can_fully_fill` is unchanged. - **Reference prices in execution records.** `reference_price` (unimpacted cents per share) and `reference_notional` (cents at the final filled quantity, using the engine's truncation and i64 clamp) are added to Rust and Python execution records. Stop references use the current close, including on hold days without rebalance fill bars. Slippage cost is `notional - reference_notional` for buys and `reference_notional - notional` for sells, up to truncation; `cost` remains commission only. The extra calculation runs only when recording is enabled; execution arithmetic and existing outputs are unchanged. -- **Opt-in backtest execution records** through Rust's `BacktestBridgeOptions.record_executions` and Python's `record_executions=True`. Results include `initial_cash`, actual `executions` (including stop exits and trimmed buys), and period-close `cash_snapshots`. Quantity is signed raw micro-shares (1 share = 1,000,000; positive buys, negative sells), with Python `side` (`buy`/`sell`); price is effective cents per share; all other monetary fields are cents. Notional truncates toward zero after scaling and clamps to i64; cash fields reflect actual balance changes, including saturation. Ledgers are `None` by default and empty for enabled empty/rejected runs. Existing calls and financial calculations are unchanged. The Python stubs for `backtest_weights` now match the runtime signature. +- **Opt-in backtest execution records** through Rust's `BacktestBridgeOptions.record_executions` and Python's `record_executions=True`. Results include `initial_cash`, actual `executions` (including stop exits and trimmed buys), and period-close `cash_snapshots`. Quantity is signed raw micro-shares (1 share = 1,000,000; positive buys, negative sells), with Python `side` (`buy`/`sell`); price is effective cents per share; all other monetary fields are cents. Notional truncates toward zero after scaling and clamps to i64; cash fields reflect actual balance changes, including saturation. Ledgers are `None` by default and empty for enabled empty/rejected runs. Existing calls and financial calculations are unchanged. *Check your code if* you build `BacktestBridgeOptions` with a struct literal: add `record_executions` or end it with `..Default::default()`. The Python stubs for `backtest_weights` now match the runtime signature. - **Lean verification.** The Lean model, proofs and replay tools (`verification/lean/`), the corpus generator (`examples/corpus_gen.rs`), the Rust-versus-Lean replay (`verification/lean/differential.sh`), and golden corpus cases 19 to 25. From a7f41256e65cd46b3cd53cd491fdd9a692429725 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:04:15 +0100 Subject: [PATCH 22/66] rebalancer: test order pacing, retry backoff, EPERM message, zero-quantity reconcile cargo-mutants with a 900 s limit showed these were never checked; a 180 s limit had counted them as timeouts. The pause between orders and the retry backoff move into two small helpers with unit tests (same behaviour). The write-ahead account summary wrapper gains a test of its result and audit checkpoints. nix gains the user feature for the root check in the kill test. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- rebalancer/Cargo.toml | 2 +- rebalancer/src/execution.rs | 34 +++++++++++++++++++++++++++-- rebalancer/src/kill.rs | 16 ++++++++++++++ rebalancer/src/recovery.rs | 33 ++++++++++++++++++++++++++++ rebalancer/tests/fetch_wrappers.rs | 35 +++++++++++++++++++++++++++++- 5 files changed, 116 insertions(+), 4 deletions(-) diff --git a/rebalancer/Cargo.toml b/rebalancer/Cargo.toml index ed7ebdd..0455e0a 100644 --- a/rebalancer/Cargo.toml +++ b/rebalancer/Cargo.toml @@ -33,7 +33,7 @@ tracing-appender = "0.2" tracing-log = "0.2" rustc-hash = "2.1" dialoguer = "0.12" -nix = { version = "0.31", features = ["signal"] } +nix = { version = "0.31", features = ["signal", "user"] } signal-hook = "0.4" fs2 = "0.4" diff --git a/rebalancer/src/execution.rs b/rebalancer/src/execution.rs index c546c8c..9331850 100644 --- a/rebalancer/src/execution.rs +++ b/rebalancer/src/execution.rs @@ -121,6 +121,18 @@ fn next_checkpoint_sequence(sequence_number: &mut u64) -> u64 { *sequence_number } +/// Whether to pause before the order after `index` (zero-based) of `count`. +/// The last order is not followed by a pause. +fn pause_after(index: usize, count: usize) -> bool { + index + 1 < count +} + +/// Seconds to wait before retry after failed `attempt` (one-based): 1, 2, 4, 8, 16. +#[cfg_attr(not(feature = "write_ahead_logging"), allow(dead_code))] +fn retry_backoff_secs(attempt: u32) -> u64 { + 2u64.pow(attempt - 1) +} + /// Process-wide graceful shutdown flag set by SIGTERM. #[derive(Debug, Clone)] pub struct ShutdownFlag { @@ -619,7 +631,7 @@ pub fn run_with_client( } // Rate limiting between orders - if i + 1 < orders.len() { + if pause_after(i, orders.len()) { orders::rate_limit_delay(config.execution.order_interval_ms); } } @@ -1131,7 +1143,7 @@ pub fn execute_order_with_write_ahead( if is_transient_error(&broker_error) { if attempt < max_retries { // Calculate exponential backoff: 1s, 2s, 4s, 8s, 16s - let backoff_secs = 2u64.pow(attempt - 1); + let backoff_secs = retry_backoff_secs(attempt); warn!( "Transient error on attempt {}/{} (will retry in {}s): {}", attempt, max_retries, backoff_secs, broker_error @@ -1217,6 +1229,24 @@ mod tests { use super::*; use nanobook_broker::error::BrokerError; + #[test] + fn pause_after_is_false_only_for_the_last_order() { + assert!(!pause_after(0, 0)); + assert!(!pause_after(0, 1)); + assert!(pause_after(0, 2)); + assert!(pause_after(0, 3)); + assert!(pause_after(1, 3)); + assert!(!pause_after(2, 3)); + assert!(!pause_after(3, 3)); + assert!(!pause_after(4, 3)); + } + + #[test] + fn retry_backoff_doubles_from_one_second() { + let secs: Vec = (1..=5).map(retry_backoff_secs).collect(); + assert_eq!(secs, vec![1, 2, 4, 8, 16]); + } + #[test] fn test_is_transient_error_connection() { assert!(is_transient_error(&BrokerError::Connection( diff --git a/rebalancer/src/kill.rs b/rebalancer/src/kill.rs index e278bc6..9576d84 100644 --- a/rebalancer/src/kill.rs +++ b/rebalancer/src/kill.rs @@ -1517,6 +1517,22 @@ timeout_secs = {timeout_secs} ); } + #[cfg(unix)] + #[test] + fn send_sigterm_reports_permission_denied() { + // Process 1 belongs to root, so a non-root caller gets EPERM. Root + // can signal it (and would terminate it), so skip that case. + if nix::unistd::geteuid().is_root() { + println!("skipped: running as root, kill(1, SIGTERM) gives no EPERM"); + return; + } + let err = send_sigterm(1).unwrap_err(); + assert!( + err.to_string().contains("Permission denied"), + "unexpected error: {err}" + ); + } + #[test] fn dangling_order_limit_outside_cents_range_saturates() { // 1e17 dollars is 1e19 cents, above i64::MAX, so the checked conversion diff --git a/rebalancer/src/recovery.rs b/rebalancer/src/recovery.rs index 3950ff1..089eda2 100644 --- a/rebalancer/src/recovery.rs +++ b/rebalancer/src/recovery.rs @@ -2672,6 +2672,39 @@ mod tests { ); } + #[cfg(feature = "write_ahead_logging")] + #[test] + fn reconcile_order_intent_zero_quantity_ignores_zero_remaining() { + use nanobook::Price; + use nanobook_broker::mock::{FillMode, MockBroker}; + use nanobook_broker::types::{BrokerOrder, BrokerOrderType}; + use nanobook_broker::{Broker, BrokerSide}; + + let mut broker = MockBroker::builder() + .fill_mode(FillMode::ImmediateFull) + .build(); + broker.connect().unwrap(); + broker + .submit_order(&BrokerOrder { + symbol: Symbol::new("AAPL"), + side: BrokerSide::Buy, + quantity: 50, + order_type: BrokerOrderType::Limit(Price(16_000)), + client_order_id: None, + }) + .unwrap(); + let open = broker.open_orders().unwrap(); + assert_eq!(open.len(), 1); + assert_eq!(open[0].remaining_quantity, 0); + + let mut sleeps = Vec::new(); + let matched = + reconcile_order_intent_with(&broker, &Symbol::new("AAPL"), 0, &mut |d| sleeps.push(d)) + .unwrap(); + assert_eq!(matched, None); + assert!(sleeps.is_empty()); + } + #[cfg(feature = "write_ahead_logging")] #[test] fn reconcile_order_intent_retries_five_times() { diff --git a/rebalancer/tests/fetch_wrappers.rs b/rebalancer/tests/fetch_wrappers.rs index fce7807..9593c38 100644 --- a/rebalancer/tests/fetch_wrappers.rs +++ b/rebalancer/tests/fetch_wrappers.rs @@ -14,7 +14,8 @@ use nanobook_rebalancer::diff::{Action, RebalanceOrder}; use nanobook_rebalancer::error::Error; use nanobook_rebalancer::execution::{ cancel_order_with_write_ahead, execute_order_with_write_ahead, - fetch_positions_with_write_ahead, fetch_quotes_with_write_ahead, + fetch_account_summary_with_write_ahead, fetch_positions_with_write_ahead, + fetch_quotes_with_write_ahead, }; struct FetchStub { @@ -220,6 +221,38 @@ fn fetch_wrappers_return_stub_positions_and_quotes() { } } +#[test] +fn fetch_account_summary_returns_broker_account_and_logs_checkpoints() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + let mut audit = AuditLog::open_in(&path, dir.path()).unwrap(); + let stub = FetchStub::ok(); + let mut seq = 200u64; + let account = + fetch_account_summary_with_write_ahead(&stub, &mut audit, &mut seq, "ref").unwrap(); + assert_eq!(account.equity_cents, 100_000_000); + assert_eq!(account.cash_cents, 100_000_000); + + #[cfg(feature = "write_ahead_logging")] + { + assert_eq!(seq, 202); + let events = nanobook_rebalancer::audit::parse_audit_events(&path).unwrap(); + assert_eq!(events.len(), 2); + assert_eq!(events[0].event, "account_summary_intent"); + assert_eq!(events[0].sequence_number, Some(201)); + assert_eq!(events[1].event, "account_summary_result"); + assert_eq!(events[1].sequence_number, Some(202)); + assert_eq!( + events[1].data.get("equity").and_then(|v| v.as_f64()), + Some(1_000_000.0) + ); + assert_eq!( + events[1].data.get("cash").and_then(|v| v.as_f64()), + Some(1_000_000.0) + ); + } +} + #[test] fn fetch_wrappers_map_connection_errors() { let dir = tempfile::tempdir().unwrap(); From 44f51b4bea11fa74ced5c4e4b432ec57fdce19f6 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:37:51 +0100 Subject: [PATCH 23/66] ci(release): write SHA256SUMS with the release file names The download step nested each artifact in its own folder, so the checksum file listed paths that do not match the release assets. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- .github/workflows/release.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9e3fce8..e12227a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -106,6 +106,8 @@ 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 --repo BoringQuantSystems/nanobook`. From 419a7a02c5516f34a71b14c53dd3ef2861132a7f Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:37:51 +0100 Subject: [PATCH 24/66] build: ship the replay fixture that corpus-replay reads Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.toml b/Cargo.toml index 44cc5f7..e262c65 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,6 +34,7 @@ include = [ "/SECURITY.md", "/SEMVER.md", "/VERIFICATION.md", + "/oracle-ocaml/test/corpus/01-simple-cross/input.jsonl", ] [dependencies] From 2211be77cd87584a9a6c47cbc3cffe3bb559d879 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:37:51 +0100 Subject: [PATCH 25/66] docs: say which events advance the timestamp and when Lean CI runs Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- CHANGELOG.md | 5 +++-- docs/reference.md | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c268dca..3fff703 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,8 +31,9 @@ order book are stated and proved in Lean 4 about a model of the engine FIFO list; 11. a submitted order's stored record matches its status. -The proofs are about the model, not the Rust code itself. On every push and pull -request, CI (`.github/workflows/lean.yml`) rebuilds them, allows only Lean's three +The proofs are about the model, not the Rust code itself. On a push to `main`, +on a pull request into `main`, and on a manual run, CI (`.github/workflows/lean.yml`) +rebuilds them, allows only Lean's three standard axioms, rechecks everything with `leanchecker --fresh`, replays the golden corpus in Lean against the trades Rust recorded for it, and runs the Rust engine and the Lean model on 1000 random event logs whose trade logs must match byte for byte. diff --git a/docs/reference.md b/docs/reference.md index 07bfe8e..b8e5167 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -66,7 +66,7 @@ Constants: `Price::ZERO`, `Price::MAX` (market buys), `Price::MIN` (market sells ### Quantities and Timestamps - `Quantity = u64` — shares or contracts, always positive. -- `Timestamp = u64` — event counter assigned by the exchange, starting at 1 and increasing by 1 (not wall-clock time), guaranteeing deterministic ordering. +- `Timestamp = u64` — sequence number assigned by the exchange, starting at 1. Each new order, stop order, and trade takes the next value. A cancellation does not take a value. Not wall-clock time. The sequence orders those events. ### Determinism From 6c87ae71ae902221224f53b3d21a773e91776d5d Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:37:51 +0100 Subject: [PATCH 26/66] test(kill): probe pid 1 with signal 0 before sending SIGTERM The permission-denied test sent SIGTERM to pid 1, which kills init when the test runs as root. It now skips unless the probe returns EPERM. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- rebalancer/src/kill.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/rebalancer/src/kill.rs b/rebalancer/src/kill.rs index 9576d84..cd13956 100644 --- a/rebalancer/src/kill.rs +++ b/rebalancer/src/kill.rs @@ -1526,6 +1526,16 @@ timeout_secs = {timeout_secs} println!("skipped: running as root, kill(1, SIGTERM) gives no EPERM"); return; } + // Signal 0 checks permission and does not deliver a signal. Skip when + // this user may signal pid 1, so the test does not stop the init process. + match nix::sys::signal::kill(nix::unistd::Pid::from_raw(1), None) { + Ok(()) => { + println!("skipped: this user may signal pid 1"); + return; + } + Err(nix::errno::Errno::EPERM) => {} + Err(error) => panic!("kill(1, 0) returned {error}, not EPERM"), + } let err = send_sigterm(1).unwrap_err(); assert!( err.to_string().contains("Permission denied"), From e127e523ffaa7a6306653ea690e072e22415b09f Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:37:51 +0100 Subject: [PATCH 27/66] fix(pid_file): hold an exclusive lock on the PID file A second rebalancer could overwrite a live PID file. The guard now locks the file for its lifetime; a second start fails while the lock is held, and a crash releases it. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- rebalancer/src/pid_file.rs | 108 ++++++++++++++++++++++++++++++++----- 1 file changed, 94 insertions(+), 14 deletions(-) diff --git a/rebalancer/src/pid_file.rs b/rebalancer/src/pid_file.rs index b853ae2..9ed3209 100644 --- a/rebalancer/src/pid_file.rs +++ b/rebalancer/src/pid_file.rs @@ -26,12 +26,14 @@ //! //! # Cleanup //! -//! If the rebalancer crashes or is killed via SIGKILL, the PID file may not be -//! cleaned up automatically. In such cases, the file should be removed manually -//! before starting a new rebalancer instance to avoid conflicts. +//! The guard holds an exclusive lock for its lifetime. A second start that +//! uses the same path fails while the lock is held. A crash releases the +//! lock. The next start then replaces the stale file. use crate::error::{Error, Result}; -use std::fs; +use fs2::FileExt; +use std::fs::{self, File, OpenOptions}; +use std::io::Write; use std::path::{Path, PathBuf}; /// Default PID file path. @@ -77,28 +79,62 @@ pub fn remove_pid_file(path: &Path) -> Result<()> { Ok(()) } -/// Write a PID file and remove it when this guard drops. +/// Write a PID file, hold its lock, and remove the file on drop. +#[derive(Debug)] pub struct PidFileGuard { path: PathBuf, + file: Option, } impl PidFileGuard { - /// Write `path` with the current process id. + /// Write `path` with the current process id and lock the file. + /// + /// The lock stays held until drop. A second guard for the same path + /// fails. Drop removes the file before it releases the lock. pub fn create(path: PathBuf) -> Result { - write_pid_file(&path)?; - Ok(Self { path }) + let file = OpenOptions::new() + .create(true) + .truncate(false) + .read(true) + .write(true) + .open(&path) + .map_err(Error::Audit)?; + match file.try_lock_exclusive() { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + return Err(Error::Aborted(format!( + "PID file {} is in use by another rebalancer", + path.display() + ))); + } + Err(error) => return Err(Error::Audit(error)), + } + file.set_len(0).map_err(Error::Audit)?; + writeln!(&file, "{}", std::process::id()).map_err(Error::Audit)?; + Ok(Self { + path, + file: Some(file), + }) } } impl Drop for PidFileGuard { fn drop(&mut self) { - if let Err(error) = remove_pid_file(&self.path) { - tracing::warn!( - path = %self.path.display(), - error = %error, - "failed to remove PID file" - ); + if self.file.is_none() { + return; + } + match fs::remove_file(&self.path) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => { + tracing::warn!( + path = %self.path.display(), + error = %error, + "failed to remove PID file" + ); + } } + self.file.take(); } } @@ -150,4 +186,48 @@ mod tests { let result = read_pid_file(path); assert!(result.is_err()); } + + #[test] + fn a_second_guard_cannot_replace_a_live_pid_file() { + if std::env::var_os("NANOBOOK_PID_HOLDER").is_some() { + let path = PathBuf::from(std::env::var("NANOBOOK_PID_PATH").unwrap()); + let guard = PidFileGuard::create(path.clone()).unwrap(); + fs::write(path.with_extension("ready"), b"1").unwrap(); + std::thread::sleep(std::time::Duration::from_secs(30)); + drop(guard); + return; + } + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("rebalancer.pid"); + let mut child = std::process::Command::new(std::env::current_exe().unwrap()) + .arg("pid_file::tests::a_second_guard_cannot_replace_a_live_pid_file") + .arg("--exact") + .env("NANOBOOK_PID_HOLDER", "1") + .env("NANOBOOK_PID_PATH", &path) + .spawn() + .unwrap(); + let ready = path.with_extension("ready"); + let started = std::time::Instant::now(); + while !ready.exists() { + if started.elapsed() > std::time::Duration::from_secs(10) { + let _ = child.kill(); + let _ = child.wait(); + panic!("holder did not lock the PID file"); + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + + let error = PidFileGuard::create(path.clone()).unwrap_err(); + assert!( + error.to_string().contains("in use by another rebalancer"), + "{error}" + ); + let _ = child.kill(); + let _ = child.wait(); + let guard = PidFileGuard::create(path.clone()).unwrap(); + assert_eq!(read_pid_file(&path).unwrap(), std::process::id()); + drop(guard); + assert!(!pid_file_exists(&path)); + } } From d6f9ee7dadf301cb323784046140534ad8b84118 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:37:51 +0100 Subject: [PATCH 28/66] fix(recovery): match open orders by filled plus remaining shares Recovery matched an open order only when its remaining quantity equalled the intent, so a partly filled order was missed and resubmitted. An order now matches when filled plus remaining equals the intent; two candidates, or one order claimed by two intents, stop reconciliation with an error. A dry run no longer writes the audit, and cron mode checks the completed window in run_with_client as run does. The IBKR connection-loss gap is documented. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- broker/src/ibkr/orders.rs | 9 +- broker/src/mock.rs | 23 + rebalancer/src/execution.rs | 19 + rebalancer/src/recovery.rs | 423 +++++++++++------- .../tests/crash_injection_integration.rs | 24 +- rebalancer/tests/mutation_recovery.rs | 128 ++++-- rebalancer/tests/mutation_stdout.rs | 3 +- rebalancer/tests/recovery_integration.rs | 101 +++-- rebalancer/tests/run_orchestration.rs | 44 +- rebalancer/tests/verification_tests.rs | 19 +- 10 files changed, 541 insertions(+), 252 deletions(-) diff --git a/broker/src/ibkr/orders.rs b/broker/src/ibkr/orders.rs index 92644a2..91b10ed 100644 --- a/broker/src/ibkr/orders.rs +++ b/broker/src/ibkr/orders.rs @@ -91,9 +91,12 @@ fn is_connection_lost(code: i32) -> bool { (1100..=1102).contains(&code) } -/// Notices the order loop acts on: errors (code < 0), warnings (>= 2000) and -/// the connection codes. Before 0.20.0 the guard admitted only the first two, -/// so the connection check below it could never run. +/// Notices this loop acts on: errors (code < 0), warnings (>= 2000) and +/// connection codes 1100 to 1102. +/// +/// ibapi 2.12 sends an error with request id -1 to the global order-update +/// stream only. This loop reads the per-order subscription. A normal 1100 +/// to 1102 notice does not reach `is_connection_lost`. fn is_order_notice(code: i32) -> bool { !(0..2000).contains(&code) || is_connection_lost(code) } diff --git a/broker/src/mock.rs b/broker/src/mock.rs index 4e4ed0e..5d933bc 100644 --- a/broker/src/mock.rs +++ b/broker/src/mock.rs @@ -102,6 +102,7 @@ impl MockBrokerBuilder { next_order_id: AtomicU64::new(1), submitted_orders: Mutex::new(Vec::new()), open_orders: Mutex::new(Vec::new()), + open_order_statuses: Mutex::new(None), } } } @@ -117,6 +118,8 @@ pub struct MockBroker { next_order_id: AtomicU64, submitted_orders: Mutex>, open_orders: Mutex>, + /// When set, `open_orders` returns these rows instead of `fill_mode`. + open_order_statuses: Mutex>>, } impl MockBroker { @@ -138,6 +141,17 @@ impl MockBroker { .clone() } + /// Make `open_orders` return `orders`. + /// + /// `FillMode` builds every row from 100 shares. Call this when the + /// caller needs an explicit filled quantity and remaining quantity. + pub fn set_open_order_statuses(&self, orders: Vec) { + *self + .open_order_statuses + .lock() + .expect("open_order_statuses mutex poisoned") = Some(orders); + } + fn fill_status(&self) -> (OrderState, u64, u64) { match &self.fill_mode { FillMode::ImmediateFull => (OrderState::Filled, 100, 0), @@ -237,6 +251,15 @@ impl Broker for MockBroker { return Err(BrokerError::NotConnected); } + if let Some(orders) = self + .open_order_statuses + .lock() + .expect("open_order_statuses mutex poisoned") + .clone() + { + return Ok(orders); + } + let open_ids = self.open_orders.lock().expect("open_orders mutex poisoned"); let (status, filled, remaining) = self.fill_status(); diff --git a/rebalancer/src/execution.rs b/rebalancer/src/execution.rs index 9331850..6442f5e 100644 --- a/rebalancer/src/execution.rs +++ b/rebalancer/src/execution.rs @@ -279,6 +279,25 @@ pub fn run_with_client( workdir: &Path, confirm: &mut dyn FnMut() -> Result, ) -> Result<()> { + if opts.cron_mode { + let audit_path = resolve_audit_path(config, workdir); + if audit_path.exists() { + let window_id = target.window_id(); + let mut audit_check = AuditLog::open_in(&audit_path, workdir)?; + if let Some(existing_seq) = audit_check.check_window_already_complete(&window_id)? { + warn!( + "Rebalance window {} already completed with sequence number {} — refusing to run", + window_id, existing_seq + ); + audit::log_idempotency_rejection(&mut audit_check, &window_id, existing_seq)?; + return Err(Error::IdempotencyRejection { + window_id, + sequence_number: existing_seq, + }); + } + } + } + let _pid_guard = crate::pid_file::PidFileGuard::create(workdir.join(crate::pid_file::DEFAULT_PID_FILE))?; diff --git a/rebalancer/src/recovery.rs b/rebalancer/src/recovery.rs index 089eda2..1a593ef 100644 --- a/rebalancer/src/recovery.rs +++ b/rebalancer/src/recovery.rs @@ -7,6 +7,8 @@ use crate::error::{Error, Result}; use crate::target::TargetSpec; use nanobook::Symbol; use nanobook_broker::Broker; +#[cfg(feature = "write_ahead_logging")] +use nanobook_broker::types::BrokerOrderStatus; use nanobook_broker::types::f64_cents_checked; use serde::{Deserialize, Serialize}; #[cfg(feature = "write_ahead_logging")] @@ -308,24 +310,10 @@ fn audit_dollars_to_cents(limit_dollars: f64) -> i64 { .unwrap_or_else(|_| (limit_dollars * 100.0).round() as i64) } -/// Query the broker for an order matching the given criteria with retry logic. -/// -/// This function attempts to find an order in the broker's open orders -/// that matches the given symbol and quantity. It uses heuristic matching -/// since the broker API doesn't support querying by client_order_id. -/// It retries on network failures with exponential backoff. -/// -/// # Arguments -/// -/// * `broker` - The broker connection to query -/// * `symbol` - The symbol to search for -/// * `quantity` - The order quantity to match +/// Find one open order whose filled and remaining shares sum to `quantity`. /// -/// # Returns -/// -/// * `Ok(Some(order_id))` - Order found at broker matching the criteria -/// * `Ok(None)` - Order not found at broker -/// * `Err(Error)` - Broker query failed after all retries +/// `BrokerOrderStatus` has no symbol. A filled order does not match. +/// Two matches return an error. `symbol` is only a log field. #[cfg(feature = "write_ahead_logging")] pub fn reconcile_order_intent( broker: &dyn Broker, @@ -335,10 +323,9 @@ pub fn reconcile_order_intent( reconcile_order_intent_with(broker, symbol, quantity, &mut std::thread::sleep) } -/// Query the broker for an open order whose remaining quantity matches `quantity`. +/// Find one open order whose filled and remaining shares sum to `quantity`. /// -/// `BrokerOrderStatus` has no symbol or side, so remaining quantity is the -/// match key. `symbol` is recorded in the log line. +/// The open-order query retries five times. `sleep` receives each delay. #[cfg(feature = "write_ahead_logging")] pub fn reconcile_order_intent_with( broker: &dyn Broker, @@ -346,73 +333,76 @@ pub fn reconcile_order_intent_with( quantity: i64, sleep: &mut dyn FnMut(Duration), ) -> Result> { + let expected = u64::try_from(quantity).unwrap_or(0); + let orders = fetch_open_orders(broker, sleep)?; + let mut matched = None; + for order in &orders { + if !order_matches_original_quantity(order, expected) { + continue; + } + if matched.is_some() { + return Err(Error::Recovery(format!( + "More than one open order matches quantity {quantity}" + ))); + } + matched = Some(order.id.0); + tracing::debug!( + symbol = %symbol, + quantity, + broker_order_id = order.id.0, + filled = order.filled_quantity, + remaining = order.remaining_quantity, + "matched open order by original quantity" + ); + } + Ok(matched) +} + +/// An open order matches when its filled and remaining shares sum to `expected`. +#[cfg(feature = "write_ahead_logging")] +fn order_matches_original_quantity(order: &BrokerOrderStatus, expected: u64) -> bool { + order.remaining_quantity > 0 + && order.filled_quantity.checked_add(order.remaining_quantity) == Some(expected) +} + +/// Read open orders. Retry five times on a broker error. +#[cfg(feature = "write_ahead_logging")] +fn fetch_open_orders( + broker: &dyn Broker, + sleep: &mut dyn FnMut(Duration), +) -> Result> { const MAX_RETRIES: usize = 5; const BASE_DELAY_MS: u64 = 1000; - let expected_remaining = u64::try_from(quantity).unwrap_or(0); - - for attempt in 0..MAX_RETRIES { + let mut attempt = 0; + loop { match broker.open_orders() { - Ok(orders) => { - for order in &orders { - if order.remaining_quantity > 0 - && order.remaining_quantity == expected_remaining - { - tracing::debug!( - symbol = %symbol, - quantity, - broker_order_id = order.id.0, - remaining = order.remaining_quantity, - "matched open order by remaining quantity" - ); - return Ok(Some(order.id.0)); - } - } - return Ok(None); + Ok(orders) => return Ok(orders), + Err(error) if attempt + 1 < MAX_RETRIES => { + let delay_ms = BASE_DELAY_MS * 2_u64.pow(attempt as u32); + tracing::warn!( + "Broker query failed (attempt {}/{}), retrying in {}ms: {}", + attempt + 1, + MAX_RETRIES, + delay_ms, + error + ); + sleep(Duration::from_millis(delay_ms)); + attempt += 1; } - Err(e) => { - if attempt < MAX_RETRIES - 1 { - let delay_ms = BASE_DELAY_MS * 2_u64.pow(attempt as u32); - tracing::warn!( - symbol = %symbol, - "Broker query failed (attempt {}/{}), retrying in {}ms: {}", - attempt + 1, - MAX_RETRIES, - delay_ms, - e - ); - sleep(Duration::from_millis(delay_ms)); - } else { - return Err(Error::Recovery(format!( - "Broker query failed after {} attempts: {}", - MAX_RETRIES, e - ))); - } + Err(error) => { + return Err(Error::Recovery(format!( + "Broker query failed after {MAX_RETRIES} attempts: {error}" + ))); } } } - - Err(Error::Recovery( - "Unexpected error in broker reconciliation".to_string(), - )) } -/// Reconcile incomplete order intents with the broker and update audit log. -/// -/// This function scans for incomplete intents (orders with client_order_id -/// but neither submitted nor failed), queries the broker for each, and -/// updates the audit log with the reconciliation results. -/// -/// # Arguments +/// Read open orders once and match each incomplete intent. /// -/// * `broker` - The broker connection to query -/// * `recovered_state` - The reconstructed state from audit log -/// * `audit_log_path` - Path to the audit log file for updates -/// -/// # Returns -/// -/// * `Ok(())` - All incomplete intents reconciled successfully -/// * `Err(Error)` - Reconciliation failed for one or more intents +/// An order claimed by two intents matches none of them. No match appends +/// `OrderFailed`. One unshared match appends `OrderSubmitted`. #[cfg(feature = "write_ahead_logging")] pub fn reconcile_incomplete_intents( broker: &dyn Broker, @@ -425,70 +415,102 @@ pub fn reconcile_incomplete_intents( let mut failed_count = 0; let mut next_sequence = recovered_state.sequence_number + 1; - // Get the parent directory as workdir for audit log validation let workdir = audit_log_path .parent() .ok_or_else(|| Error::Recovery("Invalid audit log path".to_string()))?; - for order in &recovered_state.orders { - // Check if this is an incomplete intent - if order.client_order_id.is_some() && !order.submitted && !order.failed { - let symbol = &order.symbol; - let quantity = order.shares; + let incomplete: Vec<&RecoveredOrder> = recovered_state + .orders + .iter() + .filter(|order| order.client_order_id.is_some() && !order.submitted && !order.failed) + .collect(); + + let open_orders = if incomplete.is_empty() { + Vec::new() + } else { + match fetch_open_orders(broker, &mut std::thread::sleep) { + Ok(orders) => orders, + Err(error) => { + tracing::error!("Open-order query failed: {}", error); + failed_count = incomplete.len(); + tracing::info!( + "Broker reconciliation complete: {} reconciled, {} failed", + reconciled_count, + failed_count + ); + return Err(Error::Recovery(format!( + "Failed to reconcile {failed_count} incomplete intents" + ))); + } + } + }; + let candidates: Vec> = incomplete + .iter() + .map(|order| { + let expected = u64::try_from(order.shares).unwrap_or(0); + open_orders + .iter() + .filter(|status| order_matches_original_quantity(status, expected)) + .map(|status| status.id.0) + .collect() + }) + .collect(); + + for (order, ids) in incomplete.into_iter().zip(candidates.iter()) { + let symbol = &order.symbol; + tracing::info!( + "Reconciling incomplete intent for {} (client_order_id: {:?})", + symbol.as_str(), + order.client_order_id + ); + + let unique = ids.len() == 1 + && candidates + .iter() + .filter(|other| other.contains(&ids[0])) + .count() + == 1; + if ids.is_empty() { + tracing::info!("Order not found at broker, appending OrderFailed event"); + let mut audit = AuditLog::open_in(audit_log_path, workdir)?; + audit.log_checkpoint( + Checkpoint::OrderFailed, + next_sequence, + serde_json::json!({ + "symbol": symbol.as_str(), + "reason": "not_found_at_broker", + "reconciled": true, + }), + )?; + next_sequence += 1; + reconciled_count += 1; + } else if unique { + let broker_order_id = ids[0]; tracing::info!( - "Reconciling incomplete intent for {} (client_order_id: {:?})", - symbol.as_str(), - order.client_order_id + "Order found at broker with ID {}, appending OrderSubmitted event", + broker_order_id ); - - match reconcile_order_intent(broker, symbol, quantity) { - Ok(Some(broker_order_id)) => { - // Order found at broker - append OrderSubmitted event - tracing::info!( - "Order found at broker with ID {}, appending OrderSubmitted event", - broker_order_id - ); - let mut audit = AuditLog::open_in(audit_log_path, workdir)?; - audit.log_checkpoint( - Checkpoint::OrderSubmitted, - next_sequence, - serde_json::json!({ - "symbol": symbol.as_str(), - "ibkr_id": broker_order_id, - "reconciled": true, - }), - )?; - next_sequence += 1; - reconciled_count += 1; - } - Ok(None) => { - // Order not found at broker - append OrderFailed event - tracing::info!("Order not found at broker, appending OrderFailed event",); - let mut audit = AuditLog::open_in(audit_log_path, workdir)?; - audit.log_checkpoint( - Checkpoint::OrderFailed, - next_sequence, - serde_json::json!({ - "symbol": symbol.as_str(), - "reason": "not_found_at_broker", - "reconciled": true, - }), - )?; - next_sequence += 1; - reconciled_count += 1; - } - Err(e) => { - // Broker query failed - log error and continue - tracing::error!( - "Failed to reconcile intent for {} (client_order_id: {:?}): {}", - symbol.as_str(), - order.client_order_id, - e - ); - failed_count += 1; - } - } + let mut audit = AuditLog::open_in(audit_log_path, workdir)?; + audit.log_checkpoint( + Checkpoint::OrderSubmitted, + next_sequence, + serde_json::json!({ + "symbol": symbol.as_str(), + "ibkr_id": broker_order_id, + "reconciled": true, + }), + )?; + next_sequence += 1; + reconciled_count += 1; + } else { + tracing::error!( + symbol = %symbol, + quantity = order.shares, + matches = ids.len(), + "Intent has no unique open order" + ); + failed_count += 1; } } @@ -1140,9 +1162,10 @@ pub fn run_recover( None }; - // Attempt broker reconciliation for incomplete intents if feature is enabled + // Attempt broker reconciliation for incomplete intents if feature is enabled. + // A dry run prints the plan and does not append audit events. #[cfg(feature = "write_ahead_logging")] - if let Some(broker) = broker { + if !dry_run && let Some(broker) = broker { // Check if there are incomplete intents to reconcile let has_incomplete_intents = recovered_state .orders @@ -1279,24 +1302,19 @@ mod tests { #[cfg(feature = "write_ahead_logging")] #[test] fn reconcile_order_intent_matches_quantity() { - use nanobook::Price; - use nanobook_broker::mock::{FillMode, MockBroker}; - use nanobook_broker::types::{BrokerOrder, BrokerOrderType}; - use nanobook_broker::{Broker, BrokerSide}; + use nanobook_broker::Broker; + use nanobook_broker::mock::MockBroker; + use nanobook_broker::types::{BrokerOrderStatus, OrderId, OrderState}; - let mut broker = MockBroker::builder() - .fill_mode(FillMode::ImmediatePartial(0.5)) - .build(); + let mut broker = MockBroker::builder().build(); broker.connect().unwrap(); - broker - .submit_order(&BrokerOrder { - symbol: Symbol::new("AAPL"), - side: BrokerSide::Buy, - quantity: 50, - order_type: BrokerOrderType::Limit(Price(16_000)), - client_order_id: None, - }) - .unwrap(); + broker.set_open_order_statuses(vec![BrokerOrderStatus { + id: OrderId(1), + status: OrderState::Submitted, + filled_quantity: 0, + remaining_quantity: 50, + avg_fill_price_cents: 16_000, + }]); let matched = reconcile_order_intent(&broker, &Symbol::new("AAPL"), 50).unwrap(); let other = reconcile_order_intent(&broker, &Symbol::new("MSFT"), 25).unwrap(); @@ -1304,6 +1322,85 @@ mod tests { assert_eq!(other, None); } + #[cfg(feature = "write_ahead_logging")] + #[test] + fn reconcile_order_intent_matches_partial_original_quantity() { + use nanobook_broker::Broker; + use nanobook_broker::mock::MockBroker; + use nanobook_broker::types::{BrokerOrderStatus, OrderId, OrderState}; + + let mut broker = MockBroker::builder().build(); + broker.connect().unwrap(); + // 50-share order, 25 filled, 25 still open. + broker.set_open_order_statuses(vec![BrokerOrderStatus { + id: OrderId(4), + status: OrderState::PartiallyFilled, + filled_quantity: 25, + remaining_quantity: 25, + avg_fill_price_cents: 16_000, + }]); + + let matched = reconcile_order_intent(&broker, &Symbol::new("AAPL"), 50).unwrap(); + assert_eq!(matched, Some(4)); + let remainder_only = reconcile_order_intent(&broker, &Symbol::new("AAPL"), 25).unwrap(); + assert_eq!(remainder_only, None); + + // 20 shares filled and 30 left is a 50-share order, not a 30-share order. + broker.set_open_order_statuses(vec![BrokerOrderStatus { + id: OrderId(8), + status: OrderState::PartiallyFilled, + filled_quantity: 20, + remaining_quantity: 30, + avg_fill_price_cents: 16_000, + }]); + assert_eq!( + reconcile_order_intent(&broker, &Symbol::new("AAPL"), 30).unwrap(), + None + ); + assert_eq!( + reconcile_order_intent(&broker, &Symbol::new("AAPL"), 50).unwrap(), + Some(8) + ); + } + + #[cfg(feature = "write_ahead_logging")] + #[test] + fn reconcile_order_intent_rejects_two_orders_of_the_same_quantity() { + use nanobook_broker::Broker; + use nanobook_broker::mock::MockBroker; + use nanobook_broker::types::{BrokerOrderStatus, OrderId, OrderState}; + + let mut broker = MockBroker::builder().build(); + broker.connect().unwrap(); + broker.set_open_order_statuses(vec![ + BrokerOrderStatus { + id: OrderId(4), + status: OrderState::Submitted, + filled_quantity: 0, + remaining_quantity: 50, + avg_fill_price_cents: 0, + }, + BrokerOrderStatus { + id: OrderId(5), + status: OrderState::Submitted, + filled_quantity: 0, + remaining_quantity: 50, + avg_fill_price_cents: 0, + }, + ]); + + let err = reconcile_order_intent(&broker, &Symbol::new("AAPL"), 50).unwrap_err(); + match err { + Error::Recovery(message) => { + assert!( + message.contains("More than one open order matches quantity 50"), + "{message}" + ); + } + other => panic!("expected Recovery, got {other:?}"), + } + } + #[test] fn reconstruct_state_with_checkpoints() { let dir = tempdir().unwrap(); @@ -1936,26 +2033,22 @@ mod tests { #[cfg(feature = "write_ahead_logging")] #[test] fn reconcile_order_intent_found() { - use nanobook_broker::mock::{FillMode, MockBroker}; - use nanobook_broker::{BrokerOrder, BrokerOrderType, BrokerSide}; + use nanobook_broker::Broker; + use nanobook_broker::mock::MockBroker; + use nanobook_broker::types::{BrokerOrderStatus, OrderId, OrderState}; let mut broker = MockBroker::builder() - .fill_mode(FillMode::ImmediatePartial(0.5)) .with_position(Symbol::new("AAPL"), 100, 150_00) .build(); broker.connect().unwrap(); + broker.set_open_order_statuses(vec![BrokerOrderStatus { + id: OrderId(1), + status: OrderState::Submitted, + filled_quantity: 0, + remaining_quantity: 50, + avg_fill_price_cents: 0, + }]); - // Submit an order - let order = BrokerOrder { - symbol: Symbol::new("AAPL"), - side: BrokerSide::Buy, - quantity: 50, - order_type: BrokerOrderType::Market, - client_order_id: None, - }; - broker.submit_order(&order).unwrap(); - - // Query for the order let result = reconcile_order_intent(&broker, &Symbol::new("AAPL"), 50).unwrap(); assert!(result.is_some()); } diff --git a/rebalancer/tests/crash_injection_integration.rs b/rebalancer/tests/crash_injection_integration.rs index 8c36d3f..e3be086 100644 --- a/rebalancer/tests/crash_injection_integration.rs +++ b/rebalancer/tests/crash_injection_integration.rs @@ -6,9 +6,9 @@ #[cfg(feature = "write_ahead_logging")] use nanobook::Symbol; #[cfg(feature = "write_ahead_logging")] -use nanobook_broker::mock::{FillMode, MockBroker}; +use nanobook_broker::Broker; #[cfg(feature = "write_ahead_logging")] -use nanobook_broker::{Broker, BrokerOrder, BrokerOrderType, BrokerSide}; +use nanobook_broker::mock::{FillMode, MockBroker}; use nanobook_rebalancer::audit::{AuditLog, Checkpoint, parse_audit_events}; use nanobook_rebalancer::recovery::{RecoveryAction, reconstruct_state}; @@ -223,22 +223,18 @@ fn test_crash_after_broker_call_before_order_submitted_logging() { #[cfg(not(feature = "write_ahead_logging"))] assert_eq!(action, RecoveryAction::ManualReview); - // Create MockBroker with the order already submitted (simulating broker call succeeded) + // 50 shares open, none filled. The mock fill mode is based on 100 shares. let mut broker = MockBroker::builder() - .fill_mode(FillMode::ImmediatePartial(0.5)) .with_position(Symbol::new("AAPL"), 100, 150_00) .build(); broker.connect().unwrap(); - - // Submit the order to broker (simulating the broker call that happened before crash) - let order = BrokerOrder { - symbol: Symbol::new("AAPL"), - side: BrokerSide::Buy, - quantity: 50, - order_type: BrokerOrderType::Market, - client_order_id: None, - }; - broker.submit_order(&order).unwrap(); + broker.set_open_order_statuses(vec![nanobook_broker::types::BrokerOrderStatus { + id: nanobook_broker::types::OrderId(1), + status: nanobook_broker::types::OrderState::Submitted, + filled_quantity: 0, + remaining_quantity: 50, + avg_fill_price_cents: 0, + }]); // Run broker reconciliation #[cfg(feature = "write_ahead_logging")] diff --git a/rebalancer/tests/mutation_recovery.rs b/rebalancer/tests/mutation_recovery.rs index 1413da4..4560f24 100644 --- a/rebalancer/tests/mutation_recovery.rs +++ b/rebalancer/tests/mutation_recovery.rs @@ -6,28 +6,32 @@ mod common; use common::LogCapture; -use nanobook::Symbol; use nanobook_broker::Broker; use nanobook_broker::mock::{FillMode, MockBroker}; -use nanobook_broker::{BrokerOrder, BrokerOrderType, BrokerSide}; use nanobook_rebalancer::audit::{AuditLog, Checkpoint, parse_audit_events}; +use nanobook_rebalancer::error::Error; use nanobook_rebalancer::recovery::{ RecoveredState, RecoveryAction, reconcile_incomplete_intents, reconstruct_state, }; -/// run_started, then one 50-share order intent for AAPL and one for MSFT. -fn write_two_incomplete_intents(path: &std::path::Path, workdir: &std::path::Path) { +/// run_started, then one order intent for AAPL and one for MSFT. +fn write_two_incomplete_intents( + path: &std::path::Path, + workdir: &std::path::Path, + aapl_shares: i64, + msft_shares: i64, +) { let mut log = AuditLog::open_in(path, workdir).unwrap(); log.log_checkpoint(Checkpoint::RunStarted, 1, serde_json::json!({"t": 1})) .unwrap(); - for (sequence, symbol) in [(2, "AAPL"), (3, "MSFT")] { + for (sequence, symbol, shares) in [(2, "AAPL", aapl_shares), (3, "MSFT", msft_shares)] { log.log_checkpoint( Checkpoint::OrderIntent, sequence, serde_json::json!({ "symbol": symbol, "action": "Buy", - "shares": 50, + "shares": shares, "limit": 160.0, "client_order_id": format!("c-{symbol}"), }), @@ -36,43 +40,103 @@ fn write_two_incomplete_intents(path: &std::path::Path, workdir: &std::path::Pat } } +fn open_status(id: u64, remaining: u64) -> nanobook_broker::types::BrokerOrderStatus { + nanobook_broker::types::BrokerOrderStatus { + id: nanobook_broker::types::OrderId(id), + status: nanobook_broker::types::OrderState::Submitted, + filled_quantity: 0, + remaining_quantity: remaining, + avg_fill_price_cents: 0, + } +} + #[test] -fn reconciliation_summary_counts_intents_found_at_the_broker() { +fn one_open_order_does_not_submit_two_intents_of_the_same_quantity() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("audit.jsonl"); - write_two_incomplete_intents(&path, dir.path()); + write_two_incomplete_intents(&path, dir.path(), 50, 50); - // The broker holds one open order with 50 shares remaining. - let mut broker = MockBroker::builder() - .fill_mode(FillMode::ImmediatePartial(0.5)) - .build(); + // One live 50-share order, nothing filled. Both intents ask for 50. + // The status has no symbol, so the order cannot be given to either. + let mut broker = MockBroker::builder().build(); broker.connect().unwrap(); - broker - .submit_order(&BrokerOrder { - symbol: Symbol::new("AAPL"), - side: BrokerSide::Buy, - quantity: 50, - order_type: BrokerOrderType::Market, - client_order_id: None, - }) - .unwrap(); + broker.set_open_order_statuses(vec![open_status(7, 50)]); let (state, _) = reconstruct_state(&path).unwrap(); - let capture = LogCapture::default(); - capture - .run(|| reconcile_incomplete_intents(&broker, &state, &path)) - .unwrap(); + let err = reconcile_incomplete_intents(&broker, &state, &path).unwrap_err(); + match err { + Error::Recovery(message) => { + assert!( + message.contains("Failed to reconcile 2 incomplete intents"), + "{message}" + ); + } + other => panic!("expected Recovery, got {other:?}"), + } + let events = parse_audit_events(&path).unwrap(); + assert_eq!(events.len(), 3); + assert!(events.iter().all(|event| event.event != "order_submitted")); + assert!(events.iter().all(|event| event.event != "order_failed")); +} + +#[test] +fn two_open_orders_of_one_quantity_match_neither_intent() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + write_two_incomplete_intents(&path, dir.path(), 50, 50); + + let mut broker = MockBroker::builder().build(); + broker.connect().unwrap(); + broker.set_open_order_statuses(vec![open_status(7, 50), open_status(8, 50)]); + + let (state, _) = reconstruct_state(&path).unwrap(); + let err = reconcile_incomplete_intents(&broker, &state, &path).unwrap_err(); + match err { + Error::Recovery(message) => { + assert!( + message.contains("Failed to reconcile 2 incomplete intents"), + "{message}" + ); + } + other => panic!("expected Recovery, got {other:?}"), + } + let events = parse_audit_events(&path).unwrap(); + assert_eq!(events.len(), 3); + assert!(events.iter().all(|event| event.event != "order_submitted")); + assert!(events.iter().all(|event| event.event != "order_failed")); +} +#[test] +fn two_open_orders_of_different_quantities_submit_both_intents() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + write_two_incomplete_intents(&path, dir.path(), 50, 25); + + let mut broker = MockBroker::builder().build(); + broker.connect().unwrap(); + broker.set_open_order_statuses(vec![open_status(7, 50), open_status(8, 25)]); + + let (state, _) = reconstruct_state(&path).unwrap(); + reconcile_incomplete_intents(&broker, &state, &path).unwrap(); let events = parse_audit_events(&path).unwrap(); assert_eq!(events.len(), 5); assert_eq!(events[3].event, "order_submitted"); - assert_eq!(events[3].sequence_number, Some(4)); + assert_eq!( + events[3].data.get("symbol").and_then(|v| v.as_str()), + Some("AAPL") + ); + assert_eq!( + events[3].data.get("ibkr_id").and_then(|v| v.as_u64()), + Some(7) + ); assert_eq!(events[4].event, "order_submitted"); - assert_eq!(events[4].sequence_number, Some(5)); - let text = capture.text(); - assert!( - text.contains("Broker reconciliation complete: 2 reconciled, 0 failed"), - "log was: {text}" + assert_eq!( + events[4].data.get("symbol").and_then(|v| v.as_str()), + Some("MSFT") + ); + assert_eq!( + events[4].data.get("ibkr_id").and_then(|v| v.as_u64()), + Some(8) ); } @@ -80,7 +144,7 @@ fn reconciliation_summary_counts_intents_found_at_the_broker() { fn reconciliation_summary_counts_intents_missing_at_the_broker() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("audit.jsonl"); - write_two_incomplete_intents(&path, dir.path()); + write_two_incomplete_intents(&path, dir.path(), 50, 50); let mut broker = MockBroker::builder() .fill_mode(FillMode::ImmediateFull) diff --git a/rebalancer/tests/mutation_stdout.rs b/rebalancer/tests/mutation_stdout.rs index 3c0fc72..3eebdb7 100644 --- a/rebalancer/tests/mutation_stdout.rs +++ b/rebalancer/tests/mutation_stdout.rs @@ -249,7 +249,8 @@ fn child_recover_with_broker(config: &Config, scenario: &str) { .fill_mode(FillMode::ImmediateFull) .build(); broker.connect().unwrap(); - let _ = run_recover(config, &spec(), true, Some(&broker)); + // A dry run does not reconcile. This child checks the real recover path. + let _ = run_recover(config, &spec(), false, Some(&broker)); } #[test] diff --git a/rebalancer/tests/recovery_integration.rs b/rebalancer/tests/recovery_integration.rs index 289e7a1..12833d0 100644 --- a/rebalancer/tests/recovery_integration.rs +++ b/rebalancer/tests/recovery_integration.rs @@ -589,21 +589,18 @@ fn test_broker_reconciliation_incomplete_intent_found() { .unwrap(); } - // Create MockBroker with the order actually submitted + // 50 shares open, none filled. The mock fill mode is based on 100 shares. let mut broker = MockBroker::builder() - .fill_mode(FillMode::ImmediatePartial(0.5)) .with_position(Symbol::new("AAPL"), 100, 150_00) .build(); broker.connect().unwrap(); - - let order = BrokerOrder { - symbol: Symbol::new("AAPL"), - side: BrokerSide::Buy, - quantity: 50, - order_type: BrokerOrderType::Market, - client_order_id: None, - }; - broker.submit_order(&order).unwrap(); + broker.set_open_order_statuses(vec![nanobook_broker::types::BrokerOrderStatus { + id: nanobook_broker::types::OrderId(1), + status: nanobook_broker::types::OrderState::Submitted, + filled_quantity: 0, + remaining_quantity: 50, + avg_fill_price_cents: 0, + }]); // Reconstruct state let (state, _) = reconstruct_state(&audit_path).unwrap(); @@ -958,25 +955,21 @@ fn reconcile_skips_already_submitted_intents() { #[cfg(feature = "write_ahead_logging")] #[test] fn reconcile_appends_submitted_and_failed_in_sequence() { - use nanobook::Price; use nanobook_rebalancer::recovery::reconcile_incomplete_intents; let dir = tempfile::tempdir().unwrap(); let audit_path = dir.path().join("audit.jsonl"); log_run_started_and_intents(&audit_path, dir.path()); - let mut broker = MockBroker::builder() - .fill_mode(FillMode::ImmediatePartial(0.5)) - .build(); + let mut broker = MockBroker::builder().build(); broker.connect().unwrap(); - broker - .submit_order(&BrokerOrder { - symbol: Symbol::new("AAPL"), - side: BrokerSide::Buy, - quantity: 50, - order_type: BrokerOrderType::Limit(Price(16_000)), - client_order_id: None, - }) - .unwrap(); + // AAPL's 50 shares are still open. MSFT's 25 shares are not. + broker.set_open_order_statuses(vec![nanobook_broker::types::BrokerOrderStatus { + id: nanobook_broker::types::OrderId(1), + status: nanobook_broker::types::OrderState::Submitted, + filled_quantity: 0, + remaining_quantity: 50, + avg_fill_price_cents: 16_000, + }]); let (state, _) = reconstruct_state(&audit_path).unwrap(); reconcile_incomplete_intents(&broker, &state, &audit_path).unwrap(); let events = parse_audit_events(&audit_path).unwrap(); @@ -1207,7 +1200,7 @@ audit_file = "audit.jsonl" } let mut broker = MockBroker::builder().build(); broker.connect().unwrap(); - run_recover(&config, &spec, true, Some(&broker)).unwrap(); + run_recover(&config, &spec, false, Some(&broker)).unwrap(); let events = parse_audit_events(&config.audit_path()).unwrap(); assert_eq!(events.len(), 3); let last = events.last().unwrap(); @@ -1221,3 +1214,61 @@ audit_file = "audit.jsonl" Some(true) ); } + +#[cfg(feature = "write_ahead_logging")] +#[test] +fn run_recover_dry_run_does_not_write_the_audit() { + let dir = tempfile::tempdir().unwrap(); + let config: Config = toml::from_str(&format!( + r#" +[connection] +host = "127.0.0.1" +port = 4002 +client_id = 1 +[account] +id = "DU1" +type = "cash" +[execution] +[risk] +[cost] +[logging] +dir = "{}" +audit_file = "audit.jsonl" +"#, + dir.path().display() + )) + .unwrap(); + let spec = TargetSpec::from_json( + r#"{ + "timestamp": "2026-02-08T15:30:00Z", + "targets": [{ "symbol": "AAPL", "weight": 0.5 }] + }"#, + ) + .unwrap(); + { + let mut log = AuditLog::open_in(&config.audit_path(), dir.path()).unwrap(); + log.log_checkpoint( + nanobook_rebalancer::audit::Checkpoint::RunStarted, + 1, + serde_json::json!({"target": "test"}), + ) + .unwrap(); + log.log_checkpoint( + nanobook_rebalancer::audit::Checkpoint::OrderIntent, + 2, + serde_json::json!({ + "symbol": "AAPL", + "action": "Buy", + "shares": 50, + "limit": 160.0, + "client_order_id": "c", + }), + ) + .unwrap(); + } + let before = std::fs::read(config.audit_path()).unwrap(); + let mut broker = MockBroker::builder().build(); + broker.connect().unwrap(); + run_recover(&config, &spec, true, Some(&broker)).unwrap(); + assert_eq!(std::fs::read(config.audit_path()).unwrap(), before); +} diff --git a/rebalancer/tests/run_orchestration.rs b/rebalancer/tests/run_orchestration.rs index a5cbf87..68b7b46 100644 --- a/rebalancer/tests/run_orchestration.rs +++ b/rebalancer/tests/run_orchestration.rs @@ -8,7 +8,7 @@ use nanobook_broker::error::BrokerError; use nanobook_broker::ibkr::orders::{OrderOutcome, OrderResult}; use nanobook_broker::types::{Account, Position, Quote}; use nanobook_broker::{BrokerSide, ClientOrderId}; -use nanobook_rebalancer::audit::parse_audit_events; +use nanobook_rebalancer::audit::{self, parse_audit_events}; use nanobook_rebalancer::broker::BrokerGateway; use nanobook_rebalancer::config::Config; use nanobook_rebalancer::error::{Error, Result}; @@ -424,6 +424,48 @@ fn shutdown_after_partial_cancels_current_and_skips_rest() { ); } +#[test] +fn cron_mode_refuses_a_completed_window_before_orders() { + let dir = tempfile::tempdir().unwrap(); + let config = config(dir.path()); + let spec = spec_three(); + let window_id = spec.window_id(); + { + let mut audit = audit::AuditLog::open_in(&config.audit_path(), dir.path()).unwrap(); + audit::log_cron_completed(&mut audit, 42, &window_id, 1, 1, 0).unwrap(); + } + let shutdown = ShutdownFlag::new(); + let broker = ScriptedBroker::new(dir.path(), shutdown.clone(), Vec::new()); + let mut confirm = || -> Result { panic!("confirm must not be called") }; + match run_with_client( + &config, + &spec, + &opts(true, false, true), + &broker, + &shutdown, + dir.path(), + &mut confirm, + ) { + Err(Error::IdempotencyRejection { + window_id: got_window, + sequence_number, + }) => { + assert_eq!(got_window, window_id); + assert_eq!(sequence_number, 42); + } + other => panic!("expected IdempotencyRejection, got {other:?}"), + } + assert!(broker.executes.borrow().is_empty()); + assert!(!dir.path().join(DEFAULT_PID_FILE).exists()); + let events = parse_audit_events(&config.audit_path()).unwrap(); + assert!( + events + .iter() + .any(|event| event.event == "idempotency_rejection") + ); + assert!(events.iter().all(|event| event.event != "run_started")); +} + #[test] fn confirm_error_is_aborted() { let dir = tempfile::tempdir().unwrap(); diff --git a/rebalancer/tests/verification_tests.rs b/rebalancer/tests/verification_tests.rs index 7226557..a2b20cc 100644 --- a/rebalancer/tests/verification_tests.rs +++ b/rebalancer/tests/verification_tests.rs @@ -637,21 +637,18 @@ fn test_broker_reconciliation_finds_order() { // Recover state let (state, _) = reconstruct_state(&audit_path).unwrap(); - // Create MockBroker with the order + // 50 shares open, none filled. The mock fill mode is based on 100 shares. let mut broker = MockBroker::builder() - .fill_mode(FillMode::ImmediatePartial(0.5)) .with_position(Symbol::new("AAPL"), 100, 150_00) .build(); broker.connect().unwrap(); - - let order = BrokerOrder { - symbol: Symbol::new("AAPL"), - side: BrokerSide::Buy, - quantity: 50, - order_type: BrokerOrderType::Market, - client_order_id: None, - }; - broker.submit_order(&order).unwrap(); + broker.set_open_order_statuses(vec![nanobook_broker::types::BrokerOrderStatus { + id: nanobook_broker::types::OrderId(1), + status: nanobook_broker::types::OrderState::Submitted, + filled_quantity: 0, + remaining_quantity: 50, + avg_fill_price_cents: 0, + }]); // Run broker reconciliation #[cfg(feature = "write_ahead_logging")] From 7275461b32728b6d2f4f5383d110a335f04fc027 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:47:35 +0100 Subject: [PATCH 29/66] fix(rebalancer): PID lock and log-dir checks behave the same on Windows Windows reports a held file lock as ERROR_LOCK_VIOLATION, not WouldBlock, so a second rebalancer got an audit error instead of the in-use message. Windows also answers a free-space query for a missing directory with the volume's space, so a missing log directory went unreported. Both now match Unix; the PID test waits up to 5 s for Windows to release a killed holder's lock. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- rebalancer/src/pid_file.rs | 18 ++++++++++++++++-- rebalancer/src/validator.rs | 11 +++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/rebalancer/src/pid_file.rs b/rebalancer/src/pid_file.rs index 9ed3209..85ea8c4 100644 --- a/rebalancer/src/pid_file.rs +++ b/rebalancer/src/pid_file.rs @@ -101,7 +101,11 @@ impl PidFileGuard { .map_err(Error::Audit)?; match file.try_lock_exclusive() { Ok(()) => {} - Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + // Unix reports a held lock as WouldBlock; Windows as ERROR_LOCK_VIOLATION (33). + Err(error) + if error.kind() == std::io::ErrorKind::WouldBlock + || error.raw_os_error() == fs2::lock_contended_error().raw_os_error() => + { return Err(Error::Aborted(format!( "PID file {} is in use by another rebalancer", path.display() @@ -225,7 +229,17 @@ mod tests { ); let _ = child.kill(); let _ = child.wait(); - let guard = PidFileGuard::create(path.clone()).unwrap(); + // Windows may release a killed process's lock a moment after the process exits. + let started = std::time::Instant::now(); + let guard = loop { + match PidFileGuard::create(path.clone()) { + Ok(guard) => break guard, + Err(_) if started.elapsed() < std::time::Duration::from_secs(5) => { + std::thread::sleep(std::time::Duration::from_millis(50)); + } + Err(error) => panic!("lock not released after the holder exited: {error}"), + } + }; assert_eq!(read_pid_file(&path).unwrap(), std::process::id()); drop(guard); assert!(!pid_file_exists(&path)); diff --git a/rebalancer/src/validator.rs b/rebalancer/src/validator.rs index 63ae3a2..ac05bf7 100644 --- a/rebalancer/src/validator.rs +++ b/rebalancer/src/validator.rs @@ -237,6 +237,17 @@ pub fn validate_file_permissions(config: &Config) -> Vec { pub fn validate_disk_space(config: &Config) -> Vec { let audit_path = config.audit_path(); let dir = audit_path.parent().unwrap_or_else(|| Path::new(".")); + // Windows answers for the volume even when the directory is missing, so check it first. + if !dir.is_dir() { + return vec![ValidationIssue::new( + "logging.dir", + format!( + "cannot determine available space for {}: directory does not exist", + dir.display() + ), + "verify the logging directory exists and the filesystem is accessible", + )]; + } match fs2::available_space(dir) { Ok(bytes) => validate_available_log_space(bytes, config), Err(error) => vec![ValidationIssue::new( From 223f0b4bd0d3f533f380380b5b4a1fe8db037c4e Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:43:13 +0100 Subject: [PATCH 30/66] fix(pid_file): lock a separate .lock file so --kill can read the PID on Windows A Windows file lock also blocks reads, so locking the PID file itself kept --kill from reading the running rebalancer's PID. The guard now locks .lock and writes the PID file normally; the test checks that the PID file stays readable while another process holds the lock. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- rebalancer/src/pid_file.rs | 43 ++++++++++++++++++++++++-------------- 1 file changed, 27 insertions(+), 16 deletions(-) diff --git a/rebalancer/src/pid_file.rs b/rebalancer/src/pid_file.rs index 85ea8c4..af00bc8 100644 --- a/rebalancer/src/pid_file.rs +++ b/rebalancer/src/pid_file.rs @@ -26,14 +26,13 @@ //! //! # Cleanup //! -//! The guard holds an exclusive lock for its lifetime. A second start that -//! uses the same path fails while the lock is held. A crash releases the -//! lock. The next start then replaces the stale file. +//! The guard holds an exclusive lock on `.lock` for its lifetime. +//! A second start that uses the same path fails while the lock is held. A +//! crash releases the lock. The next start then replaces the stale PID file. use crate::error::{Error, Result}; use fs2::FileExt; use std::fs::{self, File, OpenOptions}; -use std::io::Write; use std::path::{Path, PathBuf}; /// Default PID file path. @@ -79,27 +78,38 @@ pub fn remove_pid_file(path: &Path) -> Result<()> { Ok(()) } -/// Write a PID file, hold its lock, and remove the file on drop. +/// The lock file that guards `pid_path`: the same path with `.lock` appended. +/// +/// The lock sits on a separate file because a Windows lock also blocks reads, +/// and `--kill` must read the PID file while the rebalancer runs. +pub fn lock_path(pid_path: &Path) -> PathBuf { + let mut name = pid_path.as_os_str().to_owned(); + name.push(".lock"); + PathBuf::from(name) +} + +/// Write a PID file, hold the lock on its `.lock` file, and remove the PID file on drop. #[derive(Debug)] pub struct PidFileGuard { path: PathBuf, - file: Option, + lock: Option, } impl PidFileGuard { - /// Write `path` with the current process id and lock the file. + /// Lock `.lock`, then write `path` with the current process id. /// /// The lock stays held until drop. A second guard for the same path - /// fails. Drop removes the file before it releases the lock. + /// fails. Drop removes the PID file before it releases the lock. The + /// empty lock file stays on disk. pub fn create(path: PathBuf) -> Result { - let file = OpenOptions::new() + let lock = OpenOptions::new() .create(true) .truncate(false) .read(true) .write(true) - .open(&path) + .open(lock_path(&path)) .map_err(Error::Audit)?; - match file.try_lock_exclusive() { + match lock.try_lock_exclusive() { Ok(()) => {} // Unix reports a held lock as WouldBlock; Windows as ERROR_LOCK_VIOLATION (33). Err(error) @@ -113,18 +123,17 @@ impl PidFileGuard { } Err(error) => return Err(Error::Audit(error)), } - file.set_len(0).map_err(Error::Audit)?; - writeln!(&file, "{}", std::process::id()).map_err(Error::Audit)?; + write_pid_file(&path)?; Ok(Self { path, - file: Some(file), + lock: Some(lock), }) } } impl Drop for PidFileGuard { fn drop(&mut self) { - if self.file.is_none() { + if self.lock.is_none() { return; } match fs::remove_file(&self.path) { @@ -138,7 +147,7 @@ impl Drop for PidFileGuard { ); } } - self.file.take(); + self.lock.take(); } } @@ -222,6 +231,8 @@ mod tests { std::thread::sleep(std::time::Duration::from_millis(20)); } + // --kill reads the PID file while the holder runs. + assert_eq!(read_pid_file(&path).unwrap(), child.id()); let error = PidFileGuard::create(path.clone()).unwrap_err(); assert!( error.to_string().contains("in use by another rebalancer"), From 43f6dd20bec57ba3c0bf412509fb840aaab62999 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:43:14 +0100 Subject: [PATCH 31/66] test(rebalancer): write the log dir as a TOML literal string A Windows path such as C:\Users\... inside a double-quoted TOML string is read as escape sequences, so the config failed to parse and three stdout tests failed on Windows. Single quotes make a literal string on every platform. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- rebalancer/tests/mutation_stdout.rs | 2 +- rebalancer/tests/recovery_integration.rs | 4 ++-- rebalancer/tests/run_orchestration.rs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/rebalancer/tests/mutation_stdout.rs b/rebalancer/tests/mutation_stdout.rs index 3eebdb7..fac528a 100644 --- a/rebalancer/tests/mutation_stdout.rs +++ b/rebalancer/tests/mutation_stdout.rs @@ -44,7 +44,7 @@ allow_short = true max_short_pct = 1.0 [cost] [logging] -dir = "{}" +dir = '{}' audit_file = "audit.jsonl" "#, logs_dir.display() diff --git a/rebalancer/tests/recovery_integration.rs b/rebalancer/tests/recovery_integration.rs index 12833d0..2570d4c 100644 --- a/rebalancer/tests/recovery_integration.rs +++ b/rebalancer/tests/recovery_integration.rs @@ -1164,7 +1164,7 @@ type = "cash" [risk] [cost] [logging] -dir = "{}" +dir = '{}' audit_file = "audit.jsonl" "#, dir.path().display() @@ -1232,7 +1232,7 @@ type = "cash" [risk] [cost] [logging] -dir = "{}" +dir = '{}' audit_file = "audit.jsonl" "#, dir.path().display() diff --git a/rebalancer/tests/run_orchestration.rs b/rebalancer/tests/run_orchestration.rs index 68b7b46..b80a42d 100644 --- a/rebalancer/tests/run_orchestration.rs +++ b/rebalancer/tests/run_orchestration.rs @@ -183,7 +183,7 @@ allow_short = true max_short_pct = 1.0 [cost] [logging] -dir = "{}" +dir = '{}' audit_file = "audit.jsonl" "#, workdir.join("logs").display() From 9cca4fa4b1b38864023f653f95a44875907c8929 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:02:26 +0100 Subject: [PATCH 32/66] test(risk): pin limit boundaries, short logic and config checks cargo-mutants 0.20.0 showed these values were never checked: leverage failing above the limit and at zero equity, short-exposure counting and the allow_short=false sell-down-a-long case, limits disabled at 0 and at-the-limit boundaries in check_batch and check_order, the Order size warning scale, RiskConfig::validate on 1.0 drawdown and non-finite inputs, has_warnings, and RiskEngine::config. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- risk/src/checks.rs | 143 ++++++++++++++++++++++++++ risk/src/report.rs | 32 ++++++ risk/tests/check_order_tests.rs | 176 ++++++++++++++++++++++++++++++++ 3 files changed, 351 insertions(+) diff --git a/risk/src/checks.rs b/risk/src/checks.rs index c872449..2a02db2 100644 --- a/risk/src/checks.rs +++ b/risk/src/checks.rs @@ -411,4 +411,147 @@ mod tests { .contains("$250 > $100 max_batch_value_cents") ); } + + fn find<'a>(report: &'a RiskReport, name: &str) -> Option<&'a RiskCheck> { + report.checks.iter().find(|c| c.name == name) + } + + fn named<'a>(report: &'a RiskReport, name: &str) -> &'a RiskCheck { + find(report, name).unwrap_or_else(|| panic!("no check named {name:?} in {report}")) + } + + // ---- Leverage check (cargo-mutants 0.20.0: never failed in any test) ---- + + #[test] + fn leverage_above_limit_fails() { + // gross 500 * 18_500 = 9_250_000 over equity 5_000_000 = 1.85x > 1.5x + let orders = vec![(aapl(), BrokerSide::Buy, 500_u64, 18_500_i64)]; + let targets = vec![(aapl(), 0.40)]; + let report = check_batch( + &default_config(), + &orders, + &account(5_000_000), + &[], + &targets, + ); + let lev = named(&report, "Leverage"); + assert_eq!(lev.status, RiskStatus::Fail); + assert!(lev.detail.contains("1.85x > 1.50x limit"), "{}", lev.detail); + } + + #[test] + fn leverage_exactly_at_limit_passes() { + // gross 1000 * 15_000 = 15_000_000 over equity 10_000_000 = 1.50x + let mut config = default_config(); + config.max_order_value_cents = 0; // disabled, so only leverage is under test + let orders = vec![(aapl(), BrokerSide::Buy, 1000_u64, 15_000_i64)]; + let report = check_batch(&config, &orders, &account(10_000_000), &[], &[]); + let lev = named(&report, "Leverage"); + assert_eq!(lev.status, RiskStatus::Pass); + assert!( + lev.detail.contains("1.50x <= 1.50x limit"), + "{}", + lev.detail + ); + } + + #[test] + fn zero_equity_fails_leverage_and_short_exposure() { + // ratio_or_inf returns infinity for equity <= 0, also for 0 / 0 + let report = check_batch(&default_config(), &[], &account(0), &[], &[]); + let lev = named(&report, "Leverage"); + assert_eq!(lev.status, RiskStatus::Fail); + assert!(lev.detail.contains("infx > 1.50x limit"), "{}", lev.detail); + assert_eq!(named(&report, "Short exposure").status, RiskStatus::Fail); + } + + // ---- Short-selling logic ---- + + #[test] + fn selling_down_a_long_is_not_short_selling() { + let mut config = default_config(); + config.allow_short = false; + let current = vec![(aapl(), 100_i64)]; + // Sell 50 leaves 50 long; Sell 100 leaves exactly flat. + for qty in [50_u64, 100] { + let orders = vec![(aapl(), BrokerSide::Sell, qty, 18_500_i64)]; + let report = check_batch(&config, &orders, &account(10_000_000), ¤t, &[]); + assert!(!report.has_failures(), "qty {qty}: {report}"); + assert!(find(&report, "Short selling").is_none(), "qty {qty}"); + assert_eq!(named(&report, "Short exposure").status, RiskStatus::Pass); + } + } + + #[test] + fn short_exposure_counts_only_short_positions() { + // Only SPY is short: 50 * 43_000 = 2_150_000 over 10_000_000 = 21.5%. + // The long AAPL (18.5%) must not be counted, and the short must be. + let mut config = default_config(); + config.max_short_pct = 0.20; + let orders = vec![ + (aapl(), BrokerSide::Buy, 100_u64, 18_500_i64), + (spy(), BrokerSide::Sell, 50, 43_000), + ]; + let report = check_batch(&config, &orders, &account(10_000_000), &[], &[]); + let short = named(&report, "Short exposure"); + assert_eq!(short.status, RiskStatus::Fail); + assert!( + short.detail.contains("21.5% > 20.0% limit"), + "{}", + short.detail + ); + } + + #[test] + fn short_exposure_boundary() { + let config = default_config(); // max_short_pct 0.30 + // exactly 3_000_000 / 10_000_000 = 30.0%: passes + let at = vec![(spy(), BrokerSide::Sell, 100_u64, 30_000_i64)]; + let report = check_batch(&config, &at, &account(10_000_000), &[], &[]); + let short = named(&report, "Short exposure"); + assert_eq!(short.status, RiskStatus::Pass); + assert!( + short.detail.contains("30.0% <= 30.0% limit"), + "{}", + short.detail + ); + // 3_030_000 / 10_000_000 = 30.3%: fails + let over = vec![(spy(), BrokerSide::Sell, 101_u64, 30_000_i64)]; + let report = check_batch(&config, &over, &account(10_000_000), &[], &[]); + assert_eq!(named(&report, "Short exposure").status, RiskStatus::Fail); + } + + // ---- Limits at their boundary and disabled at 0 ---- + + #[test] + fn target_weight_exactly_at_max_position_passes() { + let targets = vec![(aapl(), 0.40)]; // default_config max_position_pct is 0.40 + let report = check_batch(&default_config(), &[], &account(10_000_000), &[], &targets); + assert_eq!(named(&report, "Max position").status, RiskStatus::Pass); + } + + #[test] + fn zero_order_and_batch_limits_mean_no_limit() { + let mut config = default_config(); + config.max_order_value_cents = 0; + config.max_batch_value_cents = 0; + let orders = vec![(aapl(), BrokerSide::Buy, 1000_u64, 18_500_i64)]; + let report = check_batch(&config, &orders, &account(100_000_000), &[], &[]); + assert!(find(&report, "Max order value").is_none()); + assert!(find(&report, "Max batch value").is_none()); + } + + #[test] + fn max_trade_size_warning_threshold() { + let mut config = default_config(); + config.max_trade_usd = 1000.0; // 100_000 cents + // notional exactly 100_000 cents: no warning + let at = vec![(aapl(), BrokerSide::Buy, 10_u64, 10_000_i64)]; + let report = check_batch(&config, &at, &account(100_000_000), &[], &[]); + assert!(find(&report, "Max trade size").is_none()); + // notional 100_001 cents: one warning + let over = vec![(aapl(), BrokerSide::Buy, 1_u64, 100_001_i64)]; + let report = check_batch(&config, &over, &account(100_000_000), &[], &[]); + assert_eq!(named(&report, "Max trade size").status, RiskStatus::Warn); + } } diff --git a/risk/src/report.rs b/risk/src/report.rs index 6992f27..ac13848 100644 --- a/risk/src/report.rs +++ b/risk/src/report.rs @@ -55,3 +55,35 @@ impl std::fmt::Display for RiskReport { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + fn report(statuses: &[RiskStatus]) -> RiskReport { + RiskReport { + checks: statuses + .iter() + .map(|&status| RiskCheck { + name: "check", + status, + detail: String::new(), + }) + .collect(), + } + } + + #[test] + fn has_warnings_is_true_only_for_warn_status() { + assert!(!report(&[]).has_warnings()); + assert!(!report(&[RiskStatus::Pass, RiskStatus::Pass]).has_warnings()); + assert!(!report(&[RiskStatus::Pass, RiskStatus::Fail]).has_warnings()); + assert!(report(&[RiskStatus::Pass, RiskStatus::Warn]).has_warnings()); + } + + #[test] + fn has_failures_is_true_only_for_fail_status() { + assert!(!report(&[RiskStatus::Pass, RiskStatus::Warn]).has_failures()); + assert!(report(&[RiskStatus::Pass, RiskStatus::Fail]).has_failures()); + } +} diff --git a/risk/tests/check_order_tests.rs b/risk/tests/check_order_tests.rs index 042f770..d516b27 100644 --- a/risk/tests/check_order_tests.rs +++ b/risk/tests/check_order_tests.rs @@ -403,3 +403,179 @@ fn risk_engine_accepts_valid_config() { "default RiskConfig must be valid" ); } + +// ============================================================================ +// Threshold boundaries (cargo-mutants 0.20.0 showed these were never checked) +// ============================================================================ + +fn status_of(report: &nanobook_risk::RiskReport, name: &str) -> RiskStatus { + report + .checks + .iter() + .find(|c| c.name == name) + .unwrap_or_else(|| panic!("no check named {name:?} in {report}")) + .status +} + +#[test] +fn selling_a_whole_long_with_shorts_disallowed_passes() { + let engine = RiskEngine::new(RiskConfig { + allow_short: false, + ..RiskConfig::default() + }) + .unwrap(); + // 100 held, sell 100: post quantity is exactly 0, not short. + let report = engine.check_order( + &aapl(), + BrokerSide::Sell, + 100, + 150_00, + &account(10_000_000), + &[(aapl(), 100)], + ); + assert!(!report.has_failures(), "{report}"); + assert!(!report.checks.iter().any(|c| c.name == "Short selling")); +} + +#[test] +fn order_size_warning_threshold_is_max_trade_usd() { + let engine = RiskEngine::new(RiskConfig { + max_trade_usd: 1000.0, // 100_000 cents + max_position_pct: 1.0, + ..RiskConfig::default() + }) + .unwrap(); + // notional exactly 100_000 cents: no warning + let at = engine.check_order( + &aapl(), + BrokerSide::Buy, + 10, + 10_000, + &account(100_000_000), + &[], + ); + let size = at.checks.iter().find(|c| c.name == "Order size").unwrap(); + assert_eq!(size.status, RiskStatus::Pass); + assert_eq!(size.detail, "$1000.00 <= $1000.00 max"); + assert!(!at.has_warnings()); + // one cent over: warns + let over = engine.check_order( + &aapl(), + BrokerSide::Buy, + 1, + 100_001, + &account(100_000_000), + &[], + ); + assert_eq!(status_of(&over, "Order size"), RiskStatus::Warn); +} + +#[test] +fn position_exactly_at_max_position_pct_passes() { + // 25 * 100_000 = 2_500_000 over 10_000_000 equity = 0.25 = the limit + let report = engine().check_order( + &aapl(), + BrokerSide::Buy, + 25, + 100_000, + &account(10_000_000), + &[], + ); + assert_eq!(status_of(&report, "Max position"), RiskStatus::Pass); +} + +#[test] +fn zero_max_order_value_means_no_limit() { + let engine = RiskEngine::new(RiskConfig { + max_order_value_cents: 0, + ..RiskConfig::default() + }) + .unwrap(); + let report = engine.check_order( + &aapl(), + BrokerSide::Buy, + 1000, + 15_000, + &account(100_000_000), + &[], + ); + assert_eq!(status_of(&report, "Max order value"), RiskStatus::Pass); +} + +#[test] +fn engine_config_returns_the_configured_limits() { + let engine = RiskEngine::new(RiskConfig { + max_position_pct: 0.5, + max_leverage: 2.0, + ..RiskConfig::default() + }) + .unwrap(); + assert_eq!(engine.config().max_position_pct, 0.5); + assert_eq!(engine.config().max_leverage, 2.0); +} + +#[test] +fn has_warnings_false_for_a_small_order() { + let report = engine().check_order( + &aapl(), + BrokerSide::Buy, + 10, + 150_00, + &account(10_000_000), + &[], + ); + assert!(!report.has_warnings()); +} + +// ============================================================================ +// RiskConfig::validate: non-finite values and boundaries +// ============================================================================ + +#[test] +fn max_drawdown_pct_one_validates_and_above_one_fails() { + let at = RiskConfig { + max_drawdown_pct: 1.0, + ..RiskConfig::default() + }; + assert!(at.validate().is_ok()); + let over = RiskConfig { + max_drawdown_pct: 1.5, + ..RiskConfig::default() + }; + assert!(over.validate().is_err()); +} + +#[test] +fn non_finite_short_and_trade_limits_fail_validation() { + for bad in [f64::INFINITY, f64::NAN] { + let short = RiskConfig { + max_short_pct: bad, + ..RiskConfig::default() + }; + assert!(short.validate().is_err(), "max_short_pct {bad}"); + let min_trade = RiskConfig { + min_trade_usd: bad, + ..RiskConfig::default() + }; + assert!(min_trade.validate().is_err(), "min_trade_usd {bad}"); + let max_trade = RiskConfig { + max_trade_usd: bad, + ..RiskConfig::default() + }; + assert!(max_trade.validate().is_err(), "max_trade_usd {bad}"); + } +} + +#[test] +fn zero_order_and_batch_value_limits_validate() { + let order = RiskConfig { + max_order_value_cents: 0, + ..RiskConfig::default() + }; + assert!(order.validate().is_ok()); + let batch = RiskConfig { + max_batch_value_cents: 0, + ..RiskConfig::default() + }; + assert!(batch.validate().is_ok()); +} From a352d05d08918cf46d7a6a81c2454036a80473c6 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:02:26 +0100 Subject: [PATCH 33/66] test(portfolio): pin rebalance, stop and bridge values exactly cargo-mutants 0.20.0 showed these values were never checked: rebalance_lob sizing, side and fill signs; the close loop of rebalance_simple against band, min and max order value; caps met exactly with fractional quantities; truncated sells; record_return at zero equity; getters; EqualWeight with several symbols; Shares edge values; the serde default quantity_step; and in the backtest bridge the ATR buffer trim, NextBarTypical fill price, short-side ATR stop level, stop sanitising, decompose_backtest zero entries, day budget reset and inertness, zero-close symbol returns and valid_inputs. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- src/backtest_bridge.rs | 250 ++++++++++++++++++++++++++ src/portfolio/mod.rs | 356 ++++++++++++++++++++++++++++++++++++++ src/portfolio/position.rs | 17 ++ src/portfolio/strategy.rs | 17 ++ 4 files changed, 640 insertions(+) diff --git a/src/backtest_bridge.rs b/src/backtest_bridge.rs index 595313c..3b3b8dc 100644 --- a/src/backtest_bridge.rs +++ b/src/backtest_bridge.rs @@ -2631,4 +2631,254 @@ mod tests { assert_eq!(result.stop_events[0].symbol, aapl()); assert!(result.holdings[2].iter().any(|(sym, _)| *sym == msft())); } + + // === Exact-value pins (cargo-mutants 0.20.0 showed these were never checked) === + + fn run_simple( + weights: &[Vec<(Symbol, f64)>], + prices: &[Vec<(Symbol, BarPrices)>], + fill_policy: FillPolicy, + options: BacktestBridgeOptions, + ) -> BacktestBridgeResult { + backtest_weights_with_options( + weights, + prices, + 1_000_000_00, + CostModel::zero(), + fill_policy, + 252.0, + 0.0, + options, + ) + } + + /// The ATR buffer keeps the last `6 * atr_period` absolute changes. A + /// position held longer than that must not panic while trimming. + #[test] + fn stop_tracker_trims_abs_changes_to_six_atr_periods() { + let mut tracker = StopTracker::new(100_00, 1); + for i in 1..=20 { + tracker.update(100_00 + i, 1); + } + assert_eq!(tracker.abs_changes.len(), 6); + assert!(tracker.abs_changes.iter().all(|&d| d == 1)); + + let mut wide = StopTracker::new(100_00, 1); + for i in 1..=20 { + wide.update(100_00 + i, 3); + } + assert_eq!(wide.abs_changes.len(), 18); + } + + #[test] + fn stop_config_backtest_holding_longer_than_atr_buffer_completes() { + let periods = 10; + let weights = vec![vec![(aapl(), 1.0)]; periods]; + let prices = vec![vec![(aapl(), bar(100_00))]; periods]; + let options = BacktestBridgeOptions { + stop_cfg: Some(BacktestStopConfig { + fixed_stop_pct: Some(0.5), + trailing_stop_pct: None, + atr_multiple: None, + atr_period: 1, + }), + ..Default::default() + }; + let result = run_simple(&weights, &prices, FillPolicy::SignalBarClose, options); + assert_eq!(result.returns.len(), periods); + assert!(result.stop_events.is_empty()); + assert!(result.unpriced_holding.is_none()); + } + + /// NextBarTypical fills at (high + low + close) / 3 of the next bar. + #[test] + fn next_bar_typical_fill_price_is_exact_hlc3() { + let weights = vec![vec![(aapl(), 1.0)]; 2]; + let prices = vec![ + vec![(aapl(), bar(10_000))], + vec![( + aapl(), + BarPrices { + open: 10_000, + high: 10_300, + low: 9_700, + close: 10_100, + }, + )], + ]; + let result = run_simple( + &weights, + &prices, + FillPolicy::NextBarTypical, + BacktestBridgeOptions::default(), + ); + // fill price (10_300 + 9_700 + 10_100) / 3 = 10_033; whole shares + // 100_000_000 / 10_033 = 9_967; cash left 100_000_000 - 9_967 * 10_033 + assert_eq!(result.final_cash, 1_089); + } + + #[test] + fn short_side_atr_stop_level_sits_above_the_reference_price() { + let tracker = StopTracker { + side: -1, + entry_price: 5_000, + reference_price: 5_000, + last_price: 5_000, + abs_changes: vec![10, 20, 30], + }; + let cfg = BacktestStopConfig { + fixed_stop_pct: None, + trailing_stop_pct: None, + atr_multiple: Some(2.0), + atr_period: 3, + }; + // ATR = (10 + 20 + 30) / 3 = 20; level = 5_000 + 2.0 * 20 + assert_eq!(effective_stop_level(&cfg, &tracker), Some((5_040, "atr"))); + } + + #[test] + fn sanitize_pct_accepts_only_open_unit_interval() { + for bad in [0.0, 1.0, -0.5, 1.5, f64::NAN, f64::INFINITY] { + assert_eq!(sanitize_pct(Some(bad)), None, "{bad}"); + } + assert_eq!(sanitize_pct(None), None); + assert_eq!(sanitize_pct(Some(0.5)), Some(0.5)); + } + + #[test] + fn sanitize_positive_accepts_only_positive_finite() { + for bad in [0.0, -1.0, f64::INFINITY, f64::NEG_INFINITY, f64::NAN] { + assert_eq!(sanitize_positive(Some(bad)), None, "{bad}"); + } + assert_eq!(sanitize_positive(None), None); + assert_eq!(sanitize_positive(Some(2.0)), Some(2.0)); + } + + #[test] + fn decompose_backtest_skips_symbols_with_no_weight_and_no_contribution() { + let a = aapl(); + let b = msft(); + let result = decompose_backtest( + &[vec![(a, 0.5)], vec![]], + &[vec![(a, 0.1), (b, 0.2)], vec![(a, 0.1), (b, 0.2)]], + ); + // b never carries weight: no entry in either period. a exits in + // period 1 and still reports its zero contribution that period. + assert_eq!(result.contributions.len(), 2); + assert_eq!(result.contributions[0].len(), 1); + assert_eq!(result.contributions[0][0].0, a); + assert!((result.contributions[0][0].1 - 0.05).abs() < 1e-12); + assert_eq!(result.contributions[1], vec![(a, 0.0)]); + assert_eq!(result.cumulative_contributions.len(), 2); + for period in &result.cumulative_contributions { + assert_eq!(period.len(), 1); + assert_eq!(period[0].0, a); + assert!((period[0].1 - 0.05).abs() < 1e-12); + } + assert_eq!( + result.trades, + vec![AttributionTrade { + symbol: a, + entry_index: 0, + exit_index: Some(1), + entry_weight: 0.5, + exit_weight: 0.5, + }] + ); + } + + fn held_symbols(result: &BacktestBridgeResult) -> Vec> { + result + .holdings + .iter() + .map(|period| period.iter().map(|(s, _)| s.as_str()).collect()) + .collect() + } + + /// The per-day trade counter resets when the day ordinal changes. + #[test] + fn max_trades_per_day_resets_on_new_day_ordinal() { + let bars = vec![(sym(0), bar(100_00)), (sym(1), bar(100_00))]; + let prices = vec![bars.clone(), bars.clone(), bars]; + let weights = vec![ + vec![(sym(0), 0.2)], + vec![(sym(0), 0.2), (sym(1), 0.2)], + vec![(sym(0), 0.2), (sym(1), 0.2)], + ]; + let options = BacktestBridgeOptions { + max_trades_per_day: Some(1), + period_day_ordinal: Some(vec![1, 1, 2]), + ..Default::default() + }; + let result = run_simple(&weights, &prices, FillPolicy::SignalBarClose, options); + assert_eq!( + held_symbols(&result), + vec![vec!["S0"], vec!["S0"], vec!["S0", "S1"]] + ); + } + + /// A day budget without day ordinals, and day ordinals without a day + /// budget, are both inert. + #[test] + fn day_budget_needs_both_the_cap_and_the_ordinals() { + let bars = vec![(sym(0), bar(100_00)), (sym(1), bar(100_00))]; + let prices = vec![bars]; + let weights = vec![vec![(sym(0), 0.2), (sym(1), 0.2)]]; + + let cap_only = BacktestBridgeOptions { + max_trades_per_day: Some(1), + period_day_ordinal: None, + ..Default::default() + }; + let result = run_simple(&weights, &prices, FillPolicy::SignalBarClose, cap_only); + assert_eq!(held_symbols(&result), vec![vec!["S0", "S1"]]); + + let ordinals_only = BacktestBridgeOptions { + max_trades_per_day: None, + period_day_ordinal: Some(vec![1]), + ..Default::default() + }; + let result = run_simple(&weights, &prices, FillPolicy::SignalBarClose, ordinals_only); + assert_eq!(held_symbols(&result), vec![vec!["S0", "S1"]]); + } + + /// A close of 0 gives no return (NaN), not -100% or +inf. + #[test] + fn symbol_return_is_nan_when_either_close_is_zero() { + let closes = [100_00, 0, 100_00, 110_00]; + let weights = vec![vec![]; closes.len()]; + let prices: Vec> = + closes.iter().map(|&c| vec![(aapl(), bar(c))]).collect(); + let result = run_simple( + &weights, + &prices, + FillPolicy::SignalBarClose, + BacktestBridgeOptions::default(), + ); + assert_eq!(result.symbol_returns.len(), 4); + for (period, returns) in result.symbol_returns.iter().take(3).enumerate() { + let (s, r) = returns[0]; + assert_eq!(s, aapl()); + assert!(r.is_nan(), "period {period}: {r}"); + } + assert!((result.symbol_returns[3][0].1 - 0.1).abs() < 1e-12); + } + + #[test] + fn valid_inputs_rejects_negative_prices_and_accepts_zero() { + let check = |open, high, low, close| { + let bp = BarPrices { + open, + high, + low, + close, + }; + valid_inputs(&[vec![]], &[vec![(aapl(), bp)]], 1) + }; + assert!(!check(-1, 10, 10, 10), "negative open"); + assert!(!check(5, 10, -1, 5), "negative low"); + assert!(!check(10, 10, 10, -1), "negative close"); + assert!(check(0, 0, 0, 0), "all zero"); + assert!(check(10, 10, 10, 10), "all positive"); + } } diff --git a/src/portfolio/mod.rs b/src/portfolio/mod.rs index d1ad57d..9ada9a0 100644 --- a/src/portfolio/mod.rs +++ b/src/portfolio/mod.rs @@ -2497,6 +2497,348 @@ mod tests { ); assert_eq!(portfolio.trimmed_shortfall_cents(), 0); } + + // === Exact-value pins (cargo-mutants 0.20.0 showed these were never checked) === + + fn qty_of(portfolio: &Portfolio, symbol: &Symbol) -> Shares { + portfolio + .position(symbol) + .map_or(Shares::ZERO, |p| p.quantity) + } + + // --- rebalance_lob --- + + use crate::{MultiExchange, OrderId, Price, Side, TimeInForce}; + + /// A book for `aapl` with a 10_000-share bid at 99_00 and ask at 101_00 + /// (order ids 1 and 2, mid price 100_00). + fn lob_with_spread() -> MultiExchange { + let mut multi = MultiExchange::new(); + let ex = multi.get_or_create(&aapl()); + ex.submit_limit(Side::Buy, Price(99_00), 10_000, TimeInForce::GTC); + ex.submit_limit(Side::Sell, Price(101_00), 10_000, TimeInForce::GTC); + multi + } + + #[test] + fn rebalance_lob_sizes_sides_and_prices_orders_exactly() { + let mut multi = lob_with_spread(); + let mut portfolio = Portfolio::new(1_000_000_00, CostModel::zero()); + + // T1: target 50% at mid 100_00: 50_000_000 / 100_00 = 5000 shares, + // bought from the ask at 101_00. + portfolio.rebalance_lob(&[(aapl(), 0.5)], &mut multi); + assert_eq!(qty_of(&portfolio, &aapl()), Shares::from_whole(5000)); + assert_eq!(portfolio.cash(), 49_500_000); + let ask = multi.get(&aapl()).unwrap().get_order(OrderId(2)).unwrap(); + assert_eq!(ask.remaining_quantity, 5000); + + // T2: equity = 49_500_000 + 5000 * 100_00 = 99_500_000; target 25% + // = 24_875_000; diff = -25_125_000; 2512 shares sold at the bid 99_00. + portfolio.rebalance_lob(&[(aapl(), 0.25)], &mut multi); + assert_eq!(qty_of(&portfolio, &aapl()), Shares::from_whole(2488)); + assert_eq!(portfolio.cash(), 74_368_800); + + // T3: no targets closes the whole position at the bid. + portfolio.rebalance_lob(&[], &mut multi); + assert!(portfolio.position(&aapl()).unwrap().is_flat()); + assert_eq!(portfolio.cash(), 99_000_000); + + // T5a: a flat position places no order. Ids so far: 2 limits and 3 + // market orders, so the next order gets id 6. + portfolio.rebalance_lob(&[], &mut multi); + let probe = + multi + .get_or_create(&aapl()) + .submit_limit(Side::Buy, Price(90_00), 1, TimeInForce::GTC); + assert_eq!(probe.order_id, OrderId(6)); + } + + #[test] + fn rebalance_lob_skips_a_symbol_with_a_zero_mid_price() { + let z = Symbol::new("Z"); + let mut multi = MultiExchange::new(); + multi + .get_or_create(&z) + .submit_limit(Side::Buy, Price(0), 10, TimeInForce::GTC); + let mut portfolio = Portfolio::new(1_000_00, CostModel::zero()); + portfolio.rebalance_lob(&[(z, 0.5)], &mut multi); + assert!(portfolio.position(&z).is_none()); + assert_eq!(portfolio.cash(), 1_000_00); + assert_eq!(multi.get(&z).unwrap().best_bid(), Some(Price(0))); + } + + /// Closing a sub-share long position (whole() == 0) takes the buy side + /// branch with quantity 0 and trades nothing. + #[test] + fn rebalance_lob_close_of_fractional_long_submits_a_zero_buy() { + let mut multi = lob_with_spread(); + let mut portfolio = Portfolio::new(1_000_000_00, CostModel::zero()); + portfolio.execute_fill(aapl(), Shares::from_raw(500_000), 100_00); + portfolio.rebalance_lob(&[], &mut multi); + let order = multi.get(&aapl()).unwrap().get_order(OrderId(3)).unwrap(); + assert_eq!(order.side, Side::Buy); + assert_eq!(qty_of(&portfolio, &aapl()), Shares::from_raw(500_000)); + } + + // --- close loop of rebalance_simple (positions absent from the targets) --- + + #[test] + fn close_loop_respects_no_trade_band() { + let (a, b, c) = (Symbol::new("A"), Symbol::new("B"), Symbol::new("C")); + let prices = [(a, 10_00), (b, 100_00), (c, 100_00)]; + let mut portfolio = Portfolio::new(1_000_00, CostModel::zero()); + portfolio.rebalance_simple(&[(a, 0.02), (b, 0.4), (c, 0.3)], &prices); + assert_eq!(qty_of(&portfolio, &a), Shares::from_whole(2)); + assert_eq!(qty_of(&portfolio, &b), Shares::from_whole(4)); + assert_eq!(qty_of(&portfolio, &c), Shares::from_whole(3)); + assert_eq!(portfolio.cash(), 28_000); + + portfolio.set_no_trade_band_bps(500.0); + portfolio.rebalance_simple(&[(b, 0.4)], &prices); + // A drifts 200 bps (kept), C drifts 3000 bps (closed). + assert_eq!(qty_of(&portfolio, &a), Shares::from_whole(2)); + assert_eq!(qty_of(&portfolio, &b), Shares::from_whole(4)); + assert_eq!(qty_of(&portfolio, &c), Shares::ZERO); + assert_eq!(portfolio.cash(), 58_000); + assert_eq!(portfolio.last_rebalance_order_count(), 1); + assert_eq!(portfolio.last_rebalance_notional(), 30_000); + } + + #[test] + fn close_loop_with_band_zero_closes_a_position_priced_at_zero() { + let mut portfolio = Portfolio::new(1_000_00, CostModel::zero()); + portfolio.rebalance_simple(&[(aapl(), 0.5)], &[(aapl(), 100_00)]); + assert_eq!(qty_of(&portfolio, &aapl()), Shares::from_whole(5)); + assert_eq!(portfolio.cash(), 50_000); + + // Price 0: drift 0, band 0 (disabled): the close is still placed. + portfolio.rebalance_simple(&[], &[(aapl(), 0)]); + assert_eq!(qty_of(&portfolio, &aapl()), Shares::ZERO); + assert_eq!(portfolio.last_rebalance_order_count(), 1); + assert_eq!(portfolio.last_rebalance_notional(), 0); + } + + #[test] + fn close_loop_truncates_to_max_order_value() { + let mut portfolio = Portfolio::new(1_000_00, CostModel::zero()); + portfolio.rebalance_simple(&[(aapl(), 1.0)], &[(aapl(), 100_00)]); + assert_eq!(qty_of(&portfolio, &aapl()), Shares::from_whole(10)); + assert_eq!(portfolio.cash(), 0); + + portfolio.set_max_order_value(300_00); + portfolio.rebalance_simple(&[], &[(aapl(), 100_00)]); + assert_eq!(qty_of(&portfolio, &aapl()), Shares::from_whole(7)); + assert_eq!(portfolio.cash(), 30_000); + assert_eq!(portfolio.last_rebalance_order_count(), 1); + assert_eq!(portfolio.last_rebalance_notional(), 30_000); + } + + #[test] + fn close_loop_skips_closes_below_min_order_value() { + let (a, b, c) = (Symbol::new("A"), Symbol::new("B"), Symbol::new("C")); + let prices = [(a, 10_00), (b, 10_00), (c, 10_00)]; + let mut portfolio = Portfolio::new(10_000_00, CostModel::zero()); + portfolio.rebalance_simple(&[(a, 0.1), (b, 0.005), (c, 0.01)], &prices); + assert_eq!(qty_of(&portfolio, &a), Shares::from_whole(100)); + assert_eq!(qty_of(&portfolio, &b), Shares::from_whole(5)); + assert_eq!(qty_of(&portfolio, &c), Shares::from_whole(10)); + assert_eq!(portfolio.cash(), 885_000); + + portfolio.set_min_order_value(100_00); + portfolio.rebalance_simple(&[], &prices); + // A notional 100_000 closes, B 5_000 < min stays, C 10_000 == min closes. + assert_eq!(qty_of(&portfolio, &a), Shares::ZERO); + assert_eq!(qty_of(&portfolio, &b), Shares::from_whole(5)); + assert_eq!(qty_of(&portfolio, &c), Shares::ZERO); + assert_eq!(portfolio.last_rebalance_order_count(), 2); + assert_eq!(portfolio.last_rebalance_notional(), 110_000); + assert_eq!(portfolio.cash(), 995_000); + } + + #[test] + fn close_loop_ignores_flat_positions() { + let mut portfolio = Portfolio::new(1_000_00, CostModel::zero()); + portfolio.rebalance_simple(&[(aapl(), 0.5)], &[(aapl(), 100_00)]); + portfolio.rebalance_simple(&[], &[(aapl(), 100_00)]); + assert_eq!(portfolio.last_rebalance_order_count(), 1); + // AAPL is now flat but still in the map: nothing to close. + portfolio.rebalance_simple(&[], &[(aapl(), 100_00)]); + assert_eq!(portfolio.last_rebalance_order_count(), 0); + } + + // --- truncate_qty_to_max_value, sells --- + + #[test] + fn truncate_qty_to_max_value_keeps_the_sign_of_a_sell() { + assert_eq!( + truncate_qty_to_max_value(Shares::from_whole(-10), 100, Shares::SCALE, 500), + Shares::from_whole(-5) + ); + assert_eq!( + truncate_qty_to_max_value(Shares::from_whole(10), 100, Shares::SCALE, 500), + Shares::from_whole(5) + ); + } + + #[test] + fn max_order_value_truncates_a_sell_and_does_not_buy() { + let mut portfolio = Portfolio::new(1_000_00, CostModel::zero()); + portfolio.rebalance_simple(&[(aapl(), 1.0)], &[(aapl(), 100_00)]); + portfolio.set_max_order_value(300_00); + portfolio.rebalance_simple(&[(aapl(), 0.0)], &[(aapl(), 100_00)]); + assert_eq!(qty_of(&portfolio, &aapl()), Shares::from_whole(7)); + assert_eq!(portfolio.cash(), 30_000); + } + + // --- per-rebalance notional cap with a minimum order value --- + + #[test] + fn max_rebalance_notional_truncated_order_above_min_order_value_is_admitted() { + let s: Vec = (0..3).map(|i| Symbol::new(&format!("S{i}"))).collect(); + let prices: Vec<(Symbol, i64)> = s.iter().map(|&x| (x, 100_00)).collect(); + let mut portfolio = Portfolio::new(100_000_00, CostModel::zero()); + portfolio.set_max_rebalance_notional(20_000_00); + portfolio.set_min_order_value(1_000_00); + portfolio.rebalance_simple(&[(s[0], 0.05), (s[1], 0.10), (s[2], 0.15)], &prices); + // S2 (1500 bps) takes 1_500_000, S1 is cut to the 500_000 left and + // clears the 100_000 minimum, S0 gets nothing. + assert_eq!(qty_of(&portfolio, &s[2]), Shares::from_whole(150)); + assert_eq!(qty_of(&portfolio, &s[1]), Shares::from_whole(50)); + assert_eq!(qty_of(&portfolio, &s[0]), Shares::ZERO); + assert_eq!(portfolio.last_rebalance_order_count(), 2); + assert_eq!(portfolio.last_rebalance_notional(), 20_000_00); + assert_eq!(portfolio.cash(), 8_000_000); + } + + // --- orders whose notional equals a cap exactly, with a fractional quantity --- + + /// 20 cents, step 1 micro-share: 50% at price 3 sizes 3_333_333 raw + /// (10 cents / 3), whose notional floors to 9 cents. + fn fractional_cap_portfolio() -> Portfolio { + Portfolio::with_quantity_step(20, CostModel::zero(), 1) + } + + #[test] + fn order_at_max_order_value_is_not_truncated() { + let mut portfolio = fractional_cap_portfolio(); + portfolio.set_max_order_value(9); + portfolio.rebalance_simple(&[(aapl(), 0.5)], &[(aapl(), 3)]); + assert_eq!(qty_of(&portfolio, &aapl()), Shares::from_raw(3_333_333)); + assert_eq!(portfolio.cash(), 11); + } + + #[test] + fn close_at_max_order_value_is_not_truncated() { + let mut portfolio = fractional_cap_portfolio(); + portfolio.rebalance_simple(&[(aapl(), 0.5)], &[(aapl(), 3)]); + assert_eq!(qty_of(&portfolio, &aapl()), Shares::from_raw(3_333_333)); + portfolio.set_max_order_value(9); + portfolio.rebalance_simple(&[], &[(aapl(), 3)]); + assert_eq!(qty_of(&portfolio, &aapl()), Shares::ZERO); + } + + #[test] + fn order_at_max_rebalance_notional_is_not_truncated() { + let mut portfolio = fractional_cap_portfolio(); + portfolio.set_max_rebalance_notional(9); + portfolio.rebalance_simple(&[(aapl(), 0.5)], &[(aapl(), 3)]); + assert_eq!(qty_of(&portfolio, &aapl()), Shares::from_raw(3_333_333)); + } + + // --- close_position_at, unpriced holdings, execute_fill edges --- + + #[test] + fn close_position_at_a_flat_position_returns_false() { + let mut portfolio = Portfolio::new(1_000_000_00, CostModel::zero()); + portfolio.rebalance_simple(&[(aapl(), 0.8)], &[(aapl(), 150_00)]); + assert!(portfolio.close_position_at(aapl(), 155_00)); + assert!(!portfolio.close_position_at(aapl(), 155_00)); + assert!(!portfolio.close_position_at(msft(), 155_00)); + } + + #[test] + fn unpriced_holding_needs_a_positive_price() { + let mut portfolio = Portfolio::new(100_00, CostModel::zero()); + portfolio.rebalance_simple(&[(aapl(), 1.0)], &[(aapl(), 10_00)]); + assert_eq!(qty_of(&portfolio, &aapl()), Shares::from_whole(10)); + assert_eq!(portfolio.unpriced_holding(&[(aapl(), 0)]), Some(aapl())); + assert_eq!(portfolio.unpriced_holding(&[(aapl(), -5)]), Some(aapl())); + assert_eq!(portfolio.unpriced_holding(&[]), Some(aapl())); + assert_eq!(portfolio.unpriced_holding(&[(aapl(), 10_00)]), None); + } + + #[test] + fn sell_leaving_cash_at_exactly_zero_is_filled() { + let model = CostModel { + commission_bps: 0.0, + slippage_bps: 0.0, + min_commission: 100, + }; + let mut portfolio = Portfolio::new(0, model); + // Proceeds 100 cents equal the 100-cent minimum commission. + portfolio.execute_fill(aapl(), Shares::from_whole(-1), 100); + assert_eq!(qty_of(&portfolio, &aapl()), Shares::from_whole(-1)); + assert_eq!(portfolio.cash(), 0); + } + + #[test] + fn buy_with_zero_cash_and_fine_step_is_skipped() { + let mut portfolio = Portfolio::with_quantity_step(0, CostModel::zero(), 1); + portfolio.execute_fill(aapl(), Shares::from_whole(5), 100); + assert!(portfolio.position(&aapl()).is_none()); + assert_eq!(portfolio.cash(), 0); + assert_eq!(portfolio.trimmed_fill_count(), 1); + assert_eq!( + largest_affordable_buy_qty(5_000_000, 0, 1, 100, &CostModel::zero()), + Shares::ZERO + ); + } + + // --- record_return with zero previous equity --- + + #[test] + fn record_return_with_zero_equity_from_the_start_records_no_return() { + let mut portfolio = Portfolio::new(0, CostModel::zero()); + portfolio.record_return(&[]); + assert!(portfolio.returns().is_empty()); + assert_eq!(portfolio.equity_curve(), &[0, 0]); + } + + #[test] + fn record_return_after_equity_hits_zero_keeps_one_return_per_call() { + let mut portfolio = Portfolio::new(100_00, CostModel::zero()); + portfolio.rebalance_simple(&[(aapl(), 1.0)], &[(aapl(), 10_00)]); + portfolio.record_return(&[(aapl(), 10_00)]); + portfolio.record_return(&[(aapl(), 0)]); + portfolio.record_return(&[(aapl(), 0)]); + assert_eq!(portfolio.returns(), &[0.0, -1.0, 0.0]); + } + + // --- getters read back what the setters stored --- + + #[test] + fn getters_return_the_configured_values() { + let model = CostModel { + commission_bps: 7.5, + slippage_bps: 2.5, + min_commission: 3, + }; + let mut portfolio = Portfolio::new(1_000_00, model); + portfolio.set_min_order_value(500_00); + portfolio.set_max_order_value(30_000_00); + portfolio.set_no_trade_band_bps(25.0); + portfolio.set_max_trades_per_rebalance(Some(4)); + portfolio.set_max_rebalance_notional(20_000_00); + assert_eq!(portfolio.min_order_value(), 500_00); + assert_eq!(portfolio.max_order_value(), 30_000_00); + assert_eq!(portfolio.no_trade_band_bps(), 25.0); + assert_eq!(portfolio.max_trades_per_rebalance(), Some(4)); + assert_eq!(portfolio.max_rebalance_notional(), 20_000_00); + assert_eq!(portfolio.cost_model().commission_bps, 7.5); + assert_eq!(portfolio.cost_model().slippage_bps, 2.5); + assert_eq!(portfolio.cost_model().min_commission, 3); + } } #[cfg(all(test, feature = "persistence"))] @@ -2507,6 +2849,20 @@ mod persistence_tests { Symbol::new("AAPL") } + /// JSON saved before `quantity_step` existed loads with whole-share sizing. + #[test] + fn json_without_quantity_step_defaults_to_whole_shares() { + let mut value = + serde_json::to_value(Portfolio::new(1_000_000_00, CostModel::zero())).unwrap(); + value + .as_object_mut() + .unwrap() + .remove("quantity_step") + .expect("quantity_step is serialized"); + let portfolio: Portfolio = serde_json::from_value(value).unwrap(); + assert_eq!(portfolio.quantity_step(), Shares::SCALE); + } + #[test] fn portfolio_json_roundtrip() { let mut portfolio = Portfolio::new(1_000_000_00, CostModel::zero()); diff --git a/src/portfolio/position.rs b/src/portfolio/position.rs index ee814f4..3fcf19e 100644 --- a/src/portfolio/position.rs +++ b/src/portfolio/position.rs @@ -393,4 +393,21 @@ mod tests { let expected: i128 = 1_000_000i128 * price as i128; assert_eq!(pos.market_value(price) as i128, expected); } + + #[test] + fn shares_zero_is_neither_positive_nor_negative() { + assert!(!Shares::ZERO.is_positive()); + assert!(!Shares::ZERO.is_negative()); + assert!(Shares::from_raw(1).is_positive()); + assert!(Shares::from_raw(-1).is_negative()); + } + + #[test] + fn shares_unsigned_abs_and_sub() { + assert_eq!(Shares::from_whole(-3).unsigned_abs(), 3_000_000); + assert_eq!(Shares::from_whole(3).unsigned_abs(), 3_000_000); + assert_eq!(Shares::ZERO.unsigned_abs(), 0); + assert_eq!(w(5) - w(3), w(2)); + assert_eq!(w(3) - w(5), w(-2)); + } } diff --git a/src/portfolio/strategy.rs b/src/portfolio/strategy.rs index 22139e7..b62a7ef 100644 --- a/src/portfolio/strategy.rs +++ b/src/portfolio/strategy.rs @@ -255,4 +255,21 @@ mod tests { let weights = strat.compute_weights(0, &[], &Portfolio::new(100_00, CostModel::zero())); assert!(weights.is_empty()); } + + #[test] + fn equal_weight_splits_evenly_across_symbols() { + let portfolio = Portfolio::new(100_00, CostModel::zero()); + let two = EqualWeight.compute_weights( + 0, + &[(sym("AAPL"), 150_00), (sym("MSFT"), 300_00)], + &portfolio, + ); + assert_eq!(two, vec![(sym("AAPL"), 0.5), (sym("MSFT"), 0.5)]); + + let names = ["A", "B", "C", "D"]; + let prices: Vec<(Symbol, i64)> = names.iter().map(|n| (sym(n), 10_00)).collect(); + let four = EqualWeight.compute_weights(0, &prices, &portfolio); + assert_eq!(four.len(), 4); + assert!(four.iter().all(|&(_, w)| w == 0.25)); + } } From 4b3eaea1bed86e90ff518cb492d5b9c605ebdbff Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:09:31 +0100 Subject: [PATCH 34/66] test(broker): build the binance tests only with the binance feature cargo clippy --workspace --all-targets failed without the feature: two tests include src/binance/websocket.rs (tokio_tungstenite, futures_util) and the mock kept a variable only its binance-gated code reads. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- broker/tests/binance_reconnect.rs | 2 ++ broker/tests/binance_websocket.rs | 2 ++ broker/tests/mock_binance.rs | 1 + 3 files changed, 5 insertions(+) diff --git a/broker/tests/binance_reconnect.rs b/broker/tests/binance_reconnect.rs index 0baaf6d..0b9fb48 100644 --- a/broker/tests/binance_reconnect.rs +++ b/broker/tests/binance_reconnect.rs @@ -1,3 +1,5 @@ +#![cfg(feature = "binance")] + #[path = "../src/binance/websocket.rs"] #[allow(dead_code)] mod websocket; diff --git a/broker/tests/binance_websocket.rs b/broker/tests/binance_websocket.rs index ce92c2f..676f8b8 100644 --- a/broker/tests/binance_websocket.rs +++ b/broker/tests/binance_websocket.rs @@ -1,3 +1,5 @@ +#![cfg(feature = "binance")] + #[path = "../src/binance/websocket.rs"] #[allow(dead_code)] mod websocket; diff --git a/broker/tests/mock_binance.rs b/broker/tests/mock_binance.rs index 920ee98..625e692 100644 --- a/broker/tests/mock_binance.rs +++ b/broker/tests/mock_binance.rs @@ -389,6 +389,7 @@ impl Broker for MockBroker { // Extract sequence number from client_order_id if it follows the pattern // Format: "nanobook-{short_uuid}-{sequence}" + #[cfg(feature = "binance")] let sequence_number = client_order_id .and_then(|cid| cid.rsplit('-').next().and_then(|s| s.parse::().ok())); From ccadf8f990f2a1150ee1a5435a24492c8b23eac0 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:12:35 +0100 Subject: [PATCH 35/66] test(metrics): pin exact values in portfolio metrics cargo-mutants 0.20.0 showed these values were never checked: tests only asserted finiteness, sign or a single parameter set. Add exact-value tests with a stated tolerance for: - compute_metrics: CAGR exponent (n != periods_per_year), volatility annualisation, n = 1 volatility, CAGR clamp at total and leveraged loss, and the all-zero / all-winning / all-losing profit factor, payoff ratio, Kelly and Calmar. - sortino: non-zero risk-free rate, no downside, ddof > n. - norm_ppf: 16-point grid over lower tail, centre and upper tail against Python's NormalDist().inv_cdf. - cvar: parametric sigma and strict threshold, alpha outside (0, 1). - rolling_sharpe, rolling_volatility (rolling_window): values, window == len, windows 0, 1, 2, and a zero-variance window. - rolling_max_drawdown: window 0, window == len, zero running peak. - drawdown_series: trough index on equal-depth and deeper later points. No library behaviour changed. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- src/portfolio/metrics.rs | 265 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 265 insertions(+) diff --git a/src/portfolio/metrics.rs b/src/portfolio/metrics.rs index 336943c..54b6b4e 100644 --- a/src/portfolio/metrics.rs +++ b/src/portfolio/metrics.rs @@ -865,4 +865,269 @@ mod tests { assert!(!result[4].is_nan()); assert!(result[4] > 0.0); } + + // --- exact-value tests (cargo-mutants 0.20.0 showed these were never checked) --- + + /// Assert `|actual - expected| <= tol * max(|expected|, 1)`. + fn assert_close(actual: f64, expected: f64, tol: f64, what: &str) { + let bound = tol * expected.abs().max(1.0); + assert!( + (actual - expected).abs() <= bound, + "{what}: got {actual}, expected {expected} (bound {bound})" + ); + } + + /// NaN positions must match; other positions compared with `assert_close`. + fn assert_series_close(actual: &[f64], expected: &[f64], tol: f64, what: &str) { + assert_eq!(actual.len(), expected.len(), "{what}: length"); + for (i, (&a, &e)) in actual.iter().zip(expected).enumerate() { + if e.is_nan() { + assert!(a.is_nan(), "{what}[{i}]: expected NaN, got {a}"); + } else { + assert_close(a, e, tol, &format!("{what}[{i}]")); + } + } + } + + /// A2-G1: CAGR exponent 1/years, volatility annualisation, n = 1 volatility. + #[test] + fn compute_metrics_cagr_and_volatility_exact() { + // (a) six 1% monthly returns: years = 0.5, CAGR = 1.01^12 - 1. + // Closed form; 1e-9 absolute covers powf rounding. A wrong exponent gives 0.0303. + let m = compute_metrics(&[0.01; 6], 12.0, 0.0).unwrap(); + assert_close(m.cagr, 0.126_825_030_132, 1e-9, "cagr"); + + // (b) sample std 0.0230940108 * sqrt(252); 1e-9 covers sqrt rounding. + // Dividing by sqrt(252) instead gives 0.00145. + let m = compute_metrics(&[0.03, -0.01, 0.03, -0.01], 252.0, 0.0).unwrap(); + assert_close(m.volatility, 0.366_606_055_6, 1e-9, "volatility"); + + // (c) one return: sample variance is defined as 0.0, not 0/0. + let m = compute_metrics(&[0.05], 252.0, 0.0).unwrap(); + assert_eq!(m.volatility, 0.0); + } + + /// A2-G5: total or leveraged loss clamps CAGR to -1. + #[test] + fn cagr_clamps_total_loss() { + assert_eq!(compute_metrics(&[-1.0], 12.0, 0.0).unwrap().cagr, -1.0); + // total_return = -1.5 (below -100%): must not enter the powf branch. + assert_eq!(compute_metrics(&[-1.5], 12.0, 0.0).unwrap().cagr, -1.0); + } + + /// A2-G6: degenerate win/loss series fix profit factor, payoff ratio, Kelly, Calmar. + #[test] + fn degenerate_win_loss_ratios() { + // All zeros: no wins, no losses, no drawdown. + let m = compute_metrics(&[0.0, 0.0, 0.0], 252.0, 0.0).unwrap(); + assert_eq!(m.profit_factor, 0.0); + assert_eq!(m.payoff_ratio, 0.0); + assert_eq!(m.kelly, 0.0); + assert_eq!(m.calmar, 0.0); + + // All winning: no losses, payoff ratio infinite, Kelly defined as 0. + let m = compute_metrics(&[0.01, 0.02, 0.03], 252.0, 0.0).unwrap(); + assert_eq!(m.profit_factor, f64::INFINITY); + assert_eq!(m.payoff_ratio, f64::INFINITY); + assert_eq!(m.kelly, 0.0); + assert_eq!(m.calmar, 0.0); + + // All losing: no wins, payoff ratio 0, Kelly defined as 0. + let m = compute_metrics(&[-0.01, -0.02], 252.0, 0.0).unwrap(); + assert_eq!(m.profit_factor, 0.0); + assert_eq!(m.payoff_ratio, 0.0); + assert_eq!(m.kelly, 0.0); + } + + /// A2-G2: Sortino with non-zero risk-free rate, no downside, ddof guard. + #[test] + fn sortino_risk_free_and_guards() { + // (a) excess mean 0.0066 - 0.002; downside from r - rf < 0. Reference computed + // in Python from the definition; 1e-9 covers sqrt/division rounding. Flipping + // the sign of rf in either place gives 11.33 or 7.21. + let r = [0.02, -0.01, 0.03, -0.02, 0.01]; + assert_close( + sortino(&r, 0.002, 252.0, 0), + 5.665_854_818_827, + 1e-9, + "sortino", + ); + + // (b) no return below rf: downside deviation 0 gives 0.0, not +inf. + assert_eq!(sortino(&[0.01, 0.02, 0.03], 0.0, 252.0, 0), 0.0); + + // (c) ddof larger than n: documented 0.0 (not a usize underflow panic). + assert_eq!(sortino(&[0.01, -0.02], 0.0, 252.0, 3), 0.0); + // ddof == n and empty input also give 0.0. + assert_eq!(sortino(&[0.01, -0.02], 0.0, 252.0, 2), 0.0); + assert_eq!(sortino(&[], 0.0, 252.0, 0), 0.0); + } + + /// A2-G3: rolling Sharpe values and zero-variance window. + #[test] + fn rolling_sharpe_exact() { + // window mean * sqrt(252) / sample std; 1e-12 relative covers Welford rounding. + let r = [0.02, -0.01, 0.03, 0.0, 0.01]; + let expected = [ + f64::NAN, + f64::NAN, + 10.167_822_548_835_88, + 5.083_911_274_417_94, + 13.856_406_460_551_018, + ]; + assert_series_close( + &rolling_sharpe(&r, 3, 252), + &expected, + 1e-12, + "rolling_sharpe", + ); + + // Zero-variance window: std is exactly 0, result is 0.0 (not +inf). + let result = rolling_sharpe(&[0.01; 30], 20, 252); + assert_eq!(result[19], 0.0); + assert_eq!(result[29], 0.0); + } + + /// A2-G4: probit against `statistics.NormalDist().inv_cdf` on a grid that + /// covers the lower tail, central region and upper tail. + #[test] + fn norm_ppf_matches_reference_grid() { + // Acklam's approximation is accurate to about 1.2e-9 relative; 1e-8 allows + // that. Reference values from Python's `statistics.NormalDist().inv_cdf`. + #[allow(clippy::excessive_precision)] + let grid: [(f64, f64); 16] = [ + (1e-16, -8.222_082_216_130_435), + (1e-4, -3.719_016_485_455_68), + (1e-3, -3.090_232_306_167_813), + (0.01, -2.326_347_874_040_840_8), + (0.02, -2.053_748_910_631_822_5), + (0.03, -1.880_793_608_151_250_9), + (0.1, -1.281_551_565_544_600_8), + (0.3, -0.524_400_512_708_040_7), + (0.5, 0.0), + (0.7, 0.524_400_512_708_040_7), + (0.9, 1.281_551_565_544_600_8), + (0.97, 1.880_793_608_151_250_4), + (0.98, 2.053_748_910_631_822), + (0.99, 2.326_347_874_040_840_8), + (0.999, 3.090_232_306_167_813), + (0.9999, 3.719_016_485_455_708_4), + ]; + for (p, z) in grid { + assert_close(norm_ppf(p), z, 1e-8, &format!("norm_ppf({p})")); + } + assert_eq!(norm_ppf(0.0), f64::NEG_INFINITY); + assert_eq!(norm_ppf(1.0), f64::INFINITY); + } + + /// A2-G7: parametric CVaR sigma (sample variance) and strict threshold. + #[test] + fn cvar_parametric_tail_selection() { + // (a) threshold -0.032283 selects {-0.06, -0.05}; mean -0.055. A wrong sigma + // moves the threshold to -0.0555 or -0.02745 and changes the tail set. + let r = [-0.06, -0.05, -0.03, 0.06, 0.08, 0.11, 0.12]; + assert_close( + cvar(&r, 0.2, CVaRMethod::ParametricNormal), + -0.055, + 1e-12, + "cvar", + ); + + // (b) mean is exactly 0 and norm_ppf(0.5) = 0, so the threshold is exactly 0.0; + // the return equal to it is not strictly below, so the tail is {-0.01}. + assert_eq!( + cvar(&[-0.01, 0.0, 0.01], 0.5, CVaRMethod::ParametricNormal), + -0.01 + ); + } + + /// A2-G8: documented 0.0 for empty input and alpha outside (0, 1). + #[test] + fn cvar_invalid_alpha_returns_zero() { + let r = [0.01, -0.02, 0.03, -0.04]; + for method in [CVaRMethod::Historical, CVaRMethod::ParametricNormal] { + for alpha in [0.0, -0.1, 1.0, 1.5] { + assert_eq!(cvar(&r, alpha, method), 0.0, "{method:?} alpha {alpha}"); + } + assert_eq!(cvar(&[], 0.05, method), 0.0, "{method:?} empty"); + } + // Sanity: a valid alpha is not 0.0 (historical: ceil(4 * 0.25) = 1 worst value). + assert_eq!(cvar(&r, 0.25, CVaRMethod::Historical), -0.04); + } + + /// A2-G9: window and length boundaries of `rolling_window`. + #[test] + fn rolling_window_boundaries() { + let r = [0.01, -0.01, 0.02]; + let nan = f64::NAN; + // (a) window == len gives one value. Reference sample std * sqrt(252). + assert_series_close( + &rolling_volatility(&r, 3, 252), + &[nan, nan, 0.242_487_113_059_642_82], + 1e-12, + "window 3", + ); + // (b) window 2 is computed. + assert_series_close( + &rolling_volatility(&r, 2, 252), + &[nan, 0.224_499_443_206_436_5, 0.336_749_164_809_654_8], + 1e-12, + "window 2", + ); + // (c) windows 0 and 1 (no sample variance) and window > len: all NaN. + for w in [0, 1, 4] { + assert_series_close( + &rolling_volatility(&r, w, 252), + &[nan; 3], + 1e-12, + "bad window", + ); + assert_series_close(&rolling_sharpe(&r, w, 252), &[nan; 3], 1e-12, "bad window"); + } + } + + /// A2-G10: window 0, window == len, zero running peak. + #[test] + fn rolling_max_drawdown_edges() { + let nan = f64::NAN; + assert_series_close( + &rolling_max_drawdown(&[100.0, 120.0, 90.0], 3), + &[nan, nan, 0.25], + 1e-12, + "window == len", + ); + assert_series_close( + &rolling_max_drawdown(&[1.0, 2.0, 3.0], 0), + &[nan; 3], + 1e-12, + "window 0", + ); + // Peak 0 then -1: drawdown from a zero peak is skipped (0.0), not inf. + assert_series_close( + &rolling_max_drawdown(&[0.0, -1.0], 2), + &[nan, 0.0], + 1e-12, + "zero peak", + ); + } + + /// A2-G11: trough index follows a strictly deeper later point only. + #[test] + fn drawdown_series_trough_tracking() { + // Equal-depth later point: trough stays at the first (index 1). + let events = drawdown_series(&[100.0, 90.0, 95.0, 90.0, 100.0]); + assert_eq!(events.len(), 1); + assert_close(events[0].drawdown_pct, 0.1, 1e-12, "drawdown_pct"); + assert_eq!(events[0].underwater_periods, 3); + assert_eq!(events[0].peak_index, 0); + assert_eq!(events[0].trough_index, 1); + assert_eq!(events[0].recovery_index, Some(4)); + + // Deeper later point: trough and depth move to index 2. + let events = drawdown_series(&[100.0, 90.0, 80.0, 100.0]); + assert_eq!(events.len(), 1); + assert_close(events[0].drawdown_pct, 0.2, 1e-12, "drawdown_pct"); + assert_eq!(events[0].trough_index, 2); + assert_eq!(events[0].recovery_index, Some(3)); + } } From fd99b7deee012919dbc11a1aaee573ef463724d2 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:22:41 +0100 Subject: [PATCH 36/66] test(broker): pin Binance, mock and directly reachable IBKR behaviour cargo-mutants 0.20.0 showed these survivors were never checked by any test. New tests, with exact values: - Binance: reconcile_state (orphan, missing, status mismatch, every status mapping, block flag), positions and account arithmetic, quote bid/ask/mid, trading-pair symbol, price rounding, the generated client order id sent and audited by submit_order_with_sequence, open-order side and status mapping, REST poll gating, order cache save and load for every side and status, cancel_order refusal, disconnect, order-filled audit line, query parameter validation, timestamp, and the websocket event parsing, endpoint, heartbeat guard and zero-attempt reconnect. - Mock broker: quote last price, partial-fill remainder, open_orders, cancel_order. - IBKR (no seam needed): partial-fill boundary in broker_order_status_from_ibkr_parts, reconcile_partial_fill with nothing filled, encode_order for Stop and StopLimit, best_quote_from_quote, connect/reconnect/cancel without a gateway, is_connected and disconnect. The Binance tests that need an HTTP answer use a loopback server inside the test module and a cfg(test) constructor BinanceClient::with_base_url (test builds only, no change to library behaviour). Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- broker/src/binance/audit.rs | 16 ++ broker/src/binance/client.rs | 96 +++++++ broker/src/binance/mod.rs | 334 ++++++++++++++++++++++ broker/src/binance/websocket.rs | 114 ++++++++ broker/src/ibkr/market_data.rs | 36 +++ broker/src/ibkr/mod.rs | 29 ++ broker/src/ibkr/orders.rs | 33 +++ broker/src/mock.rs | 85 ++++++ broker/tests/binance_account_reconcile.rs | 14 + broker/tests/binance_order_cache.rs | 87 ++++++ broker/tests/binance_rest_fallback.rs | 78 +++++ broker/tests/ibkr_market_order_bounds.rs | 30 ++ broker/tests/ibkr_state_query.rs | 74 ++++- 13 files changed, 1024 insertions(+), 2 deletions(-) diff --git a/broker/src/binance/audit.rs b/broker/src/binance/audit.rs index 6b4c03c..e807797 100644 --- a/broker/src/binance/audit.rs +++ b/broker/src/binance/audit.rs @@ -183,6 +183,22 @@ mod tests { assert!(content.contains("test-cid")); } + #[test] + fn test_audit_log_order_filled() { + let temp_dir = TempDir::new().unwrap(); + let log_path = temp_dir.path().join("audit.log"); + + log_order_filled(&log_path, OrderId(100), 3); + + let content = std::fs::read_to_string(&log_path).unwrap(); + assert_eq!(content.lines().count(), 1); + let event: serde_json::Value = + serde_json::from_str(content.lines().next().unwrap()).unwrap(); + assert_eq!(event["event_type"], "order_filled"); + assert_eq!(event["order_id"], 100); + assert_eq!(event["sequence"], 3); + } + #[test] fn test_audit_log_idempotency_rejection() { let temp_dir = TempDir::new().unwrap(); diff --git a/broker/src/binance/client.rs b/broker/src/binance/client.rs index 1cd5401..0755f52 100644 --- a/broker/src/binance/client.rs +++ b/broker/src/binance/client.rs @@ -82,6 +82,21 @@ impl BinanceClient { } } + /// Test-only constructor: points the client at `base_url` (a loopback + /// test server) and bypasses any proxy set in the environment. + #[cfg(test)] + pub(super) fn with_base_url(api_key: &str, secret_key: &str, base_url: &str) -> Self { + Self { + client: Client::builder() + .no_proxy() + .build() + .expect("build test HTTP client"), + api_key: api_key.to_string(), + secret_key: secret_key.to_string(), + base_url: base_url.to_string(), + } + } + /// Test connectivity (GET /api/v3/ping). pub fn ping(&self) -> Result<(), BrokerError> { let url = format!("{}/api/v3/ping", self.base_url); @@ -253,3 +268,84 @@ fn current_timestamp_ms() -> Result { .map(|d| d.as_millis() as u64) .map_err(|e| BrokerError::Connection(format!("system clock error: {e}"))) } + +#[cfg(test)] +mod tests { + use super::*; + + /// `http://127.0.0.1:` of a loopback port that was just released: + /// connecting is refused at once (a fixed port could be filtered and hang). + fn refused_base_url() -> String { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + drop(listener); + url + } + + fn invalid_chars_error(result: Result<(), BrokerError>, name: &str) { + match result { + Err(BrokerError::Order(message)) => { + assert!( + message.contains(&format!("invalid characters in {name}")), + "got {message}" + ); + } + other => panic!("expected Order error, got {other:?}"), + } + } + + #[test] + fn validate_query_param_accepts_safe_values() { + for value in ["BTCUSDT", "cid-1_a.b", "a_b", "a.b", "a-b", "0.001", ""] { + assert!( + validate_query_param(value, "symbol").is_ok(), + "{value:?} must be accepted" + ); + } + } + + #[test] + fn validate_query_param_rejects_injection_characters() { + for value in ["BTC&side=SELL", "a b", "a=b", "a?b", "a#b", "a/b", "a%b"] { + invalid_chars_error(validate_query_param(value, "symbol"), "symbol"); + } + } + + #[test] + fn validate_query_params_names_the_failing_parameter() { + assert!(validate_query_params(&[("ok", "a"), ("fine-1", "b")]).is_ok()); + + invalid_chars_error(validate_query_params(&[("ok", "a"), ("bad&", "b")]), "b"); + } + + #[test] + fn current_timestamp_is_the_wall_clock_in_milliseconds() { + let now_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() as u64; + + let stamp = current_timestamp_ms().unwrap(); + + assert!( + stamp.abs_diff(now_ms) < 5_000, + "stamp {stamp} vs clock {now_ms}" + ); + } + + #[test] + fn cancel_order_validates_the_symbol_before_any_request() { + // The server is never reached: validation fails first. + let client = BinanceClient::with_base_url("key", "secret", &refused_base_url()); + + invalid_chars_error(client.cancel_order("A&B", 1), "symbol"); + } + + #[test] + fn ping_reports_a_connection_error_when_the_server_is_unreachable() { + // Nothing listens on the port: the TCP connect is refused. + let client = BinanceClient::with_base_url("key", "secret", &refused_base_url()); + + assert!(matches!(client.ping(), Err(BrokerError::Connection(_)))); + } +} diff --git a/broker/src/binance/mod.rs b/broker/src/binance/mod.rs index 60ec335..5876189 100644 --- a/broker/src/binance/mod.rs +++ b/broker/src/binance/mod.rs @@ -858,3 +858,337 @@ impl Broker for BinanceBroker { }) } } + +#[cfg(test)] +mod tests { + use super::*; + use std::io::{Read, Write}; + use std::net::{TcpListener, TcpStream}; + use std::sync::Arc; + use std::thread; + + fn read_request(stream: &mut TcpStream) -> String { + let mut data = Vec::new(); + let mut buf = [0u8; 1024]; + loop { + let n = stream.read(&mut buf).unwrap_or(0); + if n == 0 { + break; + } + data.extend_from_slice(&buf[..n]); + if let Some(pos) = data.windows(4).position(|w| w == b"\r\n\r\n") { + let head = String::from_utf8_lossy(&data[..pos]).to_lowercase(); + let body_len = head + .lines() + .find_map(|line| line.strip_prefix("content-length:")) + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(0); + if data.len() >= pos + 4 + body_len { + break; + } + } + } + String::from_utf8_lossy(&data).into_owned() + } + + /// Loopback HTTP server: answers one connection per entry of `bodies`, in + /// order, with HTTP 200 and that JSON body. Returns the base URL and the + /// raw requests seen so far. + fn serve(bodies: Vec) -> (String, Arc>>) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let base_url = format!("http://{}", listener.local_addr().unwrap()); + let seen = Arc::new(Mutex::new(Vec::new())); + let log = Arc::clone(&seen); + thread::spawn(move || { + for body in bodies { + let Ok((mut stream, _)) = listener.accept() else { + return; + }; + let request = read_request(&mut stream); + log.lock().unwrap().push(request); + let reply = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + body.len(), + body + ); + let _ = stream.write_all(reply.as_bytes()); + } + }); + (base_url, seen) + } + + fn connected_to(base_url: &str) -> BinanceBroker { + let mut broker = BinanceBroker::new("key", "secret", true); + broker.client = Some(BinanceClient::with_base_url("key", "secret", base_url)); + broker + } + + fn open_order_json(order_id: u64, status: &str) -> String { + format!( + r#"{{"symbol":"BTCUSDT","orderId":{order_id},"status":"{status}","side":"BUY","origQty":"1","executedQty":"0"}}"# + ) + } + + fn account_json(balances: &str, open_orders: &[String]) -> String { + format!( + r#"{{"balances":[{balances}],"openOrders":[{}],"canTrade":true}}"#, + open_orders.join(",") + ) + } + + fn cache(broker: &BinanceBroker, id: u64, status: OrderState) { + broker.cache_order(OrderId(id), Symbol::new("BTC"), 1, BrokerSide::Buy, None); + broker.update_cached_order_status(OrderId(id), status); + } + + // ---- symbol and price helpers -------------------------------------- + + #[test] + fn to_binance_symbol_appends_the_quote_asset() { + let broker = BinanceBroker::new("key", "secret", true); + assert_eq!(broker.to_binance_symbol(&Symbol::new("BTC")), "BTCUSDT"); + + let broker = broker.with_quote_asset("EUR"); + assert_eq!(broker.to_binance_symbol(&Symbol::new("BTC")), "BTCEUR"); + } + + #[test] + fn parse_price_cents_rounds_to_the_nearest_cent() { + assert_eq!( + BinanceBroker::parse_price_cents("185.50", "binance bid").unwrap(), + 18_550 + ); + // 0.126 dollars = 12.6 cents + assert_eq!( + BinanceBroker::parse_price_cents("0.126", "binance bid").unwrap(), + 13 + ); + } + + // ---- quote --------------------------------------------------------- + + #[test] + fn quote_prices_bid_ask_and_mid_in_cents() { + let (url, seen) = serve(vec![ + r#"{"symbol":"BTCUSDT","bidPrice":"184.95","bidQty":"1","askPrice":"185.05","askQty":"2"}"# + .to_string(), + ]); + let broker = connected_to(&url); + + let quote = broker.quote(&Symbol::new("BTC")).unwrap(); + + assert_eq!(quote.symbol, Symbol::new("BTC")); + assert_eq!(quote.bid_cents, 18_495); + assert_eq!(quote.ask_cents, 18_505); + assert_eq!(quote.last_cents, 18_500); + let requests = seen.lock().unwrap(); + assert!( + requests[0].starts_with("GET /api/v3/ticker/bookTicker?symbol=BTCUSDT "), + "got {}", + requests[0] + ); + } + + // ---- positions and account ----------------------------------------- + + const BALANCES: &str = r#"{"asset":"BTC","free":"1.00000000","locked":"0.50000000"},{"asset":"ETH","free":"0","locked":"0"},{"asset":"USDT","free":"100.00","locked":"25.50"}"#; + + #[test] + fn positions_sum_free_and_locked_and_skip_empty_balances() { + let (url, _) = serve(vec![account_json(BALANCES, &[])]); + let broker = connected_to(&url); + + let positions = broker.positions().unwrap(); + + let rows: Vec<(String, i64)> = positions + .iter() + .map(|p| (p.symbol.as_str().to_string(), p.quantity)) + .collect(); + assert_eq!( + rows, + vec![ + ("BTC".to_string(), 150_000_000), + ("USDT".to_string(), 12_550_000_000), + ] + ); + } + + #[test] + fn account_equity_is_the_quote_asset_balance_in_cents() { + let (url, _) = serve(vec![account_json(BALANCES, &[])]); + let broker = connected_to(&url); + + let account = broker.account().unwrap(); + + // USDT free 100.00 + locked 25.50; BTC and ETH are not counted. + assert_eq!(account.equity_cents, 12_550); + assert_eq!(account.cash_cents, 12_550); + assert_eq!(account.buying_power_cents, 12_550); + assert_eq!(account.gross_position_value_cents, 0); + } + + // ---- reconcile_state ----------------------------------------------- + + #[test] + fn reconcile_state_reports_nothing_when_cache_and_broker_agree() { + let (url, _) = serve(vec![account_json( + "", + &[open_order_json(1, "NEW"), open_order_json(2, "FILLED")], + )]); + let mut broker = connected_to(&url); + cache(&broker, 1, OrderState::Submitted); + cache(&broker, 2, OrderState::Filled); + + let report = broker.reconcile_state().unwrap(); + + assert!( + report.discrepancies.is_empty(), + "{:?}", + report.discrepancies + ); + assert!(!report.has_critical_issues); + assert!(!broker.is_reconciliation_blocked()); + } + + #[test] + fn reconcile_state_reports_a_broker_order_missing_from_the_cache_as_orphan() { + let (url, _) = serve(vec![account_json( + "", + &[open_order_json(1, "NEW"), open_order_json(9, "NEW")], + )]); + let mut broker = connected_to(&url); + cache(&broker, 1, OrderState::Submitted); + cache(&broker, 2, OrderState::Filled); + + let report = broker.reconcile_state().unwrap(); + + assert_eq!( + report.discrepancies, + vec![Discrepancy::OrphanOrder { + order_id: OrderId(9) + }] + ); + assert!(report.has_critical_issues); + assert!(broker.is_reconciliation_blocked()); + } + + #[test] + fn reconcile_state_reports_a_submitted_cached_order_absent_from_the_broker_as_missing() { + let (url, _) = serve(vec![account_json("", &[open_order_json(1, "NEW")])]); + let mut broker = connected_to(&url); + cache(&broker, 1, OrderState::Submitted); + cache(&broker, 2, OrderState::Filled); + cache(&broker, 3, OrderState::Submitted); + + let report = broker.reconcile_state().unwrap(); + + // Order 2 is already Filled locally, so its absence is expected. + assert_eq!( + report.discrepancies, + vec![Discrepancy::MissingOrder { + order_id: OrderId(3) + }] + ); + assert!(report.has_critical_issues); + assert!(broker.is_reconciliation_blocked()); + } + + #[test] + fn reconcile_state_maps_every_binance_status_before_comparing() { + let statuses = [ + "PARTIALLY_FILLED", + "FILLED", + "CANCELED", + "REJECTED", + "EXPIRED", + ]; + let open: Vec = statuses + .iter() + .zip(11u64..) + .map(|(status, id)| open_order_json(id, status)) + .collect(); + let (url, _) = serve(vec![account_json("", &open)]); + let mut broker = connected_to(&url); + for id in 11..=15 { + cache(&broker, id, OrderState::Submitted); + } + + let report = broker.reconcile_state().unwrap(); + + let expected: Vec = [ + OrderState::PartiallyFilled, + OrderState::Filled, + OrderState::Cancelled, + OrderState::Rejected, + OrderState::Cancelled, + ] + .into_iter() + .zip(11u64..) + .map(|(broker_status, id)| Discrepancy::OrderStatusMismatch { + order_id: OrderId(id), + local_status: "Submitted".to_string(), + broker_status, + }) + .collect(); + assert_eq!(report.discrepancies, expected); + assert!(report.has_critical_issues); + } + + // ---- submit_order_with_sequence ------------------------------------ + + #[test] + fn submit_with_sequence_sends_and_audits_the_generated_client_order_id() { + let dir = tempfile::TempDir::new().unwrap(); + let audit_path = dir.path().join("audit.jsonl"); + let (url, seen) = serve(vec![ + r#"{"symbol":"BTCUSDT","orderId":77,"status":"NEW","executedQty":"0"}"#.to_string(), + ]); + let broker = connected_to(&url).with_audit_log_path(audit_path.clone()); + let order = BrokerOrder { + symbol: Symbol::new("BTC"), + side: BrokerSide::Buy, + quantity: 1, + order_type: BrokerOrderType::Market, + client_order_id: None, + }; + + let order_id = broker.submit_order_with_sequence(&order, Some(5)).unwrap(); + + assert_eq!(order_id, OrderId(77)); + let request = seen.lock().unwrap()[0].clone(); + let sent = request + .split("newClientOrderId=") + .nth(1) + .expect("request carries newClientOrderId") + .split('&') + .next() + .unwrap() + .to_string(); + assert!(sent.starts_with("nanobook-"), "got {sent}"); + assert!(sent.ends_with("-5"), "got {sent}"); + + let cached = broker.get_cached_order(OrderId(77)).unwrap(); + assert_eq!(cached.client_order_id.as_deref(), Some(sent.as_str())); + + assert!(check_audit_log_for_sequence(&audit_path, 5).unwrap()); + let line = std::fs::read_to_string(&audit_path).unwrap(); + let event: serde_json::Value = serde_json::from_str(line.lines().next().unwrap()).unwrap(); + assert_eq!(event["event_type"], "order_submitted"); + assert_eq!(event["order_id"], 77); + assert_eq!(event["sequence"], 5); + assert_eq!(event["client_order_id"], sent.as_str()); + } + + // ---- disconnect ---------------------------------------------------- + + #[test] + fn disconnect_drops_the_client() { + let mut broker = connected_to("http://127.0.0.1:9"); + assert!(broker.client.is_some()); + + broker.disconnect().unwrap(); + + assert!(broker.client.is_none()); + assert!(matches!(broker.positions(), Err(BrokerError::NotConnected))); + } +} diff --git a/broker/src/binance/websocket.rs b/broker/src/binance/websocket.rs index 4a258e1..bae2928 100644 --- a/broker/src/binance/websocket.rs +++ b/broker/src/binance/websocket.rs @@ -310,3 +310,117 @@ impl BinanceWebSocket { } } } + +#[cfg(test)] +mod tests { + use super::*; + + const EXECUTION_REPORT: &str = + r#"{"e":"executionReport","E":5,"s":"BTCUSDT","i":42,"c":"cid-1","X":"FILLED"}"#; + + fn execution_report_event() -> BinanceWebSocketEvent { + BinanceWebSocketEvent::ExecutionReport(ExecutionReport { + event_time: Some(5), + symbol: Some("BTCUSDT".to_string()), + order_id: Some(42), + client_order_id: Some("cid-1".to_string()), + order_status: Some("FILLED".to_string()), + raw: serde_json::from_str(EXECUTION_REPORT).unwrap(), + }) + } + + #[test] + fn execution_report_fields_are_extracted() { + let event = BinanceWebSocket::parse_text_message(EXECUTION_REPORT).unwrap(); + + assert_eq!(event, execution_report_event()); + } + + #[test] + fn account_events_become_account_updates() { + for kind in ["outboundAccountPosition", "balanceUpdate"] { + let text = format!(r#"{{"e":"{kind}","E":7}}"#); + + let event = BinanceWebSocket::parse_text_message(&text).unwrap(); + + assert_eq!( + event, + BinanceWebSocketEvent::AccountUpdate(AccountUpdate { + event_time: Some(7), + raw: serde_json::from_str(&text).unwrap(), + }), + "{kind}" + ); + } + } + + #[test] + fn unknown_events_stay_untyped() { + let event = BinanceWebSocket::parse_text_message(r#"{"e":"other"}"#).unwrap(); + + assert_eq!( + event, + BinanceWebSocketEvent::Other(serde_json::json!({"e": "other"})) + ); + } + + #[test] + fn frames_carry_events_only_for_text_and_binary() { + let text = BinanceWebSocket::parse_frame(Message::Text(EXECUTION_REPORT.into())).unwrap(); + assert_eq!(text, Some(execution_report_event())); + + let binary = BinanceWebSocket::parse_frame(Message::Binary( + EXECUTION_REPORT.as_bytes().to_vec().into(), + )) + .unwrap(); + assert_eq!(binary, Some(execution_report_event())); + + for message in [ + Message::Ping(Vec::new().into()), + Message::Pong(Vec::new().into()), + Message::Close(None), + ] { + assert_eq!(BinanceWebSocket::parse_frame(message).unwrap(), None); + } + } + + #[test] + fn endpoint_is_the_production_stream() { + let ws = BinanceWebSocket::new("key", "secret", false); + + assert_eq!(ws.endpoint(), "wss://stream.binance.com:9443/ws"); + } + + #[tokio::test] + async fn subscribe_checks_the_heartbeat_before_the_connection() { + let mut ws = BinanceWebSocket::new("key", "secret", true); + + // No heartbeat yet: reported as a timeout. + let err = ws.subscribe_user_data().await.unwrap_err(); + assert_eq!(err.to_string(), "Heartbeat timeout detected"); + assert_eq!(ws.state(), ConnectionState::Disconnected); + + // Fresh heartbeat but no socket. + ws.update_heartbeat(); + let err = ws.subscribe_user_data().await.unwrap_err(); + assert_eq!(err.to_string(), "Binance WebSocket is not connected"); + } + + #[tokio::test] + async fn reconnect_with_zero_attempts_fails_at_once_without_dialling() { + let mut ws = BinanceWebSocket::new("key", "secret", true); + ws.set_max_reconnect_attempts(0); + + // One attempt would sleep 1 s first; the call must return before that. + let result = tokio::time::timeout(Duration::from_millis(500), ws.reconnect_with_backoff()) + .await + .expect("zero attempts must not sleep or dial"); + + assert_eq!( + result.unwrap_err().to_string(), + "Failed to reconnect after 0 attempts" + ); + assert_eq!(ws.reconnect_attempts(), 0); + assert_eq!(ws.state(), ConnectionState::Disconnected); + } +} diff --git a/broker/src/ibkr/market_data.rs b/broker/src/ibkr/market_data.rs index 7cfdf67..71a835b 100644 --- a/broker/src/ibkr/market_data.rs +++ b/broker/src/ibkr/market_data.rs @@ -13,3 +13,39 @@ pub(crate) fn best_quote_from_quote(quote: &Quote) -> Option { None } } + +#[cfg(test)] +mod tests { + use super::*; + use nanobook::Symbol; + use std::time::SystemTime; + + fn quote(bid_cents: i64, ask_cents: i64) -> Quote { + Quote { + symbol: Symbol::new("AAPL"), + bid_cents, + ask_cents, + last_cents: 185_00, + volume: 0, + timestamp: SystemTime::now(), + } + } + + #[test] + fn two_sided_quote_gives_best_quote() { + assert_eq!( + best_quote_from_quote("e(184_95, 185_05)), + Some(BestQuote { + bid_cents: 184_95, + ask_cents: 185_05, + }) + ); + } + + #[test] + fn one_sided_or_empty_quote_gives_none() { + assert_eq!(best_quote_from_quote("e(0, 185_05)), None); + assert_eq!(best_quote_from_quote("e(184_95, 0)), None); + assert_eq!(best_quote_from_quote("e(0, 0)), None); + } +} diff --git a/broker/src/ibkr/mod.rs b/broker/src/ibkr/mod.rs index c66f848..ade2913 100644 --- a/broker/src/ibkr/mod.rs +++ b/broker/src/ibkr/mod.rs @@ -282,3 +282,32 @@ impl Broker for IbkrBroker { self.require_client()?.quote(symbol) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn is_connected_follows_the_connection_state() { + let mut broker = IbkrBroker::new("127.0.0.1", 1, 100); + assert!(!broker.is_connected()); + + broker.connection_state = ConnectionState::Connected; + assert!(broker.is_connected()); + + broker.connection_state = ConnectionState::Reconnecting; + assert!(!broker.is_connected()); + } + + #[test] + fn disconnect_resets_the_connection_state() { + let mut broker = IbkrBroker::new("127.0.0.1", 1, 100); + broker.connection_state = ConnectionState::Connected; + + broker.disconnect().unwrap(); + + assert_eq!(broker.connection_state(), ConnectionState::Disconnected); + assert!(!broker.is_connected()); + assert!(broker.client().is_none()); + } +} diff --git a/broker/src/ibkr/orders.rs b/broker/src/ibkr/orders.rs index 91b10ed..1bb1580 100644 --- a/broker/src/ibkr/orders.rs +++ b/broker/src/ibkr/orders.rs @@ -1181,6 +1181,39 @@ mod tests { assert_eq!(order_result.status, OrderOutcome::PartialFill); } + #[test] + fn test_reconcile_partial_fill_nothing_filled_and_flat_position_is_failed() { + // Nothing filled before the disconnect and the account is still flat + // after it: the order did not fill, so it is Failed, not a 0-share + // PartialFill. + let symbol = nanobook::Symbol::try_new("AAPL").unwrap(); + let positions = vec![Position { + symbol, + quantity: 0, + avg_cost_cents: 0, + market_value_cents: 0, + unrealized_pnl_cents: 0, + }]; + + let result = + reconcile_partial_fill(1, symbol, 0, 100, &positions, BrokerSide::Buy).unwrap(); + + assert_eq!(result.order_id, 1); + assert_eq!(result.filled_shares, 0); + assert_eq!(result.status, OrderOutcome::Failed); + } + + #[test] + fn test_reconcile_partial_fill_nothing_filled_and_no_position_is_failed() { + let symbol = nanobook::Symbol::try_new("AAPL").unwrap(); + + let result = reconcile_partial_fill(1, symbol, 0, 100, &[], BrokerSide::Buy).unwrap(); + + assert_eq!(result.order_id, 1); + assert_eq!(result.filled_shares, 0); + assert_eq!(result.status, OrderOutcome::Failed); + } + #[test] fn test_reconcile_partial_fill_sell_order() { // Test reconciliation for sell orders (negative positions) diff --git a/broker/src/mock.rs b/broker/src/mock.rs index 5d933bc..0449b53 100644 --- a/broker/src/mock.rs +++ b/broker/src/mock.rs @@ -410,4 +410,89 @@ mod tests { assert_eq!(second, OrderId(2)); assert_eq!(third, OrderId(3)); } + + fn market_order() -> BrokerOrder { + BrokerOrder { + symbol: aapl(), + side: BrokerSide::Buy, + quantity: 1, + order_type: BrokerOrderType::Market, + client_order_id: None, + } + } + + #[test] + fn with_quote_last_is_the_mid_of_bid_and_ask() { + let mut broker = MockBroker::builder() + .with_quote(aapl(), 14_950, 15_050) + .build(); + broker.connect().unwrap(); + + let quote = broker.quote(&aapl()).unwrap(); + + assert_eq!(quote.bid_cents, 14_950); + assert_eq!(quote.ask_cents, 15_050); + assert_eq!(quote.last_cents, 15_000); + } + + #[test] + fn partial_fill_remainder_is_the_unfilled_part_of_100() { + let mut broker = MockBroker::builder() + .fill_mode(FillMode::ImmediatePartial(0.5)) + .build(); + broker.connect().unwrap(); + let id = broker.submit_order(&market_order()).unwrap(); + + let status = broker.order_status(id).unwrap(); + assert_eq!(status.filled_quantity, 50); + assert_eq!(status.remaining_quantity, 50); + + let open = broker.open_orders().unwrap(); + assert_eq!(open.len(), 1); + assert_eq!(open[0].id, id); + assert_eq!(open[0].status, OrderState::PartiallyFilled); + assert_eq!(open[0].filled_quantity, 50); + assert_eq!(open[0].remaining_quantity, 50); + } + + #[test] + fn open_orders_lists_every_submitted_order() { + let mut broker = MockBroker::builder().build(); + assert!(matches!( + broker.open_orders(), + Err(BrokerError::NotConnected) + )); + + broker.connect().unwrap(); + assert!(broker.open_orders().unwrap().is_empty()); + broker.submit_order(&market_order()).unwrap(); + broker.submit_order(&market_order()).unwrap(); + + let open = broker.open_orders().unwrap(); + let ids: Vec = open.iter().map(|o| o.id).collect(); + assert_eq!(ids, vec![OrderId(1), OrderId(2)]); + for order in &open { + assert_eq!(order.status, OrderState::Filled); + assert_eq!(order.filled_quantity, 100); + assert_eq!(order.remaining_quantity, 0); + } + } + + #[test] + fn cancel_order_removes_only_that_order() { + let mut broker = MockBroker::builder().build(); + assert!(matches!( + broker.cancel_order(OrderId(1)), + Err(BrokerError::NotConnected) + )); + + broker.connect().unwrap(); + broker.submit_order(&market_order()).unwrap(); + broker.submit_order(&market_order()).unwrap(); + + broker.cancel_order(OrderId(1)).unwrap(); + + let ids: Vec = broker.open_orders().unwrap().iter().map(|o| o.id).collect(); + assert_eq!(ids, vec![OrderId(2)]); + } } diff --git a/broker/tests/binance_account_reconcile.rs b/broker/tests/binance_account_reconcile.rs index 2098f12..2897b65 100644 --- a/broker/tests/binance_account_reconcile.rs +++ b/broker/tests/binance_account_reconcile.rs @@ -165,6 +165,20 @@ mod binance_reconcile_tests { // Flag should be set assert!(broker.is_reconciliation_blocked()); } + + #[test] + fn test_cancel_order_without_symbol_is_refused() { + // The trait-level cancel has no symbol, which Binance requires: it + // must report an error, never a cancel that did not happen. + let broker = BinanceBroker::new("test_key", "test_secret", true); + + match broker.cancel_order(OrderId(1)) { + Err(BrokerError::Order(message)) => { + assert!(message.contains("symbol"), "got {message}"); + } + other => panic!("expected Order error, got {other:?}"), + } + } } // ============================================================================ diff --git a/broker/tests/binance_order_cache.rs b/broker/tests/binance_order_cache.rs index 12855c2..9fe8a8c 100644 --- a/broker/tests/binance_order_cache.rs +++ b/broker/tests/binance_order_cache.rs @@ -98,3 +98,90 @@ fn test_update_cached_order_status() { let cached = broker.get_cached_order(order_id).unwrap(); assert_eq!(cached.status, OrderState::Filled); } + +fn cached( + symbol: &str, + quantity: i64, + side: BrokerSide, + status: OrderState, + binance_order_id: &str, +) -> CachedOrder { + CachedOrder { + symbol: Symbol::new(symbol), + quantity, + side, + status, + binance_order_id: binance_order_id.to_string(), + client_order_id: Some(format!("client-{binance_order_id}")), + submitted_at: Utc::now(), + } +} + +#[test] +fn test_cache_persistence_covers_every_side_and_status() { + let dir = tempfile::TempDir::new().unwrap(); + let path = dir.path().join("orders.json"); + + let rows = [ + (1, BrokerSide::Buy, OrderState::Pending), + (2, BrokerSide::Sell, OrderState::Submitted), + (3, BrokerSide::Buy, OrderState::PartiallyFilled), + (4, BrokerSide::Sell, OrderState::Filled), + (5, BrokerSide::Buy, OrderState::Cancelled), + (6, BrokerSide::Sell, OrderState::Rejected), + ]; + let mut cache = BinanceOrderCache::new(); + for (id, side, status) in rows { + cache.orders.insert( + OrderId(id), + cached( + "BTC", + 10 * id as i64, + side, + status, + &format!("{}", 7000 + id), + ), + ); + } + + cache.save_to_disk(&path).unwrap(); + let loaded = BinanceOrderCache::load_from_disk(&path).unwrap(); + + assert_eq!(loaded.orders.len(), 6); + for (id, side, status) in rows { + let order = &loaded.orders[&OrderId(id)]; + assert_eq!(order.side, side, "order {id}"); + assert_eq!(order.status, status, "order {id}"); + assert_eq!(order.quantity, 10 * id as i64, "order {id}"); + assert_eq!(order.binance_order_id, format!("{}", 7000 + id)); + } +} + +#[test] +fn test_broker_saves_and_loads_its_cache() { + let dir = tempfile::TempDir::new().unwrap(); + let path = dir.path().join("broker_cache.json"); + + let broker = BinanceBroker::new("api-key", "secret-key", true); + broker.cache_order( + OrderId(42), + Symbol::new("BTC"), + 100, + BrokerSide::Buy, + Some("c-42".to_string()), + ); + broker.update_cached_order_status(OrderId(42), OrderState::PartiallyFilled); + broker.save_cache_to_disk(&path).unwrap(); + assert!(path.exists()); + + let fresh = BinanceBroker::new("api-key", "secret-key", true); + assert!(fresh.get_cached_order(OrderId(42)).is_none()); + fresh.load_cache_from_disk(&path).unwrap(); + + let order = fresh.get_cached_order(OrderId(42)).unwrap(); + assert_eq!(order.symbol, Symbol::new("BTC")); + assert_eq!(order.quantity, 100); + assert_eq!(order.side, BrokerSide::Buy); + assert_eq!(order.status, OrderState::PartiallyFilled); + assert_eq!(order.client_order_id.as_deref(), Some("c-42")); +} diff --git a/broker/tests/binance_rest_fallback.rs b/broker/tests/binance_rest_fallback.rs index 8ee81f8..563c97c 100644 --- a/broker/tests/binance_rest_fallback.rs +++ b/broker/tests/binance_rest_fallback.rs @@ -5,6 +5,7 @@ mod binance_rest_fallback_tests { use std::time::{Duration, SystemTime}; use nanobook::Symbol; + use nanobook_broker::BrokerError; use nanobook_broker::binance::types::{AccountInfo, BalanceInfo, OrderInfo}; use nanobook_broker::binance::{BinanceBroker, ConnectionMode}; use nanobook_broker::types::{BrokerSide, OrderId, OrderState}; @@ -110,4 +111,81 @@ mod binance_rest_fallback_tests { assert_eq!(websocket.connection_mode(), ConnectionMode::WebSocket); assert_eq!(auto.connection_mode(), ConnectionMode::Auto); } + + #[test] + fn test_poll_account_info_polls_when_due_and_skips_when_recent() { + let broker = BinanceBroker::new("api-key", "secret-key", true); + + // No poll recorded yet: a poll is due, and it needs a client. + assert!(matches!( + broker.poll_account_info(), + Err(BrokerError::NotConnected) + )); + + // Polled just now: nothing is due, so no client is needed and the + // stamp stays as it was. + let now = SystemTime::now(); + broker.set_last_account_poll(Some(now)); + broker.poll_account_info().unwrap(); + assert_eq!(broker.last_account_poll(), Some(now)); + } + + #[test] + fn test_poll_open_orders_polls_when_due_and_skips_when_recent() { + let broker = BinanceBroker::new("api-key", "secret-key", true); + + assert!(matches!( + broker.poll_open_orders(), + Err(BrokerError::NotConnected) + )); + + let now = SystemTime::now(); + broker.set_last_orders_poll(Some(now)); + broker.poll_open_orders().unwrap(); + assert_eq!(broker.last_orders_poll(), Some(now)); + } + + #[test] + fn test_open_order_side_and_status_mapping() { + let order = |order_id: u64, symbol: &str, side: &str, status: &str, qty: &str| OrderInfo { + symbol: symbol.to_string(), + order_id, + status: status.to_string(), + side: side.to_string(), + orig_qty: qty.to_string(), + executed_qty: "0".to_string(), + }; + let info = AccountInfo { + balances: Vec::new(), + positions: Vec::new(), + open_orders: vec![ + order(1, "BTCUSDT", "SELL", "NEW", "3"), + order(2, "ETHUSDT", "BUY", "PARTIALLY_FILLED", "5"), + order(3, "SOLUSDT", "BUY", "FILLED", "1"), + order(4, "ADAUSDT", "BUY", "CANCELED", "1"), + order(5, "DOGEUSDT", "BUY", "REJECTED", "1"), + order(6, "XRPUSDT", "BUY", "EXPIRED", "1"), + ], + can_trade: true, + }; + let broker = BinanceBroker::new("api-key", "secret-key", true); + + broker.update_state_from_account_info(&info).unwrap(); + + let expected = [ + (1, "BTC", BrokerSide::Sell, OrderState::Submitted, 3), + (2, "ETH", BrokerSide::Buy, OrderState::PartiallyFilled, 5), + (3, "SOL", BrokerSide::Buy, OrderState::Filled, 1), + (4, "ADA", BrokerSide::Buy, OrderState::Cancelled, 1), + (5, "DOGE", BrokerSide::Buy, OrderState::Rejected, 1), + (6, "XRP", BrokerSide::Buy, OrderState::Cancelled, 1), + ]; + for (id, symbol, side, status, quantity) in expected { + let cached = broker.get_cached_order(OrderId(id)).unwrap(); + assert_eq!(cached.symbol, Symbol::new(symbol), "order {id}"); + assert_eq!(cached.side, side, "order {id}"); + assert_eq!(cached.status, status, "order {id}"); + assert_eq!(cached.quantity, quantity, "order {id}"); + } + } } diff --git a/broker/tests/ibkr_market_order_bounds.rs b/broker/tests/ibkr_market_order_bounds.rs index 8d39c62..c8e7cf4 100644 --- a/broker/tests/ibkr_market_order_bounds.rs +++ b/broker/tests/ibkr_market_order_bounds.rs @@ -106,3 +106,33 @@ fn strict_feature_rejects_all_market_orders() { assert!(matches!(res, Err(BrokerError::MarketOrderRejected))); } + +#[test] +fn stop_order_price_is_the_stop_price_in_dollars() { + let (price, qty) = encode_order( + &mk_order(BrokerSide::Buy, BrokerOrderType::Stop(Price(182_50))), + None, + ) + .unwrap(); + + assert_eq!(price, 182.5); + assert_eq!(qty, 100.0); +} + +#[test] +fn stop_limit_order_price_is_the_limit_price_in_dollars() { + let (price, qty) = encode_order( + &mk_order( + BrokerSide::Sell, + BrokerOrderType::StopLimit { + stop: Price(182_50), + limit: Price(181_00), + }, + ), + None, + ) + .unwrap(); + + assert_eq!(price, 181.0); + assert_eq!(qty, 100.0); +} diff --git a/broker/tests/ibkr_state_query.rs b/broker/tests/ibkr_state_query.rs index 8cc1b52..8b2e4a0 100644 --- a/broker/tests/ibkr_state_query.rs +++ b/broker/tests/ibkr_state_query.rs @@ -2,9 +2,9 @@ use nanobook_broker::Broker; use nanobook_broker::BrokerError; -use nanobook_broker::ibkr::IbkrBroker; use nanobook_broker::ibkr::orders::{broker_order_status_from_ibkr_parts, map_ibkr_order_status}; -use nanobook_broker::types::OrderState; +use nanobook_broker::ibkr::{ConnectionState, IbkrBroker}; +use nanobook_broker::types::{OrderId, OrderState}; #[test] fn test_open_orders_empty_when_not_connected() { @@ -52,3 +52,73 @@ fn test_reconcile_state_requires_connection() { assert!(matches!(result, Err(BrokerError::NotConnected))); } + +#[test] +fn test_ibkr_order_status_without_fills_keeps_the_mapped_status() { + // A resting order has filled 0 and remaining = the full quantity (this is + // what `open_orders()` builds from order data). It must not read as a + // partial fill. + let status = broker_order_status_from_ibkr_parts(7, "Cancelled", 0.0, 100.0, 0.0).unwrap(); + + assert_eq!(status.id.0, 7); + assert_eq!(status.status, OrderState::Cancelled); + assert_eq!(status.filled_quantity, 0); + assert_eq!(status.remaining_quantity, 100); + assert_eq!(status.avg_fill_price_cents, 0); +} + +#[test] +fn test_ibkr_order_status_fully_filled() { + // Nothing remaining: filled > 0 alone does not make a partial fill. + let status = broker_order_status_from_ibkr_parts(7, "Filled", 100.0, 0.0, 185.5).unwrap(); + + assert_eq!(status.id.0, 7); + assert_eq!(status.status, OrderState::Filled); + assert_eq!(status.filled_quantity, 100); + assert_eq!(status.remaining_quantity, 0); + assert_eq!(status.avg_fill_price_cents, 18_550); +} + +#[test] +fn test_connect_without_gateway_fails_and_leaves_no_client() { + // A loopback port that was just released: the TCP connect is refused at + // once (a fixed port could be filtered and hang). + let port = { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.local_addr().unwrap().port() + }; + let mut broker = IbkrBroker::new("127.0.0.1", port, 100); + + let result = broker.connect(); + + match result { + Err(BrokerError::Connection(message)) => { + assert!( + message.starts_with(&format!("failed to connect to 127.0.0.1:{port}")), + "got {message}" + ); + } + other => panic!("expected Connection error, got {other:?}"), + } + assert!(broker.client().is_none()); + assert_eq!(broker.connection_state(), ConnectionState::Disconnected); + assert!(!broker.is_connected()); +} + +#[test] +fn test_reconnect_requires_connection() { + let mut broker = IbkrBroker::new("127.0.0.1", 4002, 100); + + let result = broker.reconnect(); + + assert!(matches!(result, Err(BrokerError::NotConnected))); +} + +#[test] +fn test_cancel_order_requires_connection() { + let broker = IbkrBroker::new("127.0.0.1", 4002, 100); + + let result = broker.cancel_order(OrderId(7)); + + assert!(matches!(result, Err(BrokerError::NotConnected))); +} From a5c64f9f6764c78f2e5a0302819bf8ef23806c8f Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:33:51 +0100 Subject: [PATCH 37/66] fix(broker): IBKR reconcile uses the order's side; Binance websocket follows testnet reconcile_partial_fill compared the absolute position, so a buy against a short (or a sell against a long) counted that position as fills. It now compares the signed position on the order's side; the existing manual-review branch takes the other side. Two regression tests fail on the old code. The websocket endpoint ignored testnet and always used the production stream; testnet now uses wss://stream.testnet.binance.vision/ws (Binance spot testnet docs). Both found while writing tests for mutation survivors. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- CHANGELOG.md | 9 +++++++ broker/src/binance/websocket.rs | 17 +++++++++++-- broker/src/ibkr/orders.rs | 44 +++++++++++++++++++++++++++------ 3 files changed, 61 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3fff703..f5ffa7c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -91,6 +91,15 @@ tests, fuzzing or mutation testing. Codes 1100 to 1102 never reached their check, so `execute_limit_order` did not return `ConnectionLost` with the partial fill. It does now. Found by mutation testing. +- **nanobook-broker: IBKR reconciliation after a disconnect ignored the order's side.** + `reconcile_partial_fill` compared the absolute position size, so a buy order + against a short position (or a sell against a long one) was reported as filled + by the size of that position. It now compares the position on the order's side; + a position on the other side is not counted as a fill. Found while writing tests + for mutation survivors. +- **nanobook-broker: the Binance websocket ignored `testnet`.** It always connected + to the production stream. A testnet session now uses + `wss://stream.testnet.binance.vision/ws`. - The ITCH parser read the Stock Directory (`R`) symbol from the tracking-number and timestamp bytes. `ItchMessage::StockDirectory` now carries the real symbol (ITCH 5.0 offset 11). Found by mutation testing. diff --git a/broker/src/binance/websocket.rs b/broker/src/binance/websocket.rs index bae2928..6ea47c7 100644 --- a/broker/src/binance/websocket.rs +++ b/broker/src/binance/websocket.rs @@ -256,8 +256,12 @@ impl BinanceWebSocket { } fn endpoint(&self) -> &'static str { - let _ = (&self.api_key, &self.secret_key, self.testnet); - "wss://stream.binance.com:9443/ws" + let _ = (&self.api_key, &self.secret_key); + if self.testnet { + "wss://stream.testnet.binance.vision/ws" + } else { + "wss://stream.binance.com:9443/ws" + } } fn parse_frame(message: Message) -> Result, Box> { @@ -391,6 +395,15 @@ mod tests { assert_eq!(ws.endpoint(), "wss://stream.binance.com:9443/ws"); } + #[test] + fn endpoint_follows_testnet() { + // Testnet keys do not work on the production stream, and a testnet + // session must never see production events. + let ws = BinanceWebSocket::new("key", "secret", true); + + assert_eq!(ws.endpoint(), "wss://stream.testnet.binance.vision/ws"); + } + #[tokio::test] async fn subscribe_checks_the_heartbeat_before_the_connection() { let mut ws = BinanceWebSocket::new("key", "secret", true); diff --git a/broker/src/ibkr/orders.rs b/broker/src/ibkr/orders.rs index 1bb1580..cc61967 100644 --- a/broker/src/ibkr/orders.rs +++ b/broker/src/ibkr/orders.rs @@ -828,10 +828,12 @@ pub fn reconcile_partial_fill( BrokerSide::Sell => -current_qty, }; - // Compare current quantity against pre-disconnect filled - if signed_current_qty.abs() > pre_disconnect_filled { + // Compare the position on the order's side against pre-disconnect + // filled. Signed, not absolute: a buy against a short position (or a + // sell against a long one) is not a fill of this order. + if signed_current_qty > pre_disconnect_filled { // Additional shares were filled during disconnect - let reconciled_filled = signed_current_qty.abs(); + let reconciled_filled = signed_current_qty; let remainder = expected_total - reconciled_filled; info!( @@ -847,7 +849,7 @@ pub fn reconcile_partial_fill( commission: 0.0, // Would need to query execution history status: OrderOutcome::PartialFill, }) - } else if signed_current_qty.abs() == pre_disconnect_filled { + } else if signed_current_qty == pre_disconnect_filled { // No additional fills during disconnect info!( "AUDIT: Order {} no additional fills detected during disconnect (filled={})", @@ -870,9 +872,7 @@ pub fn reconcile_partial_fill( // Position decreased - unexpected, manual review required warn!( "AUDIT: Order {} position decreased after disconnect (pre={}, current={}) - manual review required", - order_id, - pre_disconnect_filled, - signed_current_qty.abs() + order_id, pre_disconnect_filled, signed_current_qty ); Ok(OrderResult { @@ -1250,6 +1250,36 @@ mod tests { assert_eq!(order_result.status, OrderOutcome::PartialFill); } + fn position(quantity: i64) -> Vec { + vec![Position { + symbol: nanobook::Symbol::try_new("AAPL").unwrap(), + quantity, + avg_cost_cents: 15000, + market_value_cents: quantity * 15000, + unrealized_pnl_cents: 0, + }] + } + + #[test] + fn test_reconcile_buy_against_a_short_position_is_not_a_fill() { + // A short of 75 is on the other side of a buy order: no shares of this + // order were filled. The old absolute comparison reported 75 filled. + let symbol = nanobook::Symbol::try_new("AAPL").unwrap(); + let result = + reconcile_partial_fill(1, symbol, 0, 100, &position(-75), BrokerSide::Buy).unwrap(); + assert_eq!(result.filled_shares, 0); + assert_eq!(result.status, OrderOutcome::PartialFill); + } + + #[test] + fn test_reconcile_sell_against_a_long_position_is_not_a_fill() { + let symbol = nanobook::Symbol::try_new("AAPL").unwrap(); + let result = + reconcile_partial_fill(1, symbol, 50, 100, &position(75), BrokerSide::Sell).unwrap(); + assert_eq!(result.filled_shares, 50); + assert_eq!(result.status, OrderOutcome::PartialFill); + } + #[test] fn test_connection_lost_error_variant() { // Test that ConnectionLost error variant works correctly From b8bf8d0b65bd38d413177901cfe458331dde55df Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:36:23 +0100 Subject: [PATCH 38/66] refactor(broker): pull pure helpers out of the IBKR client methods Move the bodies of IbkrClient::positions, account_summary, quote and mid_price into private free functions (positions_from_updates, account_from_summaries, quote_from_ticks, mid_cents) that take the already-fetched data. The methods fetch from the gateway and call the helper. No behaviour or public API change; the helpers let tests feed exact inputs without a gateway. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- broker/src/ibkr/client.rs | 306 ++++++++++++++++++++------------------ 1 file changed, 165 insertions(+), 141 deletions(-) diff --git a/broker/src/ibkr/client.rs b/broker/src/ibkr/client.rs index 038665e..08b3143 100644 --- a/broker/src/ibkr/client.rs +++ b/broker/src/ibkr/client.rs @@ -336,39 +336,7 @@ impl IbkrClient { .positions() .map_err(|e| BrokerError::Connection(format!("failed to request positions: {e}")))?; - let mut positions = Vec::new(); - for update in subscription { - match update { - PositionUpdate::Position(pos) => { - let symbol_str = pos.contract.symbol.to_string(); - if let Some(sym) = Symbol::try_new(&symbol_str) { - let qty = pos.position as i64; - let avg_cost_cents = - f64_cents_checked(pos.average_cost, "ibkr position.average_cost")?; - debug!( - "Position: {} qty={} avg_cost={:.2}", - sym, qty, pos.average_cost - ); - positions.push(Position { - symbol: sym, - quantity: qty, - avg_cost_cents, - market_value_cents: qty.abs() * avg_cost_cents, // approximate - unrealized_pnl_cents: 0, // would need live prices for exact value - }); - } else { - warn!("Skipping symbol '{symbol_str}' (> 8 bytes)"); - } - } - PositionUpdate::PositionEnd => break, - } - } - - // Demoted to debug in S7: the position count is a coarse - // signal of account activity and shouldn't appear in - // aggregated info-level logs. - debug!("Fetched {} positions", positions.len()); - Ok(positions) + positions_from_updates(subscription) } /// Fetch all open orders known to TWS/Gateway. @@ -417,55 +385,7 @@ impl IbkrClient { BrokerError::Connection(format!("failed to request account summary: {e}")) })?; - let mut equity = 0.0_f64; - let mut cash = 0.0_f64; - let mut buying_power = 0.0_f64; - - for result in subscription { - match result { - AccountSummaryResult::Summary(s) => { - debug!("Account: {}={} {}", s.tag, s.value, s.currency); - // Each known tag routes to its own destination AND its - // own `field` label for the parse-failure warning, so - // a malformed NetLiquidation vs. BuyingPower surfaces - // distinguishably in logs. - match s.tag.as_str() { - "NetLiquidation" => { - equity = parse_f64_or_warn(&s.value, "ibkr account.NetLiquidation"); - } - "TotalCashValue" => { - cash = parse_f64_or_warn(&s.value, "ibkr account.TotalCashValue"); - } - "BuyingPower" => { - buying_power = parse_f64_or_warn(&s.value, "ibkr account.BuyingPower"); - } - _ => {} - } - } - AccountSummaryResult::End => break, - } - } - - let account = Account { - equity_cents: f64_cents_checked(equity, "ibkr NetLiquidation")?, - cash_cents: f64_cents_checked(cash, "ibkr TotalCashValue")?, - buying_power_cents: f64_cents_checked(buying_power, "ibkr BuyingPower")?, - gross_position_value_cents: f64_cents_checked( - equity - cash, - "ibkr gross_position_value", - )?, - }; - - // Demoted to debug in S7: equity/cash/buying-power are - // financial PII and must not appear in aggregated info-level - // logs. Set `RUST_LOG=debug` locally if you need to see them - // while debugging. - debug!( - "Account: equity=${:.2}, cash=${:.2}, buying_power=${:.2}", - equity, cash, buying_power - ); - - Ok(account) + account_from_summaries(subscription) } /// Fetch a live quote for a symbol. @@ -478,55 +398,7 @@ impl IbkrClient { .subscribe() .map_err(|e| BrokerError::Connection(format!("market data request failed: {e}")))?; - let mut bid = None; - let mut ask = None; - let mut last = None; - - for tick in subscription { - match tick { - TickTypes::Price(price_tick) => match price_tick.tick_type { - TickType::Bid => bid = Some(price_tick.price), - TickType::Ask => ask = Some(price_tick.price), - TickType::Last => last = Some(price_tick.price), - _ => {} - }, - TickTypes::PriceSize(ps) => match ps.price_tick_type { - TickType::Bid => bid = Some(ps.price), - TickType::Ask => ask = Some(ps.price), - TickType::Last => last = Some(ps.price), - _ => {} - }, - TickTypes::SnapshotEnd => break, - _ => {} - } - } - - let bid_cents = bid - .map(|b| f64_cents_checked(b, "ibkr tick.bid")) - .transpose()? - .unwrap_or(0); - let ask_cents = ask - .map(|a| f64_cents_checked(a, "ibkr tick.ask")) - .transpose()? - .unwrap_or(0); - let last_cents = last - .map(|l| f64_cents_checked(l, "ibkr tick.last")) - .transpose()? - .unwrap_or(0); - - // Require at least one valid price - if bid_cents <= 0 && ask_cents <= 0 && last_cents <= 0 { - return Err(BrokerError::Connection("no valid price received".into())); - } - - let quote = Quote { - symbol: *symbol, - bid_cents, - ask_cents, - last_cents, - volume: 0, // snapshot doesn't provide volume - timestamp: std::time::SystemTime::now(), - }; + let quote = quote_from_ticks(symbol, subscription)?; if let Some(best_quote) = best_quote_from_quote("e) { self.cache_best_quote(*symbol, best_quote)?; @@ -538,16 +410,7 @@ impl IbkrClient { /// Fetch bid/ask midpoint price for a symbol, in cents. pub fn mid_price(&self, symbol: &Symbol) -> Result { let q = self.quote(symbol)?; - let mid = match (q.bid_cents, q.ask_cents) { - (b, a) if b > 0 && a > 0 => b + (a - b) / 2, - (b, _) if b > 0 => b, - (_, a) if a > 0 => a, - _ => q.last_cents, - }; - if mid <= 0 { - return Err(BrokerError::Connection("no valid price received".into())); - } - Ok(mid) + mid_cents(&q) } /// Fetch live prices (bid/ask midpoint) for a set of symbols. @@ -561,3 +424,164 @@ impl IbkrClient { Ok(prices) } } + +/// Fold a position stream into broker positions (symbols over 8 bytes are skipped). +fn positions_from_updates( + updates: impl IntoIterator, +) -> Result, BrokerError> { + let mut positions = Vec::new(); + for update in updates { + match update { + PositionUpdate::Position(pos) => { + let symbol_str = pos.contract.symbol.to_string(); + if let Some(sym) = Symbol::try_new(&symbol_str) { + let qty = pos.position as i64; + let avg_cost_cents = + f64_cents_checked(pos.average_cost, "ibkr position.average_cost")?; + debug!( + "Position: {} qty={} avg_cost={:.2}", + sym, qty, pos.average_cost + ); + positions.push(Position { + symbol: sym, + quantity: qty, + avg_cost_cents, + market_value_cents: qty.abs() * avg_cost_cents, // approximate + unrealized_pnl_cents: 0, // would need live prices for exact value + }); + } else { + warn!("Skipping symbol '{symbol_str}' (> 8 bytes)"); + } + } + PositionUpdate::PositionEnd => break, + } + } + + // Demoted to debug in S7: the position count is a coarse + // signal of account activity and shouldn't appear in + // aggregated info-level logs. + debug!("Fetched {} positions", positions.len()); + Ok(positions) +} + +/// Build the account from an account-summary stream. +fn account_from_summaries( + summaries: impl IntoIterator, +) -> Result { + let mut equity = 0.0_f64; + let mut cash = 0.0_f64; + let mut buying_power = 0.0_f64; + + for result in summaries { + match result { + AccountSummaryResult::Summary(s) => { + debug!("Account: {}={} {}", s.tag, s.value, s.currency); + // Each known tag routes to its own destination AND its + // own `field` label for the parse-failure warning, so + // a malformed NetLiquidation vs. BuyingPower surfaces + // distinguishably in logs. + match s.tag.as_str() { + "NetLiquidation" => { + equity = parse_f64_or_warn(&s.value, "ibkr account.NetLiquidation"); + } + "TotalCashValue" => { + cash = parse_f64_or_warn(&s.value, "ibkr account.TotalCashValue"); + } + "BuyingPower" => { + buying_power = parse_f64_or_warn(&s.value, "ibkr account.BuyingPower"); + } + _ => {} + } + } + AccountSummaryResult::End => break, + } + } + + let account = Account { + equity_cents: f64_cents_checked(equity, "ibkr NetLiquidation")?, + cash_cents: f64_cents_checked(cash, "ibkr TotalCashValue")?, + buying_power_cents: f64_cents_checked(buying_power, "ibkr BuyingPower")?, + gross_position_value_cents: f64_cents_checked(equity - cash, "ibkr gross_position_value")?, + }; + + // Demoted to debug in S7: equity/cash/buying-power are + // financial PII and must not appear in aggregated info-level + // logs. Set `RUST_LOG=debug` locally if you need to see them + // while debugging. + debug!( + "Account: equity=${:.2}, cash=${:.2}, buying_power=${:.2}", + equity, cash, buying_power + ); + + Ok(account) +} + +/// Build a quote from a snapshot tick stream. +fn quote_from_ticks( + symbol: &Symbol, + ticks: impl IntoIterator, +) -> Result { + let mut bid = None; + let mut ask = None; + let mut last = None; + + for tick in ticks { + match tick { + TickTypes::Price(price_tick) => match price_tick.tick_type { + TickType::Bid => bid = Some(price_tick.price), + TickType::Ask => ask = Some(price_tick.price), + TickType::Last => last = Some(price_tick.price), + _ => {} + }, + TickTypes::PriceSize(ps) => match ps.price_tick_type { + TickType::Bid => bid = Some(ps.price), + TickType::Ask => ask = Some(ps.price), + TickType::Last => last = Some(ps.price), + _ => {} + }, + TickTypes::SnapshotEnd => break, + _ => {} + } + } + + let bid_cents = bid + .map(|b| f64_cents_checked(b, "ibkr tick.bid")) + .transpose()? + .unwrap_or(0); + let ask_cents = ask + .map(|a| f64_cents_checked(a, "ibkr tick.ask")) + .transpose()? + .unwrap_or(0); + let last_cents = last + .map(|l| f64_cents_checked(l, "ibkr tick.last")) + .transpose()? + .unwrap_or(0); + + // Require at least one valid price + if bid_cents <= 0 && ask_cents <= 0 && last_cents <= 0 { + return Err(BrokerError::Connection("no valid price received".into())); + } + + Ok(Quote { + symbol: *symbol, + bid_cents, + ask_cents, + last_cents, + volume: 0, // snapshot doesn't provide volume + timestamp: std::time::SystemTime::now(), + }) +} + +/// Bid/ask midpoint in cents, falling back to one side, then to the last price. +fn mid_cents(q: &Quote) -> Result { + let mid = match (q.bid_cents, q.ask_cents) { + (b, a) if b > 0 && a > 0 => b + (a - b) / 2, + (b, _) if b > 0 => b, + (_, a) if a > 0 => a, + _ => q.last_cents, + }; + if mid <= 0 { + return Err(BrokerError::Connection("no valid price received".into())); + } + Ok(mid) +} From 2ab684c8b1d38d3a1c94ab988283f64c5fb5cb9a Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:38:09 +0100 Subject: [PATCH 39/66] refactor(broker): pull pure helpers out of IBKR order and reconcile code Move code out of execute_limit_order, cancel_order, reconcile_state and reconnect_with_backoff into private functions that take their inputs as arguments: build_limit_order, run_place_order_events (event stream, elapsed-time and cancel as parameters), cancel_from_responses, cancel_request_error, diff_orders, and reconnect_with_backoff_using (sleep as a parameter; the public method passes thread::sleep). No behaviour or public API change; tests can now feed exact inputs without a gateway or a real 30 s backoff. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- broker/src/ibkr/mod.rs | 94 +++++++++------ broker/src/ibkr/orders.rs | 236 ++++++++++++++++++++++++-------------- 2 files changed, 207 insertions(+), 123 deletions(-) diff --git a/broker/src/ibkr/mod.rs b/broker/src/ibkr/mod.rs index ade2913..a20c5ab 100644 --- a/broker/src/ibkr/mod.rs +++ b/broker/src/ibkr/mod.rs @@ -127,6 +127,14 @@ impl IbkrBroker { /// * `Ok(())` - Successfully reconnected /// * `Err(BrokerError::ReconnectFailed)` - All attempts failed pub fn reconnect_with_backoff(&mut self) -> Result<(), BrokerError> { + self.reconnect_with_backoff_using(&mut thread::sleep) + } + + /// `reconnect_with_backoff` with the sleep injected. + fn reconnect_with_backoff_using( + &mut self, + sleep: &mut dyn FnMut(Duration), + ) -> Result<(), BrokerError> { const MAX_ATTEMPTS: u32 = 5; const INITIAL_DELAY_MS: u64 = 1000; const MAX_DELAY_MS: u64 = 16000; @@ -142,7 +150,7 @@ impl IbkrBroker { // Sleep before attempting reconnect (except for first attempt) if attempt > 1 { - thread::sleep(delay); + sleep(delay); } // Attempt reconnect @@ -172,48 +180,62 @@ impl IbkrBroker { let _positions = self.positions()?; let cached_orders = client.cached_orders()?; - let mut discrepancies = Vec::new(); - for broker_order in &open_orders { - match client.get_cached_order(broker_order.id.0 as i32)? { - Some(cached) => { - let local_status = orders::map_ibkr_order_status(&cached.status); - if local_status != broker_order.status { - discrepancies.push(Discrepancy::OrderStatusMismatch { - order_id: broker_order.id, - local_status: cached.status, - broker_status: broker_order.status, - }); - } - } - None => discrepancies.push(Discrepancy::OrphanOrder { - order_id: broker_order.id, - }), - } - } + let report = diff_orders(&open_orders, cached_orders, |order_id| { + client.get_cached_order(order_id) + })?; - for cached in cached_orders { - if !open_orders - .iter() - .any(|broker_order| broker_order.id.0 == cached.order_id as u64) - { - discrepancies.push(Discrepancy::MissingOrder { - order_id: OrderId(cached.order_id as u64), - }); - } + // Block reconciliation if critical issues found + if report.has_critical_issues { + self.reconciliation_blocked = true; } - let has_critical_issues = !discrepancies.is_empty(); + Ok(report) + } +} - // Block reconciliation if critical issues found - if has_critical_issues { - self.reconciliation_blocked = true; +/// Compare the broker's open orders with the locally cached orders. +/// `lookup` returns the cached order for a broker order id. +fn diff_orders( + open_orders: &[BrokerOrderStatus], + cached_orders: Vec, + lookup: impl Fn(i32) -> Result, BrokerError>, +) -> Result { + let mut discrepancies = Vec::new(); + for broker_order in open_orders { + match lookup(broker_order.id.0 as i32)? { + Some(cached) => { + let local_status = orders::map_ibkr_order_status(&cached.status); + if local_status != broker_order.status { + discrepancies.push(Discrepancy::OrderStatusMismatch { + order_id: broker_order.id, + local_status: cached.status, + broker_status: broker_order.status, + }); + } + } + None => discrepancies.push(Discrepancy::OrphanOrder { + order_id: broker_order.id, + }), } + } - Ok(DiscrepancyReport { - has_critical_issues, - discrepancies, - }) + for cached in cached_orders { + if !open_orders + .iter() + .any(|broker_order| broker_order.id.0 == cached.order_id as u64) + { + discrepancies.push(Discrepancy::MissingOrder { + order_id: OrderId(cached.order_id as u64), + }); + } } + + let has_critical_issues = !discrepancies.is_empty(); + + Ok(DiscrepancyReport { + has_critical_issues, + discrepancies, + }) } impl Broker for IbkrBroker { diff --git a/broker/src/ibkr/orders.rs b/broker/src/ibkr/orders.rs index cc61967..c23ca35 100644 --- a/broker/src/ibkr/orders.rs +++ b/broker/src/ibkr/orders.rs @@ -396,18 +396,8 @@ pub fn execute_limit_order( ) -> Result { let contract = Contract::stock(symbol.as_str()).build(); - let ib_action = match side { - BrokerSide::Buy => IbAction::Buy, - BrokerSide::Sell => IbAction::Sell, - }; - - let limit_price = limit_price_cents as f64 / 100.0; - let quantity = shares as f64; - - let mut ib_order = limit_order(ib_action, quantity, limit_price); - if let Some(cid) = client_order_id { - ib_order.order_ref = cid.as_str().to_string(); - } + let ib_order = build_limit_order(side, shares, limit_price_cents, client_order_id); + let limit_price = ib_order.limit_price.unwrap_or_default(); let order_id = client .next_valid_order_id() @@ -423,15 +413,65 @@ pub fn execute_limit_order( .map_err(|e| BrokerError::Order(format!("failed to place order {order_id}: {e}")))?; let start = Instant::now(); + let PlaceOrderOutcome { + status: final_status, + filled, + avg_price, + commission, + } = run_place_order_events( + subscription, + order_id, + timeout, + || start.elapsed(), + || cancel_order(client, order_id), + dedup_cache, + )?; + + let result = OrderResult { + symbol, + order_id, + filled_shares: filled as i64, + avg_fill_price: avg_price, + commission, + status: final_status, + }; + + info!( + "Order {order_id}: {:?} -- filled {} @ ${:.2}", + final_status, result.filled_shares, avg_price + ); + + Ok(result) +} + +/// What the order-event loop ended with. +struct PlaceOrderOutcome { + status: OrderOutcome, + filled: f64, + avg_price: f64, + commission: f64, +} + +/// Read the order events until the order is final, times out, or the +/// connection is lost. `elapsed` is the time since submission; `cancel` +/// cancels the order when the timeout is reached. +fn run_place_order_events( + events: impl IntoIterator, + order_id: i32, + timeout: Duration, + mut elapsed: impl FnMut() -> Duration, + mut cancel: impl FnMut() -> Result<(), BrokerError>, + dedup_cache: Option<&CallbackDedupCache>, +) -> Result { let mut filled = 0.0_f64; let mut avg_price = 0.0_f64; let mut commission = 0.0_f64; let mut final_status = OrderOutcome::Failed; - for response in subscription { - if start.elapsed() > timeout { + for response in events { + if elapsed() > timeout { warn!("Order {order_id} timed out after {}s", timeout.as_secs()); - match cancel_order(client, order_id) { + match cancel() { Ok(()) => {} Err(BrokerError::CancelReject { order_id: oid, @@ -547,7 +587,7 @@ pub fn execute_limit_order( // Detect silent disconnect: if loop terminated without final status and not timeout // This can happen when the connection drops without an explicit error message - if final_status == OrderOutcome::Failed && start.elapsed() < timeout { + if final_status == OrderOutcome::Failed && elapsed() < timeout { // Subscription terminated early without explicit error - likely silent disconnect warn!( "AUDIT: Subscription terminated early for order {order_id} (filled={}) - likely silent disconnect", @@ -562,21 +602,34 @@ pub fn execute_limit_order( } } - let result = OrderResult { - symbol, - order_id, - filled_shares: filled as i64, - avg_fill_price: avg_price, - commission, + Ok(PlaceOrderOutcome { status: final_status, + filled, + avg_price, + commission, + }) +} + +/// Build the limit order sent by `execute_limit_order`. +fn build_limit_order( + side: BrokerSide, + shares: i64, + limit_price_cents: i64, + client_order_id: Option<&ClientOrderId>, +) -> Order { + let ib_action = match side { + BrokerSide::Buy => IbAction::Buy, + BrokerSide::Sell => IbAction::Sell, }; - info!( - "Order {order_id}: {:?} -- filled {} @ ${:.2}", - final_status, result.filled_shares, avg_price - ); + let limit_price = limit_price_cents as f64 / 100.0; + let quantity = shares as f64; - Ok(result) + let mut ib_order = limit_order(ib_action, quantity, limit_price); + if let Some(cid) = client_order_id { + ib_order.order_ref = cid.as_str().to_string(); + } + ib_order } /// Cancel an order by ID. @@ -615,71 +668,80 @@ pub fn cancel_order(client: &Client, order_id: i32) -> Result<(), BrokerError> { std::time::SystemTime::now() ); match client.cancel_order(order_id, "") { - Ok(subscription) => { - for response in subscription { - match response { - CancelOrder::OrderStatus(s) => { - debug!("Cancel status for {order_id}: {}", s.status); - // Order is already cancelled or filled - cancel is moot - if s.status == "Cancelled" || s.status == "Filled" { - info!( - "AUDIT: Cancel confirmed for order {} (status: {})", - order_id, s.status - ); - return Ok(()); - } - } - CancelOrder::Notice(notice) => { - debug!("Cancel notice for {order_id}: {}", notice.message); - // Parse for explicit cancel rejection - // IBKR error codes indicating rejection: - // - 102: Order cancelled - // - 201: Order rejected - // - 202: Order cancelled - reason - // - 1100: Connectivity between IB and TWS has been lost - // - 460: Error reading request - // We look for messages that indicate the order cannot be cancelled - let msg = notice.message.to_lowercase(); - if msg.contains("cannot cancel") - || msg.contains("already filled") - || msg.contains("order completed") - || msg.contains("no such order") - { - // Audit log: cancel rejection - info!( - "AUDIT: Cancel rejected for order {} - reason: {}", - order_id, notice.message - ); - return Err(BrokerError::CancelReject { - order_id, - reason: notice.message, - }); - } - } + Ok(subscription) => cancel_from_responses(order_id, subscription), + Err(e) => cancel_request_error(order_id, &e), + } +} + +/// Classify the responses to a cancel request. +fn cancel_from_responses( + order_id: i32, + responses: impl IntoIterator, +) -> Result<(), BrokerError> { + for response in responses { + match response { + CancelOrder::OrderStatus(s) => { + debug!("Cancel status for {order_id}: {}", s.status); + // Order is already cancelled or filled - cancel is moot + if s.status == "Cancelled" || s.status == "Filled" { + info!( + "AUDIT: Cancel confirmed for order {} (status: {})", + order_id, s.status + ); + return Ok(()); } } - info!("AUDIT: Cancel request sent for order {}", order_id); - Ok(()) - } - Err(e) => { - warn!("Failed to cancel order {order_id}: {e}"); - // If the error indicates the order is already complete, treat as success - let err_msg = e.to_string().to_lowercase(); - if err_msg.contains("already filled") - || err_msg.contains("order completed") - || err_msg.contains("no such order") - { - info!( - "AUDIT: Cancel moot for order {} (already completed)", - order_id - ); - return Ok(()); + CancelOrder::Notice(notice) => { + debug!("Cancel notice for {order_id}: {}", notice.message); + // Parse for explicit cancel rejection + // IBKR error codes indicating rejection: + // - 102: Order cancelled + // - 201: Order rejected + // - 202: Order cancelled - reason + // - 1100: Connectivity between IB and TWS has been lost + // - 460: Error reading request + // We look for messages that indicate the order cannot be cancelled + let msg = notice.message.to_lowercase(); + if msg.contains("cannot cancel") + || msg.contains("already filled") + || msg.contains("order completed") + || msg.contains("no such order") + { + // Audit log: cancel rejection + info!( + "AUDIT: Cancel rejected for order {} - reason: {}", + order_id, notice.message + ); + return Err(BrokerError::CancelReject { + order_id, + reason: notice.message, + }); + } } - Err(BrokerError::Order(format!( - "failed to cancel order {order_id}: {e}" - ))) } } + info!("AUDIT: Cancel request sent for order {}", order_id); + Ok(()) +} + +/// Classify a failed cancel request: an already-complete order counts as cancelled. +fn cancel_request_error(order_id: i32, e: &dyn std::fmt::Display) -> Result<(), BrokerError> { + warn!("Failed to cancel order {order_id}: {e}"); + // If the error indicates the order is already complete, treat as success + let err_msg = e.to_string().to_lowercase(); + if err_msg.contains("already filled") + || err_msg.contains("order completed") + || err_msg.contains("no such order") + { + info!( + "AUDIT: Cancel moot for order {} (already completed)", + order_id + ); + return Ok(()); + } + Err(BrokerError::Order(format!( + "failed to cancel order {order_id}: {e}" + ))) } /// Reconcile order state when cancel is rejected. From 73de01d06c3f9fb04451981e59375f15326ae5a7 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:40:38 +0100 Subject: [PATCH 40/66] test(broker): pin IBKR account, quote, order-event, cancel and reconcile logic cargo-mutants 0.20.0 showed these survivors were never checked by any test. New tests with exact values, on the helpers split out in the two preceding refactor commits: - account_from_summaries: tag routing and gross = equity - cash (10_000_000 / 4_000_000 / 25_000_000 / 6_000_000 cents). - quote_from_ticks: Price and PriceSize ticks, snapshot end, single-side quotes, no-price error. - positions_from_updates: avg cost, market value, symbols over 8 bytes. - mid_cents: midpoint, one-side and last-price fallbacks, error. - build_limit_order: 18_550 cents -> 185.5, quantity, order ref. - run_place_order_events: fill, partial fill, cancel, commission, timeout (and exactly at the timeout), cancel-reject reconcile, silent disconnect, duplicate-callback cache, notices, connection codes 1100 to 1102 ending the order with ConnectionLost. - cancel_from_responses and cancel_request_error: reject phrases, already-complete orders, other failures. - diff_orders: orphan, missing, status mismatch, clean. - reconnect_with_backoff_using: sleeps 2, 4, 8, 16 s and the last error. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- broker/src/ibkr/client.rs | 195 +++++++++++++++ broker/src/ibkr/mod.rs | 109 ++++++++ broker/src/ibkr/orders.rs | 506 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 810 insertions(+) diff --git a/broker/src/ibkr/client.rs b/broker/src/ibkr/client.rs index 08b3143..0dfc06a 100644 --- a/broker/src/ibkr/client.rs +++ b/broker/src/ibkr/client.rs @@ -585,3 +585,198 @@ fn mid_cents(q: &Quote) -> Result { } Ok(mid) } + +#[cfg(test)] +mod tests { + use super::*; + use ibapi::accounts::{AccountSummary, Position as IbPosition}; + use ibapi::market_data::realtime::{TickPrice, TickPriceSize}; + use std::time::SystemTime; + + fn summary(tag: &str, value: &str) -> AccountSummaryResult { + AccountSummaryResult::Summary(AccountSummary { + tag: tag.to_string(), + value: value.to_string(), + currency: "USD".to_string(), + ..Default::default() + }) + } + + #[test] + fn account_routes_each_tag_and_derives_gross_value() { + let account = account_from_summaries(vec![ + summary("NetLiquidation", "100000.00"), + summary("TotalCashValue", "40000.00"), + summary("BuyingPower", "250000.00"), + summary("AvailableFunds", "1.00"), + AccountSummaryResult::End, + summary("NetLiquidation", "1.00"), + ]) + .unwrap(); + + assert_eq!(account.equity_cents, 10_000_000); + assert_eq!(account.cash_cents, 4_000_000); + assert_eq!(account.buying_power_cents, 25_000_000); + assert_eq!(account.gross_position_value_cents, 6_000_000); + } + + fn aapl() -> Symbol { + Symbol::new("AAPL") + } + + fn price(tick_type: TickType, price: f64) -> TickTypes { + TickTypes::Price(TickPrice { + tick_type, + price, + ..Default::default() + }) + } + + fn price_size(tick_type: TickType, price: f64) -> TickTypes { + TickTypes::PriceSize(TickPriceSize { + price_tick_type: tick_type, + price, + ..Default::default() + }) + } + + fn cents(quote: &Quote) -> (i64, i64, i64) { + (quote.bid_cents, quote.ask_cents, quote.last_cents) + } + + #[test] + fn quote_reads_bid_ask_last_from_price_ticks() { + let quote = quote_from_ticks( + &aapl(), + vec![ + price(TickType::Bid, 184.95), + price(TickType::Ask, 185.05), + price(TickType::Last, 185.00), + TickTypes::SnapshotEnd, + ], + ) + .unwrap(); + + assert_eq!(quote.symbol, aapl()); + assert_eq!(cents("e), (18_495, 18_505, 18_500)); + assert_eq!(quote.volume, 0); + assert!(quote.timestamp <= SystemTime::now()); + } + + #[test] + fn quote_reads_bid_ask_last_from_price_size_ticks() { + let quote = quote_from_ticks( + &aapl(), + vec![ + price_size(TickType::Bid, 184.95), + price_size(TickType::Ask, 185.05), + price_size(TickType::Last, 185.00), + TickTypes::SnapshotEnd, + ], + ) + .unwrap(); + + assert_eq!(cents("e), (18_495, 18_505, 18_500)); + } + + #[test] + fn quote_ignores_ticks_after_the_snapshot_end() { + let result = quote_from_ticks( + &aapl(), + vec![TickTypes::SnapshotEnd, price(TickType::Bid, 99.0)], + ); + + assert!(matches!( + result, + Err(BrokerError::Connection(m)) if m == "no valid price received" + )); + } + + #[test] + fn quote_accepts_a_single_valid_side() { + let bid = quote_from_ticks(&aapl(), vec![price(TickType::Bid, 184.95)]).unwrap(); + assert_eq!(cents(&bid), (18_495, 0, 0)); + + let ask = quote_from_ticks(&aapl(), vec![price(TickType::Ask, 185.05)]).unwrap(); + assert_eq!(cents(&ask), (0, 18_505, 0)); + + let last = quote_from_ticks(&aapl(), vec![price(TickType::Last, 185.0)]).unwrap(); + assert_eq!(cents(&last), (0, 0, 18_500)); + } + + #[test] + fn quote_without_a_positive_price_is_an_error() { + for ticks in [ + vec![TickTypes::SnapshotEnd], + vec![price(TickType::Bid, 0.0)], + vec![price(TickType::Bid, 0.0), price(TickType::Ask, 0.0)], + ] { + let result = quote_from_ticks(&aapl(), ticks); + + assert!(matches!( + result, + Err(BrokerError::Connection(m)) if m == "no valid price received" + )); + } + } + + #[test] + fn positions_convert_cost_and_value_and_skip_long_symbols() { + let held = |symbol: &str, position: f64, average_cost: f64| { + PositionUpdate::Position(IbPosition { + contract: Contract::stock(symbol).build(), + position, + average_cost, + ..Default::default() + }) + }; + + let positions = positions_from_updates(vec![ + held("AAPL", -10.0, 185.0), + held("TOOLONGSYM", 5.0, 1.0), + PositionUpdate::PositionEnd, + held("MSFT", 1.0, 1.0), + ]) + .unwrap(); + + assert_eq!(positions.len(), 1); + let p = &positions[0]; + assert_eq!(p.symbol, aapl()); + assert_eq!(p.quantity, -10); + assert_eq!(p.avg_cost_cents, 18_500); + assert_eq!(p.market_value_cents, 185_000); + assert_eq!(p.unrealized_pnl_cents, 0); + } + + fn quote_of(bid_cents: i64, ask_cents: i64, last_cents: i64) -> Quote { + Quote { + symbol: aapl(), + bid_cents, + ask_cents, + last_cents, + volume: 0, + timestamp: SystemTime::now(), + } + } + + #[test] + fn mid_is_the_midpoint_then_one_side_then_last() { + let mid = |b, a, l| mid_cents("e_of(b, a, l)).unwrap(); + + assert_eq!(mid(18_495, 18_505, 18_400), 18_500); + assert_eq!(mid(100, 103, 50), 101); + assert_eq!(mid(18_495, 0, 18_400), 18_495); + assert_eq!(mid(0, 18_505, 18_400), 18_505); + assert_eq!(mid(0, 0, 18_400), 18_400); + } + + #[test] + fn mid_without_a_positive_price_is_an_error() { + for (b, a, l) in [(0, 0, 0), (0, 0, -5)] { + assert!(matches!( + mid_cents("e_of(b, a, l)), + Err(BrokerError::Connection(m)) if m == "no valid price received" + )); + } + } +} diff --git a/broker/src/ibkr/mod.rs b/broker/src/ibkr/mod.rs index a20c5ab..25aeab0 100644 --- a/broker/src/ibkr/mod.rs +++ b/broker/src/ibkr/mod.rs @@ -332,4 +332,113 @@ mod tests { assert!(!broker.is_connected()); assert!(broker.client().is_none()); } + + fn open(id: u64, status: OrderState) -> BrokerOrderStatus { + BrokerOrderStatus { + id: OrderId(id), + status, + filled_quantity: 0, + remaining_quantity: 0, + avg_fill_price_cents: 0, + } + } + + fn cached(id: i32, status: &str) -> client::CachedOrder { + client::CachedOrder { + order_id: id, + symbol: Symbol::new("AAPL"), + quantity: 100, + side: "Buy".to_string(), + status: status.to_string(), + submitted_at: std::time::Instant::now(), + } + } + + fn diff( + open_orders: &[BrokerOrderStatus], + cached_orders: Vec, + ) -> DiscrepancyReport { + let lookup = cached_orders.clone(); + diff_orders(open_orders, cached_orders, |id| { + Ok(lookup.iter().find(|c| c.order_id == id).cloned()) + }) + .unwrap() + } + + #[test] + fn diff_orders_reports_nothing_when_broker_and_cache_agree() { + let report = diff( + &[open(1, OrderState::Submitted), open(2, OrderState::Filled)], + vec![cached(1, "Submitted"), cached(2, "Filled")], + ); + + assert!(report.discrepancies.is_empty()); + assert!(!report.has_critical_issues); + } + + #[test] + fn diff_orders_reports_a_status_mismatch() { + let report = diff( + &[open(1, OrderState::PartiallyFilled)], + vec![cached(1, "Submitted")], + ); + + assert_eq!( + report.discrepancies, + vec![Discrepancy::OrderStatusMismatch { + order_id: OrderId(1), + local_status: "Submitted".to_string(), + broker_status: OrderState::PartiallyFilled, + }] + ); + assert!(report.has_critical_issues); + } + + #[test] + fn diff_orders_reports_an_uncached_broker_order_as_orphan() { + let report = diff(&[open(9, OrderState::Submitted)], Vec::new()); + + assert_eq!( + report.discrepancies, + vec![Discrepancy::OrphanOrder { + order_id: OrderId(9) + }] + ); + assert!(report.has_critical_issues); + } + + #[test] + fn diff_orders_reports_a_cached_order_absent_from_the_broker_as_missing() { + let report = diff( + &[open(1, OrderState::Submitted)], + vec![cached(1, "Submitted"), cached(3, "Submitted")], + ); + + assert_eq!( + report.discrepancies, + vec![Discrepancy::MissingOrder { + order_id: OrderId(3) + }] + ); + assert!(report.has_critical_issues); + } + + #[test] + fn backoff_sleeps_double_up_to_the_cap_and_the_last_error_is_reported() { + let mut broker = IbkrBroker::new("127.0.0.1", 1, 100); + let mut sleeps = Vec::new(); + + let result = broker.reconnect_with_backoff_using(&mut |d| sleeps.push(d.as_millis())); + + // No sleep before the first attempt; then 2 s, 4 s, 8 s, 16 s. + assert_eq!(sleeps, vec![2_000, 4_000, 8_000, 16_000]); + match result { + Err(BrokerError::ReconnectFailed { attempts, reason }) => { + assert_eq!(attempts, 5); + assert_eq!(reason, "not connected"); + } + other => panic!("expected ReconnectFailed, got {other:?}"), + } + assert_eq!(broker.connection_state(), ConnectionState::Disconnected); + } } diff --git a/broker/src/ibkr/orders.rs b/broker/src/ibkr/orders.rs index c23ca35..bbdadb8 100644 --- a/broker/src/ibkr/orders.rs +++ b/broker/src/ibkr/orders.rs @@ -1355,4 +1355,510 @@ mod tests { assert!(error_string.contains("12345")); assert!(error_string.contains("50")); } + + // ---- build_limit_order --------------------------------------------- + + #[test] + fn limit_order_carries_price_quantity_and_client_order_id() { + let cid = ClientOrderId::new("cid-1").unwrap(); + + let order = build_limit_order(BrokerSide::Buy, 100, 18_550, Some(&cid)); + + assert_eq!(order.order_type, "LMT"); + assert!(matches!(order.action, IbAction::Buy)); + assert_eq!(order.total_quantity, 100.0); + assert_eq!(order.limit_price, Some(185.5)); + assert_eq!(order.order_ref, "cid-1"); + } + + #[test] + fn limit_order_sell_without_client_order_id() { + let order = build_limit_order(BrokerSide::Sell, 7, 100_00, None); + + assert!(matches!(order.action, IbAction::Sell)); + assert_eq!(order.total_quantity, 7.0); + assert_eq!(order.limit_price, Some(100.0)); + assert!(order.order_ref.is_empty()); + } + + // ---- run_place_order_events ---------------------------------------- + + const TIMEOUT: Duration = Duration::from_secs(10); + const ORDER_ID: i32 = 7; + + fn st(status: &str, filled: f64, remaining: f64, avg: f64) -> PlaceOrder { + PlaceOrder::OrderStatus(ibapi::orders::OrderStatus { + order_id: ORDER_ID, + status: status.to_string(), + filled, + remaining, + average_fill_price: avg, + ..Default::default() + }) + } + + fn notice(code: i32, message: &str) -> ibapi::messages::Notice { + ibapi::messages::Notice { + code, + message: message.to_string(), + error_time: None, + } + } + + fn secs(seconds: &[u64]) -> Vec { + seconds.iter().map(|s| Duration::from_secs(*s)).collect() + } + + type Run = (Result<(OrderOutcome, f64, f64, f64), BrokerError>, usize); + + /// Run the event loop. `elapsed` answers successive calls in order and + /// repeats its last value; returns the result and the cancel-call count. + fn run( + events: Vec, + elapsed: &[Duration], + cancel: fn() -> Result<(), BrokerError>, + dedup: Option<&CallbackDedupCache>, + ) -> Run { + let cancels = std::cell::Cell::new(0usize); + let calls = std::cell::Cell::new(0usize); + let result = run_place_order_events( + events, + ORDER_ID, + TIMEOUT, + || { + let i = calls.get().min(elapsed.len() - 1); + calls.set(calls.get() + 1); + elapsed[i] + }, + || { + cancels.set(cancels.get() + 1); + cancel() + }, + dedup, + ) + .map(|o| (o.status, o.filled, o.avg_price, o.commission)); + (result, cancels.get()) + } + + fn cancel_ok() -> Result<(), BrokerError> { + Ok(()) + } + + fn fresh() -> [Duration; 1] { + [Duration::ZERO] + } + + #[test] + fn events_fill_ends_the_order() { + let (result, cancels) = run( + vec![ + st("Submitted", 0.0, 100.0, 0.0), + st("Filled", 100.0, 0.0, 185.5), + ], + &fresh(), + cancel_ok, + None, + ); + + assert_eq!(result.unwrap(), (OrderOutcome::Filled, 100.0, 185.5, 0.0)); + assert_eq!(cancels, 0); + } + + #[test] + fn events_cancel_after_a_partial_fill_is_a_partial_fill() { + let (result, cancels) = run( + vec![ + st("Submitted", 40.0, 60.0, 10.0), + st("Cancelled", 40.0, 60.0, 10.0), + ], + &fresh(), + cancel_ok, + None, + ); + + assert_eq!( + result.unwrap(), + (OrderOutcome::PartialFill, 40.0, 10.0, 0.0) + ); + assert_eq!(cancels, 0); + } + + #[test] + fn events_cancel_with_nothing_filled_is_cancelled() { + let (result, _) = run( + vec![st("Cancelled", 0.0, 100.0, 0.0)], + &fresh(), + cancel_ok, + None, + ); + + assert_eq!(result.unwrap(), (OrderOutcome::Cancelled, 0.0, 0.0, 0.0)); + } + + #[test] + fn events_commission_report_is_returned() { + let (result, _) = run( + vec![ + PlaceOrder::CommissionReport(ibapi::orders::CommissionReport { + commission: 1.25, + ..Default::default() + }), + st("Filled", 100.0, 0.0, 185.5), + ], + &fresh(), + cancel_ok, + None, + ); + + assert_eq!(result.unwrap(), (OrderOutcome::Filled, 100.0, 185.5, 1.25)); + } + + #[test] + fn events_timeout_after_a_partial_fill_cancels_and_reports_partial() { + let (result, cancels) = run( + vec![ + st("Submitted", 30.0, 70.0, 10.0), + st("Submitted", 30.0, 70.0, 10.0), + ], + &secs(&[0, 11]), + cancel_ok, + None, + ); + + assert_eq!( + result.unwrap(), + (OrderOutcome::PartialFill, 30.0, 10.0, 0.0) + ); + assert_eq!(cancels, 1); + } + + #[test] + fn events_timeout_with_nothing_filled_cancels_and_reports_cancelled() { + let (result, cancels) = run( + vec![st("Submitted", 0.0, 100.0, 0.0)], + &secs(&[11]), + cancel_ok, + None, + ); + + assert_eq!(result.unwrap(), (OrderOutcome::Cancelled, 0.0, 0.0, 0.0)); + assert_eq!(cancels, 1); + } + + #[test] + fn events_exactly_at_the_timeout_do_not_cancel() { + let (result, cancels) = run( + vec![ + st("Submitted", 30.0, 70.0, 10.0), + st("Filled", 100.0, 0.0, 12.0), + ], + &secs(&[10]), + cancel_ok, + None, + ); + + assert_eq!(result.unwrap(), (OrderOutcome::Filled, 100.0, 12.0, 0.0)); + assert_eq!(cancels, 0); + } + + #[test] + fn events_timeout_cancel_rejected_because_filled_reports_filled() { + fn rejected() -> Result<(), BrokerError> { + Err(BrokerError::CancelReject { + order_id: ORDER_ID, + reason: "Order already filled".to_string(), + }) + } + let (result, cancels) = run( + vec![st("Submitted", 0.0, 100.0, 0.0)], + &secs(&[11]), + rejected, + None, + ); + + assert_eq!(result.unwrap().0, OrderOutcome::Filled); + assert_eq!(cancels, 1); + } + + #[test] + fn events_timeout_with_uncertain_cancel_reject_or_failure_is_not_filled() { + fn uncertain() -> Result<(), BrokerError> { + Err(BrokerError::CancelReject { + order_id: ORDER_ID, + reason: "Cannot cancel order at this time".to_string(), + }) + } + fn failed() -> Result<(), BrokerError> { + Err(BrokerError::Order( + "failed to cancel order 7: boom".to_string(), + )) + } + let cancellers: [fn() -> Result<(), BrokerError>; 2] = [uncertain, failed]; + for cancel in cancellers { + let (result, cancels) = run( + vec![st("Submitted", 0.0, 100.0, 0.0)], + &secs(&[11]), + cancel, + None, + ); + + assert_eq!(result.unwrap().0, OrderOutcome::Cancelled); + assert_eq!(cancels, 1); + } + } + + #[test] + fn events_end_with_a_fill_is_a_silent_disconnect() { + let (result, _) = run( + vec![st("Submitted", 30.0, 70.0, 10.0)], + &fresh(), + cancel_ok, + None, + ); + + assert!(matches!( + result, + Err(BrokerError::ConnectionLost { + order_id: ORDER_ID, + filled_quantity: 30 + }) + )); + } + + #[test] + fn events_end_with_nothing_filled_is_failed() { + let (result, _) = run(Vec::new(), &fresh(), cancel_ok, None); + + assert_eq!(result.unwrap(), (OrderOutcome::Failed, 0.0, 0.0, 0.0)); + } + + #[test] + fn events_end_at_or_after_the_timeout_is_not_a_disconnect() { + for after in [10, 11] { + let (result, cancels) = run( + vec![st("Submitted", 30.0, 70.0, 10.0)], + &secs(&[0, after]), + cancel_ok, + None, + ); + + assert_eq!( + result.unwrap(), + (OrderOutcome::Failed, 30.0, 10.0, 0.0), + "elapsed {after} s" + ); + assert_eq!(cancels, 0); + } + } + + #[test] + fn events_dedup_records_each_new_callback_and_drops_old_ones() { + let cache = CallbackDedupCache::default(); + let stale_key = OrderCallbackKey { + order_id: 99, + status: "Submitted".to_string(), + filled_quantity: 0, + }; + let stale_time = Instant::now() + .checked_sub(Duration::from_secs(301)) + .expect("monotonic clock older than 301 s"); + cache.lock().unwrap().insert(stale_key.clone(), stale_time); + + let (result, _) = run( + vec![ + st("Submitted", 0.0, 100.0, 0.0), + st("Submitted", 0.0, 100.0, 0.0), + st("Filled", 100.0, 0.0, 185.5), + ], + &fresh(), + cancel_ok, + Some(&cache), + ); + + assert_eq!(result.unwrap().0, OrderOutcome::Filled); + let keys = cache.lock().unwrap(); + assert_eq!(keys.len(), 2); + assert!(!keys.contains_key(&stale_key)); + for (status, filled) in [("Submitted", 0), ("Filled", 100)] { + assert!(keys.contains_key(&OrderCallbackKey { + order_id: ORDER_ID, + status: status.to_string(), + filled_quantity: filled, + })); + } + } + + #[test] + fn events_duplicate_callback_is_skipped() { + let cache = CallbackDedupCache::default(); + // The repeated callback carries a different average price: skipping + // it keeps 10.0; processing it would give 99.0. + let (result, _) = run( + vec![ + st("Submitted", 30.0, 70.0, 10.0), + st("Submitted", 30.0, 70.0, 99.0), + st("Submitted", 31.0, 69.0, 5.0), + ], + &secs(&[0, 0, 11]), + cancel_ok, + Some(&cache), + ); + + assert_eq!( + result.unwrap(), + (OrderOutcome::PartialFill, 30.0, 10.0, 0.0) + ); + } + + #[test] + fn events_ordinary_notices_do_not_abort_the_order() { + for code in [2104, 201, 1099, 1103, -1] { + let (result, _) = run( + vec![ + PlaceOrder::Message(notice(code, "notice")), + st("Filled", 100.0, 0.0, 185.5), + ], + &fresh(), + cancel_ok, + None, + ); + + assert_eq!( + result.unwrap().0, + OrderOutcome::Filled, + "code {code} must not abort" + ); + } + } + + #[test] + fn events_connection_codes_end_the_order_with_connection_lost() { + for code in [1100, 1101, 1102] { + let (result, _) = run( + vec![ + st("Submitted", 30.0, 70.0, 10.0), + PlaceOrder::Message(notice(code, "connectivity")), + st("Filled", 100.0, 0.0, 185.5), + ], + &fresh(), + cancel_ok, + None, + ); + + assert!( + matches!( + result, + Err(BrokerError::ConnectionLost { + order_id: ORDER_ID, + filled_quantity: 30 + }) + ), + "code {code}" + ); + } + + let (result, _) = run( + vec![PlaceOrder::Message(notice(1100, "lost"))], + &fresh(), + cancel_ok, + None, + ); + assert!(matches!( + result, + Err(BrokerError::ConnectionLost { + order_id: ORDER_ID, + filled_quantity: 0 + }) + )); + } + + // ---- cancel_from_responses / cancel_request_error ------------------ + + fn cancel_status(status: &str) -> CancelOrder { + CancelOrder::OrderStatus(ibapi::orders::OrderStatus { + status: status.to_string(), + ..Default::default() + }) + } + + fn cancel_notice(message: &str) -> CancelOrder { + CancelOrder::Notice(notice(202, message)) + } + + #[test] + fn cancel_notice_after_pending_cancel_is_a_reject() { + let result = cancel_from_responses( + ORDER_ID, + vec![ + cancel_status("PendingCancel"), + cancel_notice("Order already filled"), + ], + ); + + match result { + Err(BrokerError::CancelReject { order_id, reason }) => { + assert_eq!(order_id, ORDER_ID); + assert_eq!(reason, "Order already filled"); + } + other => panic!("expected CancelReject, got {other:?}"), + } + } + + #[test] + fn cancel_confirmed_status_ends_the_cancel_before_later_notices() { + for status in ["Cancelled", "Filled"] { + let result = cancel_from_responses( + ORDER_ID, + vec![cancel_status(status), cancel_notice("Cannot cancel")], + ); + + assert!(result.is_ok(), "status {status}"); + } + } + + #[test] + fn cancel_each_rejection_phrase_is_a_reject() { + for phrase in [ + "Cannot cancel order", + "ORDER ALREADY FILLED", + "order completed", + "No such order", + ] { + let result = cancel_from_responses(ORDER_ID, vec![cancel_notice(phrase)]); + + assert!( + matches!(result, Err(BrokerError::CancelReject { .. })), + "{phrase}" + ); + } + } + + #[test] + fn cancel_other_notices_and_empty_responses_are_ok() { + assert!( + cancel_from_responses(ORDER_ID, vec![cancel_notice("cancel acknowledged")]).is_ok() + ); + assert!(cancel_from_responses(ORDER_ID, Vec::new()).is_ok()); + } + + #[test] + fn cancel_request_error_treats_a_complete_order_as_cancelled() { + for message in [ + "Order already filled", + "ORDER COMPLETED", + "no such order 42", + ] { + assert!(cancel_request_error(42, &message).is_ok(), "{message}"); + } + } + + #[test] + fn cancel_request_error_reports_other_failures() { + match cancel_request_error(42, &"connection reset") { + Err(BrokerError::Order(message)) => { + assert_eq!(message, "failed to cancel order 42: connection reset"); + } + other => panic!("expected Order error, got {other:?}"), + } + } } From c1057d589aa90c15b5bd1a0748f74ddf2f6b71ab Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:59:58 +0100 Subject: [PATCH 41/66] test(risk): pin worst-weight tie, weight allocation split and Display output check_batch names the first of equal largest target weights and splits long, short and cash weights from the signed targets; neither detail string was asserted. RiskError and RiskReport Display output is pinned too, so a formatter that writes nothing now fails. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- risk/src/checks.rs | 31 +++++++++++++++++++++++++++++++ risk/src/error.rs | 14 ++++++++++++++ risk/src/report.rs | 30 ++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+) diff --git a/risk/src/checks.rs b/risk/src/checks.rs index 2a02db2..a143471 100644 --- a/risk/src/checks.rs +++ b/risk/src/checks.rs @@ -554,4 +554,35 @@ mod tests { let report = check_batch(&config, &over, &account(100_000_000), &[], &[]); assert_eq!(named(&report, "Max trade size").status, RiskStatus::Warn); } + + // ---- Detail strings: worst-weight symbol and weight allocation ---- + + #[test] + fn max_position_detail_names_the_first_of_tied_weights() { + let tied = vec![(aapl(), 0.20), (spy(), 0.20)]; + let report = check_batch(&default_config(), &[], &account(10_000_000), &[], &tied); + assert_eq!( + named(&report, "Max position").detail, + "20.0% (AAPL) <= 40.0% limit" + ); + + // A zero weight is not larger than the starting value 0.0, so the + // placeholder symbol stays. + let zero = vec![(aapl(), 0.0)]; + let report = check_batch(&default_config(), &[], &account(10_000_000), &[], &zero); + assert_eq!( + named(&report, "Max position").detail, + "0.0% (?) <= 40.0% limit" + ); + } + + #[test] + fn weight_allocation_splits_long_short_and_cash() { + let msft = Symbol::new("MSFT"); + let targets = vec![(aapl(), 0.50), (spy(), -0.20), (msft, 0.0)]; + let report = check_batch(&default_config(), &[], &account(10_000_000), &[], &targets); + let check = named(&report, "Weight allocation"); + assert_eq!(check.status, RiskStatus::Pass); + assert_eq!(check.detail, "50.0% long, 20.0% short, 50.0% cash"); + } } diff --git a/risk/src/error.rs b/risk/src/error.rs index d1baf2c..f186bd8 100644 --- a/risk/src/error.rs +++ b/risk/src/error.rs @@ -29,3 +29,17 @@ impl fmt::Display for RiskError { } impl std::error::Error for RiskError {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn invalid_config_displays_its_message() { + let error = RiskError::InvalidConfig("max_leverage must be positive".to_string()); + assert_eq!( + error.to_string(), + "invalid RiskConfig: max_leverage must be positive" + ); + } +} diff --git a/risk/src/report.rs b/risk/src/report.rs index ac13848..16e0e74 100644 --- a/risk/src/report.rs +++ b/risk/src/report.rs @@ -86,4 +86,34 @@ mod tests { assert!(!report(&[RiskStatus::Pass, RiskStatus::Warn]).has_failures()); assert!(report(&[RiskStatus::Pass, RiskStatus::Fail]).has_failures()); } + + #[test] + fn status_displays_as_upper_case_word() { + assert_eq!(RiskStatus::Pass.to_string(), "PASS"); + assert_eq!(RiskStatus::Warn.to_string(), "WARN"); + assert_eq!(RiskStatus::Fail.to_string(), "FAIL"); + } + + #[test] + fn report_displays_one_line_per_check() { + let report = RiskReport { + checks: vec![ + RiskCheck { + name: "Leverage", + status: RiskStatus::Pass, + detail: "1.00x <= 1.50x limit".to_string(), + }, + RiskCheck { + name: "Max trade size", + status: RiskStatus::Warn, + detail: "AAPL: $2000 > $1000 max_trade_usd".to_string(), + }, + ], + }; + assert_eq!( + report.to_string(), + "RISK CHECKS:\n [PASS] Leverage: 1.00x <= 1.50x limit\n [WARN] Max trade size: AAPL: $2000 > $1000 max_trade_usd\n" + ); + assert_eq!(RiskReport { checks: vec![] }.to_string(), "RISK CHECKS:\n"); + } } From 895d13c6f9711d4685a8038879af61d743d20e4c Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:01:45 +0100 Subject: [PATCH 42/66] test(portfolio): pin sizing guards, median shortcut, lower-tail limit and UnpricedHolding text buy_cash_required, largest_affordable_buy_qty, truncate_qty_to_max_value and size_qty return zero for non-positive quantity, price, step or cap; each guard had no direct test. norm_ppf returns exactly 0.0 next to the median and uses the central formula at p = 0.02425. UnpricedHolding Display names symbol, period and price map. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- src/backtest_bridge.rs | 21 ++++++++++++++ src/portfolio/metrics.rs | 25 ++++++++++++++++ src/portfolio/mod.rs | 61 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 107 insertions(+) diff --git a/src/backtest_bridge.rs b/src/backtest_bridge.rs index 3b3b8dc..b9726b3 100644 --- a/src/backtest_bridge.rs +++ b/src/backtest_bridge.rs @@ -2881,4 +2881,25 @@ mod tests { assert!(check(0, 0, 0, 0), "all zero"); assert!(check(10, 10, 10, 10), "all positive"); } + + #[test] + fn unpriced_holding_display_names_symbol_period_and_price_map() { + let at_fill = UnpricedHolding { + period_index: 3, + symbol: aapl(), + at_fill: true, + }; + assert_eq!( + at_fill.to_string(), + "unpriced holding AAPL at period 3 (fill)" + ); + let at_close = UnpricedHolding { + at_fill: false, + ..at_fill + }; + assert_eq!( + at_close.to_string(), + "unpriced holding AAPL at period 3 (close)" + ); + } } diff --git a/src/portfolio/metrics.rs b/src/portfolio/metrics.rs index 54b6b4e..b8cb223 100644 --- a/src/portfolio/metrics.rs +++ b/src/portfolio/metrics.rs @@ -1020,6 +1020,31 @@ mod tests { assert_eq!(norm_ppf(1.0), f64::INFINITY); } + /// Inside 1e-15 of the median the function returns exactly 0.0; the + /// central formula would give about 2.8e-16 at the next float above 0.5. + #[test] + fn norm_ppf_is_exactly_zero_next_to_the_median() { + let above = f64::from_bits(0.5_f64.to_bits() + 1); // 0.5 + 2^-53 + let below = f64::from_bits(0.5_f64.to_bits() - 1); // 0.5 - 2^-54 + assert_eq!(norm_ppf(0.5), 0.0); + assert_eq!(norm_ppf(above), 0.0); + assert_eq!(norm_ppf(below), 0.0); + } + + /// p = 0.02425 is not below the lower-tail limit, so the central rational + /// approximation applies. Reference: the central formula with Acklam's + /// coefficients evaluated in Python (-1.9729610490848712); the lower-tail + /// formula gives -1.972961053530962 there, 4.4e-9 away. + #[test] + fn norm_ppf_uses_the_central_formula_at_the_lower_limit() { + assert_close( + norm_ppf(0.02425), + -1.972_961_049_084_871_2, + 1e-12, + "norm_ppf(0.02425)", + ); + } + /// A2-G7: parametric CVaR sigma (sample variance) and strict threshold. #[test] fn cvar_parametric_tail_selection() { diff --git a/src/portfolio/mod.rs b/src/portfolio/mod.rs index 9ada9a0..fe2bec6 100644 --- a/src/portfolio/mod.rs +++ b/src/portfolio/mod.rs @@ -2667,6 +2667,67 @@ mod tests { assert_eq!(portfolio.last_rebalance_order_count(), 0); } + // --- degenerate-input guards of the private sizing helpers --- + + #[test] + fn buy_cash_required_is_zero_for_non_positive_quantity_or_price() { + // A zero notional would still be charged the 7-cent minimum commission. + let cost = CostModel { + commission_bps: 0.0, + slippage_bps: 0.0, + min_commission: 7, + }; + assert_eq!(buy_cash_required(0, 100, &cost), 0); + assert_eq!(buy_cash_required(-5, 100, &cost), 0); + assert_eq!(buy_cash_required(Shares::SCALE, 0, &cost), 0); + assert_eq!(buy_cash_required(Shares::SCALE, -100, &cost), 0); + // One share at 100 cents plus the minimum commission. + assert_eq!(buy_cash_required(Shares::SCALE, 100, &cost), 107); + } + + #[test] + fn largest_affordable_buy_qty_is_zero_for_non_positive_step_or_price() { + let cost = CostModel::zero(); + let affordable = + |step, price| largest_affordable_buy_qty(5_000_000, 1_000_000, step, price, &cost); + assert_eq!(affordable(0, 100), Shares::ZERO); + assert_eq!(affordable(-1, 100), Shares::ZERO); + assert_eq!(affordable(Shares::SCALE, 0), Shares::ZERO); + assert_eq!(affordable(Shares::SCALE, -100), Shares::ZERO); + // 5 shares at 100 cents cost 500 and fit in 1_000_000 cents of cash. + assert_eq!(affordable(Shares::SCALE, 100), Shares::from_whole(5)); + } + + #[test] + fn truncate_qty_to_max_value_is_zero_for_degenerate_inputs() { + let qty = Shares::from_whole(10); + let truncate = + |price, step, max_value| truncate_qty_to_max_value(qty, price, step, max_value); + assert_eq!(truncate(0, Shares::SCALE, 500), Shares::ZERO); + assert_eq!(truncate(100, 0, 500), Shares::ZERO); + assert_eq!(truncate(100, -1, 500), Shares::ZERO); + assert_eq!(truncate(100, Shares::SCALE, 0), Shares::ZERO); + assert_eq!(truncate(100, Shares::SCALE, -500), Shares::ZERO); + assert_eq!(truncate(100, Shares::SCALE, 500), Shares::from_whole(5)); + } + + #[test] + fn size_qty_is_zero_for_degenerate_inputs() { + assert_eq!(size_qty(0, 100, Shares::SCALE), Shares::ZERO); + assert_eq!(size_qty(10_000, 0, Shares::SCALE), Shares::ZERO); + assert_eq!(size_qty(10_000, -100, Shares::SCALE), Shares::ZERO); + assert_eq!(size_qty(10_000, 100, 0), Shares::ZERO); + assert_eq!(size_qty(10_000, 100, -1), Shares::ZERO); + assert_eq!( + size_qty(10_000, 100, Shares::SCALE), + Shares::from_whole(100) + ); + assert_eq!( + size_qty(-10_000, 100, Shares::SCALE), + Shares::from_whole(-100) + ); + } + // --- truncate_qty_to_max_value, sells --- #[test] From 2b872eafdcdf4d054b12dc7d68dd94296993b503 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:03:15 +0100 Subject: [PATCH 43/66] test(broker): pin mock open-order rows and websocket flag, buffer, counter and heartbeat limit MockBroker::set_open_order_statuses and BinanceWebSocket::is_connected, events and reconnect_attempts were only read at their defaults. The heartbeat test runs on a paused tokio clock so elapsed time equals the interval exactly; tokio gains the test-util feature as a dev-dependency. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- broker/Cargo.toml | 2 +- broker/src/binance/websocket.rs | 40 +++++++++++++++++++++++++++++++++ broker/src/mock.rs | 24 ++++++++++++++++++++ 3 files changed, 65 insertions(+), 1 deletion(-) diff --git a/broker/Cargo.toml b/broker/Cargo.toml index 8768033..99bf8c6 100644 --- a/broker/Cargo.toml +++ b/broker/Cargo.toml @@ -51,7 +51,7 @@ futures-util = { version = "0.3", optional = true } [dev-dependencies] tempfile = "3" -tokio = { version = "1.0", features = ["full"] } +tokio = { version = "1.0", features = ["full", "test-util"] } serde_json = "1" [[test]] diff --git a/broker/src/binance/websocket.rs b/broker/src/binance/websocket.rs index 6ea47c7..476e43e 100644 --- a/broker/src/binance/websocket.rs +++ b/broker/src/binance/websocket.rs @@ -404,6 +404,46 @@ mod tests { assert_eq!(ws.endpoint(), "wss://stream.testnet.binance.vision/ws"); } + #[test] + fn is_connected_follows_the_connected_flag() { + let ws = BinanceWebSocket::new("key", "secret", true); + assert!(!ws.is_connected()); + + ws.connected.store(true, Ordering::SeqCst); + assert!(ws.is_connected()); + } + + #[test] + fn events_returns_the_buffered_events() { + let mut ws = BinanceWebSocket::new("key", "secret", true); + assert!(ws.events().is_empty()); + + ws.events.push(execution_report_event()); + assert_eq!(ws.events(), &[execution_report_event()]); + } + + #[test] + fn reconnect_attempts_reports_the_counter() { + let mut ws = BinanceWebSocket::new("key", "secret", true); + ws.reconnect_attempts = 3; + + assert_eq!(ws.reconnect_attempts(), 3); + } + + #[tokio::test(start_paused = true)] + async fn heartbeat_times_out_when_the_interval_has_elapsed_exactly() { + let mut ws = BinanceWebSocket::new("key", "secret", true); + ws.set_heartbeat_interval(Duration::from_secs(10)); + ws.update_heartbeat(); + + tokio::time::advance(Duration::from_millis(9_999)).await; + assert!(ws.check_heartbeat()); + + // Elapsed time equal to the interval is a timeout. + tokio::time::advance(Duration::from_millis(1)).await; + assert!(!ws.check_heartbeat()); + } + #[tokio::test] async fn subscribe_checks_the_heartbeat_before_the_connection() { let mut ws = BinanceWebSocket::new("key", "secret", true); diff --git a/broker/src/mock.rs b/broker/src/mock.rs index 0449b53..950547d 100644 --- a/broker/src/mock.rs +++ b/broker/src/mock.rs @@ -495,4 +495,28 @@ mod tests { let ids: Vec = broker.open_orders().unwrap().iter().map(|o| o.id).collect(); assert_eq!(ids, vec![OrderId(2)]); } + + #[test] + fn set_open_order_statuses_replaces_the_rows_open_orders_returns() { + let mut broker = MockBroker::builder().build(); + broker.connect().unwrap(); + broker.submit_order(&market_order()).unwrap(); + + // 25 of 80 shares filled; FillMode alone would report 100/0 rows. + broker.set_open_order_statuses(vec![BrokerOrderStatus { + id: OrderId(7), + status: OrderState::PartiallyFilled, + filled_quantity: 25, + remaining_quantity: 55, + avg_fill_price_cents: 12_345, + }]); + + let open = broker.open_orders().unwrap(); + assert_eq!(open.len(), 1); + assert_eq!(open[0].id, OrderId(7)); + assert_eq!(open[0].status, OrderState::PartiallyFilled); + assert_eq!(open[0].filled_quantity, 25); + assert_eq!(open[0].remaining_quantity, 55); + assert_eq!(open[0].avg_fill_price_cents, 12_345); + } } From 98e17e70387061fd17a470ce67a93e6f9bdb0c3a Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:05:41 +0100 Subject: [PATCH 44/66] refactor(rebalancer): pull the lock-error classification out of PidFileGuard::create Same behaviour: a held lock gives Error::Aborted, any other lock failure Error::Audit. The mapping needs a private function so a test can feed it errors that flock never returns on this platform. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- rebalancer/src/pid_file.rs | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/rebalancer/src/pid_file.rs b/rebalancer/src/pid_file.rs index af00bc8..00367fd 100644 --- a/rebalancer/src/pid_file.rs +++ b/rebalancer/src/pid_file.rs @@ -109,19 +109,8 @@ impl PidFileGuard { .write(true) .open(lock_path(&path)) .map_err(Error::Audit)?; - match lock.try_lock_exclusive() { - Ok(()) => {} - // Unix reports a held lock as WouldBlock; Windows as ERROR_LOCK_VIOLATION (33). - Err(error) - if error.kind() == std::io::ErrorKind::WouldBlock - || error.raw_os_error() == fs2::lock_contended_error().raw_os_error() => - { - return Err(Error::Aborted(format!( - "PID file {} is in use by another rebalancer", - path.display() - ))); - } - Err(error) => return Err(Error::Audit(error)), + if let Err(error) = lock.try_lock_exclusive() { + return Err(lock_error(error, &path)); } write_pid_file(&path)?; Ok(Self { @@ -131,6 +120,22 @@ impl PidFileGuard { } } +/// The error `PidFileGuard::create` returns when locking `.lock` fails: +/// a held lock is `Aborted`, any other failure is `Audit`. +fn lock_error(error: std::io::Error, path: &Path) -> Error { + // Unix reports a held lock as WouldBlock; Windows as ERROR_LOCK_VIOLATION (33). + if error.kind() == std::io::ErrorKind::WouldBlock + || error.raw_os_error() == fs2::lock_contended_error().raw_os_error() + { + Error::Aborted(format!( + "PID file {} is in use by another rebalancer", + path.display() + )) + } else { + Error::Audit(error) + } +} + impl Drop for PidFileGuard { fn drop(&mut self) { if self.lock.is_none() { From 44ca3ab71f6a077026f89ec904f8a6e7b024927b Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:09:57 +0100 Subject: [PATCH 45/66] test(rebalancer): pin PID lock errors, guard-drop warning and reconciliation matching lock_error maps a held lock to Aborted and any other failure to Audit. Dropping PidFileGuard warns only when the PID file cannot be removed, not when it is already gone. An open order with nothing remaining does not match an intent, and the reconciliation summary counts intents found at the broker. LogCapture now installs a global subscriber that enables every callsite once; without it a callsite first hit by an uncaptured test was cached as disabled and the existing summary test failed about half of the parallel runs. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- rebalancer/src/pid_file.rs | 29 ++++++++++++ rebalancer/tests/common/mod.rs | 13 ++++++ rebalancer/tests/mutation_pid_file.rs | 40 ++++++++++++++++ rebalancer/tests/mutation_recovery.rs | 67 +++++++++++++++++++++++++++ 4 files changed, 149 insertions(+) create mode 100644 rebalancer/tests/mutation_pid_file.rs diff --git a/rebalancer/src/pid_file.rs b/rebalancer/src/pid_file.rs index 00367fd..93fb9f9 100644 --- a/rebalancer/src/pid_file.rs +++ b/rebalancer/src/pid_file.rs @@ -260,4 +260,33 @@ mod tests { drop(guard); assert!(!pid_file_exists(&path)); } + + #[test] + fn lock_error_maps_a_held_lock_to_aborted_and_any_other_failure_to_audit() { + use std::io::{Error as IoError, ErrorKind}; + + let path = Path::new("run/rebalancer.pid"); + + // A held lock: the kind alone, and the platform's own contention error. + for held in [ + IoError::from(ErrorKind::WouldBlock), + fs2::lock_contended_error(), + ] { + match lock_error(held, path) { + Error::Aborted(message) => assert_eq!( + message, + "PID file run/rebalancer.pid is in use by another rebalancer" + ), + other => panic!("expected Aborted, got {other:?}"), + } + } + + // Any other failure keeps its io error. + for kind in [ErrorKind::PermissionDenied, ErrorKind::Other] { + match lock_error(IoError::from(kind), path) { + Error::Audit(error) => assert_eq!(error.kind(), kind), + other => panic!("expected Audit({kind:?}), got {other:?}"), + } + } + } } diff --git a/rebalancer/tests/common/mod.rs b/rebalancer/tests/common/mod.rs index a91668c..cdb9eaf 100644 --- a/rebalancer/tests/common/mod.rs +++ b/rebalancer/tests/common/mod.rs @@ -37,6 +37,19 @@ impl<'a> MakeWriter<'a> for LogCapture { impl LogCapture { /// Run `f` with a subscriber that records every event at any level. pub fn run(&self, f: impl FnOnce() -> T) -> T { + // Enable every callsite for good. A callsite first reached by a test + // without a capture, while no subscriber exists, is cached as + // disabled, and a capturing test running at the same time then misses + // its events. + static ENABLE_ALL_CALLSITES: std::sync::Once = std::sync::Once::new(); + ENABLE_ALL_CALLSITES.call_once(|| { + let _ = tracing::subscriber::set_global_default( + tracing_subscriber::fmt() + .with_max_level(tracing::Level::TRACE) + .with_writer(io::sink) + .finish(), + ); + }); let subscriber = tracing_subscriber::fmt() .with_ansi(false) .with_max_level(tracing::Level::TRACE) diff --git a/rebalancer/tests/mutation_pid_file.rs b/rebalancer/tests/mutation_pid_file.rs new file mode 100644 index 0000000..f7ea63a --- /dev/null +++ b/rebalancer/tests/mutation_pid_file.rs @@ -0,0 +1,40 @@ +//! Mutation-gap tests for `PidFileGuard`: dropping the guard warns when the +//! PID file cannot be removed, and stays quiet when it is already gone. + +mod common; + +use common::LogCapture; +use nanobook_rebalancer::pid_file::PidFileGuard; + +const WARNING: &str = "failed to remove PID file"; + +#[test] +fn drop_is_quiet_when_the_pid_file_is_already_gone() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("rebalancer.pid"); + let guard = PidFileGuard::create(path.clone()).unwrap(); + std::fs::remove_file(&path).unwrap(); + + let capture = LogCapture::default(); + capture.run(|| drop(guard)); + + let text = capture.text(); + assert!(!text.contains(WARNING), "log was: {text}"); +} + +#[test] +fn drop_warns_when_the_pid_file_cannot_be_removed() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("rebalancer.pid"); + let guard = PidFileGuard::create(path.clone()).unwrap(); + // A directory in place of the file: removing it fails, and not with "not found". + std::fs::remove_file(&path).unwrap(); + std::fs::create_dir(&path).unwrap(); + + let capture = LogCapture::default(); + capture.run(|| drop(guard)); + + let text = capture.text(); + assert!(text.contains(WARNING), "log was: {text}"); + assert!(path.is_dir()); +} diff --git a/rebalancer/tests/mutation_recovery.rs b/rebalancer/tests/mutation_recovery.rs index 4560f24..a00eb70 100644 --- a/rebalancer/tests/mutation_recovery.rs +++ b/rebalancer/tests/mutation_recovery.rs @@ -168,6 +168,73 @@ fn reconciliation_summary_counts_intents_missing_at_the_broker() { ); } +#[test] +fn reconciliation_summary_counts_intents_found_at_the_broker() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + write_two_incomplete_intents(&path, dir.path(), 50, 25); + + let mut broker = MockBroker::builder().build(); + broker.connect().unwrap(); + broker.set_open_order_statuses(vec![open_status(7, 50), open_status(8, 25)]); + + let (state, _) = reconstruct_state(&path).unwrap(); + let capture = LogCapture::default(); + capture + .run(|| reconcile_incomplete_intents(&broker, &state, &path)) + .unwrap(); + + let text = capture.text(); + assert!( + text.contains("Broker reconciliation complete: 2 reconciled, 0 failed"), + "log was: {text}" + ); +} + +#[test] +fn open_order_with_nothing_remaining_does_not_match_an_intent() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + write_two_incomplete_intents(&path, dir.path(), 50, 25); + + let mut broker = MockBroker::builder().build(); + broker.connect().unwrap(); + // Order 7 was 50 shares, 20 filled and 30 still open: it is the AAPL intent. + // Order 8 is a finished 25-share order: its filled shares equal the MSFT + // intent, but nothing remains open, so it is no match. + broker.set_open_order_statuses(vec![ + nanobook_broker::types::BrokerOrderStatus { + filled_quantity: 20, + ..open_status(7, 30) + }, + nanobook_broker::types::BrokerOrderStatus { + status: nanobook_broker::types::OrderState::Filled, + filled_quantity: 25, + ..open_status(8, 0) + }, + ]); + + let (state, _) = reconstruct_state(&path).unwrap(); + reconcile_incomplete_intents(&broker, &state, &path).unwrap(); + + let events = parse_audit_events(&path).unwrap(); + assert_eq!(events.len(), 5); + assert_eq!(events[3].event, "order_submitted"); + assert_eq!( + events[3].data.get("symbol").and_then(|v| v.as_str()), + Some("AAPL") + ); + assert_eq!( + events[3].data.get("ibkr_id").and_then(|v| v.as_u64()), + Some(7) + ); + assert_eq!(events[4].event, "order_failed"); + assert_eq!( + events[4].data.get("symbol").and_then(|v| v.as_str()), + Some("MSFT") + ); +} + #[test] fn cancel_result_with_the_intent_sequence_completes_the_cancel() { let state_with = |intent: u64, result: Option| { From dfdde48497c03fc9f022485f9ed70b2914756cba Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:14:42 +0100 Subject: [PATCH 46/66] fix(broker): Binance websocket reconnect stops after its attempt limit connect() reset reconnect_attempts before trying, so every failed attempt inside reconnect_with_backoff restarted the count and the loop never ended. Reset only after a successful connect. The regression test points the client at a closed local port (test-only endpoint override) and fails on the old code after 30 s; it passes in 3 s. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- CHANGELOG.md | 6 +++++ broker/src/binance/websocket.rs | 44 ++++++++++++++++++++++++++++++--- 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f5ffa7c..04d1736 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -100,6 +100,12 @@ tests, fuzzing or mutation testing. - **nanobook-broker: the Binance websocket ignored `testnet`.** It always connected to the production stream. A testnet session now uses `wss://stream.testnet.binance.vision/ws`. +- **nanobook-broker: the Binance websocket reconnect never gave up.** `connect` + reset the attempt counter before trying, so each failed attempt inside + `reconnect_with_backoff` started the count again and the loop retried forever. + The counter now resets only after a successful connect, and the loop stops after + `max_reconnect_attempts` with its error. Found while writing tests for mutation + survivors. - The ITCH parser read the Stock Directory (`R`) symbol from the tracking-number and timestamp bytes. `ItchMessage::StockDirectory` now carries the real symbol (ITCH 5.0 offset 11). Found by mutation testing. diff --git a/broker/src/binance/websocket.rs b/broker/src/binance/websocket.rs index 476e43e..8e8f14a 100644 --- a/broker/src/binance/websocket.rs +++ b/broker/src/binance/websocket.rs @@ -62,6 +62,9 @@ pub struct BinanceWebSocket { // Auto-reconnect mechanism max_reconnect_attempts: u32, reconnect_attempts: u32, + /// Test-only: connect here instead of the Binance stream. + #[cfg(test)] + endpoint_override: Option, } impl BinanceWebSocket { @@ -79,6 +82,8 @@ impl BinanceWebSocket { heartbeat_interval: Duration::from_secs(10), max_reconnect_attempts: 5, reconnect_attempts: 0, + #[cfg(test)] + endpoint_override: None, } } @@ -100,11 +105,13 @@ impl BinanceWebSocket { /// Connect to the Binance WebSocket endpoint. pub async fn connect(&mut self) -> Result<(), Box> { self.state = ConnectionState::Reconnecting; - self.reconnect_attempts = 0; - let (stream, _) = connect_async(self.endpoint()).await.inspect_err(|_| { + let endpoint = self.endpoint().to_string(); + let (stream, _) = connect_async(endpoint).await.inspect_err(|_| { self.connected.store(false, Ordering::SeqCst); self.state = ConnectionState::Disconnected; })?; + // Reset only on success: reconnect_with_backoff counts failed connects. + self.reconnect_attempts = 0; self.client = Some(stream); self.connected.store(true, Ordering::SeqCst); @@ -255,8 +262,12 @@ impl BinanceWebSocket { self.heartbeat_interval = interval; } - fn endpoint(&self) -> &'static str { + fn endpoint(&self) -> &str { let _ = (&self.api_key, &self.secret_key); + #[cfg(test)] + if let Some(endpoint) = &self.endpoint_override { + return endpoint; + } if self.testnet { "wss://stream.testnet.binance.vision/ws" } else { @@ -430,6 +441,33 @@ mod tests { assert_eq!(ws.reconnect_attempts(), 3); } + #[tokio::test] + async fn reconnect_gives_up_after_the_attempt_limit() { + // A port that was free a moment ago refuses the connection at once. + let port = std::net::TcpListener::bind("127.0.0.1:0") + .unwrap() + .local_addr() + .unwrap() + .port(); + let mut ws = BinanceWebSocket::new("key", "secret", true); + ws.endpoint_override = Some(format!("ws://127.0.0.1:{port}/ws")); + ws.set_max_reconnect_attempts(2); + + // Real time (a paused clock jumps ahead while a socket connects): + // backoff 1 s + 2 s. Before the fix, each failed connect reset the + // counter and the loop never ended. + let result = tokio::time::timeout(Duration::from_secs(30), ws.reconnect_with_backoff()) + .await + .expect("reconnect loop must stop after its attempt limit"); + + assert_eq!( + result.unwrap_err().to_string(), + "Failed to reconnect after 2 attempts" + ); + assert_eq!(ws.reconnect_attempts(), 2); + assert_eq!(ws.state(), ConnectionState::Disconnected); + } + #[tokio::test(start_paused = true)] async fn heartbeat_times_out_when_the_interval_has_elapsed_exactly() { let mut ws = BinanceWebSocket::new("key", "secret", true); From dce499ba1c0406e4190e7a396781b7564ae1f341 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:53:56 +0100 Subject: [PATCH 47/66] test(stp): an STP-cancelled incoming order's record holds nothing cargo-mutants showed Order::stp_decrement could leave the remainder on the stored record (decrement removed, or -= turned into /=) without any test failing; the exchange overwrites the status, so only remaining_quantity shows it. Checks CancelNewest and DecrementAndCancel (law 11). Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- tests/stp_policy.rs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/tests/stp_policy.rs b/tests/stp_policy.rs index 79d7bae..6920036 100644 --- a/tests/stp_policy.rs +++ b/tests/stp_policy.rs @@ -253,3 +253,29 @@ fn cancel_newest_after_partial_fill_against_other_owner() { // ALICE's resting sell untouched (still 100 on ask side). assert_eq!(exchange.book().asks().total_quantity(), 100); } + +// ============================================================================ +// The stored record of an STP-cancelled incoming order holds nothing +// (law 11: cancelled means nothing remains). +// ============================================================================ + +#[test] +fn stp_cancelled_incoming_record_has_nothing_remaining() { + // CancelNewest, and DecrementAndCancel with the incoming order smaller: + // both cancel the incoming remainder through the same decrement. + for (policy, resting_qty, incoming_qty) in [ + (StpPolicy::CancelNewest, 100, 100), + (StpPolicy::DecrementAndCancel, 100, 40), + ] { + let (exchange, result) = run(policy, Some(ALICE), Some(ALICE), resting_qty, incoming_qty); + let order = exchange.get_order(result.order_id).unwrap(); + assert_eq!(order.remaining_quantity, 0, "policy {:?}", policy); + assert_eq!(order.filled_quantity, 0, "policy {:?}", policy); + assert_eq!(order.status, OrderStatus::Cancelled, "policy {:?}", policy); + assert_eq!( + result.cancelled_quantity, incoming_qty, + "policy {:?}", + policy + ); + } +} From 56f8f78331e3c46787160ab403b69955f2433aa4 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:55:21 +0100 Subject: [PATCH 48/66] docs: 0.20.0 mutation-testing results and two known issues VERIFICATION.md gets the per-crate cargo-mutants result on the 0.20.0 code (risk, portfolio/metrics/bridge, broker, rebalancer in both builds), what each class of surviving change means, the bugs the work found, what is not covered yet, and how it was run. The tour and README point to it instead of a placeholder and the old 0.19 matcher baseline. Known issues: the Binance Broker open_orders/cancel_order placeholders and the -0.0% risk detail. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- CHANGELOG.md | 2 ++ README.md | 5 ++-- VERIFICATION.md | 50 ++++++++++++++++++++++++++++++++++++++- python/examples/tour.py | 2 +- python/tests/test_tour.py | 2 +- 5 files changed, 56 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 04d1736..2f2f1a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -136,6 +136,8 @@ tests, fuzzing or mutation testing. - **nanobook-rebalancer: `constraints.min_trade_usd` in target.json does not change the run minimum.** The run still reads `config.risk.min_trade_usd`. - **nanobook-rebalancer: `TargetSpec::window_id` hashes with `DefaultHasher`.** The id can change after a Rust upgrade, so a cron window can fire twice. - **nanobook-rebalancer: without `write_ahead_logging`, the runner does not write `order_submitted`.** Graceful kill then cannot report a dangling order. +- **nanobook-broker: two Binance `Broker` methods are placeholders.** `open_orders` always returns an empty list, and `cancel_order` by order id is refused because the adapter keeps no id-to-symbol map. +- **nanobook-risk: an empty side prints `-0.0%`.** The "Weight allocation" detail shows `-0.0% long` (or short) when no target is on that side, because an empty `f64` sum is `-0.0` since Rust 1.83. The numbers are zero; only the sign in the text is wrong. ### Security diff --git a/README.md b/README.md index beaa405..19dc963 100644 --- a/README.md +++ b/README.md @@ -211,8 +211,9 @@ Report a vulnerability privately as described in [SECURITY.md](SECURITY.md). - 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 diff --git a/VERIFICATION.md b/VERIFICATION.md index 2eaa1a9..89361d1 100644 --- a/VERIFICATION.md +++ b/VERIFICATION.md @@ -128,7 +128,55 @@ part. ## Mutation testing: does all of this catch real bugs in the Rust code? - +[cargo-mutants](https://mutants.rs) plants one small change at a time in the code (a +`<` turned into `<=`, a `+` into `-`, a function body replaced by a constant) and runs +the test suite. If no test fails, the change "survives": the tests would not notice that +bug. For 0.20.0 we ran it on the risk, broker, portfolio and rebalancer code, with +every surviving change either killed by a new test or explained. + +Result on the 0.20.0 code (only changes that compile are counted): + +| Code | Changes | Caught by a failing test | Hang, stopped by the time limit | Cannot change any result | Text or unused code only | Out of reach of tests | +|---|---|---|---|---|---|---| +| `nanobook-risk` | 149 | 146 | 0 | 1 | 2 | 0 | +| `nanobook`: portfolio, metrics, backtest bridge | 1005 | 970 | 8 | 27 | 0 | 0 | +| `nanobook-broker` (IBKR and Binance) | 428 | 388 | 0 | 5 | 6 | 29 | +| `nanobook-rebalancer` (both builds) | 753 | 717 | 4 | 29 | 1 | 2 | + +- "Cannot change any result": no reachable input gives a different answer, for + example `>` against `>=` where the equal case is filtered out a few lines earlier. + Each one is listed with its reason in the triage notes. +- "Out of reach of tests": 27 broker changes need a live Interactive Brokers + connection (whole-function replacements on the client, its order cache and its + callback de-duplication), one needs the Binance network, and one differs only when + a 300 s age equals the limit to the nanosecond on a clock the test cannot set; in + the rebalancer, two replace the interactive confirmation prompt. +- The matching engine itself (`book.rs`, `level.rs`, `matching.rs`, + `exchange.rs`, `price_levels.rs`) had no surviving change in the full core run + (5046 changes). A test added for 0.20.0 also pins the order record after a + self-trade stop (`tests/stp_policy.rs`). + +Sorting the surviving changes and writing the tests found twelve bugs, all fixed in +0.20.0 with a regression test: the ITCH Stock Directory symbol offset; the deflated +Sharpe ratio formula; IBKR connection-loss codes that never reached their check; IBKR +reconciliation that ignored the order's side; a Binance websocket that ignored +`testnet` and a reconnect loop that never gave up; and six in the rebalancer, among +them close orders priced on the wrong side of mid, an aborted run that exited with +code 0, and audit limits read as cents instead of dollars. The changelog lists each. + +Not covered yet: the statistics, indicator, volatility, scenario and optimisation +modules (`stats.rs`, `indicators.rs`, `volatility.rs`, `scenarios.rs`, +`optimize.rs`, `garch.rs`, `cv.rs`) and the command-line tools. In the core run they +left 1153 surviving changes, most of them missing exact-value tests. They are the +next step after 0.20.0. + +**How it was run.** cargo-mutants 27.1 on a separate Linux machine, each package on its +own (`--package`), the broker with `--features ibkr,binance`, the core with +`--all-features`, the rebalancer twice (default features, and +`--features write_ahead_logging,guaranteed_kill_switch`), with `--timeout 900`. The +time limit matters: the rebalancer's write-ahead tests take about 75 s, and with a +180 s limit 15 surviving changes were wrongly counted as hangs. A change counts as +caught when a test fails in at least one build that compiles it. ## What this work found diff --git a/python/examples/tour.py b/python/examples/tour.py index 03c4624..0c33276 100644 --- a/python/examples/tour.py +++ b/python/examples/tour.py @@ -302,7 +302,7 @@ def scene5(): print() print("recheck the proofs yourself, from the repository root:") print(" verification/lean/check.sh 0") - print("mutation score: see VERIFICATION.md") # placeholder until the 0.20.0 score is final + print("mutation-testing results, crate by crate: VERIFICATION.md") # --------------------------------------------------------------------------- figure diff --git a/python/tests/test_tour.py b/python/tests/test_tour.py index e9f8be3..3ac7ac7 100644 --- a/python/tests/test_tour.py +++ b/python/tests/test_tour.py @@ -90,7 +90,7 @@ def test_scene5_laws_match_verification_md(output): s = scene(output, 5) assert len(re.findall(r"^\s+law\s+\d+:", s, flags=re.M)) == 11 assert "verification/lean/check.sh 0" in s - assert "mutation score: see VERIFICATION.md" in s + assert "mutation-testing results, crate by crate: VERIFICATION.md" in s if not VERIFICATION.exists(): pytest.skip("VERIFICATION.md not next to python/ (installed layout)") table = re.findall(r"^\| (\d+) \| (.*?) \| `", VERIFICATION.read_text(), flags=re.M) From dcb23e52edba6c6b5f7bd3a65831da5e6e42bada Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:06:13 +0100 Subject: [PATCH 49/66] docs(changelog): BacktestBridgeResult also gains three fields cargo-semver-checks against 0.19.3 lists initial_cash, executions and cash_snapshots on BacktestBridgeResult besides the options field; a struct literal of either type breaks. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f2f1a2..6d86256 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -124,7 +124,7 @@ tests, fuzzing or mutation testing. fill-or-kill check under a self-trade policy. `OrderBook::can_fully_fill` is unchanged. - **Reference prices in execution records.** `reference_price` (unimpacted cents per share) and `reference_notional` (cents at the final filled quantity, using the engine's truncation and i64 clamp) are added to Rust and Python execution records. Stop references use the current close, including on hold days without rebalance fill bars. Slippage cost is `notional - reference_notional` for buys and `reference_notional - notional` for sells, up to truncation; `cost` remains commission only. The extra calculation runs only when recording is enabled; execution arithmetic and existing outputs are unchanged. -- **Opt-in backtest execution records** through Rust's `BacktestBridgeOptions.record_executions` and Python's `record_executions=True`. Results include `initial_cash`, actual `executions` (including stop exits and trimmed buys), and period-close `cash_snapshots`. Quantity is signed raw micro-shares (1 share = 1,000,000; positive buys, negative sells), with Python `side` (`buy`/`sell`); price is effective cents per share; all other monetary fields are cents. Notional truncates toward zero after scaling and clamps to i64; cash fields reflect actual balance changes, including saturation. Ledgers are `None` by default and empty for enabled empty/rejected runs. Existing calls and financial calculations are unchanged. *Check your code if* you build `BacktestBridgeOptions` with a struct literal: add `record_executions` or end it with `..Default::default()`. The Python stubs for `backtest_weights` now match the runtime signature. +- **Opt-in backtest execution records** through Rust's `BacktestBridgeOptions.record_executions` and Python's `record_executions=True`. Results include `initial_cash`, actual `executions` (including stop exits and trimmed buys), and period-close `cash_snapshots`. Quantity is signed raw micro-shares (1 share = 1,000,000; positive buys, negative sells), with Python `side` (`buy`/`sell`); price is effective cents per share; all other monetary fields are cents. Notional truncates toward zero after scaling and clamps to i64; cash fields reflect actual balance changes, including saturation. Ledgers are `None` by default and empty for enabled empty/rejected runs. Existing calls and financial calculations are unchanged. *Check your code if* you build `BacktestBridgeOptions` with a struct literal: add `record_executions` or end it with `..Default::default()`. `BacktestBridgeResult` gains the three fields `initial_cash`, `executions` and `cash_snapshots`; code that builds it with a struct literal must set them. The Python stubs for `backtest_weights` now match the runtime signature. - **Lean verification.** The Lean model, proofs and replay tools (`verification/lean/`), the corpus generator (`examples/corpus_gen.rs`), the Rust-versus-Lean replay (`verification/lean/differential.sh`), and golden corpus cases 19 to 25. From 4751a2672aba875075124ce5e661ba44ae89bc83 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:17:55 +0100 Subject: [PATCH 50/66] fix(broker): MockBroker::cancel_order also removes configured open-order rows From review of PR 86: rows set with set_open_order_statuses bypassed cancel_order, so open_orders kept returning a cancelled order. cancel_order now drops the row too. The test fixture order is also 100 shares, the size the mock builds its fills from. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- broker/src/mock.rs | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/broker/src/mock.rs b/broker/src/mock.rs index 950547d..669ad42 100644 --- a/broker/src/mock.rs +++ b/broker/src/mock.rs @@ -285,6 +285,15 @@ impl Broker for MockBroker { .lock() .expect("open_orders mutex poisoned") .retain(|&oid| oid != id); + // Rows set by `set_open_order_statuses` are open orders too. + if let Some(rows) = self + .open_order_statuses + .lock() + .expect("open_order_statuses mutex poisoned") + .as_mut() + { + rows.retain(|row| row.id != id); + } Ok(()) } @@ -411,11 +420,12 @@ mod tests { assert_eq!(third, OrderId(3)); } + /// A 100-share order: the mock builds every fill status from 100 shares. fn market_order() -> BrokerOrder { BrokerOrder { symbol: aapl(), side: BrokerSide::Buy, - quantity: 1, + quantity: 100, order_type: BrokerOrderType::Market, client_order_id: None, } @@ -496,6 +506,25 @@ mod tests { assert_eq!(ids, vec![OrderId(2)]); } + #[test] + fn cancel_order_removes_a_configured_row() { + let mut broker = MockBroker::builder().build(); + broker.connect().unwrap(); + let row = |id: u64| BrokerOrderStatus { + id: OrderId(id), + status: OrderState::Submitted, + filled_quantity: 0, + remaining_quantity: 50, + avg_fill_price_cents: 0, + }; + broker.set_open_order_statuses(vec![row(7), row(8)]); + + broker.cancel_order(OrderId(7)).unwrap(); + + let ids: Vec = broker.open_orders().unwrap().iter().map(|o| o.id).collect(); + assert_eq!(ids, vec![OrderId(8)]); + } + #[test] fn set_open_order_statuses_replaces_the_rows_open_orders_returns() { let mut broker = MockBroker::builder().build(); From 2a590f4276196e5b97974449fedf0a4521daa304 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:17:55 +0100 Subject: [PATCH 51/66] fix(broker): clamp the Binance websocket backoff exponent before pow From review of PR 86: set_max_reconnect_attempts above 64 made 2u64.pow overflow (panic in debug, zero delay in release). The delay is now a small function that clamps the exponent first; a unit test covers attempts 0 to 6, 65 and u32::MAX. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- broker/src/binance/websocket.rs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/broker/src/binance/websocket.rs b/broker/src/binance/websocket.rs index 8e8f14a..255b9ed 100644 --- a/broker/src/binance/websocket.rs +++ b/broker/src/binance/websocket.rs @@ -47,6 +47,13 @@ pub struct ExecutionReport { pub raw: Value, } +/// Delay before reconnect attempt `attempt` (1-based): 1 s, 2 s, 4 s, 8 s, then 16 s. +/// +/// The exponent is clamped before `pow`, so any `max_reconnect_attempts` is safe. +fn backoff_delay(attempt: u32) -> Duration { + Duration::from_secs(2u64.pow(attempt.saturating_sub(1).min(4))) +} + /// Binance WebSocket client. pub struct BinanceWebSocket { api_key: String, @@ -196,12 +203,8 @@ impl BinanceWebSocket { self.reconnect_attempts += 1; self.state = ConnectionState::Reconnecting; - // Calculate backoff delay: 2^(attempt-1) seconds, capped at 16s - let backoff_secs = 2u64.pow(self.reconnect_attempts.saturating_sub(1)).min(16); - let backoff = Duration::from_secs(backoff_secs); - // Wait for backoff - sleep(backoff).await; + sleep(backoff_delay(self.reconnect_attempts)).await; // Attempt to reconnect if let Ok(()) = self.connect().await { @@ -433,6 +436,15 @@ mod tests { assert_eq!(ws.events(), &[execution_report_event()]); } + #[test] + fn backoff_doubles_to_16_seconds_and_stays_there() { + let secs: Vec = [0, 1, 2, 3, 4, 5, 6, 65, u32::MAX] + .iter() + .map(|&attempt| backoff_delay(attempt).as_secs()) + .collect(); + assert_eq!(secs, vec![1, 1, 2, 4, 8, 16, 16, 16, 16]); + } + #[test] fn reconnect_attempts_reports_the_counter() { let mut ws = BinanceWebSocket::new("key", "secret", true); From a4de469c1cd412b7120bb165d4217d5a3ac72b13 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:24:32 +0100 Subject: [PATCH 52/66] fix(rebalancer): write the PID file atomically; stop the holder child in its test From review of PR 86. write_pid_file truncated the file before writing, and --kill reads it without the lock, so a kill racing a start could read an empty PID. It now writes .tmp and renames it over the PID file. A test reads the file in a loop while it is rewritten 20000 times; it fails on the old code. The holder-process test now kills and reaps the child even when an assertion fails. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- rebalancer/src/pid_file.rs | 73 +++++++++++++++++++++++++++++++------- 1 file changed, 60 insertions(+), 13 deletions(-) diff --git a/rebalancer/src/pid_file.rs b/rebalancer/src/pid_file.rs index 93fb9f9..f7233e5 100644 --- a/rebalancer/src/pid_file.rs +++ b/rebalancer/src/pid_file.rs @@ -40,12 +40,22 @@ pub const DEFAULT_PID_FILE: &str = "rebalancer.pid"; /// Write the current process ID to a PID file. /// +/// The PID goes to `.tmp` first and is renamed over `path`, so a reader +/// (`--kill`, which does not take the lock) never sees an empty or partial file. +/// /// # Errors /// /// Returns an error if the file cannot be written or if the PID cannot be obtained. pub fn write_pid_file(path: &Path) -> Result<()> { let pid = std::process::id(); - fs::write(path, pid.to_string()).map_err(Error::Audit)?; + let mut tmp_name = path.as_os_str().to_owned(); + tmp_name.push(".tmp"); + let tmp = PathBuf::from(tmp_name); + fs::write(&tmp, pid.to_string()).map_err(Error::Audit)?; + if let Err(error) = fs::rename(&tmp, path) { + let _ = fs::remove_file(&tmp); + return Err(Error::Audit(error)); + } Ok(()) } @@ -205,6 +215,43 @@ mod tests { assert!(result.is_err()); } + #[test] + fn a_reader_never_sees_an_empty_pid_file_while_it_is_rewritten() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("rebalancer.pid"); + write_pid_file(&path).unwrap(); + + let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let reader = { + let (path, stop) = (path.clone(), stop.clone()); + std::thread::spawn(move || { + let mut reads = 0_u32; + while !stop.load(std::sync::atomic::Ordering::Relaxed) { + // Every read must hold the whole PID. + assert_eq!(read_pid_file(&path).unwrap(), std::process::id()); + reads += 1; + } + reads + }) + }; + for _ in 0..20_000 { + write_pid_file(&path).unwrap(); + } + stop.store(true, std::sync::atomic::Ordering::Relaxed); + assert!(reader.join().unwrap() > 0); + assert!(!path.with_extension("pid.tmp").exists()); + } + + /// Kills and reaps the holder process even when an assertion fails. + struct KillOnDrop(std::process::Child); + + impl Drop for KillOnDrop { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + #[test] fn a_second_guard_cannot_replace_a_live_pid_file() { if std::env::var_os("NANOBOOK_PID_HOLDER").is_some() { @@ -218,33 +265,33 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("rebalancer.pid"); - let mut child = std::process::Command::new(std::env::current_exe().unwrap()) - .arg("pid_file::tests::a_second_guard_cannot_replace_a_live_pid_file") - .arg("--exact") - .env("NANOBOOK_PID_HOLDER", "1") - .env("NANOBOOK_PID_PATH", &path) - .spawn() - .unwrap(); + let child = KillOnDrop( + std::process::Command::new(std::env::current_exe().unwrap()) + .arg("pid_file::tests::a_second_guard_cannot_replace_a_live_pid_file") + .arg("--exact") + .env("NANOBOOK_PID_HOLDER", "1") + .env("NANOBOOK_PID_PATH", &path) + .spawn() + .unwrap(), + ); let ready = path.with_extension("ready"); let started = std::time::Instant::now(); while !ready.exists() { if started.elapsed() > std::time::Duration::from_secs(10) { - let _ = child.kill(); - let _ = child.wait(); panic!("holder did not lock the PID file"); } std::thread::sleep(std::time::Duration::from_millis(20)); } // --kill reads the PID file while the holder runs. - assert_eq!(read_pid_file(&path).unwrap(), child.id()); + assert_eq!(read_pid_file(&path).unwrap(), child.0.id()); let error = PidFileGuard::create(path.clone()).unwrap_err(); assert!( error.to_string().contains("in use by another rebalancer"), "{error}" ); - let _ = child.kill(); - let _ = child.wait(); + // Kill and reap the holder; a failed assertion above does the same on drop. + drop(child); // Windows may release a killed process's lock a moment after the process exits. let started = std::time::Instant::now(); let guard = loop { From 43fb11ec73df52500e15145bd6957568849d46af Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:24:32 +0100 Subject: [PATCH 53/66] fix(rebalancer): take the PID guard before the cron completed-window check From review of PR 86. The check ran first, so two cron callers could both pass it; if one finished before the other took the PID lock, the second never saw the new cron_completed event and could submit the same window twice. The guard is now taken first. A second caller that finds the lock held now gets the 'in use by another rebalancer' error instead of IdempotencyRejection. A test holds the guard over a completed window and fails on the old order. The same test file now writes the logging dir as an escaped TOML string value instead of a single-quoted literal, which broke on a path with an apostrophe. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- rebalancer/src/execution.rs | 8 +++-- rebalancer/tests/run_orchestration.rs | 47 +++++++++++++++++++++++++-- 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/rebalancer/src/execution.rs b/rebalancer/src/execution.rs index 6442f5e..fea96ae 100644 --- a/rebalancer/src/execution.rs +++ b/rebalancer/src/execution.rs @@ -279,6 +279,11 @@ pub fn run_with_client( workdir: &Path, confirm: &mut dyn FnMut() -> Result, ) -> Result<()> { + // Hold the PID guard before the completed-window check. Checked first, two + // cron callers could both pass it and the second would submit the same window again. + let _pid_guard = + crate::pid_file::PidFileGuard::create(workdir.join(crate::pid_file::DEFAULT_PID_FILE))?; + if opts.cron_mode { let audit_path = resolve_audit_path(config, workdir); if audit_path.exists() { @@ -298,9 +303,6 @@ pub fn run_with_client( } } - let _pid_guard = - crate::pid_file::PidFileGuard::create(workdir.join(crate::pid_file::DEFAULT_PID_FILE))?; - // 2. Open audit log let audit_path = resolve_audit_path(config, workdir); let existing_checkpoint_sequence = audit::max_checkpoint_sequence(&audit_path)?; diff --git a/rebalancer/tests/run_orchestration.rs b/rebalancer/tests/run_orchestration.rs index b80a42d..28b7f92 100644 --- a/rebalancer/tests/run_orchestration.rs +++ b/rebalancer/tests/run_orchestration.rs @@ -183,10 +183,10 @@ allow_short = true max_short_pct = 1.0 [cost] [logging] -dir = '{}' +dir = {} audit_file = "audit.jsonl" "#, - workdir.join("logs").display() + toml::Value::String(workdir.join("logs").display().to_string()) )) .unwrap() } @@ -466,6 +466,49 @@ fn cron_mode_refuses_a_completed_window_before_orders() { assert!(events.iter().all(|event| event.event != "run_started")); } +#[test] +fn cron_mode_takes_the_pid_guard_before_the_completed_window_check() { + let dir = tempfile::tempdir().unwrap(); + let config = config(dir.path()); + let spec = spec_three(); + { + let mut audit = audit::AuditLog::open_in(&config.audit_path(), dir.path()).unwrap(); + audit::log_cron_completed(&mut audit, 42, &spec.window_id(), 1, 1, 0).unwrap(); + } + let events_before = parse_audit_events(&config.audit_path()).unwrap().len(); + // Another run holds the guard. A second caller must wait on it, not read + // the audit log first: the holder may finish the window after that read. + let holder = + nanobook_rebalancer::pid_file::PidFileGuard::create(dir.path().join(DEFAULT_PID_FILE)) + .unwrap(); + let shutdown = ShutdownFlag::new(); + let broker = ScriptedBroker::new(dir.path(), shutdown.clone(), Vec::new()); + let mut confirm = || -> Result { panic!("confirm must not be called") }; + match run_with_client( + &config, + &spec, + &opts(true, false, true), + &broker, + &shutdown, + dir.path(), + &mut confirm, + ) { + Err(Error::Aborted(message)) => { + assert!( + message.contains("in use by another rebalancer"), + "{message}" + ); + } + other => panic!("expected Aborted, got {other:?}"), + } + assert!(broker.executes.borrow().is_empty()); + assert_eq!( + parse_audit_events(&config.audit_path()).unwrap().len(), + events_before + ); + drop(holder); +} + #[test] fn confirm_error_is_aborted() { let dir = tempfile::tempdir().unwrap(); From 05b1de54029fa55135a946843c96d0fb54e5a22a Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:24:32 +0100 Subject: [PATCH 54/66] fix(rebalancer): name the cause when the logging directory check fails From review of PR 86. validate_disk_space used is_dir(), so a path that is a file, or a directory that cannot be read, was reported as 'directory does not exist'. It now reads the metadata and says 'path is not a directory' or the I/O error. A test covers a file used as the logging directory; it fails on the old message. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- rebalancer/src/validator.rs | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/rebalancer/src/validator.rs b/rebalancer/src/validator.rs index ac05bf7..d2140ce 100644 --- a/rebalancer/src/validator.rs +++ b/rebalancer/src/validator.rs @@ -238,11 +238,19 @@ pub fn validate_disk_space(config: &Config) -> Vec { let audit_path = config.audit_path(); let dir = audit_path.parent().unwrap_or_else(|| Path::new(".")); // Windows answers for the volume even when the directory is missing, so check it first. - if !dir.is_dir() { + let problem = match std::fs::metadata(dir) { + Ok(metadata) if metadata.is_dir() => None, + Ok(_) => Some("path is not a directory".to_string()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + Some("directory does not exist".to_string()) + } + Err(error) => Some(format!("directory cannot be read: {error}")), + }; + if let Some(problem) = problem { return vec![ValidationIssue::new( "logging.dir", format!( - "cannot determine available space for {}: directory does not exist", + "cannot determine available space for {}: {problem}", dir.display() ), "verify the logging directory exists and the filesystem is accessible", @@ -553,6 +561,25 @@ mod tests { ); } + #[test] + fn disk_space_names_the_cause_of_a_bad_log_directory() { + let missing = valid_config(Path::new("/nonexistent-nanobook-test-dir/logs")); + let issues = validate_disk_space(&missing); + assert!(issues[0].message.ends_with("directory does not exist")); + + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("not-a-dir"); + std::fs::write(&file, b"x").unwrap(); + let issues = validate_disk_space(&valid_config(&file)); + assert_eq!(issues.len(), 1); + assert_eq!(issues[0].field, "logging.dir"); + assert!( + issues[0].message.ends_with("path is not a directory"), + "{}", + issues[0].message + ); + } + #[test] fn available_log_space_boundary() { let dir = tempfile::tempdir().unwrap(); From 3643edd4491a40b888017cea8392b10236a726d6 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:24:32 +0100 Subject: [PATCH 55/66] test(rebalancer): escape the logging dir as TOML; reverse the broker list in a recovery test; tighten the mixed-intent test From review of PR 86. - recovery_integration.rs and mutation_stdout.rs wrote the temp dir as a single-quoted TOML literal, which breaks on a path with an apostrophe. They write an escaped TOML string value (checked on C:\Users\O'Brien\...). - mutation_recovery.rs: a second test lists the open orders in the reverse of the intent order, so assigning by list position instead of quantity is caught. - recovery_integration.rs: the mixed-intent test gave the mock a 50-share order that reported 50 filled and 50 open. It now sets a 25 filled, 25 open order, and checks the last audit event is order_failed for MSFT instead of an assertion that could not fail. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- rebalancer/tests/mutation_recovery.rs | 28 ++++++++++++ rebalancer/tests/mutation_stdout.rs | 4 +- rebalancer/tests/recovery_integration.rs | 57 +++++++++++++----------- 3 files changed, 61 insertions(+), 28 deletions(-) diff --git a/rebalancer/tests/mutation_recovery.rs b/rebalancer/tests/mutation_recovery.rs index a00eb70..52a4a1b 100644 --- a/rebalancer/tests/mutation_recovery.rs +++ b/rebalancer/tests/mutation_recovery.rs @@ -140,6 +140,34 @@ fn two_open_orders_of_different_quantities_submit_both_intents() { ); } +#[test] +fn intents_match_open_orders_by_quantity_not_by_the_broker_list_order() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("audit.jsonl"); + write_two_incomplete_intents(&path, dir.path(), 50, 25); + + // The 25-share order is listed first, the reverse of the intent order. + let mut broker = MockBroker::builder().build(); + broker.connect().unwrap(); + broker.set_open_order_statuses(vec![open_status(8, 25), open_status(7, 50)]); + + let (state, _) = reconstruct_state(&path).unwrap(); + reconcile_incomplete_intents(&broker, &state, &path).unwrap(); + let events = parse_audit_events(&path).unwrap(); + assert_eq!(events.len(), 5); + let submitted: Vec<(&str, u64)> = events[3..] + .iter() + .map(|event| { + assert_eq!(event.event, "order_submitted"); + ( + event.data["symbol"].as_str().unwrap(), + event.data["ibkr_id"].as_u64().unwrap(), + ) + }) + .collect(); + assert_eq!(submitted, vec![("AAPL", 7), ("MSFT", 8)]); +} + #[test] fn reconciliation_summary_counts_intents_missing_at_the_broker() { let dir = tempfile::tempdir().unwrap(); diff --git a/rebalancer/tests/mutation_stdout.rs b/rebalancer/tests/mutation_stdout.rs index fac528a..3657995 100644 --- a/rebalancer/tests/mutation_stdout.rs +++ b/rebalancer/tests/mutation_stdout.rs @@ -44,10 +44,10 @@ allow_short = true max_short_pct = 1.0 [cost] [logging] -dir = '{}' +dir = {} audit_file = "audit.jsonl" "#, - logs_dir.display() + toml::Value::String(logs_dir.display().to_string()) )) .unwrap() } diff --git a/rebalancer/tests/recovery_integration.rs b/rebalancer/tests/recovery_integration.rs index 2570d4c..207d78a 100644 --- a/rebalancer/tests/recovery_integration.rs +++ b/rebalancer/tests/recovery_integration.rs @@ -438,10 +438,10 @@ port = 7497 client_id = 1 [logging] -# Literal string (single quotes): a Windows temp path such as -# C:\Users\RUNNER~1\AppData\Local\Temp\... contains \U, \A and \T, which are -# invalid escapes in a TOML basic string and made Config::load fail here. -dir = '{}' +# The path is written as a TOML string value, escaped as needed: a Windows temp +# path such as C:\Users\RUNNER~1\AppData\Local\Temp\... has backslashes, and a +# user name may hold an apostrophe. +dir = {} audit_file = "audit.jsonl" [execution] @@ -461,7 +461,7 @@ commission_per_share = 0.005 commission_min = 1.0 slippage_bps = 5 "#, - dir.path().display() + toml::Value::String(dir.path().display().to_string()) ), ) .unwrap(); @@ -679,7 +679,6 @@ fn test_broker_reconciliation_incomplete_intent_not_found() { #[test] fn test_broker_reconciliation_mixed_intents() { use nanobook_rebalancer::recovery::reconcile_incomplete_intents; - use std::fs; let dir = tempfile::tempdir().unwrap(); let audit_path = dir.path().join("audit.jsonl"); @@ -730,23 +729,20 @@ fn test_broker_reconciliation_mixed_intents() { .unwrap(); } - // Create MockBroker with only the AAPL order (no orders for MSFT) + // Create MockBroker with only the AAPL order (no orders for MSFT): a + // 50-share order, 25 filled and 25 still open. let mut broker = MockBroker::builder() - .fill_mode(FillMode::ImmediatePartial(0.5)) .with_position(Symbol::new("AAPL"), 100, 150_00) .with_position(Symbol::new("MSFT"), 50, 300_00) .build(); broker.connect().unwrap(); - - // Submit AAPL order to broker (MSFT order is not submitted) - let order = BrokerOrder { - symbol: Symbol::new("AAPL"), - side: BrokerSide::Buy, - quantity: 50, - order_type: BrokerOrderType::Market, - client_order_id: None, - }; - broker.submit_order(&order).unwrap(); + broker.set_open_order_statuses(vec![nanobook_broker::types::BrokerOrderStatus { + id: nanobook_broker::types::OrderId(1), + status: nanobook_broker::types::OrderState::PartiallyFilled, + filled_quantity: 25, + remaining_quantity: 25, + avg_fill_price_cents: 0, + }]); // Reconstruct state let (state, _) = reconstruct_state(&audit_path).unwrap(); @@ -757,10 +753,19 @@ fn test_broker_reconciliation_mixed_intents() { // Reconciliation should succeed (only MSFT is incomplete) assert!(result.is_ok()); - // Verify audit log was updated with OrderFailed for MSFT - let audit_contents = fs::read_to_string(&audit_path).unwrap(); - // MSFT should be marked as failed since it's incomplete and no matching order at broker - assert!(audit_contents.contains("order_failed") || audit_contents.contains("MSFT")); + // MSFT (25 shares) is incomplete and no open order started at 25 shares, + // so it is marked failed. The 25 filled plus 25 open order is a 50-share order. + let events = nanobook_rebalancer::audit::parse_audit_events(&audit_path).unwrap(); + let last = events.last().unwrap(); + assert_eq!(last.event, "order_failed"); + assert_eq!( + last.data.get("symbol").and_then(|v| v.as_str()), + Some("MSFT") + ); + assert_eq!( + last.data.get("reason").and_then(|v| v.as_str()), + Some("not_found_at_broker") + ); } #[cfg(feature = "write_ahead_logging")] @@ -1164,10 +1169,10 @@ type = "cash" [risk] [cost] [logging] -dir = '{}' +dir = {} audit_file = "audit.jsonl" "#, - dir.path().display() + toml::Value::String(dir.path().display().to_string()) )) .unwrap(); let spec = TargetSpec::from_json( @@ -1232,10 +1237,10 @@ type = "cash" [risk] [cost] [logging] -dir = '{}' +dir = {} audit_file = "audit.jsonl" "#, - dir.path().display() + toml::Value::String(dir.path().display().to_string()) )) .unwrap(); let spec = TargetSpec::from_json( From de9dc4e0c46ef4a4092f7a05041bce27875d194d Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:24:43 +0100 Subject: [PATCH 56/66] docs(portfolio): fix the mean return in the Sortino test comment From review of PR 86. The fixture mean is 0.006, not 0.0066; the tested excess mean is 0.004. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- src/portfolio/metrics.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/portfolio/metrics.rs b/src/portfolio/metrics.rs index b8cb223..7b81792 100644 --- a/src/portfolio/metrics.rs +++ b/src/portfolio/metrics.rs @@ -942,9 +942,9 @@ mod tests { /// A2-G2: Sortino with non-zero risk-free rate, no downside, ddof guard. #[test] fn sortino_risk_free_and_guards() { - // (a) excess mean 0.0066 - 0.002; downside from r - rf < 0. Reference computed - // in Python from the definition; 1e-9 covers sqrt/division rounding. Flipping - // the sign of rf in either place gives 11.33 or 7.21. + // (a) mean return 0.006, excess mean 0.006 - 0.002; downside from r - rf < 0. + // Reference computed in Python from the definition; 1e-9 covers sqrt/division + // rounding. Flipping the sign of rf in either place gives 11.33 or 7.21. let r = [0.02, -0.01, 0.03, -0.02, 0.01]; assert_close( sortino(&r, 0.002, 252.0, 0), From 5f28b1604a73fe287b8c182c9a9f2b2134b5a834 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:25:06 +0100 Subject: [PATCH 57/66] docs: correct the Timestamp table, the IBKR connection-loss and recovery entries, and the mutation-testing triage reference From review of PR 86. - docs/reference.md: the Timestamp table said +1 per event; cancellations take no value. - CHANGELOG.md: the connection-loss fix only applies to a notice on the order's own stream (ibapi 2.12 sends 1100 to 1102 to the global stream); recovery matches filled plus remaining quantity; the Binance cancel_order note was wrong (an order cache exists but is unused). Known issues added for Binance open orders from /api/v3/account, IBKR connection notices, reconcile_partial_fill and quantity-only recovery matching. Fixed entries added for the PID guard order and the backoff clamp. - VERIFICATION.md: no triage notes exist in the repository; the reference is removed. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- CHANGELOG.md | 18 +++++++++++++----- VERIFICATION.md | 2 +- docs/reference.md | 2 +- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d86256..cc86d11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -88,9 +88,11 @@ tests, fuzzing or mutation testing. - `Trade::vwap` returns `None` when the quantity sum does not fit, instead of overflowing. - **nanobook-broker: an IBKR connection loss during an order was not reported.** - Codes 1100 to 1102 never reached their check, so `execute_limit_order` did not - return `ConnectionLost` with the partial fill. It does now. Found by mutation - testing. + The order loop dropped codes 1100 to 1102 before its check, so `execute_limit_order` + did not return `ConnectionLost` with the partial fill when such a notice reached the + order's own stream. It does now. ibapi 2.12 sends these notices with request id -1 to + its global order-update stream, not to the order's stream (see Known issues). Found + by mutation testing. - **nanobook-broker: IBKR reconciliation after a disconnect ignored the order's side.** `reconcile_partial_fill` compared the absolute position size, so a buy order against a short position (or a sell against a long one) was reported as filled @@ -116,7 +118,9 @@ tests, fuzzing or mutation testing. - **nanobook-rebalancer: recovery and kill read audit `limit` as cents.** The writers store dollars. A 160.25 limit now reconstructs as 16025 cents. - **nanobook-rebalancer: the runner did not write `rebalancer.pid`.** `run` now writes the PID file at start and removes it on every exit path. - **nanobook-rebalancer: the close loop sent a limit-0 order when the quote was 0.** It now skips that symbol. -- **nanobook-rebalancer: recovery matched the first open order with remaining quantity.** It now matches remaining quantity of the incomplete intent. +- **nanobook-rebalancer: two cron runs could both pass the completed-window check.** The PID-file lock is now taken before the check, so a second caller that finds the lock held gets "in use by another rebalancer" rather than an idempotency rejection. `--kill` also no longer reads an empty PID file while a run starts: the PID is written to a temporary file and renamed. +- **nanobook-broker: a Binance websocket `set_max_reconnect_attempts` above 64 overflowed the backoff.** The delay stays 16 s from the fifth attempt on. +- **nanobook-rebalancer: recovery matched the first open order with remaining quantity.** It now matches an open order whose filled plus remaining quantity equals the incomplete intent's quantity; an order that two intents match is given to neither. ### Added @@ -136,7 +140,11 @@ tests, fuzzing or mutation testing. - **nanobook-rebalancer: `constraints.min_trade_usd` in target.json does not change the run minimum.** The run still reads `config.risk.min_trade_usd`. - **nanobook-rebalancer: `TargetSpec::window_id` hashes with `DefaultHasher`.** The id can change after a Rust upgrade, so a cron window can fire twice. - **nanobook-rebalancer: without `write_ahead_logging`, the runner does not write `order_submitted`.** Graceful kill then cannot report a dangling order. -- **nanobook-broker: two Binance `Broker` methods are placeholders.** `open_orders` always returns an empty list, and `cancel_order` by order id is refused because the adapter keeps no id-to-symbol map. +- **nanobook-broker: two Binance `Broker` methods are placeholders.** `open_orders` always returns an empty list, and `cancel_order` by order id is refused: the adapter has an order cache with the symbol of each order, but `cancel_order` does not use it yet. +- **nanobook-broker: Binance open-order polling and `reconcile_state` read `openOrders` from `/api/v3/account`.** Binance does not return that field there (open orders come from `/api/v3/openOrders`), so both see an empty list on the real service. The tests feed the field by hand. +- **nanobook-broker: an IBKR connection notice (1100 to 1102) does not reach `execute_limit_order` as such.** ibapi 2.12 delivers it with request id -1 to the global order-update stream, so a lost connection is reported when the order's stream ends, not when the notice arrives. +- **nanobook-broker: `ibkr::orders::reconcile_partial_fill` compares the net position, not the change since the order began.** A position held before the order counts as filled shares. +- **nanobook-rebalancer: recovery matches open orders by quantity only.** `BrokerOrderStatus` has no symbol or client order id, so one open order of the right size marks an incomplete intent as submitted whatever its symbol. - **nanobook-risk: an empty side prints `-0.0%`.** The "Weight allocation" detail shows `-0.0% long` (or short) when no target is on that side, because an empty `f64` sum is `-0.0` since Rust 1.83. The numbers are zero; only the sign in the text is wrong. ### Security diff --git a/VERIFICATION.md b/VERIFICATION.md index 89361d1..b66e6f5 100644 --- a/VERIFICATION.md +++ b/VERIFICATION.md @@ -145,7 +145,7 @@ Result on the 0.20.0 code (only changes that compile are counted): - "Cannot change any result": no reachable input gives a different answer, for example `>` against `>=` where the equal case is filtered out a few lines earlier. - Each one is listed with its reason in the triage notes. + The table gives counts only; the reason for each change is not published here. - "Out of reach of tests": 27 broker changes need a live Interactive Brokers connection (whole-function replacements on the client, its order cache and its callback de-duplication), one needs the Binance network, and one differs only when diff --git a/docs/reference.md b/docs/reference.md index b8e5167..cacae7f 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -144,7 +144,7 @@ assert_eq!(err.unwrap_err(), ValidationError::ZeroPrice); | `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` | Event counter, +1 per event (not wall clock) | — | +| `Timestamp` | `type Timestamp = u64` | Sequence number, +1 per new order, stop order, or trade (cancellations take none; not wall clock) | — | ### Result Types From 9368404b78ec1034b3faaa22949d5a15add1b9c3 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:27:00 +0100 Subject: [PATCH 58/66] docs: IBKR connection-loss fix is partial; Timestamp is an event counter VERIFICATION.md counted the IBKR connection-loss guard as a fixed bug; the order loop is fixed, but ibapi 2.12 sends notices 1100-1102 on the global order-update stream (known issue). UBIQUITOUS_LANGUAGE.md called Timestamp a nanosecond counter; it is an event sequence number (src/types.rs). From review of PR 86. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- UBIQUITOUS_LANGUAGE.md | 2 +- VERIFICATION.md | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/UBIQUITOUS_LANGUAGE.md b/UBIQUITOUS_LANGUAGE.md index 2d55500..1cb21a9 100644 --- a/UBIQUITOUS_LANGUAGE.md +++ b/UBIQUITOUS_LANGUAGE.md @@ -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 diff --git a/VERIFICATION.md b/VERIFICATION.md index b66e6f5..0808042 100644 --- a/VERIFICATION.md +++ b/VERIFICATION.md @@ -156,13 +156,15 @@ Result on the 0.20.0 code (only changes that compile are counted): (5046 changes). A test added for 0.20.0 also pins the order record after a self-trade stop (`tests/stp_policy.rs`). -Sorting the surviving changes and writing the tests found twelve bugs, all fixed in +Sorting the surviving changes and writing the tests found twelve bugs, fixed in 0.20.0 with a regression test: the ITCH Stock Directory symbol offset; the deflated -Sharpe ratio formula; IBKR connection-loss codes that never reached their check; IBKR -reconciliation that ignored the order's side; a Binance websocket that ignored -`testnet` and a reconnect loop that never gave up; and six in the rebalancer, among -them close orders priced on the wrong side of mid, an aborted run that exited with -code 0, and audit limits read as cents instead of dollars. The changelog lists each. +Sharpe ratio formula; IBKR connection-loss codes dropped before their check (fixed in +the order loop, but ibapi 2.12 delivers these notices on another stream, see the +changelog's known issues); IBKR reconciliation that ignored the order's side; a +Binance websocket that ignored `testnet` and a reconnect loop that never gave up; and +six in the rebalancer, among them close orders priced on the wrong side of mid, an +aborted run that exited with code 0, and audit limits read as cents instead of +dollars. The changelog lists each, and the broker problems still open. Not covered yet: the statistics, indicator, volatility, scenario and optimisation modules (`stats.rs`, `indicators.rs`, `volatility.rs`, `scenarios.rs`, From 62dfc826ff9e8324d451a08a985863d6c7d8c44a Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:14:37 +0100 Subject: [PATCH 59/66] fix(broker): reconcile_partial_fill counts only the change since the order began A position held before the order counted as filled shares: 75 shares held before a buy of 100 read as 75 filled after a disconnect. The function now takes baseline_position (signed shares held before the order) and compares the change since then, on the order's side, with the pre-disconnect fill. The opposite-side rule from a5c64f9 is unchanged. Public signature change: reconcile_partial_fill gains baseline_position after expected_total. Existing tests pass 0 as the baseline, which keeps their asserted values. New tests: buy and sell with a non-zero baseline. Found by the bot review of PR 86 (thread T23). CHANGELOG: entry moved from Known issues to Fixed, with a Changed note. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- CHANGELOG.md | 12 ++++++- broker/src/ibkr/orders.rs | 69 +++++++++++++++++++++++++++++++-------- 2 files changed, 67 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc86d11..6f9ea66 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -68,6 +68,12 @@ tests, fuzzing or mutation testing. such orders can no longer be cancelled. `SubmitResult.status` is unchanged. *Check your code if* you read order status through `get_order` after an IOC submit. Covered by law 11. +- **nanobook-broker: `ibkr::orders::reconcile_partial_fill` takes the position held + before the order.** The signature is now `reconcile_partial_fill(order_id, symbol, + pre_disconnect_filled, expected_total, baseline_position, current_positions, side)`; + `baseline_position` is the signed shares held in the symbol before the order was + submitted (0 if none). *Check your code if* you call this function: pass the + position you read before submitting the order, or 0 when you held none. - **Level and book totals are exact.** `total_quantity`, `quantity_at_or_better` and snapshot totals cap at `u64::MAX` instead of wrapping or panicking, and `BookSnapshot::imbalance` uses exact side sums. @@ -99,6 +105,11 @@ tests, fuzzing or mutation testing. by the size of that position. It now compares the position on the order's side; a position on the other side is not counted as a fill. Found while writing tests for mutation survivors. +- **nanobook-broker: IBKR reconciliation after a disconnect counted shares held before + the order as filled.** `reconcile_partial_fill` compared the net position with the + filled quantity, so 75 shares held before a buy order read as 75 shares filled. It + now takes the position held before the order and counts only the change since then + on the order's side (see Changed). Found by the bot review of PR 86. - **nanobook-broker: the Binance websocket ignored `testnet`.** It always connected to the production stream. A testnet session now uses `wss://stream.testnet.binance.vision/ws`. @@ -143,7 +154,6 @@ tests, fuzzing or mutation testing. - **nanobook-broker: two Binance `Broker` methods are placeholders.** `open_orders` always returns an empty list, and `cancel_order` by order id is refused: the adapter has an order cache with the symbol of each order, but `cancel_order` does not use it yet. - **nanobook-broker: Binance open-order polling and `reconcile_state` read `openOrders` from `/api/v3/account`.** Binance does not return that field there (open orders come from `/api/v3/openOrders`), so both see an empty list on the real service. The tests feed the field by hand. - **nanobook-broker: an IBKR connection notice (1100 to 1102) does not reach `execute_limit_order` as such.** ibapi 2.12 delivers it with request id -1 to the global order-update stream, so a lost connection is reported when the order's stream ends, not when the notice arrives. -- **nanobook-broker: `ibkr::orders::reconcile_partial_fill` compares the net position, not the change since the order began.** A position held before the order counts as filled shares. - **nanobook-rebalancer: recovery matches open orders by quantity only.** `BrokerOrderStatus` has no symbol or client order id, so one open order of the right size marks an incomplete intent as submitted whatever its symbol. - **nanobook-risk: an empty side prints `-0.0%`.** The "Weight allocation" detail shows `-0.0% long` (or short) when no target is on that side, because an empty `f64` sum is `-0.0` since Rust 1.83. The numbers are zero; only the sign in the text is wrong. diff --git a/broker/src/ibkr/orders.rs b/broker/src/ibkr/orders.rs index bbdadb8..c4e5589 100644 --- a/broker/src/ibkr/orders.rs +++ b/broker/src/ibkr/orders.rs @@ -821,15 +821,18 @@ pub fn reconcile_filled_order(order_id: i32, rejection_reason: &str) -> Result expected, a partial fill occurred during disconnect +/// 3. Subtract the position held before the order (`baseline_position`), and +/// take the change on the order's side: shares filled since the order began +/// 4. If that exceeds the pre-disconnect filled quantity, a partial fill occurred +/// during disconnect /// 5. Update order state to PartialFill with the reconciled quantity /// /// # Important: No Double-Submit @@ -846,6 +849,9 @@ pub fn reconcile_filled_order(order_id: i32, rejection_reason: &str) -> Result Result { info!( - "AUDIT: Reconciling order {} after disconnect - symbol={}, pre_disconnect_filled={}, expected_total={}", - order_id, symbol, pre_disconnect_filled, expected_total + "AUDIT: Reconciling order {} after disconnect - symbol={}, pre_disconnect_filled={}, expected_total={}, baseline_position={}", + order_id, symbol, pre_disconnect_filled, expected_total, baseline_position ); // Find the position for this symbol @@ -881,16 +888,18 @@ pub fn reconcile_partial_fill( match current_position { Some(pos) => { - let current_qty = pos.quantity; + // Change in position since the order began. A position held before + // the order is in the baseline and is not a fill. + let current_qty = pos.quantity - baseline_position; - // For buy orders, positive quantity indicates long position - // For sell orders, negative quantity indicates short position + // For buy orders, a rise in the position is a fill + // For sell orders, a fall in the position is a fill let signed_current_qty = match side { BrokerSide::Buy => current_qty, BrokerSide::Sell => -current_qty, }; - // Compare the position on the order's side against pre-disconnect + // Compare the change on the order's side against pre-disconnect // filled. Signed, not absolute: a buy against a short position (or a // sell against a long one) is not a fill of this order. if signed_current_qty > pre_disconnect_filled { @@ -1163,6 +1172,7 @@ mod tests { symbol, pre_disconnect_filled, expected_total, + 0, &positions, side, ); @@ -1200,6 +1210,7 @@ mod tests { symbol, pre_disconnect_filled, expected_total, + 0, &positions, side, ); @@ -1230,6 +1241,7 @@ mod tests { symbol, pre_disconnect_filled, expected_total, + 0, &positions, side, ); @@ -1258,7 +1270,7 @@ mod tests { }]; let result = - reconcile_partial_fill(1, symbol, 0, 100, &positions, BrokerSide::Buy).unwrap(); + reconcile_partial_fill(1, symbol, 0, 100, 0, &positions, BrokerSide::Buy).unwrap(); assert_eq!(result.order_id, 1); assert_eq!(result.filled_shares, 0); @@ -1269,7 +1281,7 @@ mod tests { fn test_reconcile_partial_fill_nothing_filled_and_no_position_is_failed() { let symbol = nanobook::Symbol::try_new("AAPL").unwrap(); - let result = reconcile_partial_fill(1, symbol, 0, 100, &[], BrokerSide::Buy).unwrap(); + let result = reconcile_partial_fill(1, symbol, 0, 100, 0, &[], BrokerSide::Buy).unwrap(); assert_eq!(result.order_id, 1); assert_eq!(result.filled_shares, 0); @@ -1299,6 +1311,7 @@ mod tests { symbol, pre_disconnect_filled, expected_total, + 0, &positions, side, ); @@ -1328,16 +1341,46 @@ mod tests { // order were filled. The old absolute comparison reported 75 filled. let symbol = nanobook::Symbol::try_new("AAPL").unwrap(); let result = - reconcile_partial_fill(1, symbol, 0, 100, &position(-75), BrokerSide::Buy).unwrap(); + reconcile_partial_fill(1, symbol, 0, 100, 0, &position(-75), BrokerSide::Buy).unwrap(); assert_eq!(result.filled_shares, 0); assert_eq!(result.status, OrderOutcome::PartialFill); } + #[test] + fn test_reconcile_buy_counts_only_the_change_since_the_baseline() { + // 75 shares were held before the order. The position is still 75 after + // the reconnect, so none of the order's shares filled. The old code + // compared the position itself (75) against the filled quantity and + // reported 75 shares filled. + let symbol = nanobook::Symbol::try_new("AAPL").unwrap(); + let result = + reconcile_partial_fill(1, symbol, 0, 100, 75, &position(75), BrokerSide::Buy).unwrap(); + assert_eq!(result.filled_shares, 0); + assert_eq!(result.status, OrderOutcome::Failed); + + // 25 further shares filled during the disconnect: 100 - 75. + let result = + reconcile_partial_fill(1, symbol, 0, 100, 75, &position(100), BrokerSide::Buy).unwrap(); + assert_eq!(result.filled_shares, 25); + assert_eq!(result.status, OrderOutcome::PartialFill); + } + + #[test] + fn test_reconcile_sell_counts_only_the_change_since_the_baseline() { + // A short of 30 was held before the sell order; 20 more were sold. + let symbol = nanobook::Symbol::try_new("AAPL").unwrap(); + let result = + reconcile_partial_fill(1, symbol, 5, 100, -30, &position(-50), BrokerSide::Sell) + .unwrap(); + assert_eq!(result.filled_shares, 20); + assert_eq!(result.status, OrderOutcome::PartialFill); + } + #[test] fn test_reconcile_sell_against_a_long_position_is_not_a_fill() { let symbol = nanobook::Symbol::try_new("AAPL").unwrap(); let result = - reconcile_partial_fill(1, symbol, 50, 100, &position(75), BrokerSide::Sell).unwrap(); + reconcile_partial_fill(1, symbol, 50, 100, 0, &position(75), BrokerSide::Sell).unwrap(); assert_eq!(result.filled_shares, 50); assert_eq!(result.status, OrderOutcome::PartialFill); } From 144a4e1bd3121082b33afdcf21aa6b08384a1572 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:19:05 +0100 Subject: [PATCH 60/66] fix(broker): read Binance open orders from GET /api/v3/openOrders poll_open_orders and reconcile_state read openOrders from /api/v3/account, which Binance does not return there, so both saw an empty list on the real service: every cached order reconciled as missing and each account poll emptied the order cache. BinanceBroker::open_orders was a placeholder that returned an empty list. BinanceClient::open_orders is a new signed GET /api/v3/openOrders call, used by poll_open_orders, reconcile_state and Broker::open_orders. poll_account_info and update_state_from_account_info now refresh positions only; the new BinanceBroker::update_order_cache_from_open_orders fills the order cache. AccountInfo::open_orders is kept but documented as always empty on the real service. Tests: the reconcile_state tests served the open orders inside an /account reply; they now serve a bare array at /openOrders and one asserts the request path. Two tests in binance_rest_fallback.rs pinned the order cache being filled by update_state_from_account_info; they now call update_order_cache_from_open_orders, with unchanged assertions. New tests for open_orders, poll_open_orders and poll_account_info. Found by the bot review of PR 86 (thread T27). CHANGELOG: entry moved from Known issues to Fixed, with a Changed note. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- CHANGELOG.md | 20 ++- broker/src/binance/client.rs | 26 +++- broker/src/binance/mod.rs | 211 ++++++++++++++++++-------- broker/src/binance/types.rs | 2 + broker/tests/binance_rest_fallback.rs | 8 +- 5 files changed, 200 insertions(+), 67 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f9ea66..9b875ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -74,6 +74,16 @@ tests, fuzzing or mutation testing. `baseline_position` is the signed shares held in the symbol before the order was submitted (0 if none). *Check your code if* you call this function: pass the position you read before submitting the order, or 0 when you held none. +- **nanobook-broker: Binance open orders come from `GET /api/v3/openOrders`.** + `BinanceClient::open_orders` is new. `BinanceBroker::open_orders` now returns the + open orders (it returned an empty list); `poll_open_orders` and `reconcile_state` + read the new endpoint; `poll_account_info` and `update_state_from_account_info` + refresh positions only and no longer touch the order cache. New + `BinanceBroker::update_order_cache_from_open_orders` fills the cache from a list of + `OrderInfo`. `AccountInfo::open_orders` stays but is always empty on the real + service. *Check your code if* you read the order cache after `poll_account_info`, or + fed `update_state_from_account_info` an `AccountInfo` with `open_orders`: call + `poll_open_orders` or `update_order_cache_from_open_orders` for the orders. - **Level and book totals are exact.** `total_quantity`, `quantity_at_or_better` and snapshot totals cap at `u64::MAX` instead of wrapping or panicking, and `BookSnapshot::imbalance` uses exact side sums. @@ -105,6 +115,13 @@ tests, fuzzing or mutation testing. by the size of that position. It now compares the position on the order's side; a position on the other side is not counted as a fill. Found while writing tests for mutation survivors. +- **nanobook-broker: Binance open orders were always empty on the real service.** + Open-order polling and `reconcile_state` read `openOrders` from `/api/v3/account`, + which Binance does not return there, so both saw no open orders; every cached order + then read as missing, and each account poll emptied the order cache. + `BinanceBroker::open_orders` was a placeholder that returned an empty list. All three + now use a signed `GET /api/v3/openOrders` (see Changed). Found by the bot review of + PR 86. - **nanobook-broker: IBKR reconciliation after a disconnect counted shares held before the order as filled.** `reconcile_partial_fill` compared the net position with the filled quantity, so 75 shares held before a buy order read as 75 shares filled. It @@ -151,8 +168,7 @@ tests, fuzzing or mutation testing. - **nanobook-rebalancer: `constraints.min_trade_usd` in target.json does not change the run minimum.** The run still reads `config.risk.min_trade_usd`. - **nanobook-rebalancer: `TargetSpec::window_id` hashes with `DefaultHasher`.** The id can change after a Rust upgrade, so a cron window can fire twice. - **nanobook-rebalancer: without `write_ahead_logging`, the runner does not write `order_submitted`.** Graceful kill then cannot report a dangling order. -- **nanobook-broker: two Binance `Broker` methods are placeholders.** `open_orders` always returns an empty list, and `cancel_order` by order id is refused: the adapter has an order cache with the symbol of each order, but `cancel_order` does not use it yet. -- **nanobook-broker: Binance open-order polling and `reconcile_state` read `openOrders` from `/api/v3/account`.** Binance does not return that field there (open orders come from `/api/v3/openOrders`), so both see an empty list on the real service. The tests feed the field by hand. +- **nanobook-broker: the Binance `Broker::cancel_order` by order id is a placeholder.** It is refused: the adapter has an order cache with the symbol of each order, but `cancel_order` does not use it yet. - **nanobook-broker: an IBKR connection notice (1100 to 1102) does not reach `execute_limit_order` as such.** ibapi 2.12 delivers it with request id -1 to the global order-update stream, so a lost connection is reported when the order's stream ends, not when the notice arrives. - **nanobook-rebalancer: recovery matches open orders by quantity only.** `BrokerOrderStatus` has no symbol or client order id, so one open order of the right size marks an incomplete intent as submitted whatever its symbol. - **nanobook-risk: an empty side prints `-0.0%`.** The "Weight allocation" detail shows `-0.0% long` (or short) when no target is on that side, because an empty `f64` sum is `-0.0` since Rust 1.83. The numbers are zero; only the sign in the text is wrong. diff --git a/broker/src/binance/client.rs b/broker/src/binance/client.rs index 0755f52..a64a9f7 100644 --- a/broker/src/binance/client.rs +++ b/broker/src/binance/client.rs @@ -6,7 +6,7 @@ use log::debug; use reqwest::blocking::Client; use super::auth; -use super::types::{AccountInfo, BookTicker, OrderResponse}; +use super::types::{AccountInfo, BookTicker, OrderInfo, OrderResponse}; use crate::error::BrokerError; /// Validate that a parameter value is safe for URL query strings. @@ -132,6 +132,30 @@ impl BinanceClient { .map_err(|e| BrokerError::Connection(format!("failed to parse account: {e}"))) } + /// Get every open order of the account (GET /api/v3/openOrders). + /// + /// `GET /api/v3/account` does not list open orders; this endpoint does. + pub fn open_orders(&self) -> Result, BrokerError> { + let timestamp = current_timestamp_ms()?; + let query = format!("timestamp={timestamp}"); + let signature = auth::sign(&query, &self.secret_key)?; + let url = format!( + "{}/api/v3/openOrders?{query}&signature={signature}", + self.base_url + ); + + let resp = self + .client + .get(&url) + .header("X-MBX-APIKEY", &self.api_key) + .send() + .map_err(|e| BrokerError::Connection(format!("open orders request failed: {e}")))?; + + let resp = check_response(resp, "open orders", BrokerError::Connection)?; + resp.json::>() + .map_err(|e| BrokerError::Connection(format!("failed to parse open orders: {e}"))) + } + /// Submit a new order (POST /api/v3/order). #[allow(clippy::too_many_arguments)] pub fn submit_order( diff --git a/broker/src/binance/mod.rs b/broker/src/binance/mod.rs index 5876189..4ce39de 100644 --- a/broker/src/binance/mod.rs +++ b/broker/src/binance/mod.rs @@ -49,6 +49,19 @@ pub struct CachedOrder { pub submitted_at: DateTime, } +/// Map a Binance order status string to an [`OrderState`]. +fn order_state_from_binance(status: &str) -> OrderState { + match status { + "NEW" => OrderState::Submitted, + "PARTIALLY_FILLED" => OrderState::PartiallyFilled, + "FILLED" => OrderState::Filled, + "CANCELED" => OrderState::Cancelled, + "REJECTED" => OrderState::Rejected, + "EXPIRED" => OrderState::Cancelled, + _ => OrderState::Submitted, + } +} + /// Binance spot broker implementing the generic Broker trait. /// /// Uses REST API for all operations. Blocking (sync) via reqwest::blocking. @@ -347,18 +360,16 @@ impl BinanceBroker { Ok(()) } - /// Poll open orders through REST and refresh the local order cache. - /// - /// Binance's account-info response carries the open-orders snapshot used by - /// this simplified fallback path. + /// Poll open orders through REST (`GET /api/v3/openOrders`) and refresh the + /// local order cache. pub fn poll_open_orders(&self) -> Result<(), BrokerError> { let last_poll = self.last_orders_poll(); if !self.should_poll(last_poll) { return Ok(()); } - let info = self.require_client()?.account_info()?; - self.update_order_cache_from_account_info(&info)?; + let open_orders = self.require_client()?.open_orders()?; + self.update_order_cache_from_open_orders(&open_orders); *self .last_orders_poll .lock() @@ -366,7 +377,10 @@ impl BinanceBroker { Ok(()) } - /// Apply a REST account-info snapshot to local fallback caches. + /// Apply a REST account-info snapshot to the local position cache. + /// + /// The order cache is not touched: `GET /api/v3/account` does not list open + /// orders. Use [`update_order_cache_from_open_orders`](Self::update_order_cache_from_open_orders). pub fn update_state_from_account_info( &self, info: &types::AccountInfo, @@ -395,21 +409,19 @@ impl BinanceBroker { .position_cache .lock() .expect("Binance position cache mutex poisoned") = positions; - self.update_order_cache_from_account_info(info)?; Ok(()) } - fn update_order_cache_from_account_info( - &self, - info: &types::AccountInfo, - ) -> Result<(), BrokerError> { + /// Replace the local order cache with a snapshot of the open orders + /// (`BinanceClient::open_orders`). + pub fn update_order_cache_from_open_orders(&self, open_orders: &[types::OrderInfo]) { let mut cache = self .order_cache .lock() .expect("Binance order cache mutex poisoned"); cache.orders.clear(); - for order in &info.open_orders { + for order in open_orders { let base_symbol = order .symbol .strip_suffix(&self.quote_asset) @@ -421,15 +433,7 @@ impl BinanceBroker { "SELL" => BrokerSide::Sell, _ => BrokerSide::Buy, }; - let status = match order.status.as_str() { - "NEW" => OrderState::Submitted, - "PARTIALLY_FILLED" => OrderState::PartiallyFilled, - "FILLED" => OrderState::Filled, - "CANCELED" => OrderState::Cancelled, - "REJECTED" => OrderState::Rejected, - "EXPIRED" => OrderState::Cancelled, - _ => OrderState::Submitted, - }; + let status = order_state_from_binance(&order.status); let quantity = parse_f64_or_warn(&order.orig_qty, "binance order.origQty") as i64; cache.orders.insert( OrderId(order.order_id), @@ -444,8 +448,6 @@ impl BinanceBroker { }, ); } - - Ok(()) } pub fn load_cache_from_disk(&self, path: &Path) -> Result<(), BrokerError> { @@ -514,7 +516,7 @@ impl BinanceBroker { /// Reconcile local state with Binance account state. /// - /// Queries account info from Binance and compares against local order cache + /// Queries the open orders from Binance (`GET /api/v3/openOrders`) and compares against local order cache /// to detect discrepancies such as orphan orders, missing orders, and position mismatches. /// /// # Returns @@ -522,7 +524,7 @@ impl BinanceBroker { /// * `Err(BrokerError)` - If query fails or not connected pub fn reconcile_state(&mut self) -> Result { let client = self.require_client()?; - let info = client.account_info()?; + let open_orders = client.open_orders()?; let mut discrepancies = Vec::new(); @@ -536,7 +538,7 @@ impl BinanceBroker { }; // Check for orphan orders (orders on broker but not in cache) - for broker_order in &info.open_orders { + for broker_order in &open_orders { let order_id = OrderId(broker_order.order_id); let found = cached_orders .iter() @@ -548,8 +550,7 @@ impl BinanceBroker { // Check for missing orders (orders in cache but not on broker) for (order_id, cached_order) in &cached_orders { - let found = info - .open_orders + let found = open_orders .iter() .any(|broker_order| broker_order.order_id == order_id.0); if !found && cached_order.status == OrderState::Submitted { @@ -560,21 +561,13 @@ impl BinanceBroker { } // Check for order status mismatches - for broker_order in &info.open_orders { + for broker_order in &open_orders { let order_id = OrderId(broker_order.order_id); if let Some((_, cached_order)) = cached_orders .iter() .find(|(id, _)| id.0 == broker_order.order_id) { - let broker_status = match broker_order.status.as_str() { - "NEW" => OrderState::Submitted, - "PARTIALLY_FILLED" => OrderState::PartiallyFilled, - "FILLED" => OrderState::Filled, - "CANCELED" => OrderState::Cancelled, - "REJECTED" => OrderState::Rejected, - "EXPIRED" => OrderState::Cancelled, - _ => OrderState::Submitted, - }; + let broker_status = order_state_from_binance(&broker_order.status); if cached_order.status != broker_status { discrepancies.push(Discrepancy::OrderStatusMismatch { order_id, @@ -823,10 +816,24 @@ impl Broker for BinanceBroker { } fn open_orders(&self) -> Result, BrokerError> { - // Binance open orders query requires GET /api/v3/openOrders endpoint. - // For now return empty list. Full implementation requires - // querying via the client and parsing the response. - Ok(Vec::new()) + let client = self.require_client()?; + Ok(client + .open_orders()? + .iter() + .map(|order| { + let orig = parse_f64_or_warn(&order.orig_qty, "binance order.origQty") as u64; + let executed = + parse_f64_or_warn(&order.executed_qty, "binance order.executedQty") as u64; + BrokerOrderStatus { + id: OrderId(order.order_id), + status: order_state_from_binance(&order.status), + filled_quantity: executed, + remaining_quantity: orig.saturating_sub(executed), + // openOrders reports no average price. + avg_fill_price_cents: 0, + } + }) + .collect()) } fn cancel_order(&self, id: OrderId) -> Result<(), BrokerError> { @@ -929,11 +936,14 @@ mod tests { ) } - fn account_json(balances: &str, open_orders: &[String]) -> String { - format!( - r#"{{"balances":[{balances}],"openOrders":[{}],"canTrade":true}}"#, - open_orders.join(",") - ) + /// Body of `GET /api/v3/account`: Binance returns no open orders there. + fn account_json(balances: &str) -> String { + format!(r#"{{"balances":[{balances}],"canTrade":true}}"#) + } + + /// Body of `GET /api/v3/openOrders`: a bare JSON array. + fn open_orders_json(open_orders: &[String]) -> String { + format!("[{}]", open_orders.join(",")) } fn cache(broker: &BinanceBroker, id: u64, status: OrderState) { @@ -995,7 +1005,7 @@ mod tests { #[test] fn positions_sum_free_and_locked_and_skip_empty_balances() { - let (url, _) = serve(vec![account_json(BALANCES, &[])]); + let (url, _) = serve(vec![account_json(BALANCES)]); let broker = connected_to(&url); let positions = broker.positions().unwrap(); @@ -1015,7 +1025,7 @@ mod tests { #[test] fn account_equity_is_the_quote_asset_balance_in_cents() { - let (url, _) = serve(vec![account_json(BALANCES, &[])]); + let (url, _) = serve(vec![account_json(BALANCES)]); let broker = connected_to(&url); let account = broker.account().unwrap(); @@ -1031,16 +1041,23 @@ mod tests { #[test] fn reconcile_state_reports_nothing_when_cache_and_broker_agree() { - let (url, _) = serve(vec![account_json( - "", - &[open_order_json(1, "NEW"), open_order_json(2, "FILLED")], - )]); + let (url, seen) = serve(vec![open_orders_json(&[ + open_order_json(1, "NEW"), + open_order_json(2, "FILLED"), + ])]); let mut broker = connected_to(&url); cache(&broker, 1, OrderState::Submitted); cache(&broker, 2, OrderState::Filled); let report = broker.reconcile_state().unwrap(); + // Binance lists open orders at /openOrders, not in the /account reply. + let requests = seen.lock().unwrap(); + assert!( + requests[0].starts_with("GET /api/v3/openOrders?"), + "got {}", + requests[0] + ); assert!( report.discrepancies.is_empty(), "{:?}", @@ -1052,10 +1069,10 @@ mod tests { #[test] fn reconcile_state_reports_a_broker_order_missing_from_the_cache_as_orphan() { - let (url, _) = serve(vec![account_json( - "", - &[open_order_json(1, "NEW"), open_order_json(9, "NEW")], - )]); + let (url, _) = serve(vec![open_orders_json(&[ + open_order_json(1, "NEW"), + open_order_json(9, "NEW"), + ])]); let mut broker = connected_to(&url); cache(&broker, 1, OrderState::Submitted); cache(&broker, 2, OrderState::Filled); @@ -1074,7 +1091,7 @@ mod tests { #[test] fn reconcile_state_reports_a_submitted_cached_order_absent_from_the_broker_as_missing() { - let (url, _) = serve(vec![account_json("", &[open_order_json(1, "NEW")])]); + let (url, _) = serve(vec![open_orders_json(&[open_order_json(1, "NEW")])]); let mut broker = connected_to(&url); cache(&broker, 1, OrderState::Submitted); cache(&broker, 2, OrderState::Filled); @@ -1107,7 +1124,7 @@ mod tests { .zip(11u64..) .map(|(status, id)| open_order_json(id, status)) .collect(); - let (url, _) = serve(vec![account_json("", &open)]); + let (url, _) = serve(vec![open_orders_json(&open)]); let mut broker = connected_to(&url); for id in 11..=15 { cache(&broker, id, OrderState::Submitted); @@ -1134,6 +1151,80 @@ mod tests { assert!(report.has_critical_issues); } + // ---- open orders --------------------------------------------------- + + #[test] + fn open_orders_reads_the_open_orders_endpoint() { + let partial = r#"{"symbol":"BTCUSDT","orderId":8,"status":"PARTIALLY_FILLED","side":"SELL","origQty":"5","executedQty":"2"}"#; + let (url, seen) = serve(vec![open_orders_json(&[ + open_order_json(7, "NEW"), + partial.to_string(), + ])]); + let broker = connected_to(&url); + + let orders = broker.open_orders().unwrap(); + + let rows: Vec<(u64, OrderState, u64, u64)> = orders + .iter() + .map(|o| (o.id.0, o.status, o.filled_quantity, o.remaining_quantity)) + .collect(); + assert_eq!( + rows, + vec![ + (7, OrderState::Submitted, 0, 1), + (8, OrderState::PartiallyFilled, 2, 3), + ] + ); + let requests = seen.lock().unwrap(); + assert!( + requests[0].starts_with("GET /api/v3/openOrders?"), + "got {}", + requests[0] + ); + assert!(requests[0].contains("signature="), "got {}", requests[0]); + } + + #[test] + fn open_orders_is_empty_when_binance_lists_none() { + let (url, _) = serve(vec![open_orders_json(&[])]); + let broker = connected_to(&url); + + assert!(broker.open_orders().unwrap().is_empty()); + } + + #[test] + fn poll_open_orders_refreshes_the_cache_from_the_open_orders_endpoint() { + let (url, seen) = serve(vec![open_orders_json(&[open_order_json(21, "NEW")])]); + let broker = connected_to(&url); + cache(&broker, 5, OrderState::Submitted); + + broker.poll_open_orders().unwrap(); + + let cached = broker.get_cached_order(OrderId(21)).unwrap(); + assert_eq!(cached.status, OrderState::Submitted); + assert_eq!(cached.quantity, 1); + // The snapshot replaces the cache: order 5 is not open at Binance. + assert!(broker.get_cached_order(OrderId(5)).is_none()); + assert!( + seen.lock().unwrap()[0].starts_with("GET /api/v3/openOrders?"), + "got {}", + seen.lock().unwrap()[0] + ); + } + + #[test] + fn poll_account_info_refreshes_positions_and_leaves_the_order_cache() { + // /account lists no open orders, so it must not empty the order cache. + let (url, _) = serve(vec![account_json(BALANCES)]); + let broker = connected_to(&url); + cache(&broker, 5, OrderState::Submitted); + + broker.poll_account_info().unwrap(); + + assert_eq!(broker.cached_positions().len(), 2); + assert!(broker.get_cached_order(OrderId(5)).is_some()); + } + // ---- submit_order_with_sequence ------------------------------------ #[test] diff --git a/broker/src/binance/types.rs b/broker/src/binance/types.rs index 2ee9268..092df12 100644 --- a/broker/src/binance/types.rs +++ b/broker/src/binance/types.rs @@ -43,6 +43,8 @@ pub struct AccountInfo { pub balances: Vec, #[serde(default)] pub positions: Vec, + /// Not returned by `GET /api/v3/account`; the field stays empty on the real + /// service. Open orders come from `BinanceClient::open_orders`. #[serde(default)] pub open_orders: Vec, #[serde(default)] diff --git a/broker/tests/binance_rest_fallback.rs b/broker/tests/binance_rest_fallback.rs index 563c97c..5c687ed 100644 --- a/broker/tests/binance_rest_fallback.rs +++ b/broker/tests/binance_rest_fallback.rs @@ -51,9 +51,9 @@ mod binance_rest_fallback_tests { let broker = BinanceBroker::new("api-key", "secret-key", true) .with_connection_mode(ConnectionMode::Rest); - broker - .update_state_from_account_info(&account_info_fixture()) - .unwrap(); + let info = account_info_fixture(); + broker.update_state_from_account_info(&info).unwrap(); + broker.update_order_cache_from_open_orders(&info.open_orders); let positions = broker.cached_positions(); assert_eq!(positions.len(), 2); @@ -170,7 +170,7 @@ mod binance_rest_fallback_tests { }; let broker = BinanceBroker::new("api-key", "secret-key", true); - broker.update_state_from_account_info(&info).unwrap(); + broker.update_order_cache_from_open_orders(&info.open_orders); let expected = [ (1, "BTC", BrokerSide::Sell, OrderState::Submitted, 3), From ac0f321efe52dbb2b2c44ef7475f5a6c431bf323 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:29:19 +0100 Subject: [PATCH 61/66] fix(rebalancer): recovery matches open orders on symbol and quantity reconcile_order_intent and reconcile_incomplete_intents matched an open order to an incomplete intent by quantity alone, because BrokerOrderStatus carried no symbol: any open order of the right size marked the intent as submitted, whatever its symbol. BrokerOrderStatus gains symbol: Option. IBKR fills it from the order's contract in open_orders (kept apart from the status rows, since an OrderStatus message replaces the row and carries no symbol), Binance from the trading pair minus the quote asset, MockBroker from the submitted order. order_status leaves it None. Recovery matches only an order whose symbol equals the intent's; an order with no symbol matches nothing. Neither adapter gives a client order id for an open order, so the id is not matched. compare_broker_state now reports the broker's symbol on an orphan instead of UNKNOWN. The check that an order claimed by two intents is given to neither is removed: an order has one symbol and recovery holds one incomplete intent per symbol, so it can no longer fire. Two open orders of the same symbol and quantity still fail the intent. Tests: new reconcile_order_intent_ignores_an_order_of_another_symbol, plus a symbol on every BrokerOrderStatus the existing tests build (AAPL where the test meant AAPL, so their values stand). Two tests in mutation_recovery.rs pinned the quantity-only limitation and are changed to the corrected values: one_open_order_does_not_submit_two_intents_of_the_same_quantity now has the MSFT order go to the MSFT intent and the AAPL intent record not-found; two_open_orders_of_one_quantity_match_neither_intent now has two open orders per symbol, so each intent stays ambiguous and the asserted outcome is unchanged. Found by the bot review of PR 86 (thread T12). CHANGELOG: entry moved from Known issues to Fixed, with a Changed note. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- CHANGELOG.md | 16 ++- broker/src/binance/mod.rs | 31 ++++-- broker/src/ibkr/client.rs | 15 ++- broker/src/ibkr/mod.rs | 2 + broker/src/ibkr/orders.rs | 42 +++++++- broker/src/lib.rs | 1 + broker/src/mock.rs | 13 ++- broker/src/types.rs | 4 + broker/tests/mock_binance.rs | 2 + rebalancer/src/kill.rs | 8 ++ rebalancer/src/recovery.rs | 97 +++++++++++++++---- .../tests/crash_injection_integration.rs | 1 + rebalancer/tests/mutation_recovery.rs | 56 ++++++----- rebalancer/tests/recovery_integration.rs | 4 + rebalancer/tests/verification_tests.rs | 1 + 15 files changed, 234 insertions(+), 59 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b875ca..5b7fcb0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -68,6 +68,16 @@ tests, fuzzing or mutation testing. such orders can no longer be cancelled. `SubmitResult.status` is unchanged. *Check your code if* you read order status through `get_order` after an IOC submit. Covered by law 11. +- **nanobook-broker: `BrokerOrderStatus` has a `symbol`.** The new field + `symbol: Option` is `Some` in `open_orders` for the IBKR adapter (from the + order's contract), the Binance adapter (the trading pair without the quote asset) + and `MockBroker` (the symbol of the submitted order). It is `None` in `order_status` + (a lookup by order id alone) and when `Symbol` cannot hold the name. IBKR and Binance + give no client order id for an open order, so recovery matches on symbol and + quantity. *Check your code if* you build `BrokerOrderStatus` with a struct literal + or implement `Broker`: set `symbol` (`None` if you do not know it). Code that feeds + recovery open orders through `MockBroker::set_open_order_statuses` must set the + symbol, or recovery finds no match. - **nanobook-broker: `ibkr::orders::reconcile_partial_fill` takes the position held before the order.** The signature is now `reconcile_partial_fill(order_id, symbol, pre_disconnect_filled, expected_total, baseline_position, current_positions, side)`; @@ -149,6 +159,11 @@ tests, fuzzing or mutation testing. - **nanobook-rebalancer: two cron runs could both pass the completed-window check.** The PID-file lock is now taken before the check, so a second caller that finds the lock held gets "in use by another rebalancer" rather than an idempotency rejection. `--kill` also no longer reads an empty PID file while a run starts: the PID is written to a temporary file and renamed. - **nanobook-broker: a Binance websocket `set_max_reconnect_attempts` above 64 overflowed the backoff.** The delay stays 16 s from the fifth attempt on. - **nanobook-rebalancer: recovery matched the first open order with remaining quantity.** It now matches an open order whose filled plus remaining quantity equals the incomplete intent's quantity; an order that two intents match is given to neither. +- **nanobook-rebalancer: recovery matched open orders by quantity only.** An open order + of the right size marked an incomplete intent as submitted whatever its symbol, + because `BrokerOrderStatus` had no symbol. It now matches on symbol and quantity + (see Changed). An order with no known symbol matches no intent, so its intent is + recorded as not found at the broker. Found by the bot review of PR 86. ### Added @@ -170,7 +185,6 @@ tests, fuzzing or mutation testing. - **nanobook-rebalancer: without `write_ahead_logging`, the runner does not write `order_submitted`.** Graceful kill then cannot report a dangling order. - **nanobook-broker: the Binance `Broker::cancel_order` by order id is a placeholder.** It is refused: the adapter has an order cache with the symbol of each order, but `cancel_order` does not use it yet. - **nanobook-broker: an IBKR connection notice (1100 to 1102) does not reach `execute_limit_order` as such.** ibapi 2.12 delivers it with request id -1 to the global order-update stream, so a lost connection is reported when the order's stream ends, not when the notice arrives. -- **nanobook-rebalancer: recovery matches open orders by quantity only.** `BrokerOrderStatus` has no symbol or client order id, so one open order of the right size marks an incomplete intent as submitted whatever its symbol. - **nanobook-risk: an empty side prints `-0.0%`.** The "Weight allocation" detail shows `-0.0% long` (or short) when no target is on that side, because an empty `f64` sum is `-0.0` since Rust 1.83. The numbers are zero; only the sign in the text is wrong. ### Security diff --git a/broker/src/binance/mod.rs b/broker/src/binance/mod.rs index 4ce39de..ccc4d64 100644 --- a/broker/src/binance/mod.rs +++ b/broker/src/binance/mod.rs @@ -252,6 +252,12 @@ impl BinanceBroker { format!("{}{}", symbol.as_str(), self.quote_asset) } + /// Base asset of a Binance trading pair ("BTCUSDT" gives "BTC"), or `None` + /// when `Symbol` cannot hold it. + fn base_symbol_of(&self, pair: &str) -> Option { + Symbol::try_new(pair.strip_suffix(&self.quote_asset).unwrap_or(pair)) + } + fn require_client(&self) -> Result<&BinanceClient, BrokerError> { self.client.as_ref().ok_or(BrokerError::NotConnected) } @@ -422,11 +428,7 @@ impl BinanceBroker { cache.orders.clear(); for order in open_orders { - let base_symbol = order - .symbol - .strip_suffix(&self.quote_asset) - .unwrap_or(&order.symbol); - let Some(symbol) = Symbol::try_new(base_symbol) else { + let Some(symbol) = self.base_symbol_of(&order.symbol) else { continue; }; let side = match order.side.as_str() { @@ -808,6 +810,7 @@ impl Broker for BinanceBroker { // Full implementation would need a local order cache. Ok(BrokerOrderStatus { id, + symbol: None, status: OrderState::Submitted, filled_quantity: 0, remaining_quantity: 0, @@ -826,6 +829,7 @@ impl Broker for BinanceBroker { parse_f64_or_warn(&order.executed_qty, "binance order.executedQty") as u64; BrokerOrderStatus { id: OrderId(order.order_id), + symbol: self.base_symbol_of(&order.symbol), status: order_state_from_binance(&order.status), filled_quantity: executed, remaining_quantity: orig.saturating_sub(executed), @@ -1164,15 +1168,24 @@ mod tests { let orders = broker.open_orders().unwrap(); - let rows: Vec<(u64, OrderState, u64, u64)> = orders + let rows: Vec<(u64, Option, OrderState, u64, u64)> = orders .iter() - .map(|o| (o.id.0, o.status, o.filled_quantity, o.remaining_quantity)) + .map(|o| { + ( + o.id.0, + o.symbol, + o.status, + o.filled_quantity, + o.remaining_quantity, + ) + }) .collect(); + let btc = Some(Symbol::new("BTC")); assert_eq!( rows, vec![ - (7, OrderState::Submitted, 0, 1), - (8, OrderState::PartiallyFilled, 2, 3), + (7, btc, OrderState::Submitted, 0, 1), + (8, btc, OrderState::PartiallyFilled, 2, 3), ] ); let requests = seen.lock().unwrap(); diff --git a/broker/src/ibkr/client.rs b/broker/src/ibkr/client.rs index 0dfc06a..024ad8e 100644 --- a/broker/src/ibkr/client.rs +++ b/broker/src/ibkr/client.rs @@ -347,10 +347,17 @@ impl IbkrClient { .map_err(|e| BrokerError::Connection(format!("failed to request open orders: {e}")))?; let mut statuses = HashMap::new(); + // Only OrderData carries the symbol. An OrderStatus for the same order + // can come before or after it and replaces the row, so the symbols are + // kept apart and put back at the end. + let mut symbols = HashMap::new(); for update in subscription { match update { Orders::OrderData(order_data) => { let status = broker_order_status_from_order_data(&order_data)?; + if let Some(symbol) = status.symbol { + symbols.insert(status.id.0, symbol); + } statuses.insert(status.id.0, status); } Orders::OrderStatus(order_status) => { @@ -373,7 +380,13 @@ impl IbkrClient { } } - Ok(statuses.into_values().collect()) + Ok(statuses + .into_values() + .map(|mut status| { + status.symbol = symbols.get(&status.id.0).copied(); + status + }) + .collect()) } /// Fetch account summary (equity, cash, buying power). diff --git a/broker/src/ibkr/mod.rs b/broker/src/ibkr/mod.rs index 25aeab0..31edd35 100644 --- a/broker/src/ibkr/mod.rs +++ b/broker/src/ibkr/mod.rs @@ -277,6 +277,7 @@ impl Broker for IbkrBroker { // storing active order subscriptions. Ok(BrokerOrderStatus { id, + symbol: None, status: OrderState::Submitted, filled_quantity: 0, remaining_quantity: 0, @@ -336,6 +337,7 @@ mod tests { fn open(id: u64, status: OrderState) -> BrokerOrderStatus { BrokerOrderStatus { id: OrderId(id), + symbol: None, status, filled_quantity: 0, remaining_quantity: 0, diff --git a/broker/src/ibkr/orders.rs b/broker/src/ibkr/orders.rs index c4e5589..cfdcf4f 100644 --- a/broker/src/ibkr/orders.rs +++ b/broker/src/ibkr/orders.rs @@ -138,6 +138,7 @@ pub fn broker_order_status_from_ibkr_parts( Ok(BrokerOrderStatus { id: OrderId(order_id as u64), + symbol: None, status: mapped, filled_quantity, remaining_quantity, @@ -151,13 +152,15 @@ pub fn broker_order_status_from_ibkr_parts( pub fn broker_order_status_from_order_data( order_data: &OrderData, ) -> Result { - broker_order_status_from_ibkr_parts( + let mut status = broker_order_status_from_ibkr_parts( order_data.order_id, &order_data.order_state.status, 0.0, order_data.order.total_quantity, 0.0, - ) + )?; + status.symbol = nanobook::Symbol::try_new(&order_data.contract.symbol.0); + Ok(status) } /// Deduplication key for order-status callbacks. @@ -1385,6 +1388,41 @@ mod tests { assert_eq!(result.status, OrderOutcome::PartialFill); } + #[test] + fn test_order_data_status_carries_the_contract_symbol() { + let data = OrderData { + order_id: 5, + contract: Contract { + symbol: ibapi::contracts::Symbol::new("AAPL"), + ..Contract::default() + }, + order: Order { + total_quantity: 100.0, + ..Order::default() + }, + ..OrderData::default() + }; + + let status = broker_order_status_from_order_data(&data).unwrap(); + + assert_eq!(status.id, OrderId(5)); + assert_eq!(status.symbol, Some(nanobook::Symbol::new("AAPL"))); + assert_eq!(status.remaining_quantity, 100); + + // A symbol that `Symbol` cannot hold (over 8 bytes) is left out. + let long = OrderData { + contract: Contract { + symbol: ibapi::contracts::Symbol::new("ABCDEFGHIJ"), + ..Contract::default() + }, + ..OrderData::default() + }; + assert_eq!( + broker_order_status_from_order_data(&long).unwrap().symbol, + None + ); + } + #[test] fn test_connection_lost_error_variant() { // Test that ConnectionLost error variant works correctly diff --git a/broker/src/lib.rs b/broker/src/lib.rs index a4f53d5..92f94ae 100644 --- a/broker/src/lib.rs +++ b/broker/src/lib.rs @@ -64,6 +64,7 @@ use nanobook::Symbol; /// fn order_status(&self, id: OrderId) -> Result { /// Ok(BrokerOrderStatus { /// id, +/// symbol: None, /// status: OrderState::Submitted, /// filled_quantity: 0, /// remaining_quantity: 10, diff --git a/broker/src/mock.rs b/broker/src/mock.rs index 669ad42..8de0236 100644 --- a/broker/src/mock.rs +++ b/broker/src/mock.rs @@ -117,7 +117,7 @@ pub struct MockBroker { cash_cents: i64, next_order_id: AtomicU64, submitted_orders: Mutex>, - open_orders: Mutex>, + open_orders: Mutex>, /// When set, `open_orders` returns these rows instead of `fill_mode`. open_order_statuses: Mutex>>, } @@ -224,7 +224,7 @@ impl Broker for MockBroker { self.open_orders .lock() .expect("open_orders mutex poisoned") - .push(id); + .push((id, order.symbol)); Ok(id) } } @@ -239,6 +239,7 @@ impl Broker for MockBroker { Ok(BrokerOrderStatus { id, + symbol: None, status, filled_quantity: filled, remaining_quantity: remaining, @@ -266,8 +267,9 @@ impl Broker for MockBroker { Ok(open_ids .iter() .copied() - .map(|id| BrokerOrderStatus { + .map(|(id, symbol)| BrokerOrderStatus { id, + symbol: Some(symbol), status, filled_quantity: filled, remaining_quantity: remaining, @@ -284,7 +286,7 @@ impl Broker for MockBroker { self.open_orders .lock() .expect("open_orders mutex poisoned") - .retain(|&oid| oid != id); + .retain(|&(oid, _)| oid != id); // Rows set by `set_open_order_statuses` are open orders too. if let Some(rows) = self .open_order_statuses @@ -482,6 +484,7 @@ mod tests { let ids: Vec = open.iter().map(|o| o.id).collect(); assert_eq!(ids, vec![OrderId(1), OrderId(2)]); for order in &open { + assert_eq!(order.symbol, Some(aapl())); assert_eq!(order.status, OrderState::Filled); assert_eq!(order.filled_quantity, 100); assert_eq!(order.remaining_quantity, 0); @@ -512,6 +515,7 @@ mod tests { broker.connect().unwrap(); let row = |id: u64| BrokerOrderStatus { id: OrderId(id), + symbol: None, status: OrderState::Submitted, filled_quantity: 0, remaining_quantity: 50, @@ -534,6 +538,7 @@ mod tests { // 25 of 80 shares filled; FillMode alone would report 100/0 rows. broker.set_open_order_statuses(vec![BrokerOrderStatus { id: OrderId(7), + symbol: None, status: OrderState::PartiallyFilled, filled_quantity: 25, remaining_quantity: 55, diff --git a/broker/src/types.rs b/broker/src/types.rs index d18a1db..0ff2d4d 100644 --- a/broker/src/types.rs +++ b/broker/src/types.rs @@ -205,6 +205,10 @@ pub struct OrderId(pub u64); #[derive(Debug, Clone)] pub struct BrokerOrderStatus { pub id: OrderId, + /// Symbol of the order, or `None` when the adapter cannot tell (a status + /// query by order id alone, or a symbol that `Symbol` cannot hold). An + /// order with no symbol never matches a symbol in recovery. + pub symbol: Option, pub status: OrderState, pub filled_quantity: u64, pub remaining_quantity: u64, diff --git a/broker/tests/mock_binance.rs b/broker/tests/mock_binance.rs index 625e692..0174d92 100644 --- a/broker/tests/mock_binance.rs +++ b/broker/tests/mock_binance.rs @@ -449,6 +449,7 @@ impl Broker for MockBroker { Ok(BrokerOrderStatus { id, + symbol: None, status: order.status, filled_quantity: match order.status { OrderState::Filled => quantity, @@ -481,6 +482,7 @@ impl Broker for MockBroker { result.push(BrokerOrderStatus { id: OrderId(order_id), + symbol: None, status: order.status, filled_quantity: 0, remaining_quantity: quantity, diff --git a/rebalancer/src/kill.rs b/rebalancer/src/kill.rs index cd13956..7350e01 100644 --- a/rebalancer/src/kill.rs +++ b/rebalancer/src/kill.rs @@ -670,6 +670,7 @@ mod tests { .iter() .map(|(id, status, remaining_quantity)| BrokerOrderStatus { id: OrderId(*id), + symbol: None, status: *status, filled_quantity: 0, remaining_quantity: *remaining_quantity, @@ -714,6 +715,7 @@ mod tests { fn order_status(&self, id: OrderId) -> std::result::Result { Ok(BrokerOrderStatus { id, + symbol: None, status: OrderState::Submitted, filled_quantity: 0, remaining_quantity: 1, @@ -1100,6 +1102,7 @@ timeout_secs = {timeout_secs} let orders = vec![ BrokerOrderStatus { id: OrderId(1), + symbol: None, status: OrderState::Pending, filled_quantity: 0, remaining_quantity: 1, @@ -1107,6 +1110,7 @@ timeout_secs = {timeout_secs} }, BrokerOrderStatus { id: OrderId(2), + symbol: None, status: OrderState::Submitted, filled_quantity: 0, remaining_quantity: 1, @@ -1114,6 +1118,7 @@ timeout_secs = {timeout_secs} }, BrokerOrderStatus { id: OrderId(3), + symbol: None, status: OrderState::PartiallyFilled, filled_quantity: 1, remaining_quantity: 1, @@ -1121,6 +1126,7 @@ timeout_secs = {timeout_secs} }, BrokerOrderStatus { id: OrderId(4), + symbol: None, status: OrderState::Filled, filled_quantity: 1, remaining_quantity: 0, @@ -1128,6 +1134,7 @@ timeout_secs = {timeout_secs} }, BrokerOrderStatus { id: OrderId(5), + symbol: None, status: OrderState::Cancelled, filled_quantity: 0, remaining_quantity: 0, @@ -1135,6 +1142,7 @@ timeout_secs = {timeout_secs} }, BrokerOrderStatus { id: OrderId(6), + symbol: None, status: OrderState::Submitted, filled_quantity: 1, remaining_quantity: 0, diff --git a/rebalancer/src/recovery.rs b/rebalancer/src/recovery.rs index 1a593ef..ae88572 100644 --- a/rebalancer/src/recovery.rs +++ b/rebalancer/src/recovery.rs @@ -193,7 +193,9 @@ pub fn compare_broker_state( if is_orphan { discrepancies.push(Discrepancy::OrphanOrder { broker_order_id: broker_order.id.0, - symbol: "UNKNOWN".to_string(), // BrokerOrderStatus doesn't include symbol + symbol: broker_order + .symbol + .map_or_else(|| "UNKNOWN".to_string(), |s| s.as_str().to_string()), status: format!("{:?}", broker_order.status), }); } @@ -310,10 +312,11 @@ fn audit_dollars_to_cents(limit_dollars: f64) -> i64 { .unwrap_or_else(|_| (limit_dollars * 100.0).round() as i64) } -/// Find one open order whose filled and remaining shares sum to `quantity`. +/// Find one open order of `symbol` whose filled and remaining shares sum to +/// `quantity`. /// -/// `BrokerOrderStatus` has no symbol. A filled order does not match. -/// Two matches return an error. `symbol` is only a log field. +/// An order with another symbol, or with no symbol, does not match. A filled +/// order does not match. Two matches return an error. #[cfg(feature = "write_ahead_logging")] pub fn reconcile_order_intent( broker: &dyn Broker, @@ -323,7 +326,8 @@ pub fn reconcile_order_intent( reconcile_order_intent_with(broker, symbol, quantity, &mut std::thread::sleep) } -/// Find one open order whose filled and remaining shares sum to `quantity`. +/// Find one open order of `symbol` whose filled and remaining shares sum to +/// `quantity`. /// /// The open-order query retries five times. `sleep` receives each delay. #[cfg(feature = "write_ahead_logging")] @@ -337,7 +341,7 @@ pub fn reconcile_order_intent_with( let orders = fetch_open_orders(broker, sleep)?; let mut matched = None; for order in &orders { - if !order_matches_original_quantity(order, expected) { + if !order_matches_intent(order, symbol, expected) { continue; } if matched.is_some() { @@ -352,16 +356,18 @@ pub fn reconcile_order_intent_with( broker_order_id = order.id.0, filled = order.filled_quantity, remaining = order.remaining_quantity, - "matched open order by original quantity" + "matched open order by symbol and original quantity" ); } Ok(matched) } -/// An open order matches when its filled and remaining shares sum to `expected`. +/// An open order matches an intent when it has the intent's symbol and its +/// filled and remaining shares sum to `expected`. #[cfg(feature = "write_ahead_logging")] -fn order_matches_original_quantity(order: &BrokerOrderStatus, expected: u64) -> bool { - order.remaining_quantity > 0 +fn order_matches_intent(order: &BrokerOrderStatus, symbol: &Symbol, expected: u64) -> bool { + order.symbol == Some(*symbol) + && order.remaining_quantity > 0 && order.filled_quantity.checked_add(order.remaining_quantity) == Some(expected) } @@ -401,8 +407,9 @@ fn fetch_open_orders( /// Read open orders once and match each incomplete intent. /// -/// An order claimed by two intents matches none of them. No match appends -/// `OrderFailed`. One unshared match appends `OrderSubmitted`. +/// An intent matches an open order by symbol and quantity. No match appends +/// `OrderFailed`. One match appends `OrderSubmitted`. Two matches fail the +/// intent without an event. #[cfg(feature = "write_ahead_logging")] pub fn reconcile_incomplete_intents( broker: &dyn Broker, @@ -451,7 +458,7 @@ pub fn reconcile_incomplete_intents( let expected = u64::try_from(order.shares).unwrap_or(0); open_orders .iter() - .filter(|status| order_matches_original_quantity(status, expected)) + .filter(|status| order_matches_intent(status, &order.symbol, expected)) .map(|status| status.id.0) .collect() }) @@ -465,12 +472,9 @@ pub fn reconcile_incomplete_intents( order.client_order_id ); - let unique = ids.len() == 1 - && candidates - .iter() - .filter(|other| other.contains(&ids[0])) - .count() - == 1; + // An order has one symbol and there is one incomplete intent per symbol, + // so an order cannot match two intents. + let unique = ids.len() == 1; if ids.is_empty() { tracing::info!("Order not found at broker, appending OrderFailed event"); let mut audit = AuditLog::open_in(audit_log_path, workdir)?; @@ -1310,6 +1314,7 @@ mod tests { broker.connect().unwrap(); broker.set_open_order_statuses(vec![BrokerOrderStatus { id: OrderId(1), + symbol: Some(Symbol::new("AAPL")), status: OrderState::Submitted, filled_quantity: 0, remaining_quantity: 50, @@ -1334,6 +1339,7 @@ mod tests { // 50-share order, 25 filled, 25 still open. broker.set_open_order_statuses(vec![BrokerOrderStatus { id: OrderId(4), + symbol: Some(Symbol::new("AAPL")), status: OrderState::PartiallyFilled, filled_quantity: 25, remaining_quantity: 25, @@ -1348,6 +1354,7 @@ mod tests { // 20 shares filled and 30 left is a 50-share order, not a 30-share order. broker.set_open_order_statuses(vec![BrokerOrderStatus { id: OrderId(8), + symbol: Some(Symbol::new("AAPL")), status: OrderState::PartiallyFilled, filled_quantity: 20, remaining_quantity: 30, @@ -1363,6 +1370,47 @@ mod tests { ); } + #[cfg(feature = "write_ahead_logging")] + #[test] + fn reconcile_order_intent_ignores_an_order_of_another_symbol() { + use nanobook_broker::Broker; + use nanobook_broker::mock::MockBroker; + use nanobook_broker::types::{BrokerOrderStatus, OrderId, OrderState}; + + let row = |id: u64, symbol: Option<&str>| BrokerOrderStatus { + id: OrderId(id), + symbol: symbol.map(Symbol::new), + status: OrderState::Submitted, + filled_quantity: 0, + remaining_quantity: 50, + avg_fill_price_cents: 0, + }; + let mut broker = MockBroker::builder().build(); + broker.connect().unwrap(); + + // An open MSFT order of 50 shares is not the AAPL intent of 50 shares. + // The old match by quantity alone returned Some(1). + broker.set_open_order_statuses(vec![row(1, Some("MSFT"))]); + assert_eq!( + reconcile_order_intent(&broker, &Symbol::new("AAPL"), 50).unwrap(), + None + ); + + // An order whose symbol the broker could not give never matches. + broker.set_open_order_statuses(vec![row(2, None)]); + assert_eq!( + reconcile_order_intent(&broker, &Symbol::new("AAPL"), 50).unwrap(), + None + ); + + // The AAPL order is picked out from among orders of the same size. + broker.set_open_order_statuses(vec![row(1, Some("MSFT")), row(3, Some("AAPL"))]); + assert_eq!( + reconcile_order_intent(&broker, &Symbol::new("AAPL"), 50).unwrap(), + Some(3) + ); + } + #[cfg(feature = "write_ahead_logging")] #[test] fn reconcile_order_intent_rejects_two_orders_of_the_same_quantity() { @@ -1375,6 +1423,7 @@ mod tests { broker.set_open_order_statuses(vec![ BrokerOrderStatus { id: OrderId(4), + symbol: Some(Symbol::new("AAPL")), status: OrderState::Submitted, filled_quantity: 0, remaining_quantity: 50, @@ -1382,6 +1431,7 @@ mod tests { }, BrokerOrderStatus { id: OrderId(5), + symbol: Some(Symbol::new("AAPL")), status: OrderState::Submitted, filled_quantity: 0, remaining_quantity: 50, @@ -1740,6 +1790,13 @@ mod tests { let report = compare_broker_state(&broker, &state).unwrap(); assert!(report.has_critical_issues); assert!(!report.discrepancies.is_empty()); + // The orphan is reported with the symbol the broker gave it. + assert!( + report + .discrepancies + .iter() + .any(|d| matches!(d, Discrepancy::OrphanOrder { symbol, .. } if symbol == "AAPL")) + ); } #[test] @@ -2043,6 +2100,7 @@ mod tests { broker.connect().unwrap(); broker.set_open_order_statuses(vec![BrokerOrderStatus { id: OrderId(1), + symbol: Some(Symbol::new("AAPL")), status: OrderState::Submitted, filled_quantity: 0, remaining_quantity: 50, @@ -2699,6 +2757,7 @@ mod tests { > { Ok(nanobook_broker::types::BrokerOrderStatus { id, + symbol: None, status: nanobook_broker::types::OrderState::Submitted, filled_quantity: 0, remaining_quantity: 1, diff --git a/rebalancer/tests/crash_injection_integration.rs b/rebalancer/tests/crash_injection_integration.rs index e3be086..0c67ae4 100644 --- a/rebalancer/tests/crash_injection_integration.rs +++ b/rebalancer/tests/crash_injection_integration.rs @@ -230,6 +230,7 @@ fn test_crash_after_broker_call_before_order_submitted_logging() { broker.connect().unwrap(); broker.set_open_order_statuses(vec![nanobook_broker::types::BrokerOrderStatus { id: nanobook_broker::types::OrderId(1), + symbol: Some(Symbol::new("AAPL")), status: nanobook_broker::types::OrderState::Submitted, filled_quantity: 0, remaining_quantity: 50, diff --git a/rebalancer/tests/mutation_recovery.rs b/rebalancer/tests/mutation_recovery.rs index 52a4a1b..6ea414d 100644 --- a/rebalancer/tests/mutation_recovery.rs +++ b/rebalancer/tests/mutation_recovery.rs @@ -40,9 +40,10 @@ fn write_two_incomplete_intents( } } -fn open_status(id: u64, remaining: u64) -> nanobook_broker::types::BrokerOrderStatus { +fn open_status(id: u64, symbol: &str, remaining: u64) -> nanobook_broker::types::BrokerOrderStatus { nanobook_broker::types::BrokerOrderStatus { id: nanobook_broker::types::OrderId(id), + symbol: Some(nanobook::Symbol::new(symbol)), status: nanobook_broker::types::OrderState::Submitted, filled_quantity: 0, remaining_quantity: remaining, @@ -56,27 +57,30 @@ fn one_open_order_does_not_submit_two_intents_of_the_same_quantity() { let path = dir.path().join("audit.jsonl"); write_two_incomplete_intents(&path, dir.path(), 50, 50); - // One live 50-share order, nothing filled. Both intents ask for 50. - // The status has no symbol, so the order cannot be given to either. + // One live 50-share MSFT order, nothing filled. Both intents ask for 50. + // The order belongs to MSFT only: the AAPL intent finds no order. let mut broker = MockBroker::builder().build(); broker.connect().unwrap(); - broker.set_open_order_statuses(vec![open_status(7, 50)]); + broker.set_open_order_statuses(vec![open_status(7, "MSFT", 50)]); let (state, _) = reconstruct_state(&path).unwrap(); - let err = reconcile_incomplete_intents(&broker, &state, &path).unwrap_err(); - match err { - Error::Recovery(message) => { - assert!( - message.contains("Failed to reconcile 2 incomplete intents"), - "{message}" - ); - } - other => panic!("expected Recovery, got {other:?}"), - } + reconcile_incomplete_intents(&broker, &state, &path).unwrap(); let events = parse_audit_events(&path).unwrap(); - assert_eq!(events.len(), 3); - assert!(events.iter().all(|event| event.event != "order_submitted")); - assert!(events.iter().all(|event| event.event != "order_failed")); + assert_eq!(events.len(), 5); + assert_eq!(events[3].event, "order_failed"); + assert_eq!( + events[3].data.get("symbol").and_then(|v| v.as_str()), + Some("AAPL") + ); + assert_eq!(events[4].event, "order_submitted"); + assert_eq!( + events[4].data.get("symbol").and_then(|v| v.as_str()), + Some("MSFT") + ); + assert_eq!( + events[4].data.get("ibkr_id").and_then(|v| v.as_u64()), + Some(7) + ); } #[test] @@ -87,7 +91,13 @@ fn two_open_orders_of_one_quantity_match_neither_intent() { let mut broker = MockBroker::builder().build(); broker.connect().unwrap(); - broker.set_open_order_statuses(vec![open_status(7, 50), open_status(8, 50)]); + // Two open orders per symbol, so each intent has two candidates. + broker.set_open_order_statuses(vec![ + open_status(7, "AAPL", 50), + open_status(8, "AAPL", 50), + open_status(9, "MSFT", 50), + open_status(10, "MSFT", 50), + ]); let (state, _) = reconstruct_state(&path).unwrap(); let err = reconcile_incomplete_intents(&broker, &state, &path).unwrap_err(); @@ -114,7 +124,7 @@ fn two_open_orders_of_different_quantities_submit_both_intents() { let mut broker = MockBroker::builder().build(); broker.connect().unwrap(); - broker.set_open_order_statuses(vec![open_status(7, 50), open_status(8, 25)]); + broker.set_open_order_statuses(vec![open_status(7, "AAPL", 50), open_status(8, "MSFT", 25)]); let (state, _) = reconstruct_state(&path).unwrap(); reconcile_incomplete_intents(&broker, &state, &path).unwrap(); @@ -149,7 +159,7 @@ fn intents_match_open_orders_by_quantity_not_by_the_broker_list_order() { // The 25-share order is listed first, the reverse of the intent order. let mut broker = MockBroker::builder().build(); broker.connect().unwrap(); - broker.set_open_order_statuses(vec![open_status(8, 25), open_status(7, 50)]); + broker.set_open_order_statuses(vec![open_status(8, "MSFT", 25), open_status(7, "AAPL", 50)]); let (state, _) = reconstruct_state(&path).unwrap(); reconcile_incomplete_intents(&broker, &state, &path).unwrap(); @@ -204,7 +214,7 @@ fn reconciliation_summary_counts_intents_found_at_the_broker() { let mut broker = MockBroker::builder().build(); broker.connect().unwrap(); - broker.set_open_order_statuses(vec![open_status(7, 50), open_status(8, 25)]); + broker.set_open_order_statuses(vec![open_status(7, "AAPL", 50), open_status(8, "MSFT", 25)]); let (state, _) = reconstruct_state(&path).unwrap(); let capture = LogCapture::default(); @@ -233,12 +243,12 @@ fn open_order_with_nothing_remaining_does_not_match_an_intent() { broker.set_open_order_statuses(vec![ nanobook_broker::types::BrokerOrderStatus { filled_quantity: 20, - ..open_status(7, 30) + ..open_status(7, "AAPL", 30) }, nanobook_broker::types::BrokerOrderStatus { status: nanobook_broker::types::OrderState::Filled, filled_quantity: 25, - ..open_status(8, 0) + ..open_status(8, "MSFT", 0) }, ]); diff --git a/rebalancer/tests/recovery_integration.rs b/rebalancer/tests/recovery_integration.rs index 207d78a..b3a21fe 100644 --- a/rebalancer/tests/recovery_integration.rs +++ b/rebalancer/tests/recovery_integration.rs @@ -596,6 +596,7 @@ fn test_broker_reconciliation_incomplete_intent_found() { broker.connect().unwrap(); broker.set_open_order_statuses(vec![nanobook_broker::types::BrokerOrderStatus { id: nanobook_broker::types::OrderId(1), + symbol: Some(Symbol::new("AAPL")), status: nanobook_broker::types::OrderState::Submitted, filled_quantity: 0, remaining_quantity: 50, @@ -738,6 +739,7 @@ fn test_broker_reconciliation_mixed_intents() { broker.connect().unwrap(); broker.set_open_order_statuses(vec![nanobook_broker::types::BrokerOrderStatus { id: nanobook_broker::types::OrderId(1), + symbol: Some(Symbol::new("AAPL")), status: nanobook_broker::types::OrderState::PartiallyFilled, filled_quantity: 25, remaining_quantity: 25, @@ -970,6 +972,7 @@ fn reconcile_appends_submitted_and_failed_in_sequence() { // AAPL's 50 shares are still open. MSFT's 25 shares are not. broker.set_open_order_statuses(vec![nanobook_broker::types::BrokerOrderStatus { id: nanobook_broker::types::OrderId(1), + symbol: Some(Symbol::new("AAPL")), status: nanobook_broker::types::OrderState::Submitted, filled_quantity: 0, remaining_quantity: 50, @@ -1071,6 +1074,7 @@ impl Broker for FailOpenBroker { > { Ok(nanobook_broker::types::BrokerOrderStatus { id, + symbol: None, status: nanobook_broker::types::OrderState::Submitted, filled_quantity: 0, remaining_quantity: 1, diff --git a/rebalancer/tests/verification_tests.rs b/rebalancer/tests/verification_tests.rs index a2b20cc..8929d78 100644 --- a/rebalancer/tests/verification_tests.rs +++ b/rebalancer/tests/verification_tests.rs @@ -644,6 +644,7 @@ fn test_broker_reconciliation_finds_order() { broker.connect().unwrap(); broker.set_open_order_statuses(vec![nanobook_broker::types::BrokerOrderStatus { id: nanobook_broker::types::OrderId(1), + symbol: Some(Symbol::new("AAPL")), status: nanobook_broker::types::OrderState::Submitted, filled_quantity: 0, remaining_quantity: 50, From 98407ddfabf8bd55fc872d1ba0f28663dc5ef197 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:38:16 +0100 Subject: [PATCH 62/66] fix(broker): reconcile_partial_fill reads a symbol missing from the positions as flat Follow-up to 62dfc82. When the symbol was absent from the position list the function returned the pre-disconnect fill and ignored baseline_position. A sell of 100 from a baseline of +75 that sold the position down to flat (the row gone) reported 0 filled and Failed; a buy that covered a short did the same. A missing row is now compared as quantity 0 when a baseline was held. With no baseline the not-found result is unchanged. Test: test_reconcile_counts_a_position_missing_from_the_list_as_flat (sell from +75, buy from -30). Found in the review of the fix for PR 86, thread T23. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- broker/src/ibkr/orders.rs | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/broker/src/ibkr/orders.rs b/broker/src/ibkr/orders.rs index cfdcf4f..cb9d25b 100644 --- a/broker/src/ibkr/orders.rs +++ b/broker/src/ibkr/orders.rs @@ -886,8 +886,20 @@ pub fn reconcile_partial_fill( order_id, symbol, pre_disconnect_filled, expected_total, baseline_position ); - // Find the position for this symbol - let current_position = current_positions.iter().find(|p| p.symbol == symbol); + // Find the position for this symbol. A symbol missing from the positions is + // flat. If a position was held before the order, flat is a change (closed + // out), so compare it as quantity 0 instead of reporting "not found". + let flat = Position { + symbol, + quantity: 0, + avg_cost_cents: 0, + market_value_cents: 0, + unrealized_pnl_cents: 0, + }; + let current_position = current_positions + .iter() + .find(|p| p.symbol == symbol) + .or((baseline_position != 0).then_some(&flat)); match current_position { Some(pos) => { @@ -1368,6 +1380,22 @@ mod tests { assert_eq!(result.status, OrderOutcome::PartialFill); } + #[test] + fn test_reconcile_counts_a_position_missing_from_the_list_as_flat() { + // 75 shares were held before a sell of 100. After the reconnect the + // symbol is not in the list at all: the position was sold down to flat, + // 75 shares of this order filled. Reporting "not found" would give 0. + let symbol = nanobook::Symbol::try_new("AAPL").unwrap(); + let result = reconcile_partial_fill(1, symbol, 0, 100, 75, &[], BrokerSide::Sell).unwrap(); + assert_eq!(result.filled_shares, 75); + assert_eq!(result.status, OrderOutcome::PartialFill); + + // A short of 30 covered by a buy of 30 (flat): 30 filled. + let result = reconcile_partial_fill(1, symbol, 0, 30, -30, &[], BrokerSide::Buy).unwrap(); + assert_eq!(result.filled_shares, 30); + assert_eq!(result.status, OrderOutcome::PartialFill); + } + #[test] fn test_reconcile_sell_counts_only_the_change_since_the_baseline() { // A short of 30 was held before the sell order; 20 more were sold. From 7ed72c0e6f317ce4677bcb8b8559fdec465f3082 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:43:39 +0100 Subject: [PATCH 63/66] fix(broker): execute_limit_order reads IBKR connection notices from the global stream ibapi 2.12 sends an error with request id -1 (codes 1100 to 1102) only to the global order-update stream, not to the order's own subscription, so the connection-loss arm of the order loop never saw them: a lost connection was noticed only when the order's stream ended, and the wait blocked until then. execute_limit_order now takes Client::order_update_stream before placing the order and hands the loop an OrderEvents iterator. It looks at the order's stream for at most 500 ms, reads the order's events first (so a fill ahead of the notice is counted), then drains the global stream without waiting and passes a 1100 to 1102 notice on as PlaceOrder::Message. run_place_order_events is unchanged and returns ConnectionLost with the partial fill. The order's stream counts as ended when next_timeout returns nothing and the subscription holds an error or the client is disconnected. ibapi allows one global stream at a time: if it is taken, a warning is logged and the order runs as before. No signature change. Tests drive OrderEvents with scripted polls through run_place_order_events: global_connection_notice_ends_the_wait_while_the_order_stream_is_quiet and global_notice_at_the_end_of_the_order_stream_is_still_read fail on the old code (Ok(Failed) instead of ConnectionLost); fills_already_on_the_order_stream_count_before_a_global_notice and other_global_notices_do_not_abort_the_order pin the ordering and that other notices are ignored. The live ibapi calls cannot run without TWS. Found by the bot review of PR 86 (thread T0). CHANGELOG: entry moved from Known issues to Fixed, with a Changed note. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- CHANGELOG.md | 15 ++- broker/src/ibkr/orders.rs | 203 +++++++++++++++++++++++++++++++++++++- 2 files changed, 211 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b7fcb0..8cc8042 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -94,6 +94,11 @@ tests, fuzzing or mutation testing. service. *Check your code if* you read the order cache after `poll_account_info`, or fed `update_state_from_account_info` an `AccountInfo` with `open_orders`: call `poll_open_orders` or `update_order_cache_from_open_orders` for the orders. +- **nanobook-broker: `execute_limit_order` holds ibapi's order-update stream while an + order is in flight.** No signature changes. *Check your code if* you subscribe to + `order_update_stream` on the same ibapi client yourself: a subscription taken while + an order runs fails with `AlreadySubscribed`, and if you hold it when an order + starts, that order does not see 1100 to 1102 notices (see Fixed). - **Level and book totals are exact.** `total_quantity`, `quantity_at_or_better` and snapshot totals cap at `u64::MAX` instead of wrapping or panicking, and `BookSnapshot::imbalance` uses exact side sums. @@ -117,8 +122,13 @@ tests, fuzzing or mutation testing. The order loop dropped codes 1100 to 1102 before its check, so `execute_limit_order` did not return `ConnectionLost` with the partial fill when such a notice reached the order's own stream. It does now. ibapi 2.12 sends these notices with request id -1 to - its global order-update stream, not to the order's stream (see Known issues). Found - by mutation testing. + its global order-update stream, not to the order's stream, so `execute_limit_order` + now also reads that stream while the order is in flight (every half second) and + ends the wait with `ConnectionLost` and the partial fill when a 1100 to 1102 notice + arrives. ibapi allows one such stream at a time: if another part of the program + holds it, the order still runs and a warning is logged, and a lost connection then + shows only when the order's own stream ends. Found by mutation testing and by the + bot review of PR 86. - **nanobook-broker: IBKR reconciliation after a disconnect ignored the order's side.** `reconcile_partial_fill` compared the absolute position size, so a buy order against a short position (or a sell against a long one) was reported as filled @@ -184,7 +194,6 @@ tests, fuzzing or mutation testing. - **nanobook-rebalancer: `TargetSpec::window_id` hashes with `DefaultHasher`.** The id can change after a Rust upgrade, so a cron window can fire twice. - **nanobook-rebalancer: without `write_ahead_logging`, the runner does not write `order_submitted`.** Graceful kill then cannot report a dangling order. - **nanobook-broker: the Binance `Broker::cancel_order` by order id is a placeholder.** It is refused: the adapter has an order cache with the symbol of each order, but `cancel_order` does not use it yet. -- **nanobook-broker: an IBKR connection notice (1100 to 1102) does not reach `execute_limit_order` as such.** ibapi 2.12 delivers it with request id -1 to the global order-update stream, so a lost connection is reported when the order's stream ends, not when the notice arrives. - **nanobook-risk: an empty side prints `-0.0%`.** The "Weight allocation" detail shows `-0.0% long` (or short) when no target is on that side, because an empty `f64` sum is `-0.0` since Rust 1.83. The numbers are zero; only the sign in the text is wrong. ### Security diff --git a/broker/src/ibkr/orders.rs b/broker/src/ibkr/orders.rs index cb9d25b..93ce6b5 100644 --- a/broker/src/ibkr/orders.rs +++ b/broker/src/ibkr/orders.rs @@ -78,7 +78,7 @@ use ibapi::contracts::Contract; #[cfg(not(feature = "strict-market-reject"))] use ibapi::orders::order_builder::market_order; use ibapi::orders::order_builder::{limit_order, stop, stop_limit}; -use ibapi::orders::{Action as IbAction, CancelOrder, Order, OrderData, PlaceOrder}; +use ibapi::orders::{Action as IbAction, CancelOrder, Order, OrderData, OrderUpdate, PlaceOrder}; use log::{debug, info, warn}; use crate::error::BrokerError; @@ -95,12 +95,66 @@ fn is_connection_lost(code: i32) -> bool { /// connection codes 1100 to 1102. /// /// ibapi 2.12 sends an error with request id -1 to the global order-update -/// stream only. This loop reads the per-order subscription. A normal 1100 -/// to 1102 notice does not reach `is_connection_lost`. +/// stream only, not to the order's own subscription. `OrderEvents` reads +/// that stream and hands such a notice to this loop. fn is_order_notice(code: i32) -> bool { !(0..2000).contains(&code) || is_connection_lost(code) } +/// How long `OrderEvents` waits on the order's own stream before it looks at +/// the global order-update stream again. +const GLOBAL_STREAM_POLL: Duration = Duration::from_millis(500); + +/// One look at the order's own stream. Short-lived, so the size of `PlaceOrder` +/// does not matter. +#[allow(clippy::large_enum_variant)] +enum OrderPoll { + Event(PlaceOrder), + /// Nothing arrived within the poll interval. + Idle, + /// The stream is over: closed, reset or shut down. + Ended, +} + +/// The events of one order, plus connection notices (codes 1100 to 1102) +/// read from the global order-update stream and passed on as +/// `PlaceOrder::Message`, so `run_place_order_events` ends the wait with +/// `ConnectionLost` when TWS reports the loss. +/// +/// `next_order` looks at the order's own stream for at most +/// `GLOBAL_STREAM_POLL`. `next_global_notice` returns the next notice from the +/// global stream without waiting. The order's events come first, so a fill +/// that arrived before the notice is counted. +struct OrderEvents { + next_order: O, + next_global_notice: G, +} + +impl Iterator for OrderEvents +where + O: FnMut() -> OrderPoll, + G: FnMut() -> Option, +{ + type Item = PlaceOrder; + + fn next(&mut self) -> Option { + loop { + let poll = (self.next_order)(); + if let OrderPoll::Event(event) = poll { + return Some(event); + } + while let Some(notice) = (self.next_global_notice)() { + if is_connection_lost(notice.code) { + return Some(PlaceOrder::Message(notice)); + } + } + if matches!(poll, OrderPoll::Ended) { + return None; + } + } + } +} + pub fn map_ibkr_order_status(status: &str) -> OrderState { match status { "Submitted" | "PreSubmitted" | "PendingSubmit" | "ApiPending" => OrderState::Submitted, @@ -411,10 +465,40 @@ pub fn execute_limit_order( side, shares, symbol, limit_price, order_id ); + // TWS reports a lost connection (1100 to 1102) on the global order-update + // stream only. Only one such stream exists at a time and it is released + // when dropped. If it is taken, the order still runs and a lost connection + // shows only as the end of the order's own stream. + let global_stream = match client.order_update_stream() { + Ok(stream) => Some(stream), + Err(e) => { + warn!( + "Order-update stream unavailable ({e}): a connection notice for order {order_id} will not be seen" + ); + None + } + }; + let subscription = client .place_order(order_id, &contract, &ib_order) .map_err(|e| BrokerError::Order(format!("failed to place order {order_id}: {e}")))?; + let events = OrderEvents { + next_order: || match subscription.next_timeout(GLOBAL_STREAM_POLL) { + Some(event) => OrderPoll::Event(event), + None if subscription.error().is_some() || !client.is_connected() => OrderPoll::Ended, + None => OrderPoll::Idle, + }, + next_global_notice: || { + let stream = global_stream.as_ref()?; + loop { + if let OrderUpdate::Message(notice) = stream.try_next()? { + return Some(notice); + } + } + }, + }; + let start = Instant::now(); let PlaceOrderOutcome { status: final_status, @@ -422,7 +506,7 @@ pub fn execute_limit_order( avg_price, commission, } = run_place_order_events( - subscription, + events, order_id, timeout, || start.elapsed(), @@ -1881,6 +1965,117 @@ mod tests { )); } + // ---- OrderEvents: notices from the global order-update stream ------ + + /// Run the order loop over `OrderEvents`. `polls` are the successive looks + /// at the order's own stream (the stream ends when they run out) and + /// `global` the successive reads of the global stream (empty when they + /// run out). + fn run_merged( + polls: Vec, + global: Vec>, + ) -> Result<(OrderOutcome, f64), BrokerError> { + let mut polls = std::collections::VecDeque::from(polls); + let mut global = std::collections::VecDeque::from(global); + let events = OrderEvents { + next_order: || polls.pop_front().unwrap_or(OrderPoll::Ended), + next_global_notice: || global.pop_front().flatten(), + }; + run_place_order_events( + events, + ORDER_ID, + TIMEOUT, + || Duration::ZERO, + cancel_ok, + None, + ) + .map(|o| (o.status, o.filled)) + } + + fn event(status: &str, filled: f64, remaining: f64, avg: f64) -> OrderPoll { + OrderPoll::Event(st(status, filled, remaining, avg)) + } + + #[test] + fn global_connection_notice_ends_the_wait_while_the_order_stream_is_quiet() { + // The order's own stream stays open and silent; the loss is reported + // only on the global stream. Without reading it the wait ends with + // `Ok(Failed)` when the stream finally ends. + for code in [1100, 1101, 1102] { + let result = run_merged( + vec![OrderPoll::Idle, OrderPoll::Idle, OrderPoll::Idle], + vec![None, Some(notice(code, "connectivity"))], + ); + + assert!( + matches!( + result, + Err(BrokerError::ConnectionLost { + order_id: ORDER_ID, + filled_quantity: 0 + }) + ), + "code {code}: {result:?}" + ); + } + } + + #[test] + fn fills_already_on_the_order_stream_count_before_a_global_notice() { + // The notice is ready from the start, but the 40-share fill came + // first on the order's stream. + let result = run_merged( + vec![ + event("Submitted", 40.0, 60.0, 10.0), + OrderPoll::Idle, + OrderPoll::Idle, + ], + vec![Some(notice(1100, "connectivity"))], + ); + + assert!( + matches!( + result, + Err(BrokerError::ConnectionLost { + order_id: ORDER_ID, + filled_quantity: 40 + }) + ), + "{result:?}" + ); + } + + #[test] + fn global_notice_at_the_end_of_the_order_stream_is_still_read() { + let result = run_merged( + vec![OrderPoll::Ended], + vec![Some(notice(1100, "connectivity"))], + ); + + assert!(matches!( + result, + Err(BrokerError::ConnectionLost { + order_id: ORDER_ID, + filled_quantity: 0 + }) + )); + } + + #[test] + fn other_global_notices_do_not_abort_the_order() { + let result = run_merged( + vec![OrderPoll::Idle, event("Filled", 100.0, 0.0, 185.5)], + vec![ + Some(notice(2104, "market data farm connection is OK")), + Some(notice(201, "order rejected")), + Some(notice(1103, "other")), + None, + ], + ); + + assert_eq!(result.unwrap().0, OrderOutcome::Filled); + } + // ---- cancel_from_responses / cancel_request_error ------------------ fn cancel_status(status: &str) -> CancelOrder { From a2986abdf3c1416c170afc1b445cdf54e5b812ab Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:43:50 +0100 Subject: [PATCH 64/66] docs: BrokerOrderStatus has a symbol The developer reference listed the struct without the field added in ac0f321 (recovery matches open orders on symbol and quantity). Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- docs/reference.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/reference.md b/docs/reference.md index cacae7f..bb427b4 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -591,6 +591,7 @@ pub struct Quote { pub struct BrokerOrderStatus { pub id: OrderId, + pub symbol: Option, // None when the adapter cannot tell (order_status by id alone) pub status: OrderState, // Pending | Submitted | PartiallyFilled | Filled | Cancelled | Rejected pub filled_quantity: u64, pub remaining_quantity: u64, From 6b38bd5080309996ed87d26a2023b9befd6688f9 Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:47:41 +0100 Subject: [PATCH 65/66] docs(changelog): broker and rebalancer go to 0.11.0, risk to 0.8.2 cargo-semver-checks finds two breaking changes in nanobook-broker (BrokerOrderStatus.symbol, reconcile_partial_fill's baseline argument), so 0.10.2 is not a valid version; the rebalancer builds on those types. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- CHANGELOG.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cc8042..19848a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,9 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased -nanobook and the Python package move from 0.19.3 to 0.20.0, and nanobook-broker -from 0.10.1 to 0.10.2. nanobook-risk and nanobook-rebalancer are republished only if -their code changes before the release. +nanobook and the Python package move from 0.19.3 to 0.20.0. nanobook-broker moves +from 0.10.1 to 0.11.0 and nanobook-rebalancer from 0.10.2 to 0.11.0: both have +breaking changes (see Changed). nanobook-risk moves from 0.8.1 to 0.8.2 (no API +change: `#![forbid(unsafe_code)]` and tests). ### Highlight: matching rules proved in Lean 4 From a90931f0a143df49dbb917067990e5bec3f1b8fe Mon Sep 17 00:00:00 2001 From: "jac-made[bot]" <350467601+jac-made[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:54:23 +0100 Subject: [PATCH 66/66] test(rebalancer): a log path through a file is reported as unreadable cargo-mutants (c8 job 177) showed the NotFound guard in validate_disk_space could match every error. The test now covers a path through a file, which fails with 'not a directory' on Unix. VERIFICATION.md gets the job 177 numbers for the broker and the rebalancer. Co-authored-by: Ricardo Frantz <4220623+ricardofrantz@users.noreply.github.com> --- VERIFICATION.md | 13 ++++++++----- rebalancer/src/validator.rs | 13 +++++++++++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/VERIFICATION.md b/VERIFICATION.md index 0808042..cc8b726 100644 --- a/VERIFICATION.md +++ b/VERIFICATION.md @@ -140,17 +140,20 @@ Result on the 0.20.0 code (only changes that compile are counted): |---|---|---|---|---|---|---| | `nanobook-risk` | 149 | 146 | 0 | 1 | 2 | 0 | | `nanobook`: portfolio, metrics, backtest bridge | 1005 | 970 | 8 | 27 | 0 | 0 | -| `nanobook-broker` (IBKR and Binance) | 428 | 388 | 0 | 5 | 6 | 29 | -| `nanobook-rebalancer` (both builds) | 753 | 717 | 4 | 29 | 1 | 2 | +| `nanobook-broker` (IBKR and Binance) | 434 | 392 | 0 | 3 | 6 | 33 | +| `nanobook-rebalancer` (both builds) | 757 | 721 | 4 | 29 | 1 | 2 | - "Cannot change any result": no reachable input gives a different answer, for example `>` against `>=` where the equal case is filtered out a few lines earlier. The table gives counts only; the reason for each change is not published here. -- "Out of reach of tests": 27 broker changes need a live Interactive Brokers - connection (whole-function replacements on the client, its order cache and its - callback de-duplication), one needs the Binance network, and one differs only when +- "Out of reach of tests": 31 broker changes need a live Interactive Brokers + connection (whole-function replacements on the client, its order cache, its + callback de-duplication, and the check that an order's own update stream has + ended), one needs the Binance network, and one differs only when a 300 s age equals the limit to the nanosecond on a clock the test cannot set; in the rebalancer, two replace the interactive confirmation prompt. +- One rebalancer change (the log-directory error check) survived the last run and is + caught by a test added after it; that kill was checked by hand. - The matching engine itself (`book.rs`, `level.rs`, `matching.rs`, `exchange.rs`, `price_levels.rs`) had no surviving change in the full core run (5046 changes). A test added for 0.20.0 also pins the order record after a diff --git a/rebalancer/src/validator.rs b/rebalancer/src/validator.rs index d2140ce..2b6d695 100644 --- a/rebalancer/src/validator.rs +++ b/rebalancer/src/validator.rs @@ -578,6 +578,19 @@ mod tests { "{}", issues[0].message ); + + // A path through a file fails with "not a directory", not "not found" + // (Unix; Windows reports such a path as not found). + #[cfg(unix)] + { + let issues = validate_disk_space(&valid_config(&file.join("sub"))); + assert_eq!(issues.len(), 1); + assert!( + issues[0].message.contains("directory cannot be read"), + "{}", + issues[0].message + ); + } } #[test]