19 KiB
Stock Bot — Execution Milestones (M0 → M5)
Actionable build tracker for turning Stock Bot into the AI algo research & IB live trading platform defined in PLATFORM-PLAN.md.
Sequencing rule: Build Vertical Slice 1 (M0 + M1) before touching multi-asset Rust internals or greenfield UI dashboards. That puts you and desktop Claude Code onto real survivorship-clean US+CA daily, filing, and short-interest signal research by Week 3.
Explicit Scope Cuts & Deferrals
- Cut: Dual-backend QuestDB ↔ DuckDB parity harness (storage is split cleanly by workload from Day 1: DuckDB+Parquet for daily/PIT/features; QuestDB
10.2.0for1mintraday/hot bars). - Cut:
eodFundamentalsOLDscrape-time valuation snapshots in backtests (look-ahead + corrupted CDR currencies). - Cut: Macro release/surprise event studies on
teData(no release timestamps or initial vintages exist in raw data;teDatais restricted to lagged regime tags). - Cut:
ttFutures(corrupted dates and separate contract-roll/margin domain; revisit post-M5). - Defer to
M4: React Merge Review UI (use generated CSV/Markdown conflict reports + SQLoverrideseed files inM1), greenfieldHome/Marketspages, and custom Knowledge Base CRUD (mount~/repos/studio/catalog/quant/library/library.ymlread-only via MCP). - Defer to post-
M5: Multi-host distributed research worker pool (quanthas 24 threads + 125 GiB RAM + 3.6 TiB NVMe on one box) and Form 4 XML / SEDI insider dollar-size parsing.
M0 — Safety, Migrations & Gate Lock (Days 1–3)
Goal: Every repo gate passes, dev/QA database isolation is airtight at both client and server layers, secrets and holdout export leaks are closed, and schema migrations work across data-pipeline and web-api.
Checklist
- Fix failing baseline gates:
- Update
scripts/test/workspace.test.ts:85fordocker-compose.dev.ymldefault inscripts/docker.sh. - Fix all 65 ESLint issues (
59curly+2non-null warnings inapps/stock/data-pipeline/scripts/phase1-inventory.ts;4curlyerrors inapps/stock/config/src/env-safety.ts,libs/core/di/src/container/builder.ts,libs/data/mongodb/src/client.ts). - Delete the 6 stray root files (
tetest.ts,test-queue.ts,proxy-playwrite.ts,test-rust-strategies.js,test-typescript-strategy.js,test-e2e-backtest.sh).
- Update
- Fix PostgreSQL init & shared migration runner:
- Strip hardcoded
CREATE DATABASE trading_botand\c trading_bot;fromdatabase/postgres/init/01-init-database.sqlthrough05-add-visible-column.sqlsodocker-compose.dev.yml(trading_bot_devon5433) anddocker-compose.prod.ymlinitialize master tables in$POSTGRES_DB. - Extract
runMigrationsfromapps/stock/web-api/src/migrations/migration-runner.tsinto@stock-bot/postgres(libs/data/postgres) withmasterandresearchmigration tracks +bun run db:migrate.
- Strip hardcoded
- Close
MongoDBClientreadOnlybypass &env-safety.tsgaps:- Block or read-only-proxy
getDatabase(),getDb(),database,getCollection(), andcollection()inlibs/data/mongodb/src/client.tswhenreadOnly: true. - Delete legacy MongoDB-writing
apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts(and its route hook inweb-api). - Change
apps/stock/config/src/env-safety.ts:86-94fromlogger.warntothrow new ErrorwhendataPipelinetargets port27017withoutreadOnly: trueor withtrading_admin, and checkport === 27017even when URI omits/stock. - Default
QUEUE_ENABLE_SCHEDULED_JOBS=falseoutside explicit ingestion deployments so startingdata-ingestionnever triggers background crawls unintentionally.
- Block or read-only-proxy
- Purge hardcoded credentials & close
sb-research.*holdout leak:- Rotate and remove the hardcoded Webshare proxy URL in
apps/stock/data-ingestion/src/handlers/ib/shared/config.ts:19(read from env only) and extendscripts/audit-secrets.tsto catchhttp(s)://user:pass@literals; also fixfetch-symbols.action.ts:108(ib_symbols→ibSymbols). - Remove
GET /api/v2/datasets/canonical/:hash/exportfromsb-research.*permissions inapps/stock/web-api/src/services/research-agents.service.ts:51and scope agentGETroutes to granted projects/templates.
- Rotate and remove the hardcoded Webshare proxy URL in
- Pin container tags, kernel limits &
quantRAM caps:- Replace all
:latest/ floating tags indocker-compose*.ymlwith exact pinned versions (questdb:10.2.0,postgres:16.9-alpine,mongo:7.0.21-jammy,dragonfly:v1.30.3, etc.). - Configure
shm_size(2gonquant,512min dev) for PostgreSQL 16 parallel workers,ulimits.nofile = 1048576on QuestDB/MongoDB,/etc/sysctl.d/99-stockbot.conf(vm.max_map_count = 1048576) onquant, and hardmem_limit+ engine caps indocker-compose.quant.yml(reserving~24 GiBof125 GiBfor OS page cache).
- Replace all
Exit Criteria
CARGO_BUILD_JOBS=2 bun run checkpasses all 11 gates (0errors,0warnings).- Fresh
trading_bot_devcontainer (5433) contains both master (02–05) and research (06–33) tables, verified by automated test. - Integration test proves
data-pipelinethrows on bothmongoClient.insertOne()andmongoClient.getDatabase().collection('x').insertOne(), andstudio_stock_bot_readrejects server-side writes. - Security test proves
sb-research.*receives403on dataset/exportand ungranted projectGETs.
M1 — Vertical Slice 1: Security Master + Honest Daily/Event Signal Lab (Weeks 1–3)
Goal: Resolve US + Canadian equities into permanent listing_ids, curate honest survivorship-aware daily bars + corporate actions + FX + filings/earnings/Canadian shorts into Parquet + DuckDB, enforce the 6-month Vault and trial_ledger, and start testing real signals in Python/marimo.
Checklist
- Step 1 — Security Master (
Postgres+apps/stock/data-pipeline):- Add DDL migration for
exchange,exchange_source_map,instrument,instrument_identifier_history,listing,listing_symbol_history,corporate_action_continuity,provider_mapping,resolution_conflict,override,golden_field_audit(see DATA-CONTRACTS.md). - Implement Pass 1 (ISO 10383 MIC seed + ~320 source exchange mappings; mark EOD
UScomposite, EODNMFQSexcluded mutual funds, IBAEQLIT/IEX/ARCAEDGE/OTCLNKECN/etc.ats_routing, CEOTSX/CDX/CNQ/AQL→XTSE/XTSX/XCNQ/NEOE) and review once via committed seed SQL. - Implement Pass 2 normalization (fix
provider-symbol.tsfor IBexchangeId/description; ticker root/suffix parser; ISIN Luhn validator + CUSIP→ISIN derivation; precompute[first_bar_date, last_bar_date]per(source, source_id)). - Implement Pass 3 two-stage matching (Stage A: global ISIN/CUSIP →
instrument; Stage B: EOD/QM venue →listing, IBconidattached at(instrument_id, currency), temporal bar-span overlap required on Tier 3/4 ticker matches) + Pass 6 OTC delisting chains (SIVB→SIVBQ). - Implement Pass 4 batch 25-date cross-sectional price cross-check (
{ date: { $in: sampleDates } }) and export US+CA match & conflict report +overrideseed file.
- Add DDL migration for
- Step 2 Core — Zero-Copy Rust Bulk ETL + Daily, Actions, FX & Events (
Parquet + DuckDB):- Build
tools/curate-etlin the Cargo workspace (mongodb::bson::RawDocumentBufzero-copy BSON cursors + preloaded in-RAMprovider_mapping/qmSplitstables +rayonsharded Zstdparquetwriter) so846MeodPricesrows (and3.40BeodIntraday1Mrows inM2) never iterate through single-threaded JS object loops. - Curate
bars_1d(un-adjustingeodPrices.volumeviaqmSplitsand cross-checkingqmPrices.sharevolume). - Curate
corporate_actions&adj_factors(qmSplitsexcluding1:1no-ops,qmDividendsignoring bogususdFxRate: 1, plus OTC continuation &-30%/-100%Shumway terminal delisting events). - Curate
fx_1d(CAD.FOREX1971–2025 +teMarketData.USDCADthrough 2026). - Curate
events(qmFilingsUTC-convertedtimefiled+ form groups;qmEarningslinked toqmFilingsor lagged to16:05 ETwhenannounceTime == 'N/A') andshorts(ceoShortswith+4Canadian business-dayknown_atlag).
- Build
MarketDataStore+ Rolling 6-Month Vault +trial_ledger:- Implement
MarketDataStore(TS) andstockbot.data(Python) over DuckDB + Parquet with mandatoryknown_at <= asOf,ts < VAULT_CUTOFF_TS(max_ingested_ts - 6 months), and per-connectionSET memory_limit = '6GB'; SET threads = 4; SET temp_directory = ...enforcement. - Add PostgreSQL
trial_ledgerandvault_evaluationstables (protected byreject_research_evidence_mutation()) + canonical DSR (\hat{N}effective trials) in@stock-bot/calculations(see VALIDATION-AND-RIGOR.md).
- Implement
- Signal Analyzer +
marimoWorkspace:- Implement
analyze_signalandevent_study(IC, rank-IC, quantile spreads, turnover, pre/post-2023 recency split, Newey-West $t$-stat, automatictrial_ledgerwrite). - Stand up
marimo edit ./research/notebooks --watch(127.0.0.1:2718) with marimo agent rules (CLAUDE.md) andmarimo check --format=jsonpre-commit/CI check.
- Implement
Exit Criteria
- US+CA match report committed:
100%of exchange codes mapped;\ge 95\%of US/CA equities resolved;FB(2012–2022) andFB(2025 ETF) have distinctlisting_ids;SIVBchains toSIVBQ;NVDApre-splitclose * raw_volumematchesqmPriceswithin1%. - 20y US+CA daily scan + 1 signal IC/quantile/turnover/recency/DSR evaluation finishes in
< 5 sonquantwithout reading any Vault row. - End-to-end test runs a Canadian
ceoShorts/qmFilingssignal study instockbotPython SDK, logs its return vector totrial_ledger, and computes $\hat{N}$-deflated Sharpe.
M2 — MCP Copilot, Intraday QuestDB 10.2.0 & PIT Fundamentals (Weeks 4–5)
Goal: Connect desktop Claude Code via MCP, curate 2D point-in-time fundamentals (qmFinancials × qmFilings) and split-unadjusted 1m intraday bars (QuestDB 10.2.0), and launch the versioned batch Feature Library.
Checklist
- MCP Server (
web-api/ standalone stdio+SSE wrapper):- Expose
search_symbols,query_data(vault-fenced),analyze_signal,event_study,file_finding,read_knowledge(serving~/repos/studio/catalog/quant/library/library.yml+ Postgresfindings/provider_caveats).
- Expose
- PIT Fundamentals & CEO Posts (
Parquet + DuckDB):- Join
qmFinancials(+qmFinancials-old) toqmFilings.timefiled(10-Q,10-K,40-F, SEDARInterim/Annual financial statements), applying+45d/+90d(US/TSX) and+60d/+120d(TSXV/CSE) statutory lags where unlinked (known_at_source = 'statutory_lag_estimate'). - Materialize 2D
(period_end, known_at)deduplicated wide snapshots + TTM features (fundamentals_pit). - Curate
ceoPosts(14.8M) separatingbot == "1"newswires from retail posts and guardingedited != nulltext timestamps; curate laggedteDataregime series.
- Join
- Intraday Curation (
QuestDB 10.2.0):- Replace legacy
libs/data/questdb(LATEST BY→LATEST ON, parameterized PGWire queries, ILP v2 batch writer); verifyvm.max_map_count >= 1048576andulimits.nofile = 1048576onquantbefore bulk load. - Extend
tools/curate-etlwith sharded multi-socket ILP v2 writers to stream split-unadjustedeodIntraday1M(3.40Brows, US 2003–2025), rawqmIntraday(CA/US 2024–2025), andCAD.FOREX1m(5.2Mbars) intoPARTITION BY MONTHbars_1m(270partitions across 22.5y) andfx_1m(listing_id SYMBOL CAPACITY 65536 NOCACHE,DEDUP UPSERT KEYS(ts, listing_id)).
- Replace legacy
- Versioned Feature Library (
D04reopened):- Build declarative SQL/Polars batch runner writing versioned
(listing_id, ts, known_at, value)columns +register_signal(...)SDK entrypoint.
- Build declarative SQL/Polars batch runner writing versioned
Exit Criteria
- Desktop Claude Code via MCP executes a fundamental + alt-data signal study and event study end-to-end, exports a
marimo check-clean static HTML snapshot, and files a finding. - Restatement fixture test proves a restated Q1 (
known_at > Q2) never overwrites Q2 infundamentalsAsOf. - Split-boundary test on
NEXM.V(1:20) andNVDA.US(10:1) confirmsbars_1msession closes match rawbars_1dcloses within0.5%, and 1y of1mbars for one listing loads in< 250 mswarm /< 1 scold.
M3 — Portfolio Backtest v2: Columnar Screener + Multi-Asset Rust Engine (Weeks 6–9)
Goal: Turn surviving signals into multi-asset long/short US+CA (+ FX) strategies with exact 8-decimal Rust accounting, zero Python→TS indicator translation, full CPCV/DSR/PBO validation, and the human 6-month Vault gate.
Checklist
- Tier 1 Columnar Screener:
- Vectorized Polars/DuckDB portfolio sweep (
signal × universe × rebalance × cost), writing fullM_{T \times N}return matrices totrial_ledgerand computing CSCV PBO (S = 16).
- Vectorized Polars/DuckDB portfolio sweep (
- Tier 2 Rust
financial/Multi-Asset Upgrades (apps/stock/engine/src/financial/*):- Task 1 — Retire JSON-over-Postgres/IPC/N-API bar path (prerequisite): Store only
(hash, manifest, parquet_paths)inbacktest_datasets(retiring the255 MB-cappedpayload JSONBblob), pass only the manifest + read-only Parquet paths throughNativeBacktestWorkerIPC and N-API so Rustparquet/arrow-rsreads columns directly with zero JS bar objects, replace per-bar JSON stdio incandidate-sandbox.tswith compact Arrow IPC /Float64Arraybarrier frames, removeserde_json::Valuetriple-parsing from bulk payloads inapi/canonical.rs, and lift single-series TS gates innative-worker.ts. - Atomic timestamp-slice marks (
F06): Update all marks at timestamptbefore checkingRiskAccountdaily-loss/drawdown latches. - Simultaneous
Targetsell-netting: Credit haircut-adjusted pendingSellproceeds toward same-barrierBuyreservations inMatchingAccount::submit. - Feature side-channel: Pass precomputed
featurescolumns intoReplaydecision barriers andStrategyContext. - Long/short, multi-currency Margin & corporate actions: Signed positions/targets + borrow fee accrual;
BTreeMap<Currency, Posting>(USD/CADcash & negative margin-loan interest +FXCONVsweeps + tradable FX pairs); ex-date splits, cash dividends, TSX/TSXV100/500/1000board-lot rounding, and OTC/Shumway delisting liquidations.
- Task 1 — Retire JSON-over-Postgres/IPC/N-API bar path (prerequisite): Store only
- Validation Suite & Engine Consolidation:
- Add Purged Walk-Forward & CPCV (
purge = horizon + warmup,embargo = max(5d, 0.01 * T)), parameter stability surface, capacity (ADV participation), and US/CA factor exposure (MKT,SMB,HML,MOM). - Implement one-shot human Vault Holdout Gate (
Validated → Paper, capped at\le 10evaluations/year invault_evaluations). - Retire legacy
f64BacktestEngine, legacy TSSimulationExecution, and deadapps/stock/analyticsmetric scripts.
- Add Purged Walk-Forward & CPCV (
Exit Criteria
- Rust unit + differential fixtures pass for: atomic hedged mark neutrality, 100%-invested
Sell A + Buy Btarget rotation, split + dividend 8-decimal conservation, USD/CAD margin interest, TSX board-lot sizing, andSIVBdelisting liquidation. - 20y US+CA cross-sectional long/short daily backtest (
~5,000+listings) finishes in< 30 sonquant. - A real
M2signal promoted viaregister_signalruns throughTier 1 Screen → Tier 2 Rust Engine → CPCV/DSR/PBO/Recency → Human 6m Vault Gatewith zero indicator code duplicated in TypeScript.
M4 — Autonomous Agent Campaigns, Studio Bridge & App Evolution (Weeks 10–12)
Goal: Run bounded overnight research campaigns safely on quant, connect the Studio Quant hypothesis loop, and surface everything cleanly in web-app.
Checklist
- Campaign Runner & SQL Budgets:
- Add
campaignstable and PostgreSQLBEFORE INSERTtriggers enforcing cumulative per-campaign and daily trial, bar-evaluation, and wall-clock budgets. - Package containerized campaign runner (
--networkrestricted to Research Kernel API/MCP only; zero DB port or host filesystem access) implementingScout,Data Analyst,Signal Researcher,Strategy Builder, andSkepticworkflows + ntfy/Discord notifications.
- Add
- Studio Bridge:
- Webhook/API endpoint accepting Studio Quant hypotheses → creating bounded Stock Bot campaigns → posting structured
verdict + DSR + PBO + static HTML linkreceipts back to Studio.
- Webhook/API endpoint accepting Studio Quant hypotheses → creating bounded Stock Bot campaigns → posting structured
- Incremental
web-appEvolution:- Wire
/research/agentsintoSidebar.tsxand unifysrc/components/charts/Chart.tsx+SymbolChart.tsx. - Ship
Lab(Signal Analyzer, Event Study, sandboxed<iframe sandbox="allow-scripts" srcDoc={...}>HTML viewer + on-demandmarimo runlauncher),Agents(live campaigns, budgets, findings/dead-ends feed),Strategies(lifecycle + Vault gate), andData(coverage, quality monitors, conflict queue), followed by lightweightHomeandMarketsviews.
- Wire
Exit Criteria
- Overnight containerized campaign launched from a Studio Quant idea completes unattended on
quant, stays strictly inside SQL trial budgets, passesSkepticaudit checks, and renders static-HTML-backed findings in theAgentsfeed. - Attempting to exceed campaign trial/compute caps or access Vault dates from inside the agent container fails closed (
403/ SQL trigger error).
M5 — Paper at Scale → Live Interactive Brokers Margin (9900K) (Weeks 13–16)
Goal: Harden paper execution for long-running multi-asset portfolios, connect headless IB Gateway on the isolated 9900K server, validate live vs. backtest drift in IB Paper, and go live on small capital.
Checklist
paper-hostHardening (apps/stock/engine/src/api/paper.rs&orchestrator/src/paper/*):- Replace
O(N)double genesis receipt replay instage_financial_transactionwith periodic compacted state snapshots + bounded tail journal; exposeMatchingResetover NAPI; run non-builtin paper strategy code inside theA02sandbox; lift single-deployment / single-series limits.
- Replace
- IB Gateway & Market Data / OMS Bridge (
9900K):- Deploy headless
IB Gateway+IBCon9900K(handling nightly ~21:00 ET resets and1100 → 1102re-subscriptions). - Build
ib-bridgeaggregatingreqRealTimeBars(5s, TRADES)+ L1reqMktDataquotes (\le 80active lines) into post-grace closed bars; pin(conid, currency, exchange="SMART", primaryExchange)fromlisting; route cash sweeps viaFXCONVand FX alpha trades viaIDEALPRO; implement idempotent client order IDs, partial fills, TSX15:40 ET/ US15:50 ETauction cutoffs, and continuous position/cash reconciliation.
- Deploy headless
- Risk, Kill Switches & Dual Drift Monitor:
- Global + per-strategy exposure, daily-loss, drawdown, and order-rate kill switches +
TradingUI controls. - Implement Execution Drift (live IB fills vs. Rust replay on recorded IB bars/quotes) and Feed Basis Drift (Rust replay on recorded IB bars vs. next-day curated EOD/QM bars), with automatic demotion proposals when outside bounds.
- Global + per-strategy exposure, daily-loss, drawdown, and order-rate kill switches +
Exit Criteria
paper-hostprocesses100,000sequential quotes with flat< 5 msp99 latency.- Strategy runs
\ge 30trading days and\ge 50trades on IB Paper across US (USD) + TSX (CAD) listings, surviving nightly IB Gateway resets with0unrecovered reconciliation mismatches and Execution Drift<= 15 bps/trade. - Small-capital live deployment passes pre-flight kill-switch, partial-fill,
FXCONV, and reconciliation drills with explicit operator approval.