81 KiB
Architectural & Quantitative Review of docs/PLATFORM-PLAN.md
Reviewed against: stock-bot working tree at HEAD = c353ddbe (+ uncommitted env-safety/compose WIP), QA MongoDB stock (read-only via MONGODB_READ_URI as studio_stock_bot_read@stock), deployed QuestDB 10.2.0, docs/data-pipeline/phase1-investigation.md, October backlog ADRs (ADR-001–ADR-008), and current QuestDB / IBKR API / marimo documentation.
Date: 2026-11-26
Verification tags used throughout this review
[Verified: repo]— confirmed directly in source, SQL migrations, tests, or committed benchmark measurements (file:linecited).[Verified: QA Mongo / PG]— confirmed via read-only queries against the 31 collections instock(studio_stock_bot_read) andtrading_botPostgreSQL.[Verified: external]— confirmed against deployed QuestDB10.2.0(SELECT version(), build), current QuestDB 9.x/10.x docs, IBKR TWS/Web API docs, and marimo 2025/2026 docs.[Assumed]— explicitly stated engineering or market assumption not directly observable in the repo or ingested snapshot.
1. Executive Summary
Is the plan sound?
Directionally yes; mechanically no — several load-bearing assumptions in Sections 5, 6, 7, 9, and 13 fail against the actual raw data in QA MongoDB and the existing code.
Your core strategic instincts are right: signal-first before strategy-first, permanent listing_id keys, mandatory multiple-testing adjustment via a trial ledger, desktop MCP copilot first (D2), and keeping the deterministic fixed-decimal Rust financial kernel (apps/stock/engine/src/financial/*) as the sole accounting authority. The October backlog left you with an unusually strong foundation for invariant enforcement (write-once PostgreSQL triggers, 8-decimal BigRational-backed postings, and a real seccomp/cgroup Docker + Rust PID1 sandbox).
However, the plan was written against an idealized mental model of what the vendors delivered and how QuestDB, the NAPI engine boundary, and the holdout gates behave. In reality:
- Your primary fundamentals (
qmFinancials,eodFinancialsOLD,eodFundamentalsOLD) and macro (teData) collections lack point-in-time filing/release dates and restatement/vintage history;eodIntraday1M(3.40Bbars) is already split-adjusted whileeodPriceshas raw OHLC + split-adjusted volume; andeodSymbolChangecontains only 230 US rows from 2024–2025. - Section 6's
ISIN + MICblocking fails on >80–90% ofibSymbolsbecause IB tags NYSE, Nasdaq, and TSX stocks with secondary execution/ATS venues (AEQLIT,ARCAEDGE,BEX,IEX,OTCLNKECN) rather than primary listing MICs. - Today's "sealed" holdout is readable in plaintext JSON by any
sb-research.*agent token, the Rust/TS pull loop runs at ~5,400 bars/s (making universe-scale callbacks unviable without a feature side-channel and atomic rebalancing fixes), and a solo-developer Phase A→C waterfall delays your first honest signal test by months.
The three things most likely to sink it
- Silent phantom alpha from vendor data illusions (Sections 5, 6, 7). Treating
eodFinancialsOLD.filingDateas real (99.26%equalreportDate),teDataas release-dated (0%release dates, 100% final-revised values),eodIntraday1Mas raw (it is retroactively split-adjusted, so applyingadj_factorsdouble-adjusts every split),eodPrices.volumeas raw (it is split-adjusted, inflating historical dollar-volume capacity by10\times\text{–}56\times), and exchange-delisted bars (SIVB.USending at$106.04) as terminal without OTC-pink continuation (SIVBQ.US→$0.006) or bankruptcy delisting returns will systematically manufacture fake 3.0+ Sharpe backtests that agents will aggressively mine. - Unplugged trial-ledger bypasses and adaptive holdout burn (Sections 1, 9, 11, 12). Today
sb-research.*tokens are explicitly allowed to export full holdout OHLCV JSON (research-agents.service.ts:51), agent budgets enforce concurrent (maxActiveTrials) rather than cumulative lifetime limits, and giving Claude Code / marimo raw table access (stockbot.data.bars()or raw SQL) lets an agent evaluate 5,000 signals in Polars memory and logN = 1on the winner. Worse, letting unattended campaigns (§15) touch the holdout and feed pass/fail into the Knowledge Base / Studioevolveloop adaptively overfits the holdout within weeks. - Solo-developer infrastructure sprawl before testing one real signal (Sections 5, 9, 14, 16). Building a full 6-pass security master + review UI, curating 10 datasets into QuestDB, writing a dual-backend QuestDB↔Parquet parity harness, building 4 playground pillars, and extending the single-asset Rust engine into a multi-currency long/short portfolio engine serially before testing a single cross-sectional hypothesis is ~9–12 months of plumbing.
Verdicts on Decisions Log (D1–D9)
Per ground rules, D1–D8 are treated as settled unless concrete evidence proves a failure mode:
| # | Decision | Verdict | Concrete Evidence & Required Adjustment |
|---|---|---|---|
| D1 | QuestDB for all curated data + parity harness | Challenge partially | Keep QuestDB 10.2.0 for intraday (bars_1m/5m/1h) where SAMPLE BY and WAL streaming excel, but put daily bars, corporate actions, PIT fundamentals/events/shorts/macro, and features directly in Parquet + DuckDB from Day 1, and drop the parity harness. QuestDB ASOF JOIN breaks on long-format EAV fundamentals and regresses fiscal periods on restatements/10-K comparative backfills; DEDUP UPSERT KEYS destroys known_at history or breaks LATEST ON; and libs/data/questdb is currently broken/disabled (data-pipeline/src/index.ts:66). (See Finding F3.) |
| D2 | Desktop copilot first via MCP | Settled (with boundary fix) | Keep D2, but distinguish interactive desktop Claude Code (which has host shell/DB access in studio.config.json:5,9) from autonomous campaign agents (which must run in network-isolated containers with MCP-only access), and air-gap the final Vault Holdout from both. (See Finding F4.) |
| D3–D8 | US+CA priority, incremental UI, Step 1 merge first, IB live end-state, full strategy & lab scope | Settled | Sound; sequenced into vertical slices in Section 4 so D7/D8 do not block early research. |
| D9 | marimo for Python labs inside the app | Confirm (with 4 rules) | Confirm marimo over Jupyter ([Verified: external]). Pure .py git diffs, deterministic DAG execution, marimo check --format=json static validation for LLM edits, marimo edit --mcp, and zero-RAM marimo export html snapshots fit agentic quant research far better than .ipynb. Enforce: (1) separate origin (never same-origin allow-same-origin with web-app's SameSite=Strict session cookie), (2) static HTML snapshots by default in the Agent Lab Feed (--session-ttl 300 for on-demand marimo run), (3) marimo's CLAUDE.md rules + marimo check pre-hook to prevent MB002 variable-redefinition errors and _underscore cell-local scoping so intermediates don't pin GBs of RAM, and (4) register_signal materializes batch feature columns rather than translating Python into TS. (See Findings F5 & F11.) |
2. Findings Ranked by Impact
F1 [CRITICAL — PIT & Data Integrity] — Raw Fundamentals, Macro, Earnings, Filings, and Shorts Cannot Support the Plan's known_at Claims as Written
-
What the plan says (§5 lines 248–251, §7 lines 364–371):
- Fundamentals (
qmFinancials,eodFinancialsOLD,eodFundamentalsOLD): "Point-in-time by filing date (known_at), not period end; restatements as new versions." - Macro (
teData): "release date asknown_at." - Filings (
qmFilings): "insider transactions extracted where present." - Earnings (
qmEarnings), Shorts (ceoShorts), Corporate actions (qmSplits,qmDividends,eodSymbolChange), FX ("to be sourced").
- Fundamentals (
-
What I found (
[Verified: QA Mongo]): Every dataset in Section 7 was sampled and audited viaMONGODB_READ_URI:Dataset (Collection & Count) Empirical Audit Result in QA MongoDB Real PIT known_atDerivable?Honest Fallback & Research Ruled Out Fundamentals — QM ( qmFinancials1.86M+ omittedqmFinancials-old908k)0 / 5,000 ( 0.0%) havefilingDateoracceptedDate; onlyreportDate,periodEndDate,created_at(2025 crawl). Unique-indexed on(qmSearchCode, reportPeriod, reportDate)and overwritten in place → 0 restatement versions acrossAAPL,NVDA,SMCI,TSLA,SHOP:CA,RY:CA,X:CA.Only filingDateviaqmFilingsjoin; NO restatement history.Join (listing_id, periodEndDate)to earliest matching10-Q/10-K/40-F/SEDAR52-109filingtimefiledinqmFilings. Where unmatched, add statutory deadline lag (US: +45d Q / +90d FY; CA TSX: +45d Q / +90d FY; CA TSXV/CSE venture: +60d Q / +120d FY per NI 51-102) + flagknown_at_quality = 'estimated_lag'. Rules out: restatement alpha, pre-restatement surprise studies, exact filing-day fundamental triggers on unlinked rows.Fundamentals — EOD ( eodFinancialsOLD2.98M,eodFundamentalsOLD106.6k)In eodFinancialsOLD(20k sample):19,851 / 20,000(99.26%) havefilingDate === reportDate(30–90d look-ahead!). IneodFundamentalsOLD:filing_dateisnullacross quarters,Highlights/Valuationare unversioned scrape-time snapshots, and currency labels are corrupted on CDRs (AAPLonNEO,_id: 658615f03d1ee2d2611de872, labels Apple's$335.0BUSDtotalAssetsas"CAD"on alternating quarters!).No. Quarantine eodFundamentalsOLDHighlights/Valuationcompletely from backtests (live screener display only). UseeodFinancialsOLDonly for pre-QM history with mandatory +45d/+90d/+120d lag, ignoring its bogusfilingDate == reportDate, and cross-check statement currency against magnitude/instrument currency.Macro ( teData14,794docs)Every document stores data: [{ d: "YYYY-MM-01", v: <number> }]withlastUpdated: 2026-04-02(e.g., USGDP CQOQ{d: "2025-12-01", v: 0.7}, USNFP TCH{d: "2026-02-01", v: -92}, CACACPIYOY{d: "2026-02-01", v: 1.8}). Zero release dates; zero initial/revised vintages.No. Apply conservative publication lags ( +1dcentral-bank ratesFDTR/CCLR;+35dmonthly CPI/NFP/unemployment;+65dinitial /+90dfinal quarterly GDP) and restrictteDatato coarse slow-moving regime filters. Rules out: macro release event studies, macro surprise trading, and un-revised real-time GDP/NFP models (unless ALFRED/FRED + StatCan real-time vintages are ingested).Earnings ( qmEarnings444,865docs)297,779 / 444,865(66.94%) haveannounceTime: "N/A"(80,481AMC,66,605BTO).consensusEpsis overwritten in place (created_at: 2025-06-29), with no estimate revision history.Date yes; intraday session only on 33% (unless linked to qmFilings).Link to qmFilings(8-K/ CanadianNews releasetimefiled) to resolve BMO vs AMC. WhereannounceTime == "N/A"and unlinked, stampknown_at = reportDate 16:05 ET(tradable atT+1open). Rules out: pre-announcement analyst-revision drift andT+0open PEAD entries on un-timestamped rows.Filings ( qmFilings30.52Mdocs)100%of sampled rows carry second-precisiontimefiled("2024-10-08T17:30:13 EST","2023-11-28T10:02:05 EST"). However, documents contain metadata + external QuoteMedia URLs (htmllink/xlslink) ONLY — zero filing body text and zero parsed Form 4 / SEDI share counts or buy/sell indicators (verified on AAPL Form 4acc: 0000320193-24-000114,filer: "MAESTRI LUCA").Yes ( timefiled, convertEST/EDTcleanly to UTC).Filing-arrival/form-type event studies work immediately ( Form 4count,144sale notice count,8-K,NI 43-101,52-109). Rules out: insider net-buy dollar/share-size signals until Form 4 XML / SEDI is fetched and parsed.Dividends & Splits ( qmDividends495,942,qmSplits18,751)qmDividends:408,295(82.33%) have validdeclared < date(ex-date);86,588(17.46%) lackdeclared;1,059havedeclared >= date; CAD dividends carry bogususdFxRate: 1(X:CA_id: 6861bc9c9aba109fccfe8659).qmSplits: only5,646 / 18,751(30.11%) havedeclared, plus258no-opsplitratio == 1rows.Ex-date accounting: 100%. Announcement known_at: 82% divs, 30% splits.Filter splitratio == 1and ignoreqmDividends.usdFxRate(join realfxinstead). Accounting/adjustments trigger onex_date(known to market atex_dateopen). Rules out: split-announcement drift on the 70% missingdeclaredunless linked toqmFilings.Symbol Changes ( eodSymbolChange230docs)230 rows total, 100% exchange: "US",effectivespanning2024-08-12to2025-07-03only (0Canadian rows,0pre-Aug-2024 history).Useless for 20y history. Cannot drive listing_symbol_history(see Finding F2).CEO Posts & Shorts ( ceoPosts14.78M,ceoShorts692,904)100% Canadian ( CNQ4,583,TSX4,127,CDX3,292,AQL587;0US).ceoPostshas mstimestamp, but360 / 20,000(1.80%) haveedited != nullwherespieltext was overwritten later, and includes@thenewswirepress-release bots (bot: "1").ceoShortstimestamps (SHOP.TO:2025-05-15,2025-05-31,2025-06-15) are CIRO/IIROC semi-monthly report period-ends, NOT publication dates (published 3–4 business days later).Posts: yes (with edit guard). Shorts: requires +4 business-day lag. For ceoPosts, ifedited != null, either set textknown_at = editedor exclude edited text from NLP while keeping unedited post-count pulse attimestamp; separatebot == "1"newswires from retail posts! ForceoShorts, setknown_at = timestamp + 4 Canadian business days (17:00 ET). Rules out: US social/short research from CEO.ca.FX ( USD/CAD)Already ingested ( [Verified: QA Mongo])!eodPriceshasCAD.FOREX(12,109daily bars,1971-01-04..2025-08-13) andCADUSD.FOREX(9,351daily bars);eodIntraday1Mhas5,202,0561m bars forCAD.FOREX+5,204,726forCADUSD.FOREX;teMarketDatahasUSDCAD(2,865daily bars through2026-04-02).Yes. No external FX sourcing needed for Phase A–E; curate CAD.FOREX(1m + 1d) supplemented byteMarketData.USDCAD(post-Aug 2025).Futures ( ttFutures1.46Mdocs)Individual historical contracts ( AD90M,CD,CL,SP,US) from 1959 onward with corrupted date strings (minDate: "2001-/0-2/",maxDate: "NaN-at-e\"").Dirty / archival. Defer completely out of scope until post-equity live. -
Recommendation: Add an explicit
known_at_sourceenum ('filing_timestamp' | 'exchange_bar_close' | 'declared_date' | 'statutory_lag_estimate') to every curated PIT row, implement theqmFilings→qmFinancials/qmEarningstimestamp join + NI 51-102 / SEC statutory lag fallbacks ++4bdCIRO short lag, quarantineeodFundamentalsOLDsnapshots, and restrictteDatato lagged regime features (adding FRED/ALFRED + StatCan real-time vintages later only if macro-release alpha becomes a priority).
F2 [CRITICAL — Price/Volume/Survivorship Corruption] — Split-Adjustment Asymmetry Across eodPrices, qmPrices, and eodIntraday1M, Plus Unmodeled Terminal Delisting Losses
-
What the plan says (§5 lines 245–247, §6 lines 317–320, §9 lines 430–431):
bars_1m,bars_5m,bars_1h,bars_1dstore raw OHLCV, withadj_factorsapplied on read or materialized (ADR-003:17also mandates raw prices for share/cash execution).- Universe is "survivorship-free" with "delistings with delisting returns".
-
What I found (
[Verified: QA Mongo]):eodIntraday1M(3.40Bbars) is ALREADY retroactively split-adjusted, whereaseodPrices(845.7Mbars) has RAW OHLC:- Tested on
NEXM.V/NEXM:CA(1:20reverse split on2025-06-20inqmSplits,splitratio: 20): pre-spliteodIntraday1Mon2025-06-18 16:01already reportsclose: 24.29(matching post-split2025-06-20 18:02close: 24.2799), instead of raw~$1.21! StoringeodIntraday1Mintobars_1mas "raw" and applyingadj_factorsdouble-adjusts every split across 3.4 billion bars. Conversely,qmIntraday(173Mbars) stores both raw (open..close,sharevolume) and split-adjusted (adjustedopen..adjustedclose,avolume).
- Tested on
eodPrices.volumeis SPLIT-ADJUSTED whileeodPrices.closeis RAW (10×–56× dollar-volume inflation!):- Tested on
X.TO/X:CA(5:1split on2023-06-14): on2023-06-13,eodPriceshasclose: 147.78(raw),adjustedClose: 28.1493, andvolume: 676,795(= 5 × 135,359), whereasqmPriceshasunadjustedclose: 147.78andsharevolume: 135,359(raw)! - Tested on
NVDA(10:1split on2024-06-10): on2024-06-07,eodPriceshasclose: 1208.88(raw) andvolume: 412,385,776(= 10 × 41,238,580), whereasqmPriceshasunadjustedclose: 1208.88andsharevolume: 41,238,580(raw)! - Multiplying
eodPrices.close * eodPrices.volumeyields $498.5B/day for NVDA pre-split (10× overstated) and 56× overstated pre-2014 liquidity for AAPL — completely breaking universe dollar-volume filters andADR-003:12'sparticipation_rate * bar.volumefill-capacity cap!
- Tested on
- Delisted symbols exist (
52,745US +3,136CA ineodSymbols;15,790US +3,626CA inactive inqmSymbols), BUT terminal delisting losses & spliced bankruptcies corrupt naive survivorship:- Primary → OTC Pink venue drop hides bankruptcy wipeouts:
SIVB.US(Exchange: NASDAQ,ISIN: US78486Q1013) ends on2023-03-09atclose: $106.04, then reappears as a separate symbolSIVBQ.US(Exchange: PINK, same ISINUS78486Q1013) trading pennies down to$0.006. Under §6'slisting = instrument + mic,XNAS(SIVB) andOTCM(SIVBQ) are distinctlisting_ids: marking or exitingSIVBat its lastXNASbar ($106.04) misses a -99.5% loss! - Missing terminal cancellation bars:
BBBYQ.USends on2023-09-29at$0.0789with no$0.00(-100%) Chapter 11 cancellation event; meanwhile cash M&A (AAR-UN.TOending2018-05-25at$8.09,X.USending2025-06-20at$54.84) ends near deal price. - Overwritten pre-bankruptcy tickers in EOD:
GM.USineodPricesstarts2010-11-18(post-bankruptcy IPO) andHTZ.USstarts2021-07-01— pre-2009 Old GM and pre-2020 Old Hertz were overwritten under their root tickers.
- Primary → OTC Pink venue drop hides bankruptcy wipeouts:
-
Recommendation:
- Un-adjust
eodPrices.volumeandeodIntraday1MOHLCV during Step 2 curation using cumulative post-bar split factors fromqmSplits(cross-checked againsteodPricesstep changes andqmPrices/qmIntradayraw series where overlapping), sobars_*is genuinely raw in both price and share count; reject or flag any symbol where split un-adjustment leaves an unexplained step jump. - Link exchange delistings to same-ISIN OTC continuation (
XNAS/XNYS→OTCM) as a mandatory corporate-action liquidation bridge: if a strategy's universe excludes OTC, force-exit at the first tradable OTC open (capturing the$106.04 → $0.50SVB gap loss!), and if a delisted equity has no M&A/cash payout filing and disappears below$1.00(or with-Qbankruptcy suffix), apply a Shumway terminal delisting return (-30%default on involuntary exchange delisting without OTC print;-100%on cancelledPINK/Qshares).
- Un-adjust
F3 [CRITICAL — Storage Architecture (D1 & §5)] — QuestDB ASOF JOIN, DEDUP, and INT Keys Break on Bitemporal Fundamentals and Cross-Sectional Scans; libs/data/questdb Is Broken Today
-
What the plan says (§3 D1, §5 lines 192–253):
- Keep all curated data (
bars_*,adj_factors,corporate_actions, long-formatfundamentals (listing_id, period_end, field),events,shorts,macro,fx) in QuestDB with integerlisting_idkeys andknown_aton every row (known_at <= asOfas a query rule), plus a dual-backend parity harness from Day 1.
- Keep all curated data (
-
What I found (
[Verified: external — QuestDB 10.2.0]+[Verified: repo]):- Deployed QuestDB version discrepancy:
docker-compose.yml:67anddocker-compose.dev.yml:82use unpinnedquestdb/questdb:latest(quantpulled QuestDB10.2.0, while the pre-migration local image was built2025-05-30). Worse,apps/stock/data-pipeline/src/index.ts:66setsenableQuestDB: false("Disabled for now due to auth issues"), andlibs/data/questdbis broken:client.ts:272&query-builder.ts:230emit deprecatedLATEST BY,client.ts:323runs invalidSELECT * FROM table_columns WHERE table_name = ?,schema.ts:313-335silently dropsWAL/dedup/capacity/indexoptions,query-builder.ts:95-111interpolates raw SQL strings, andschema.ts:28-156auto-creates 6 legacy ticker-keyed tables on everyconnect(). - Long-format EAV
fundamentals (listing_id, period_end, field, value, known_at)breaks QuestDBASOF JOIN:- QuestDB
ASOF JOINrequires both tables to be ordered by their designated timestamp and returns at most ONE right-hand row per left row (bars_1d ASOF JOIN fundamentals ON (listing_id)returns 1 randomfield, dropping the other 120 fields!). Joining 20 fields requires 20 chained self-joins, andPIVOTstrips the designated timestamp while clobbering un-updated fields toNULLon partial filings.
- QuestDB
- The Bitemporal Restatement / Comparative-Backfill Trap:
- Suppose Q1 (
period_end = 2024-03-31) is filed2024-05-10, Q2 (period_end = 2024-06-30) is filed2024-08-10, and on2024-09-01a 10-Q/A restatement (or 10-K comparative table) updates Q1 (period_end = 2024-03-31,known_at = 2024-09-01). At bar2024-09-15, a 1DASOF JOINonknown_atpicks2024-09-01and overwrites Q2 with restated Q1, moving the company backward in fiscal time! Nor canASOF JOINcompute 4-quarter TTM sums (E/P,FCF yield,ROE).
- Suppose Q1 (
DEDUP UPSERT KEYSvs.known_atVersioning onbars_*:- QuestDB WAL
DEDUP UPSERT KEYS(ts, listing_id)is destructive last-writer-wins: updating a historical bar with a newknown_atdestroys prior history and makesWHERE known_at <= old_asOfdrop that bar entirely (creating a missing-date hole!). Puttingknown_atin the dedup key (DEDUP UPSERT KEYS(ts, listing_id, known_at)) creates duplicate(listing_id, ts)rows that QuestDB'sLATEST ONcannot deduplicate across a time range becauseLATEST ONonly accepts the designated timestamp (ts) and returns 1 row per partition key (75M(listing_id, ts)keys!).
- QuestDB WAL
INTlisting_idDisables QuestDB's Fast Paths:- In QuestDB,
LATEST ON ts PARTITION BY colonly halts backward partition scans early whencolisSYMBOL(dictionary-encoded); onINTit scans every partition in range.ASOF JOINlikewise uses specialized memoized paths onSYMBOL. At 50k–400k listings across 10 tables,SYMBOLmust be declaredSYMBOL CAPACITY 65536 NOCACHEto avoid JVM heap bloat.
- In QuestDB,
- QuestDB Native Parquet Reality (
QuestDB 10.2.0):- QuestDB 10.2 supports
read_parquet()andALTER TABLE ... CONVERT PARTITION TO PARQUET, which cuts disk usage 5–10× on coldbars_1mpartitions — but queries slower inside QuestDB than native mmap and rewrites entire partitions on out-of-order writes, and its internaltable~N/directories (_txn/_meta) are not external Hive Parquet lakes.
- QuestDB 10.2 supports
- Deployed QuestDB version discrepancy:
-
Recommendation: Amend D1 now to split curated storage by workload behind
MarketDataStore, and cut the dual-backend parity harness.- DuckDB + Hive Parquet (
/mnt/data/stockbot/curated/*.parquet): Storebars_1d,corporate_actions,adj_factors, bitemporalfundamentals,events,shorts,macro,fx, andfeaturesin ZSTD Parquet queried via DuckDB. DuckDB handles 75M daily rows (20y × 15klistings) withRANK() OVER (PARTITION BY ts), true 2D bitemporalQUALIFY row_number() OVER (PARTITION BY listing_id, period_end ORDER BY known_at DESC) = 1, and zero-copy Arrow export to Polars/marimo in <1–3 seconds onquant's SN850X NVMe + 125 GiB RAM. - QuestDB
10.2.0(pinned image tag, rebuilt thin client): Reserve strictly forbars_1m(deriving5m/1hviaSAMPLE BYor materializing where needed) + live/paper hot streaming bars, usinglisting_id SYMBOL CAPACITY 65536 NOCACHE, single-versionDEDUP UPSERT KEYS(ts, listing_id)+ a separate sparsebar_revisionstable, and converting sealed>90dbars_1mpartitions to Parquet (CONVERT PARTITION TO PARQUET) only if NVMe space requires it. - (Close runner-up if you insist on keeping 100% of v1 in QuestDB: materialize wide forward-filled
fundamental_pit_snapshots+ TTM columns indata-pipelinebefore writing to QuestDB, storelisting_idasSYMBOL NOCACHE, keepbars_1dsingle-version + sparsebar_revisions, and still skip building the DuckDB parity harness until QuestDB fails a measured exit target.)
- DuckDB + Hive Parquet (
F4 [CRITICAL — Statistical Rigor & Security (§1, §9, §11, §12)] — Active Holdout Leak in web-api Today, Six Trial-Ledger Bypass Vectors, and Adaptive Holdout Overfitting
-
What the plan says (§1 lines 44–50, §9 lines 437–458, §11 lines 531–535, §15 line 671):
- Sealed out-of-sample holdout "Exists"; every signal analysis, screen, and backtest from any agent, notebook, or UI is recorded in the trial ledger; notebooks get a "flagged raw-SQL escape hatch"; and "Everything up to Validated can run unattended."
-
What I found (
[Verified: repo]):- The "sealed" holdout is wide open across calls today:
- While a single
ChronologicalValidationstate machine (apps/stock/web-api/src/services/chronological-validation.service.ts:163-444,database/postgres/init/24-chronological-validation.sql) freezestrainselection before runningtest,research-agents.service.ts:51explicitly permitssb-research.*tokens to callGET /api/v2/datasets/canonical/:hash/export! BecausesubmitValidationimmediately inserts thetestslice intobacktest_datasetsand returns its hash (and the parentbacktestIdspanstrain+validation+test), any agent can download every bar of thetestholdout in plaintext JSON (scripts/research-client.ts:782-797), run whole-window sweeps onbacktestId, read all other principals'testtrade logs via unscoped globalGETs (research-agents.service.ts:46-53), and re-submitv1, v2, ..., v500againsttestwith zero cumulative budget (28-research-agents.sql:100-191only caps concurrentactive_trialsand per-experiment<= 100runs, never lifetime trials!).
- While a single
- No trial ledger, DSR, PBO, or CPCV exists in the live stack:
chronological-validation.ts:30-31hardcodeslabelHorizonMs: z.literal(0)(no purge/embargo). The only DSR code in the repo (apps/stock/analytics/src/analysis/statistical_validation.py:56-58, 130-156) is dead (503disabled inCL35), omits skewness/kurtosis and cross-trial Sharpe variance, and callscalculate_deflated_sharpe_ratiowith defaultnum_trials = 1(ln(1) = 0)!
- Three fatal bypasses in the proposed MCP + Python SDK + marimo design:
- In-memory Polars evasion: Once
stockbot.data.bars()or MCPquery_datareturns a DataFrame to marimo or a script, an agent can loop over 5,000 expressions in Python memory with zero SDK analysis calls and register only the winner (N = 1logged instead of5,000). - Desktop Claude Code host access:
studio.config.json:5,9gives desktop agents"shell": trueon the host where.envand unauthenticated QuestDB (:9000/:8812) live. - Raw-SQL escape hatch (§5 line 211): Bypasses
known_at <= asOf, holdout date fences, and trial counting simultaneously. "Flagging" a notebook does not stop an agent or human from copying the winning formula into a clean MCP backtest call.
- In-memory Polars evasion: Once
- Adaptive holdout destruction (§15 line 671): Allowing unattended agent campaigns to run through
Validatedon the holdout and write verdicts to the Knowledge Base / Studioevolveloop turns the holdout into an adaptive training oracle (kadaptive queries leak information atO(\sqrt{k/T})).
- The "sealed" holdout is wide open across calls today:
-
Recommendation:
- Two-Tier Air-Gapped Holdout: Split OOS into (a) Research Validation (
ts < VAULT_CUTOFF_DATE, e.g., trailing 24 months reserved) evaluated via Purged Walk-Forward + CPCV (purge = horizon + warmup,embargo = max(5d, 0.01*T)) + DSR/PBO for unattendedValidatedgating, and (b) a Physically Air-Gapped Vault Holdout (ts >= VAULT_CUTOFF_DATE) stored in a separate vault path unreadable byMarketDataStore,export, marimo, orsb-research.*tokens. Only a humanValidated → Paperaction triggers a one-shot Vault evaluation (hard-capped at\le 10vault burns/year in an immutable Postgres table, rolling forward annually). - Patch
research-agents.service.ts&28-research-agents.sqlimmediately: Remove/exportfromsb-research.*, scopeGETroutes byallowedProjectIds/grants, and add cumulative per-campaign and daily trial + bar-evaluation counters enforced in SQL triggers. - Define "related trial" deterministically & store return vectors for
\hat{N}: Group trials by objective(universe_market, horizon_bucket)({US, CA, US_CA} × {intraday, swing_1_10d, position_10d_plus}), never by agent-inventedfamilylabels. Persist the daily out-of-warmup return/IC vector (float32 array, ~20 KB for 20y daily) of every evaluated variant intrial_ledgerso DSR computes Bailey & López de Prado's effective independent trials $\hat{N} = 1 + (N-1)(1 - \bar{\rho})$, cross-trial Sharpe variance\text{Var}[\{\widehat{SR}_n\}], and non-normal(\hat{\gamma}_3, \hat{\gamma}_4), while PBO (CSCV,S=16slices) runs over synchronous campaign return matricesM_{T \times N}. - Close notebook/agent bypasses: Run autonomous agents in
--networkisolated containers talking only to the MCP/HTTP API (no raw SQL, no DB ports, no host shell); restrict the raw-SQL escape hatch to human localhost sessions over pre-vault views; and log data-pull footprints (universe × window × features) alongside every trial.
- Two-Tier Air-Gapped Holdout: Split OOS into (a) Research Validation (
F5 [HIGH — Security Master (§6)] — Blocking on MIC Breaks on >80% of ibSymbols, Ticker Reuse (FB, GM, HTZ) Collides Without Validity Windows, and Naïve MongoDB Price Cross-Checks Are 13.6× Slower Due to Index Order
-
What the plan says (§6 lines 260–351):
- Pass 1 maps each provider exchange code to a canonical ISO 10383
mic. - Pass 3 blocks candidates within
country + MIC: Tier 1 =Valid ISIN + MIC(IB, EOD), Tier 2 =CUSIP-derived ISIN + MIC(IB → EOD), Tier 3 =Normalized ticker + MIC (+ currency). - Pass 4 compares overlapping daily closes per candidate pair; Pass 6 sources ticker history from
eodSymbolChange.
- Pass 1 maps each provider exchange code to a canonical ISO 10383
-
What I found (
[Verified: QA Mongo]+[Verified: repo]):ibSymbols(18,402rows) stores execution/ATS venues, NOT primary listing MICs (isPrimeExchIdisnull):- Actual
ibSymbolsvenue distribution ([Verified: QA Mongo]):- Canada (
3,846rows):AEQLIT(Cboe/NEO Lit ATS) =2,506(65.2%),VENTURE=826,TSE=514(13.4%). Over 83% of TSX-listed stocks inibSymbols(e.g.CIA= Champion Iron) haveexchangeId = "AEQLIT"(NEOE), whereas EOD (TO) and QM (TSX) place them onXTSE! - US (
14,556rows):OTCLNKECN=6,627,ARCAEDGE=1,067,AMEX=838,BEX=777,DRCTEDGE=682,EDGEA=523,IEX=509(e.g., AgilentA!),LTSE=426,MEMX=397,NYSE= ONLY370(2.5%),CHX=310,NYSENAT=250,NASDAQ= ONLY241(1.7%)! - Meanwhile,
eodSymbolsputs103,792US rows under compositeeodExchange = "US"(including44,970NMFQSmutual funds that must be excluded from equity universes, plus262Exchange: nulland288Exchange: "US"rows), and existingnormalizeProviderSymbol(apps/stock/data-pipeline/src/normalization/provider-symbol.ts:34-49) ignoresexchangeIdanddescription, skipping 100% ofibSymbolstoday!
- Canada (
- Result: Blocking or matching Tier 1/Tier 2 on
ISIN + MICmisses >90% of US NYSE/Nasdaq stocks and >83% of TSX stocks inibSymbols!
- Actual
- Matching without temporal validity windows corrupts reused tickers (
FBvsMETA, CSE duplicates):- Verified live collision (
[Verified: QA Mongo]): EOD retroactively renamed Facebook's 2012–2022 bars toMETA.US, whileFB.USis now active (Name: "ProShares Trust ProShares S&P 500 Dynamic Buffer ETF",Exchange: "BATS",Isin: null, bars starting2025-06-26). MeanwhileqmFilings(30.5Mdocs) keys historical 2012–2022 Facebook filings bysymbol: "FB"! Static Tier 3 ticker matching attaches Meta's historical filings/events onto a 2025 S&P 500 Buffer ETF. Similarly,qmSymbolshas duplicate(symbol, exchange)rows onCNQ(VOY:CNXactive +VOY:CCinactive,PKK,RIPP, etc.).
- Verified live collision (
- ISINs and CUSIPs are NOT immutable across reorganizations and TSXV share consolidations:
instrument(instrument_id, ISIN, CUSIP, ...)assumes 1 permanent ISIN per company. In Canada (XTSX/XCNQ), every reverse split / name change / continuance issues a new CUSIP and ISIN, and corporate redomiciliations (LINPraxair/Linde US → Ireland → UK ISINs; SPAC de-SPACs) change ISIN while the economic listing continues.
- Pass 4 Price Cross-Check MongoDB Index Trap:
eodPrices(845.7Mdocs) has{date: 1, eodSearchCode: 1}and{eodSearchCode: 1}— no{eodSearchCode: 1, date: 1}index! Benchmarking 10 symbols viaMONGODB_READ_URItook309.6 msoneodPrices(scanning full 25y symbol history) vs22.8 msonqmPrices(13.6×slower warm; seconds per symbol cold on uncached delisted symbols → many hours for 50k pairs).
-
Recommendation:
- Two-stage resolution (Instrument first, Venue second): Resolve
instrumentglobally by Luhn-valid ISIN / CUSIP-derived ISIN (with aninstrument_identifier_history(instrument_id, id_type, id_value, valid_from, valid_to)table for reorganizations/reverse-splits). Determine primarylisting (instrument_id, mic)from EODExchange+ QMexchange(filtering outNMFQSmutual funds from equity universes), and attachibSymbols(conid) at(instrument_id, currency)— never treating IBAEQLIT/IEX/BEX/ARCAEDGEas primary listing MICs! - Precompute
[first_bar_date, last_bar_date]per(source, source_id)before Pass 3: Require overlapping active date windows on Tier 3/4 ticker matches, populateprovider_mapping.(valid_from, valid_to)from observed bar/filing spans + corporate actions rather than relying on the 230-roweodSymbolChangetable, and route non-overlapping same-ticker pairs (like pre-2022FBvs 2025FB) to separatelisting_ids. - Execute Pass 4 Price Cross-Check via 25 stratified cross-sectional dates (
{ date: { $in: sampleDates } }), NOT per-pair queries: QueryingeodPricesbydatefirst hits{date: 1, eodSearchCode: 1}sequentially (or run Pass 4 in DuckDB after bulk-extracting US+CA daily closes), completing all US+CA candidate return-correlation & USD/CAD ratio checks in <30 seconds instead of hours.
- Two-stage resolution (Instrument first, Venue second): Resolve
F6 [HIGH — "One Engine" vs. Actual Design (§4, §8, §9, §11)] — Three Engines, 5× Conflicting Math Implementations, a 5,400 bars/s NAPI Bottleneck, Two Multi-Asset Rust Bugs, and a Five-Wall Python→TS Promotion Blockade
-
What the plan says (§1 line 46, §8, §9, §11 lines 534–536):
- "One engine. The same Rust core runs backtest, paper and live."
- Tier 1 fast vectorized screener "Reopens deferred task P06".
- Tier 2 extends the Rust engine to multi-asset cross-sectional long/short portfolios; strategies stay sandboxed TypeScript;
register_signal(...)promotes a Python notebook signal into the feature library and strategy lifecycle.
-
What I found (
[Verified: repo]):- Three coexisting simulators + 5–6 conflicting indicator/metric implementations exist today:
- Engines: (a) Canonical fixed-decimal Rust
financial/*, (b) Legacyf64RustBacktestEngine(engine/src/backtest/engine.rs), and (c) Legacy TypeScriptSimulationExecution(orchestrator/src/execution/SimulationExecution.ts). - Math divergence (
[Verified: repo]): RSI has 3 incompatible formulas (on flat pricesgain=loss=0, Rustrsi.rs:72-77returns99.01, Rustcalculate_rsireturns100.0, TSRsiIndicatorrsi.ts:36-38returns50.0, andtrailingSimpleRsiuses simple rolling averages instead of Wilder smoothing!). Sharpe, Sortino, Volatility, Annualization, and Max Drawdown have 5–6 implementations using conflictingddof=0vsddof=1,252vs365vs365.25days/year, geometric vs arithmetic returns, and Sortino denominators (return-statistics.ts:50-102vssimple_results.rs:174-235, 399-431vsperformance.py:139-163vsstatistical_validation.py:94-108).
- Engines: (a) Canonical fixed-decimal Rust
P06is mischaracterized (§9 line 418 vsdocs/development/backlog/tasks/P06.md):P06is a tiny declarative AST inside the event-driven RustReplayloop requiring exact economic-hash equivalence — not a vectorized cross-sectional screener. A vectorized matrix screener (Polars/DuckDBcomputing(T × N)weights × forward returns minus linear turnover cost) intentionally omits integer lot rounding, cash reservations, and path-dependent halts: it will implement simplified portfolio math separate from Rust, and the plan should own that explicitly rather than calling itP06.
- Two concrete multi-asset bugs inside
apps/stock/engine/src/financial/today:- Bug A — Non-atomic
Targetcash reservation blocks portfolio rotation (matching.rs:1083-1136,risk.rs:564-566):Ledger,RiskAccount, andMatchingAccountalready use multi-instrumentBTreeMaps internally (single-asset is gated in TS atnative-worker.ts:49-51andcandidate-execution.ts:27-42), butStrategyIntent::TargetsubmitsSell AandBuy Bsequentially againstavailable_cash(). Because pendingSell Aproceeds are not credited until next-open fill, any fully invested cross-sectional rebalance rejectsBuy BwithRiskRejection::InsufficientCash! - Bug B — Sequential same-timestamp marking latches false drawdown halts (
ROADMAP.md:44,replay.rs:24-28): Updating marks lexically one instrument at a time at timestampttrips irreversible portfolio daily-loss/drawdown halts on intermediate unhedged marks even when simultaneous offsetting long/short moves leave net equity flat.
- Bug A — Non-atomic
- The 5,400 bars/s NAPI + JSON wall (
conditional-review.md:27-28,api/canonical.rs:33-43):- Every trading bar crosses JS↔Rust NAPI twice (
advance+submit), double-parsing JSON insideapi/canonical.rs:33-43and recursively cloning/freezing plain JSON state (strategy-decision.ts:35-88) — plus two Docker stdio pipe crossings per bar for sandboxed candidates (candidate-sandbox.ts:279-323). At ~5,400–7,400 bars/s, a single 20-year daily cross-sectional backtest over 8,000 listings (40Mbars) takes ~1.8 hours unless strategies trigger only on rebalance barriers (e.g., daily close / weekly) with batch binary/Arrow observation loading rather than stringified JSON per bar!
- Every trading bar crosses JS↔Rust NAPI twice (
- Five hard walls block moving a signal from Python/marimo to a TypeScript strategy today:
- (i)
candidate-host.ts:29-42bans allimports (even@stock-bot/calculations); (ii)StrategyContext(libs/research/src/strategy-api.ts:39-60) only carries OHLCVPreparedBars — zero channel for features, fundamentals, or events; (iii)Replay::validate(replay.rs:404-413) requiresopen/high/low/close > 0(Positive), so signed signals/z-scores cannot even be passed as synthetic bars; (iv)copyJsonStatebansFloat64Array/Map; and (v) promoting a candidate topaper-host.ts:34-37drops the Docker/seccomp sandbox completely!
- (i)
- Three coexisting simulators + 5–6 conflicting indicator/metric implementations exist today:
-
Recommendation:
- Make Feature Materialization the sole Python → TypeScript bridge: Define features once as versioned DuckDB SQL or Python/Polars batch jobs (
features/<name>/v<k>.py|.sql) that write(listing_id, ts, known_at, value: f64)to thefeaturesstore. Add a read-onlyfeatures: Record<string, number | null>map to RustReplaydecision barriers andStrategyContext. Then Python notebooks, the vectorized screener, AND TypeScript strategies all read the exact same precomputed feature values — zero Python→TS indicator rewrites, and sandboxed TS strategies shrink to ~40 lines of pure sizing/rebalance logic! - Consolidate metrics & retire legacy engines: Delete dead
apps/stock/analyticsmetric code and retire legacyf64BacktestEngine+ TSSimulationExecutiononce multi-asset cutover lands; makelibs/calculations(returnStatistics,drawdownAnalysis, plus new DSR/PBO) the single metric calculator served by the Research Kernel API to UI, MCP, and Python SDK. - Fix Rust multi-asset replay before Phase C: (a) Apply all bar marks at timestamp
tatomically before evaluatingRiskAccountdrawdown/daily-loss latches; (b) add net-proceeds target rebalancing (expected_sell_proceeds * (1 - haircut)offsetting same-barrier buy reservations for next-openTargetbatches); (c) strip the duplicateserde_json::Valueround-trip inapi/canonical.rs:33-43and load datasets into Rust from Parquet/Arrow paths instead ofJSON.stringify(which also hits PostgreSQL's 1 GBJSONBlimit on universe datasets!).
- Make Feature Materialization the sole Python → TypeScript bridge: Define features once as versioned DuckDB SQL or Python/Polars batch jobs (
F7 [HIGH — Phase 0 Safety & Bootstrap] — Three Undocumented Bugs in the Current Working Tree Break Phase 0 Isolation and Leak Secrets
-
What the plan says (§2 lines 71–92, §6 line 351, §16 Phase 0, §17 lines 691–698):
- Only 2 gates fail (
test:toolingandlint:check);audit:secretspasses;mongoReadOnlyrejects all MongoDB writes at the client layer;assertEnvironmentSafety()enforces dev isolation; Phase 0 startstrading_bot_dev(5433) and runsdata-pipelineagainst QA Mongo viaMONGODB_READ_URI.
- Only 2 gates fail (
-
What I found (
[Verified: repo]):- Dev PostgreSQL init scripts (
01–05) hardcode\c trading_bot;— leavingtrading_bot_devwith ZERO master tables:database/postgres/init/01-init-database.sql:5-9runsCREATE DATABASE trading_botand\c trading_bot;, and02-master-schema.sql:3,03-initial-data.sql:2,04-provider-exchange-mapping-schema.sql:3, and05-add-visible-column.sql:3all execute\c trading_bot;! Meanwhile06–33omit\cand run inPOSTGRES_DB(trading_bot_dev). On a freshdocker-compose.dev.ymlvolume,exchanges,symbols,provider_mappings,provider_exchange_mappings, andsync_statusare created in an unusedtrading_botDB, sodata-pipelineconnecting totrading_bot_devimmediately crashes on missing tables!
MongoDBClientreadOnly: trueis bypassed bygetDatabase()/collection(), anddata-pipelinehas an active MongoDB write handler:libs/data/mongodb/src/client.ts:195-202, 384-395, 637-639, 682-684(getDatabase(),getDb(),database,getCollection(),collection()) return unwrapped nativemongodbdriver objects with zeroassertWritable()checks!apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts:73-128callsmongoClient.getDatabase().collection('masterExchanges').updateOne(...)and.insertOne(...)!- Worse,
apps/stock/config/src/env-safety.ts:86-94only emitslogger.warn(does not throw!) ifdevelopmentdataPipelineconnects to QA MongoDB astrading_admin, andisQaMongoTarget(lines 43-47) returnsfalseifMONGODB_URIomits/stockin the URL path (mongodb://localhost:27017?authSource=admin)!
- Live third-party credentials committed in source missed by
audit:secrets+ scheduled ingestion auto-start:apps/stock/data-ingestion/src/handlers/ib/shared/config.ts:19hardcodes a live rotating Webshare proxy URL with username/password, anddocs/data-sources.md:15contains a plaintext Alpha Vantage key.- Starting
data-ingestionruns scheduled background crawls automatically unlessQUEUE_ENABLE_SCHEDULED_JOBS=false(verified live whenteCountries.updated_atadvanced on container boot).
- Dev PostgreSQL init scripts (
-
Recommendation: Add four mandatory items to Phase 0 before touching Phase A: (1) strip
CREATE DATABASE trading_botand\c trading_bot;fromdatabase/postgres/init/01..05.sql; (2) throw inMongoDBClient.getDatabase()/collection()whenreadOnly: true(or proxy read-only collections), delete legacysync-ib-exchanges.operations.ts, and makeassertEnvironmentSafety()throw ifdataPipelinetargets port27017withoutreadOnlyor withtrading_admin; (3) rotate and remove the hardcoded Webshare proxy credential inib/shared/config.ts:19(anddocs/data-sources.md:15) and addhttp://user:pass@URL patterns toscripts/audit-secrets.ts; (4) defaultQUEUE_ENABLE_SCHEDULED_JOBS=falseoutside explicit ingestion worker deployments.
F8 [HIGH — Live Execution & Drift (§13)] — Missing Live Bar Architecture, Confounded Drift Monitoring, Unbounded O(N) Paper State Replay, and IBKR USD/CAD + TSX Microstructure Gaps
-
What the plan says (§13 lines 600–615):
- Extend existing restart-safe paper host to multi-strategy/multi-asset → add IB adapter (TWS/IB Gateway) for US + Canada → OMS, continuous reconciliation, per-strategy/global risk, "Live vs backtest tracking error on the same bars; auto-demote when outside bounds", and "USD and CAD accounts/positions; base-currency P&L".
-
What I found (
[Verified: repo]+[Verified: external — IBKR API]):- Zero IB API code exists in the repo, and
paper-hosthas 4 concrete defects today:- Only a
@Disabled()Playwright marketing-page scraper exists (apps/stock/data-ingestion/src/handlers/ib/), which also writes toib_symbolsinstead ofibSymbols(fetch-symbols.action.ts:108). O(N)genesis replay per quote (apps/stock/engine/src/api/paper.rs:68-125):stage_financial_transactionis stateless across NAPI; on every single quote, it loads the entire uncompactedsimulation_accounts.stateJSONB from Postgres and replays everyMatchingReceiptandRiskReceiptfrom account genesis twice (MatchingAccount::restoreat line 75 +RiskAccount::restoreat line 95)! Over weeks of 1m/quote paper trading, every tick grows linearly slower until timeouts trip.- Backtest vs. Paper execution-mode split: Backtest
ReplayrejectsExecutionMode::Quote(replay.rs:360-361, forcingOpen), whereasvalidatePaperConfigurationrejectsExecutionMode::Open(paper-configuration.ts:36-37, forcingQuoteand requiring every pushed HTTP frame to end with an L1quote,feed.ts:370-372). - Bar-revision crash & missing reset/sandbox:
CanonicalPaperRuntime(feed.ts:158-161,CanonicalPaperRuntime.ts:344-349) throws a fatalconflictif a bar is revised;api/paper.rs:20-32omitsMatchingReset(so a drawdown halt can never be operator-reset via NAPI); andpaper-host.ts:34-37loads promoted candidate JS unsandboxed inside the privileged orchestrator process!
- Only a
- Source of live IB bars & why they systematically diverge from EOD/QM bars:
- IB
reqRealTimeBarsemits 5-second bars only (whatToShow="TRADES"required for non-zero volume) and shares IBKR's 100 concurrent market-data line cap (and 60 req / 10 min pacing limit) with L1reqMktDataquote streams! MeanwhilereqHistoricalData(..., keepUpToDate=True)mutates forming bars in place, sends no explicit bar-closed event, revises just-closed bars on late prints, and silently dies during IBKR's nightly ~21:00 ET server reset. - Vendor vs. IB bar divergence: IBKR
SMARTTRADESfilters out away-from-NBBO, combo, contingent, and certain off-exchange/odd-lot prints included in US SIP / TMX consolidated EOD & QM feeds (so IB bar volume is systematically lower and H/L wicks differ), and primary opening/closing crosses (15:50 ETNYSE/Nasdaq MOC cutoff;15:40 ETTSX MOC cutoff) differ betweenSMARTandprimaryExchange. Comparing live IB P&L against a backtest rerun on EOD/QM bars confounds feed divergence with execution drift!
- IB
- USD/CAD & Canadian market-structure traps on IBKR:
- Margin vs. Cash FX: On an IBKR Margin account, buying USD stocks in a CAD-funded account does NOT auto-convert currency — it creates a negative USD cash balance (a margin loan accruing daily USD interest)! On a Cash account, auto-conversion charges ~3 bps markup. Explicit programmatic FX conversion must route to
exchange="FXCONV"(secType="CASH",USD.CAD, $2 min), neverIDEALPRO(which creates a virtualUSD.CADFX position inpositions()that breaks reconciliation!). Both US and CA equities +USD.CADsettleT+1, except across mismatched US/CA bank holidays (Thanksgiving, Victoria Day, Civic Holiday, Boxing Day). - Interlisted routing & TSX/TSXV board lots: Interlisted stocks (
SHOP,RY,TD,CNQ) must pinconid+currency+primaryExchange(TSEvsNYSE) soSMARTnever routes across the border. And TSX/TSXV enforce price-tiered Standard Trading Units (Board Lots):100shares ($\ge $1.00$),500shares ($$0.10\text{–}$0.995$),1,000shares ($<$0.10$) — whereas currentwholeShareTarget(canonical-sma.ts:148) sizes to 1-share integers, generating odd-lot/mixed-lot orders routed to Canadian odd-lot dealers with inferior resting fill semantics!
- Margin vs. Cash FX: On an IBKR Margin account, buying USD stocks in a CAD-funded account does NOT auto-convert currency — it creates a negative USD cash balance (a margin loan accruing daily USD interest)! On a Cash account, auto-conversion charges ~3 bps markup. Explicit programmatic FX conversion must route to
- Zero IB API code exists in the repo, and
-
Recommendation:
- Build a dedicated IB Gateway Market Data & OMS Bridge service (speaking TWS socket API to headless
IB Gatewaymanaged byIBCon the isolated9900Kbox perdocs/servers.md): aggregatereqRealTimeBars(5s, TRADES)+ L1reqMktDataquotes into session-aligned bars emitted only after bar-close + 2s grace (soCanonicalPaperRuntimenever sees mid-bar mutations), capped to\le 80active symbols without quote boosters (or run daily strategies off scheduled post-close/pre-open snapshots). - Split Drift Monitoring into two orthogonal checks:
- Engine/Execution Drift: Live IB fills vs. Rust backtest replay on the exact recorded IB live bars & quotes (isolates slippage, partial fills, latency, and OMS bugs).
- Feed Basis Drift: Rust replay on recorded IB bars vs. Rust replay on ingested EOD/QM bars for the same dates (isolates SIP vs. IB
SMARTbar/volume divergence).
- Fix Rust
Ledger&paper.rsbefore multi-strategy paper: Compactsimulation_accountscheckpoints (periodic snapshot + tail receipts instead ofO(N)genesis replay), exposeMatchingReset, model per-currency cash bucketsBTreeMap<Currency, Posting>with explicitFXCONVrebalance policy (or daily IB margin-interest accrual if intentionally borrowing), pinconid + currency + primaryExchangefrom the security master, and enforce TSX/TSXV board-lot rounding (100/500/1000) in position sizing.
- Build a dedicated IB Gateway Market Data & OMS Bridge service (speaking TWS socket API to headless
F9 [MEDIUM — PostgreSQL Migrations (§18 Q2)] — web-api's migration-runner.ts Cannot Be Reused As-Is for data-pipeline
-
What the plan says (§18 line 713):
- "How are schema changes applied to existing PostgreSQL volumes? Recommendation: reuse
apps/stock/web-api/src/migrations/migration-runner.tsfor master tables instead of init SQL only."
- "How are schema changes applied to existing PostgreSQL volumes? Recommendation: reuse
-
What I found (
[Verified: repo]):apps/stock/web-api/src/migrations/migration-runner.ts:9-102uses a solid transaction-pinned advisory lock (pg_advisory_xact_lock(0x53544254, 1)), but has four blockers: (1) importing fromapps/stock/web-apiintoapps/stock/data-pipelineviolates theCL26cross-app import gate (scripts/test/shared-runtime.test.ts:13-24), whilelibs/data/postgres/src/index.ts:12still has// TODO: Implement migrations; (2)migration-runner.ts:48-77hardcodes an exact===filename allowlist (09–33) duplicated across 3 test files (test/postgres/migration-runner.test.ts:13-39, etc.); (3)09-backtest-run-contract.sqlcrashes on standalonedata-pipelinetest schemas (test/postgres/pipeline-safety.test.ts) where06..08(backtests/runs) weren't pre-created; and (4)PipelineSyncRepository.ts:19uses a different advisory lock key (0x73746274).
-
Recommendation: Extract
runMigrationsinto@stock-bot/postgres(libs/data/postgres), fix\c trading_bot;in01..05.sql, split migrations into two ordered tracks (masterDDL02..05 + security_mastervsresearchDDL06..33+) using idempotent baseline guards (CREATE TABLE IF NOT EXISTSfor02..08), and exposebun run db:migrateso bothdata-pipelineandweb-apiapply only pure fast DDL on startup.
F10 [MEDIUM — Agent Knowledge Base & Web App (§12, §14)] — Unnecessary Duplication of Studio's 83-Card Quant Library, Plus Misstated web-app Baseline
-
What the plan says (§12 lines 556–566, 589; §14 lines 638–648):
- Build a Knowledge Base in Stock Bot "modeled on Studio's cards: Methods, Known anomalies and their literature, Your verified findings and dead ends, Data caveats" that "can feed Studio's quant library."
- Evolve
dashboard → Home,research/experiments/backtest → Lab + Strategies + Agents,charts → Shared chart components.
-
What I found (
[Verified: repo]):/home/boki/repos/studio/catalog/quant/library/library.ymlalready contains 83 curated quant cards across 12 sections (validation,alphas,features,statistics[DSR, BH-FDR, White's Reality Check, Newey-West],ml,regimes,pitfalls[PBO, look-ahead, survivorship],portfolio,risk,microstructure,execution,live-ops). Maintaining a second copy of generic quant methods/literature in Stock Bot creates guaranteed two-way sync rot.web-appbaseline discrepancies (29,590LOC):apps/stock/web-app/src/features/dashboardis an empty directory (0files) removed inCL24(App.tsx:27-28redirects/to/backtests) —Homeis greenfield, not an evolution ofdashboard.- Conversely,
ResearchAgentsPage.tsx(377LOC at/research/agents,App.tsx:55) andStoredSourceInspector.tsx(364LOC) already exist today (though/research/agentsis missing fromSidebar.tsx!), and two separate chart stacks exist (src/components/charts/Chart.tsxvssrc/features/charts/components/SymbolChart.tsx). - Also minor repo-state inaccuracies in §2 & §3:
studio.config.json:34-42points to nonexistentdesign/*anddocs/marketing/brand.md; actual backlog completion after E13 (CL22–CL35,docs/development/backlog/README.md:3-15) is 113 done / 5 deferred / 4 merged = 122 IDs (not99/5/4 = 108); and §2lint:check(line 85) is61inphase1-inventory.ts(59errors +2warnings) +4in WIP files =65(not61 + 7).
-
Recommendation: Mount/read Studio's
catalog/quant/library/library.ymldirectly as read-only methodology/literature context in the MCP server, and store only empirical Stock Bot artifacts (findings,dead_ends, andprovider_caveatslinked to run/signal hashes) in PostgreSQL. Inweb-app, wire existing/research/agentsintoSidebar.tsx, unify the twolightweight-chartswrappers before building Lab screens, and defer greenfieldHome+Marketsuntil after Signal Lab and Portfolio Backtest v2 work.
F11 [MEDIUM — marimo Integration Details (D9 & §11)] — Cookie/Origin Isolation, Kernel RAM Pinning, and MB002 Agent Codegen Failures
-
What the plan says (§3 D9, §11 lines 507–539):
- Agents write
research/notebooks/*.py;marimo editfor your sessions on localhost behind the app's auth;marimo run/ static HTML for agent findings embedded in the AppLabtab.
- Agents write
-
What I found (
[Verified: external — marimo docs]+[Verified: repo]):- Same-origin
<iframe>steals operator session cookies:web-apiissuesstock_bot_session(HttpOnly; SameSite=Strict,libs/core/di/src/http/security.ts:254). Ifmarimois reverse-proxied underweb-app's origin with<iframe sandbox="allow-scripts allow-same-origin">, JavaScript in an agent-authored notebook widget can call/api/v2/paper-deploymentsor/api/v2/research-agentsas'operator'! - Per-tab Python kernel memory pinning: Both
marimo editandmarimo runspawn 1 Python process per open browser session and keep all global cell variables pinned in RAM to power reactive downstream cells (easily 1–3 GB per Polars tab). - LLM
MB002(multiple-definitions) trap: Unprimed LLMs writedf = ...orfig = ...across multiple cells, which marimo's static DAG compiler hard-rejects (MB002). Fortunately,marimo check --format=json file.pyvalidates the entire AST/DAG statically in milliseconds without starting a kernel, andmarimo edit --mcpgives desktop Claude Code live read-only cell inspection.
- Same-origin
-
Recommendation: Confirm D9 (marimo) with four concrete implementation rules: (1) render Agent Lab Feed notebooks as static HTML snapshots (
marimo export html) in<iframe sandbox="allow-scripts" srcDoc={...}>(zero RAM, noallow-same-origin), spinning upmarimo run --session-ttl 300on a separate port/origin only on explicit "Open interactive" click; (2) run yourmarimo edit ./research/notebooks --watch --mcpon a dedicated loopback port (127.0.0.1:2718) with token auth; (3) inject marimo's official agent rules (_dfunderscore-prefixed cell-local variables to free Polars memory immediately) into agent prompts and gate every agent notebook write onmarimo check --format=jsonexit code0.
3. Section 18 Open Questions — Answers & Recommended Defaults
| # | Section 18 Question | Answer from Repo / Data & Recommended Default |
|---|---|---|
| Q1 | Which MongoDB login does routine pipeline work use (studio_stock_bot_read vs trading_admin)? |
[Verified: QA Mongo & repo] studio_stock_bot_read@stock (role: read@stock) already exists in QA MongoDB (phase1-investigation.md:116, verified live). Default: Use studio_stock_bot_read via MONGODB_READ_URI for all data-pipeline runs in dev, qa, and prod (provision an identical read@<db> user on dev 27018/stock_dev and prod). Only data-ingestion ever receives trading_admin / readWrite credentials. Make assertEnvironmentSafety() throw if dataPipeline uses trading_admin. |
| Q2 | How are schema changes applied to existing PostgreSQL volumes? | [Verified: repo] Do not import web-api's migration-runner.ts directly (violates CL26 and fails on \c trading_bot; in 01..05.sql — see Finding F9). Default: Move runMigrations to @stock-bot/postgres, strip \c trading_bot; from 01..05.sql, replace the hardcoded filename allowlist with checksum-verified numbered SQL migrations split into master and research tracks, and run via bun run db:migrate + service startup. |
| Q3 | Is marimo confirmed for the Lab (D9)? | Yes — confirm D9, using static HTML export for the Agent Feed, separate-origin 127.0.0.1:2718 (--watch --mcp) for marimo edit, _-prefixed local variables, and mandatory marimo check gating (see Finding F11). |
| Q4 | Exact storage exit-criteria numbers (Section 5) — confirm or adjust? | Adjust to include row/universe counts and cold vs. warm cache (vague workloads invite cherry-picked benchmarks): • W1 (20y US+CA daily scan + 1 signal IC/quantiles, ~15k active+delisted listings / ~45M bars): < 3 s warm / < 8 s cold (DuckDB+Parquet hits < 2 s on quant).• W2 (1 listing, 1y of 1m regular+extended bars, ~100k–200k rows): < 250 ms warm / < 1 s cold.• W3 (4 concurrent campaign workers): p95 wall-time degradation < 35% vs. 1 worker, zero OOM / lease timeouts.• W4 (1 date cross-section, ~8k alive listings × 20 features): < 100 ms. |
| Q5 | Which FX source for USD/CAD? | [Verified: QA Mongo] Already ingested! Use eodPrices / eodIntraday1M CAD.FOREX (12,109 daily bars 1971–2025 + 5.20M 1m bars) patched post-Aug 2025 by teMarketData (USDCAD, through 2026-04-02), and once IB Gateway is connected in Phase F, ingest live USD.CAD MIDPOINT bars directly from IB + Bank of Canada daily noon/16:30 indicative rates for accounting reconciliation. |
| Q6 | Is ttFutures in scope, and when? |
[Verified: QA Mongo] Out of scope now — defer indefinitely (post-Phase F). ttFutures (1.46M docs) has corrupted date strings ("2001-/0-2/", "NaN-at-e\""), requires continuous contract-roll splicing, point-value multipliers, and initial/maintenance margin semantics orthogonal to US/CA equities. |
| Q7 | Thresholds for lifecycle gates (IC, deflated Sharpe, paper duration, drift bounds)? | Recommended Concrete Defaults ([Assumed] quant calibration for US+CA daily/intraday):• Hypothesis → Signal: Mean rank IC $ |
| Q8 | Which hosts join the worker pool, and when? | [Verified: repo — docs/servers.md + live quant specs] Keep all research, pipeline, QuestDB, Postgres, MongoDB, and worker-pool slots on quant (12900K, 24 threads, 125 GiB RAM, 3.6 TiB NVMe) through Phases 0–E — zero distributed multi-host worker complexity needed! Bring 9900K (8C/16T, 32 GB RAM) online only in Phase F strictly as the isolated Paper + Live IB Gateway host (docs/servers.md:6-17), and use TrueNAS MinIO strictly for cold backups/snapshots. Keep your desktop workstation out of unattended overnight worker pools. |
4. Revised Roadmap (Solo-Developer Critical Path)
Strategy: Thinnest Honest End-to-End Slice First ("Vertical Slice 1" in ~3 Weeks)
Instead of building every dataset, UI screen, QuestDB table, and multi-asset Rust extension before testing your first hypothesis, build one narrow, completely honest vertical slice (US+CA security master → daily bars + corporate actions + Canadian shorts/filings in DuckDB/Parquet → trial ledger + Vault cutoff → Python stockbot SDK + marimo Signal Analyzer). That gets you and desktop Claude Code hunting real cross-sectional & alt-data edges by Week 3, while heavy Rust multi-asset refactoring follows only once you have validated signals worth trading as portfolios.
Explicit Cuts & Deferrals
- Cut the dual-backend QuestDB↔DuckDB parity harness (use DuckDB+Parquet directly for daily/PIT/features; QuestDB
10.2.0for1mintraday). - Cut
eodFundamentalsOLDsnapshots from backtesting and cut macro-release event studies onteData(physically unsupported by the raw data). - Cut
ttFuturesfrom scope. - Defer Pass 5 Merge Review Web UI in Slice 1 — generate a markdown/CSV conflict report + SQL
overrideseed file (~320 exchanges + top symbol conflicts take <2 hours to review in an editor vs. weeks of React CRUD). - Defer a custom Knowledge Base DB/UI — serve
~/repos/studio/catalog/quant/library/library.yml(83 cards) read-only via MCP + onefindingstable in Postgres. - Defer multi-host distributed scheduling (
quant's 24 threads + 125 GiB RAM handle 8–12 local workers on one machine) and defer greenfieldHome&Marketsdashboards until Phase E.
Phased Sequence & Sharp Exit Criteria
| Phase | Scope | Sharp, Falsifiable Exit Criteria |
|---|---|---|
| 0. Safety & Gate Lock (2–3 days) | • Fix workspace.test.ts & lint:check (65 issues), delete 6 stray root files.• Strip \c trading_bot; from database/postgres/init/01..05.sql; extract runMigrations to @stock-bot/postgres.• Block MongoDBClient.getDatabase()/collection() when readOnly: true, delete sync-ib-exchanges.operations.ts, make env-safety.ts throw on non-readonly QA Mongo, default QUEUE_ENABLE_SCHEDULED_JOBS=false.• Rotate & purge hardcoded Webshare proxy credentials ( ib/shared/config.ts:19) + Alpha Vantage key (docs/data-sources.md:15).• Remove /export from sb-research.* (research-agents.service.ts:51) and add cumulative trial budget columns. |
1. All 11 repo gates pass (0 errors, 0 warnings).2. Automated test proves fresh trading_bot_dev (5433) has all master + research tables.3. Integration test proves data-pipeline throws on both client.insertOne() and client.getDatabase().collection().insertOne(), and QA Mongo rejects writes via studio_stock_bot_read.4. Test proves sb-research.* gets 403 on /api/v2/datasets/canonical/:hash/export. |
| 1. Vertical Slice 1: Security Master + Honest Daily/Event Signal Lab (Weeks 1–3) | • Step 1 Merge (US+CA): Instrument-first ISIN/CUSIP + instrument_identifier_history + EOD/QM primary MIC (exclude NMFQS) + IB conid attached at (instrument_id, currency) + bar-span validity windows + 25-date cross-sectional price check + OTC delisting continuation links (SIVB→SIVBQ) + SQL override file.• Step 2 Core ( DuckDB + Parquet): Curate bars_1d (un-adjusting eodPrices.volume!), corporate_actions + adj_factors (qmSplits, qmDividends), fx (CAD.FOREX + teMarketData.USDCAD), qmFilings (timefiled), qmEarnings (lagged when announceTime='N/A'), and ceoShorts (+4bd lag).• MarketDataStore + Vault Air-Gap: VAULT_CUTOFF_DATE = '2025-01-01' hard-enforced on non-vault reads.• Trial Ledger + Python SDK + marimo: Postgres trial_ledger storing (cluster, params, return_vector) + DSR (effective N_hat) + stockbot Python SDK + marimo edit (127.0.0.1:2718). |
1. US+CA match report committed: 100% of ~320 exchange rows reviewed; \ge 95\% of active+delisted US/CA equities resolved with < 0.5% unreviewed high-cap conflicts; FB (2012–2022) and FB (2025 ETF) resolve to distinct listing_ids; SIVB links to SIVBQ terminal loss; NVDA pre-split close * raw_volume matches qmPrices within 1%.2. 20y US+CA daily universe scan + 1 signal IC/quantile/turnover/DSR runs in < 5 s on quant without touching ts >= 2025-01-01.3. Every analyze_signal call writes an immutable trial_ledger row with return vector and increments \hat{N}. |
| 2. MCP Copilot + Intraday QuestDB + PIT Fundamentals (Weeks 4–5) | • MCP Server: Expose search_symbols, query_data (vault-fenced), analyze_signal, event_study, file_finding, read_knowledge (backed by Studio's library.yml + Postgres findings) to Claude Code / Claude Desktop.• PIT Fundamentals: Curate qmFinancials joined to qmFilings timefiled (+ NI 51-102/SEC statutory lag fallback) with 2D (period_end, known_at) deduplication + TTM wide snapshots.• Intraday ( QuestDB 10.2.0): Pin QuestDB Docker tag, replace broken libs/data/questdb, un-adjust eodIntraday1M splits (cross-checked against qmIntraday raw), load bars_1m (listing_id SYMBOL CAPACITY 65536 NOCACHE).• Versioned Feature Library: Batch SQL/Polars feature jobs ( technical, cross_sectional, fundamental, short_interest, event). |
1. Claude Code via MCP runs an end-to-end cross-sectional signal analysis + event study, exports a marimo check-clean static HTML snapshot, and files a finding.2. Restatement regression test proves restated Q1 ( known_at > Q2) never overwrites Q2 in fundamentalsAsOf.3. NEXM.V and NVDA.US 1m vs 1d split-boundary continuity test passes with < 0.5% session-close discrepancy, and 1y of 1m bars for 1 listing loads in < 500 ms. |
| 3. Portfolio Backtest v2 (Tier 1 Screener + Tier 2 Rust Multi-Asset) (Weeks 6–9) | • Tier 1 Columnar Screener: Fast vectorized parameter/universe screener over precomputed features, logging full M_{T \times N} matrix to trial_ledger for PBO & DSR.• Tier 2 Rust financial/ Upgrades: (a) Atomic timestamp-slice mark updates before risk checks (F06 fix); (b) simultaneous sell-proceeds netting in StrategyIntent::Target (matching.rs:1083); (c) features map in Replay + StrategyContext; (d) corporate-action split share adjustment + cash dividend postings + OTC/Shumway delisting liquidation; (e) long/short + borrow cost + multi-currency BTreeMap<Currency, Posting> (USD/CAD via fx); (f) Arrow/Parquet dataset loading into Rust (replacing JSONB snapshots) + remove double JSON parse in api/canonical.rs.• Validation Suite: Purged Walk-Forward, CPCV, DSR, PBO, cost sensitivity, capacity, factor exposure, and one-shot human Vault Holdout gate. Retire legacy BacktestEngine and TS SimulationExecution. |
1. Differential fixtures pass for: atomic long/short mark neutrality, fully-invested Sell A + Buy B target rotation, 10:1 split + cash dividend exact 8-decimal conservation, and SIVB delisting loss.2. Full 20y US+CA cross-sectional daily portfolio backtest ( ~5,000+ listings, weekly/daily rebalance) completes in < 30 s in Tier 2 Rust.3. A surviving signal from Phase 2 passes Screen → Rust Engine → CPCV/DSR/PBO → Human Vault Gate using precomputed features with zero indicator rewrite in TS. |
| 4. Autonomous Campaigns, Studio Bridge & Incremental Web App (Weeks 10–12) | • Containerized campaign runner (quant) with strict per-campaign/daily trial & compute budgets, Roles (Scout, Data Analyst, Signal Researcher, Strategy Builder, Skeptic), and Studio Quant hypothesis → verdict webhook/API bridge.• Web App ( Lab signal/event views + static HTML marimo viewer, Agents feed + wired /research/agents, Data coverage/quality/conflicts, unified charts). |
1. Overnight containerized campaign from a Studio hypothesis runs unattended within budget, cannot reach DB ports or Vault dates, runs Skeptic checks, and posts static-HTML-backed findings to the Lab Feed. 2. Attempting to exceed campaign trial budget halts admission via Postgres trigger. |
5. Paper at Scale → Live IB (9900K) (Weeks 13–16) |
• Fix api/paper.rs O(N) receipt replay via periodic state compaction + tail journal, add MatchingReset, and sandbox promoted candidate code in paper-host (or require explicit built-in compilation).• Deploy headless IB Gateway + IBC + IB Market Data & OMS Bridge on isolated 9900K: idempotent client order IDs, conid + currency + primaryExchange pinning, TSX/TSXV 100/500/1000 board-lot sizing, FXCONV cash conversion, continuous position/cash reconciliation, kill switches, and Dual Drift Monitor (Execution Drift + Feed Basis Drift). |
1. paper-host processes 100,000 sequential quotes with flat < 5 ms p99 latency (proving O(1) compacted state).2. Paper runs 30+ trading days on IB paper account across US ( USD) + TSX (CAD) listings with zero unrecovered reconciliation breaks and Execution Drift < 15 bps/trade.3. Live small-capital deployment passes kill-switch, partial-fill, nightly IB Gateway 21:00 ET reconnect, and FXCONV tests. |
5. Specific Edits to docs/PLATFORM-PLAN.md, by Section
- §1 (Vision and principles, lines 44–52):
- Principle 1: Clarify that where raw providers omit true
known_at(QM/EOD fundamentals, TE macro, CIRO shorts), the pipeline stamps explicit conservative statutory/publication lags and tagsknown_at_sourceso strategies cannot unknowingly trade estimated timestamps at intraday precision. - Principle 2: Clarify that Rust owns all accounting, execution, and portfolio ledger semantics,
libs/calculationsowns canonical performance/statistical formulas, and batch feature jobs own signal/feature values consumed identically by Python, the Tier 1 screener, and Tier 2 Rust strategies.
- Principle 1: Clarify that where raw providers omit true
- §2 (Where the project stands, lines 60, 75, 85, 96–106):
- Line 60: Update October backlog count to 113 done / 5 deferred / 4 merged out of 122 tasks (
docs/development/backlog/README.md). - Line 75: Note hardcoded Webshare proxy credential in
apps/stock/data-ingestion/src/handlers/ib/shared/config.ts:19and Alpha Vantage key indocs/data-sources.md:15to be purged in Phase 0. - Line 85: Fix
lint:checksplit to59 errors + 2 warnings = 61inphase1-inventory.tsand4errors in WIP files (env-safety.ts,builder.ts,mongodb/src/client.ts). - Lines 98–103: Add 31st collection
qmFinancials-old(908k), note existingCAD.FOREX(12.1k1d,5.2M1m) andteMarketData.USDCAD(2.9k1d) FX series, and noteibSymbols.exchangeIdrepresents execution/ATS venues rather than primary listing exchanges.
- Line 60: Update October backlog count to 113 done / 5 deferred / 4 merged out of 122 tasks (
- §3 (Decisions log, lines 123, 131):
- D1: Amend to hybrid curated store behind
MarketDataStore: DuckDB + Parquet for daily bars, corporate actions, PIT fundamentals/events/shorts/macro, and features; QuestDB10.2.0for1m/5m/1hintraday and hot streaming bars; remove the dual-backend parity harness. - D9: Change status from
Proposedto Confirmed, subject to separate-origin isolation, static HTML default in Agent Feed,_-local variable memory rules, andmarimo checkgating.
- D1: Amend to hybrid curated store behind
- §5 (Data architecture and storage, lines 188–253):
- Line 211: Remove the raw-SQL escape hatch for agents (restrict to human localhost sessions over pre-vault read-only views).
- Line 214 (
MarketDataStore): Enforce server-sideVAULT_CUTOFF_DATEceiling on all research/SDK/MCP calls. - Line 226: Specify
listing_idisINT32inMarketDataStore/Parquet andSYMBOL CAPACITY 65536 NOCACHEinside QuestDB. - Line 239: Delete the dual-backend parity harness; replace lines 232–237 with the four quantified workloads in §3 Q4 above.
- Line 245: Add mandatory split un-adjustment of
eodPrices.volumeandeodIntraday1MOHLCV during curation, and keepbars_*single-version with a separatebar_revisionstable. - Line 248: Replace EAV-only
fundamentalswith bitemporal(listing_id, period_end, known_at)deduplication + wide forward-filled PIT + TTM snapshots. - Line 251: Replace "known_at = release date" on
macrowith "lagged publication cutoff (known_at_source = 'statutory_lag_estimate'); final-revised values, restricted to regime filters."
- §6 (Step 1 — Security master, lines 264–351):
- Add
instrument_identifier_history(instrument_id, id_type, id_value, valid_from, valid_to)andcorporate_action_continuity(linking primary delistings to same-ISIN OTC continuations such asSIVB→SIVBQ). - Pass 1 & Pass 3 (lines 285, 300–310): Remove
MICblocking onibSymbols; resolveinstrumentglobally by Luhn-valid ISIN / CUSIP→ISIN, assign primarylisting.micfrom EODExchange+ QMexchange(excludingNMFQSmutual funds from equities), and attach IBconidat(instrument_id, currency). Require overlapping[first_bar_date, last_bar_date]spans on Tier 3/4 ticker matches. - Pass 4 (lines 314–323): Specify cross-sectional 25-date batch extraction (
{ date: { $in: sampleDates } }or DuckDB post-extract) instead of per-pair MongoDB queries. - Pass 6 (line 341): Replace
eodSymbolChange(only 230 rows, 2024–2025 US) with observed provider bar/filing validity spans + corporate actions.
- Add
- §7 (Step 2 — Processing remaining datasets, lines 359–372):
- Update Fundamentals (
qmFinancialsjoined toqmFilings.timefiled+ NI 51-102/SEC lag fallback; quarantineeodFundamentalsOLDsnapshots), Earnings (reportDate 16:05 ETfallback whenannounceTime == 'N/A'), Filings (metadata + timestamps only until Form 4/SEDI XML parser is added — remove "insider transactions extracted where present"), Shorts (+4business-day CIRO publication lag), Macro (lagged regime-only), Futures (explicitly out of scope), and FX (CAD.FOREX+teMarketData.USDCADalready present).
- Update Fundamentals (
- §8 & §9 (Feature library & Backtesting, lines 391–458):
- §8: Specify features are materialized by versioned DuckDB/Polars batch jobs and passed into Tier 2 Rust
Replay+StrategyContextvia a newfeaturesmap so Python, Tier 1, and Tier 2 read identical values without rewriting indicators in zero-import TS. - §9 line 418: Remove "Reopens deferred task P06" (document Tier 1 as a net-new columnar screener; reopen
D04andP03instead). - §9 Tier 2: Add atomic timestamp-slice marking (
F06fix), simultaneous sell-proceeds netting onTargetrebalances, OTC/Shumway delisting liquidation, and Arrow/Parquet dataset loading (replacing PostgresJSONBdataset snapshots for multi-asset runs). - §9 Validation & Trial ledger: Define relatedness clusters by
(universe_market, horizon_bucket), store return/IC vectors to compute effective\hat{N}for DSR + synchronous matrices for PBO, add nonzeropurge/embargoto Walk-Forward & CPCV, and split unattended Research Validation from the human-only one-shot Vault Holdout.
- §8: Specify features are materialized by versioned DuckDB/Polars batch jobs and passed into Tier 2 Rust
- §11 & §12 (Playground & Agents, lines 507–597):
- §11: Enforce marimo separate-origin / static HTML snapshot rules and
marimo checkpre-validation. - §12: Reuse
~/repos/studio/catalog/quant/library/library.ymlread-only for methodology/literature cards; isolate campaign agents in no-DB-network containers; enforce cumulative trial/compute budgets in PostgreSQL triggers.
- §11: Enforce marimo separate-origin / static HTML snapshot rules and
- §13 (Execution: paper to live on IB, lines 600–615):
- Add
paper.rscheckpoint compaction (fixingO(N)genesis receipt replay),MatchingResetNAPI support,IB Gateway + IBC5s/quote bridge on9900K,conid + currency + primaryExchangecontract pinning,FXCONV(notIDEALPRO) vs. IB Margin negative-cash borrow modeling, TSX/TSXV100/500/1000board-lot sizing, and split Drift Monitoring into Execution Drift vs. Feed Basis Drift.
- Add
- §14, §16, §17 (App, Roadmap, Immediate next steps):
- §14: Note
dashboardis empty (0files), wire existing/research/agentsintoSidebar.tsx, and unify the twolightweight-chartswrappers. - §16 & §17: Adopt the 6-phase vertical-slice roadmap and expanded Phase 0 checklist in §4 above.
- §14: Note
6. Resolved Owner Decisions (2026-11-26)
-
IBKR Account Type & Currency Policy — RESOLVED:
IBKR Margin account (USD+CAD), plus spot FX tradable as an alpha asset class if edge is found.- Design impact: Rust
Ledgermodels per-currency cash/margin balances (BTreeMap<Currency, Posting>) with daily IBKR benchmark+spread interest on negative currency balances, usesexchange="FXCONV"for cash-funding sweeps (no virtual position), and supportsIDEALPRO/CAD.FOREXas first-class tradable FX instruments when a strategy explicitly takes FX exposure.
- Design impact: Rust
-
Vault Holdout vs. Recent-Regime Decay — RESOLVED:
No switch in v1; use a short rolling6-monthVault (today - 6m, or final 6 months of ingested data until ingestion catches up to present) + a mandatory Post-2023 Recency Gate.- Design impact: Keeps 2023–2025 AI/higher-rate regime data inside Zone 1 so dead pre-LLM signals get filtered out during walk-forward, while still reserving ~126 unseen trading days to catch agent p-hacking before Paper. A
full_historyswitch (vault_touched = true) can be added later only if needed.
- Design impact: Keeps 2023–2025 AI/higher-rate regime data inside Zone 1 so dead pre-LLM signals get filtered out during walk-forward, while still reserving ~126 unseen trading days to catch agent p-hacking before Paper. A
-
Storage Split (Amending D1) — RESOLVED:
Confirmed Parquet + DuckDB from Day 1 for daily bars, corporate actions, PIT fundamentals/events/shorts/macro, and features; QuestDB10.2.0reserved for1m/5m/1hintraday and hot live/paper bars; dual-backend parity harness cut. -
v1 Data Scope (
teData&qmFilings) — RESOLVED:
Confirmed lean v1:teDatarestricted to lagged regime filters andqmFilingsused for exacttimefiledtimestamps + form-type event counts; ALFRED macro vintages and Form 4 XML / SEDI insider transaction parsing deferred to Phase 2+. -
Live IB Intraday Symbol Cap — RESOLVED:
Confirmed\le 50\text{–}80active streaming symbols at a time (within IBKR's standard 100 market-data line limit, no paid quote boosters required initially).