stock-bot/design/MILESTONES.md
2026-11-27 00:12:48 -05:00

19 KiB
Raw Blame History

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.0 for 1m intraday/hot bars).
  • Cut: eodFundamentalsOLD scrape-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; teData is 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 + SQL override seed files in M1), greenfield Home/Markets pages, and custom Knowledge Base CRUD (mount ~/repos/studio/catalog/quant/library/library.yml read-only via MCP).
  • Defer to post-M5: Multi-host distributed research worker pool (quant has 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:85 for docker-compose.dev.yml default in scripts/docker.sh.
    • Fix all 65 ESLint issues (59 curly + 2 non-null warnings in apps/stock/data-pipeline/scripts/phase1-inventory.ts; 4 curly errors in apps/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).
  • Fix PostgreSQL init & shared migration runner:
    • Strip hardcoded CREATE DATABASE trading_bot and \c trading_bot; from database/postgres/init/01-init-database.sql through 05-add-visible-column.sql so docker-compose.dev.yml (trading_bot_dev on 5433) and docker-compose.prod.yml initialize master tables in $POSTGRES_DB.
    • Extract runMigrations from apps/stock/web-api/src/migrations/migration-runner.ts into @stock-bot/postgres (libs/data/postgres) with master and research migration tracks + bun run db:migrate.
  • Close MongoDBClient readOnly bypass & env-safety.ts gaps:
    • Block or read-only-proxy getDatabase(), getDb(), database, getCollection(), and collection() in libs/data/mongodb/src/client.ts when readOnly: true.
    • Delete legacy MongoDB-writing apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts (and its route hook in web-api).
    • Change apps/stock/config/src/env-safety.ts:86-94 from logger.warn to throw new Error when dataPipeline targets port 27017 without readOnly: true or with trading_admin, and check port === 27017 even when URI omits /stock.
    • Default QUEUE_ENABLE_SCHEDULED_JOBS=false outside explicit ingestion deployments so starting data-ingestion never triggers background crawls unintentionally.
  • 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 extend scripts/audit-secrets.ts to catch http(s)://user:pass@ literals; also fix fetch-symbols.action.ts:108 (ib_symbols → ibSymbols).
    • Remove GET /api/v2/datasets/canonical/:hash/export from sb-research.* permissions in apps/stock/web-api/src/services/research-agents.service.ts:51 and scope agent GET routes to granted projects/templates.
  • Pin container tags, kernel limits & quant RAM caps:
    • Replace all :latest / floating tags in docker-compose*.yml with exact pinned versions (questdb:10.2.0, postgres:16.9-alpine, mongo:7.0.21-jammy, dragonfly:v1.30.3, etc.).
    • Configure shm_size (2g on quant, 512m in dev) for PostgreSQL 16 parallel workers, ulimits.nofile = 1048576 on QuestDB/MongoDB, /etc/sysctl.d/99-stockbot.conf (vm.max_map_count = 1048576) on quant, and hard mem_limit + engine caps in docker-compose.quant.yml (reserving ~24 GiB of 125 GiB for OS page cache).

Exit Criteria

  1. CARGO_BUILD_JOBS=2 bun run check passes all 11 gates (0 errors, 0 warnings).
  2. Fresh trading_bot_dev container (5433) contains both master (02–05) and research (06–33) tables, verified by automated test.
  3. Integration test proves data-pipeline throws on both mongoClient.insertOne() and mongoClient.getDatabase().collection('x').insertOne(), and studio_stock_bot_read rejects server-side writes.
  4. Security test proves sb-research.* receives 403 on dataset /export and ungranted project GETs.

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 US composite, EOD NMFQS excluded mutual funds, IB AEQLIT/IEX/ARCAEDGE/OTCLNKECN/etc. ats_routing, CEO TSX/CDX/CNQ/AQL → XTSE/XTSX/XCNQ/NEOE) and review once via committed seed SQL.
    • Implement Pass 2 normalization (fix provider-symbol.ts for IB exchangeId/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, IB conid attached 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 + override seed file.
  • Step 2 Core — Zero-Copy Rust Bulk ETL + Daily, Actions, FX & Events (Parquet + DuckDB):
    • Build tools/curate-etl in the Cargo workspace (mongodb::bson::RawDocumentBuf zero-copy BSON cursors + preloaded in-RAM provider_mapping/qmSplits tables + rayon sharded Zstd parquet writer) so 846M eodPrices rows (and 3.40B eodIntraday1M rows in M2) never iterate through single-threaded JS object loops.
    • Curate bars_1d (un-adjusting eodPrices.volume via qmSplits and cross-checking qmPrices.sharevolume).
    • Curate corporate_actions & adj_factors (qmSplits excluding 1:1 no-ops, qmDividends ignoring bogus usdFxRate: 1, plus OTC continuation & -30%/-100% Shumway terminal delisting events).
    • Curate fx_1d (CAD.FOREX 1971–2025 + teMarketData.USDCAD through 2026).
    • Curate events (qmFilings UTC-converted timefiled + form groups; qmEarnings linked to qmFilings or lagged to 16:05 ET when announceTime == 'N/A') and shorts (ceoShorts with +4 Canadian business-day known_at lag).
  • MarketDataStore + Rolling 6-Month Vault + trial_ledger:
    • Implement MarketDataStore (TS) and stockbot.data (Python) over DuckDB + Parquet with mandatory known_at <= asOf, ts < VAULT_CUTOFF_TS (max_ingested_ts - 6 months), and per-connection SET memory_limit = '6GB'; SET threads = 4; SET temp_directory = ... enforcement.
    • Add PostgreSQL trial_ledger and vault_evaluations tables (protected by reject_research_evidence_mutation()) + canonical DSR (\hat{N} effective trials) in @stock-bot/calculations (see VALIDATION-AND-RIGOR.md).
  • Signal Analyzer + marimo Workspace:
    • Implement analyze_signal and event_study (IC, rank-IC, quantile spreads, turnover, pre/post-2023 recency split, Newey-West $t$-stat, automatic trial_ledger write).
    • Stand up marimo edit ./research/notebooks --watch (127.0.0.1:2718) with marimo agent rules (CLAUDE.md) and marimo check --format=json pre-commit/CI check.

Exit Criteria

  1. US+CA match report committed: 100% of exchange codes mapped; \ge 95\% of US/CA equities resolved; FB (2012–2022) and FB (2025 ETF) have distinct listing_ids; SIVB chains to SIVBQ; NVDA pre-split close * raw_volume matches qmPrices within 1%.
  2. 20y US+CA daily scan + 1 signal IC/quantile/turnover/recency/DSR evaluation finishes in < 5 s on quant without reading any Vault row.
  3. End-to-end test runs a Canadian ceoShorts / qmFilings signal study in stockbot Python SDK, logs its return vector to trial_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 + Postgres findings/provider_caveats).
  • PIT Fundamentals & CEO Posts (Parquet + DuckDB):
    • Join qmFinancials (+ qmFinancials-old) to qmFilings.timefiled (10-Q, 10-K, 40-F, SEDAR Interim/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) separating bot == "1" newswires from retail posts and guarding edited != null text timestamps; curate lagged teData regime series.
  • Intraday Curation (QuestDB 10.2.0):
    • Replace legacy libs/data/questdb (LATEST BY → LATEST ON, parameterized PGWire queries, ILP v2 batch writer); verify vm.max_map_count >= 1048576 and ulimits.nofile = 1048576 on quant before bulk load.
    • Extend tools/curate-etl with sharded multi-socket ILP v2 writers to stream split-unadjusted eodIntraday1M (3.40B rows, US 2003–2025), raw qmIntraday (CA/US 2024–2025), and CAD.FOREX 1m (5.2M bars) into PARTITION BY MONTH bars_1m (270 partitions across 22.5y) and fx_1m (listing_id SYMBOL CAPACITY 65536 NOCACHE, DEDUP UPSERT KEYS(ts, listing_id)).
  • Versioned Feature Library (D04 reopened):
    • Build declarative SQL/Polars batch runner writing versioned (listing_id, ts, known_at, value) columns + register_signal(...) SDK entrypoint.

Exit Criteria

  1. 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.
  2. Restatement fixture test proves a restated Q1 (known_at > Q2) never overwrites Q2 in fundamentalsAsOf.
  3. Split-boundary test on NEXM.V (1:20) and NVDA.US (10:1) confirms bars_1m session closes match raw bars_1d closes within 0.5%, and 1y of 1m bars for one listing loads in < 250 ms warm / < 1 s cold.

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 full M_{T \times N} return matrices to trial_ledger and computing CSCV PBO (S = 16).
  • 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) in backtest_datasets (retiring the 255 MB-capped payload JSONB blob), pass only the manifest + read-only Parquet paths through NativeBacktestWorker IPC and N-API so Rust parquet/arrow-rs reads columns directly with zero JS bar objects, replace per-bar JSON stdio in candidate-sandbox.ts with compact Arrow IPC / Float64Array barrier frames, remove serde_json::Value triple-parsing from bulk payloads in api/canonical.rs, and lift single-series TS gates in native-worker.ts.
    • Atomic timestamp-slice marks (F06): Update all marks at timestamp t before checking RiskAccount daily-loss/drawdown latches.
    • Simultaneous Target sell-netting: Credit haircut-adjusted pending Sell proceeds toward same-barrier Buy reservations in MatchingAccount::submit.
    • Feature side-channel: Pass precomputed features columns into Replay decision barriers and StrategyContext.
    • Long/short, multi-currency Margin & corporate actions: Signed positions/targets + borrow fee accrual; BTreeMap<Currency, Posting> (USD/CAD cash & negative margin-loan interest + FXCONV sweeps + tradable FX pairs); ex-date splits, cash dividends, TSX/TSXV 100/500/1000 board-lot rounding, and OTC/Shumway delisting liquidations.
  • 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 10 evaluations/year in vault_evaluations).
    • Retire legacy f64 BacktestEngine, legacy TS SimulationExecution, and dead apps/stock/analytics metric scripts.

Exit Criteria

  1. Rust unit + differential fixtures pass for: atomic hedged mark neutrality, 100%-invested Sell A + Buy B target rotation, split + dividend 8-decimal conservation, USD/CAD margin interest, TSX board-lot sizing, and SIVB delisting liquidation.
  2. 20y US+CA cross-sectional long/short daily backtest (~5,000+ listings) finishes in < 30 s on quant.
  3. A real M2 signal promoted via register_signal runs through Tier 1 Screen → Tier 2 Rust Engine → CPCV/DSR/PBO/Recency → Human 6m Vault Gate with 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 campaigns table and PostgreSQL BEFORE INSERT triggers enforcing cumulative per-campaign and daily trial, bar-evaluation, and wall-clock budgets.
    • Package containerized campaign runner (--network restricted to Research Kernel API/MCP only; zero DB port or host filesystem access) implementing Scout, Data Analyst, Signal Researcher, Strategy Builder, and Skeptic workflows + ntfy/Discord notifications.
  • Studio Bridge:
    • Webhook/API endpoint accepting Studio Quant hypotheses → creating bounded Stock Bot campaigns → posting structured verdict + DSR + PBO + static HTML link receipts back to Studio.
  • Incremental web-app Evolution:
    • Wire /research/agents into Sidebar.tsx and unify src/components/charts/Chart.tsx + SymbolChart.tsx.
    • Ship Lab (Signal Analyzer, Event Study, sandboxed <iframe sandbox="allow-scripts" srcDoc={...}> HTML viewer + on-demand marimo run launcher), Agents (live campaigns, budgets, findings/dead-ends feed), Strategies (lifecycle + Vault gate), and Data (coverage, quality monitors, conflict queue), followed by lightweight Home and Markets views.

Exit Criteria

  1. Overnight containerized campaign launched from a Studio Quant idea completes unattended on quant, stays strictly inside SQL trial budgets, passes Skeptic audit checks, and renders static-HTML-backed findings in the Agents feed.
  2. 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-host Hardening (apps/stock/engine/src/api/paper.rs & orchestrator/src/paper/*):
    • Replace O(N) double genesis receipt replay in stage_financial_transaction with periodic compacted state snapshots + bounded tail journal; expose MatchingReset over NAPI; run non-builtin paper strategy code inside the A02 sandbox; lift single-deployment / single-series limits.
  • IB Gateway & Market Data / OMS Bridge (9900K):
    • Deploy headless IB Gateway + IBC on 9900K (handling nightly ~21:00 ET resets and 1100 → 1102 re-subscriptions).
    • Build ib-bridge aggregating reqRealTimeBars(5s, TRADES) + L1 reqMktData quotes (\le 80 active lines) into post-grace closed bars; pin (conid, currency, exchange="SMART", primaryExchange) from listing; route cash sweeps via FXCONV and FX alpha trades via IDEALPRO; implement idempotent client order IDs, partial fills, TSX 15:40 ET / US 15:50 ET auction cutoffs, and continuous position/cash reconciliation.
  • Risk, Kill Switches & Dual Drift Monitor:
    • Global + per-strategy exposure, daily-loss, drawdown, and order-rate kill switches + Trading UI 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.

Exit Criteria

  1. paper-host processes 100,000 sequential quotes with flat < 5 ms p99 latency.
  2. Strategy runs \ge 30 trading days and \ge 50 trades on IB Paper across US (USD) + TSX (CAD) listings, surviving nightly IB Gateway resets with 0 unrecovered reconciliation mismatches and Execution Drift <= 15 bps/trade.
  3. Small-capital live deployment passes pre-flight kill-switch, partial-fill, FXCONV, and reconciliation drills with explicit operator approval.