The tools directory¶
Part of the reference tier. The map of the documents is MAP.md.
Everything here exists to turn a claim into a number that somebody else can reproduce. The directory names say which kind of tool a file is:
| directory | what lives there | the gate runs |
|---|---|---|
gate/ |
the gate, the six lints it calls, lib.sh (the shared shell helpers) and detach.sh (one long command, started detached) |
the lints, on every tier 1 run; check_docs.py on the pages a docs run names |
sweep/ |
the measurements that vary one thing over a window and print a table | risk_check.sh |
fetch/ |
getting data in and cutting it down: five venue fetchers, slice.py, inspect_source.py |
slice.py window, fetch_iex_hist.py --self-test |
study/ |
the studies: one question each, and the drivers that turn a window into a row | seven --self-tests, and viability.py |
live/ |
the tools that speak to a socket or a live config: relay, config reader, sender, soak, tracer, resume, the account probe, the calendar gate and the context reader | venue_relay.py --self-test, live_config.py --self-test, calendar_gate.py --self-test, venue_context.py --self-test |
export/ |
the bundle a reader that cannot clone the tree is given | no |
bench/ |
two harnesses for the performance line: the paired A/B runner and the libc call counter | no |
legacy/ |
the CSV and UDP generators for the L1 path that the demo and data/scenarios/ still use |
no |
The relay exists twice.
tools/live/venue_relay.pyis the implementation the engine's order session was ported from (ADR 0006) and stays in the tree as the reference a reader can diff the port against -- kept for review, not the route a run uses;src/lines/venue_relay_main.cppis the one a session runs. The C++ relay's order leg also serves the two questions the engine cannot answer alone -- the venue's working orders and the account's balance -- over the same engine socket (PENDING,EQUITY), and--venue-demopoints its market leg at the demo public stream.
Two things a reader can rely on, because both are counted rather than promised. A tool the gate does not run is quoted
only through a marked block that check_docs.py re-runs, so its arithmetic has a witness even when nobody runs it by
hand; and every file under tools/ has a line in the inventory below, because lint_prose.py fails a build when one
does not.
The inventory: every file under tools/, one line each
| tool | what it prints | run by |
|---|---|---|
tools/gate/verify_l2.sh |
one line per tier, and the field that moved | is the gate |
tools/gate/quiet.sh |
the first and last few lines of a command's output, and the log that holds the rest | hand |
tools/study/okx_download_rank.py |
the archived screen re-ranked for the download decision, in the two shapes the measured instruments define | hand |
tools/gate/check_docs.py |
checked N recorded run(s), 0 mismatch(es) |
gate |
tools/gate/check_written_fields.py |
checked N metric fields, 0 unwritten |
gate |
tools/gate/check_layering.py |
the include that crosses a layer boundary | gate |
tools/gate/check_links.py |
checked N link(s), 0 problem(s) |
gate |
tools/gate/check_adr.py |
a decision and its index row that disagree | gate |
tools/gate/check_deploy.py |
the couplings between deploy/, .env.example, config/live.example.yaml and deploy.yml that a host would otherwise discover -- the env names the relay reads, the template's keys, the engine's endpoints against the relay's listeners, the units' ordering, the stop window against the engine's deadline, the package step against the units' paths, RELAY_ORDER_LIVE against its venue, OnFailure= against a shipped notifier, the report's clock and sandbox, the seat template against seat 1's unit, the rollback latch, and (added 2026-11-29) the calendar both live units read against the file the bootstrap seeds -- 22 rules, each with a defect in the self-test |
gate |
tools/fetch/okx_depth_align.py |
validate a downloaded 400-level book archive and align it with another instrument: the flat {instId,action,asks,bids,ts} shape, an opening snapshot, at least 100 levels a side, a first timestamp inside the named UTC day, the two ranges printed, and --watch N for an overnight drop. --self-test builds four archives and pins the pass plus three refusals |
hand |
tools/study/knob_summary.py |
one line an arm out of a live_knobs_ab.py log, which prints no CSV: median fills, median closed P&L in bps, the positive-day count, the worst day, the median pause count and CE(0.02) -- the owner's risk ruler (docs/ROADMAP.md, "the rulers") applied to the per-window series. Its sibling sweep_summary.py prints the same CE column for a sweep CSV. It is tracked rather than a /tmp script because a collector that a reboot takes with it leaves a number nobody can re-derive |
hand |
tools/gate/check_params.py |
the parameter registry and the coupling invariants a single-value check cannot see: the schema of config/param_registry.json (quadrant, kind, authority, unit, evidence_ref per key, and derived_from for a derived money parameter), the coverage of config/params_schema.yaml's live keys (the tool prints the count), the three-way authority rule (AGENT_TUNABLE is exactly the schema's derived AGENT_KEYS; an OWNER_ONLY key the tool can write must be live_tunable, so a delegation is a visible row; a SYSTEM key is never writable), and four relations against a profile -- overshoot (limit + (1+layers)*size)*P*ctVal <= cap, stop clamp k*peak*sigma <= stop <= beta*E, order_burst >= 2*(1+layers), and the two pause rulers never both. Inputs the invariants need (--equity, --price, --sigma, --k, --beta, --ct-val) are named on the command line rather than read from a document. --schema reconciles config/params_schema.yaml against the C++ defaults and parse branches, the registry and the runtime reader's own parse of the same file, key by key, and prints every difference. --self-test pins a clean profile, five mutations each naming its invariant, and a derived dollar with no formula refused |
--self-test |
tools/gate/check_seats.py |
the Phase-1 seat mirror: reconciles config/seats/<seat>.yaml (one file per seat: instrument, profile, ceiling, floor, ports, contract size, tick, lot, window, venue, bar) against the named profile's engine.symbol/max_exposure_usd/link endpoints, config/liquidity_floors.json, and config/account_policy.yaml -- the ceiling is declared once and its two copies must be the same number, no two seats share a port, the bar is present, and sum(ceiling) stays inside max_total_ceiling_usd (write-time). The run-time max_ceiling_to_equity refusal is seat_inventory.sh's, not this file's. --self-test pins each refusal on a synthetic mirror |
--self-test, --check |
tools/gate/params_schema_gen.py |
writes config/params_schema.yaml, the one declaration of the live keys: the authored fields (name, flag, group, live_tunable, live_required, positional position, cpp_field and the live_refused/requires/required_with couplings) are the file's own, type/default/range are derived from the AppConfig member and parse branch in src/app/app_config.* with the parser's own refusal sentence kept as the range's source comment, and the classification comes from the registry. --write is idempotent and --check refuses drift by re-rendering and diffing; tools/live/live_config.py reads the file at run time |
gate, through check_params.py --schema |
tools/study/market_density.py |
the whole OKX USDT-swap market's trade density, one row a symbol: 48 half-hour UTC buckets plus the 04:30-12:30Z and 15:30-23:30Z windows and their weakest bucket, --min-rate for the Stage 0b 2.5/s floor; reads an allswap-trades-<day> CSV or zip as a stream, n/a for an empty or uncovered slice |
|
tools/study/window_sigma.py |
the three-hour price sigma a stop's noise bound needs, per day, from the trade tapes: the last print of each minute inside the window, the standard deviation of one-minute log returns scaled by sqrt(minutes), and the two aggregates a bound is quoted from -- the median and the p95 -- with L_noise = k * Cap_eff * sigma printed at each --k. The price is the last trade print rather than the mid (a tape has none, and a mark uses the mid), which is the one approximation and is stated in the docstring; a day with fewer than half its minutes printed is reported and left out, because a sigma from five prints describes the tape's gaps. --self-test pins an alternating tape against the closed form a * sqrt((n^2-1)/(n(n-1))) and refuses a sparse day |
--self-test |
tools/study/trade_turnover.py |
what an instrument actually traded on each UTC day, from the trade tapes: the print count and sum(price * size), one row a day, with the day taken from the tape's filename rather than a print's clock because a tape's last prints spill past midnight. It exists because the venue's own turnover_24h_usd reaches about thirty days back, so a dead month cannot be read from it (the NES floor in docs/ROADMAP.md is the worked example). A tape with no readable row, a directory with no tape, and a day asked for and absent are each refused by name; a row with an unreadable price or size is counted and reported rather than skipped quietly |
--self-test |
tools/study/portfolio_stress.py |
two seats merged into one account: the joint per-day series, sweep_summary.py's gate applied to it in USD, the correlation and worst-day overlap, and the margin both seats fully loaded need at each leverage (peak position from max_inv, priced at the archive's own print) |
hand |
tools/sweep/up_ten_contract_cell.sh |
the ten-contract cell and its state arms in one script: the control, --jump-ticks=2 and the registered --jump-ticks=3, with the bar and the three measured rows in the header. Exists because the cell was recorded by reference and the flags that rebuild it (--extra-layers=1, --settle-slippage-ticks=1) were in a /tmp driver; --symbol/--tick run the same cell on the other seat, which is what the two-seat ranking needs |
hand |
tools/sweep/post_only_refusals.sh |
what a venue actually refuses, as a share of submissions: the live file's shape and the frozen cell's, over one flat day and one trending day, as a grid of quote distance and latency. It exists because the live window of 2026-11-29 read 682 refusals in 738 orders -- and 738 = 682 + 56 fills with 679 cancels requested, i.e. the strategy's own re-quotes. Measured 2026-11-30: 0.0 / 0.0 / 0.3 percent at 0 / 10 ms / 100 ms on 2026-11-19, 0.0 / 0.0 / 0.5 on 2026-11-26, 0.6 / 2.2 / 3.3 percent at 0.3 / 1 / 3 s, and 0.2-0.5 points of change from a one-tick quote against a three-tick one. The zero-latency arm is a checked control: a non-zero share there is the strategy pricing through its own book, and the script fails | hand |
tools/sweep/window_grid.sh |
the schedule line's first cut (Tier 1 #9): the same frozen cell at four equal two-hour slots of the same UTC day -- the recorded 13:30-15:30, 00:30-02:30, 07:30-09:30, 20:30-22:30 -- by calling up_ten_contract_cell.sh once per slot with only --start/--end moved, then one sweep_summary.py line per window. It exists because every closure was measured inside one window that is a restriction written before measurement, and nothing in the frontier map prices the constraint; --days/--windows/--arm/--out narrow the grid, and the bar is registered in docs/ROADMAP.md and in the script's own header |
hand |
deploy/report_seats.sh |
the 15:35 report for every seat: seat 1's journal, then one per line of /etc/toyquant/seats, each row read from toyquant-live@<seat> and written to window_ledger-<seat>.csv (daily_report.py --seat). A wrapper rather than a timer per seat, because the report is a property of the account's day: N seats cost N rows and N mails, not N timers to keep in step. A seat that fails is named and the rest run; the exit status is the first failure |
the report unit |
deploy/seat_files.py |
a second seat's two files, written from a spec instead of by hand: renders live-<seat>.yaml from the shipped config/live.example.yaml (the shape a deploy proves), writes live-<seat>.env with the instrument facts and its two ports, refuses seat 1's 8765/8766, a ceiling above the template's, an instrument that is not a venue perpetual and any key it does not know, checks the result with live_config.py, backs up what was there and only then moves it in. Driven by --ops seat; --dry-run prints both files and --self-test proves the refusals in a temp dir |
hand + --ops seat |
tools/live/calendar_gate.py |
whether a seat's window may open: two layers in one file. The token layer closes band_hours either side of a cliff-release day (the NES row); the macro layer closes the window an instant falls inside, written as 08:30 us-eastern and converted by the reader, because 08:30 is 13:30 UTC in winter and 12:30 UTC in summer. Two policies -- skip refuses (exit 3, which is what an ExecStartPre needs) and warn allows while naming the event -- and a macro row whose date is not marked verified is downgraded to a warning, so a guessed date is visible in every run instead of silently closing or opening a window. A file under calendar.d/ that cannot be parsed warns and is skipped, while the operator's own calendar.yaml keeps refusing: the meta table says no meta row can open or close a window, and a status-only cross-check file is where a meta row is all there is -- measured 2026-11-30, when a clean cross-check wrote note: "", the empty value refused the file, and the live unit's ExecStartPre would have stopped the 13:30 session. --list prints the next --days of events. Its self-test pins both DST directions, the band's two edges, a lead, an unverified row, seven typos it must refuse and the auto-layer warning it must not |
the live units' ExecStartPre, gate |
deploy/calendar.yaml |
the calendar itself: the NES cliff (2026-12-24, 20.78M tokens, 8.1 percent of circulating) and the BLS CPI/NFP and Fed FOMC dates, each with its source and a verified flag. Tracked and shipped because the deploy bundle is git ls-files -- an ignored calendar cannot reach the host, and a gate reading a file the host never received would allow every window in silence. deploy/bootstrap_server.sh seeds /etc/toyquant/calendar.yaml once and never rewrites it, so an operator's own rows survive a deploy |
bootstrap, check_deploy |
tools/live/sync_venue_calendar.py |
the calendar's one fetched layer: the venue's scheduled maintenance from GET /api/v5/system/status (keyless, the venue's own statement), written atomically to /etc/toyquant/calendar.d/venue.yaml with a meta block naming the fetch time, its result and the row count. A failed fetch keeps the rows it already knew and records the failure, so a rate-limited morning (code 50011, measured 2026-11-29) does not erase a known upgrade. --cross-check compares FairEconomy's USD high-impact week with the operator's macro rows and writes a status-only file: an aggregator may warn, never close a window. Runs from toyquant-calendar.timer at 01:00 UTC; --self-test pins both epoch forms, the carry-forward, the atomic write and the comparison |
toyquant-calendar.timer |
tools/live/venue_context.py |
the three public numbers a window is read against, over the 24 hours before its open: turnover_24h_usd and oi_change_24h_pct from the venue's hourly statistic, funding_rate from its funding history. Keyless, one read per series, --row/--csv/--json for a caller. A missing series is an empty cell with a reason, never a zero, because a turnover_24h_usd=0 reads as a dead instrument -- which is the fact these columns exist to distinguish from a quiet strategy. The arithmetic is the self-test's: a day is 24 points, a floor of 12 refuses a short series, and the funding row is the newest one at or before the open |
daily_report.py, env_columns.py, gate |
tools/study/env_columns.py |
a sweep's per-day rows joined with those three columns through a day-keyed cache, so a cross-month reversal can be read as market-versus-engine without a session spent looking for news (docs/ROADMAP.md's NES row is the worked example). The context is not fetched by the sweep -- a replay of local depth must not depend on an exchange's uptime -- so --fetch fills the cache separately, one flushed line a day, and a day the venue's history no longer reaches is named and exits 1 |
gate |
tools/study/window_admission.py |
the registered red lines as code: one line a candidate window, each of the six clauses printed with its number beside its limit, then PASS or FAIL(reasons). The four admission clauses are the fill floor (25 for 2 h, 12 for a 1 h atom), the thin-day share (15 percent), the leave-one-out median (positive) and the best day's share (0.35); the two replacement clauses are CE(0.02) and the positive-day share, both against the baseline's own numbers. The arithmetic is sweep_summary.py's, imported rather than re-implemented, and --self-test builds a pass and three fails. Since 2026-11-29 it is the record's arithmetic: a candidate measured from then on is decided by significance.py and the methodology page |
gate |
tools/study/significance.py |
the screening funnel's arithmetic: a day's net dollars, the Sharpe ratio per observation, Mertens (2002)'s standard error under skewness and raw kurtosis, the deflated ratio against the expected maximum of N zero-skill candidates taken over the null variance 1/(T-1), and the marginal test against --baseline with the condition SR > max(0, rho * SR_P). --alpha is the owner's significance level, --trials defaults to the participation ratio of the trials' correlation matrix (N_eff = N^2 / sum c_ij^2, duplicates and nesting counted once), --explicit-trials forces a count for a sensitivity check, and --tails prints the days that carry the skew with the skew each removal leaves. A duplicate series is named on the output so N can be audited, a CSV whose net_usd cannot be read is refused by name, and --self-test pins the moments of [1, 2, 3], a flat Sharpe, the hurdle rising with N and falling with T, the effective count of a duplicated and of an orthogonal set, the tail by removal and that refusal |
gate |
tools/study/sim_vs_real.py |
the queue model's error, one line a window: reads the live order record (record_stats.py, the fill_rate and the local_us round trip) and the window ledger's net_pnl_usd beside a replay's row (okx_maker_baseline.py --out), and prints the signed gaps -- fill_rate and net_usd, sim minus live -- with the record's own p50 latency named, so a gap is the model's error rather than the venue's. The replay must have been started with the record's measured latency (the AGENTS rule that a replay reproduces one live window, latencies from the record's own rows); a record whose round trip is not measurable prints latency=unmeasured. --self-test pins the sign, the rounding and the unmeasured hole |
--self-test |
tools/study/sim_vs_real_daily.py |
the daily Sim-to-Real driver: reads the record's p50 round trip and the seat profile's strategy keys (yaml), starts okx_maker_baseline.py with --latency-us=<rtt> and those keys, then hands the replay and the record to sim_vs_real.py. One command, so the replay runs the geometry that traded and the record's own latency rather than a re-typed guess. --dry-run prints the replay command; --self-test pins the profile-to-flag mapping and that a profile hole drops the flag rather than defaulting one |
--self-test |
tools/ops/jobq.sh |
the serial queue the heavy measurements run in: a job is a file with four cells -- the command, the artifact it writes, the tool that reads that artifact, and the bar that closes it -- so the row a session used to keep in .handoff.md is a file in the out root's jobs/ now (TQ_OUT_DIR, default out/jobs/). add registers one, run starts the detached runner (one job at a time, nice 10, and a disk guard that marks a job blocked rather than filling /tmp), status prints state, start, exit, artifact size and bar, tail reads a job's log, stop finishes the current job and then stops. State lives in the tree rather than in /tmp, so a reboot loses the log and not the queue, and a failed job does not stop the jobs behind it. A job carries the binary it ran on (sha256 and the commit, recorded by add), and status says ran on another binary when the current build differs; --verdict "<command>" runs the consumer once after a successful job and stores its last line as <name>.verdict, which status prints last -- a job whose artifact nothing reads is a wait, not an experiment; and status warns when a done(0) job's artifact is absent, which is the shape that hid twenty-two guessed paths on 2026-11-29; --post-hook "<command>" runs a command detached after a successful job (the Google Drive lane's rclone upload -- a multi-gigabyte copy that never blocks the next job), its log at <name>.hook.log; and status exits 0 once the table printed, whatever the last row carries |
hand |
tools/ops/cloud_sync.sh |
the Google Drive lane's one rclone wrapper: copy and sync with the pacer flags that stop gdrive's rateLimitExceeded (measured 2026-12-02, a bare four-transfer run sat 3h25m) -- two transfers, four checkers, a three-transactions-per-second cap, a 200 ms minimum sleep between drive requests, and five retries. jobq's post-hook and the EOD sync name this script rather than rclone, so the flags have one home; the dry-run form prints the command, check verifies rclone is on PATH, and the self-test pins the flags and both verbs |
--self-test |
tools/ops/eod_sync.sh |
the close's cloud tail: after each seat's window it syncs the generated record -- the ledger a window appended, the close-out's verdict and journal paste, the study CSVs -- from the out root's runtime/ and study/ to the ops layer of the lake (gdrive:ToyQuant/ops, overridable with CLOUD=), then regenerates the content-addressed data manifest (data_inventory --write-manifest) and pushes it to the manifest layer (gdrive:ToyQuant/manifest), on top of cloud_sync.sh. The tracked documents already ride the bundle sync; this moves what the bundle does not carry. The dry-run form prints the commands, and the self-test pins that each root names its layer |
--self-test |
tools/ops/hydrate.sh |
the pre-replay hydrate: pull the raw layer's archives this host is missing (gdrive:ToyQuant/raw/crypto, overridable with REMOTE=) back onto the data root, so a replay reads local disk instead of listing the remote; rclone copy skips files already here, so it is on-demand by construction, and naming a symbol pulls just it. On top of cloud_sync.sh; the dry-run form prints the command and the self-test pins the pull direction |
--self-test |
tools/ops/disk_guard.sh |
the data disk's floor: warn (and exit nonzero) when the SSD holding the data root has less than FLOOR_GB (default 30) free, and name the audited eviction that frees it (data_inventory --prune old --keep-days 60) -- the lake keeps the raw layer on the cloud, so old local archives are the first to drop and hydrate.sh pulls them back. A free-gigabyte override simulates a nearly-full disk for the self-test, which pins the threshold both ways |
--self-test |
deploy/install_profile.sh |
write a profile the tree carries onto a seat's config: it solves the pair's inventory_limit from the venue's live mark at the apply (the risk budget stays max_exposure_usd; a mark with no room refuses), validates with the reader the unit's ExecStartPre runs, keeps the replaced file as <name>.bak-profile, installs 0640 for the service group, and restores the backup when the reader refuses. Seat 1 is the plain unit's pair (live.yaml/live.env); a named seat is live-<seat>.yaml/live-<seat>.env, and the same mapping reads the contract size. The file it installs is a derived copy -- the profile it is given is never rewritten |
--self-test |
tools/ops/tq.sh |
the entry point's first verb: status composes resume.sh's tree/handoff/queue screen with the two roots, the registry's coverage line and the live template's config check -- the facts a session used to collect with five commands -- and an unknown verb is refused by name |
--self-test |
tools/ops/resume.sh |
where the work stands in one screen, for a session that was compacted or starts cold: the tree (HEAD, origin, uncommitted), the handoff's state block, the queue with its failed/blocked/artifact-warning counts, and the three commands that read a number. --full prints the whole handoff and the whole queue. Exit is 1 when the tree is dirty or a job failed, so it can be a gate |
hand |
tools/ops/jobs.py |
the three views of a run that dispatch_deploy.sh logs needs: list prints each job and the steps that did not succeed, failed prints the job ids that did not, tail N prints the last N lines of the job log zip the API hands back, and lines prints the whole log without the two-space prefix so a parser (window_ledger.py --from-log) reads a record rather than a rendering. Split out because a bash function that both parsed JSON and unpacked an archive was the third quoting layer in one line |
hand |
tools/ops/dispatch_deploy.sh |
the deploy loop without a browser: run dispatches deploy.yml (or ops.yml with --ops <action>), and --key/--value/--add carry set-key's inputs zipped in order (--ops unset-key --seat <s> takes --key as the line pattern to remove from the seat's env, default TOYQUANT_), so a setting is applied without the browser; wait blocks to the conclusion of the run run dispatched (run records the new id and wait follows it through runs/<id>; the newest-run loop is the manual fallback), status prints the newest run of each, logs names the job and step that failed, window dispatches --ops ledger, saves the series to the out root's runtime/window_ledger.csv (TQ_OUT_DIR, default out/runtime/) and prints it -- the window's own numbers reaching this tree without a journal pasted by hand -- and record [--since ISO] [--until ISO] [--save PATH] dispatches --ops record, writes the window's rows to that root's runtime/record-*.csv with record_dump.py, and prints record_stats.py's table on it, so the artifact and its reader travel in one command. Reads secrets/gh.token -- a fine-grained token with Actions: Read and write and nothing else -- and refuses a dirty tree, a second concurrent dispatch, data_gate=true, a setting named for a workflow that carries none, and --since/--until on any action but record |
hand |
tools/fetch/data_inventory.py |
classify a data/ tree: every file as a symbol, a kind (400-level depth, trade tape, other) and a day, with sizes per symbol, and the findings that cost a run when they are found late -- partial downloads, a day with only one of the two files, the same day in two layouts, an unreadable gzip, days older than a retention. --write-manifest PATH writes one JSON line a file (symbol, day, bytes, mtime, fast_sha256 over the first and last 64 KB plus the size) and prints the manifest's own hash, so a report can name the tree it read; --prune deletes only under an explicit rule and prints each path |
hand |
deploy/notify.py |
one mail when a unit fails: the unit, the host, the four properties that name the ending and the journal tail; unconfigured-safe, --dry-run prints it, --self-test pins both paths |
host |
deploy/order_summary.py |
the order record summarised where it lives: counts by kind, by cancel reason and by reject reason, then the last rows with their prices -- the reading a post-only refusal is localised from. Refuses a file whose header does not start with the recorder's fifteen columns (the recorder gained local_us and mid on 2026-11-30, and a reader that demanded equality would refuse every record the new binary writes), and an empty record. --rows prints the selected rows as the recorder's own CSV instead, bounded by --since/--until in ISO-8601 UTC and converted into the record's own clock unit, measured from the file (a 13-digit ts is milliseconds, a 16-digit one microseconds); the dump keeps every column the file carried, because a dump written to the reader's own fifteen would drop the clock and the mid the record exists to hold; an empty selection is refused by name, because a dump of nothing reads as a quiet window. --self-test pins the counts, the symbol filter, both refusals, the clock read, the window and a seventeen-column record |
--ops orders, --ops record |
tools/live/liquidity_gate.py |
the L4 gate: whether the instrument's last 24 hours look like a live market, from the one public series venue_context.py already fetches (turnover_24h_usd over [at-24h, at), keyless). Three outcomes and no fourth -- pass (0), a dead season or an unmeasurable series (3), an internal error (255) -- because the unit line is an ExecCondition=: systemd treats 1-254 as "condition not met, skip" and marks nothing, while an ExecStartPre= returning 3 would mark the unit failed and the host degraded for a market that is only closed. A gate with no positive --floor-usd is refused as a failure, since a gate without a floor opens every market. --row prints the one key=value line a skipped window keeps, so the journal names the number and the floor. The order venue is asked first, because it is the same question: the ticker of the venue the orders reach (RELAY_ORDER_LIVE picks the demo's header), and no 24h volume or a one-sided book skips the window whatever the production floor says -- measured 2026-12-01, the demo's NES read ask 0.2322 / no bid / volume 0 while production read 0.3308-0.3312 on 61.2M, and the 01:30Z window filled none of 2,730 orders. An instrument the order venue's public API does not list (UP returns 51001) is unknown and falls through to the floor, because the private leg can still serve it. The line names the series: source=venue_24h when the hourly series answered, source=venue_ticker when the gate fell back to the order venue's own ticker volCcy24h (so an unreadable series does not silently close a live market), none when neither did. Before all of it, the dirty lock: /var/lib/toyquant/locks/<seat>.dirty (the seat from the config's basename: live.yaml is 1, live-<name>.yaml the name) skips the window with the lock's first line in the journal -- a window whose close-out left a position or no end-of-window recon does not start itself |
--self-test |
tools/live/record_dump.py |
the window's record out of an --ops record job log: the runner timestamps that prefix every line are stripped, the header is found by the fifteen names it starts with (the record gained local_us and mid), and the rows are written with the record's own header -- the width is read from that header rather than from this file's constant, so a dump is the file the session wrote and not a narrower copy of it. A log with no header, or a header with no row under it, is an error rather than an empty file (the 2026-11-28 lesson); --self-test pins the prefix, a repeated header, the epilogue, a seventeen-column record and both refusals |
--self-test, dispatch_deploy.sh record |
deploy/record_window.sh |
the --ops record action's body, on the host: the seat's file (or seat 1's), the two ISO bounds passed to the reader untouched (it is the one place that converts an instant into the record's clock unit), and the rows printed by order_summary.py --rows. A script rather than an inline branch because the workflow's remote heredoc had reached GitHub's 21,000-character step limit -- an inlined branch answered 422 ... Exceeded max expression length 21000 and no action ran at all (measured 2026-11-30) |
--ops record |
tools/live/record_stats.py |
the record's three measured distributions -- round trip time from a submission to its first report (p50/p90/p99, measured on local_us when the record carries it, which since 2026-11-30 it does: the writer's own microsecond clock on both ends, one clock and therefore subtractable; on an older record the only pair is ts, and that one is refused by name when a first report predates its own submission -- 359 of 738 on the 2026-11-29 window, because a submission carries the engine's event clock and a report the venue frame's market time; the line names the clock it used), the post-only and reject rates per submission, and the funnel's counts -- with --since/--until selecting one window from an appended file and --day/--close-window splitting the wind-down's fills out of the session's. A fill is a trade report and only that (an acknowledgement carries liquidity_role=unknown, and counting those read 1,532 fills against the journal's 56), and the post-only line is split by who ended the order: a post_only report with no cancel of ours before it is venue_declines, one after it is own_cancels -- the difference a lazy label hid for a week. The input to a sim-to-real calibration: the numbers a replay default may be replaced with, measured rather than assumed |
--self-test |
deploy/seat_probe.sh |
a seat's startup run outside the window: refuses between 13:25 and 15:35 UTC, beside a running instance, and on a seat whose clip is not one contract -- the ceiling is capped at PROBE_CEILING (50 USD) rather than refused -- a seat's ceiling is the owner's risk number and the probe's own safety is the cap it forces (the NES seat reads 40 USD, --ops seats, 2026-11-30); renders the seat's flags as the service user (so an unreadable file fails here, not in a start loop), starts the relay, runs the engine for a few seconds with its own record prefix and the seat's repricing suppression zeroed (the 40,000 a seat carries means a probe of seconds would never reach its first order), and reads [START] step=... back -- the last step printed is where a hanging start stopped -- with the strategy's own end-of-run lines ([STRATEGY_METRICS], [EXECUTION], [SHUTDOWN]), because a probe that reports "no orders" without the counters is reporting a fact and hiding its cause. It then prints the record it wrote through order_summary.py, so the prices and refusal reasons of those seconds reach the job log instead of a file on a host nobody reads. --self-test pins the rewrite (including the ceiling cap), the clip guard and the window refusal |
--ops seat-probe |
tools/live/close_cost.py |
what a wind-down really cost: the mid from the day's own 400-level archive at the moment it began, the price that archive's book offered for the quantity (--quantity, and --tick to print the distance in ticks), and the recorder's own fill for the same window. The last line is the whole measurement as one key=value line, so a page's marked block re-derives it rather than quoting a copy. Measured 2026-11-29: 7 contracts sold at 0.2177 cost -0.0889 USD, -58.3 bps of notional, against the replay's 2.30 bps. Calibrated 2026-11-30 on the two closes whose book is on disk: the 2026-11-27 book takes 50 contracts at the bid itself (-11.33 bps, 2.00 ticks) and 2026-11-26's takes 104 at 0.216087 (-7.51 bps, 1.63 ticks), so the touch absorbs the residual and --settle-slippage-ticks=1 is one tick of pessimism. A ladder mode answers the admission question the single moment cannot (2026-11-30): --from/--to/--every with --ladder 10,25,50,100 and --budget-bps makes one pass over the archive, samples the book on the cadence, walks it for every quantity, and counts the moments inside the concession -- measured on abs(walk - mid), so a buy and a sell read the same number. On NES's 28 recorded days at 01:00-04:30 quarter-hourly a 50-contract sell stays inside 10 bps on 296 of 420 moments (70.5 percent), worst 19.22 bps, against 359/420 at ten contracts and 229/420 at a hundred -- a size floor, not only a flow floor |
--self-test |
deploy/start_seat.sh |
one seat's pair, started after the identity of its two files is repaired: /etc/toyquant is 0750 root:toyquant and the unit reads its config as that account, so root:root 0640 is a window that never opens -- measured 2026-11-29, the NES seat failed five times in thirty seconds with Permission denied, and the dispatcher had no verb to start a single seat. --no-start repairs and reports; --self-test pins 0640 and the missing-seat refusal |
--ops seat-start |
deploy/seat_inventory.sh |
the host inventory in one answer (L2): every seat, its ceiling and its two ports, its unit's state and its last [RECON] at=end, then the ceiling sum beside the account's own equity as a ratio -- notional against cash is a leverage figure, not a verdict. A seat whose files are missing is named and the rest still print, and the exit is non-zero; --self-test builds a temp etc dir and pins the two-seat sum plus that refusal |
--ops seats |
deploy/activate.sh |
the host activation a deploy performs, as one tracked script instead of a single-quoted ssh argument: daemon-reload, reset-failed, a bounded start of the relay that prints the attempt it succeeded on, the port wait, the preflight, and a session report that never touches a running session. A start that will not come up is a warning, because --ops restart and the 13:30 window are the proofs that work |
hand |
deploy/relay_restart_guard.py |
the guarded Relay restart: restart the relay only when it is safe and only when there is new code, as a separate action never a merge. Three guards must all pass -- a non-trading window (now outside every seat's window, read from the seat manifests config/seats/*.yaml so a new seat's hours close the window without touching the guard), no live session (no engine unit active), and a deploy landed after the relay last restarted (the RELEASE mtime against the relay's ExecMainStartTimestamp, an unreadable one refuses) -- then it restarts the relay and waits for its ports; the preflight is the caller's. --check prints the guards' verdicts and restarts nothing; --self-test pins the window edges, the session states, the newer-deploy-vs-start code guard, and the manifest-loaded window |
--self-test |
deploy/retire_seat1.sh |
the fold's first step: remove seat 1's facts from the shared live.env (its instrument, its two ports 8765/8766, its window) and keep the credential -- the long-term n-seat shape where live.env is the shared credential and live-<seat>.env is each seat's facts. It is the step the fold is blocked on: --ops seat --seat up refuses 8765/8766 while live.env still holds them. --check prints the lines it would remove and changes nothing; it backs up before removing. --self-test pins that the facts go, the credential and the relay line stay, and a backup is written |
--self-test |
deploy/fold_finish.sh |
the fold's last step: enable toyquant-window-start@up.timer/stop@up.timer (with the seat's own hours as a drop-in, the reset line first) and retire the plain unit's timers and services, so the next 12:30Z window opens the instance and not the fact-less toyquant-live.service. --check names the enable and the disable and changes nothing; --self-test pins the clock read |
--self-test |
tools/ops/predeploy.sh |
everything a deploy can be told locally before any SSH exists, in under a second: both workflows parse, deploy.yml's remote heredoc parses, every deploy/*.sh and tools/ops/*.sh passes bash -n, check_deploy and both self-tests pass, lint_prose/check_links agree with the tree, and a dirty tree is refused. dispatch_deploy.sh run calls it unless --no-predeploy |
hand |
tools/ops/seat_activate.sh |
one seat's enablement as one sequence: the live mark, the limit solved from it, the read-only --ops account probe (permission list, account level, position mode, USDT cushion, leverage), the couplings check on the derived pair, the seat's effective venue (refuses a demo leg), then the profile install (the host derives again), the preflight and the short seat probe. --dry-run stops after the read-only half. It never writes the seat's venue trio or key |
--dry-run |
tools/ops/closeout_check.py |
the close-out review as a check: one window's ledger row against that window's order record, through record_stats.py's reader -- fills by role, the post-only split (venue declines + own cancels), the fee sum, and net = gross - fees, plus the window's own label (12:30-15:30 UTC for seat 1) and, when a journal is given, the two [RECON] at=end lines. Three verdicts and the unknown one is not a pass: pass (0), fail (1) with the broken clause named, unknown (2) when a cell was empty. --self-test pins a reconciled window, each break by name, and the empty cell. It exists because the A1 bar is the decomposition, and a read that is not a check is the row a session can talk itself into. The residual clause reads both the row's residual_units and the recon's venue_units (both must be zero); when it fails, or the end-of-window recon is missing, the review prints [CLOSEOUT] LOCK and the wrapper turns that into the host lock. A window whose ledger says more than one session restarted: the recorder truncates at a restart, so the per-session clauses reconcile the last session and the sessions clause names the restart; the money tolerance is 1e-5, the ledger's own five decimals |
--self-test |
tools/ops/seat_day.py |
the N-seat plan's second item: one verdict per seat-day -- PASS | SKIP | DIRTY | UNKNOWN, one line, the reason beside it -- by reading the same three artifacts (the window series, the order record and a journal extract, named like closeout_check.py's) and reusing that review's reconciliation, so "reconciled" has one definition. PASS is closeout's pass, DIRTY its fail, UNKNOWN its unknown; SKIP is a window that never opened (the journal names the gate: the L4 verdict=skip row, the calendar's skip, the dirty lock, or no session lines at all). --write appends the line to a seat-day ledger (one line per seat-day), the durable record the mail and the EOD sync read. --self-test pins pass, a dirty residual, a named skip, an empty-journal skip, an unknown hole, and the append |
--self-test |
tools/ops/window_closeout.sh |
one window's close-out in one command, for the scheduled read after the close: --seat, --date, --start/--end, --out (default the out root's runtime/closeout-<seat>-<date>/). It refuses a dirty tree (the dispatcher would), then fetches the ledger row, the record, the seat inventory and a journal extract through dispatch_deploy.sh, and runs closeout_check.py on them with the journal -- the artifacts and the verdict land in that directory, so the next session reads files rather than a transcript. Seat 1 is the plain unit pair: its series is the shared window_ledger.csv and its record live_orders.csv, so the fetches name no --seat; a named seat is @name and reads its own files. A [CLOSEOUT] LOCK line in the check output dispatches --ops lock --seat <seat>, so the seat's next window is skipped by the gate until a human unlocks it |
hand |
tools/ops/window_ledger.py |
the window series as a series: --table one line a window (fills, fees, net, gross, residual, equity, markout, and the order path daily_report.py now carries -- submissions, cancels, post-only declines, the rate-limited count and the strategy's refresh and pause counts), --progress N the cumulative fills against a target and the weeks left at the current rate, --check monotone windows with one row each, --emit a two-line SVG, and --context the instrument's own series beside the window (turnover, open-interest change and funding for the 24 h before each open, written by daily_report.py). --from-log rebuilds the CSV out of an --ops ledger job log and --save writes it under the tree, which is how the series is read without a journal pasted by hand; a log with no CSV in it is refused rather than saved empty. It exists for the live sample's own question -- 300 to 500 fills before its markout can be compared with the replay's, whose 28 days read a median of +0.416 and a worst of -0.808 |
hand |
tools/gate/check_leaks.py |
a secret, a machine path or a private file that a commit would publish; --audit reports the deny-list's remaining public surface without failing |
gate |
tools/gate/check_sweep_columns.py |
sweep columns: ok -- the sweep's CSV against the two one-minute runs the gate makes |
gate |
tools/gate/lint_prose.py |
a flag, model, path or size figure the documents get wrong | gate |
tools/gate/lib.sh |
field_of and emit_block, sourced by the shell tools |
sourced |
tools/gate/detach.sh |
the log path; the status lands in /tmp/<name>.exit beside it |
hand |
tools/sweep/fee_sweep.sh |
PnL before fees, what closed, what the schedule kept | hand |
tools/sweep/latency_sweep.sh |
one row per order and cancel latency, 1 to 50 ms | hand |
tools/sweep/limit_sweep.sh |
what the kill switch saves, and what it costs | hand |
tools/sweep/trend_sweep.sh |
one row per --trend-params cell on one slice |
hand |
tools/sweep/equity_schedule_sweep.sh |
which queue model the equity tape supports | hand |
tools/sweep/multi_day_check.sh |
one measured row per Deribit day | hand |
tools/sweep/workload_matrix.sh |
the four fill levers around one window | hand |
tools/sweep/risk_check.sh |
four runs and the invariant each one holds | gate |
tools/sweep/compare_runs.sh |
one row per field, one column per variant | hand |
tools/sweep/f4_windows.sh |
the F4 and equity windows, re-run | hand |
tools/sweep/okx_maker_baseline.py |
one row per day per queue model for one L2 strategy inside a UTC window -- fills, fees, gross, net, breakeven, and the inventory the window ended holding -- with --strategy choosing the line (the maker by default, trend_l2 and execution_l2 on the same cut and columns). The cut is keyed by both bounds: okx_<symbol>_<day>_<start>_<end>.jsonl plus a <cut>.meta.json (symbol, day, start, end, tick, archive name/bytes/mtime, rows); a cut whose meta declares another window is refused, and a legacy cut (no end in the name, no meta) is read with a warning so a warm cache is not thrown away. Every row carries data_sha: the manifest's twelve characters for the symbol's and the day's files, so a row traces to the bytes it replayed (n/a when no manifest is present) |
hand |
tools/fetch/fetch_databento.py |
a downloaded day, split into a depth CSV and a trade CSV | hand |
tools/fetch/fetch_deribit_options.py |
one straddle a month and its implied volatility | hand |
tools/fetch/fetch_funding_rates.py |
one instrument's funding series as a CSV carry reads |
hand |
tools/fetch/fetch_iex_hist.py |
the container walk over a pcap, and its refusal | both |
tools/fetch/fetch_okx_trades.py |
one UTC+8 day of OKX trades cut to one symbol, or a window: --from/--to with --pause (a rapid loop answers HTTP 429), --skip-existing to resume, --output-dir for the per-instrument folder; each venue-wide zip (166-615 MB) is deleted after slicing |
hand |
tools/fetch/prefetch_windows.sh |
the days the next questions will need, three blocks with the question written above each: UP's sixty-day sample (2026-09-28..2026-10-29, the second month the "one month is one regime" argument asks for), NES on the same 28 days as UP (a seat comparison needs one sample), and the first live window's own day. --block N runs one; both fetchers take --skip-existing, so a re-run costs nothing and the script is safe on a timer |
hand |
tools/fetch/fetch_okx_depth.py |
OKX's 400-level book archive for one instrument, one day or a window, at the portal's own URL shape (/cdn/okx/match/orderbook/pro/L2/400lv/daily/<stamp>/<sym>-L2orderbook-400lv-<day>.tar.gz, measured 2026-11-27 after eight guessed paths answered 404); each file is refused unless its single .data member opens with a snapshot for that symbol stamped inside the named UTC day, and a 404 (a day before the listing) is named instead of stored |
hand |
tools/fetch/fetch_okx_index.py |
the venue's index series for one instrument, one minute bars, one day or a window: the number a swap's mark price is built from, so a perp-index basis has a series even where no spot book is listed. /api/v5/market/index-candles serves the recent bars and /history-index-candles the older ones, both code 0 on 2026-11-28 (a live bar at 0.1997-0.2001, a thirty-day-old one at 0.1388), a hundred bars a call and no key; an empty page is the end of the history rather than a failure, a refusal is retried, and a day with no bars is written as a header only |
hand |
tools/study/fill_basis_asymmetry.py |
the perp-index basis at each maker fill, bucketed into deciles with the buy share and the one-second markout beside each bucket: reads the replay's own record, the window cut's mid series and the index bars above, and --split DAY prints the bottom decile's lean in two halves, which is how Tier 2 #5's sign-stability bar is read as a line instead of an argument |
hand |
deploy/release_path.py |
the release-path classifier: a diff is light only when every changed path is one of the card's six (three directories, *.service, *.timer, *.env.example) and none names a program; empty is full, because a classifier told nothing must not answer "light". --self-test pins twelve paths, a mixed list and the empty one; check_deploy's nineteenth rule holds its allowlist to the card |
hand |
tools/study/fill_decomposition.py |
the window's P&L as spread + drift - fees, reconciled against the sweep CSV's net_usd: spread is each maker fill's edge at the instant, drift is that fill marked at the window's last mid, fees come from the record. It prints the gap per day and refuses to quote the split when the identity does not reconcile -- three of twenty-one days reconcile today, so what it delivers is the method and the open question (the residual's valuation), not a table to cite. --record PATH [--end-mid PRICE] [--curve] closes one record with no cut beside it: gross is sum(sells) - sum(buys) at qty / 1e6 coins (the fee column fixes the unit -- a 10x here was caught by the ledger's own net), a leftover is marked by the average-cost pass, and --curve prints one row a fill; measured 2026-11-30 on the 11-29 record: 56 fills, gross -0.194000, fees 0.031983, net -0.225983, the ledger's own figure to the digit. It cannot split that gross into capture and drift -- that needs the mid at each fill |
hand |
tools/study/pnl_attribution.py |
the window's P&L as four per-fill terms that must sum to net_pnl_usd at every horizon -- capture, markout(τ), inventory_carry(τ), fee -- with the markout net read at 1s/5s/30s and the fills sliced by half-hour, spread, clip or queue; an extension of fill_decomposition.py that splits its drift at a markout horizon so the short-horizon adverse selection and the long-horizon inventory move read as two numbers |
--self-test |
tools/study/market_profile.py |
the market's physical quantities a white-box model derives from -- tau_hold (submission-to-fill seconds, P50/P90), sigma (the 1s mid log-return std, annualised) and kappa (the fill rate per quote-distance bin), each re-derived from the same record and cut pnl_attribution.py reads |
--self-test |
tools/study/derive_params.py |
the white-box step: the Avellaneda-Stoikov optimal half-spread (adverse-selection + inventory terms, floored at the maker fee) and the inventory-skew slope, derived from the measured sigma/kappa/tau_hold and the owner's gamma |
--self-test |
tools/study/gate_latency_counterfactual.py |
what a state gate is worth once the cancel has to travel: the same 3 s leader state read at each fill and one latency earlier, so a moving fill is avoidable only if the state had already turned a round trip before it and unavoidable when it turned inside the trip. Three sets -- no gate, a free cancel, and the measured latency -- with their means and medians; it is the in-flight term a counterfactual needs before a gate can be believed | hand |
tools/fetch/slice.py |
a bounded window, streamed, from a file too large to replay | both |
tools/fetch/inspect_source.py |
delimiter, types, timestamp columns, implied top of book | hand |
tools/study/book_lead_lag.py |
does the leader's mid move before the follower's: two mid series on one cadence from the two 400-level archives, returns in bps, the cross-correlation at every lag inside ±N ms, and the peak printed beside the correlation at zero and at our own 78/118 ms round trip. Measured 2026-11-28 on BTC to UP over the seven overlapping days: the peak sits at 0 ms with corr 0.013, so there is no lead a 76-118 ms reaction could use | hand |
tools/study/fill_markout_by_state.py |
the same question asked the way a gate would use it: the frozen cell replayed with --record-orders, each maker execution's 1 s markout against the follower's mid, bucketed by the leader's 3 s return at the fill's stamp. Measured 2026-11-28 over the seven days: the flat bucket keeps a +2.17 bps median on 77 percent of the fills while the two moving buckets sit at 0.00 and mean -3.2 and -3.7, so the state worth gating is the absolute return and not its sign -- a rise is as bad for a passive fill as a fall |
hand |
tools/study/window_regimes.py |
the windows bucketed by their own physics -- A: absolute move at or below 100 bps, B: 100 to 200, C: above 200 -- and joined with one arm's per-day rows (--rows, --folder). Measured 2026-11-28 over twenty-eight days: the label separates the worst day by 45 times (A +5.5 bps, C -250.5) and nothing else, since the medians fall +19.6, +9.5, +6.4 as the move grows; no C-day has efficiency above 0.5, so the month holds "wide two-way range" and no one-way day at all; and the half hour before 13:30 does not separate the buckets (C's pre-window move is the smallest of the three). Reproduced on the sixty-day arm (59 days, 2026-10-17 skipped as n/a): +19.5, +10.7, +8.4 closed -- the ordering and the size within 2 bps, efficiency still under 0.5 on all 26 C-days, the same single -250.5 worst day (2026-11-22, one event rather than a regime) -- and A's worst day is -28.6 there, so "A never loses" was the nine-day sample and not the bucket |
hand |
tools/study/leader_state_out_of_sample.py |
prepares the cuts fill_markout_by_state.py needs for a month the gate was never measured on, then runs it: --days (default 2026-10-30..2026-11-26), one two-hour cut plus one trade slice per day, the seven days the gate was found on skipped by name rather than counted twice, the sweep tool's lock and free-space refusal reused, one flushed line per day. --prepare-only stops after the cuts. Written before its data landed so the twenty-one-day counterfactual is one command, not a recipe remembered from a session |
hand |
tools/study/live_knobs_ab.py |
the live file's advance debounce, A/B on one window with the live flags: 40,000 ms (what live.yaml and the recorded ten-contract cell both carry) reads 31 buy / 40 sell quotes, 3 fills, -0.2317 USD, against 40 ms 52 / 25, 6 fills, +0.1066. The arm that shows the first live window's 2,547-to-44 split is not the strategy's shape -- the engine is near-balanced -- and that 40 ms is a new setting to register, not a cell to go back to |
hand |
tools/study/analyze_l2_windows.py |
one row per time window per strategy | hand |
tools/study/benchmark_l2_strategies.py |
the strategy set on one window, marking thin rows; --include-legacy adds inventory_aware_l2, which lives under src/strategy/maker/legacy/ and has no pinned run |
hand |
tools/study/benchmark_replay_windows.py |
the replay benchmark per time window | hand |
tools/study/calibrate_queue_model.py |
how a level decrease splits into trades and cancels | hand |
tools/study/capacity_table.py |
what a book costs to run, by capital, breadth and tier | both |
tools/study/cascade_probe.py |
a forced-flow burst's forward move, from the trade tape or from the book thinning; --days is the multi-day form |
hand |
tools/study/check_okx_book.py |
a rebuilt book against the archive's own snapshots | hand |
tools/study/figure_charge.py |
the quickstart's cost figure as inline SVG | hand |
tools/study/figure_path.py |
the two path figures as inline SVG | both |
tools/study/funding_extreme_test.py |
whether a funding extreme predicts the next eight hours | hand |
tools/study/lowturnover_test.py |
the pre-registered rule on sixty equity windows | hand |
tools/study/measure_l2_baseline.py |
replay seconds, and the hash of the output | hand |
tools/lib/okx_data.py |
where an OKX depth archive and trade tape live: <root>/<SYMBOL>/ or the flat root, so one module owns the two layouts every study tool reads |
hand |
tools/lib/roots.py |
the two generated roots in one place, TQ_DATA_DIR and TQ_OUT_DIR, defaulting to today's data/ and out/. Cut 4 of the tree's four lifetimes moves 55 GB out of the checkout, so a reader asks data(...)/out(...) instead of writing the path as a string, and the migration is one reader at a time rather than a rename of forty files. A relative override resolves against the repository root rather than the caller's directory, because a session started from /tmp and one started from the tree must read the same files; the path a caller builds is returned unresolved so the caller names a missing file itself |
--self-test, run by the code tier |
tools/lib/roots.sh |
the shell twin of roots.py: sourced by a script that needs $TQ_DATA_DIR or $TQ_OUT_DIR, with the same defaulting and the same rule for a relative override. It is sourced, so it is exempt from the cd guard the other tool scripts carry — a sourced file that changed directory would move its caller |
bash -n, the code tier's cd-guard loop, and the tier's assertions on the defaults and both override shapes |
tools/study/okx_book_window.py |
a day archive's time-weighted half-spread inside a UTC window, and the window cut that opens on a snapshot | hand |
tools/study/okx_book_depth.py |
the same cut's top two levels, time-weighted: the size a quote would stand behind, and the USD it is worth | hand |
tools/study/okx_halfhour_profile.py |
a day's half-hour profile -- duration-weighted half spread and trades a second -- with no P&L, for deciding a window on the book rather than on a run | hand |
tools/study/okx_tape_toxicity.py |
the tape's own adverse selection per half hour: each print's signed mid move over a stated horizon, as the passive side's markout -- mean, median and the share the mid moved on, with no strategy and no P&L | hand |
tools/study/okx_quote_share.py |
how much of the book one quote is: the window's market turnover, the time-weighted USD resting at the level the quote joins, and the two ratios that say whether a size is invisible -- with --order-units so a size ladder reads on one scale |
hand |
tools/study/okx_fill_profile.py |
our own fills per half hour, from a run's trade stream: capture against the mid, markout at two horizons, the net contracts and the share of fills that opened a position -- the subset the quotes actually got | hand |
tools/study/okx_spread_screen.py |
every swap's median half-spread and tick width over repeated ticker reads, against three thresholds, archiving its reads; --quote-ticks adds the basis points a quote that far behind the touch captures a fill, which is the column the fee is actually paid out of |
hand |
tools/study/plot_report.py |
quotes, distance, inventory and equity as one PNG | hand |
tools/study/pnl_interval.py |
a mean beside the interval it carries | both |
tools/study/ring_bench_table.py |
the ring hand-off over several sessions | hand |
tools/study/screen_spread.py |
symbols whose half spread could absorb a fee | hand |
tools/study/slice_pnl.py |
the same maker per slice, as two joinable tables | both |
tools/study/venue_ratio.py |
instruments ranked by capture against their own move | hand |
tools/study/fee_gate_table.py |
both gates in one row: the fee against the spread, and R_max against its reference, imported from the two tools above rather than recomputed | hand |
tools/study/viability.py |
the eight closed lines, re-derived | gate |
tools/study/volatility_window.py |
a windowed true range and its median split | both |
tools/study/walk_forward.py |
chosen on the past, scored on the next window | both |
tools/study/roadmap_index.py |
the ROADMAP's change log as a table -- the date, the section, the row's own title (inline code stripped; the index is a map, not a flag surface) and the line the row starts on -- with --write regenerating docs/ROADMAP_INDEX.md and --check refusing a stale copy (the docs tier runs the check) |
--check |
tools/study/sweep_summary.py |
one sweep CSV in, the median and its spread out: closed min/max, positive days, fills, fee range, the absolute residual, the leave-one-out median and the best day's dominance. --gate applies the owner's two dispersion conditions (leave-one-out median positive, worst day within --worst-multiple of the median), which archived the BLUR size ladder. --gamma (0.02 by default, the owner's registered coefficient) adds the CE = mean - gamma/2 * variance column, which is the risk ruler a risk lever is now read on; --gamma 0 leaves it off |
gate |
tools/live/venue_relay.py |
the relay the deployed units ship: market data to the engine and the order leg both ways, on the venue's grid, with the engine's three queries (PENDING, EQUITY, POSITION) answered from signed REST reads and CLOSE placed as a reduceOnly market order. SIGTERM refuses new orders, cancels what the relay placed and leaves only once nothing is live |
both |
tools/live/live_config.py |
turns config/live.yaml into the engine's arguments -- the positionals first, then one flag=value a line -- and refuses a key it does not know, so the ignored live file is a contract rather than a second copy of the flags |
gate |
tools/live/websocket_sender.py |
a local venue streaming two recorded files | hand |
tools/live/soak_push.sh |
a session's ping, reconnect and sequence counters | hand |
tools/live/trace_order.sh |
the order that waited longest, stage by stage | hand |
tools/live/resume_live.sh |
a snapshot written, resumed, and either break -- the file's or the venue's | hand |
tools/live/okx_probe.py |
the account's own side: USDT equity, the position in contracts, pending orders, and one contract placed for a run that needs a position the ledger does not know about; rtt/warm/touch measure the link's round trip and the post-only decline rate, amend times an amend against cancel+place on the same tunnel, and spec <inst> prints the venue's own tickSz, lotSz, minSz, ctVal and instIdCode plus what one contract is in engine units |
hand |
tools/live/venue_probe.py |
the host's path to the venue, per name: the DNS answers, the TCP connect, the TLS handshake and the time to first byte of one unauthenticated GET /api/v5/public/time, three samples a name — and the machine's own facts first, because every wire lever assumes them: the clock's zone and NTP sync, busy_poll, whether a governor exists to set, and each NIC's MTU and driver. Read-only by construction, so it may run beside a window; dispatched as the ops workflow's probe-venue action, which ships this file with the workflow rather than waiting for a deploy. A name that does not resolve is printed as a result — wsaws.okx.com answers No address associated with hostname |
hand |
tools/live/soak.sh |
one live ws session of a fixed shape, post-only or baseline, with both legs recorded so the window can be replayed; started as bash .run.sh soak <mode>, because a session typed into the tool's terminal once wedged it |
hand |
tools/live/stop_smoke.py |
P2, the stateful stop, on the real binary: the unit's own ws invocation with --live-orders, a fixture market leg on loopback (one snapshot and 16 prints, then silence) and the relay's simulated order venue, so no key and no host are needed. It waits for a resting order, sends SIGTERM -- what systemctl stop sends -- and asserts exit 0, under 5 s, [SHUTDOWN] step=record/step=done, both [RECON] at=end lines, a cancel for that id in the record and working=0 at the venue. The verdict line is the last thing it prints; it runs in the gate's code tier |
gate |
tools/export/bundle.py |
two bundles, a manifest and a diff, each checked | hand |
tools/export/push_windows.sh |
the tree onto the reviewer's Drive, through rclone (no mount, no powershell.exe): the bundle is written to out/export, uploaded with --checksum, then checked by rclone's hash comparison, each remote size and the remote manifest.txt's commit against HEAD. The remote comes from .drive-target (gdrive:AI_Code_Sync) or TOYQUANT_DRIVE_DIR; a local directory there takes bundle.py --sync's own copy. diff.patch is the remote manifest's commit to HEAD |
hand |
tools/export/install_post_commit.sh |
the hook it wrote, or the one it repaired | hand |
tools/bench/ab_bench.sh |
paired differences, their mean and t statistic | hand |
tools/bench/count_libc_calls.c |
libc call counts, byte totals, a size histogram | hand |
tools/legacy/gen_ticks.py |
a reproducible synthetic tick CSV | hand |
tools/legacy/udp_sender.py |
the rows it sent, at the CSV's own intervals | hand |
The four conventions¶
- A script knows where the repository is. A shell script starts with
cd "$(dirname "$0")/../.." || exit 1, so paths inside it are written relative to the root and a tool started from anywhere behaves the same. A Python tool resolves its data fromPath(__file__).resolve().parents[2]where it can, and otherwise is documented as being run from the root — the gate and every command in the documents do that. - Shell helpers are sourced, never copied.
. tools/gate/lib.shgivesfield_of, which reads aname=valueout of a run's output with the same rulecheck_docs.pyuses, andemit_block, which prints a marked block. A tool that prints a table usually also prints that block, so pasting its output into a document is the whole job of documenting a number — andtools/gate/check_docs.pythen fails the build when the number moves. - A tool that cannot run says so. The fetchers and sweeps need files that are not in the repository (paid Databento windows, the free sample days); a missing input is an error naming the file, never a table of zeros.
- Nothing here is a build step. The build is CMake and
CMakeLists.txt; no tool is on the path from source to binary. Deleting a tool breaks a document, not the program.
Where to start¶
- To accept a change:
tools/gate/verify_l2.sh all. - To see what a gate tier actually checks: the comment block at the top of
tools/gate/verify_l2.sh. - To pick the cheapest check that can see your mistake:
smoke(two replays, about a second),code(tier 0 and the invariants, about fifteen seconds) anddocs <pages>(the documents, page by page) are the halves of tier 1 that a change pays for separately.fastis the whole of tier 1 and belongs once per task, not once per edit: the document half is about two minutes and almost all of it is one page whose blocks replay Databento equity windows. - To reproduce a number a document quotes: the marked block next to it names the command, and
check_docs.pyruns exactly that command. - To add a measurement: put the script in
sweep/if it prints a table for a document, instudy/if it answers one question once, and infetch/if it is about getting or cutting data -- then add its line to the inventory above, becauselint_prose.pycounts the directory and a tool nobody named fails a build. - To hand the repository to a reader that cannot clone it:
TOYQUANT_DRIVE_DIR=<the folder your client syncs> python3 tools/export/bundle.py --syncwrites two bundles, a manifest that carries the commit and a sha256 per file, anddiff.patchsince the commit the previous manifest carried -- then checks the lot. That diff is what a read-only reviewer is given: a review needs the change, not the tree, and the manifest is how it says "this is stale" (whole tree 3.35 MB, manifest plus the three front doors 47.6 KB, a typical diff a few KB). A dump without the check is a copy with no age, which is what a ten-day-old snapshot is: the one this tool was written for described a README three times the length of the real one, and nothing in it could say so.