Skip to content
alienxvikingPublic

About

A quantitative trading platform in Rust — immutable market-data capture, deterministic replay, and an engine where backtest, paper and live trading are the same code.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

quant

A quantitative trading platform, built as a long-term systems-engineering project. Crypto is the first venue implementation, not the point of the project — the engine is meant to outlive any single strategy or market.

The one architectural idea

One strategy binary, three worlds, no code changes between them:

              ┌── HistoricalSource   (Parquet replay, as fast as possible)
EventSource ──┼── ReplaySource       (raw capture, wall-clock paced)  [not built]
              └── LiveSource         (venue WebSocket)
                        │
                        ▼
                     Engine ────────►  Strategy
                        │
                        ▼
                    RiskLayer         (mandatory chokepoint — not optional,
                        │              not called politely by the strategy)
                        ▼
                 ┌── SimulatedVenue   (fills, fees, latency; also paper's venue)
ExecutionVenue ──┴── LiveVenue        (real orders)                        [M8]
Mode Source Venue
Backtest Historical Simulated
Paper Live Simulated
Live Live Live

There is deliberately no PaperVenue, and finding that out was one of M5's results. A paper venue fills against a reconstructed book at prices the book showed — which is exactly SimulatedVenue. What separates a backtest from paper trading is the source and the durability, not the matching, so writing a second fill model would have created two things that must agree forever with no way to notice when they stopped.

ReplaySource is not built either. This diagram used to list it unmarked, beside a LiveVenue that carries its [M8] — and a diagram that marks one unbuilt thing and not another is claiming the unmarked ones exist. Two types implement EventSource outside the tests: HistoricalSource over the Parquet tier and LiveSource over the socket. Wall-clock-paced replay of raw capture is a shape the seam leaves room for and nothing has needed yet — M5 does not get its live-versus-replay comparison by pacing a capture afterwards, it gets it from one ingress feeding both paths at once. Same class of claim as PaperVenue above, corrected the same way.

A strategy must not be able to tell which pair it is wired to. If it can, that is a bug. Divergence between these three paths is how backtests end up describing a system that was never run.

Invariants

These are enforced by the compiler and the test suite, not by discipline:

  1. Money is integral. Fixed-point i64 scaled by 1e8. clippy::float_arithmetic is denied workspace-wide.
  2. Two timestamps on every event, and only local_recv_ts is ever dispatched on. Anything else is lookahead bias.
  3. Gaps are recorded events. "We were not watching" is data, not silence.
  4. Time is injected. Components take a &dyn Clock. Anything that calls the wall clock directly cannot be backtested.

Layout

crates/
  quant-core/       types, time, instruments, the event contract  [M0]
  quant-storage/    the raw capture format: framing, blocks, torn-tail
                    recovery. Knows no venue and no network.       [M1a]
  quant-recorder/   ingress stamping, sequencing, bounded-channel
                    overload policy, writer loop. Venue-agnostic.  [M1b]
  quant-binance/    the Binance WebSocket dialect, the REST snapshot
                    fetch, plus the `record` binary. The only crate
                    that knows a venue.                            [M1b]
  quant-meta/       Postgres: capture sessions and segments. Sits
                    above the recorder; optional and best-effort.   [M1c]
  quant-verify/     the offline verifier: turns the acceptance
                    criteria into a command with an exit code.
                    Top of the dependency graph.                   [M1d]
  quant-book/       order book reconstruction and its invariants.
                    Venue-agnostic; depends only on quant-core.    [M2b]
  quant-normalize/  a capture session back out as ordered events:
                    segments joined, book driven, and the Parquet
                    tier written and read back. `normalize` bin.  [M2c/d]
  quant-engine/     the seam: the loop, Strategy, RiskLayer,
                    ExecutionVenue, the portfolio and the journal.
                    Knows no venue, no format, no network.     [M3b/M5c]
  quant-sim/        the simulated counterparty and its cost
                    models. Every backtest number comes from
                    the assumptions stated here.               [M3c/M4]
  quant-backtest/   the wiring: a naive strategy, an equity curve,
                    and the `backtest`, `paper` and `reconcile`
                    binaries.                              [M3d/M5c/d]
  quant-explain/    the time cursor: what the system was doing at an
                    instant, read from raw and the journal. Writes
                    nothing -- no index, no cache, no sidecar.      [M7]
docs/
  overview.md         the whole project as a narrative, start to finish;
                      authoritative on nothing, and says so
  data-contract.md    the on-disk format and its acceptance criteria
  engine-contract.md  the seam a strategy sees, and why it is shaped
                      that way. Written before the engine exists.
  observability.md    why M7 is a reader and not an exporter, and its
                      criteria. Written before the reader exists.
  run-log.md          what a decision record contains, what it refuses to
                      be, and the three criteria it is measured against. [M7.5]
  live-run.md         why M8 is the engine gaining a second asynchronous
                      input, and what reconciling against a counterparty
                      can and cannot prove. Written before the code. [M8]
  machine-move.md     getting the artifacts between machines: what moves,
                      what is rebuilt instead, and what a third party in
                      the middle changes
  acceptance-run.md   how the 7-day M1 run is conducted and judged
  paper-run.md        how the 2-week M5 paper run is conducted and judged
ops/
  preflight.sh      refuse to waste a week: clock, disk, build, clean root
  start-run.sh      start a run: supervisors + verify loop. `--paper` runs
                    M5's fortnight instead of a bare recorder
  supervise.sh      keep one symbol running to its deadline, restarting it
                    only if it *died* -- a clean exit is the run finishing
  test-supervise.sh exercise that restart rule against a fake child, in ~20s
  verify-loop.sh    verify during the capture rather than after it
  status.sh         "how is it going" in one command
  stop-run.sh       stop it in a way that still seals the files
  fix-clock.sh      sync the host clock, which venue latency also measures

Every ops/ script has a PowerShell half beside the bash one. The bash half is the one that has been run — M1's seven days were conducted from it and M5's fortnight is being conducted from it now — and it is the only half that knows --paper, because an untested paper mode on the side nobody runs is exactly the harness M1 warns about.

Milestones

# Milestone Done when
M0 Foundation + data contract CI green; contract written before the recorder exists done
M1 Binance market data recorder Runs 7 days unattended; zero unexplained gaps done
M2 Normalizer + book reconstruction Book invariants hold at every tick of a replayed day done
M3 Engine seam + SimulatedVenue + MA crossover Equity curve produced, and it is unimpressive done
M4 Fee, slippage and latency modelling Results degrade sensibly under realistic costs done
M5 Paper trading 2 weeks live; paper P&L matches a backtest over the same window done
M6 Risk engine + kill switch Limits provably veto a misbehaving strategy, under test done
M7 Observability "What was it doing at 03:14 last Tuesday?" answered in a minute done
M7.5 The run log A record that detects its own incompleteness, and a diff that refuses rather than passing done
M8 Live, tiny capital Our record and the venue's agree exactly; the model predicts the right kind of outcome for every order; its price error is inside a bound registered beforehand

Milestones have acceptance criteria, not feature lists. "Done" means the criterion passes, and M5's took two weeks of wall clock to satisfy: the fortnight ran 2026-09-18 → 2026-10-02 and paper P&L reproduced a backtest over the same window exactly. docs/paper-run.md is the procedure and docs/observability.md is M7's.

M1's acceptance run — the one criterion only time can satisfy — was spent in full: seven days unattended on an Apple Silicon Mac, 2026-08-21 → 2026-08-28, quant-verify exit 0 with every discontinuity explained by a record in the capture. See docs/acceptance-run.md for the procedure, and "The acceptance run, and how it went" in CLAUDE.md for the result.

M2 is complete. Both weeks of the acceptance capture replay as two joined 8-day sessions with book invariants holding at all 70.5M ticks, zero deltas dropped for want of an anchor, and zero chain breaks — where replaying one file at a time had dropped 7,000 to 34,000 deltas on each day after the first. The normalized Parquet tier is written (2.1 GB from 3.0 GB of raw), and 70,545,345 events replayed from Parquet match the raw replay event for event, which is what turns "Normalized is disposable, rebuilt from raw" from a claim in a table into a fact.

M3 is complete, and its criterion is unusual on purpose: an equity curve is produced, and it is unimpressive. A moving-average crossover over the acceptance week takes $100 to $97.53 — a 2.47% loss with no fees modelled at all. That is the result to want. A crossover that looked profitable on its first run would mean the harness was lying, and every way it could lie (dispatching on the wrong timestamp, filling at prices the book never showed, trading through a gap) is invisible in the output. See docs/engine-contract.md.

M4 is complete, and it answers the question the project was built to ask honestly. At Binance spot's published 10 bps a side, the same week takes $100 to $64.74 — the strategy loses 2.5% on price and 33% on commission. 418 fills on a $76 position is 43% of position value in fees in a week, so gross returns would have to beat that to break even. That is a real result: this strategy class, at this turnover, at retail fees, cannot work. Learning it from recorded data cost nothing.

M5's fortnight ran 2026-09-18 → 2026-10-02 and passed. Two symbols, one paper process each, on the Mac, pinned to the tag m5-run-start and never pulled there — the running process would not change if it were, but the ability to say which code produced the result would. paper runs LiveSource + SimulatedVenue with the capture and the engine fed from one ingress — the same records with the same timestamps, which is what makes "paper P&L must match a backtest over the same window" checkable exactly rather than approximately.

It did match, to the satoshi, on both symbols: 824 fills and cash 31.64743842 on BTCUSDT, 822 and 97.65757574 on ETHUSDT, identical on each side. The capture is 97,937,822 frames with missing 0, zero findings, and 15 reconnects each paired with a resync — including a 12-hour Wi-Fi outage recorded as a gap rather than left as a silence, during which the strategy placed no orders at all. docs/paper-run.md is the procedure.

The rehearsal also produced M4's finding in miniature, from live data: one round trip bought at 77,634.64 and sold at 77,637.67 — three tenths of a cent of price against fifteen and a half cents of fees.

A restart during the fortnight would forfeit the exact match, and that is newly understood — a mid-run restart had been framed throughout as a reader problem, this document included. The reader half is settled, and it is settled at write time rather than at read time: a reader concatenates a day's parts in index order and never merges them, and that index is trustworthy only because the writer earned it. Two sessions sharing a UTC day are written as separate parts, and before publishing the second the writer compares the venue's own update-id span out of each part's Parquet footer against the parts already there and refuses one that does not follow — refuses rather than reorders, because a part that does not follow means the sessions were concurrent, and there is no ordering of two simultaneous recordings of the same messages that is the truth. The span and not local_recv_ts, which the data contract originally called for: our clock steps, so ordering by it would reverse two sessions at the seam without saying so. The half that is not settled is state. The journal holds fills, checkpoints and the kill switch, and Engine::resuming replaces the portfolio — nothing in it carries the strategy. So a restarted paper process comes back with the right cash and position but with empty crossover windows and a zeroed equity sampler (and, until m8c-journal-readers recounted it from the journal, a zeroed daily risk tally), while the judging backtest runs all of it continuously across that same instant. Fill counts would then differ for reasons that have nothing to do with live-versus-replay, which is the only thing M5 asks, and nothing at judging time can undo it. The exact comparison needs a fortnight with no restarts.

M6 is complete, built before M5's fortnight on purpose so one long run exercises the limits too. Two deliberately misbehaving strategies live in the test suite; an oversized order never reaches the venue, and a runaway gets exactly its limit of orders out however long the run. The risk engine keeps its own tally rather than reading the portfolio, because a limit computed from the accounting can only be as correct as the accounting — and would fail in the same direction.

One M4 finding worth repeating: latency is a variance, not a cost. At 50 ms the result got slightly better, because latency moves the fill to a later book and over a 60-second horizon the sign of that move is a coin flip. So the tests assert that latency changes something, and deliberately not which direction.

Development

docker compose up -d          # Postgres (metadata only)
cargo test --workspace --all-features
cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo fmt --all

These are the commands CI runs, so a change that passes them here passes there. The environment variables the workspace reads are listed, with what each one is for, in .env.example.

Testing

A fresh clone needs nothing but a Rust toolchain: cargo test --workspace --all-features builds the workspace and runs the whole suite. Unit tests live beside the code, in a tests module or a crate's src/tests.rs, because most of what they pin is private. Each crate's tests/ directory holds the integration tests, which wire crates together or run a binary as a user would.

Two kinds of test depend on the machine rather than the code:

  • Postgres. The quant-meta tests skip themselves when QUANT_DATABASE_URL is unset. To run them, docker compose up -d and export the URL from .env.example. CI always provides a database, which is the only reason skipping is acceptable.
  • Release. Overflow checks are off in release builds, so CI runs the suite a second time with --release. Run it locally after touching money arithmetic.

CI runs both on Linux, and the suite again on Apple Silicon without the database (.github/workflows/ci.yml).

Recording

# Record BTCUSDT until ctrl-c, or for a fixed number of seconds.
cargo run -p quant-binance --bin record -- BTCUSDT data
cargo run -p quant-binance --bin record -- BTCUSDT data 60

# Inspect what landed: frames, sequence holes, gap records, tail, trailer.
cargo run -p quant-storage --example dump -- \
  data/raw/exchange=binance/symbol=BTCUSDT/date=*/session=*/part-00000.bin.zst

A clean shutdown writes a trailer, so the file states its own frame and block counts and the reader cross-checks them. A SIGKILL leaves no trailer, which is how "complete" and "interrupted" stay distinguishable from the bytes alone.

Capture files roll at the UTC day boundary, driven by each record's own receive timestamp rather than the writer's clock — so which partition a message lands in is a property of the data, not of how busy the disk was.

A book snapshot is fetched over REST on every connect and hourly thereafter, and written into the same file and the same sequence as the deltas. This is the one thing the recorder cannot defer to the normalizer: Binance's depth stream is incremental, GET /api/v3/depth serves only the book's current state, and a snapshot not taken at a reconnect can never be taken. The fetch runs concurrently with draining the socket, so the snapshot's ingest_seq lands between the deltas it arrived between — which is what tells a book builder which deltas precede the anchor and are stale. Nothing is discarded at capture time; that is M2's job, where a mistake costs a re-derive rather than a re-record.

While recording, one metrics line per minute says whether it is healthy: messages and bytes per second, queue depth and its high-water mark against capacity, messages dropped in the interval, venue-latency percentiles, and gap counts by cause. Queue depth is the one that matters most — without it, a stalled consumer and a quiet market look identical from outside.

Venue latency is local_recv_ts - exchange_ts, which measures the host clock as much as the network, so the recorder checks itself against the venue's clock at startup and warns above a one-second offset.

Reconstructing a book

# parse every frame in a capture file; reports anything that will not parse
cargo run --release -p quant-binance --example parse_all -- <path to part-*.bin.zst>

# replay a whole session through a book and check the invariants at every tick
cargo run --release -p quant-normalize --bin normalize -- data

The per-file replay example is gone, deliberately. A single file starts mid-stream with no anchor, which is where those 7,000 to 34,000 dropped deltas came from; joining a session's segments takes it to zero. Keeping it would also have left two implementations of apply recorded events to a book and check every tick, and the one nobody maintains is the one that quietly stops agreeing.

The normalized tier holds events, not books: trades/, book_deltas/, book_snapshots/, gaps/. A book is derived at replay time, never stored — storing one would mean a state per delta for something re-derivable in seconds.

Reconstruction is where the three steps the recorder deliberately deferred live, because a mistake here costs a re-derive rather than a week of re-recording: buffer the deltas, discard the ones the snapshot supersedes, and check that the chain joins. The buffering is not optional — the snapshot arrives later in the stream than the deltas it supersedes, since the recorder fetches it concurrently with draining the socket.

An invalidated book is cleared, not flagged. A flag can be ignored; an empty book cannot be misread as prices, which is what makes "refuse to trade across a gap" enforceable rather than advisory.

Verifying

cargo run -p quant-verify --bin verify -- data
cargo run -p quant-verify --bin verify -- data --reconcile   # also check the index

# and replay it: is the capture complete, and does it reconstruct?
cargo run --release -p quant-normalize --bin normalize -- data
cargo run --release -p quant-normalize --bin normalize -- data --write   # write the Parquet tier
cargo run --release -p quant-normalize --bin normalize -- data --check   # raw vs Parquet, event by event

# and run a strategy over it
cargo run --release -p quant-backtest --bin backtest -- data --symbol BTCUSDT
cargo run --release -p quant-backtest --bin backtest -- data --equity-csv equity.csv
cargo run --release -p quant-backtest --bin backtest -- data --realistic \
  --max-order 100 --max-position 100 --max-daily-loss 5 --max-orders 200

Exit 0 means every discontinuity in every session is explained by a record in the capture; non-zero means it is not. That is what makes it runnable from cron during a long capture rather than something a person reads afterwards.

Every check has the same shape — find a discontinuity, then ask whether the file already explains it, and never infer an explanation:

Discontinuity Explained by
a skipped ingest_seq the frame immediately after the hole is a gap record
a break in the venue's depth update-id chain any gap record between the two deltas
depth deltas with no book behind them a snapshot anywhere in that connection episode, or a recorded SnapshotFailed
no file trailer being the last segment, i.e. still open or killed

The unit is the session, not the file: ingest_seq spans a session, so a hole straddling midnight is invisible to a per-file check. Errors fail the run and warnings do not, because a torn tail on a file still being written is normal and failing on it would train everyone to ignore the exit code.

The risk limits on that last backtest line are quote-currency notionals and a daily order count, and they are unset by default, so a bare run is byte-identical to the one before limits existed — the same reason costs are off by default. paper defaults the other way and says why: a fortnight unattended is the wrong place for no limits, whereas a backtest whose limits changed under it would stop being a measurement of the strategy.

Metadata (optional)

Set QUANT_DATABASE_URL and the recorder indexes itself into Postgres: one capture_sessions row per run, one capture_segments row per sealed file.

docker compose up -d
export QUANT_DATABASE_URL=postgres://quant:quant_local_dev@localhost:5432/quant
cargo run -p quant-binance --bin record -- BTCUSDT data 60

Unset, or a database that will not answer, logs a warning and records anyway. Market data cannot be regenerated and an index row can, so the index is allowed to be missing and the capture is not allowed to stop. Everything in those tables is reconstructible from the capture files themselves — otherwise Postgres would quietly have become the source of truth for it.

The quant-meta tests need a database and skip themselves without one. CI always provides it, which is the only reason skipping is acceptable.

About

A quantitative trading platform in Rust — immutable market-data capture, deterministic replay, and an engine where backtest, paper and live trading are the same code.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages