renames docs
This commit is contained in:
parent
4cd6038063
commit
13eb8352f3
25 changed files with 0 additions and 0 deletions
250
design/DATA-CONTRACTS.md
Normal file
250
design/DATA-CONTRACTS.md
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
# Stock Bot — Data, Security Master & Storage Contracts
|
||||
|
||||
Authoritative specification for `data-pipeline`, PostgreSQL reference schemas, DuckDB/Parquet + QuestDB `10.2.0` curated tables, and `MarketDataStore`. Every rule below was verified against live QA MongoDB (`stock`, 31 collections) on 2026-11-26.
|
||||
|
||||
---
|
||||
|
||||
## 1. Empirical Provider Rules & Traps (QA MongoDB `stock`)
|
||||
|
||||
`data-pipeline` connects strictly read-only via `MONGODB_READ_URI` (`studio_stock_bot_read@stock`). Never trust raw field names without applying the provider-specific transformations below:
|
||||
|
||||
| Collection (Docs) | Verified Empirical Behavior | Mandatory `data-pipeline` Rule |
|
||||
| --- | --- | --- |
|
||||
| `eodPrices` (`845.7M`) | `open/high/low/close` are **raw**, **but `volume` is retroactively split-adjusted** (`NVDA` pre-10:1 split `2024-06-07` has `close=1208.88`, `volume=412.39M` = $10\times$ raw; `X.TO` pre-5:1 split has $5\times$ raw volume). Indexes: `{date:1, eodSearchCode:1}` and `{eodSearchCode:1}` (no `{eodSearchCode:1, date:1}`). | Divide historical `volume` by cumulative post-bar split factor so `close * raw_volume` equals true dollar volume; cross-check against `qmPrices.sharevolume`. Query cross-sectional slices by `date` first when scanning MongoDB. |
|
||||
| `qmPrices` (`51.5M`) | `unadjustedopen..unadjustedclose` and `sharevolume` are **genuinely raw** (both price and share count). Index: `{qmSearchCode:1, date:1}`. | Use as primary raw-volume truth and cross-check partner for `eodPrices`. |
|
||||
| `eodIntraday1M` (`3.40B`) | **OHLCV is ALREADY retroactively split-adjusted** (`NEXM.V` pre-1:20 reverse split on `2025-06-18` reports `close=24.29` instead of raw `~1.21`). Covers US deeply back to Dec 2003; sparse/empty on many TSX tickers (`SHOP.TO` has `0` rows). | Un-adjust pre-split OHLCV using cumulative split factors before writing raw `bars_1m` (or never re-apply `adj_factors` on top without un-adjusting first!). Verify `1m` session close vs raw `bars_1d.close`. |
|
||||
| `qmIntraday` (`173.3M`) | Stores **both** raw (`open..close`, `sharevolume`) and adjusted (`adjustedopen..adjustedclose`, `avolume`). Covers TSX/CA (`SHOP:CA`, `X:CA`) from ~May 2024 onward. | Primary `1m` intraday source for Canadian listings where `eodIntraday1M` is empty, and split-calibration truth for overlapping symbols. |
|
||||
| `eodSymbols` (`317.8k`) | `103.8k` rows have composite `eodExchange="US"`, of which **`44,970` (`43.3%`) have `Exchange="NMFQS"` (mutual funds)**, `18,114` `PINK`, `15,858` `NASDAQ`, `9,879` `NYSE`. `52,745` US + `3,136` CA rows have `delisted=true`. EOD retroactively renames changed tickers (`META.US` holds 2012–2022 Facebook; `FB.US` is now a 2025 ProShares ETF) and overwrote pre-bankruptcy `GM.US` (`starts 2010-11-18`) and `HTZ.US` (`starts 2021-07-01`). | Resolve US MIC from `eodSymbols.Exchange` (not `eodExchange="US"`); exclude `NMFQS` from equity universes; never assume `Code.US` is a single historical company without checking bar spans and `qmFilings`. |
|
||||
| `ibSymbols` (`18,402`) | Fields use **`exchangeId`** and **`description`** (which legacy `provider-symbol.ts` ignored). `100%` ISIN/CUSIP/`conid`, **but `exchangeId` is an execution/ATS venue, NOT primary listing MIC**: CA has `AEQLIT=2,506` (`65%`) vs `TSE=514`; US has `OTCLNKECN=6,627`, `ARCAEDGE=1,067`, `BEX=777`, `DRCTEDGE=682`, `IEX=509` vs **`NYSE=370` (`2.5%`) and `NASDAQ=241` (`1.7%`)**! Contains placeholder/checksum-bad ISINs (`CATSETEST001`, `CA00149WBAD4`, `CA8131391062` for `SCU.UN`). | **Never block `ibSymbols` on MIC.** Validate ISIN Luhn check digit (derive `US`/`CA` + CUSIP + check digit when ISIN checksum fails on a valid 9-char CUSIP), match globally to `instrument`, and attach `conid` to `listing` by `(instrument_id, currency)`. |
|
||||
| `qmSymbols` (`47,243`) | `0%` ISIN/CUSIP; `15,790` US + `3,626` CA rows have `active=false`. Contains duplicate `(symbol, exchange)` pairs on CSE (`VOY:CNX` active + `VOY:CC` inactive). | Disambiguate via `active` flag, `qmSearchCode`, and observed `[first_bar_date, last_bar_date]` overlap. |
|
||||
| `ceoSymbols` (`12,589`), `ceoPosts` (`14.78M`), `ceoShorts` (`692.9k`) | 100% Canadian (`CNQ=4,583`, `TSX=4,127`, `CDX=3,292`, `AQL=587`). `ceoSymbols.symbol` embeds `.TO`/`.V` suffixes. `ceoPosts` has `1.8%` edited posts (`edited != null` mutates `spiel`) and `bot="1"` (`@thenewswire`). `ceoShorts.timestamp` is the 15th / month-end **report period date**, NOT CIRO dissemination date. | Map `TSX→XTSE`, `CDX→XTSX`, `CNQ→XCNQ`, `AQL→NEOE`; strip embedded `.TO`/`.V`; separate `bot="1"` posts and set text `known_at = COALESCE(edited, timestamp)`; set `ceoShorts` `known_at = timestamp + 4 Canadian business days (17:00 ET)`. |
|
||||
| `qmFinancials` (`1.86M`), `qmFinancials-old` (`908k`) | Standardized `BalanceSheet`, `CashFlow`, `IncomeStatement`, `periodEndDate`, `reportDate` — **`0%` `filingDate` and `0` restatement versions** (overwritten in place). | Derive `known_at` by joining `(listing_id, periodEndDate)` to `qmFilings.timefiled`; where unlinked, add statutory deadline lag (`+45d Q / +90d FY` US & TSX; `+60d Q / +120d FY` TSXV/CSE) with `known_at_source = 'statutory_lag_estimate'`. |
|
||||
| `eodFinancialsOLD` (`2.98M`), `eodFundamentalsOLD` (`106.6k`) | `eodFinancialsOLD` sets `filingDate == reportDate` on **`99.26%`** of rows. `eodFundamentalsOLD` has `filing_date: null`, unversioned current valuation ratios, and mislabels USD figures as `"CAD"` on NEO CDRs (`AAPL` CDR `$335B` assets). | **Quarantine `eodFundamentalsOLD` `Highlights`/`Valuation` from all backtests.** Use `eodFinancialsOLD` only for pre-QM historical backfill with mandatory statutory lag (ignoring its `filingDate`). |
|
||||
| `qmFilings` (`30.52M`) | Has exact second-level `timefiled` (`"2025-01-31T06:01:27 EST"`) for both US EDGAR (`10-Q`, `10-K`, `8-K`, `4`, `144`) and **Canadian SEDAR+** (`Interim financial statements/report`, `Annual financial statements`, `MD&A`, `52-109`, `NI 43-101`, `45-106F1`). Metadata + external download URLs only (no parsed Form 4 share counts). | Primary `known_at` clock for `qmFinancials` and `qmEarnings`, plus standalone filing-arrival/form-type event stream. Convert `EST`/`EDT` strings cleanly using `America/New_York` rules. |
|
||||
| `qmEarnings` (`444.9k`) | `66.94%` (`297,779`) have `announceTime="N/A"` (`80,481` `AMC`, `66,605` `BTO`); `consensusEps` is overwritten post-hoc. | Link to same-day `qmFilings` `8-K` / `News release` `timefiled`; if still unknown, set `known_at = reportDate 16:05 ET` (tradable `T+1` open). |
|
||||
| `qmDividends` (`495.9k`), `qmSplits` (`18.8k`), `eodSymbolChange` (`230`) | `qmDividends`: `82.3%` have `declared < date`, bogus `usdFxRate: 1` on CAD rows. `qmSplits`: `30.1%` have `declared`, `258` have `splitratio == 1`. `eodSymbolChange`: only `230` US rows (`2024-08..2025-07`). | Filter `splitratio == 1`; ignore `usdFxRate`; never rely on `eodSymbolChange` for multi-year ticker history. |
|
||||
| `teData` (`14.8k`), `teMarketData` (`435`), `CAD.FOREX` | `teData` has `{d, v}` final-revised values only (no release dates/vintages). `CAD.FOREX` (`eodPrices` `12,109` 1d, `eodIntraday1M` `5.20M` 1m) + `teMarketData.USDCAD` (`2,865` 1d through Apr 2026) already provide complete USD/CAD history. | Lag `teData` (`+1d` central-bank rates, `+35d` monthly CPI/NFP, `+65d/+90d` GDP) for coarse regime filters only. Curate `CAD.FOREX` + `teMarketData.USDCAD` directly into `fx_1d` and `fx_1m`. |
|
||||
|
||||
---
|
||||
|
||||
## 2. Security Master Schema (PostgreSQL)
|
||||
|
||||
Applied via `@stock-bot/postgres` (`master` migration track; no `\c` meta-commands):
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS exchange (
|
||||
mic VARCHAR(10) PRIMARY KEY, -- ISO 10383 (e.g. XNYS, XNAS, XTSE, XTSX, XCNQ, NEOE, OTCM)
|
||||
operating_mic VARCHAR(10) NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
country_iso CHAR(2) NOT NULL,
|
||||
currency CHAR(3) NOT NULL,
|
||||
timezone TEXT NOT NULL, -- e.g. 'America/New_York', 'America/Toronto'
|
||||
calendar_code VARCHAR(16) NOT NULL,
|
||||
board_lot_policy VARCHAR(16) NOT NULL DEFAULT 'us_100', -- 'us_100' | 'tsx_tiered' | 'fx'
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS exchange_source_map (
|
||||
source VARCHAR(16) NOT NULL, -- 'eod' | 'qm' | 'ib' | 'ceo'
|
||||
source_code VARCHAR(32) NOT NULL,
|
||||
role VARCHAR(20) NOT NULL, -- 'primary_venue' | 'composite' | 'ats_routing' | 'forex' | 'excluded_fund'
|
||||
mic VARCHAR(10) REFERENCES exchange(mic),
|
||||
country_iso CHAR(2),
|
||||
method VARCHAR(32) NOT NULL,
|
||||
reviewed_by TEXT,
|
||||
PRIMARY KEY (source, source_code)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS instrument (
|
||||
instrument_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
primary_isin CHAR(12) UNIQUE,
|
||||
primary_cusip CHAR(9),
|
||||
canonical_name TEXT NOT NULL,
|
||||
security_type VARCHAR(16) NOT NULL, -- 'common'|'preferred'|'unit'|'warrant'|'right'|'etf'|'cdr'|'fx'
|
||||
issuer_country CHAR(2),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS instrument_identifier_history (
|
||||
instrument_id INTEGER NOT NULL REFERENCES instrument(instrument_id),
|
||||
id_type VARCHAR(8) NOT NULL, -- 'ISIN' | 'CUSIP'
|
||||
id_value VARCHAR(16) NOT NULL,
|
||||
valid_from DATE,
|
||||
valid_to DATE,
|
||||
source VARCHAR(16) NOT NULL,
|
||||
PRIMARY KEY (id_type, id_value, valid_from)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS listing (
|
||||
listing_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
instrument_id INTEGER NOT NULL REFERENCES instrument(instrument_id),
|
||||
mic VARCHAR(10) NOT NULL REFERENCES exchange(mic),
|
||||
ticker_root VARCHAR(24) NOT NULL,
|
||||
class_suffix VARCHAR(12) NOT NULL DEFAULT '',
|
||||
currency CHAR(3) NOT NULL,
|
||||
ib_conid BIGINT,
|
||||
ib_primary_exchange VARCHAR(16), -- e.g. 'NYSE', 'NASDAQ', 'TSE', 'VENTURE'
|
||||
listed_from DATE,
|
||||
listed_to DATE,
|
||||
delist_reason VARCHAR(24), -- 'active'|'merger_cash'|'moved_to_otc'|'bankruptcy_cancelled'|'unknown_ involuntary'
|
||||
terminal_return NUMERIC(10, 6), -- e.g. -0.300000 or -1.000000 when no post-delist OTC bar exists
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS corporate_action_continuity (
|
||||
from_listing_id INTEGER NOT NULL REFERENCES listing(listing_id),
|
||||
to_listing_id INTEGER NOT NULL REFERENCES listing(listing_id),
|
||||
effective_date DATE NOT NULL,
|
||||
kind VARCHAR(24) NOT NULL, -- 'otc_delist_transfer' | 'venue_uplisting' | 'reorg_continuation'
|
||||
PRIMARY KEY (from_listing_id, effective_date)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS listing_symbol_history (
|
||||
listing_id INTEGER NOT NULL REFERENCES listing(listing_id),
|
||||
ticker VARCHAR(32) NOT NULL,
|
||||
valid_from DATE NOT NULL,
|
||||
valid_to DATE,
|
||||
source VARCHAR(16) NOT NULL,
|
||||
PRIMARY KEY (listing_id, ticker, valid_from)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS provider_mapping (
|
||||
source VARCHAR(16) NOT NULL,
|
||||
source_id VARCHAR(64) NOT NULL, -- eodSearchCode, qmSearchCode, ib conid/id, ceoId
|
||||
valid_from DATE NOT NULL DEFAULT '1900-01-01',
|
||||
valid_to DATE,
|
||||
listing_id INTEGER NOT NULL REFERENCES listing(listing_id),
|
||||
method VARCHAR(24) NOT NULL, -- 'tier1_isin'|'tier2_cusip'|'tier3_ticker_span'|'tier4_name'|'override'
|
||||
confidence NUMERIC(4, 3) NOT NULL,
|
||||
price_corr NUMERIC(5, 4),
|
||||
PRIMARY KEY (source, source_id, valid_from)
|
||||
);
|
||||
```
|
||||
|
||||
Plus `resolution_conflict`, `override` (keyed by `(source, source_id, valid_from)` and applied last with precedence `1.000`), and `golden_field_audit`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Curated Storage Schemas
|
||||
|
||||
### A. DuckDB + Hive Parquet (`/mnt/data/stockbot/curated/`)
|
||||
|
||||
All Parquet files use `ZSTD` compression, integer `listing_id` (`INT32`), UTC `TIMESTAMPTZ` (`ts`, `known_at`), and explicit `known_at_source`.
|
||||
|
||||
- **Bulk ETL rule (`tools/curate-etl`):** Multi-hundred-million and multi-billion-row collections (`eodPrices` `846M`, `eodIntraday1M` `3.40B`, `eodIntraday5M` `1.08B`, `qmFilings` `30.5M`) are curated via a dedicated Rust binary in the Cargo workspace (`mongodb::bson::RawDocumentBuf` zero-copy BSON cursors + in-RAM `provider_mapping`/`qmSplits` lookup tables + `rayon` sharded `parquet`/ILP writers)—**never** through single-threaded JS/Node object-allocation loops.
|
||||
- **DuckDB connection budget:** Every `MarketDataStore` (TS) and `stockbot.data` (Python) DuckDB instance must execute at connection open:
|
||||
```sql
|
||||
SET memory_limit = '6GB';
|
||||
SET threads = 4;
|
||||
SET temp_directory = '/mnt/data/stockbot/tmp/duckdb';
|
||||
```
|
||||
(overridable via env on local dev, e.g. `2GB`/`2` threads) so concurrent campaign workers never inherit DuckDB's default `80%` host-RAM (`~100 GiB`) ceiling.
|
||||
|
||||
Schemas:
|
||||
|
||||
- **`bars_1d/year=YYYY/part.parquet`**: `(listing_id INT32, ts TIMESTAMPTZ, session_date DATE, open DOUBLE, high DOUBLE, low DOUBLE, close DOUBLE, volume DOUBLE, vwap DOUBLE, currency VARCHAR, source VARCHAR, known_at TIMESTAMPTZ)` — strictly raw OHLC and **un-adjusted** share `volume`, sorted by `(listing_id, session_date)`.
|
||||
- **`adj_factors/part.parquet`**: `(listing_id INT32, ex_date DATE, split_factor DOUBLE, div_cash DOUBLE, div_currency VARCHAR, cum_split_factor DOUBLE, cum_total_factor DOUBLE, known_at TIMESTAMPTZ)`.
|
||||
- **`corporate_actions/part.parquet`**: `(listing_id INT32, ex_date DATE, declared_date DATE, kind VARCHAR, ratio DOUBLE, cash_amount DOUBLE, currency VARCHAR, successor_listing_id INT32, terminal_return DOUBLE, known_at TIMESTAMPTZ, known_at_source VARCHAR)`.
|
||||
- **`fundamentals_bitemporal/part.parquet`**: `(listing_id INT32, period_end DATE, fiscal_period VARCHAR, currency VARCHAR, known_at TIMESTAMPTZ, known_at_source VARCHAR, <standardized statement columns...>)`.
|
||||
- **`fundamentals_pit/year=YYYY/part.parquet`**: Wide pre-resolved point-in-time snapshots keyed by `(listing_id INT32, effective_known_at TIMESTAMPTZ)` where each row computes:
|
||||
$$\text{latest } k \text{ periods by } \texttt{period\_end} \text{ of } \left(\arg\max_{\texttt{known\_at} \le \texttt{effective\_known\_at}} \text{ per } (\texttt{listing\_id}, \texttt{period\_end})\right)$$
|
||||
forward-filling un-restated fields and precomputing 4-quarter TTM sums so a restatement of Q1 never overwrites Q2.
|
||||
- **`events/year=YYYY/part.parquet`**: `(listing_id INT32, ts TIMESTAMPTZ, known_at TIMESTAMPTZ, known_at_source VARCHAR, kind VARCHAR, subtype VARCHAR, payload_json VARCHAR)`.
|
||||
- **`shorts/part.parquet`**: `(listing_id INT32, report_date DATE, known_at TIMESTAMPTZ, shares_short DOUBLE, net_change DOUBLE, pct_float DOUBLE, source VARCHAR)`.
|
||||
- **`macro/part.parquet`**: `(country_iso VARCHAR, indicator VARCHAR, period_date DATE, known_at TIMESTAMPTZ, known_at_source VARCHAR, value DOUBLE)`.
|
||||
- **`fx_1d/part.parquet`**: `(pair VARCHAR, session_date DATE, ts TIMESTAMPTZ, open DOUBLE, high DOUBLE, low DOUBLE, close DOUBLE, source VARCHAR, known_at TIMESTAMPTZ)`.
|
||||
- **`features/<feature_name>/v<version>/year=YYYY/part.parquet`**: `(listing_id INT32, ts TIMESTAMPTZ, known_at TIMESTAMPTZ, value DOUBLE)`.
|
||||
|
||||
### B. QuestDB `10.2.0` (Intraday & Live Streaming)
|
||||
|
||||
Image pinned to `questdb/questdb:10.2.0`. Host kernel must enforce `vm.max_map_count >= 1048576` (`/etc/sysctl.d/99-stockbot.conf`), container `ulimits.nofile` set to `1048576`, and off-heap memory bounded via `QDB_RAM_USAGE_LIMIT_BYTES=21474836480` (`20 GiB`) + JVM `-Xms2g -Xmx4g` inside a `28g` container `mem_limit` on `quant`.
|
||||
|
||||
`listing_id` is stored as decimal string inside `SYMBOL CAPACITY 65536 NOCACHE` and converted to `number` (`INT32`) at the `MarketDataStore` adapter boundary. `bars_1m` uses **`PARTITION BY MONTH`** (`270` partitions / `~3,780` files across 22.5 years at `~13.2M` rows/month, vs. `~5,670` partitions / `~79,000` files under `PARTITION BY DAY`—cutting 1-year `W2` cold partition seeks from 252 to 12 while keeping live monthly WAL `< 40 MB`):
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS bars_1m (
|
||||
listing_id SYMBOL CAPACITY 65536 NOCACHE,
|
||||
open DOUBLE,
|
||||
high DOUBLE,
|
||||
low DOUBLE,
|
||||
close DOUBLE,
|
||||
volume DOUBLE,
|
||||
vwap DOUBLE,
|
||||
session SYMBOL CAPACITY 8 CACHE, -- 'PRE' | 'RTH' | 'POST'
|
||||
source SYMBOL CAPACITY 8 CACHE, -- 'eod_unadj' | 'qm_raw' | 'ib_live'
|
||||
known_at TIMESTAMP,
|
||||
ts TIMESTAMP
|
||||
) TIMESTAMP(ts) PARTITION BY MONTH WAL
|
||||
DEDUP UPSERT KEYS(ts, listing_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS fx_1m (
|
||||
pair SYMBOL CAPACITY 32 CACHE, -- 'USD.CAD'
|
||||
open DOUBLE,
|
||||
high DOUBLE,
|
||||
low DOUBLE,
|
||||
close DOUBLE,
|
||||
source SYMBOL CAPACITY 8 CACHE,
|
||||
ts TIMESTAMP
|
||||
) TIMESTAMP(ts) PARTITION BY MONTH WAL
|
||||
DEDUP UPSERT KEYS(ts, pair);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS bar_revisions (
|
||||
listing_id SYMBOL CAPACITY 65536 NOCACHE,
|
||||
timeframe SYMBOL CAPACITY 8 CACHE,
|
||||
bar_ts TIMESTAMP,
|
||||
prev_close DOUBLE,
|
||||
new_close DOUBLE,
|
||||
prev_volume DOUBLE,
|
||||
new_volume DOUBLE,
|
||||
revised_at TIMESTAMP
|
||||
) TIMESTAMP(revised_at) PARTITION BY MONTH WAL;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. `MarketDataStore` Contract
|
||||
|
||||
```ts
|
||||
export type DataScope = 'vault_fenced' | 'vault_evaluation_only';
|
||||
|
||||
export interface MarketDataStore {
|
||||
bars(q: {
|
||||
listingIds: number[];
|
||||
timeframe: '1m' | '5m' | '1h' | '1d';
|
||||
from: string;
|
||||
to: string;
|
||||
adjustment: 'raw' | 'split' | 'total';
|
||||
asOf?: string;
|
||||
scope?: DataScope; // defaults to 'vault_fenced'; 'vault_evaluation_only' requires human operator Vault token
|
||||
}): AsyncIterable<BarBatch>;
|
||||
|
||||
crossSection(q: {
|
||||
features: string[]; // versioned refs, e.g. 'rsi_14@v1'
|
||||
date: string;
|
||||
universe: UniverseRef;
|
||||
asOf?: string;
|
||||
}): Promise<Table>;
|
||||
|
||||
fundamentalsAsOf(q: {
|
||||
listingIds: number[];
|
||||
fields: string[];
|
||||
asOf: string;
|
||||
allowEstimatedLag?: boolean; // default true for daily/swing, false for intraday event triggers
|
||||
}): Promise<Table>;
|
||||
|
||||
events(q: {
|
||||
kinds: EventKind[];
|
||||
listingIds?: number[];
|
||||
from: string;
|
||||
to: string;
|
||||
asOf?: string;
|
||||
}): Promise<Table>;
|
||||
|
||||
shortsAsOf(q: { listingIds: number[]; from: string; to: string; asOf?: string }): Promise<Table>;
|
||||
macroAsOf(q: { countries: string[]; indicators: string[]; from: string; to: string; asOf?: string }): Promise<Table>;
|
||||
fx(q: { pair: 'USD.CAD'; timeframe: '1m' | '1d'; from: string; to: string }): Promise<Table>;
|
||||
universe(q: { ref: UniverseRef; date: string }): Promise<number[]>; // survivorship-free active listings on date
|
||||
}
|
||||
```
|
||||
|
||||
**Hard adapter invariant:** When `scope !== 'vault_evaluation_only'`, the adapter clamps `to` and `asOf` to `< VAULT_CUTOFF_TS` (rejecting requests with `from >= VAULT_CUTOFF_TS` with `VaultHoldoutFenceError`).
|
||||
169
design/MILESTONES.md
Normal file
169
design/MILESTONES.md
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
# 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](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 `GET`s.
|
||||
|
||||
---
|
||||
|
||||
## M1 — Vertical Slice 1: Security Master + Honest Daily/Event Signal Lab *(Weeks 1–3)*
|
||||
|
||||
**Goal:** Resolve US + Canadian equities into permanent `listing_id`s, 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](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](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_id`s; `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.
|
||||
377
design/PLATFORM-PLAN.md
Normal file
377
design/PLATFORM-PLAN.md
Normal file
|
|
@ -0,0 +1,377 @@
|
|||
# Stock Bot — AI Algo Research Platform Plan
|
||||
|
||||
As of 2026-11-26 (revised post-audit). Owner: Boki.
|
||||
|
||||
Stock Bot becomes a personal **edge factory**: ideas go in, AI agents test them at scale on honest point-in-time data, you explore alongside them, and survivors move through paper trading to live trading on Interactive Brokers — then get monitored until their edge decays.
|
||||
|
||||
Companion specs:
|
||||
- **[MILESTONES.md](MILESTONES.md)** — executable milestone checklist (`M0` → `M5`), scope cuts, and exit criteria.
|
||||
- **[DATA-CONTRACTS.md](DATA-CONTRACTS.md)** — raw provider quirks, security-master DDL, `known_at` rules, and Parquet/QuestDB schemas.
|
||||
- **[VALIDATION-AND-RIGOR.md](VALIDATION-AND-RIGOR.md)** — canonical metrics, trial ledger ($\hat{N}$ DSR & PBO), 6-month Vault, recency gate, and IB/TSX execution rules.
|
||||
|
||||
---
|
||||
|
||||
## Contents
|
||||
|
||||
1. [Vision and principles](#1-vision-and-principles)
|
||||
2. [Where the project stands](#2-where-the-project-stands)
|
||||
3. [Decisions log](#3-decisions-log)
|
||||
4. [System architecture](#4-system-architecture)
|
||||
5. [Data architecture and storage](#5-data-architecture-and-storage)
|
||||
6. [Step 1 — Cross-source merge (security master)](#6-step-1--cross-source-merge-security-master)
|
||||
7. [Step 2 — Processing the remaining datasets](#7-step-2--processing-the-remaining-datasets)
|
||||
8. [Feature library](#8-feature-library)
|
||||
9. [Backtesting](#9-backtesting)
|
||||
10. [Orchestration](#10-orchestration)
|
||||
11. [Research and analytics playground](#11-research-and-analytics-playground)
|
||||
12. [Agent layer](#12-agent-layer)
|
||||
13. [Execution: paper to live on IB](#13-execution-paper-to-live-on-ib)
|
||||
14. [The app](#14-the-app)
|
||||
15. [Strategy lifecycle](#15-strategy-lifecycle)
|
||||
16. [Roadmap](#16-roadmap)
|
||||
|
||||
---
|
||||
|
||||
## 1. Vision and principles
|
||||
|
||||
The real product is **trustworthy evidence produced fast**. Most retail algo work fails because results look good and are not real. The edge comes from:
|
||||
|
||||
- **Rigor at scale** — agents can run thousands of tests; the platform makes sure the statistics account for that and penalize pre-LLM regime decay.
|
||||
- **Data few others combine** — 14.8M CEO.ca posts, 30.5M US/Canadian filings with second-level timestamps, 693k CIRO short records, fundamentals, dividends, splits, earnings, 54 years of USD/CAD (`5.2M` 1m bars), and `3.4B` 1m bars across US and Canadian markets.
|
||||
- **Capacity-constrained niches** — Canadian small/mid-caps (`TSX`/`TSXV`/`CSE`), cross-border US/CA interlisted pairs, and filing/short/retail-flow events where institutional AI pods cannot deploy size.
|
||||
- **Research speed** — "is there something here?" answered in seconds over Parquet + DuckDB, before writing a line of strategy code.
|
||||
- **Execution quality** — one Rust financial kernel for portfolio backtest, paper, and live IB execution, paired with dual drift monitoring.
|
||||
|
||||
Ideas come from two places: you, and the Quant profile in Studio (`~/repos/studio`). Agents test them. You research alongside them. Everything that can give an edge is in scope: intraday, swing/daily, cross-sectional equity portfolios, FX, and event/alt-data strategies.
|
||||
|
||||
### Design principles
|
||||
|
||||
1. **Point-in-time everything — with honest provenance.** Every query answers "as known at time T": universe membership, prices, fundamentals, events. Where raw vendors omit true availability timestamps, the pipeline applies conservative statutory/publication lags and tags `known_at_source` (`filing_timestamp` vs `statutory_lag_estimate`) so strategies never unknowingly trade estimated timestamps at intraday precision.
|
||||
2. **Single source of truth per calculation.**
|
||||
- **Rust (`apps/stock/engine/src/financial`)** owns all accounting, cash/margin, corporate actions, fills, risk, and replay.
|
||||
- **`@stock-bot/calculations`** owns canonical return/drawdown/Sharpe/DSR/PBO statistics served by the Research Kernel API.
|
||||
- **Batch feature jobs** compute versioned features once; Python notebooks, the Tier 1 screener, and Tier 2 TypeScript/Rust strategies all consume the exact same materialized feature values.
|
||||
3. **Signal-first, not strategy-first.** Research starts with "does this signal predict anything?" Strategies are built only on signals that survived cost, regime, and recency checks.
|
||||
4. **Every trial counts.** An immutable trial ledger records every signal analysis, screen, and backtest with its return/IC vector. Significance is adjusted for effective independent trials $\hat{N}$ (Deflated Sharpe Ratio) and Combinatorial Symmetric Cross-Validation (PBO), backed by a rolling **6-month Air-Gapped Vault** and a **Post-2023 Recency Gate**.
|
||||
5. **Agents and you use the same tools.** One Research Kernel API, one MCP surface, one Python SDK. Autonomous campaign agents run in network-isolated containers with no host shell or direct DB port access.
|
||||
6. **Rigor lives in the engine, not the UX.** Keep receipts, fencing, and provenance underneath. Make the surface fast and playful.
|
||||
7. **Raw stays raw.** MongoDB is the provider landing zone. Only `data-pipeline` reads it via `MONGODB_READ_URI` (`studio_stock_bot_read`).
|
||||
8. **Stable identity.** Everything downstream keys on permanent integer `listing_id` (or ISO country / currency pair), never on mutable tickers.
|
||||
|
||||
---
|
||||
|
||||
## 2. Where the project stands
|
||||
|
||||
The October engineering backlog closed at **113 done / 5 deferred (`D04`, `P03`, `P05`, `P06`, `CL21`) / 4 merged = 122 retained tasks**, delivering:
|
||||
|
||||
- the canonical fixed-decimal Rust financial kernel (`Ledger`, `RiskAccount`, `MatchingAccount`, `Replay`);
|
||||
- canonical single-asset research with 3-phase chronological validation, walk-forward, and cost sensitivity;
|
||||
- an isolated Linux Docker + seccomp + Rust PID1 guardian sandbox for agent-written TypeScript (`A02`);
|
||||
- scoped `sb-research.*` agent credentials (`A01`) and a typed `ResearchClient`;
|
||||
- a 1/2/4-slot worker pool and human-reviewed paper deployments;
|
||||
- full `quant` server deployment (`12900K`, 24 threads, 125 GiB RAM, 4 TB WD Black SN850X NVMe at `/mnt/data/stockbot`).
|
||||
|
||||
### Baseline gates & Phase 0 findings (2026-11-26)
|
||||
|
||||
9 of 11 repository gates pass on the current working tree; audit uncovered specific Phase 0 items that must land before Phase A:
|
||||
|
||||
- **Failing gates:** `test:tooling` (`178 pass, 1 fail` — `scripts/test/workspace.test.ts:85` expects `docker-compose.yml` after `scripts/docker.sh` switched default to `dev`) and `lint:check` (`63 curly errors + 2 warnings = 65`: `61` in `phase1-inventory.ts`, `4` in WIP files).
|
||||
- **Dev PostgreSQL init bug:** `database/postgres/init/01`–`05` hardcode `\c trading_bot;`, leaving `trading_bot_dev` (`5433`) with zero master/pipeline tables on fresh startup.
|
||||
- **Read-only MongoDB bypass:** `MongoDBClient.getDatabase()`/`collection()` (`libs/data/mongodb/src/client.ts`) expose unwrapped driver objects bypassing `mongoReadOnly`, used by legacy `sync-ib-exchanges.operations.ts`; `env-safety.ts` warns instead of throwing when `dataPipeline` uses `trading_admin`.
|
||||
- **Credential & holdout leaks:** `apps/stock/data-ingestion/src/handlers/ib/shared/config.ts:19` contains a hardcoded proxy URL credential; `research-agents.service.ts:51` allows `sb-research.*` tokens to call `/api/v2/datasets/canonical/:hash/export` (leaking holdout bars) and lacks cumulative lifetime/campaign trial caps; `data-ingestion` runs scheduled crawls on boot unless `QUEUE_ENABLE_SCHEDULED_JOBS=false`.
|
||||
- **Stray root files to remove:** `tetest.ts`, `test-queue.ts`, `proxy-playwrite.ts`, `test-rust-strategies.js`, `test-typescript-strategy.js`, `test-e2e-backtest.sh`.
|
||||
|
||||
### Raw data inventory (QA MongoDB `stock` — 31 collections)
|
||||
|
||||
| Provider | Collections (documents) | Key Audit Notes |
|
||||
| --- | --- | --- |
|
||||
| **EOD** | `eodSymbols` 318k, `eodExchanges` 76, `eodPrices` 846M, `eodIntraday1M` 3.40B, `eodIntraday5M` 1.08B, `eodIntraday1H` 110M, `eodSymbolChange` 230, `eodFundamentalsOLD` 107k, `eodFinancialsOLD` 2.98M | `eodPrices` has raw OHLC + **split-adjusted `volume`**; `eodIntraday1M` (US back to 2003) has **split-adjusted OHLC**; `CAD.FOREX` has `12.1k` 1d + `5.2M` 1m USD/CAD bars; `eodSymbolChange` only covers Aug 2024–Jul 2025 US; `eodFinancialsOLD` sets `filingDate == reportDate` on 99.3% of rows. |
|
||||
| **QM** | `qmSymbols` 47k, `qmExchanges` 25, `qmPrices` 51.5M, `qmIntraday` 173M, `qmFinancials` 1.86M, `qmFinancials-old` 908k, `qmFilings` 30.5M, `qmEarnings` 445k, `qmDividends` 496k, `qmSplits` 18.8k | `qmPrices` has raw OHLC + **raw `sharevolume`**; `qmIntraday` covers TSX/CA 1m (from May 2024) with both raw & adjusted columns; `qmFilings` holds US EDGAR + **Canadian SEDAR+** `timefiled` to the second (no parsed Form 4 share counts); `qmFinancials` has `0%` `filingDate` and `0` restatements (rescued via `qmFilings` join). |
|
||||
| **IB** | `ibSymbols` 18.4k, `ibExchanges` 214 | `100%` ISIN, `99.98%` CUSIP, `100%` `conid`; `exchangeId` records execution/ATS venues (`AEQLIT`, `ARCAEDGE`, `IEX`, `OTCLNKECN`), **not** primary listing MICs (`NYSE`=370, `NASDAQ`=241, `TSE`=514). |
|
||||
| **CEO** | `ceoSymbols` 12.6k, `ceoExchanges` 4, `ceoPosts` 14.8M, `ceoShorts` 693k | 100% Canadian (`TSX`, `CDX`, `CNQ`, `AQL`); `ceoShorts` back to Apr 2017 (stamps 15th/month-end report dates, requiring `+4bd` CIRO publication lag); `ceoPosts` has 1.8% edited posts (`edited != null`) and `@thenewswire` bot accounts. |
|
||||
| **TE** | `teCountries` 198, `teIndicators` 163, `teData` 14.8k, `teMarketData` 435, `teUrls` 2.4M | `teData` stores `{d, v}` final-revised series only (no release dates or vintages → lagged regime use only); `teMarketData` includes `USDCAD` daily bars through Apr 2026. |
|
||||
| **TT** | `ttFutures` 1.46M | Individual historical contracts with corrupted date strings (`"NaN-at-e\""`, `"2001-/0-2/"`) → deferred out of scope. |
|
||||
|
||||
---
|
||||
|
||||
## 3. Decisions log
|
||||
|
||||
| # | Decision | Status |
|
||||
| --- | --- | --- |
|
||||
| **D1** | **Storage split:** Curate daily bars, corporate actions, PIT fundamentals/events/shorts/macro, FX, and versioned features directly into **Hive Parquet + DuckDB** behind `MarketDataStore`. Reserve **QuestDB `10.2.0`** (`SYMBOL CAPACITY 65536 NOCACHE`) for `1m`/`5m`/`1h` intraday and hot live/paper bars. No dual-backend parity harness. | Settled (2026-11-26) |
|
||||
| **D2** | **Copilot:** Desktop first — Claude Code / Claude Desktop connected through an MCP server. Autonomous campaign agents run in network-isolated containers with MCP-only access. | Settled (2026-11-26) |
|
||||
| **D3** | **Markets:** Multi-market, with US + Canada (and USD/CAD + G10 spot FX) as priority; `ttFutures` out of scope. | Settled (2026-11-26) |
|
||||
| **D4** | **Web app:** Evolve incrementally alongside backend phases; no rewrite. | Settled (2026-11-26) |
|
||||
| **D5** | **First step:** Cross-source entity resolution in `data-pipeline` (two-stage: global ISIN/CUSIP → `instrument`, EOD/QM venue → `listing`, IB `conid` attached at `(instrument_id, currency)`). | Settled (2026-11-26) |
|
||||
| **D6** | **End state:** Paper → live on **Interactive Brokers Margin account** (`USD` + `CAD` cash/margin sub-ledgers, `FXCONV` sweeps, `IDEALPRO` when trading FX alpha, $\le 80$ active intraday streaming symbols on isolated `9900K` host). | Settled (2026-11-26) |
|
||||
| **D7** | **Strategy scope:** Intraday, swing/daily, cross-sectional long/short equity portfolios, FX, and event/alt-data strategies (excluding macro-release surprises and insider dollar-volume in v1). | Settled (2026-11-26) |
|
||||
| **D8** | **Research playground:** Market intelligence, exploration lab, strategy tearsheets, and agent lab feed — delivered incrementally starting with Signal Lab + MCP. | Settled (2026-11-26) |
|
||||
| **D9** | **marimo** confirmed for Python labs: `marimo edit --watch --mcp` on separate loopback origin (`127.0.0.1:2718`), zero-RAM `marimo export html` snapshots in the Agent Feed, `_`-prefixed local variables, and mandatory `marimo check` AST/DAG gating. | Confirmed (2026-11-26) |
|
||||
| **D10** | **Holdout & recency defense:** Rolling **6-month Air-Gapped Vault** (`today - 6m`, unreadable by `MarketDataStore`/MCP/marimo during research, unlocked once at human `Validated → Paper` gate; no toggle switch in v1) + mandatory **Post-2023 Recency Gate**. | Settled (2026-11-26) |
|
||||
| **D11** | **Python → TypeScript bridge:** Signals promote via **materialized batch feature jobs** (`register_signal` → versioned `features` column read by Rust `Replay` + `StrategyContext`), eliminating manual Python-to-TypeScript indicator rewrites. | Settled (2026-11-26) |
|
||||
| **D12** | **Knowledge base:** Mount Studio's 83-card `catalog/quant/library/library.yml` read-only for methodology/literature; store only empirical Stock Bot `findings`, `dead_ends`, and `provider_caveats` in PostgreSQL. | Settled (2026-11-26) |
|
||||
|
||||
---
|
||||
|
||||
## 4. System architecture
|
||||
|
||||
```text
|
||||
┌────────────────────────────────────────────┐
|
||||
Ideas: you + Studio ───▶ │ AGENTS (desktop copilot, Studio, campaigns)│
|
||||
└───────────────┬────────────────────────────┘
|
||||
│ MCP tools / HTTP API / Python SDK
|
||||
┌──────────────────────────────────────────▼─────────────────────────────────────────┐
|
||||
│ RESEARCH KERNEL (one API) │
|
||||
│ query data (vault-fenced) · analyze signal · event study · screen · backtest · │
|
||||
│ tearsheet · findings · campaigns · trial ledger · vault promotion gate │
|
||||
└───────┬───────────────────┬──────────────────────┬───────────────────┬─────────────┘
|
||||
│ │ │ │
|
||||
┌───────▼───────┐ ┌────────▼────────┐ ┌─────────▼────────┐ ┌───────▼─────────┐
|
||||
│ DATA │ │ BACKTEST │ │ ORCHESTRATION │ │ EXECUTION │
|
||||
│ MarketDataStore│ │ columnar screen │ │ campaigns, │ │ paper host → │
|
||||
│ • DuckDB/Parq │ │ + Rust engine │ │ budgets, local │ │ IB Gateway (9900K│
|
||||
│ • QuestDB 10.2│ │ + CPCV/DSR/PBO │ │ worker pool │ │ OMS, dual drift)│
|
||||
└───────▲───────┘ └─────────────────┘ └──────────────────┘ └─────────────────┘
|
||||
│
|
||||
┌───────┴──────────────────────────────────────────────┐
|
||||
│ PIPELINE (data-pipeline): raw → merged → curated → │
|
||||
│ batch features; security master in PostgreSQL │
|
||||
└───────▲──────────────────────────────────────────────┘
|
||||
│ read-only (MONGODB_READ_URI: studio_stock_bot_read)
|
||||
┌───────┴───────────────┐ ┌──────────────────────────────────────────┐
|
||||
│ MongoDB raw landing │◀───────│ data-ingestion (providers: EOD, QM, IB, │
|
||||
│ (QA, never written │ │ CEO, TE) │
|
||||
│ from dev/tests) │ └──────────────────────────────────────────┘
|
||||
└───────────────────────┘
|
||||
|
||||
APP (web-app): Lab (+ marimo) · Agents · Strategies · Data · Trading · Markets · Home
|
||||
```
|
||||
|
||||
| Layer | Owns | Language |
|
||||
| --- | --- | --- |
|
||||
| `data-ingestion` | Provider crawlers → raw MongoDB (scheduled jobs disabled outside dedicated ingester) | TypeScript |
|
||||
| `data-pipeline` + `curate-etl` | Entity resolution & orchestration (TS), zero-copy BSON bulk bar ETL (`tools/curate-etl` in Rust), PIT/feature batch jobs → Postgres + Parquet + QuestDB | TypeScript + Rust (`RawDocumentBuf`/Arrow/ILP) + Python/DuckDB |
|
||||
| Research kernel | Single API + MCP server enforcing vault cutoff, budgets, trial ledger, and canonical metrics | TypeScript (`web-api` / `orchestrator` / `@stock-bot/calculations`) |
|
||||
| Engine | Authoritative accounting, multi-currency margin ledger, corporate actions, fills, risk, replay | Rust (`apps/stock/engine/src/financial`) |
|
||||
| Python SDK + marimo | Exploration, Signal Analyzer, Event Study, Tier 1 columnar screener, feature batch definitions | Python (`polars`, `duckdb`, `marimo`) |
|
||||
| `web-app` | Incremental UI over Research Kernel state | TypeScript / React |
|
||||
|
||||
---
|
||||
|
||||
## 5. Data architecture and storage
|
||||
|
||||
Full schemas and SQL contracts live in **[DATA-CONTRACTS.md](DATA-CONTRACTS.md)**.
|
||||
|
||||
### Layers
|
||||
|
||||
| Layer | Store | Contents | Who writes | Who reads |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Raw | MongoDB (`stock`) | Provider documents as fetched | `data-ingestion` | `data-pipeline` only (`studio_stock_bot_read`) |
|
||||
| Reference | PostgreSQL | Exchanges, instruments, identifier history, listings, symbol history, provider mappings, corporate-action continuations, conflicts, overrides | `data-pipeline` | Everything |
|
||||
| Curated (Daily & PIT) | **Parquet + DuckDB** | `bars_1d`, `adj_factors`, `corporate_actions`, bitemporal `fundamentals` + wide PIT/TTM snapshots, `events`, `shorts`, `macro`, `fx_1d` | `data-pipeline` | `MarketDataStore` |
|
||||
| Curated (Intraday & Hot) | **QuestDB `10.2.0`** | `bars_1m` (`5m`/`1h` via `SAMPLE BY` or materialized), `fx_1m`, recorded live/paper IB bars & quotes, sparse `bar_revisions` | `data-pipeline`, IB bridge | `MarketDataStore` |
|
||||
| Features | **Parquet + DuckDB** (1d) / **QuestDB** (intraday) | Versioned precomputed feature series (`(listing_id, ts, known_at, value)`) | Feature jobs | `MarketDataStore`, Screener, Rust `Replay` |
|
||||
| Research & Vault state | PostgreSQL | Projects, campaigns, `trial_ledger` (with return vectors), findings, strategies, runs, `vault_evaluations` | Research kernel | App, MCP, SDK |
|
||||
|
||||
### Access rules & performance targets
|
||||
|
||||
1. **One access contract (`MarketDataStore` in TS, `stockbot.data` in Python).** Every non-vault call enforces `ts < VAULT_CUTOFF_TS` and `known_at <= asOf` inside the adapter. No raw-SQL escape hatch is exposed to agents; human localhost sessions may query read-only pre-vault DuckDB views.
|
||||
2. **Storage & memory hygiene.**
|
||||
- `MarketDataStore` and Parquet expose `listing_id` as `INT32`; inside QuestDB `10.2.0`, `listing_id` is stored as `SYMBOL CAPACITY 65536 NOCACHE` so `LATEST ON` backward partition scans and `ASOF JOIN` fast paths work without JVM heap bloat.
|
||||
- QuestDB `bars_1m` uses **`PARTITION BY MONTH`** (`270` partitions across 22.5y instead of `~5,670` daily partitions) with host `vm.max_map_count >= 1048576`, `ulimits.nofile = 1048576`, and `QDB_RAM_USAGE_LIMIT_BYTES` capped (`20 GiB` on `quant`). Sealed `>90d` monthly partitions may be compressed in-place (`ALTER TABLE bars_1m CONVERT PARTITION TO PARQUET`) if NVMe capacity requires it; recent partitions remain native mmap.
|
||||
- Every DuckDB connection explicitly sets `memory_limit = '6GB'`, `threads = 4`, and `temp_directory` on `quant` (instead of DuckDB's `80%` host-RAM default), leaving `~24 GiB` of `quant`'s `125 GiB` unallocated for Linux NVMe page cache.
|
||||
3. **Measured storage targets on `quant` (`12900K`, SN850X NVMe):**
|
||||
- **W1:** 20y US+CA daily universe (~15k active+delisted listings, ~45M bars) + 1 signal IC/quantile scan: **`< 3 s` warm / `< 8 s` cold**.
|
||||
- **W2:** 1 listing, 1y of `1m` bars (~100k–200k rows) from QuestDB: **`< 250 ms` warm / `< 1 s` cold**.
|
||||
- **W3:** 4 concurrent campaign workers: **p95 slowdown `< 35%`**, zero OOM or lease expiries.
|
||||
- **W4:** 1 date cross-section (~8k alive listings × 20 features): **`< 100 ms`**.
|
||||
|
||||
---
|
||||
|
||||
## 6. Step 1 — Cross-source merge (security master)
|
||||
|
||||
Exact DDL and edge-case rules are specified in **[DATA-CONTRACTS.md](DATA-CONTRACTS.md)**.
|
||||
|
||||
### Target model (PostgreSQL)
|
||||
|
||||
- `exchange`: `mic` (ISO 10383 PK), `operating_mic`, `name`, `country_iso`, `currency`, `timezone`, `calendar_code`, `is_composite_or_ats`.
|
||||
- `exchange_source_map`: `(source, source_code)` → `mic` (or explicit non-primary role: `'composite' | 'ats_routing' | 'forex' | 'excluded_fund'`), `reviewed_by`.
|
||||
- `instrument`: `instrument_id` (`INT4` identity), `primary_isin`, `primary_cusip`, `canonical_name`, `security_type` (`common`, `preferred`, `unit`, `warrant`, `right`, `etf`, `cdr`, `fx`), `issuer_country`.
|
||||
- `instrument_identifier_history`: `(instrument_id, id_type, id_value, valid_from, valid_to, source)` — preserves continuity across TSXV share consolidations and corporate redomiciliations (`LIN`).
|
||||
- `listing`: permanent `listing_id` (`INT4` identity), `instrument_id`, `mic`, `ticker_root`, `class_suffix`, `currency`, `ib_conid`, `listed_from`, `listed_to`, `delist_reason`.
|
||||
- `listing_symbol_history`: `(listing_id, ticker, valid_from, valid_to, source)`.
|
||||
- `corporate_action_continuity`: `(from_listing_id, to_listing_id, effective_date, kind)` — links primary-venue delistings (`SIVB` on `XNAS`) to same-ISIN OTC continuations (`SIVBQ` on `OTCM`) so bankruptcy losses are never truncated at halt price.
|
||||
- `provider_mapping`: `(source, source_id, valid_from)` → `listing_id`, `valid_to`, `method`, `confidence`.
|
||||
- `resolution_conflict`, `override` (always wins on re-runs), and `golden_field_audit`.
|
||||
|
||||
### Six-pass resolution pipeline
|
||||
|
||||
1. **Pass 1 — Exchanges (~320 rows):** Seed ISO 10383 MICs; map EOD (`76`), IB (`214`), QM (`25`), and CEO (`4: TSX→XTSE, CDX→XTSX, CNQ→XCNQ, AQL→NEOE`). Explicitly tag EOD `US` as composite (resolved via per-symbol `eodSymbols.Exchange`), exclude EOD `NMFQS` (`44,970` mutual funds) from equity universes, and mark IB ATS/smart codes (`AEQLIT`, `ARCAEDGE`, `BEX`, `DRCTEDGE`, `EDGEA`, `IEX`, `MEMX`, `OTCLNKECN`, `PSX`, `IBEOS`) as **`ats_routing`** rather than primary listing MICs.
|
||||
2. **Pass 2 — Normalization & Observed Spans:** Parse root + suffix (`AAA-P`/`AAA.P`, `AACT U`/`AACT.U`, `SCU.UN`, strip CEO `.TO`/`.V`), Luhn-validate ISINs (rejecting `CATSETEST001`, `CA00149WBAD4`, checksum-corrupted `CA8131391062` while recovering valid CUSIP `813139106` → `CA8131391064`), fix `provider-symbol.ts` to read IB `exchangeId`/`description`, and precompute `[first_bar_date, last_bar_date]` per `(source, source_id)`.
|
||||
3. **Pass 3 — Two-Stage Matching (Instrument first, Listing second):**
|
||||
- **Stage A (`instrument`):** Match globally by Luhn-valid ISIN and US/CA CUSIP-derived ISIN (`IB ↔ EOD`). Interlisted US/CA shares (`SHOP` on `XTSE` CAD and `XNYS` USD) share one `instrument_id` and get two `listing_id`s.
|
||||
- **Stage B (`listing` & non-ISIN sources):** Assign primary `listing.mic` from EOD `Exchange` + QM `exchange`; attach IB `conid` at `(instrument_id, currency)` (resolving the 83% TSX-on-`AEQLIT` and >90% NYSE/Nasdaq-on-ATS `ibSymbols` problem). Match QM and CEO by `(normalized_ticker, mic, currency)` **requiring overlapping `[first_bar_date, last_bar_date]` spans** so reused tickers (`FB` 2012–2022 Meta vs `FB` 2025 ProShares ETF; CSE `CNX`/`CC` duplicates) never collide.
|
||||
4. **Pass 4 — Fast Cross-Sectional Price Cross-Check:** Extract 25 stratified trading dates via `{ date: { $in: sampleDates } }` (hitting `eodPrices`'s `{date: 1, eodSearchCode: 1}` index sequentially in seconds rather than scanning 846M docs per pair) or run in DuckDB post-extract; verify price ratio ($\approx 1.0$ or $\approx \text{USD/CAD}$) and return correlation.
|
||||
5. **Pass 5 — Conflict Export & Overrides:** Write unresolved conflicts to `resolution_conflict`; review initial US+CA conflicts via generated markdown/CSV + SQL `override` seed file in Milestone 1 (deferring the React review UI until ongoing delta runs warrant it).
|
||||
6. **Pass 6 — Golden Record & OTC Delisting Chains:** Populate golden fields (`IB` → `EOD` for ISIN/CUSIP/`conid`/currency; `EOD` → `QM` for name/sector/listing span) and link same-ISIN `XNAS`/`XNYS` → `OTCM` delisting continuations.
|
||||
|
||||
---
|
||||
|
||||
## 7. Step 2 — Processing the remaining datasets
|
||||
|
||||
| Dataset | Raw sources | Curation & PIT (`known_at`) Rules | Store |
|
||||
| --- | --- | --- | --- |
|
||||
| **Daily bars** | `eodPrices`, `qmPrices` | Raw OHLC; **un-adjust `eodPrices.volume`** using cumulative `qmSplits` factors (cross-checked against raw `qmPrices.sharevolume`); `known_at` = session close | Parquet (`bars_1d`) |
|
||||
| **Intraday bars** | `eodIntraday1M` (US 2003–2025), `qmIntraday` (CA/US 2024–2025) | **Un-adjust `eodIntraday1M` OHLCV** for post-bar splits (cross-checked against `qmIntraday` raw & `bars_1d`); enforce venue session calendars | QuestDB `10.2.0` (`bars_1m`) |
|
||||
| **Corporate actions** | `qmSplits`, `qmDividends`, `eodPrices`/`qmPrices` spans | Drop `splitratio == 1` no-ops; ignore bogus `qmDividends.usdFxRate: 1`; link same-ISIN OTC delistings (`SIVB`→`SIVBQ`) + apply Shumway terminal delisting returns (`-30%` involuntary unlinked delist, `-100%` cancelled `-Q`/Pink) | Parquet (`corporate_actions`, `adj_factors`) |
|
||||
| **Fundamentals** | `qmFinancials`, `qmFinancials-old` + `qmFilings` (`eodFinancialsOLD` pre-QM fallback only; **`eodFundamentalsOLD` snapshots quarantined**) | Join `(listing_id, periodEndDate)` to earliest matching `10-Q`/`10-K`/`40-F`/SEDAR `Interim/Annual financial statements` `timefiled` in `qmFilings`. Fallback: statutory lag (`+45d Q / +90d FY` US & TSX; **`+60d Q / +120d FY` TSXV/CSE**) tagged `known_at_source = 'statutory_lag_estimate'`. Materialize 2D `(period_end, known_at)` deduplicated wide PIT + TTM snapshots. | Parquet (`fundamentals_pit`) |
|
||||
| **Earnings** | `qmEarnings` + `qmFilings` | Resolve `"announceTime": "N/A"` (`66.9%` of rows) via `qmFilings` `8-K` / `News release` `timefiled`; otherwise lag to `reportDate 16:05 ET` (tradable `T+1` open) | Parquet (`events`) |
|
||||
| **Filings** | `qmFilings` (`30.5M`) | Parse `timefiled` (`EST`/`EDT` → UTC); expose form-type & filing-arrival events (Form 4 / 144 / 8-K / NI 43-101 / 45-106F1 counts; insider share/dollar parsing deferred) | Parquet (`events`) |
|
||||
| **CEO posts** | `ceoPosts` (`14.8M`) via `ceoSymbols` | Separate `bot == "1"` (`@thenewswire`) from retail posts; if `edited != null` (`1.8%`), guard text features with `known_at = edited` | Parquet (`events`) |
|
||||
| **Shorts** | `ceoShorts` (`693k`, CA 2017–2025) | Stamp `known_at = report_timestamp + 4 Canadian business days (17:00 ET)` to match CIRO dissemination lag | Parquet (`shorts`) |
|
||||
| **Macro** | `teCountries`, `teIndicators`, `teData` | Lagged publication cutoffs (`+1d` policy rates, `+35d` monthly CPI/NFP, `+65d/+90d` GDP); **regime filters only** (final-revised values, no release event studies) | Parquet (`macro`) |
|
||||
| **FX** | `eodPrices`/`eodIntraday1M` (`CAD.FOREX`, `CADUSD.FOREX`) + `teMarketData` (`USDCAD`) | Curate existing 1971–2026 daily + `5.2M` `1m` USD/CAD series immediately; add IB `USD.CAD` live feed in Milestone 5 | Parquet (`fx_1d`) + QuestDB (`fx_1m`) |
|
||||
|
||||
---
|
||||
|
||||
## 8. Feature library
|
||||
|
||||
Features are defined once as **versioned DuckDB SQL or Python/Polars batch jobs** (`features/<family>/<name>_v<k>`), materialized to Parquet/QuestDB with `(listing_id, ts, known_at, value: f64)`, and registered with warm-up length, inputs, `known_at` rule, and unit tests:
|
||||
|
||||
- **Technical:** multi-horizon log/simple returns, realized vol, Wilder RSI (`flatValue = 50.0` standardized), ATR, MA distance, overnight/intraday gaps, dollar-volume z-score (on un-adjusted volume!), VWAP distance, opening range.
|
||||
- **Cross-sectional:** universe/sector-neutralized ranks and winsorized z-scores per date.
|
||||
- **Fundamental (PIT):** E/P, B/P, FCF yield, ROE, gross/operating margins, Sloan accruals, YoY asset/revenue growth, net-debt/EBITDA — computed strictly from 2D-deduplicated TTM snapshots.
|
||||
- **Event & Canadian alt-data:** days since/until earnings, filing-burst flags (`45-106F1` financings, `NI 43-101`, Form 4/144 clusters), CEO.ca retail vs newswire post velocity, CIRO short-interest % of float & semi-monthly $\Delta$ days-to-cover.
|
||||
- **Cross-border & FX:** interlisted TSX vs NYSE CAD-adjusted basis (`CAD.FOREX` 1m/1d) and lead-lag spreads.
|
||||
- **Regime:** market breadth, realized-vol state, sector dispersion, lagged central-bank/CPI/PMI state.
|
||||
|
||||
**Promotion bridge (D11):** Calling `register_signal(...)` from Python/marimo registers a versioned batch feature job. Rust `Replay` and TypeScript `StrategyContext` receive a read-only `features: Record<string, number | null>` map at each decision barrier — so zero indicator or statistical math is ever rewritten in zero-import TypeScript.
|
||||
|
||||
---
|
||||
|
||||
## 9. Backtesting
|
||||
|
||||
Mathematical formulas and ledger schemas are specified in **[VALIDATION-AND-RIGOR.md](VALIDATION-AND-RIGOR.md)**.
|
||||
|
||||
### Tier 1 — Fast columnar screener (Polars / DuckDB)
|
||||
|
||||
- Evaluates hundreds to thousands of `feature × horizon × universe × rebalance` variants in seconds over precomputed Parquet columns, applying linear spread + commission + borrow-rate turnover haircuts.
|
||||
- Net-new columnar screener (distinct from deferred backlog task `P06`, which remains closed; `D04` shared features and `P03` worker dataset caching are reopened instead).
|
||||
- Finds candidates only; **never** certifies a strategy. Logs the complete synchronous return matrix $M_{T \times N}$ to `trial_ledger` in one atomic batch.
|
||||
|
||||
### Tier 2 — Authoritative Rust portfolio engine (`apps/stock/engine/src/financial`)
|
||||
|
||||
Extends the existing 8-decimal Rust kernel (retiring legacy `f64` `BacktestEngine` and TypeScript `SimulationExecution` upon cutover):
|
||||
|
||||
- **Atomic timestamp-slice marking (`F06` fix):** Apply all instrument marks at timestamp `t` before evaluating `RiskAccount` portfolio drawdown/daily-loss latches so hedged long/short moves never trigger false intermediate halts.
|
||||
- **Simultaneous target rebalancing:** Credit haircut-adjusted pending `Sell` proceeds against same-barrier `Buy` reservations in `MatchingAccount::submit` so fully invested cross-sectional rotations execute cleanly in one barrier.
|
||||
- **Zero-JSON market-data path & Feature side-channel:** Eliminate the 8× JSON/Zod/IPC/N-API bar path (`backtest_datasets.payload` `255 MB` `JSONB` ceiling, `structuredClone`, `fork({ serialization: 'json' })`, and `api/canonical.rs` triple `serde_json::Value` parse). Retain only `(hash, manifest, parquet_paths)` in PostgreSQL, read Parquet/Arrow columns directly inside Rust `Replay`, restrict `canonical.rs` `keys_match` to small control/config envelopes, and stream multi-asset decision-barrier slices to `candidate-sandbox.ts` as compact **Arrow IPC / flat `Float64Array` binary frames** on declared rebalance barriers.
|
||||
- **Long/short, multi-currency margin & corporate actions:** Signed quantities/targets, short borrow fee accrual, `BTreeMap<Currency, Posting>` (`USD` + `CAD` cash/margin balances with IB benchmark+spread interest on negative balances, plus tradable FX pairs), ex-date split share adjustments, cash dividend postings, TSX/TSXV board-lot sizing (`100`/`500`/`1,000` shares), and OTC/Shumway delisting liquidations.
|
||||
|
||||
### Validation suite, Trial Ledger & 6-Month Vault
|
||||
|
||||
- **Trial ledger (`trial_ledger` in PostgreSQL):** Groups trials deterministically by `(universe_market, horizon_bucket)` (`{US, CA, US_CA, FX} × {intraday, swing_1_10d, position_10d_plus}`) and stores each variant's out-of-warmup daily return/IC vector (`FLOAT4[]`) to compute Bailey & López de Prado **effective independent trials $\hat{N}$**, non-normal **Deflated Sharpe Ratio (DSR $\ge 0.95$)**, and **PBO ($\le 0.20$)** via CSCV ($S = 16$).
|
||||
- **Purged Walk-Forward & CPCV:** Replaces `labelHorizonMs = 0` with mandatory `purge = horizon + warmup` and `embargo = max(5d, 0.01 * T)`.
|
||||
- **Post-2023 Recency Gate:** Post-2023 IC and Sharpe must be positive and $\ge 50\%$ of pre-2023 levels so decayed pre-LLM anomalies fail automatically.
|
||||
- **Rolling 6-Month Air-Gapped Vault (`D10`):** Most recent 6 months (~126 trading days) fenced off from all research/MCP/marimo reads; evaluated **once** when **you** promote a `Validated` strategy toward `Paper` ($\le 10$ vault evaluations/year recorded in immutable `vault_evaluations`).
|
||||
|
||||
---
|
||||
|
||||
## 10. Orchestration
|
||||
|
||||
- **Single-host research & campaign execution on `quant` (`12900K`):** With 24 threads, 125 GiB RAM, and 3.6 TiB NVMe on `quant`, all databases, DuckDB/QuestDB stores, and 4–8 worker-pool slots run locally on `quant` — avoiding distributed multi-host worker complexity until 24 cores saturate.
|
||||
- **Campaigns with hard SQL budgets:** `campaign → experiments → trials`, with cumulative trial, bar-evaluation, and wall-clock caps enforced by PostgreSQL `BEFORE INSERT` triggers (closing today's concurrent-only `active_trials` gap).
|
||||
- **Shared dataset/feature memory (`P03`):** Trials in a campaign share memory-mapped Parquet/Arrow columns on `quant`.
|
||||
- **Notifications:** Desktop/phone alerts (ntfy or Discord) when campaigns complete, vault candidates surface, or data monitors trip.
|
||||
|
||||
---
|
||||
|
||||
## 11. Research and analytics playground
|
||||
|
||||
1. **Exploration Lab (built first):**
|
||||
- **Signal Analyzer:** IC, rank-IC, decay across `1d/5d/20d`, quantile spreads, turnover, breakeven cost, and breakdowns by regime, sector, market-cap tier, country (`US` vs `CA`), and pre/post-2023.
|
||||
- **Event Study:** Pre/post abnormal return fans around filings (`NI 43-101`, `45-106F1`, Form 4/8-K), earnings, CIRO short spikes, and CEO.ca bursts.
|
||||
- **marimo Labs (`D9`):**
|
||||
- `marimo edit ./research/notebooks --watch --mcp` runs on a **dedicated loopback origin (`127.0.0.1:2718`)** with token auth so iframe scripts never share `web-app`'s `SameSite=Strict` `stock_bot_session` cookie.
|
||||
- Agent findings attach **static HTML exports (`marimo export html`)** rendered in `<iframe sandbox="allow-scripts" srcDoc={...}>` (zero idle Python RAM); interactive `marimo run --session-ttl 300` launches on-demand only.
|
||||
- Agent notebook writes must pass `marimo check --format=json` (`0` errors) and use `_`-prefixed cell-local variables for heavy Polars frames.
|
||||
2. **Tearsheets:** Equity, underwater drawdown, rolling Sharpe, trade-to-bar drill-down (over unified `lightweight-charts`), exposures, capacity, full validation suite (`DSR`, `PBO`, `CPCV`, recency), and live dual drift.
|
||||
3. **Agent Lab Feed:** Findings + dead ends linked to immutable trial counts, $\hat{N}$-adjusted DSR, and static HTML notebook snapshots, with one-click `Approve / Reject / Dig deeper / Promote to Paper (run 6m Vault)`.
|
||||
4. **Market Intelligence (`Markets` & `Home`):** Built incrementally in Phase 4 once core research and portfolio backtesting are live.
|
||||
|
||||
---
|
||||
|
||||
## 12. Agent layer
|
||||
|
||||
- **Roles:** `Scout` (Studio/notes → testable hypothesis + economic rationale), `Data Analyst` (coverage & `known_at_source` check), `Signal Researcher` (IC / event studies), `Strategy Builder` (`register_signal` → Tier 1 screen → Tier 2 Rust backtest), `Skeptic` (audits look-ahead, split/volume artifacts, liquidity/board-lots, post-2023 decay, multiple testing), `Portfolio Manager` (marginal Sharpe & correlation vs existing book), `Monitor` (paper/live drift & decay).
|
||||
- **Knowledge base (`D12`):** MCP mounts Studio's 83-card `~/repos/studio/catalog/quant/library/library.yml` read-only for statistical/methodological cards, while PostgreSQL stores Stock Bot's empirical `findings`, `dead_ends`, and `provider_caveats`.
|
||||
- **Security & isolation:**
|
||||
- Desktop Claude Code connects via MCP (`D2`) for interactive copilot work.
|
||||
- Autonomous campaign agents run in **network-isolated containers** reaching **only** the Research Kernel MCP/HTTP endpoint (`sb-research.*` tokens with `/export` revoked, `GET` routes project-scoped, and SQL cumulative trial caps).
|
||||
- **Studio bridge:** Studio Quant ideas (`hypothesis`) trigger bounded Stock Bot campaigns via API and receive structured `verdict + DSR + tearsheet/HTML link` receipts back.
|
||||
|
||||
---
|
||||
|
||||
## 13. Execution: paper to live on IB
|
||||
|
||||
Deployed on the dedicated, isolated **`9900K` host** (`docs/servers.md`) in Milestone 5:
|
||||
|
||||
- **Paper runtime fixes (prerequisite):** Compact `simulation_accounts` state (periodic snapshot + tail receipts, eliminating today's $O(N)$ double genesis replay in `apps/stock/engine/src/api/paper.rs`), expose `MatchingReset` over NAPI, and execute non-builtin strategy code inside the `A02` sandbox rather than importing raw JS into the privileged `paper-host` process.
|
||||
- **IB Gateway & Market Data Bridge:** Headless `IB Gateway` supervised by `IBC` (handling nightly ~21:00 ET resets and `1100→1102` stream re-subscriptions). Aggregates `reqRealTimeBars(5s, TRADES)` + L1 `reqMktData` quotes into session-aligned bars emitted **after bar-close + 2s grace**, budgeted to $\le 80$ concurrent symbols within IBKR's standard 100-line cap.
|
||||
- **Contract & Canadian market-structure rules:**
|
||||
- Pin `(conid, symbol, currency, exchange="SMART", primaryExchange)` from `listing` so interlisted US/CA tickers (`SHOP`, `RY`, `TD`) never route across borders.
|
||||
- Enforce TSX/TSXV price-tiered board lots (`100` sh $\ge \$1.00$, `500` sh $\$0.10\text{–}\$0.995$, `1,000` sh $< \$0.10$) and auction cutoffs (`15:40 ET` TSX MOC vs `15:50 ET` NYSE/Nasdaq MOC).
|
||||
- **IBKR Margin `USD` / `CAD` & FX policy:**
|
||||
- Track separate `USD` and `CAD` cash/margin sub-ledgers in Rust `Ledger`, accruing daily IBKR benchmark+spread interest on negative currency balances.
|
||||
- Route cash-funding conversions to **`exchange="FXCONV"`** (`$2` min, updates cash without creating virtual FX positions); route intentional FX alpha trades to **`exchange="IDEALPRO"`**.
|
||||
- **OMS, Risk & Dual Drift Monitoring:**
|
||||
- Idempotent client order IDs, partial-fill state machine, continuous broker-vs-ledger position/cash reconciliation, per-strategy + global daily-loss/drawdown/order-rate kill switches.
|
||||
- **Dual Drift Monitor:** separates **(1) Execution Drift** (live IB fills vs Rust replay on *recorded live IB bars/quotes*) from **(2) Feed Basis Drift** (Rust replay on *recorded IB bars* vs next-day *curated EOD/QM bars*).
|
||||
|
||||
---
|
||||
|
||||
## 14. The app
|
||||
|
||||
Evolves incrementally (`D4`) from today's `29.6k`-line React codebase (`apps/stock/web-app/src/features/*`):
|
||||
|
||||
- **Immediate cleanup:** Wire existing `ResearchAgentsPage.tsx` (`/research/agents`) into `Sidebar.tsx` and consolidate the two separate `lightweight-charts` wrappers (`src/components/charts/Chart.tsx` and `src/features/charts/components/SymbolChart.tsx`).
|
||||
- **Target navigation (delivered with each milestone):**
|
||||
- **Lab** (Signal Analyzer, Event Study, static-HTML + live marimo link)
|
||||
- **Strategies** (lifecycle stages, tearsheets, CPCV/DSR/PBO + 6m Vault gate)
|
||||
- **Agents** (campaigns, budgets, findings/dead-ends feed, `sb-research.*` tokens)
|
||||
- **Data** (`exchanges`/`symbols`/`pipeline` + coverage map, quality monitors, conflict queue)
|
||||
- **Trading** (`paper` + IB live positions, USD/CAD cash & margin, Dual Drift, kill switches)
|
||||
- **Markets** & **Home** (greenfield — note `src/features/dashboard` is currently empty and deferred until Milestone 4).
|
||||
|
||||
---
|
||||
|
||||
## 15. Strategy lifecycle
|
||||
|
||||
```text
|
||||
Idea ─▶ Hypothesis ─▶ Signal ─▶ Candidate ─▶ Validated ──[You: 6m Vault]──▶ Paper ─▶ Live ─▶ Retired
|
||||
```
|
||||
|
||||
| Stage | Quantitative Gate to Enter | Who Approves |
|
||||
| --- | --- | --- |
|
||||
| **Hypothesis** | Economic rationale, target universe/horizon, `known_at_source` verified clean | Agent (`Scout` + `Data Analyst`) |
|
||||
| **Signal** | $|\overline{\text{Rank IC}}| \ge 0.015$ ($t \ge 3.0$ Newey-West) or event abnormal return $\ge +35\text{ bps}$ ($t \ge 3.0$); **Post-2023 Recency Gate** ($\ge 50\%$ of pre-2023 IC & $> 0$) | Agent, logged to `trial_ledger` |
|
||||
| **Candidate** | Tier 1 screen net Sharpe $\ge 1.0$ at $1.5\times$ costs; turnover within $2\%$ ADV | Agent |
|
||||
| **Validated** | Tier 2 Rust engine + Purged Walk-Forward/CPCV: **DSR $\ge 0.95$** (cluster $\hat{N}$), **PBO $\le 0.20$**, net Sharpe $> 0$ at $2.0\times$ costs + `Skeptic` sign-off | Agent proposes to Lab Feed |
|
||||
| **Paper** | One-shot **6-month Vault Holdout** Sharpe $> 0.5$ & within $1.5\sigma$ of CPCV + **manual code/evidence review** | **You** |
|
||||
| **Live** | $\ge 30$ paper trading days & $\ge 50$ trades; Execution Drift $\le 15\text{ bps/trade}$; `0` unrecovered reconciliation breaks | **You** (small → scaled) |
|
||||
| **Retired** | Rolling decay or drift beyond bounds, or manual halt | `Monitor` proposes, **You** confirm |
|
||||
|
||||
---
|
||||
|
||||
## 16. Roadmap
|
||||
|
||||
Detailed checklists, file targets, and exit criteria live in **[MILESTONES.md](MILESTONES.md)**:
|
||||
|
||||
| Milestone | Delivers | Target Window |
|
||||
| --- | --- | --- |
|
||||
| **M0 — Safety & Gate Lock** | All 11 gates green, dev PG `\c` bug fixed, `@stock-bot/postgres` migrations, `MongoDBClient` `readOnly` leak closed, proxy secret purged, `sb-research.*` `/export` blocked | Days 1–3 |
|
||||
| **M1 — Vertical Slice 1 (Security Master + Daily/Event Signal Lab)** | US+CA security master (Passes 1–6 via SQL/CSV overrides), curated `bars_1d` + `corporate_actions` + `fx_1d` + `qmFilings`/`qmEarnings`/`ceoShorts` in DuckDB+Parquet, 6m Vault fence, `trial_ledger` + DSR, Python `stockbot` SDK + `marimo` Signal Analyzer | Weeks 1–3 |
|
||||
| **M2 — MCP Copilot, Intraday QuestDB & PIT Fundamentals** | MCP server + Studio library mount, `qmFinancials × qmFilings` 2D PIT fundamentals, `QuestDB 10.2.0` `bars_1m` + `fx_1m` (split-unadjusted), versioned batch Feature Library | Weeks 4–5 |
|
||||
| **M3 — Portfolio Backtest v2 (Screener + Multi-Asset Rust)** | Tier 1 columnar screener, Tier 2 Rust multi-asset upgrades (atomic marks, target sell-netting, `features` channel, long/short margin, USD/CAD, corporate actions, OTC delistings, Arrow load), CPCV + PBO + Vault promotion gate | Weeks 6–9 |
|
||||
| **M4 — Autonomous Campaigns, Studio Bridge & Lab UI** | Containerized campaign runner with SQL cumulative budgets, agent roles + `Skeptic`, Studio webhook bridge, unified `web-app` Lab/Agents/Data/Markets/Home screens | Weeks 10–12 |
|
||||
| **M5 — Compacted Paper → Live IB Margin (`9900K`)** | `paper.rs` state compaction + sandboxed paper candidates, headless `IB Gateway + IBC` bridge on `9900K`, OMS + TSX board-lots + `FXCONV`, continuous reconciliation, Dual Drift Monitor, small-capital live | Weeks 13–16 |
|
||||
43
design/README.md
Normal file
43
design/README.md
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
# Stock Bot — Documentation Map
|
||||
|
||||
Start here. Every document below has a single responsibility; historical sprint logs and superseded design notes have been retired.
|
||||
|
||||
---
|
||||
|
||||
## 1. Platform Direction & Execution Plan
|
||||
|
||||
| Document | Owns | When to Read |
|
||||
| --- | --- | --- |
|
||||
| **[PLATFORM-PLAN.md](PLATFORM-PLAN.md)** | Target system architecture, settled decisions (`D1`–`D12`), layer boundaries, agent roles, and IB execution model | Before making architectural changes or starting a new milestone |
|
||||
| **[MILESTONES.md](MILESTONES.md)** | Active checklist (`M0` → `M5`), task order, explicit scope cuts, target file paths, and falsifiable exit criteria | Day-to-day execution for you, Claude Code, and Studio agents |
|
||||
| **[DATA-CONTRACTS.md](DATA-CONTRACTS.md)** | Raw MongoDB provider quirks, PostgreSQL security-master DDL, split/volume un-adjustment rules, `known_at` derivation, DuckDB/Parquet & QuestDB `10.2.0` schemas, and `MarketDataStore` API | Before touching `data-pipeline`, `data-ingestion`, SQL migrations, or `MarketDataStore` |
|
||||
| **[VALIDATION-AND-RIGOR.md](VALIDATION-AND-RIGOR.md)** | Canonical metric definitions, `trial_ledger` schema, effective-trials DSR ($\hat{N}$), CSCV PBO, Purged CPCV/Walk-Forward, rolling 6-month Vault + Post-2023 Recency Gate, lifecycle gates, and Dual Live Drift + IB/TSX execution rules | Before touching `libs/calculations`, `libs/research`, validation workflows, or paper/live execution |
|
||||
| **[servers.md](servers.md)** | Host roles (`quant` `12900K` research/data server, `9900K` isolated IB live/paper host, `TrueNAS` cold storage, dev workstation) and port/storage layout | Infrastructure, deployment, and worker sizing |
|
||||
|
||||
---
|
||||
|
||||
## 2. Current Connected Runtime & Code Tour
|
||||
|
||||
These documents describe **what is already implemented and running in code today**:
|
||||
|
||||
| Document | Owns |
|
||||
| --- | --- |
|
||||
| **[guide/README.md](guide/README.md)** | High-level tour of the current canonical single-asset research workbench |
|
||||
| **[guide/system-map.md](guide/system-map.md)** | Applications, shared libraries, queues, and process boundaries |
|
||||
| **[guide/backtest-walkthrough.md](guide/backtest-walkthrough.md)** | End-to-end trace of a canonical backtest from HTTP admission to Rust replay and result persistence |
|
||||
| **[guide/strategy-development.md](guide/strategy-development.md)** | Current `StrategyProgram` callback contract and isolated candidate packaging |
|
||||
| **[guide/code-reading.md](guide/code-reading.md)** | Function-level call paths across `web-api`, `orchestrator`, and `engine` |
|
||||
| **[backtest-datasets.md](backtest-datasets.md)** | Current v2 retained dataset snapshot preparation, hashing, and local export |
|
||||
| **[data-pipeline/phase1-investigation.md](data-pipeline/phase1-investigation.md)** | Measured 31-collection QA MongoDB inventory, identifier coverage, and cross-provider tricky cases |
|
||||
|
||||
---
|
||||
|
||||
## 3. Enduring Architecture Decisions & Gates
|
||||
|
||||
| Document | Owns |
|
||||
| --- | --- |
|
||||
| **[development/QUALITY-GATES.md](development/QUALITY-GATES.md)** | Build, typecheck, contract, lint, native Rust, disposable PostgreSQL/Redis, and E2E verification gates |
|
||||
| **[development/architecture/overview.md](development/architecture/overview.md)** | Core invariants of the Rust financial kernel and durable worker supervision |
|
||||
| **[development/architecture/research-product.md](development/architecture/research-product.md)** | Retained provenance, idempotency, agent grants (`A01`), candidate isolation (`A02`), and paper custody (`A04`) |
|
||||
| **[development/architecture/benchmarks.md](development/architecture/benchmarks.md)** | Reproducible dataset and replay benchmark methodology |
|
||||
| **[development/architecture/decisions/](development/architecture/decisions/)** | Approved ADRs `001`–`008` (ownership, 8-decimal postings, availability timing, NAPI pull boundary, durable cutover, AI boundary, performance) |
|
||||
103
design/VALIDATION-AND-RIGOR.md
Normal file
103
design/VALIDATION-AND-RIGOR.md
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
# Stock Bot — Validation, Trial Ledger & Execution Rigor
|
||||
|
||||
Canonical mathematical and operational rules for `@stock-bot/calculations`, `@stock-bot/research`, the PostgreSQL `trial_ledger`, the 6-month Vault Holdout, and IBKR Margin / TSX execution.
|
||||
|
||||
---
|
||||
|
||||
## 1. Canonical Metric Conventions (`@stock-bot/calculations`)
|
||||
|
||||
No Python script, UI component, or legacy simulator may define its own Sharpe, Sortino, volatility, or drawdown formula. All layers read metrics computed by `@stock-bot/calculations`:
|
||||
|
||||
- **Return series:** Daily (or session-level) mark-to-market net portfolio total returns $r_t = \frac{E_t - E_{t-1}}{E_{t-1}}$ in the account's base currency, starting from `initialCapital` (so first-period losses are never skipped).
|
||||
- **Annualization factor ($A$):** `252` trading sessions/year for equity strategies (`252 * 390` only when reporting un-aggregated 1m bar statistics; tearsheets always aggregate intraday equity to daily session closes before computing Sharpe/DSR/PBO so intraday and daily strategies compare on the same `252`/yr scale).
|
||||
- **Volatility:** Sample standard deviation ($N - 1$ degrees of freedom), annualized via $\hat{\sigma}_{\text{ann}} = \hat{\sigma}_d \sqrt{252}$.
|
||||
- **Sharpe Ratio ($\widehat{SR}$):** Arithmetic excess return over risk-free rate $r_f$ per period:
|
||||
$$\widehat{SR}_{\text{ann}} = \frac{\bar{r}_d - r_{f,d}}{\hat{\sigma}_d}\sqrt{252}$$
|
||||
- **Sortino Ratio:** Downside root-mean-square over **all** $T$ observations (`target = r_{f,d}`), never standard deviation of negative-only observations:
|
||||
$$\widehat{\text{Sortino}}_{\text{ann}} = \frac{(\bar{r}_d - r_{f,d}) \cdot 252}{\sqrt{\frac{252}{T}\sum_{t=1}^{T} \min(0, r_t - r_{f,d})^2}}$$
|
||||
- **RSI convention:** Wilder smoothing (`1/period`), with flat-price (`avg_gain == 0 && avg_loss == 0`) standardized to **`50.0`** across Rust, TypeScript, and batch feature jobs.
|
||||
|
||||
---
|
||||
|
||||
## 2. Trial Ledger & Multiple-Testing Math (`DSR` & `PBO`)
|
||||
|
||||
### A. PostgreSQL `trial_ledger` Schema (Append-Only)
|
||||
|
||||
Protected against `UPDATE`/`DELETE`/`TRUNCATE` by `reject_research_evidence_mutation()`:
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS trial_ledger (
|
||||
trial_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
principal_id TEXT NOT NULL, -- 'operator' | 'agent:<uuid>'
|
||||
campaign_id UUID,
|
||||
stage VARCHAR(16) NOT NULL, -- 'signal_ic' | 'event_study' | 'screen' | 'engine_backtest'
|
||||
universe_market VARCHAR(12) NOT NULL, -- 'US_EQ' | 'CA_EQ' | 'US_CA_EQ' | 'FX'
|
||||
horizon_bucket VARCHAR(16) NOT NULL, -- 'intraday' | 'swing_1_10d' | 'position_10d_plus'
|
||||
hypothesis_id UUID,
|
||||
expression_hash CHAR(64) NOT NULL, -- SHA-256 of canonical signal/strategy + params + universe + window
|
||||
sample_start DATE NOT NULL,
|
||||
sample_end DATE NOT NULL, -- must be < VAULT_CUTOFF_DATE
|
||||
n_obs INTEGER NOT NULL,
|
||||
sharpe_unann DOUBLE PRECISION NOT NULL,
|
||||
skewness DOUBLE PRECISION NOT NULL,
|
||||
kurtosis DOUBLE PRECISION NOT NULL, -- Pearson kurtosis (normal = 3.0)
|
||||
daily_series REAL[] NOT NULL -- daily net return or daily cross-sectional IC vector (~5k floats = 20 KB)
|
||||
);
|
||||
```
|
||||
|
||||
### B. Relatedness Cluster & Effective Independent Trials ($\hat{N}$)
|
||||
|
||||
- **Deterministic cluster key:** `(universe_market, horizon_bucket)`. Agents cannot reset `N = 1` by inventing a new strategy `family` name.
|
||||
- **Multi-horizon / breakdown accounting:** A single `analyze_signal` call evaluating 3 horizons (`1d`, `5d`, `20d`) records **3 rows** in `trial_ledger`.
|
||||
- **Effective independent trials ($\hat{N}$, Bailey & López de Prado):** Given $K$ trials in the cluster with overlapping daily series correlation matrix $P$:
|
||||
$$\bar{\rho} = \frac{2}{K(K - 1)}\sum_{1 \le i < j \le K} \rho_{ij}, \qquad \hat{N} = \max\!\big(1,\; 1 + (K - 1)(1 - \max(0, \bar{\rho}))\big)$$
|
||||
Sweeping `SMA(20)` and `SMA(21)` ($\rho \approx 0.97$) adds $\approx 0.03$ effective trials; testing 100 orthogonal signals ($\bar{\rho} \approx 0$) yields $\hat{N} \approx 100$.
|
||||
|
||||
### C. Non-Normal Deflated Sharpe Ratio (`DSR`)
|
||||
|
||||
Using unannualized per-day $\widehat{SR}$ over $T$ daily observations, skewness $\hat{\gamma}_3$, Pearson kurtosis $\hat{\gamma}_4$, and cross-sectional variance $\hat{\sigma}_{\{SR\}}^2 = \text{Var}(\{\widehat{SR}_k\}_{k=1}^K)$ across the cluster:
|
||||
|
||||
$$SR_0 = \hat{\sigma}_{\{SR\}} \left[ (1 - \gamma)\Phi^{-1}\!\left(1 - \frac{1}{\hat{N}}\right) + \gamma\,\Phi^{-1}\!\left(1 - \frac{1}{\hat{N} e}\right) \right], \quad \gamma \approx 0.57721566$$
|
||||
|
||||
$$\widehat{\text{SE}}(\widehat{SR}) = \sqrt{\frac{1 - \hat{\gamma}_3 \widehat{SR} + \frac{\hat{\gamma}_4 - 1}{4}\widehat{SR}^2}{T - 1}}, \qquad \text{DSR} = \Phi\!\left(\frac{\widehat{SR} - SR_0}{\widehat{\text{SE}}(\widehat{SR})}\right)$$
|
||||
|
||||
**Gate:** Candidate → Validated requires **`DSR >= 0.95`**.
|
||||
|
||||
### D. Probability of Backtest Overfitting (`PBO` via CSCV)
|
||||
|
||||
Computed on any synchronous screen/experiment return matrix $M \in \mathbb{R}^{T \times N}$ ($N \ge 4$):
|
||||
1. Partition $T$ into $S = 16$ contiguous equal sub-periods (respecting `purge` at boundaries).
|
||||
2. For all $\binom{16}{8} = 12,870$ splits into in-sample $J$ and out-of-sample $\bar{J}$: find $n^* = \arg\max_n SR_n(J)$, compute the relative OOS rank $\omega \in (0, 1)$ of $n^*$ within $\{SR_n(\bar{J})\}$, and set $\lambda = \ln\!\frac{\omega}{1 - \omega}$.
|
||||
3. $\text{PBO} = \Pr(\lambda < 0)$ across all $12,870$ splits.
|
||||
|
||||
**Gate:** Candidate → Validated requires **`PBO <= 0.20`**.
|
||||
|
||||
---
|
||||
|
||||
## 3. Purging, Embargo, Recency & the 6-Month Vault
|
||||
|
||||
1. **Purged Walk-Forward & CPCV:** Every train/test boundary enforces:
|
||||
- `purge_bars = prediction_horizon_bars + feature_warmup_bars` (eliminating `labelHorizonMs = 0` overlap leakage).
|
||||
- `embargo_days = max(5, ceil(0.01 * total_trading_days))` after each test fold before resuming training.
|
||||
2. **Post-2023 Recency Gate:** Every candidate must report pre-2023 (`< 2023-01-01`) vs. post-2023 (`2023-01-01 .. VAULT_CUTOFF_DATE`) performance. Post-2023 rank-IC and post-cost Sharpe must both be **strictly positive** and **$\ge 50\%$** of pre-2023 levels.
|
||||
3. **Rolling 6-Month Air-Gapped Vault (`VAULT_CUTOFF_DATE`):**
|
||||
- Set to `max_curated_date - 6 calendar months` (~126 trading days).
|
||||
- Physically fenced in `MarketDataStore` (`scope = 'vault_fenced'`), with `/export` disabled for `sb-research.*` tokens and campaign containers blocked from DB ports.
|
||||
- **One-shot human burn:** Triggered only on operator `Validated → Paper` action (`<= 10` evaluations/year enforced by an append-only `vault_evaluations` table). Requires Vault post-cost Sharpe $> 0.5$ and within $1.5\sigma$ of CPCV fold distribution.
|
||||
|
||||
---
|
||||
|
||||
## 4. IBKR Margin, USD/CAD, TSX Microstructure & Dual Drift Rules
|
||||
|
||||
1. **Multi-currency IBKR Margin accounting (`USD` + `CAD`):**
|
||||
- Rust `Ledger` holds `cash: BTreeMap<Currency, Posting>` (signed `Decimal`, scale 8).
|
||||
- Buying a `USD` asset without `USD` cash creates a negative `USD` balance accruing daily IBKR tier benchmark + spread interest (no implicit free FX conversion).
|
||||
- Automated cash sweeps emit `secType="CASH"`, `symbol="USD"`, `currency="CAD"`, **`exchange="FXCONV"`** (`$2.00` USD min fee, `0.2` bps) — never `IDEALPRO`, unless a strategy explicitly opens a tracked FX alpha position.
|
||||
2. **Contract & Canadian board-lot rules:**
|
||||
- Every IB `Contract` specifies `conid`, `currency`, `exchange="SMART"`, and `primaryExchange` (`NYSE`, `NASDAQ`, `TSE`, `VENTURE`, etc.).
|
||||
- Position sizing on `XTSE` / `XTSX` (`board_lot_policy = 'tsx_tiered'`) rounds target orders to **Standard Trading Units** (`100` shares if mark $\ge \$1.00$ CAD; `500` shares if $\$0.10\text{–}\$0.995$; `1,000` shares if $< \$0.10$) unless odd-lot execution + wider spread penalty is explicitly enabled.
|
||||
- Auction orders enforce hard venue cutoffs (`15:40 ET` TSX `MOC`; `15:50 ET` NYSE/Nasdaq `MOC`/`LOC`).
|
||||
3. **Dual Live Drift Monitor:**
|
||||
- **Check 1 — Engine/Execution Drift:** Compare live IB fills & cash against a Rust replay run on the **exact recorded live IB bars & L1 quotes** (gate: $|\Delta\text{fill}| \le 15\text{ bps/trade}$, daily tracking error $\le 50\text{ bps}$ annualized).
|
||||
- **Check 2 — Feed Basis Drift:** Next morning after EOD/QM ingestion, compare Rust replay on **recorded IB bars** vs. Rust replay on **curated EOD/QM bars** for the same session to detect SIP vs. IB `SMART` volume/auction divergence before blaming execution.
|
||||
164
design/backtest-datasets.md
Normal file
164
design/backtest-datasets.md
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
# Backtest dataset preparation
|
||||
|
||||
Both backends use the same historical-data preparation boundary. There are no
|
||||
application-level instrument, bar-count, JSON/IPC-size or stored-snapshot-size caps,
|
||||
and no dataset-limit configuration. Runs load the complete requested historical range
|
||||
into memory; they are not silently truncated. Runtime, database and available-memory
|
||||
constraints still apply. No environment-file changes or database migrations are required.
|
||||
|
||||
## Loading and replay
|
||||
|
||||
QuestDB and Mongo queries retain their instrument and exclusive date-range filters,
|
||||
but have no application row limit. Mongo queries still project historical fields only.
|
||||
Synthetic data still requires explicit opt-in and a stable seed.
|
||||
|
||||
Replay loads the stored JSONB snapshot and validates it before execution. Invalid prices,
|
||||
duplicate or unordered bars, missing listings, incompatible requests and corrupted hashes
|
||||
remain errors. Failed snapshot preparation rolls back insertion and the run pointer
|
||||
together; the fencing/lease/cancellation predicates are unchanged.
|
||||
|
||||
## Canonical preparation and compatibility
|
||||
|
||||
`prepareDataset` parses each bar, validates identities/provenance/ranges/OHLC/order, and
|
||||
incrementally hashes bounded JSON chunks. It produces the exact same v1 digest bytes as
|
||||
`JSON.stringify({ manifest: manifestWithoutHash, bars })`; property reordering by JSONB
|
||||
does not change identity. Prices, timestamp ties and adjustment policies are unchanged.
|
||||
|
||||
Returned datasets are detached from caller inputs and deeply frozen, including nested
|
||||
manifest metadata and every bar. A private weak cache recognizes only these prepared
|
||||
objects. Internal handoffs reuse them without another array reconstruction/content hash;
|
||||
request compatibility is still checked. Raw database, resolver
|
||||
and caller objects always pass the full boundary. Clone a prepared value before editing
|
||||
it; altered content requires a new valid hash, not mutation of a pinned snapshot.
|
||||
|
||||
The synchronous `validateDataset` facade uses the same validator for small diagnostic
|
||||
calls. Runtime loading/restoration uses the asynchronous driver, yielding every 2,048
|
||||
bars so cancellation, execution deadlines and lease heartbeats can run. Abort signals
|
||||
propagate through loading, resolver callbacks and repository preparation; cancelled late
|
||||
reads cannot dispatch a worker. Driver queries already in flight are not forcibly killed.
|
||||
Sorting and final persistence/IPC serialization remain synchronous operations. The batch
|
||||
size controls event-loop yielding only; it is not an input limit.
|
||||
|
||||
## Reproducible preparation benchmark
|
||||
|
||||
```sh
|
||||
bun run benchmark:dataset
|
||||
```
|
||||
|
||||
The script compares four in-process validation handoffs of one valid dataset against the
|
||||
pre-refactor whole-schema/whole-JSON hash path. Each mode runs in a separate process;
|
||||
hashes must match. Timing excludes fixture creation. Peak RSS includes fixture creation
|
||||
and the runtime, so it is not an allocation counter or an incremental heap measurement.
|
||||
This is not an end-to-end backtest/database/native-worker benchmark or a CI threshold.
|
||||
|
||||
Historical Bun 1.2.17 sample, recorded before removal of the size-limit machinery
|
||||
(not a claim about current timings):
|
||||
|
||||
| Bars / instruments | Previous time | Prepared time | Previous peak RSS | Prepared peak RSS |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 10,000 / 1 | 62 ms | 28 ms | 126 MiB | 107 MiB |
|
||||
| 100,000 / 10 | 565 ms | 191 ms | 258 MiB | 176 MiB |
|
||||
| 1,000,000 / 100 | 6,190 ms | 2,559 ms | 1,545 MiB | 695 MiB |
|
||||
|
||||
Results vary with machine load and garbage collection. This optional diagnostic remains
|
||||
available; it does not impose input limits or change v1 content identity.
|
||||
|
||||
## Stored EOD preparation across declared sessions (v2)
|
||||
|
||||
In backtest **Settings → Prepare dataset from source export**, choose **Stored EOD —
|
||||
declared sessions only** and upload the complete v2 metadata JSON. The panel displays
|
||||
the selected series' declared session windows, clipped to the warmup/evaluation bounds,
|
||||
in UTC. Preview reads these windows sequentially; retain saves the captured input and
|
||||
hash without querying the mutable source again.
|
||||
The reads are not an atomic database snapshot; the captured rows define the retained
|
||||
dataset. Cancellation prevents subsequent reads/results but does not interrupt an
|
||||
already dispatched Mongo query.
|
||||
|
||||
The existing API opts in explicitly:
|
||||
|
||||
```json
|
||||
{ "metadata": { "...": "complete v2 metadata" }, "selection": "declared-sessions" }
|
||||
```
|
||||
|
||||
Send this to `POST /api/v2/datasets/canonical/stored-source`. The response echoes
|
||||
`selection` alongside `input` and `preparation`; retain uses that exact `input` and
|
||||
`preparation.hash`. Omitting `selection` preserves the continuous-range query.
|
||||
|
||||
Empty selected sessions, invalid selected rows, duplicates and bars crossing a session
|
||||
boundary fail preparation. Rows outside the declared windows are never read. Sessions,
|
||||
corporate-action coverage and source timing remain explicit operator declarations:
|
||||
successful preparation does not certify them or establish gap-free data. The source
|
||||
inspector diagnoses its own selected range independently of these capture windows.
|
||||
|
||||
## Reusing a retained dataset in the web workbench
|
||||
|
||||
In **Settings → Canonical research setup**, use **Load more canonical datasets** to
|
||||
browse beyond the newest 50 entries. A failed page can be retried without losing the
|
||||
loaded choices or advancing past that page. **Refresh canonical datasets** reloads
|
||||
the list and verifies the selected hash again.
|
||||
|
||||
If an AI workflow or earlier result gives you an exact hash, paste it into **Retained
|
||||
dataset hash** and choose **Use dataset hash**. The existing catalog endpoint checks
|
||||
the retained content and compatibility. A missing, unavailable or malformed hash lookup
|
||||
cannot enable saving; a selected dataset outside the loaded page remains visible.
|
||||
**Save canonical setup** saves the verified choice and its bounds without starting a run.
|
||||
|
||||
Settings are loaded on the first visit and stay in memory while switching tabs or
|
||||
selecting another run of the same backtest. That includes source previews and an
|
||||
unconfirmed retention retry's exact input/hash. Other tabs use the saved definition;
|
||||
an unsaved settings draft does not change a run. Explicit discard, leaving this
|
||||
backtest and reloading do not provide persistent draft recovery. Save settings and
|
||||
resolve retention before leaving if you need to keep the work.
|
||||
|
||||
## Downloading a retained snapshot for local exploration
|
||||
|
||||
Choose **Download retained dataset** beneath a verified dataset in **Settings →
|
||||
Canonical research setup**, or beside a saved canonical result's **Immutable configuration
|
||||
and reporting policy**. The saved-result action uses that run's original dataset hash,
|
||||
even if the editable backtest now selects another dataset. Downloading neither saves
|
||||
settings nor starts a run.
|
||||
|
||||
The file is `dataset-<hash>.json`, containing the complete v2 `{manifest, bars}` snapshot.
|
||||
The API validates retained content and identity before returning it; timestamps,
|
||||
availability delays, source ordinals, null values and any parent hash are preserved.
|
||||
This is identical dataset content, not a promise of original JSON formatting. The
|
||||
manifest hash is the canonical dataset identity, not a checksum of downloaded file bytes.
|
||||
|
||||
Open the file in VS Code or a notebook, or give it to your local AI exploration tools.
|
||||
For a quick TypeScript inspection with Bun:
|
||||
|
||||
```ts
|
||||
const dataset = await Bun.file('/path/to/dataset-<hash>.json').json();
|
||||
console.log(dataset.manifest);
|
||||
console.table(dataset.bars.slice(0, 5));
|
||||
```
|
||||
|
||||
Treat this as inspection of frozen observations, not validation of a trading hypothesis.
|
||||
When testing features, respect each bar's `availableAt`; the file includes the entire
|
||||
historical range, including observations unavailable to an earlier decision.
|
||||
|
||||
To retain the same file in another initialized research database, set
|
||||
`RESEARCH_DATASET_DATABASE_URL` explicitly to that database and use the existing importer:
|
||||
|
||||
```sh
|
||||
bun run scripts/import-research-dataset.ts --file '/path/to/dataset-<hash>.json'
|
||||
```
|
||||
|
||||
The importer validates the full snapshot and repeats safely for an already retained hash.
|
||||
This file is distinct from the source-input JSON accepted by **Prepare dataset from source
|
||||
export**; use the importer for the complete retained snapshot.
|
||||
|
||||
Export supports the existing eligible single-asset canonical dataset selection. Missing,
|
||||
corrupt and unsupported snapshots return an error instead of a file. A failed download
|
||||
offers **Retry dataset download**; changing the selected hash cancels the pending action.
|
||||
The endpoint is `GET /api/v2/datasets/canonical/:hash/export`, using existing read, operator,
|
||||
service or browser-session access. Research-agent tokens remain unable to call dataset
|
||||
routes; a user can supply the downloaded file to local tools explicitly.
|
||||
|
||||
## Verification
|
||||
|
||||
`bun run check` includes complete-range reads without row caps, acceptance beyond the
|
||||
former listing ceiling, immutable reuse, v1 hash compatibility, deterministic replay,
|
||||
invalid-data rejection and CPU cancellation. The disposable PostgreSQL/Redis suite
|
||||
additionally verifies tamper detection, cancellation rollback and lease/owner-loss replay.
|
||||
See the root README for safety-suite setup; never use development trading databases.
|
||||
310
design/data-pipeline/phase1-investigation.md
Normal file
310
design/data-pipeline/phase1-investigation.md
Normal file
|
|
@ -0,0 +1,310 @@
|
|||
# Phase 1 data-pipeline investigation
|
||||
|
||||
Full inventory run at **2026-11-26T08:29:35.173Z** against checkout `f8ca9b529bea0e1b6ab1f5ef73b79c2b1a29eb3b`. The inventory script was an uncommitted addition at that SHA. The run took **24.85 seconds** and peaked at **1,413 MiB RSS**.
|
||||
|
||||
Command `bun apps/stock/data-pipeline/scripts/phase1-inventory.ts > /tmp/p1.json` from the repository root. The private JSON contains the sampled key sets, index names, source excerpts, exact tallies and per-pair results. The report uses only the first full run for measured figures.
|
||||
|
||||
## a. Source inventory
|
||||
|
||||
The `stock` database contained **31 collections**. Source names start with lowercase provider prefixes followed by a camelCase entity name (`qm*`, `eod*`, `ib*`, `ceo*`, `te*`, `tt*`). No `XX_`-prefixed, TradingView, or Webshare collection was present. This describes persisted data; see [DATA-CONTRACTS.md](../DATA-CONTRACTS.md) for the canonical 31-collection contracts and adjustment rules.
|
||||
|
||||
The exact count column comes from `countDocuments({})` for collections whose estimate was below one million. A dash means the estimate was used. The inventory sampled top-level keys from up to 200 documents per collection. Large time-series and event collections had metadata and key samples only.
|
||||
|
||||
| Provider | Collection | Entity | Estimated documents | Exact documents | Indexes |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| ceo | `ceoExchanges` | exchange | 4 | 4 | 1 |
|
||||
| ceo | `ceoPosts` | other | 14,779,267 | — | 2 |
|
||||
| ceo | `ceoShorts` | other | 692,904 | 692,904 | 2 |
|
||||
| ceo | `ceoSymbols` | stock | 12,589 | 12,589 | 2 |
|
||||
| eod | `eodExchanges` | exchange | 76 | 76 | 1 |
|
||||
| eod | `eodFinancialsOLD` | other | 2,975,061 | — | 3 |
|
||||
| eod | `eodFundamentalsOLD` | other | 106,589 | 106,589 | 2 |
|
||||
| eod | `eodIntraday1H` | other | 110,450,096 | — | 4 |
|
||||
| eod | `eodIntraday1M` | other | 3,402,612,960 | — | 4 |
|
||||
| eod | `eodIntraday5M` | other | 1,075,367,880 | — | 4 |
|
||||
| eod | `eodPrices` | other | 845,701,704 | — | 4 |
|
||||
| eod | `eodSymbolChange` | other | 230 | 230 | 1 |
|
||||
| eod | `eodSymbols` | stock | 317,807 | 317,807 | 41 |
|
||||
| ib | `ibExchanges` | exchange | 214 | 214 | 1 |
|
||||
| ib | `ibSymbols` | stock | 18,402 | 18,402 | 1 |
|
||||
| qm | `qmDividends` | other | 495,942 | 495,942 | 2 |
|
||||
| qm | `qmEarnings` | other | 444,865 | 444,865 | 2 |
|
||||
| qm | `qmExchanges` | exchange | 25 | 25 | 1 |
|
||||
| qm | `qmFilings` | other | 30,521,360 | — | 2 |
|
||||
| qm | `qmFinancials` | other | 1,864,342 | — | 2 |
|
||||
| qm | `qmFinancials-old` | other | 907,764 | 907,764 | 4 |
|
||||
| qm | `qmIntraday` | other | 173,281,224 | — | 2 |
|
||||
| qm | `qmPrices` | other | 51,524,772 | — | 2 |
|
||||
| qm | `qmSplits` | other | 18,751 | 18,751 | 2 |
|
||||
| qm | `qmSymbols` | stock | 47,243 | 47,243 | 60 |
|
||||
| te | `teCountries` | country | 197 | 197 | 1 |
|
||||
| te | `teData` | country | 14,794 | 14,794 | 3 |
|
||||
| te | `teIndicators` | country | 163 | 163 | 1 |
|
||||
| te | `teMarketData` | country | 435 | 435 | 3 |
|
||||
| te | `teUrls` | other | 2,424,784 | — | 8 |
|
||||
| tt | `ttFutures` | other | 1,460,406 | — | 4 |
|
||||
|
||||
### Identifier coverage
|
||||
|
||||
Cells show filled records and percentages within the full collection. Coverage measures nonempty values, including values later rejected by identifier validation. The JSON records the tested field aliases, including EOD `eodExchange` before `Exchange`, IB `localSymbol` before `symbol`, and QM profile and symbol-info paths. Country and other collections are inventoried as their own entity types. The stock/exchange identifier pass is confined to the eight collections below.
|
||||
|
||||
| Collection | Records | Ticker | Exchange code | ISIN | FIGI | CUSIP | Name | Country | Currency |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| `ceoExchanges` | 4 | 0 (0.00%) | 4 (100.00%) | 0 (0.00%) | 0 (0.00%) | 0 (0.00%) | 0 (0.00%) | 4 (100.00%) | 0 (0.00%) |
|
||||
| `ceoSymbols` | 12,589 | 12,589 (100.00%) | 12,589 (100.00%) | 0 (0.00%) | 0 (0.00%) | 0 (0.00%) | 12,560 (99.77%) | 0 (0.00%) | 0 (0.00%) |
|
||||
| `eodExchanges` | 76 | 0 (0.00%) | 76 (100.00%) | 0 (0.00%) | 0 (0.00%) | 0 (0.00%) | 76 (100.00%) | 76 (100.00%) | 76 (100.00%) |
|
||||
| `eodSymbols` | 317,807 | 317,807 (100.00%) | 317,807 (100.00%) | 196,833 (61.93%) | 0 (0.00%) | 0 (0.00%) | 317,807 (100.00%) | 317,807 (100.00%) | 317,807 (100.00%) |
|
||||
| `ibExchanges` | 214 | 0 (0.00%) | 214 (100.00%) | 0 (0.00%) | 0 (0.00%) | 0 (0.00%) | 214 (100.00%) | 214 (100.00%) | 0 (0.00%) |
|
||||
| `ibSymbols` | 18,402 | 18,402 (100.00%) | 18,402 (100.00%) | 18,402 (100.00%) | 0 (0.00%) | 18,399 (99.98%) | 18,402 (100.00%) | 18,402 (100.00%) | 18,376 (99.86%) |
|
||||
| `qmExchanges` | 25 | 0 (0.00%) | 25 (100.00%) | 0 (0.00%) | 0 (0.00%) | 0 (0.00%) | 25 (100.00%) | 25 (100.00%) | 0 (0.00%) |
|
||||
| `qmSymbols` | 47,243 | 47,243 (100.00%) | 47,243 (100.00%) | 0 (0.00%) | 0 (0.00%) | 0 (0.00%) | 47,243 (100.00%) | 47,243 (100.00%) | 0 (0.00%) |
|
||||
|
||||
Supplemental identifiers and ranking fields
|
||||
|
||||
| Collection | Field | Filled |
|
||||
| --- | --- | --- |
|
||||
| `ceoExchanges` | `mic` | 0 (0.00%) |
|
||||
| `eodExchanges` | `mic` | 73 (96.05%) |
|
||||
| `ibExchanges` | `mic` | 0 (0.00%) |
|
||||
| `ibSymbols` | `conid` | 18,402 (100.00%) |
|
||||
| `qmExchanges` | `mic` | 0 (0.00%) |
|
||||
| `qmExchanges` | `priority` | 25 (100.00%) |
|
||||
|
||||
### Example documents
|
||||
|
||||
The excerpts below preserve real document IDs and selected fields. The full JSON trims nested objects and arrays and retains more of each record.
|
||||
|
||||
**Exchange**
|
||||
|
||||
`ceoExchanges`
|
||||
`{"_id": "685824287a995922a6f9b0e3", "exchange": "TSX", "countryCode": "CA"}`
|
||||
|
||||
`ceoExchanges`
|
||||
`{"_id": "685824287a995922a6f9b0e4", "exchange": "CDX", "countryCode": "CA"}`
|
||||
|
||||
**Other**
|
||||
|
||||
`ceoPosts`
|
||||
`{"_id": "68584d967a995922a6fa97d3", "spielId": "2875b3d77a40", "ceoId": "BGF", "timestamp": 1744193045999, "score": 1, "votes": 1}`
|
||||
|
||||
`ceoPosts`
|
||||
`{"_id": "68584d967a995922a6fa97d4", "spielId": "ef70832d6c62", "ceoId": "BGF", "timestamp": 1744290036418, "score": 7, "votes": 7}`
|
||||
|
||||
**Stock**
|
||||
|
||||
`ceoSymbols`
|
||||
`{"_id": "685824287a995922a6f9b0b3", "symbol": "1689.TO", "exchange": "TSX", "name": "WisdomTree Natural Gas", "type": "company", "stockType": null, "marketCap": null}`
|
||||
|
||||
`ceoSymbols`
|
||||
`{"_id": "685824287a995922a6f9b0b4", "symbol": "A.V", "exchange": "CDX", "name": "Armor Minerals Inc.", "type": "company", "stockType": null, "marketCap": 34481079.45}`
|
||||
|
||||
**Country**
|
||||
|
||||
`teCountries`
|
||||
`{"_id": "69cdcbe61d0a0362a5e5d120", "slug": "united-states", "name": "United States", "url": "/united-states"}`
|
||||
|
||||
`teCountries`
|
||||
`{"_id": "69cdcbe61d0a0362a5e5d121", "slug": "united-kingdom", "name": "United Kingdom", "url": "/united-kingdom"}`
|
||||
|
||||
### MongoDB access and repeatability
|
||||
|
||||
The planning run reported only `trading_admin` with `root@admin`. Fresh `usersInfo` queries on `admin` and `stock` returned both accounts below.
|
||||
|
||||
| User | Authentication database | Roles |
|
||||
| --- | --- | --- |
|
||||
| `trading_admin` | admin | `root@admin` |
|
||||
| `studio_stock_bot_read` | stock | `read@stock` |
|
||||
|
||||
The live result was **`readOnlyUserExists = true`**. The configured account was used for the two `usersInfo` calls. The pre-existing read-only account was used for collection reads. This investigation created no database users and made no database writes.
|
||||
|
||||
Collection names, complete index definitions and user roles were identical before and after the read-only checks. The estimates were also identical. No collection-level count drift was observed during the verification window.
|
||||
|
||||
The second full run returned identical match tallies and tricky-case excerpts. Random field-key samples may differ on repeat runs. Independent mongosh checks matched five collection estimates and all fixture references. A separate psql read-only transaction matched all five inventory table counts.
|
||||
|
||||
## b. Existing mapping UI, data, and merge rules
|
||||
|
||||
The exchange screen lists existing exchange mappings, displays their status and lets a user add or edit a provider exchange mapping. The pipeline screen starts sync operations and presents counts. The symbol screens browse and filter records. Repository search found no symbol-level mapping editor. Within the application code, the symbol sync paths own writes to `provider_mappings`; the separately exposed pipeline reset can clear the table.
|
||||
|
||||
**Exchange mapping UI**
|
||||
|
||||
- [`apps/stock/web-app/src/features/exchanges/ExchangesPage.tsx`](../../apps/stock/web-app/src/features/exchanges/ExchangesPage.tsx)
|
||||
- [`apps/stock/web-app/src/features/exchanges/components/AddProviderMappingDialog.tsx`](../../apps/stock/web-app/src/features/exchanges/components/AddProviderMappingDialog.tsx)
|
||||
- [`apps/stock/web-app/src/features/exchanges/components/ExchangesTable.tsx`](../../apps/stock/web-app/src/features/exchanges/components/ExchangesTable.tsx)
|
||||
- [`apps/stock/web-app/src/features/exchanges/services/exchangeApi.ts`](../../apps/stock/web-app/src/features/exchanges/services/exchangeApi.ts)
|
||||
|
||||
**Pipeline and symbol screens**
|
||||
|
||||
- [`apps/stock/web-app/src/features/pipeline/PipelinePage.tsx`](../../apps/stock/web-app/src/features/pipeline/PipelinePage.tsx)
|
||||
- [`apps/stock/web-app/src/features/pipeline/services/pipelineApi.ts`](../../apps/stock/web-app/src/features/pipeline/services/pipelineApi.ts)
|
||||
- [`apps/stock/web-app/src/features/symbols/SymbolsPage.tsx`](../../apps/stock/web-app/src/features/symbols/SymbolsPage.tsx)
|
||||
- [`apps/stock/web-app/src/features/symbols/SymbolDetailPage.tsx`](../../apps/stock/web-app/src/features/symbols/SymbolDetailPage.tsx)
|
||||
|
||||
**Web API**
|
||||
|
||||
- [`apps/stock/web-api/src/routes/exchange.routes.ts`](../../apps/stock/web-api/src/routes/exchange.routes.ts)
|
||||
- [`apps/stock/web-api/src/routes/pipeline.routes.ts`](../../apps/stock/web-api/src/routes/pipeline.routes.ts)
|
||||
- [`apps/stock/web-api/src/services/exchange.service.ts`](../../apps/stock/web-api/src/services/exchange.service.ts)
|
||||
- [`apps/stock/web-api/src/services/pipeline.service.ts`](../../apps/stock/web-api/src/services/pipeline.service.ts)
|
||||
|
||||
Exchange routes include `GET /provider-mappings/all`, `GET /provider-mappings/:provider`, `PATCH /provider-mappings/:id`, `POST /provider-mappings`, `GET /provider-exchanges/unmapped/:provider`, and `GET /stats/summary` under the exchanges prefix. Pipeline routes include `POST /symbols/:provider`, `POST /provider-mappings/qm`, `POST /provider-mappings/ib`, and `GET /stats/provider-mappings` under the pipeline prefix. The inventory invoked no API endpoints.
|
||||
|
||||
**Postgres storage and visibility**
|
||||
|
||||
- [`database/postgres/init/02-master-schema.sql`](../../database/postgres/init/02-master-schema.sql)
|
||||
- [`database/postgres/init/04-provider-exchange-mapping-schema.sql`](../../database/postgres/init/04-provider-exchange-mapping-schema.sql)
|
||||
- [`database/postgres/init/05-add-visible-column.sql`](../../database/postgres/init/05-add-visible-column.sql)
|
||||
|
||||
`exchanges` and `symbols` hold canonical records, keyed by exchange code and by ticker plus exchange ID respectively. `provider_exchange_mappings` links provider codes to exchange UUIDs and allows unresolved mappings. `provider_mappings` links provider symbols to canonical symbol UUIDs. `sync_status` records provider and operation status. The visibility flag affects which exchanges the UI and summary show. The live check used `to_regclass` before selecting each table.
|
||||
|
||||
| Table | Rows |
|
||||
| --- | --- |
|
||||
| `exchanges` | 301 |
|
||||
| `symbols` | 0 |
|
||||
| `provider_mappings` | 0 |
|
||||
| `provider_exchange_mappings` | 313 |
|
||||
| `sync_status` | 3 |
|
||||
| `master_exchanges` | missing |
|
||||
| `master_symbols` | missing |
|
||||
| `provider_symbol_mappings` | missing |
|
||||
|
||||
The plan’s names `master_exchanges`, `master_symbols` and `provider_symbol_mappings` are absent from the live Postgres schema. As separately inventoried in section a, the Mongo sources are the provider collections, and the legacy IB handler’s `masterExchanges` collection was also absent from this snapshot.
|
||||
|
||||
| Provider | Has exchange UUID | Verified | Active | Auto mapped | Rows |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| eod | yes | no | no | no | 2 |
|
||||
| eod | yes | no | no | yes | 72 |
|
||||
| eod | yes | no | yes | no | 2 |
|
||||
| ib | yes | no | no | no | 1 |
|
||||
| ib | yes | no | no | yes | 186 |
|
||||
| qm | yes | no | no | yes | 26 |
|
||||
| qm | yes | no | yes | no | 1 |
|
||||
| unified | yes | no | no | yes | 22 |
|
||||
| unified | yes | no | yes | no | 1 |
|
||||
|
||||
The symbol-mapping counts by provider and verification and the confidence histogram are both empty because `provider_mappings` contains zero rows.
|
||||
|
||||
### Existing field and source precedence
|
||||
|
||||
- **Provider normalization**. Uses the first populated ticker of `symbol`, `code`, and `Code`, and the first populated exchange of `exchangeCode`, `exchange`, `exchange_id`, and `Exchange`. It chooses a provider search code, name, country and currency by field precedence. This code does not read `exchangeId`, the live IB symbol spelling. It defines field precedence rather than a source ranking. [`apps/stock/data-pipeline/src/normalization/provider-symbol.ts`](../../apps/stock/data-pipeline/src/normalization/provider-symbol.ts)
|
||||
- **Generic provider symbol sync**. Supports QM, EOD and IB; normalizes the relevant Mongo source and sends each record to the shared repository. [`apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations.ts`](../../apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations.ts)
|
||||
- **Shared SQL sync**. Requires an exact active mapped exchange and matches symbols on ticker plus exchange UUID. Non-null incoming name, country and currency can replace existing values. Verified provider-symbol links retain their symbol and exchange assignments in this path; last-seen timestamps advance. Exchange mapping uses exact code and preserves existing conflicts rather than scoring candidates across sources. [`apps/stock/data-pipeline/src/repositories/PipelineSyncRepository.ts`](../../apps/stock/data-pipeline/src/repositories/PipelineSyncRepository.ts)
|
||||
- **Dedicated QM symbol sync**. Has a fixed exchange-code translation map, a ticker and exchange lookup, and non-null field precedence for name, country and currency. It has its own provider mapping SQL and does not share the verified-link protection in the common repository. [`apps/stock/data-pipeline/src/handlers/symbols/operations/qm-symbols.operations.ts`](../../apps/stock/data-pipeline/src/handlers/symbols/operations/qm-symbols.operations.ts)
|
||||
- **QM exchange mapping sync**. Groups provider exchange codes, supplies name and country, infers CAD for Canada and USD otherwise, and calls the SQL repository with 0.80 confidence. [`apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-qm-provider-mappings.operations.ts`](../../apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-qm-provider-mappings.operations.ts)
|
||||
- **Dedicated QM exchange sync**. Processes QM exchange records through its own SQL path, with exchange lookup and metadata handling. [`apps/stock/data-pipeline/src/handlers/exchanges/operations/qm-exchanges.operations.ts`](../../apps/stock/data-pipeline/src/handlers/exchanges/operations/qm-exchanges.operations.ts)
|
||||
- **Legacy IB exchange sync**. Builds an IB-derived canonical exchange identifier and aliases and targets the Mongo collection `masterExchanges`. Its new records mark the direct IB mapping verified at 1.00 confidence, independent of the live SQL mapping flags. That code path was inspected only. [`apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts`](../../apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts)
|
||||
- **QM ingestion deduplication**. Sets `qmExchanges.priority` from a hard-coded venue list. Within a ticker and country, it prefers a bare QM search code in the US and `symbol:COUNTRY` elsewhere. If neither is present it chooses exchange priority, then market cap, and uses the result to set active flags. This ranks listings inside QM, rather than sources against one another. [`apps/stock/data-ingestion/src/handlers/qm/actions/symbol-dedup.action.ts`](../../apps/stock/data-ingestion/src/handlers/qm/actions/symbol-dedup.action.ts)
|
||||
|
||||
The canonical symbol storage lacks ISIN and FIGI columns, per-field provenance, a match-review queue and a separate country entity. The current symbol and exchange sync paths provide no CEO, TE or TT mappings. The existing code and data support listing and manual exchange mapping by provider, not a general cross-provider merge policy.
|
||||
|
||||
## c. Cross-source matching
|
||||
|
||||
Each source record is counted once across the other providers. Strong means a shared checksum-valid ISIN, a nine-character CUSIP (including the embedded value of valid US and Canadian ISINs), or a 12-character FIGI when supplied. The effective FIGI input was empty. Weak-only means no strong match and either the same ticker and mapped exchange UUID or the same ticker and currency with name token Jaccard ≥ 0.8. Both records require an existing non-null exchange mapping for either weak heuristic. These are candidate links and measured overlaps, not confirmed entity identity.
|
||||
|
||||
| Provider | Projected records | Strong | Weak only | Unmatched | Exact weak | Normalized weak |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| qm | 47,243 | 0 | 976 | 46,267 | 913 | 976 |
|
||||
| eod | 317,807 | 21,200 | 2,710 | 293,897 | 2,452 | 2,710 |
|
||||
| ib | 18,402 | 14,216 | 1,555 | 2,631 | 1,351 | 1,555 |
|
||||
| ceo | 12,589 | 0 | 0 | 12,589 | 0 | 0 |
|
||||
|
||||
Exact weak uses the trimmed raw ticker. Normalized weak also folds case, strips known venue affixes such as `.US` and `:NASDAQ`, and canonicalizes one-letter share classes across dot, dash, slash and whitespace forms. The two weak columns overlap. Their union is the weak-only classification. Each rule occurrence is recorded in the JSON.
|
||||
|
||||
| Provider | Missing exchange code | No mapping row | Mapping has null master | Has master |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| qm | 0 | 0 | 0 | 47,243 |
|
||||
| eod | 0 | 9,845 | 0 | 307,962 |
|
||||
| ib | 0 | 0 | 0 | 18,402 |
|
||||
| ceo | 0 | 12,589 | 0 | 0 |
|
||||
|
||||
| Provider | Observed normalization rules |
|
||||
| --- | --- |
|
||||
| qm | `share_class_dot` 1,298, `share_class_separator` 2 |
|
||||
| eod | `case` 1,727, `share_class_dot` 2,561, `share_class_separator` 2,561 |
|
||||
| ib | `share_class_dot` 579, `share_class_separator` 45 |
|
||||
| ceo | `share_class_dot` 3,105 |
|
||||
|
||||
The pair counts are directed and count records in the source on the left. A record can appear in more than one pair.
|
||||
|
||||
| Pair | Projected records | Strong | Weak only | Unmatched | Exact weak | Normalized weak |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| qm→eod | 47,243 | 0 | 712 | 46,531 | 650 | 712 |
|
||||
| qm→ib | 47,243 | 0 | 264 | 46,979 | 263 | 264 |
|
||||
| qm→ceo | 47,243 | 0 | 0 | 47,243 | 0 | 0 |
|
||||
| eod→qm | 317,807 | 0 | 712 | 317,095 | 650 | 712 |
|
||||
| eod→ib | 317,807 | 21,200 | 2,620 | 293,987 | 2,398 | 2,620 |
|
||||
| eod→ceo | 317,807 | 0 | 0 | 317,807 | 0 | 0 |
|
||||
| ib→qm | 18,402 | 0 | 264 | 18,138 | 263 | 264 |
|
||||
| ib→eod | 18,402 | 14,216 | 1,546 | 2,640 | 1,342 | 1,546 |
|
||||
| ib→ceo | 18,402 | 0 | 0 | 18,402 | 0 | 0 |
|
||||
| ceo→qm | 12,589 | 0 | 0 | 12,589 | 0 | 0 |
|
||||
| ceo→eod | 12,589 | 0 | 0 | 12,589 | 0 | 0 |
|
||||
| ceo→ib | 12,589 | 0 | 0 | 12,589 | 0 | 0 |
|
||||
|
||||
### Exchange codes
|
||||
|
||||
The denominator is distinct nonempty exchange codes per source after case and whitespace normalization. A non-null explicit SQL mapping counts as strong, split into verified, otherwise auto-mapped, and other. The instrument heuristic for unresolved exchanges uses an exact non-placeholder OperatingMIC or country and name token agreement. A SQL mapping may point to an exchange with no equivalent code in the other Mongo sources.
|
||||
|
||||
| Provider | Distinct codes | Mapped / strong | Verified | Auto | Other mapped | Cross-source only | Unmatched |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| qm | 25 | 25 | 0 | 24 | 1 | 0 | 0 |
|
||||
| eod | 76 | 73 | 0 | 69 | 4 | 0 | 3 |
|
||||
| ib | 188 | 187 | 0 | 186 | 1 | 0 | 1 |
|
||||
| ceo | 4 | 0 | 0 | 0 | 0 | 0 | 4 |
|
||||
|
||||
### Tricky cases
|
||||
|
||||
The deterministic selection produced **25 candidates** across 5 buckets. The same record pair can qualify for more than one bucket. The script sorts by identifier or ticker, then source and document ID, and keeps up to five per bucket. No cross-source candidate shared both ticker and mapped exchange while carrying two distinct valid ISINs.
|
||||
|
||||
| Bucket | Candidate key | Source document excerpts |
|
||||
| --- | --- | --- |
|
||||
| `isin_currency_or_country_conflict` | `AGP8696W1045` | `eodSymbols/6870729a89b14ad0b4a7fc48` · Code=SVQ, eodSearchCode=SVQ.F, eodExchange=F, Exchange=F, Isin=AGP8696W1045, Country=Germany, Currency=EUR · master `d9df353b-dae0-43c1-b722-1a0a043d38d2` <br> `ibSymbols/684cd228ba15394e9c03cafd` · symbol=SVA, localSymbol=SVA, exchangeId=NASDAQ, isin=AGP8696W1045, cusip=P8696W104, country=US, currency=USD · master `17eaa972-fac5-4701-8c51-61fe61287820` |
|
||||
| `isin_currency_or_country_conflict` | `AN8068571086` | `eodSymbols/6870729a89b14ad0b4a7f07b` · Code=SLB, eodSearchCode=SLB.PA, eodExchange=PA, Exchange=PA, Isin=AN8068571086, Country=France, Currency=EUR · master `4b186932-19e2-4151-8728-6c9f3469260c` <br> `ibSymbols/684cd226ba15394e9c03c7f9` · symbol=SLB, localSymbol=SLB, exchangeId=EDGX, isin=AN8068571086, cusip=806857108, country=US, currency=USD · master `34c0796c-8d15-434c-9c87-806b062327f3` |
|
||||
| `isin_currency_or_country_conflict` | `AU000000AGD4` | `eodSymbols/6870729f89b14ad0b4a9e61d` · Code=AGD, eodSearchCode=AGD.AU, eodExchange=AU, Exchange=AU, Isin=AU000000AGD4, Country=Australia, Currency=AUD · master `84fe59d5-8228-4e13-b70e-1f507b6597eb` <br> `ibSymbols/684cd08bba15394e9c038dda` · symbol=AGLD, localSymbol=AGLD, exchangeId=AEQLIT, isin=AU000000AGD4, cusip=Q0819E102, country=CA, currency=CAD · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
| `isin_currency_or_country_conflict` | `AU000000CIA2` | `eodSymbols/6870729b89b14ad0b4a83e5f` · Code=MMPI, eodSearchCode=MMPI.F, eodExchange=F, Exchange=F, Isin=AU000000CIA2, Country=Germany, Currency=EUR · master `d9df353b-dae0-43c1-b722-1a0a043d38d2` <br> `ibSymbols/684cd213ba15394e9c039ad2` · symbol=CIA, localSymbol=CIA, exchangeId=AEQLIT, isin=AU000000CIA2, cusip=Q22964102, country=CA, currency=CAD · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
| `isin_currency_or_country_conflict` | `AU000000CY57` | `eodSymbols/6870729f89b14ad0b4a9eeef` · Code=CY5, eodSearchCode=CY5.AU, eodExchange=AU, Exchange=AU, Isin=AU000000CY57, Country=Australia, Currency=AUD · master `84fe59d5-8228-4e13-b70e-1f507b6597eb` <br> `ibSymbols/684cd214ba15394e9c039eaa` · symbol=CYG, localSymbol=CYG, exchangeId=VENTURE, isin=AU000000CY57, cusip=Q3080P103, country=CA, currency=CAD · master `bb86f438-d8c1-40b5-ad03-897274de6377` |
|
||||
| `isin_ticker_variation` | `AGP8696W1045` | `eodSymbols/6870729a89b14ad0b4a7fc48` · Code=SVQ, eodSearchCode=SVQ.F, eodExchange=F, Exchange=F, Isin=AGP8696W1045, Country=Germany, Currency=EUR · master `d9df353b-dae0-43c1-b722-1a0a043d38d2` <br> `ibSymbols/684cd228ba15394e9c03cafd` · symbol=SVA, localSymbol=SVA, exchangeId=NASDAQ, isin=AGP8696W1045, cusip=P8696W104, country=US, currency=USD · master `17eaa972-fac5-4701-8c51-61fe61287820` |
|
||||
| `isin_ticker_variation` | `AN8068571086` | `eodSymbols/6870729a89b14ad0b4a804dc` · Code=SCL, eodSearchCode=SCL.STU, eodExchange=STU, Exchange=STU, Isin=AN8068571086, Country=Germany, Currency=EUR · master `6b1ed995-47c4-4e8a-98a8-eefdb1513189` <br> `ibSymbols/684cd226ba15394e9c03c7f9` · symbol=SLB, localSymbol=SLB, exchangeId=EDGX, isin=AN8068571086, cusip=806857108, country=US, currency=USD · master `34c0796c-8d15-434c-9c87-806b062327f3` |
|
||||
| `isin_ticker_variation` | `AU000000AGD4` | `eodSymbols/6870729f89b14ad0b4a9e61d` · Code=AGD, eodSearchCode=AGD.AU, eodExchange=AU, Exchange=AU, Isin=AU000000AGD4, Country=Australia, Currency=AUD · master `84fe59d5-8228-4e13-b70e-1f507b6597eb` <br> `ibSymbols/684cd08bba15394e9c038dda` · symbol=AGLD, localSymbol=AGLD, exchangeId=AEQLIT, isin=AU000000AGD4, cusip=Q0819E102, country=CA, currency=CAD · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
| `isin_ticker_variation` | `AU000000CIA2` | `eodSymbols/6870729b89b14ad0b4a83e5f` · Code=MMPI, eodSearchCode=MMPI.F, eodExchange=F, Exchange=F, Isin=AU000000CIA2, Country=Germany, Currency=EUR · master `d9df353b-dae0-43c1-b722-1a0a043d38d2` <br> `ibSymbols/684cd213ba15394e9c039ad2` · symbol=CIA, localSymbol=CIA, exchangeId=AEQLIT, isin=AU000000CIA2, cusip=Q22964102, country=CA, currency=CAD · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
| `isin_ticker_variation` | `AU000000CY57` | `eodSymbols/6870729f89b14ad0b4a9eeef` · Code=CY5, eodSearchCode=CY5.AU, eodExchange=AU, Exchange=AU, Isin=AU000000CY57, Country=Australia, Currency=AUD · master `84fe59d5-8228-4e13-b70e-1f507b6597eb` <br> `ibSymbols/684cd214ba15394e9c039eaa` · symbol=CYG, localSymbol=CYG, exchangeId=VENTURE, isin=AU000000CY57, cusip=Q3080P103, country=CA, currency=CAD · master `bb86f438-d8c1-40b5-ad03-897274de6377` |
|
||||
| `share_class_format` | `AAA.P` | `eodSymbols/6870729789b14ad0b4a719de` · Code=AAA-P, eodSearchCode=AAA-P.V, eodExchange=V, Exchange=V, Country=Canada, Currency=CAD · master `c4d21513-3671-4187-9f87-1a8138b39a33` <br> `ibSymbols/684cd08bba15394e9c038c1a` · symbol=AAA.P, localSymbol=AAA.P, exchangeId=VENTURE, isin=CA33719F1099, cusip=33719F109, country=CA, currency=CAD · master `bb86f438-d8c1-40b5-ad03-897274de6377` |
|
||||
| `share_class_format` | `AAAJ.P` | `eodSymbols/6870729789b14ad0b4a72085` · Code=AAAJ-P, eodSearchCode=AAAJ-P.V, eodExchange=V, Exchange=V, Country=Canada, Currency=CAD · master `c4d21513-3671-4187-9f87-1a8138b39a33` <br> `ibSymbols/684cd08bba15394e9c038c1b` · symbol=AAAJ.P, localSymbol=AAAJ.P, exchangeId=AEQLIT, isin=CA00036L1013, cusip=00036L101, country=CA, currency=CAD · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
| `share_class_format` | `AACT.U` | `ibSymbols/684cd08bba15394e9c038c28` · symbol=AACT U, localSymbol=AACT U, exchangeId=PSX, isin=KYG330331128, cusip=G33033112, country=US, currency=USD · master `48898e5f-0749-47c6-9832-2af991768477` <br> `qmSymbols/685f48529aba109fcce7be10` · symbol=AACT.U, qmSearchCode=AACT.U:EGX, exchange=EDGX, countryCode=US · master `34c0796c-8d15-434c-9c87-806b062327f3` |
|
||||
| `share_class_format` | `AAM.U` | `ibSymbols/684cd08bba15394e9c038c38` · symbol=AAM U, localSymbol=AAM U, exchangeId=IBEOS, isin=KYG1000R1193, cusip=G1000R119, country=US, currency=USD · master `d0209689-cbe9-4258-919a-7f6cd73db322` <br> `qmSymbols/685f484f9aba109fcce7b6ba` · symbol=AAM.U, qmSearchCode=AAM.U, exchange=NYE, countryCode=US · master `662967e1-3293-4a40-bbd3-297f200c156a` |
|
||||
| `share_class_format` | `ACAP.P` | `eodSymbols/6870729789b14ad0b4a719e6` · Code=ACAP-P, eodSearchCode=ACAP-P.V, eodExchange=V, Exchange=V, Country=Canada, Currency=CAD · master `c4d21513-3671-4187-9f87-1a8138b39a33` <br> `ibSymbols/684cd08bba15394e9c038ca6` · symbol=ACAP.P, localSymbol=ACAP.P, exchangeId=VENTURE, isin=CA04941B1094, cusip=04941B109, country=CA, currency=CAD · master `bb86f438-d8c1-40b5-ad03-897274de6377` |
|
||||
| `dual_master_exchanges` | `AGP8696W1045` | `eodSymbols/6870729a89b14ad0b4a7fc48` · Code=SVQ, eodSearchCode=SVQ.F, eodExchange=F, Exchange=F, Isin=AGP8696W1045, Country=Germany, Currency=EUR · master `d9df353b-dae0-43c1-b722-1a0a043d38d2` <br> `ibSymbols/684cd228ba15394e9c03cafd` · symbol=SVA, localSymbol=SVA, exchangeId=NASDAQ, isin=AGP8696W1045, cusip=P8696W104, country=US, currency=USD · master `17eaa972-fac5-4701-8c51-61fe61287820` |
|
||||
| `dual_master_exchanges` | `AN8068571086` | `eodSymbols/6870729a89b14ad0b4a7f07b` · Code=SLB, eodSearchCode=SLB.PA, eodExchange=PA, Exchange=PA, Isin=AN8068571086, Country=France, Currency=EUR · master `4b186932-19e2-4151-8728-6c9f3469260c` <br> `ibSymbols/684cd226ba15394e9c03c7f9` · symbol=SLB, localSymbol=SLB, exchangeId=EDGX, isin=AN8068571086, cusip=806857108, country=US, currency=USD · master `34c0796c-8d15-434c-9c87-806b062327f3` |
|
||||
| `dual_master_exchanges` | `AU000000AGD4` | `eodSymbols/6870729789b14ad0b4a719fc` · Code=AGLD, eodSearchCode=AGLD.V, eodExchange=V, Exchange=V, Isin=AU000000AGD4, Country=Canada, Currency=CAD · master `c4d21513-3671-4187-9f87-1a8138b39a33` <br> `ibSymbols/684cd08bba15394e9c038dda` · symbol=AGLD, localSymbol=AGLD, exchangeId=AEQLIT, isin=AU000000AGD4, cusip=Q0819E102, country=CA, currency=CAD · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
| `dual_master_exchanges` | `AU000000CIA2` | `eodSymbols/6870729889b14ad0b4a723d9` · Code=CIA, eodSearchCode=CIA.TO, eodExchange=TO, Exchange=TO, Isin=AU000000CIA2, Country=Canada, Currency=CAD · master `54a5f743-5dde-4de2-a0f9-0a11bc517a73` <br> `ibSymbols/684cd213ba15394e9c039ad2` · symbol=CIA, localSymbol=CIA, exchangeId=AEQLIT, isin=AU000000CIA2, cusip=Q22964102, country=CA, currency=CAD · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
| `dual_master_exchanges` | `AU000000CY57` | `eodSymbols/6870729f89b14ad0b4a9eeef` · Code=CY5, eodSearchCode=CY5.AU, eodExchange=AU, Exchange=AU, Isin=AU000000CY57, Country=Australia, Currency=AUD · master `84fe59d5-8228-4e13-b70e-1f507b6597eb` <br> `ibSymbols/684cd214ba15394e9c039eaa` · symbol=CYG, localSymbol=CYG, exchangeId=VENTURE, isin=AU000000CY57, cusip=Q3080P103, country=CA, currency=CAD · master `bb86f438-d8c1-40b5-ad03-897274de6377` |
|
||||
| `invalid_isin` | `CA00149WBAD4` | `ibSymbols/684cd212ba15394e9c038fd5` · symbol=AIP.U.BAD, localSymbol=AIP.U.BAD, exchangeId=AEQLIT, isin=CA00149WBAD4, cusip=00149WBAD, country=CA, currency=CAD · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
| `invalid_isin` | `CA45175CBAD7` | `ibSymbols/684cd218ba15394e9c03ae3f` · symbol=IKNK.BADN, localSymbol=IKNK.BAD.NEW, exchangeId=AEQLIT, isin=CA45175CBAD7, cusip=45175CBAD, country=CA · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
| `invalid_isin` | `CA52886N1024` | `eodSymbols/6870729d89b14ad0b4a91247` · Code=LEXXW, eodSearchCode=LEXXW.US, eodExchange=US, Exchange=NASDAQ, Isin=CA52886N1024, Country=USA, Currency=USD · master `c6aebb89-82fb-403e-9e82-2cae8068bf55` |
|
||||
| `invalid_isin` | `CA8131391062` | `ibSymbols/684cd225ba15394e9c03c664` · symbol=SCU.UN, localSymbol=SCU.UN.NEW, exchangeId=TSE, isin=CA8131391062, cusip=813139106, country=CA · master `d8272e91-5cd3-4a74-ba38-f77d527b5b8d` |
|
||||
| `invalid_isin` | `CATSETEST001` | `ibSymbols/684cd230ba15394e9c03d587` · symbol=ZYZ.A, localSymbol=ZYZ.A, exchangeId=AEQLIT, isin=CATSETEST001, cusip=TSETEST00, country=CA, currency=CAD · master `e09270dd-a099-4e96-9dce-7b52820352b9` |
|
||||
|
||||
## d. Stack and conventions
|
||||
|
||||
- **Runtime and workspace**. Bun workspaces and Turbo tasks drive package orchestration.
|
||||
[`package.json`](../../package.json) · [`turbo.json`](../../turbo.json) · [`bunfig.toml`](../../bunfig.toml)
|
||||
- **Query layer**. The Postgres library uses `pg` and raw SQL. The pipeline repository follows that pattern and uses transaction helpers. There is no ORM in this layer.
|
||||
[`libs/data/postgres/package.json`](../../libs/data/postgres/package.json) · [`libs/data/postgres/src/client.ts`](../../libs/data/postgres/src/client.ts) · [`libs/data/postgres/src/transactions.ts`](../../libs/data/postgres/src/transactions.ts) · [`apps/stock/data-pipeline/src/repositories/PipelineSyncRepository.ts`](../../apps/stock/data-pipeline/src/repositories/PipelineSyncRepository.ts)
|
||||
- **Schema changes**. Numbered SQL files are mounted into the Postgres container’s init directory. This is container initialization, so changes to an already initialized volume need a separate application decision. The Studio migration skill refers to Studio’s own Drizzle schema and does not describe this repository.
|
||||
[`docker-compose.yml`](../../docker-compose.yml) · [`database/postgres/init/02-master-schema.sql`](../../database/postgres/init/02-master-schema.sql) · [`database/postgres/init/04-provider-exchange-mapping-schema.sql`](../../database/postgres/init/04-provider-exchange-mapping-schema.sql) · [`database/postgres/init/05-add-visible-column.sql`](../../database/postgres/init/05-add-visible-column.sql)
|
||||
- **Queue and handlers**. The workspace queue and handler libraries provide registration, job dispatch, scheduled operations and metrics. The pipeline registers exchange and symbol handlers.
|
||||
[`libs/core/queue/src/queue-manager.ts`](../../libs/core/queue/src/queue-manager.ts) · [`libs/core/handlers/src/index.ts`](../../libs/core/handlers/src/index.ts) · [`apps/stock/data-pipeline/src/handlers/index.ts`](../../apps/stock/data-pipeline/src/handlers/index.ts) · [`apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts`](../../apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler.ts) · [`apps/stock/data-pipeline/src/handlers/symbols/symbols.handler.ts`](../../apps/stock/data-pipeline/src/handlers/symbols/symbols.handler.ts)
|
||||
- **HTTP API**. Hono routers delegate to services.
|
||||
[`apps/stock/web-api/package.json`](../../apps/stock/web-api/package.json) · [`apps/stock/web-api/src/routes/exchange.routes.ts`](../../apps/stock/web-api/src/routes/exchange.routes.ts) · [`apps/stock/web-api/src/routes/pipeline.routes.ts`](../../apps/stock/web-api/src/routes/pipeline.routes.ts)
|
||||
- **Tests**. The pipeline package and environment safety suite run Bun tests.
|
||||
[`apps/stock/data-pipeline/package.json`](../../apps/stock/data-pipeline/package.json) · [`test/unit/environment-safety.test.ts`](../../test/unit/environment-safety.test.ts)
|
||||
- **Web app**. React and Vite, with the application split into feature folders.
|
||||
[`apps/stock/web-app/package.json`](../../apps/stock/web-app/package.json) · [`apps/stock/web-app/vite.config.ts`](../../apps/stock/web-app/vite.config.ts) · [`apps/stock/web-app/src/features/exchanges/ExchangesPage.tsx`](../../apps/stock/web-app/src/features/exchanges/ExchangesPage.tsx)
|
||||
|
||||
## e. Open questions for the director
|
||||
|
||||
- Should the project adopt the existing scoped read-only MongoDB login for routine audits, and how should environments that only have `trading_admin` supply an equivalent login?
|
||||
- Should the design use the observed camelCase collection names as the contract, and where should any legacy `XX_` assumptions be corrected?
|
||||
- Which of `exchanges`, `symbols`, `provider_mappings` and `provider_exchange_mappings` should be extended or replaced? How does the legacy IB Mongo path fit?
|
||||
- Which sources should win conflicts for individual fields? The QM venue priority covers a narrower case within a single source.
|
||||
- Are CEO, TE and TT in scope for the next phase, and which entities or feeds should each contribute?
|
||||
- What applies schema changes to existing Postgres volumes? The repository uses numbered SQL init files and the Studio skill refers to Drizzle.
|
||||
74
design/development/QUALITY-GATES.md
Normal file
74
design/development/QUALITY-GATES.md
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
# Mandatory quality and integration gates
|
||||
|
||||
All gates apply to the scoped change; unrelated failing baseline checks must be reported, not hidden. No claim of successful validation without the exact command/result. The plan itself does not certify current engine behavior.
|
||||
|
||||
## G0 — Scope and architecture
|
||||
|
||||
Approved plan/task, satisfied dependencies and ADRs, isolated branch/worktree, reserved write locks, clean knowledge of pre-existing changes. No application change beyond the task. Contract changes require the designated contract owner and dependent-task update before implementation.
|
||||
|
||||
## G1 — Economic invariants
|
||||
|
||||
For every canonical financial transition:
|
||||
|
||||
- Equity = cash + marked signed position value; available cash subtracts reservations and cannot be negative under cash policy.
|
||||
- Every fill/fee ID applies once; conflicting reuse fails. Fees, cash, remaining reservations and positions reconcile after partial/rejected/cancelled orders.
|
||||
- Owner quantities and derived aggregate basis reconcile; owner realized/unrealized P&L + allocated reserve reconcile to account totals.
|
||||
- No unsupported short/borrowing, negative quantity, non-finite input, overflow or hidden rounding path.
|
||||
- All accepted intents (including explicit orders and direct native calls) pass Rust risk; risk hints cannot override account limits.
|
||||
- No observation/feature/fit artifact is visible before availableAt. Future-suffix mutation cannot change earlier decisions.
|
||||
- Same versioned data/config/seed/strategy/engine produces the same economic hash; fixed decision traces reproduce identical financial transitions.
|
||||
- Research sessions cannot modify paper accounts, clocks, subscriptions or checkpoints.
|
||||
- No-result/undefined risk metric is null/diagnosed, not a fabricated zero.
|
||||
|
||||
Required named regressions: C01 terminal_fee_equity, C03 fee_budget_10000 and computed fee commitments, F02 same_asset_two_owners, F05 same_bar_forbidden and zero available volume, F06 future_suffix_mutation, F08 session-end returns and exposure union.
|
||||
|
||||
Timing/risk policy regressions also include adjacent_open_zero_latency, positive_latency_skips_open, future_ohlcv_does_not_change_open_fill, feature_timeframe_does_not_duplicate_liquidity, daily_close_target_survives_to_open, out_of_session_DAY_rejected and drawdown_halt_survives_rollover_restore.
|
||||
|
||||
## G2 — Durability and recovery
|
||||
|
||||
Existing [canonical paper](../../test/postgres/canonical-paper.test.ts), [canonical paper crash](../../test/postgres/canonical-paper-crash.test.ts) and [durable backtest](../../test/postgres/durable-backtest.test.ts) cases are mandatory for touching those boundaries. Inject failures before/after decision, intent, fill, snapshot, result commits and publication. Verify stale attempt fencing, duplicate IDs, pending inputs, cancellation and restore-before-each-decision. Recovery must preserve per-effect context, not just final balances.
|
||||
|
||||
No tests against a development trading account/database. `bun run test:postgres` requires a disposable `stock_bot_safety*` database and dedicated Redis DB15 via `PIPELINE_TEST_DATABASE_URL` and `BACKTEST_TEST_REDIS_URL`. Provision/start containers only when execution and resource use are authorized.
|
||||
|
||||
## G3 — Product/API contracts
|
||||
|
||||
Verify existing v2 consumers and old saved results. Test request schema, immutable snapshots, idempotent submit, errors/status transitions and actor permissions. Browser tests cover navigation/reload, late-response selection races, loading/error/empty states, cancellation acknowledgement and failed/incomplete trials. No client financial simulator. New metric fields have units/null semantics; stored historical rows are not rewritten.
|
||||
|
||||
## G4 — Research integrity and isolation
|
||||
|
||||
Chronological train/validation/test boundaries. When fit artifacts or overlapping forward labels are supported, require retained fit windows and horizon-dependent embargo/purge; R08 initially rejects uncontracted models instead of building a generic ML pipeline. Record trials/selection/holdout access, no preprocessing fit on future windows. AI assertions are separate from evidence. Sandbox malicious/looping code, deny secrets/network/future datasets and prohibit research-token paper/live writes. Paper activation requires independent readiness and human approval.
|
||||
|
||||
## G5 — Performance
|
||||
|
||||
Changes to hot loops, storage layouts, buffers, caches, concurrency or declarative execution include P01 workload measurements, build/host metadata and economic hash equality. A faster but different result fails. No unstable timing assertion in ordinary unit tests; repeated benchmark evidence and explicit release budget are separate.
|
||||
|
||||
## G6 — Repository checks and release cutover
|
||||
|
||||
Existing commands (not all equivalent):
|
||||
|
||||
```sh
|
||||
bun run test:contracts
|
||||
bun run typecheck
|
||||
bun run test:calculations
|
||||
bun run test:integration
|
||||
bun run test:native
|
||||
bun run check
|
||||
bun run test:postgres
|
||||
```
|
||||
|
||||
`bun run check` runs build/types/contracts/tooling/utils/calculations/integration/native/lint and secret audit; it **does not include** disposable PostgreSQL or browser E2E. Run `bun run test:e2e` separately for the web workbench. Native command is `cargo test -p engine --lib --offline`; missing dependencies are a reported blocker, not a pass.
|
||||
|
||||
The browser gate requires a built checkout, explicit `PIPELINE_TEST_DATABASE_URL` pointing to a disposable `stock_bot_safety*` database, dedicated Redis DB15 in `BACKTEST_TEST_REDIS_URL`, and Chromium. Install the pinned browser explicitly with `bun run test:e2e:install` if missing; do not install browsers implicitly during checks. The command rebuilds the frontend for same-origin production use. It exercises authenticated HTTP/WebSocket routes, durable dispatch and SQL persistence with deterministic UI fixtures plus an actual native smoke run. Fixture results are not financial-correctness evidence. Never use a development trading database or queue.
|
||||
|
||||
Before making canonical Rust the default: all in-scope approved economic fixtures pass, every implemented strategy mode shares the same financial transition semantics/hashes (an unimplemented DSL is not a gate), canonical results render/reopen/reproduce, and paper migration passes fault tests if paper is switched. Keep a versioned rollback route for software deployment, but never silently downgrade a failed run's economics or mutate accounts between incompatible schemas.
|
||||
|
||||
Independent reviewer signs off G1/G2 for financial work; integration owner runs combined branch gates. Only then may planning mark done with commit and evidence references.
|
||||
|
||||
## Revised gate interpretation
|
||||
|
||||
- Implementation dependencies block coding/integration. `release_gates` block enabling the complete feature, not integrating a tested component; this avoids the F05-matcher/F06-replay deadlock. Conditional gates apply only when the named feature is enabled.
|
||||
- C03 deliberately preserves legacy reducing/short financing semantics; canonical cash-only invariants apply to F04 onward. No new borrowing claim is made for the interim patch.
|
||||
- Exact owner remaining cost/residuals and per-strategy RNG/decision cursors are tested. Rounded display average is never reconstructed into authoritative basis.
|
||||
- Determinism is scoped to controlled inputs and pinned supported artifacts/platform. Trace replay and strategy recomputation are tested separately; no finite conformance suite proves arbitrary code deterministic.
|
||||
- Fixes need no switch to restore a bug. Compatibility adapters apply only to actual schema/engine cutovers and historical readers.
|
||||
- Before native integration tests, build the addon from the assigned worktree and verify resolution/hash. Generated native artifacts are not authored changes. Shared writable build output or workspace symlinks pointing at another agent's source invalidate isolation.
|
||||
38
design/development/architecture/benchmarks.md
Normal file
38
design/development/architecture/benchmarks.md
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
# Benchmark plan: staged measurement, one small harness
|
||||
|
||||
P01 starts with available code. No application benchmark was run during this planning review.
|
||||
|
||||
## Stage0: available now
|
||||
|
||||
Extend [benchmark-dataset.ts](../../../scripts/benchmark-dataset.ts) and add a small research driver:
|
||||
|
||||
- Fresh process/addon startup; existing native load/run/result parse.
|
||||
- Single asset at1k/10k/100k bars; multi-asset fixture with equal-time events.
|
||||
- Several repeated parameter trials using an existing supported native strategy.
|
||||
- Dataset preparation/repeated prepared-object handoff measured separately from native/IPC work.
|
||||
|
||||
Record host/runtime/source/native-binary hash, seed, dataset/config identity, raw elapsed samples, returned bytes and RSS. Fresh-process and reused-input results are different; neither implies cross-trial resident data. Report startup/load/run/parse phases only where observable. DB/queue/allocations/TS-callback metrics are explicitly unavailable until their owning tasks instrument them.
|
||||
|
||||
Use deterministic fixtures and an economic-field hash excluding UUIDs, logs and wall time. Existing bad economics remain labelled limitations; benchmark parity does not validate alpha or accounting.
|
||||
|
||||
## Extend when the capability exists
|
||||
|
||||
| Owner | Added workload/counter |
|
||||
| --- | --- |
|
||||
| F06 |1k/10k/100k replay scaling; tie-order/hash equality; logging cost |
|
||||
| F07/S01 | Tagged-step and real TS decisions; crossings, context bytes, decision time |
|
||||
| R06 | Summary/result storage/query latency and batch queue wait |
|
||||
| P04 |1/2/4 isolated workers; trials/s, tail latency, total RSS and hash equality |
|
||||
| P03, if justified | Load-count reduction and resident dataset state-reset/lifetime |
|
||||
| D04, if justified | Same-feature request count and incremental/batch parity |
|
||||
| A02 | Restricted strategy IPC cost and timeout cleanup |
|
||||
|
||||
Later representative profiles:100 assets x10k observations;10 strategies over20 assets;100–1000 trials; high-turnover100k-fill result. Run them only when those semantics exist. Do not build missing features to make P01's benchmark matrix appear complete.
|
||||
|
||||
## Protocol
|
||||
|
||||
Short measurements: warmups plus repeated raw samples, medians/p95 where sample count supports them. Long sweeps: at least3 measured runs with load disclosed. Release native builds for performance; verify the actual addon hash. Cold OS/DB caches are claimed only when controlled; do not disrupt shared services to force them.
|
||||
|
||||
Compare equal economic/decision policies, inputs and outputs. Report bars/s for replay and end-to-end separately, trials/s, CPU time where available, RSS/bytes and parallel efficiency. Establish budgets from variance, not invented throughput targets. No timing-flaky unit tests or arbitrary dataset caps.
|
||||
|
||||
Optimization approval must estimate time saved across real research workloads against implementation/maintenance cost. The declarative path is optional, not a milestone every project must reach.
|
||||
25
design/development/architecture/decisions/001-ownership.md
Normal file
25
design/development/architecture/decisions/001-ownership.md
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
# ADR-001 — Application versus financial authority
|
||||
|
||||
Status: **user-mandated direction**; the detailed backlog still awaits approval.
|
||||
|
||||
## Selected approach
|
||||
|
||||
TypeScript owns product/application logic, strategy authoring, signal/regime composition and research orchestration. Rust owns authoritative financial state transitions, deterministic replay, matching and risk. Keep a modular monolith, existing durable dispatch/runner, shared public contracts and existing web product.
|
||||
|
||||
## Rationale and evidence
|
||||
|
||||
Historical TypeScript `applyFill` (`orchestrator/src/execution/model.ts`, retired in pre-M0 cleanup) and Rust [process_fill](../../../../apps/stock/engine/src/backtest/engine.rs#L426) were competing authorities. Consolidation removes behavioral drift; moving all authoring to Rust would reduce flexibility without proving a throughput benefit.
|
||||
|
||||
## Alternatives and tradeoffs
|
||||
|
||||
- All TypeScript: simpler language footprint, conflicts with required native financial authority.
|
||||
- All Rust: less runtime crossing, conflicts with flexible TS development goals.
|
||||
- Separate services per stage: more operational overhead without demonstrated need.
|
||||
|
||||
## Migration consequences
|
||||
|
||||
Preserve all existing recovery/data/registry/calculation behavior. Keep explicit legacy readers and paths until cutover tests pass, but never auto-fallback from a failed canonical run to legacy economics. Gates: F01–F08, S01–S03, R05; delete duplicate execution only in S06.
|
||||
|
||||
## Skeptical revision
|
||||
|
||||
Do not port reviewed statistical reporting to Rust solely for language uniformity. F08 consumes Rust financial postings/session marks through one existing TS calculation path; this is analysis, not competing cash/fill accounting. C06 uses a fail-closed legacy composition guard instead of building another soon-to-be-retired research runtime. One canonical SMA path is sufficient for initial cutover.
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
# ADR-002 — Money, cost basis, ownership and funding
|
||||
|
||||
Status: **approved by owner, 2026-10-22** (explicit “yes” to ADR-002/003/004 as written). This revision replaces the unimplemented half-even/rounded-average proposal; approval does not itself alter legacy code or accounts.
|
||||
|
||||
## Selected minimal policy
|
||||
|
||||
- Use a maintained checked decimal implementation (for example a pinned Rust decimal crate), not hand-written fixed-point arithmetic. Monetary postings and quantities use8 fractional digits initially. Explicit half-up/away-from-zero tie rounding matches the current TS `amount()` policy; tick/lot rules may be stricter. Reject unsupported precision, non-finite values and overflow.
|
||||
- Decimal strings are financial command/snapshot transport. Market observations and statistical feature arrays need not become strings or be copied through the boundary per observation.
|
||||
- **Remaining cost amount is authoritative. Average price is derived.** For a partial disposal release the proportional basis rounded at posting precision; the final disposal releases the exact remaining residual. Example: cost5 for3 shares must release exactly5 over all sales, not5.00000001 reconstructed from average1.66666667.
|
||||
- Store owner-keyed quantity/cost/P&L from the first ledger implementation (F02 absorbs F03). Account quantities/basis aggregate those books. Fees are explicit separate postings; initial unallocated capital belongs to a reserve owner. Broker suspense handling is deferred with broker integration, not a generalized suspense-account subsystem now.
|
||||
- First project-gated model is single-base-currency cash-funded long-only, no borrowing. Fee-inclusive reservations and fill-time checks live in Rust. Adverse gaps reject unaffordable remaining quantity rather than borrow or silently resize.
|
||||
- No internal crossing/netting. Stable owner/intent admission priority; one owner cannot sell/cancel another's inventory. A strategy instance selects target OR explicit-order mode; mixing modes rejects in v1.
|
||||
- Account daily-loss reset follows one declared account risk-session calendar, not each asset's venue or UTC date. Explicit boundary commands roll only the daily baseline. Drawdown peak/halt survives sessions and restore; authorized operator reset records its baseline.
|
||||
|
||||
## Legacy correction is different
|
||||
|
||||
C03 only adds unpaid-fee liability to the **existing non-reducing gross-capital test**. It preserves existing short/reducing behavior and8-place rounding. It is not the new cash-only account model and makes no claim to eliminate all debt in legacy short covers.
|
||||
|
||||
## Evidence / alternative costs
|
||||
|
||||
Historical TS amount/cost basis and aggregate owner attribution (`orchestrator/src/execution/model.ts`, retired in pre-M0 cleanup), [native fill broadcast](../../../../apps/stock/engine/src/backtest/engine.rs#L489). Exact postings fix arithmetic, not market modeling. A full multicurrency double-entry/margin/borrow engine is not required for v1.
|
||||
|
||||
## Migration and tests
|
||||
|
||||
F01 owns scalar/command fixtures; F02 implements owned books once; F04 owns funding/risk. Preserve old results; account conversion must reconcile quantities, cost residuals, cash and fees or refuse an implicit migration. No switch restoring a correctness defect. Required tests: positive/negative rounding ties, partial/final residual, A/B owner basis, duplicate fees, overflow and persisted daily/drawdown state.
|
||||
|
||||
“Project-gated” means the specified regression tests passed on declared modeling policies. It is not independent certification, proof of alpha, a broker guarantee or a generic certification framework.
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
# ADR-003 — Information availability and execution timing
|
||||
|
||||
Status: **approved by owner, 2026-10-22** (explicit “yes” to ADR-002/003/004 as written). Versioned implementation remains task-gated; legacy snapshots/results are preserved.
|
||||
|
||||
## Selected policy
|
||||
|
||||
- Dataset v2 records instrument, timeframe, interval start/end, event time, availability time and deterministic source sequence; dates and calendars are versioned. Replay derives a separate open-only execution event at interval start, exposing only open/time, and a completed-bar observation at its availability time. The full stored OHLCV row is never exposed at its open.
|
||||
- A completed-bar decision cannot trade at its own close. Default bar mode fills at the **next eligible open**; quote mode uses the next eligible observed quote. Default terminal treatment marks open positions, not invented liquidation.
|
||||
- V1 bar matching uses open-only market/limit crossing. It does not invent an OHLC path, intrabar stop order or within-bar limit touch. Explicit unsupported order types reject.
|
||||
- Pin exactly one execution series (source/timeframe) per instrument per run. Only that series supplies matching opportunities, liquidity capacity and authoritative financial marks. Other timeframes are feature observations, not duplicate executable volume. Strategies declare a decision cadence; adding an unused feature series must not add decision triggers or alter fills.
|
||||
- Target-generated orders are GTC until replaced/cancelled by their owner or cancelled at run termination. Explicit DAY orders are accepted only during an open venue session and expire at that session's close; out-of-session DAY submission rejects. A daily-close target therefore survives to the next session's open. No fill is invented for an order cancelled at run termination.
|
||||
- Liquidity capacity at an open is a declared model using **previously available** volume (e.g. last completed bar volume times participation), never the new bar's future total volume. Quote mode uses available quote size. No known capacity means no simulated fill; zero capacity cannot fill. Report this approximation.
|
||||
- Stable event ordering uses availability time, phase, instrument and source sequence. For bar mode at equal timestamps: publish completed prior-interval observations, update marks/features, create synchronized decisions, then process next-interval open-only events. The default assumes zero modeled decision/order latency. A decision can therefore fill at the immediately adjacent bar's open even when prior close and next open share the same timestamp, but never at the prior close. The next open's price is not in the decision context. Persist this zero-latency assumption explicitly; positive configured latency or delayed data skips opens occurring before decision availability plus latency. Quote mode instead requires a strictly subsequent eligible quote identity, not reuse of the quote just observed. Orders cannot be inserted retroactively into a completed event phase.
|
||||
- Keep quote timestamps unchanged when the simulation clock advances. Missing/stale inputs are explicit. Equal-time cross-asset decisions use the same snapshot; execution priority is deterministic.
|
||||
- Daily session labels become actual venue session boundaries using a retained calendar revision, including DST/half days. Unknown mappings reject project-gated execution.
|
||||
- Warmup observations are available for features but cannot generate fills. Fit data and test data remain separately bounded.
|
||||
- Raw prices are required for executable share/cash semantics. Provider-adjusted data may be an explicitly labelled signal input, not a replacement for action accounting. V1 project correctness-gate evidence requires supported action coverage or action-free eligibility; unknown coverage remains a limitation.
|
||||
|
||||
## Evidence and rationale
|
||||
|
||||
[Current same-event execution](../../../../apps/stock/engine/src/backtest/engine.rs#L249), historical bar-close bid/ask (`orchestrator/src/services/ExecutionService.ts`, retired in pre-M0 cleanup), [v1 timestamp contract](../../../../libs/core/types/src/historical-data.ts#L90), [invented VWAP](../../../../apps/stock/orchestrator/src/data/historical-dataset.ts#L230).
|
||||
|
||||
## Alternatives / tradeoffs
|
||||
|
||||
Same-close fills are allowed only as an explicitly named legacy assumption, not default evidence. Full tick/order-book replay and stochastic intrabar paths are deferred. Next-open open-only matching is limited but traceable; zero modeled latency is optimistic and must be disclosed. Using the new bar's total volume to constrain a fill at its open would itself leak future information.
|
||||
|
||||
## Migration
|
||||
|
||||
D01 creates new hashes without rewriting v1 snapshots. F05/F06 consume v2 timing. C01 fixes existing liquidation accounting without silently changing policy. F08/R05 record execution-policy versions and retain old result semantics. New economics will change backtest returns; that is an intentional correction, not a parity failure to hide.
|
||||
|
||||
## Implementation boundaries
|
||||
|
||||
F05 tests matcher transitions against explicit execution-event keys. F06 owns derived open events, calendars, decision barriers and end-to-end latency tests; those release gates must not force F05 to implement replay first. D01 includes availability and coverage/eligibility in one versioned manifest change (D03 merged).
|
||||
|
||||
At each barrier all due strategy contexts share one immutable ledger revision; submit decisions as a batch in stable admission priority. Explicit IOC/FOK semantics are retained for paper compatibility. Account risk-session reset is a separate declared clock from individual instrument session expiry.
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
# ADR-004 — One pull-session boundary, not two strategy frameworks
|
||||
|
||||
Status: **approved by owner, 2026-10-22** (explicit “yes” to ADR-002/003/004 as written). Session execution is implemented by F07/S01, not by approving this contract direction.
|
||||
|
||||
## Selected approach
|
||||
|
||||
Reuse NAPI-RS in the existing research worker. TS drives a synchronous bounded pull loop, not a reentrant Rust-to-JS callback. Web/API processes never execute the native loop. IPC stays at worker supervision and, later, the untrusted-strategy boundary.
|
||||
|
||||
The first strategy path uses reviewed incremental TS calculations directly. A cache/feature DAG is not a prerequisite. Port one SMA strategy first; retain other strategies as explicit legacy artifacts until needed. Do not port every native built-in just to validate NAPI.
|
||||
|
||||
## Minimal contract
|
||||
|
||||
`advance(eventBudget)` returns one of:
|
||||
|
||||
- `progress`: no decision; allow cancellation/supervisor progress.
|
||||
- `decisionBatch`: barrier ID/revision, immutable prefix contexts for due strategy instances.
|
||||
- `complete`: canonical ledger/mark/result inputs.
|
||||
|
||||
At a decision barrier, collect all due strategies' intents/next states against the **same** portfolio revision. Submit the batch once; Rust validates owner identity, mode, IDs and admits in the pinned priority order. No early callback can mutate the next callback's view. Target versus explicit-order mode is fixed per strategy instance; duplicate targets consider existing owned commitments.
|
||||
|
||||
Each strategy has its own seed/RNG cursor and decision sequence. Stage next state/RNG until submission. An exception discards the staged barrier and fails the attempt; a risk rejection is a valid committed outcome, with feedback to the strategy. On an ambiguous process failure, discard/restart the attempt rather than reuse half-advanced resident state.
|
||||
|
||||
## Determinism claim, precisely
|
||||
|
||||
Controlled clock/random inputs, prefix observations and pinned strategy/runtime/native artifacts produce repeatable fixture traces on the supported platform. Repeated conformance tests **cannot prove arbitrary JavaScript deterministic**. Trusted code can violate conventions; this is not a security sandbox. Economic replay of a recorded decision trace and recomputation of strategy decisions are separate tests.
|
||||
|
||||
A snapshot sufficient for decision recomputation includes ledger/open orders/reservations, replay cursor, decision IDs, strategy states and RNG cursors; any incremental indicators must be checkpointed or deterministically rebuilt from the recorded warmup prefix.
|
||||
|
||||
## Alternatives and tradeoffs
|
||||
|
||||
NAPI already exists; [callback registration explicitly fails](../../../../apps/stock/engine/src/api/backtest.rs#L63). The existing [native worker](../../../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts) supplies killable process isolation. Keep it. No embedded JS runtime, generic transport adapter or mandatory per-observation IPC. A typed native plan remains deferred P06.
|
||||
|
||||
F07 introduces the session; S01 drives it; S02 ships one real strategy. F07/S01 extend P01 measurements for actual crossings, context bytes and decisions. P03 cross-trial resident data is optional; loading once per session is ordinary behavior.
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
# ADR-005 — Shared kernel, distinct persistence boundaries
|
||||
|
||||
Status: **approved by owner continuation, 2026-10-23**. After the handoff named S01 and linked this pending decision, the owner instructed “commit all of it and continue.” This approves the documented direction for the next task; paper migration/default activation remain separately gated. Preservation of existing recovery is required.
|
||||
|
||||
## One implementation
|
||||
|
||||
Use one internal Rust `apply(state, command) -> effects` financial kernel.
|
||||
|
||||
- Research keeps state resident and applies events directly. Do **not** serialize, clone or rehydrate a full account snapshot per observation.
|
||||
- Paper loads the committed snapshot into private staged native state inside the existing SQL transaction, invokes the same kernel, persists snapshot/orders/fills/ordered journal effects atomically, commits, then publishes. Failed SQL work discards the staged state.
|
||||
- Snapshot encoding is a boundary operation, not the hot-loop algorithm. Exact per-effect views remain available where the existing recovery journal requires them; do not replace them with a final batch state.
|
||||
|
||||
TS owns SQL custody, not independent accounting. No native/DB two-phase commit and no new event-sourcing framework.
|
||||
|
||||
## Decision durability
|
||||
|
||||
Preserve durable step recovery, account locks, and duplicate/conflict handling in [canonical paper execution custody](../../../../apps/stock/orchestrator/src/execution/canonical-paper.ts), along with existing failure tests. Paper strategy contexts use committed event views; never substitute a later account state. Restore RNG/decision cursors along with checkpoint state.
|
||||
|
||||
All currently supported paper order policies must be preserved or a migration explicitly refused. F05 covers market/limit and DAY/GTC/IOC/FOK; do not silently drop IOC/FOK at cutover.
|
||||
|
||||
## Migration
|
||||
|
||||
C06 contains unsafe legacy research/paper composition; it does not build a temporary second worker framework. F02 builds owner accounting once. S03 adopts the kernel and durable recovery without waiting for Sharpe/Sortino or web pages. S04 verifies paper feed/readiness. S06 retires competing active execution after those gates, retaining result readers/research algorithms.
|
||||
|
||||
Compare financial transitions for the **same event and intent trace**. Research and paper receive different real-world prices/availability; identical P&L is not promised for different inputs. Broker fills remain future external facts to reconcile, not simulated orders that can be rejected after occurrence.
|
||||
|
||||
## S01 retry scope
|
||||
|
||||
The existing durable research runner retries whole attempts. S01 follows that boundary: create a fresh native session from frozen data/configuration, clone original strategy states and restore original per-owner seeds, then recompute observations, decisions and RNG cursors. Per-barrier TypeScript diagnostic snapshots are not independently resumable financial checkpoints. Do not add a native checkpoint wire or accept a TS-only mid-run resume merely for S01. Existing Rust checkpoint reconstruction and paper SQL checkpoints remain preserved; S03 owns their durable integration.
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
# ADR-006 — Web-first research product and minimal persistence
|
||||
|
||||
Status: **approved by owner continuation on 2026-10-23**, after the S05 handoff explicitly linked this decision for the next research-product work. Web as primary product is user-mandated. Approval covers direction; engine cutover and trading activation remain separate release gates.
|
||||
|
||||
## Selected approach
|
||||
|
||||
Extend current React features, Hono v2 APIs, SQL definitions/runs/results, durable outbox/queue, frozen datasets and websocket projection. The browser and AI clients use the same business APIs.
|
||||
|
||||
Add only strategies, immutable strategy_versions, research_projects, hypotheses, experiments and analysis_artifacts. Attach candidate/experiment identity to existing runs; keep backtests as editable templates. A later paper deployment record is optional. Store stable single-owner/agent identity without implementing full multi-tenancy.
|
||||
|
||||
Retain artifact bytes or immutable retained references, not hashes alone. Archive referenced evidence; no automatic purge by default. Future operator retention must respect references and explicit consent.
|
||||
|
||||
## Evidence
|
||||
|
||||
[Existing submission transaction](../../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211), [existing result contract](../../../../libs/core/types/src/backtest-run.ts#L4), [schema deletion cascade](../../../../database/postgres/init/08-create-runs-table.sql#L13), [existing UI routes](../../../../apps/stock/web-app/src/app/App.tsx#L24).
|
||||
|
||||
## Alternatives / tradeoffs
|
||||
|
||||
A separate research database, job service, AI-only APIs or general laboratory/workflow system duplicates working infrastructure. SQL metadata and bounded job expansion suffice. Existing JSONB results are acceptable until measurement warrants paged/normalized detail. Source editing initially uses repository/artifact submission plus schema forms and version diff; no browser IDE prerequisite.
|
||||
|
||||
## Migration
|
||||
|
||||
W01–W04 deliver the existing exploratory workflow while engine work proceeds. R01–R04 add strategy/workspace value independently of Rust cutover. R05 turns that same workbench into a reproducible canonical-engine workflow; R06–R09 add experiments/validation. Legacy results stay read-only and visibly qualified. See [product contracts](../research-product.md).
|
||||
|
||||
## Reduced product dependencies
|
||||
|
||||
API/data contracts gate implementation, not unrelated screens. Catalog/workspace/experiment/dataset UI tasks can use focused tests before W04 is complete, but shared browser coverage remains a feature-release gate. Basic experiment comparison needs a frozen dataset ID, not the entire project workspace or dataset picker. Findings reference immutable metric paths rather than creating another metric store. R06 ships summary projections; P05 is only a later measured detail optimization.
|
||||
27
design/development/architecture/decisions/007-ai-boundary.md
Normal file
27
design/development/architecture/decisions/007-ai-boundary.md
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
# ADR-007 — AI authorization, code isolation and promotion
|
||||
|
||||
Status: **implementation authorized by owner, 2026-10-24**, through the instruction to complete all remaining scheduled tasks. Research-only quotas, OS isolation and no autonomous live access remain mandatory. Actual paper activation still requires a deliberate human action; no trading is activated by development or task closure.
|
||||
|
||||
## Selected approach
|
||||
|
||||
Use existing operator authentication plus explicit research-agent identity/scope. AI may create hypotheses/candidate artifacts and submit bounded experiments, but cannot loosen account risk, choose its own privileges or invoke paper/live administration.
|
||||
|
||||
Unreviewed code is built/imported/evaluated in an OS-restricted process or container with no network, secrets, database, broker credentials, shared writable paper state or full future dataset. The financial supervisor sends prefix-only contexts over IPC. Require CPU/wall/memory/process limits and safe cancellation. A JS `vm` or a separate unrestricted process alone is insufficient.
|
||||
|
||||
Trusted registered/reviewed artifacts can run beside NAPI in a worker for speed. Moving an artifact into that tier requires an explicit operator action, never an AI-supplied trust flag. If the sandbox is unavailable, reject untrusted execution; do not silently downgrade.
|
||||
|
||||
Implementation clarification (A02/A04): the trusted **research** path is limited to server-registered built-ins. Catalog approval never changes a candidate's isolated research execution. A separate immutable human paper-promotion receipt may authorize the exact candidate factory in the paper host after held-out/cost evidence and financial-build parity checks. That action is a deliberate trust decision; paper starts unbound/halted, and live remains unavailable.
|
||||
|
||||
The first isolation profile is a local Linux x86_64 Docker scratch image containing the installed Bun runtime, trusted protocol host and independent Rust PID1 guardian. It has no host/data mounts or network, uses cgroup limits and a restricted unprivileged child, and dies on supervisor disconnect or a monotonic deadline. Version the image, host, guardian, runtime and policy in retained requests. A standalone restricted transpiler accepts self-contained TypeScript; no dependency installation, remote build service, JavaScript VM security claim or second simulator is introduced.
|
||||
|
||||
## Evidence
|
||||
|
||||
[Current role model](../../../../libs/core/di/src/http/security.ts#L4) is a small operator boundary, not research isolation. Historical `StrategyRegistry.ts` (retired in pre-M0 cleanup) exposed execution services that the new decision API must not expose.
|
||||
|
||||
## Alternatives / tradeoffs
|
||||
|
||||
Running all AI code in the API/engine process is fast but not a meaningful protection against future-data reads or credential access. Sandboxing all reviewed code unnecessarily penalizes the trusted fast path. IPC has a cost; P01/A02 measure it separately.
|
||||
|
||||
## Migration
|
||||
|
||||
A01 adds actor/budget admission; A02 adds isolation; A03 composes existing research APIs; A04 permits only human-reviewed paper promotion after paper gates. Limits apply to autonomous job budgets and resource use, **not arbitrary truncation of the owner's datasets**. Local dev .env policy is not changed by this plan, but sandboxed code must never receive its contents.
|
||||
24
design/development/architecture/decisions/008-performance.md
Normal file
24
design/development/architecture/decisions/008-performance.md
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
# ADR-008 — Performance work earns its complexity
|
||||
|
||||
Status: performance work explicitly resumed by the owner, 2026-10-28. Evaluate all remaining conditional tasks using the smallest supported change; record no-go decisions for extensions without demonstrated value. P06 still needs a bounded, measured justification before a prototype.
|
||||
|
||||
## Sequence
|
||||
|
||||
1. P01 measures currently available dataset/native execution paths. Missing counters are unavailable, not zero; getters are not callback benchmarks.
|
||||
2. F06 constructs sorted historical replay once and measures scaling. P02 is merged, not a second queue rewrite.
|
||||
3. F07/S01 add real step/TS-decision/context-byte measurements.
|
||||
4. P04 runs independent trials with the existing one-shot workers. It need not wait for resident cross-trial datasets.
|
||||
5. P03 shared datasets, D04 shared feature caching and P05 detail-storage/pagination remain deferred until profiles identify meaningful repeated work.
|
||||
6. P06 may prototype a tiny plan only with owner-approved budget and representative end-to-end benefit target.
|
||||
|
||||
## Why change the old gate
|
||||
|
||||
A removable20% fraction permits at most1.25x speedup; a simultaneous1.5x condition is not a useful universal rule. Record the actual fraction, Amdahl upper bound, end-to-end timings and maintenance cost. The owner chooses whether the benefit warrants a bounded prototype. No automatic language/framework project is authorized by a microbenchmark.
|
||||
|
||||
## Constraints
|
||||
|
||||
Correctness/policy hashes must match. Keep financial event processing serial within one portfolio; parallelize independent trials. No GPU/distributed scheduler/feature service/embedded JS or Arrow-everywhere conversion without evidence. Existing [queue insertion scan](../../../../apps/stock/engine/src/backtest/mod.rs#L138) is a concrete reason to choose a sorted cursor, not a reason to rewrite unrelated infrastructure.
|
||||
|
||||
## October 28 review outcome
|
||||
|
||||
P08 implements one measured local TypeScript state-handling optimization, preserving exact Rust economic hashes. D04/P03/P05/P06 remain deferred; CL21 also remains unnecessary without a concrete replay edit. No new blanket performance pause is imposed; see [benchmarks.md](../benchmarks.md) for measured figures.
|
||||
154
design/development/architecture/overview.md
Normal file
154
design/development/architecture/overview.md
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
# Architecture baseline and target
|
||||
|
||||
> **Historical planning baseline.** The observations and example interfaces below describe
|
||||
> the pre-migration state and proposed design, not today's runtime. For the implemented
|
||||
> connections and current strategy API, start with the [project guide](../../guide/README.md).
|
||||
|
||||
Planning baseline: commit `b7aeca4`, inspected 2026-10-22. This is a historical baseline, not today's runtime contract; see [architecture decisions](./decisions) and [PLATFORM-PLAN.md](../../PLATFORM-PLAN.md) for current boundaries and locked decisions.
|
||||
|
||||
## What exists
|
||||
|
||||
The React/Vite application already has saved backtest definitions, run selection, charts, trades and metrics. The Hono/Bun API writes a request snapshot and dispatch outbox in one PostgreSQL transaction. The existing dispatcher/queue and fenced runner claim attempts, freeze datasets, heartbeat leases and persist results. PostgreSQL-backed websocket projections and polling support status updates.
|
||||
|
||||
There are currently two economic implementations: a TypeScript simulation with durable account/decision recovery, and a native Rust backtester with its own fill/accounting behavior. The TS path can switch the shared paper ModeManager. Native TS callback registration is unsupported. Neither path should currently be treated as project-gated research performance.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
UI[Existing React backtest pages] --> API[Hono v2 backtest API]
|
||||
API --> PG[(Postgres definitions / runs / dispatch / results)]
|
||||
PG --> DIS[Existing dispatcher and queue]
|
||||
DIS --> RUN[Fenced durable runner]
|
||||
STORE[Provider storage] --> DATA[Frozen hashed datasets]
|
||||
DATA --> RUN
|
||||
RUN --> TS[TS BacktestEngine and SimulationExecution]
|
||||
RUN --> NW[Native worker / NAPI]
|
||||
NW --> OLD[Rust BacktestEngine]
|
||||
TS --> MODE[Shared paper ModeManager: interference risk]
|
||||
TS --> RESULT[Result adapters]
|
||||
OLD --> RESULT
|
||||
RESULT --> PG
|
||||
PG --> WS[Websocket run projection / polling]
|
||||
WS --> UI
|
||||
```
|
||||
|
||||
Evidence: [transactional submission](../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211), [dataset freeze](../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190), legacy `StrategyRecovery.ts` (retired in pre-M0 cleanup), [container composition](../../../apps/stock/orchestrator/src/container.ts).
|
||||
|
||||
## Target: one product, one financial core
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
WEB[Primary React research workbench] --> API[TS research / strategies / experiments API]
|
||||
AI[Authorized AI research client] --> API
|
||||
API --> PG[(Existing Postgres metadata / immutable provenance / results)]
|
||||
API --> Q[Existing dispatch + durable queue]
|
||||
Q --> SUP[TS run supervisor / bounded worker pool]
|
||||
DATA[Frozen datasets + retained model artifacts] --> SUP
|
||||
SUP --> STR[TS strategy decisions / signal and regime composition]
|
||||
SUP --> CORE[Rust replay + matching + owner ledger + risk]
|
||||
STR -->|intents only| CORE
|
||||
CORE -->|available context and effects| STR
|
||||
PLAN[Optional small declarative plan] -.-> CORE
|
||||
UNTRUSTED[Restricted TS process: no secrets or future dataset] -->|validated intents via IPC| SUP
|
||||
CORE --> RES[Canonical economics / metrics / diagnostic artifacts]
|
||||
RES --> PG
|
||||
PAPER[TS paper adapter + durable transaction custody] --> CORE
|
||||
PAPER --> JOURNAL[(Existing checkpoints / intents / execution journal)]
|
||||
PG --> WEB
|
||||
LIVE[Future broker adapter: disabled] -.-> CORE
|
||||
```
|
||||
|
||||
This remains a modular monolith with existing operational processes and bounded computation workers—not a new service topology.
|
||||
|
||||
## Responsibility boundaries
|
||||
|
||||
| Boundary | TypeScript owns | Rust owns |
|
||||
| --- | --- | --- |
|
||||
| Product | UI/API, strategies/versions, projects, experiments, findings, configuration | No web business logic |
|
||||
| Research | Candidate expansion, bounded scheduling, validation recipes, AI clients; reviewed statistical analytics over canonical results | Deterministic replay and authoritative financial result inputs |
|
||||
| Strategy | Arbitrary compatible author logic, feature/signal composition, regime integration, checkpoint payload | Validated read-only context and decision admission |
|
||||
| Features | Definitions, metadata, reviewed TS calculations when fast enough | Existing/bulk native calculation where profiling and parity justify it |
|
||||
| Finance | Display/transport only; allocation preferences and intent proposals | Accepted quantities, reservations, positions, cost basis, cash, fees, order transitions, risk limits |
|
||||
| Durability | Existing PostgreSQL transactions, leases, idempotency custody, retained artifacts | One financial kernel, versioned boundary snapshots and ordered effects |
|
||||
| Execution | Provider/broker connectivity and reconciliation orchestration | Simulation semantics; canonical accounting/risk for observed broker facts |
|
||||
|
||||
A future broker's fills are external facts, not simulated prices. They must be accounted for even when a risk limit is breached, then trigger a halt/reconciliation workflow; they must not be silently discarded to make an invariant look satisfied.
|
||||
|
||||
## Minimal module shape
|
||||
|
||||
Keep current app and library boundaries. Add focused modules, not another package/service for every noun:
|
||||
|
||||
- `apps/stock/engine/src/financial/`: scalar types, ledger, ownership, risk, matching, replay. Adapt `positions/`, `risk/`, `backtest/` and `indicators/`; do not replace all Rust code.
|
||||
- `apps/stock/orchestrator/src/strategies/`: versioned TS decision API, registry, built-ins, signals/regime functions.
|
||||
- `apps/stock/orchestrator/src/backtest/`: existing durable runner/native worker, session adapter and later pool.
|
||||
- `apps/stock/orchestrator/src/execution/`: existing transaction/recovery adapters, eventually without independent arithmetic.
|
||||
- `apps/stock/web-api/src/{routes,services}/`: strategy/research/experiment additions alongside current backtests.
|
||||
- `apps/stock/web-app/src/features/{backtest,strategies,research,experiments}/`: coherent research journeys.
|
||||
- `libs/core/types/src/`: public versioned contracts. `libs/calculations/`: preserve reviewed semantics and migration inventory.
|
||||
|
||||
## Minimal decision contract
|
||||
|
||||
Illustrative contract to be implemented by F01/S01, not a new framework:
|
||||
|
||||
```ts
|
||||
type Decimal = string; // validated fixed-scale transport, not JS money arithmetic
|
||||
type Intent =
|
||||
| { kind: "targetQuantity"; instrumentId: string; quantity: Decimal }
|
||||
| { kind: "order"; instrumentId: string; side: "buy" | "sell";
|
||||
quantity: Decimal; type: "market" | "limit"; limitPrice?: Decimal;
|
||||
timeInForce: "DAY" | "GTC" | "IOC" | "FOK" };
|
||||
|
||||
interface DecisionContext {
|
||||
decisionId: string;
|
||||
nowMs: number; // engine availability clock
|
||||
strategyInstanceId: string;
|
||||
features: Readonly<FeatureSnapshot>; // only available prefix; includes regime inputs
|
||||
positions: Readonly<OwnedPositions>;
|
||||
portfolio: Readonly<AccountView>;
|
||||
risk: Readonly<EffectiveRiskView>; // context, not a mutable policy object
|
||||
random(): number; // run/strategy seeded stream
|
||||
}
|
||||
interface Strategy<State, Params> {
|
||||
decisionCadence: { executionSeriesId: string; event: "barClose" };
|
||||
initialState(params: Params): State;
|
||||
onDecision(ctx: DecisionContext, state: Readonly<State>, params: Params):
|
||||
{ nextState: State; intents: readonly Intent[] };
|
||||
checkpointVersion: string;
|
||||
}
|
||||
// Trusted worker drives a pull loop; Rust never needs a reentrant JS callback.
|
||||
const step = engine.advance(session, eventBudget);
|
||||
switch (step.kind) {
|
||||
case "progress": yieldToSupervisor(); break;
|
||||
case "decisionBatch": {
|
||||
// All contexts are from one immutable ledger revision; RNG is per strategy.
|
||||
const staged = step.contexts.map(ctx => evaluateAndStage(ctx));
|
||||
engine.submitDecisions(session, step.barrierId, staged.map(x => ({
|
||||
strategyInstanceId: x.strategyInstanceId, decisionId: x.decisionId,
|
||||
intents: x.intents,
|
||||
})));
|
||||
commitStagedStates(staged); // business rejections are committed outcomes
|
||||
break;
|
||||
}
|
||||
case "complete": persistCanonicalResult(step.result); break;
|
||||
}
|
||||
// On exception/ambiguous crash: discard the attempt, never reuse half-advanced state.
|
||||
```
|
||||
|
||||
S01 initially uses prefix-only observations and reviewed incremental calculations; D04 shared caching is optional. S02 ports one SMA first, not every builtin. All due callbacks finish against the same portfolio snapshot before admission.
|
||||
|
||||
The supervisor stamps owner identity; a strategy cannot forge another owner's ID. Target quantity is an **absolute desired holding**, not an additive order. Rust subtracts owned inventory plus outstanding commitments and applies risk. Repeated target decisions cannot duplicate orders. V1 cancels/replaces owned outstanding target orders deterministically; explicit orders use unique decision-derived IDs.
|
||||
|
||||
A strategy instance uses target OR explicit-order mode; mixed intent styles reject in v1. The ledger stores remaining cost amounts, not reconstructed rounded-average basis. Statistical report functions reuse reviewed TS calculations over authoritative Rust values; only profiling justifies a native port.
|
||||
|
||||
Portfolio allocation is initially an explicit TS policy producing per-strategy budgets, not a new optimizer class. Rust enforces both those registered budgets and stricter account constraints. No cross-strategy netting in v1; order priority is stable strategy-instance/intent sequence. Independent models can produce ordinary typed scores; a universal signal schema is unnecessary.
|
||||
|
||||
## Example end-to-end lifecycle
|
||||
|
||||
A TS strategy requests SMA20/SMA60, momentum and realized volatility. A volatility classifier consumes the same feature snapshot. After warmup, the strategy combines momentum and trend scores with a mean-reversion score; high-volatility regime lowers its desired quantity. It compares that target with its own holdings and returns one target intent. It cannot modify cash or bypass risk.
|
||||
|
||||
Rust resolves the target against existing owned orders, reserves fee-inclusive cash and validates portfolio limits. A completed-bar decision becomes eligible at the next interval's open or a subsequent quote, never the just-observed close. Adjacent bars may share a timestamp: ADR-003 explicitly orders close/decision before the next open under a disclosed zero-latency model; the strategy cannot inspect that open in advance. Matching emits an owned fill, fee and account/position effects; strategy state observes committed effects at the next decision. An exit is target zero and follows the same path. Reports reconcile to the ledger, including open terminal positions.
|
||||
|
||||
Research replays frozen data into this core. Paper sends normalized live observations into the same core through durable SQL transactions. Clock sources and liquidity inputs differ; financial transition rules do not. AI/untrusted decisions run outside the data/engine supervisor, receiving only the available prefix.
|
||||
|
||||
## What remains intentionally simple
|
||||
|
||||
No microservices rewrite, event-sourcing platform, generic workflow DAG runtime, universal plugin hierarchy, mandatory Rust strategy rewrite, browser IDE or optimizer framework. Existing journals remain where they already protect recovery. Shorting, corporate-action execution, intrabar stop paths and real brokers require explicit later policies, not permissive defaults.
|
||||
125
design/development/architecture/research-product.md
Normal file
125
design/development/architecture/research-product.md
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
# Integrated research product contracts
|
||||
|
||||
Status: approved under ADR-006 on 2026-10-23. This is the minimum product model, not a general laboratory system.
|
||||
|
||||
## Existing paths to preserve
|
||||
|
||||
- [BacktestListPageV2](../../../apps/stock/web-app/src/features/backtest/BacktestListPageV2.tsx#L17) already lists/creates definitions.
|
||||
- [BacktestDetailPageV2](../../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx#L24) already selects runs, renders charts/trades/configuration and links saved URLs.
|
||||
- [backtestApiV2](../../../apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts#L54) already exposes definitions, runs, results and controls.
|
||||
- [createRun](../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211) already freezes a request and creates dispatch in one transaction.
|
||||
- [run-updates](../../../apps/stock/web-api/src/websocket/run-updates.ts#L68) projects committed SQL state; reuse it.
|
||||
- [SQL migrations 06–13](../../../database/postgres/init/) already contain definitions, runs/results, dispatch, execution ledger, datasets and recovery.
|
||||
- [strategy/analytics placeholders](../../../apps/stock/web-app/src/app/App.tsx#L24) are not a strategy/research product today.
|
||||
|
||||
## Minimum entities
|
||||
|
||||
| Entity | Minimum contents / relationships | Mutability |
|
||||
| --- | --- | --- |
|
||||
| strategies (new) | ID, owner principal, name/status/docs, clone lineage, optional project | Metadata editable/archiveable |
|
||||
| strategy_versions (new) | Strategy ID, version ID, source/bundle and retained artifact, hashes, parameter schema, checkpoint/API version, review status | Published executable content immutable; review decisions audited separately |
|
||||
| research_projects (new) | ID, owner, title/description/status | Editable/archiveable |
|
||||
| hypotheses (new) | Project ID, proposition, author kind/ID, state, validation criteria | Revisioned narrative; evidence state cannot be self-asserted by AI |
|
||||
| backtests (existing) | Saved editable configuration template, optional version/project links | Edits do not change historical runs |
|
||||
| experiments (new) | Optional project/hypothesis links, version(s), bounded grid, seed, partitions, cost/risk policies, selection rule; immutable validation report when completed | Inputs frozen at submission; reports append-only; clone to change |
|
||||
| runs (existing) | Existing request/attempt/lease/cancel fields; experiment ID, trial key, frozen version/provenance, actor | Inputs immutable; execution state fenced |
|
||||
| backtest_results (existing) | One terminal result per run, economics/metrics versions, full retained provenance, limitations and correctness-test policy/version references | Append-only; no silent metric rewrites |
|
||||
| analysis_artifacts (new) | Kind (note/finding), revisioned narrative, authorship, exact run/version/retained-artifact references; reference experiment validation reports rather than storing a second copy | Versioned; evidence refs protected |
|
||||
| paper_deployments (later) | Human approval, version/account/policy/evidence IDs, activation history | Explicit transitions; no live deployment in this plan |
|
||||
|
||||
Project/hypothesis links are optional. Add their nullable foreign keys only when the referenced tables exist; R01/R06 must work without R03 or placeholder research rows. Keep any cross-epic additive link migration under one integrator-owned SQL lock.
|
||||
|
||||
A run is a durable logical trial; attempts already exist on it. Do not add a competing job/attempt table. Run/experiment many-strategy configuration is a frozen list of strategy-version + instance + parameter + budget records. Artifact hashes alone are insufficient: retain retrievable source/bundle/model bytes and dependency/build identity.
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
RESEARCH_PROJECT ||--o{ HYPOTHESIS : contains
|
||||
RESEARCH_PROJECT o|--o{ STRATEGY : organizes
|
||||
STRATEGY ||--o{ STRATEGY_VERSION : versions
|
||||
RESEARCH_PROJECT o|--o{ EXPERIMENT : contains
|
||||
HYPOTHESIS o|--o{ EXPERIMENT : motivates
|
||||
BACKTEST_TEMPLATE ||--o{ RUN : snapshots
|
||||
EXPERIMENT o|--o{ RUN : groups
|
||||
STRATEGY_VERSION }o--o{ RUN : frozen_configuration
|
||||
RUN ||--o| BACKTEST_RESULT : produces
|
||||
RUN }o--o{ ANALYSIS_ARTIFACT : supports
|
||||
```
|
||||
|
||||
The many-version/run relationship can initially live in validated frozen configuration JSON with referential validation; introduce a join table only if query or referential-integrity needs justify it. Findings' run references must have DB-enforced retention/integrity (small reference relation if needed), not only free-text links.
|
||||
|
||||
## API rules shared by browser and AI
|
||||
|
||||
Keep `/api/v2` and current operator sessions. New APIs follow the task-specific contracts, not a parallel `/ai/backtests` path.
|
||||
|
||||
- IDs are stable opaque IDs; every write records owner/actor. Server derives actor, never trusts submitted privilege fields.
|
||||
- Save template and submit run are explicit separate actions. Submit uses an idempotency key + input fingerprint; identical retry returns same run, different payload returns409.
|
||||
- Use typed errors:400/422 input,401/403 auth,404 missing,409 immutable/conflict/reference,429 AI budget,503 unavailable dependency. Async accepted work returns202 + run/experiment URL.
|
||||
- Persisted state is authoritative. Cancel acceptance is not completed cancellation; failed/incomplete runs cannot masquerade as successful zero return.
|
||||
- Existing run diagnostics remain authoritative. W01 exposes shared cancellation; native-unsupported pause/resume/speed controls are absent/disabled. Add per-run support metadata only when a real second supported control path needs it, not a generic capability registry.
|
||||
- Results distinguish financial engine, strategy execution mode, metrics/economics policy versions and provenance completeness. Maintain compatibility fields for old clients.
|
||||
- Reproduce-original pins original inputs; rerun-current creates a new request. Missing original code/dataset/model is a clear failure, not a fallback.
|
||||
- Comparison must surface mismatched costs, datasets, windows, engines and failed candidates; default ranking uses comparable completed project-gated runs.
|
||||
- Canonical single and batch submissions require a resolved retained dataset hash. Prepare sources before admission; individual sweep trials must not independently reload provider history.
|
||||
- Retention is archive-first. Referenced runs/versions/datasets/artifacts cannot disappear through an existing cascade.
|
||||
- UI/API do not calculate competing equity, fees or fills. Display-only formatting/downsampling never changes financial results.
|
||||
|
||||
## Product increments
|
||||
|
||||
| Slice | User journey | Tasks | Engine prerequisite |
|
||||
| --- | --- | --- | --- |
|
||||
| M1 exploratory workbench | Select supported existing strategy -> save/configure -> durable submit -> status/cancel -> results/trades -> reopen | W01–W04 | Existing engines, explicitly limited/legacy/ungated |
|
||||
| M2 organized research | Create project/hypothesis -> select immutable registered version -> run -> save evidence-qualified finding | R01–R04/R10 | Can ship alongside engine migration |
|
||||
| M3 reproducible canonical run | Choose version/dataset/cost/risk -> Rust run with TS decisions -> inspect -> reproduce original | F01/F02/F04–F08, D01, S01/S02, R05/R11/R12 | Canonical economics + explicit correctness tests |
|
||||
| M4 experiment loop | Preview sweep -> run -> compare -> validate out of sample/costs/regimes | R06–R09/S05 | M3 |
|
||||
| M5 AI loop | AI candidate -> bounded isolated experiments -> evidence -> human review -> paper promotion | A01–A04/S03/S04 | M4 + isolated code + verified paper path |
|
||||
|
||||
Do not delay M1/M2 for the entire Rust migration. Conversely, delivering those screens does not make old financial results trustworthy. M1 release requires C06 runtime isolation; exploratory labels never excuse interference with paper state.
|
||||
|
||||
Canonical source preparation is explicit and precedes run admission. Preview returns materialized source bytes and their normalized identity; retention captures those exact bytes through the existing immutable store. A subsequent source read may differ and must be requested explicitly. Canonical admission validates the retained content and atomically freezes its hash with the executable and policies; the worker verifies the binding before decisions. Retention retries reuse the captured input, and run retries reuse the retained dataset. This 2026-10-24 refinement supersedes the original asynchronous source-preparation-inside-run proposal, avoiding another run lifecycle without weakening frozen-input guarantees. Legacy v1 source preparation/readers retain their existing behavior.
|
||||
|
||||
## Example: bounded AI-assisted multi-strategy research
|
||||
|
||||
Illustrative workflow, not a claim of profitable results:
|
||||
|
||||
1. An authorized agent registers the hypothesis “trend and mean-reversion components benefit from different volatility budgets” in a project. It specifies validation criteria before seeing held-out results.
|
||||
2. It selects immutable SMA and mean-reversion versions (or submits isolated candidate artifacts), two strategy instances per asset, a frozen multi-asset dataset, a fixed seed and long-only account/risk policy. The execution series is 1m; 5m/1h inputs are feature-only. Model/threshold fits use training data only.
|
||||
3. It previews a bounded grid: 3 fast windows × 2 slow windows × 2 high-volatility multipliers = 12 candidate portfolios. A declared 30-trial research budget admits those 12, with all failures retained.
|
||||
4. It selects at most two candidates using the recorded validation criterion, then requests 3 cost scenarios each (6 runs) and 4 chronological walk-forward segments each (8 runs). Two final held-out runs bring the total to 28; each admission still checks remaining budget. The held-out data is not exposed to candidate code before its designated phase.
|
||||
5. It compares aggregate and per-owner equity/P&L, regime sample counts, turnover, cost sensitivity and failed execution diagnostics. A finding cites the exact 28 run IDs/configurations and distinguishes exploratory selection from held-out evidence. Failure to outperform the baseline remains a valid finding.
|
||||
6. The user opens the same experiment in the web app, inspects trades/positions, reproduces an original run, requests further validation if desired and explicitly approves a version for paper trading only after S04 readiness. The agent cannot activate paper or live trading.
|
||||
|
||||
No extra AI database, simulator or agent framework is needed for this workflow.
|
||||
|
||||
## UI conventions and tests
|
||||
|
||||
Reuse current Card/Dialog/DataTable/layout/chart/metric components and responsive layouts. Add only research/strategy/experiment navigation. Preserve draft input on errors, show loading separate from empty, label incomplete/cancelled/legacy/ungated results, and allow reopening exact saved URLs. Do not replace working components for cosmetic consistency.
|
||||
|
||||
Existing [analytics-ui tests](../../../test/integration/analytics-ui.test.tsx#L1) use server rendering. W04 now supplies the shared [Playwright workflow harness](../../../test/e2e/workbench.test.ts), real authenticated Hono routes, disposable SQL/Redis, durable dispatch and native smoke coverage. Extend it for research-product flows instead of creating a second harness.
|
||||
|
||||
R11 exposes retained v1 metadata and exact hash selection in both backtest forms. Catalog coverage is unknown and full content integrity is not verified by metadata inspection; the runner validates retained bytes before binding/execution. That R11 milestone was legacy/v1 only. R05 subsequently added a separate fully validated v2 canonical picker and retained-input runner. Legacy source requests retain their original asynchronous behavior and economics qualifications; new canonical source preparation follows the before-admission sequence above.
|
||||
|
||||
## Review clarifications
|
||||
|
||||
- Metrics are derived by one reviewed reporting path from Rust ledger/session marks; the browser does not recalculate finances.
|
||||
- R06 provides small SQL summaries now. Full result pagination/storage normalization is deferred P05.
|
||||
- Project/catalog/dataset screens are not prerequisites for backend experiments or an AI client. Release still requires the applicable browser story and isolation gates.
|
||||
- Walk-forward v1 uses explicitly reset accounts/state per segment with indicator warmup. Display segment returns and reset semantics; do not label stitched independent capital as one continuous executable portfolio.
|
||||
- AI narratives cite run/version/metric paths. Traceable evidence is not automatic validation of an arbitrary natural-language conclusion.
|
||||
|
||||
Validation reports (R08) are immutable experiment-owned outputs, not research findings. Their display must work before R03. R09 enables save/link-finding only when R03 evidence APIs are present; the finding references the exact report and contributing runs, without moving financial truth into a second store.
|
||||
|
||||
|
||||
R01 now retains immutable bundled JavaScript and exact dependency locks with source/build metadata. Three tables support editable strategy metadata, immutable versions and append-only reviews. The offline seed command registers only locally packaged built-ins; HTTP uploads/clones remain candidates. Catalog parameter validation never evaluates code, and all versions remain explicitly non-runnable. R02 may deliver catalog/forms before R05, but version-based execution requires R05; arbitrary candidates additionally require A02. Review approval is evidence, not activation. Original TS source and complete run reproducibility remain outside this catalog-only claim.
|
||||
|
||||
|
||||
## A04 execution: human-reviewed paper promotion
|
||||
|
||||
The `/paper` workflow retains an immutable deployment before any account is bound. Select a sealed chronological or walk-forward **test** run and a fully completed standalone cost study from the same source dataset, strategy version, parameters, risk policy and research build. Review the exact retained code, including AI-originated code, and approve its catalog version separately. Supply a new account/session identity and explicit future feed, intraday observation cadence, risk clock and venue sessions; the platform does not infer them. Financial settings come from the selected saved cost scenario. Preview shows the exact evidence, paper-host identity and limitations; **Create halted deployment** records the promotion without activating trading. An uncertain response freezes the draft: use **Retry same promotion receipt**, which retains the original input and key.
|
||||
|
||||
To use an explicit paper host, build the orchestrator with `bun run --cwd apps/stock/orchestrator build` and apply the registered database migrations. Configure `services.orchestrator.defaultMode: paper`, durable PostgreSQL, and `services.orchestrator.paperDeploymentHost: { enabled: true }`; do not also configure `canonicalPaper`. An optional `deploymentId` binds that immutable deployment at startup but never activates it. Keep research workers in their separate research role. This configuration is opt-in; promotion does not change application defaults.
|
||||
|
||||
The web API requires an explicitly configured `ORCHESTRATOR_URL`. Both services must enable authentication, share the configured administrator credential (`STOCK_BOT_ADMIN_TOKEN`), and explicitly allow the browser origin through `STOCK_BOT_ALLOWED_ORIGINS`; the orchestrator verifies forwarded operator sessions. The original operator credential and Origin are checked at both ends. Development auth bypass, research-agent credentials and service tokens cannot authorize promotion, binding or activation. A missing host or mismatched origin is an unavailable/error state, never a fallback to service privilege.
|
||||
|
||||
Open the saved deployment, **Bind halted host**, connect the trusted feed, inspect readiness/recovery diagnostics, then explicitly **Activate paper**. Recovery of pending work requires the displayed acknowledgment. Restart preserves the same account cash, positions, owner checkpoints and execution journal; it does not recopy historical capital or strategy state. Use **Halt paper** before intervention. Later review revocation blocks new binding/activation but does not halt a running session automatically. Historical evidence and halt remain accessible.
|
||||
|
||||
Paper-host, native engine, dependency and runtime artifacts must remain immutable while running. Drift fails closed and requires restart; changed build/evidence requires a newly reviewed deployment and a new account, not an in-place account reset. Research and paper must share the native financial build, while their worker/host bundles have separate identities. Human promotion explicitly permits these exact bytes to run as trusted paper-host code; the research candidate sandbox does not extend to paper. Paper starts from factory state, uses quotes/displayed size rather than historical Open/volume fills, currently accepts one intraday strategy/asset, and has no live broker. Holdouts and cost sensitivity are retained evidence, not a performance guarantee.
|
||||
87
design/guide/README.md
Normal file
87
design/guide/README.md
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
# Understanding Stock Bot
|
||||
|
||||
Start here if you want to understand the repository before changing it. These guides describe the connected implementation as of **October 24, 2026**, with links to the code. They cover the stock platform; `apps/wcag-ada` is separate.
|
||||
|
||||
## The idea in one minute
|
||||
|
||||
You write a **TypeScript strategy** that looks at available market observations and asks for a desired position. The **Rust financial engine** decides whether that request is allowed, simulates execution, and updates money and positions. The **web application** lets you configure, run, compare and record this research.
|
||||
|
||||
The TypeScript backend connects those pieces. It saves exact inputs, dispatches jobs, supervises workers and records results. **PostgreSQL remembers what happened; Redis delivers work.** Historical prices are retained as hashed datasets so a later provider update does not silently change an old experiment.
|
||||
|
||||
In this repository, **canonical** means the supported, authoritative Rust financial path. You will also find older simulators and prototype interfaces. Their presence does not mean new web backtests use them.
|
||||
|
||||
## Read in this order
|
||||
|
||||
| Guide | Question it answers |
|
||||
| --- | --- |
|
||||
| 1. [System map](system-map.md) | What are the applications, libraries and databases, and how are they connected? |
|
||||
| 2. [Follow one backtest](backtest-walkthrough.md) | What happens between clicking Run and seeing a trade, result or failure? |
|
||||
| 3. [Understand and write a strategy](strategy-development.md) | Where does my trading logic go, what can it access, and what does it return? |
|
||||
| 4. [Read the implementation](code-reading.md) | Which functions call each other, who owns each piece of state, and why are the checks there? |
|
||||
|
||||
Read the diagrams and examples first. Follow the source links when a component becomes relevant; you do not need to understand every library before writing a strategy.
|
||||
|
||||
For code-level detail, the fourth guide links the documented callback contracts, replay loop, Rust financial methods, durable runner/repository and browser state hook. Their source comments explain invariants and failure behavior beside the implementation.
|
||||
|
||||
## A first tour through the product
|
||||
|
||||
When your local application is configured and running:
|
||||
|
||||
1. Open **Strategies**. Inspect a strategy family and an immutable version. Notice the parameters and executable identity; editing a new version must not change old runs.
|
||||
2. Open **Backtests**. A saved backtest is a reusable configuration. Its run history contains individual executions. Select an existing run before trying to configure a new one.
|
||||
3. On a run, inspect its inputs, status, provenance, equity and trades. Check whether it completed and which engine/policies produced it before interpreting its metrics. Older results retain their qualifications.
|
||||
4. Open **Experiments**. These group related trials, such as a parameter sweep. Follow a trial back to its individual run; comparison is not a separate simulator.
|
||||
5. Open **Research**. A project collects hypotheses and findings linked to evidence. An AI-written hypothesis or conclusion is still a claim; the cited runs are the inspectable evidence.
|
||||
|
||||
With an empty database, those pages may have no saved records yet. The walkthrough and test fixture below let you understand the flow without fetching market data. Creating a run requires a retained dataset and an eligible strategy version, not just a ticker symbol.
|
||||
|
||||
The standalone **Portfolio**, **Analytics** and **Settings** routes are currently placeholders. Run and experiment pages contain the implemented research analytics. See the [route map](../../apps/stock/web-app/src/app/App.tsx) for what each URL opens.
|
||||
|
||||
## Names you will see
|
||||
|
||||
| Term | Meaning here |
|
||||
| --- | --- |
|
||||
| **Strategy family / version** | A family organizes related revisions. A version pins a particular strategy definition and parameter contract. A run records the selected version and parameter values. |
|
||||
| **Backtest template** | A saved configuration you can edit and use to submit runs. Editing it does not rewrite a submitted run's inputs. |
|
||||
| **Run / attempt** | A run is one logical trial with frozen inputs. An attempt is one worker's claimed execution of it. Recovery can create another attempt without creating a different research question. |
|
||||
| **Retained dataset** | Exact validated bars and metadata, saved under a content hash. Provider storage is the mutable source; retention supplies the research snapshot. |
|
||||
| **Experiment** | A set of related runs with a saved comparison or search configuration. It can compare strategy candidates without combining their accounts. |
|
||||
| **Hypothesis / finding** | The question you propose and the conclusion you record. Findings can cite exact runs and artifacts. Neither is automatically proof of a successful strategy. |
|
||||
| **Intent / order / fill** | The strategy's desired exposure, the engine's executable instruction, and an actual simulated execution. An accepted intent is not a guaranteed fill. |
|
||||
| **Position / owner** | A held quantity and the strategy instance responsible for it. Financial attribution uses ownership rather than assuming every trade in a symbol belongs to the same strategy. |
|
||||
| **Event time / availability time** | When a market event happened versus when its information may be used. A completed bar cannot inform a decision before it becomes available. |
|
||||
| **Paper deployment** | A separately reviewed, explicitly activated paper account workflow. A completed research run does not activate it. |
|
||||
|
||||
## Learn from a small executable example
|
||||
|
||||
Start with the [SMA fixture](../../test/fixtures/canonical-sma.ts), then its [strategy](../../apps/stock/orchestrator/src/strategies/canonical-sma.ts) and [regression tests](../../test/integration/canonical-sma.test.ts). It uses seven bars and hand-checkable trades. The walkthrough explains why the final equity is `9969.30` from `10000` starting capital.
|
||||
|
||||
From the repository root, after dependencies and workspace/native builds are available:
|
||||
|
||||
```sh
|
||||
bun test test/integration/canonical-sma.test.ts
|
||||
```
|
||||
|
||||
This fixture does not need a provider connection or running databases. For initial build requirements and the broader check commands, use the [root README](../../README.md#build-and-verify).
|
||||
|
||||
## What is available, and what is still constrained
|
||||
|
||||
- New web research runs use one execution asset and one retained series, with cash-funded, long-only financial policies. Lower-level multi-asset contracts and tests do not make multi-asset web admission available.
|
||||
- TypeScript callback strategies, retained candidate packages, parameter sweeps, chronological validation, walk-forward studies and cost comparisons are connected research paths. The guides explain their boundaries rather than claiming every strategy or market model is supported.
|
||||
- Research workers can execute independent trials concurrently. That does not mean multiple workers can mutate the same account simultaneously.
|
||||
- Paper trading requires separate configuration, reviewed code and explicit human activation. Live trading is disabled; there is no connected real-broker execution adapter.
|
||||
- A large declarative strategy language and shared feature-cache framework are not required to understand or use the current callback path.
|
||||
|
||||
## Deeper references
|
||||
|
||||
- [Calculation library](../../libs/calculations/README.md): reviewed indicators and analytics, plus clearly separated preserved legacy functions.
|
||||
- [TypeScript strategy contract](../../libs/research/src/strategy-api.ts): the actual callback context and output types.
|
||||
- [Research product reference](../development/architecture/research-product.md): API policies, provenance and paper setup. Its original design examples and later implementation notes need to be read in context.
|
||||
- [Architecture decisions](../development/architecture/decisions): why the boundaries were chosen. These record decisions and migration context, not a substitute for the current runtime map.
|
||||
- [Platform plan](../PLATFORM-PLAN.md) and [milestones](../MILESTONES.md): target AI quant research architecture, locked design decisions (`D1`–`D12`), and phased build exit criteria.
|
||||
|
||||
When documentation and an implementation disagree, follow the current entrypoint, contract and focused regression test. Historical plans explain the direction; these guides explain how the current pieces fit together.
|
||||
|
||||
Primary navigation lists implemented workflows. Standalone Portfolio, Analytics and Settings
|
||||
remain unavailable at their existing URLs and are hidden from the menu. Saved backtest and
|
||||
experiment pages continue to provide performance, trade and risk analysis.
|
||||
195
design/guide/backtest-walkthrough.md
Normal file
195
design/guide/backtest-walkthrough.md
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
# Follow one backtest from the browser to the ledger
|
||||
|
||||
[Guide home](README.md) · [System map](system-map.md) · [Writing strategies](strategy-development.md)
|
||||
|
||||
The browser configures research; TypeScript organizes the work and makes strategy decisions; Rust decides what those decisions do to money and positions. PostgreSQL keeps the durable record. Redis delivers work to the orchestrator.
|
||||
|
||||
This walkthrough follows the current canonical research path. Its admitted runs use one retained strategy version and one eligible asset/series, with cash-funded long-only execution. Historical results and experimental code elsewhere in the repository do not expand that supported scope.
|
||||
|
||||
The [guide glossary](README.md#names-you-will-see) explains templates, runs, attempts, intents and fills.
|
||||
|
||||
## 1. Configure a run
|
||||
|
||||
Open a backtest, choose an immutable strategy version, select a prepared dataset, and configure capital, fees, slippage and risk. The browser checks execution eligibility before enabling submission. Missing dataset metadata or an unavailable retained build is an execution problem to resolve, not something the UI silently substitutes.
|
||||
|
||||
Start reading at [BacktestDetailPageV2](../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx), [CanonicalSetup](../../apps/stock/web-app/src/features/backtest/components/CanonicalSetup.tsx), and [backtestApiV2](../../apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts). The browser submits through `/api/v2/backtests/:id/runs` and later reads `/api/v2/runs/:id` and `/api/v2/runs/:id/results`.
|
||||
|
||||
The dataset records both **when a bar describes the market** and **when the completed bar becomes available**. A 09:03–09:04 bar cannot provide its close at 09:03. Delayed availability can be later than 09:04. Rust exposes observations according to availability, with explicit warmup and trading boundaries. See [historical-dataset-v2.ts](../../apps/stock/orchestrator/src/data/historical-dataset-v2.ts) and [how stored data becomes research input](system-map.md#how-stored-market-data-becomes-research-input).
|
||||
|
||||
## 2. Admission freezes the request and schedules it durably
|
||||
|
||||
[`admitCanonicalRequest()`](../../apps/stock/web-api/src/services/canonical-research.service.ts) validates the retained strategy package, dataset, parameters, policies and installed build identity. [`BacktestServiceV2.createRun()`](../../apps/stock/web-api/src/services/backtest-v2.service.ts) saves the immutable `request_snapshot` and a `backtest_dispatch` row in the same PostgreSQL transaction.
|
||||
|
||||
The dispatch row is an **outbox**: a durable promise to enqueue the run. If Redis is unavailable after the SQL commit, the saved request still exists. [`BacktestDispatcher`](../../apps/stock/web-api/src/services/BacktestDispatcher.ts) retries publication to the existing BullMQ queue. Queue messages carry the run ID; workers load the authoritative request from SQL.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant UI as Browser
|
||||
participant API as Web API / dispatcher
|
||||
participant DB as PostgreSQL
|
||||
participant Q as Redis / BullMQ
|
||||
participant Run as Orchestrator runner
|
||||
participant Child as Native worker / TS strategy
|
||||
participant Rust as Rust engine
|
||||
UI->>API: Submit saved configuration + submission key
|
||||
API->>DB: Save frozen run + dispatch intent atomically
|
||||
API-->>UI: Run ID
|
||||
API->>Q: Publish run ID
|
||||
Q->>Run: Deliver job to a pool slot
|
||||
Run->>DB: Claim attempt and load frozen request/dataset
|
||||
Run->>Child: Start disposable worker with exact inputs
|
||||
Child->>Rust: Load replay session through native binding
|
||||
loop Eligible decision barriers
|
||||
Rust-->>Child: Available observations + financial view
|
||||
Child->>Rust: Validated strategy intent
|
||||
Rust->>Rust: Risk checks, next-open matching, accounting
|
||||
end
|
||||
Rust-->>Child: Terminal financial report
|
||||
Child-->>Run: Validated result envelope
|
||||
Run->>DB: Commit result under attempt ownership
|
||||
UI->>API: Read saved status and result
|
||||
API->>DB: Read durable run
|
||||
API-->>UI: Financial report + analysis + provenance
|
||||
```
|
||||
|
||||
## 3. A runner owns the attempt; a child process owns the replay
|
||||
|
||||
[`ResearchBacktestPool`](../../apps/stock/orchestrator/src/backtest/ResearchBacktestPool.ts) reserves independent runner slots. Each slot has its own [`BacktestRunner`](../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts), which claims a database lease, renews it, reports progress, checks cancellation and commits only while it owns the attempt. This prevents an abandoned worker from overwriting its replacement's result.
|
||||
|
||||
[`RustBacktestAdapter.runCanonical()`](../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts) loads the frozen dataset and calls [`NativeBacktestWorker.execute()`](../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts). The native simulation runs in a disposable child process, so cancellation or a deadline can terminate it. That child has no database/service-container access.
|
||||
|
||||
[`native-worker.ts`](../../apps/stock/orchestrator/src/backtest/native-worker.ts) verifies the retained package and build before loading code. Approved built-ins execute as TypeScript callbacks there. Candidate code instead runs through the isolated candidate controller in its restricted container; it receives available observation prefixes, not the supervisor's full future dataset. Both paths submit decisions to the same Rust financial engine.
|
||||
|
||||
## 4. Follow a concrete SMA trade
|
||||
|
||||
The existing [SMA oracle](../../test/fixtures/canonical-sma.ts) and [regression test](../../test/integration/canonical-sma.test.ts) provide a small example you can calculate by hand. This synthetic fixture uses initial capital **10,000**, fast/slow periods **2/3**, strategy sizing budget **40**, a **1% fee**, and zero spread/slippage. These are test inputs, not recommended trading parameters.
|
||||
|
||||
| Bar | Open | Close | Key event |
|
||||
| --- | ---: | ---: | --- |
|
||||
| 1 | 3 | 3 | Start the history. |
|
||||
| 2 | 3 | 2 | Still gathering history. |
|
||||
| 3 | 2 | 1 | Enough for an average, but no crossover yet. |
|
||||
| 4 | 1 | 4 | Fast average crosses above slow; request a target of 10 shares. |
|
||||
| 5 | 5 | 5 | The entry fills at this open: 10 × 5, plus a 0.50 fee. |
|
||||
| 6 | 5 | 1 | Fast average crosses below slow; request a target of zero. |
|
||||
| 7 | 2 | 1 | The exit fills at this open: 10 × 2, less a 0.20 fee. |
|
||||
|
||||
[`createSmaStrategy().decide()`](../../apps/stock/orchestrator/src/strategies/canonical-sma.ts) retains its observed close history and emits a desired quantity. At bar 4's close, `40 / 4` gives ten whole shares. That sizing budget is a strategy input; Rust still checks actual cash, reservations and portfolio limits. It does not promise the future fill price will equal 4.
|
||||
|
||||
[`StrategyController`](../../apps/stock/orchestrator/src/strategies/strategy-controller.ts) validates callback state and intent against the current decision barrier. [`runReplaySession()`](../../apps/stock/orchestrator/src/backtest/native-replay.ts) drives the native session until another decision is needed or the run ends. Rust's [`Replay`](../../apps/stock/engine/src/financial/replay.rs) owns event order and information availability; [`MatchingAccount`](../../apps/stock/engine/src/financial/matching.rs), [risk](../../apps/stock/engine/src/financial/risk.rs) and [ledger](../../apps/stock/engine/src/financial/ledger.rs) own admissibility, fills and money.
|
||||
|
||||
The entry decision cannot fill at bar 4's open of 1: that price was already past when the close became known. It fills at bar 5's eligible open of 5. The exit similarly fills at bar 7's open of 2. Available volume and execution policy can restrict fills in other cases; a target is never proof that the whole position was filled.
|
||||
|
||||
Final cash and equity are **10,000 − 50 − 0.50 + 20 − 0.20 = 9,969.30**. Fees total **0.70**, and this example ends flat. The test checks exact fills, fees and equity, including identical financial output across different replay step budgets.
|
||||
|
||||
If a run ends with an open position, Rust values the remaining position using its terminal marks. It does **not** invent a closing sale or closing commission. Pending orders are cancelled at finish. Open positions, fills and terminal equity therefore belong in separate result views.
|
||||
|
||||
## 5. Save and inspect the result
|
||||
|
||||
Rust returns financial facts, including orders, fills, positions and valuation. [`buildCanonicalBacktestReport()`](../../libs/research/src/results.ts) derives statistical analysis from those facts without replacing the ledger. Unavailable metrics retain an explicit reason; an absent win rate or benchmark comparison is not zero performance.
|
||||
|
||||
`BacktestRunner` validates the result and commits it through [`PostgresBacktestRunRepository`](../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts). Completion notifications follow persistence. The browser's [CanonicalResults](../../apps/stock/web-app/src/features/backtest/components/CanonicalResults.tsx) and [ResultProvenance](../../apps/stock/web-app/src/features/backtest/components/ResultProvenance.tsx) render this saved record. Reloading the page reads the same run; it does not rerun the simulation. WebSocket updates help refresh the display, but the database owns status and results.
|
||||
|
||||
### Take the result into a notebook or local AI workflow
|
||||
|
||||
Open a completed canonical run and choose **Download run result**. The file,
|
||||
`run-<runId>.json`, contains the complete result already displayed, including the original
|
||||
request. Changing the backtest's editable settings does not change an earlier run's file.
|
||||
Downloading makes no additional API request and neither saves settings nor submits a run.
|
||||
|
||||
Useful fields for exploration:
|
||||
|
||||
| Field | Contents |
|
||||
| --- | --- |
|
||||
| `request` | Original dataset hash, strategy package/parameters, execution policy and engine/build identity. |
|
||||
| `financial.projection` | Native fills and terminal valuation. |
|
||||
| `financial.view` | Native orders, account and strategy-owned position views. |
|
||||
| `financial.reporting` | Evaluation bounds, session samples and reporting policy. |
|
||||
| `analytics` | Metrics, unavailable-value reasons and statistical assumptions. |
|
||||
|
||||
For a quick inspection with Bun:
|
||||
|
||||
```ts
|
||||
const result = await Bun.file('/path/to/run-<runId>.json').json();
|
||||
console.log(result.runId, result.request.datasetHash);
|
||||
console.table(result.financial.projection.fills);
|
||||
console.log(result.financial.projection.valuation, result.analytics.unavailable);
|
||||
```
|
||||
|
||||
Financial decimal strings and null metric values remain unchanged; chart rounding is not
|
||||
exported. Keep null reasons when comparing runs instead of treating missing metrics as zero.
|
||||
Pair the result with its [retained dataset download](../backtest-datasets.md#downloading-a-retained-snapshot-for-local-exploration)
|
||||
to explore observations and outcomes in VS Code, notebooks or local AI tools.
|
||||
|
||||
This is an analysis record, not a self-contained replay archive or an upload format. Bars
|
||||
and engine binaries are separate; use **Reproduce original run** for the existing retained
|
||||
execution path. The JSON includes the retained strategy JavaScript as text and never executes
|
||||
it during download or JSON inspection. A local download failure offers **Retry run result download**.
|
||||
|
||||
## 6. Retry, cancel and reproduce are different operations
|
||||
|
||||
| Operation | What to expect |
|
||||
| --- | --- |
|
||||
| Retry an uncertain submission | Resend the same submission key and body to recover the same run. Do not invent another key just because the HTTP response was lost. |
|
||||
| Recover a lost worker | The dispatcher detects an expired lease and may schedule a new attempt within the retry/deadline policy. Old ownership is fenced out. |
|
||||
| Retry a failed experiment trial | Review its recorded failure, then use the trial retry action. It preserves the frozen trial inputs and records retry history. |
|
||||
| Cancel | The API records cancellation; the runner stops work and records the terminal state. Request accepted and worker stopped are separate moments. |
|
||||
| Run the current configuration | Submit a new snapshot of the editable template, which may now differ from earlier runs. |
|
||||
| Reproduce a saved run | Use the reproduction action to preserve original input/build identity and compare financial hashes. Missing retained builds block reproduction rather than falling back to current code. |
|
||||
|
||||
See [RunReproduction](../../apps/stock/web-app/src/features/backtest/components/RunReproduction.tsx), [ExperimentTrialRecovery](../../apps/stock/web-app/src/features/experiments/components/ExperimentTrialRecovery.tsx), and the reproduction methods in `BacktestServiceV2`. Reproduction verifies economic output; elapsed wall time and new run IDs need not match. Arbitrary candidate JavaScript still needs deterministic authoring: retaining its code and seed does not make nondeterministic code deterministic.
|
||||
|
||||
## Grow one run into a research workflow
|
||||
|
||||
When a linked backtest cannot be loaded, the setup page keeps other successfully loaded
|
||||
catalog choices available and reports the lookup failure. The unavailable
|
||||
selection stays selected until you choose another; your experiment name and parameter grid
|
||||
are preserved. **Retry saved backtests** retries loading without automatically choosing a
|
||||
different template. Selecting a valid template does not save anything or submit runs; use
|
||||
the normal preview and confirmation steps.
|
||||
|
||||
1. Create a **research project and hypothesis**, link a strategy, and save the backtest configuration. Keep the proposed explanation separate from measured evidence.
|
||||
2. Create an **experiment** with a bounded parameter grid. Each trial uses the same durable run path above. Compare completed results alongside errors and incomplete trials.
|
||||
3. Use **chronological validation** to select on training data, then evaluate the selected parameters on held-out validation/test data. A saved sealed report links the evidence. Walk-forward applies this over windows; its current windows reset state and capital, so do not interpret them as one continuously traded account.
|
||||
4. Run **cost sensitivity** on the selected configuration and compare ordinary experiments with compatible inputs. Save findings with explicit run/report references.
|
||||
5. Reopen those saved IDs to inspect or reproduce the work. The browser is the normal research interface; authorized AI clients use the same backend capabilities with separate grants and budgets.
|
||||
|
||||
Project, hypothesis, note and finding creation also verifies the returned content before
|
||||
opening a saved record or showing success. If that acknowledgement cannot be verified,
|
||||
the original draft stays blocked. Use **Check saved projects** or **Check saved records**
|
||||
to review what committed; checking does not resubmit. Start a new request only after that
|
||||
review, or deliberately discard the draft and open the existing record.
|
||||
|
||||
When editing a saved hypothesis, note or finding, **Save new revision** clears the draft
|
||||
only after the returned revision matches its entry, submitted text and retained citations.
|
||||
An unverifiable acknowledgement may follow a committed write: the form preserves and
|
||||
blocks the draft without retrying. Review it, then deliberately choose **Discard draft and
|
||||
reload history** to inspect the saved revisions before deciding whether another edit is needed.
|
||||
|
||||
Project edits and archive/restore actions also verify their acknowledgement. An uncertain
|
||||
project update blocks further project and child writes; an uncertain entry archive blocks
|
||||
entry writes. Refreshing lists preserves that block and any draft. Use **Discard edits and
|
||||
reload project** or **Discard draft and reload archive state** to deliberately discard drafts
|
||||
and read the committed state before continuing. Entry archival may return a newer narrative
|
||||
revision from a concurrent editor; it does not append a narrative revision itself.
|
||||
|
||||
Open a hypothesis, note or finding and choose **Download saved revision** to take its
|
||||
narrative and citations into local analysis. When viewing history, the file contains that
|
||||
exact older revision. While editing, it exports the saved version and leaves your draft
|
||||
untouched. Archived entries can still be downloaded.
|
||||
|
||||
The file `research-<entryId>-<revisionId>.json` has `kind: "research-revision-export/v1"`,
|
||||
`projectId`, an `entry` identity/kind (including an artifact's linked hypothesis-revision
|
||||
ID), and the complete saved `revision`. Authorship, source/report hashes, raw cited values,
|
||||
unavailable reasons and limitations are preserved. Downloading uses the loaded record and
|
||||
makes no additional API request. A local failure offers **Retry saved revision download**.
|
||||
Pair it with the separate run-result and dataset files above for notebook or AI analysis.
|
||||
The file is an analysis record; replay uses the retained execution path.
|
||||
|
||||
Useful entry points are [ResearchProjectPage](../../apps/stock/web-app/src/features/research/ResearchProjectPage.tsx), [ExperimentDetailPage](../../apps/stock/web-app/src/features/experiments/ExperimentDetailPage.tsx), [ChronologicalValidationDetailPage](../../apps/stock/web-app/src/features/experiments/ChronologicalValidationDetailPage.tsx), and [WalkForwardDetailPage](../../apps/stock/web-app/src/features/experiments/WalkForwardDetailPage.tsx).
|
||||
|
||||
The [AI research-cycle example](../../scripts/examples/research-cycle.ts) submits prepared candidate packages, bounded searches, held-out validation and cost studies, then creates evidence-linked findings. It records request intents and receipts for recovery. It does not independently generate code, supply a model SDK or activate trading; AI-written findings remain distinguishable from validated results.
|
||||
|
||||
## How paper trading differs
|
||||
|
||||
Paper trading uses the same Rust financial kernel with fresh quote inputs, rather than replaying frozen historical opens. A human must review the required held-out/cost evidence and create a separate immutable deployment. [`PaperDeploymentHost`](../../apps/stock/orchestrator/src/paper/PaperDeploymentHost.ts) then requires explicit binding, readiness and activation; creating a deployment does not start trading. Candidate catalog approval alone is insufficient, and research agents cannot promote or activate deployments. Paper account/checkpoint recovery is separate from disposable research runs. Live broker deployment is not available through this workflow.
|
||||
116
design/guide/code-reading.md
Normal file
116
design/guide/code-reading.md
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
# Reading the implementation
|
||||
|
||||
The cleanup keeps old dataset/report paths as compatibility entrypoints. Read
|
||||
`libs/research/src/datasets.ts` for V2 normalization and hashes, and
|
||||
`libs/research/src/results.ts` for statistical reporting. The backtest API facade now delegates
|
||||
to `apps/stock/web-api/src/services/backtests/{templates,runs,reproduction,results}.ts`.
|
||||
Frontend run observation/submission, strategy cloning/version inspection and experiment
|
||||
submission each have focused hooks/components beside their existing pages. These moves
|
||||
preserve the Rust financial engine and saved-run contracts described below.
|
||||
|
||||
The API and orchestrator share server helpers through [`libs/trading-runtime`](../../libs/trading-runtime/package.json): historical storage, retained-package verification, paper admission and lazy build identity inspection. These modules do not run strategies or simulate money. Browser-safe wire schemas live under [`stock-config/contracts`](../../apps/stock/config/src/contracts), and strategy authors import only types from `@stock-bot/research/strategy-api`.
|
||||
|
||||
[`createResearchServices()`](../../apps/stock/web-api/src/services/research-services.ts) is the API composition point: it shares experiment, validation, evidence and result readers explicitly. The production run repository exposes canonical operations; historical write fixtures use the private compatibility adapter. On the web side, research read/edit/save lifecycles live in [feature hooks](../../apps/stock/web-app/src/features/research/hooks/useResearchEntry.ts), while components render their state.
|
||||
|
||||
|
||||
[Guide home](README.md) · [System map](system-map.md) · [Backtest walkthrough](backtest-walkthrough.md) · [Strategy authoring](strategy-development.md)
|
||||
|
||||
This guide follows **functions and state**, rather than application boxes. The linked TypeScript files now have explanatory TSDoc comments, and the Rust financial modules have module and method documentation. Read these beside the implementation; you can hover documented symbols in your editor.
|
||||
|
||||
## 1. Begin with the decision contract
|
||||
|
||||
Open [strategy-api.ts](../../libs/research/src/strategy-api.ts). `StrategyProgram` describes the object a strategy factory returns. Its `decide(context)` callback returns two things:
|
||||
|
||||
- `nextState`: what the strategy wants to remember for its next decision.
|
||||
- `intent`: what exposure or orders it wants the financial engine to consider.
|
||||
|
||||
Neither is a database write or a completed trade. `StrategyContext` is a read-only view. `positions` contains this owner's holdings; `portfolio.portfolio.positions` contains holdings across the account. `observations` contains the published input accumulated since this owner last ran. Keep any longer feature history in explicit state.
|
||||
|
||||
Then read [canonical-sma.ts](../../apps/stock/orchestrator/src/strategies/canonical-sma.ts). Follow `createSmaStrategy()` into `decide()`: validate/restore state → consume fresh observations → calculate crossover → return a target. The resulting quantity is a total desired holding. Rust decides the difference between that target, current holdings and working orders.
|
||||
|
||||
**A useful distinction:** a rejected order can still be a successfully processed strategy decision. The callback's state and random cursor advance when the native admission response is confirmed, even if risk rejected the requested order. Waiting for a fill before committing all strategy state would have different semantics.
|
||||
|
||||
## 2. Follow one callback into Rust
|
||||
|
||||
Read these symbols in order:
|
||||
|
||||
| Symbol | What to trace in its body |
|
||||
| --- | --- |
|
||||
| [`prepareReplayLoad()`](../../apps/stock/orchestrator/src/backtest/native-replay.ts) | Revalidates dataset bytes, matches execution series, and converts prices and names into the native wire format. It does not calculate strategy features. |
|
||||
| [`runStrategyReplay()`](../../apps/stock/orchestrator/src/backtest/strategy-runtime.ts) | Creates the controller and native session for a fresh attempt. Success includes diagnostics; failure retains the last confirmed diagnostics. |
|
||||
| [`NativeReplaySession.advance()`](../../apps/stock/orchestrator/src/backtest/native-replay.ts) | Calls the NAPI addon and validates the returned identity and schema. `eventBudget` limits work per call, not the number of bars in the experiment. |
|
||||
| [`replaySteps()`](../../apps/stock/orchestrator/src/backtest/native-replay.ts) | Accumulates observations until Rust requests a decision. Its generator alternates between staging decisions and confirming admission; both synchronous and isolated async drivers use it. |
|
||||
| [`StrategyController.stage()`](../../apps/stock/orchestrator/src/strategies/strategy-controller.ts) | Buffers inputs per owner and calls only owners due at the barrier, all against the same financial view. The next callback states are still proposals. |
|
||||
| [`stageStrategyDecision()`](../../apps/stock/orchestrator/src/strategies/strategy-decision.ts) | Constructs the owner-specific context, provides the seeded RNG, rejects async/lossy state, and stamps the decision identity. |
|
||||
| [`NativeReplaySession.submit()`](../../apps/stock/orchestrator/src/backtest/native-replay.ts) | Sends the complete batch to Rust and reads admission feedback. Later eligible market events determine actual fills. |
|
||||
| [`StrategyController.committed()`](../../apps/stock/orchestrator/src/strategies/strategy-controller.ts) | Checks revision and feedback for every staged owner before replacing confirmed state. Clears consumed input for owners that ran. |
|
||||
|
||||
A **barrier** is a point where Rust pauses historical advancement so all due strategies can decide from one account view. A faster callback must not get a newer view just because another callback already returned. A **revision** identifies which account/admission state a message belongs to; it helps reject stale or mismatched responses.
|
||||
|
||||
The research diagnostic snapshot is deliberately not a resume token. It lacks the complete financial state. An interrupted durable research attempt starts from the retained original inputs with a fresh native session. Paper recovery has its own durable account/checkpoint protocol.
|
||||
|
||||
## 3. Read the financial modules as a chain of responsibilities
|
||||
|
||||
Start at [financial/mod.rs](../../apps/stock/engine/src/financial/mod.rs), then:
|
||||
|
||||
| Module and symbols | What they own |
|
||||
| --- | --- |
|
||||
| [`Replay::events`, `advance`, `submit`](../../apps/stock/engine/src/financial/replay.rs) | Schedule available observations and physical execution events, stop for decisions, and require exactly the pending owners. Look at event phases and tie-breaking before changing timing. |
|
||||
| [`MatchingAccount::apply`, `submit`, `execute`](../../apps/stock/engine/src/financial/matching.rs) | Reconcile targets/orders, preserve correctly sized pending orders, apply execution eligibility and distribute finite fill capacity. |
|
||||
| [`RiskAccount::apply`, `reservation`](../../apps/stock/engine/src/financial/risk.rs) | Reserve cash or owner inventory and enforce financial constraints. An affordable order at submission can become unaffordable at a later gap price. |
|
||||
| [`Ledger::apply`, `apply_fill`, `valuation`](../../apps/stock/engine/src/financial/ledger.rs) | Post actual fills/fees, maintain owner cost basis and shared cash, and value remaining inventory. Checked decimal arithmetic lives in [scalar.rs](../../apps/stock/engine/src/financial/scalar.rs). |
|
||||
|
||||
Two details explain otherwise surprising results:
|
||||
|
||||
- At a bar's open, that bar's completed volume is still future information. Replay uses the latest published completed bar's volume for capacity. No known volume means no fill capacity.
|
||||
- Ending a replay cancels working orders and values existing holdings. It does not invent a liquidation trade or a closing fee. Inspect positions as well as closed trades.
|
||||
|
||||
The financial interfaces have command identities and receipts for retry handling. An exact retry may return old effects marked as replayed; callers must not publish them twice. A receipt is not the same thing as a strategy decision, a durable run or a worker attempt.
|
||||
|
||||
## 4. Understand how execution survives outside one process
|
||||
|
||||
The native session above is disposable. The durable workflow around it uses SQL state:
|
||||
|
||||
1. [`BacktestServiceV2.createRun()`](../../apps/stock/web-api/src/services/backtest-v2.service.ts) locks the saved template, admits its inputs and inserts both the frozen run request and `backtest_dispatch` row. A submission key recovers the same run after an uncertain HTTP response.
|
||||
2. [`admitCanonicalRequest()`](../../apps/stock/web-api/src/services/canonical-research.service.ts) resolves the retained version/dataset/build and constructs policies and a research account identity. It returns a request; it does not enqueue or simulate it. `canonicalCapability()` uses admission as a preview; new submissions check again, while receipt retries recover their already admitted run.
|
||||
3. [`BacktestDispatcher.dispatch()`](../../apps/stock/web-api/src/services/BacktestDispatcher.ts) first recovers expired leases, then reserves due outbox rows in SQL, then publishes run IDs to Redis outside the transaction. A failed publish delays delivery without deleting the saved intent.
|
||||
4. [`BacktestRunner.runQueued()` and `execute()`](../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts) load the saved request and claim an attempt. `execute()` coordinates heartbeats, progress, cancellation, worker execution and completion. It never edits a paper account.
|
||||
5. [`PostgresBacktestRunRepository.startCanonical()`](../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts) gives the worker a fresh attempt ID and lease. `loadCanonicalDataset()` checks the bound bytes under that ownership. `completeCanonical()` commits the validated result and completed status together.
|
||||
|
||||
The worker's **attempt ID is a fencing token**: SQL compares it with the current owner before allowing a write. A stopped worker that wakes up late cannot overwrite a replacement's result. The lease also has to be unexpired according to database time. A local Boolean such as `busy` only protects one runner instance; it cannot replace those database checks.
|
||||
|
||||
`BacktestRunner.execute()` has three phases: preparing, executing and persisting. Read its `try/catch/finally` as carefully as its success path. Lease uncertainty stops the attempt; it does not authorize the old worker to mark the run failed. Progress writes are drained before completion, and cleanup waits for heartbeat work before reusing the runner.
|
||||
|
||||
The adapter/process boundary is [RustBacktestAdapter.runCanonical()](../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts) → [NativeBacktestWorker.execute()](../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts) → [native-worker.ts](../../apps/stock/orchestrator/src/backtest/native-worker.ts). The parent can terminate a child that is stuck in native computation. The child still uses the same Rust engine; spawning a process does not introduce another simulator.
|
||||
|
||||
## 5. Trace the browser state separately
|
||||
|
||||
Open [useBacktestV2.ts](../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2.ts), then its caller [BacktestDetailPageV2.tsx](../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2.tsx).
|
||||
|
||||
- `loadBacktest()` loads the editable definition and run list. Generation counters discard late replies after navigation.
|
||||
- `selectRun()` and `refreshSelection()` own one status → result request chain. Polls and WebSocket refresh notifications converge on that chain.
|
||||
- `stopMonitoring()` aborts browser reads. `cancelRun()` requests server cancellation. Leaving the page is not cancelling the experiment.
|
||||
- `createRun()` keeps an in-memory submission key/body after an uncertain response. A repeated click can recover the same accepted run; this is not a persistent browser journal.
|
||||
- `runResults` comes from the saved result API. Charts render those facts; they do not reconstruct cash or fills from a second model.
|
||||
|
||||
The state names reflect different lifetimes: **template**, **selected run**, **submission**, and **result**. Combining them into one loading/error flag would make navigation and retry behavior harder to represent correctly.
|
||||
|
||||
## 6. Where a change belongs
|
||||
|
||||
| You want to change… | Start here |
|
||||
| --- | --- |
|
||||
| A signal, regime filter or entry/exit decision | Canonical strategy and its parameter/state contracts; see the [strategy guide](strategy-development.md). |
|
||||
| An indicator used in several places | [libs/calculations](../../libs/calculations/README.md), with its warmup/alignment semantics and fixtures. |
|
||||
| Which retained inputs can run | `validateCanonicalSetup()` / `admitCanonicalRequest()` and shared [canonical-research contracts](../../apps/stock/config/src/contracts/canonical-research.ts). |
|
||||
| Fill timing, fees, funding or position accounting | The corresponding Rust financial module and its existing regression tests. |
|
||||
| Worker retry, cancellation or result persistence | Dispatcher, runner and repository; keep attempt ownership checks intact. |
|
||||
| A run display, selection or loading/error state | Backtest feature components, hook and typed API client. |
|
||||
|
||||
Read tests as concrete examples of the contracts:
|
||||
|
||||
- [strategy-runtime.test.ts](../../test/integration/strategy-runtime.test.ts): owner isolation, buffered cadence, rejected intents, unconfirmed state and future-data boundaries.
|
||||
- [canonical-sma.test.ts](../../test/integration/canonical-sma.test.ts): hand-checkable signals, next-open fills and money.
|
||||
- [canonical-durable-runner.test.ts](../../test/integration/canonical-durable-runner.test.ts): cancellation, lease loss and retired execution paths.
|
||||
- Rust [replay](../../apps/stock/engine/src/financial/replay_tests.rs), [matching](../../apps/stock/engine/src/financial/matching_tests.rs), [risk](../../apps/stock/engine/src/financial/risk_tests.rs) and [ledger](../../apps/stock/engine/src/financial/ledger_tests.rs) tests: the economic invariants behind each layer.
|
||||
|
||||
For a first reading exercise, follow a request for ten shares through `stage()` → `submit()` → a later `execute()` → `apply_fill()`. At each step ask: **is this proposed state, accepted state, or persisted state?** Those boundaries explain most of the checks in this execution path.
|
||||
136
design/guide/strategy-development.md
Normal file
136
design/guide/strategy-development.md
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
# Understanding and changing a strategy
|
||||
|
||||
[Guide home](README.md) · [System map](system-map.md) · [Backtest walkthrough](backtest-walkthrough.md)
|
||||
|
||||
A strategy is a TypeScript function that reads observations and account state, then returns desired exposure plus its next state. Rust decides whether that exposure is affordable and permitted, creates orders, simulates fills, applies fees, and accounts for positions. Changing a signal should not require changing financial accounting.
|
||||
|
||||
## Read these files in order
|
||||
|
||||
| File | What to look for |
|
||||
| --- | --- |
|
||||
| [strategy-api.ts](../../libs/research/src/strategy-api.ts) | `StrategyProgram`, its `decide` callback, and the read-only `StrategyContext`. |
|
||||
| [canonical-sma.ts](../../apps/stock/orchestrator/src/strategies/canonical-sma.ts) | A complete strategy: validated parameters, versioned state, history, crossover, target quantity. |
|
||||
| [canonical-mean-reversion.ts](../../apps/stock/orchestrator/src/strategies/canonical-mean-reversion.ts) | Trend, momentum, volatility regime, entry filters, and exits composed in TypeScript. |
|
||||
| [canonical-builtins.ts](../../apps/stock/orchestrator/src/strategies/canonical-builtins.ts) | The small built-in factory and checks binding each strategy owner to its instrument and observation series. |
|
||||
| [strategy-controller.ts](../../apps/stock/orchestrator/src/strategies/strategy-controller.ts) | Callback state, deterministic random state, and native admission acknowledgement. |
|
||||
| [canonical-regime-research.test.ts](../../test/integration/canonical-regime-research.test.ts) | Concrete expected decisions, next-open fills, fees, equity, and repeatability. |
|
||||
|
||||
Start with these canonical files; older classes under `strategies/builtin/` belong to the earlier runtime.
|
||||
|
||||
## What the callback receives
|
||||
|
||||
| Context field | Meaning |
|
||||
| --- | --- |
|
||||
| `now`, `barrier` | Engine time and a synchronized decision point; each required input has an availability status. |
|
||||
| `observations` | Observations published since this owner last ran, including buffered input for slower decision cadences. `event_time` describes the market event; `available_at` says when the strategy may know it. This is not the entire historical dataset. |
|
||||
| `positions` | Positions already filtered to this strategy's `ownerId`. Select the relevant `instrumentId` when reading a holding. Account-wide positions are in `portfolio.portfolio.positions`. |
|
||||
| `portfolio` | Read-only native account view. A strategy cannot alter cash by changing this object. |
|
||||
| `state` | Your previously confirmed plain JSON state. Return a replacement in `nextState`. |
|
||||
| `previousAdmission` | The previous decision's admission outcome, not a stream of subsequent fills. Read current positions for current holdings. |
|
||||
| `random()` | Seeded random source valid during the synchronous callback. Use this instead of `Math.random()` when decisions require randomness. |
|
||||
|
||||
Keep history in explicit state, use engine time instead of `Date.now()`, and avoid network access or hidden mutable module state. Built-ins validate state shape and retain an observation watermark so late older bars cannot rewrite evaluated history. Candidate isolation limits access; it does not prove arbitrary code is deterministic or free of research bias.
|
||||
|
||||
## A minimal callback shape
|
||||
|
||||
Import author types from `@stock-bot/research/strategy-api`. This subpath contains only types; it exposes no native sessions, execution controllers, brokers, or storage services.
|
||||
|
||||
This simple callback requests one share when its series is fresh. It demonstrates the authoring contract; it is not a validated investment strategy or a ready-to-upload candidate package.
|
||||
|
||||
```ts
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import type { RetainedProgramSelection } from '@stock-bot/stock-config/candidate-execution';
|
||||
import type { StrategyProgram } from '@stock-bot/research/strategy-api';
|
||||
|
||||
export function createStrategy(
|
||||
selection: RetainedProgramSelection
|
||||
): StrategyProgram<null> {
|
||||
return {
|
||||
ownerId: selection.ownerId,
|
||||
strategyId: selection.strategyId,
|
||||
strategyVersion: selection.strategyVersion,
|
||||
seed: selection.seed,
|
||||
mode: 'target',
|
||||
initialState: null,
|
||||
decide(context) {
|
||||
const fresh = context.barrier.inputs.some(input =>
|
||||
input.series_id === selection.seriesId &&
|
||||
typeof input.availability === 'object' &&
|
||||
'Fresh' in input.availability
|
||||
);
|
||||
return {
|
||||
nextState: null,
|
||||
intent: {
|
||||
mode: 'target',
|
||||
targets: fresh
|
||||
? [{
|
||||
instrumentId: selection.instrumentId,
|
||||
quantity: parseFinancialDecimal('1'),
|
||||
}]
|
||||
: [],
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
For a self-contained source with no runtime imports, use [fresh-position.ts](../../libs/research/examples/fresh-position.ts). Its `shares` parameter must be a nonnegative safe integer; the example converts that checked integer to a fixed eight-decimal quantity. All imports erase during TypeScript transformation. [The public API tests](../../scripts/test/public-strategy-api.test.ts) compile the example outside the monorepo without path aliases, check the emitted module, and compare source and packaged decisions/state through the same Rust replay. Production candidate packaging still uses the existing isolated CLI; this test does not replace isolation or approval.
|
||||
|
||||
`quantity` is a desired **total holding for this owner**, not “buy this many more.” `parseFinancialDecimal('1')` creates the validated financial string `"1.00000000"`. Numeric arrays remain useful for features; financial postings use the decimal contract.
|
||||
|
||||
An empty target list means no new target update. An explicit zero target requests an exit. Neither guarantees a fill: Rust reconciles the target with holdings and pending orders, applies risk checks, and uses eligible future execution events. Never report a position change merely because the callback requested one.
|
||||
|
||||
The built-ins use [wholeShareTarget](../../apps/stock/orchestrator/src/strategies/canonical-sizing.ts) to size desired holdings from `ownerBudget`. That budget is a sizing input, **not an independently enforced owner allocation cap**. Native portfolio constraints are authoritative; parameters cannot grant borrowing or bypass risk.
|
||||
|
||||
## Features, signals, and regimes
|
||||
|
||||
`calculateMeanReversionSignals` computes a mean, z-score, trend return, momentum return, and return volatility from admitted closes. A low/high volatility label supplies an optional entry filter. This is a threshold model, not a statistically validated market classifier.
|
||||
|
||||
The strategy combines these values into entry and exit decisions and remembers desired exposure through partial execution. Keep a new feature or filter similarly explicit. Reuse the [calculation library](../../libs/calculations/README.md); do not create another ledger or fill calculator. No universal signal framework is required to add a second condition.
|
||||
|
||||
For a first change, follow one parameter from [the built-in selection schemas](../../apps/stock/config/src/contracts/builtin-strategy.ts), through the calculation and decision, into the [regime fixture](../../test/fixtures/canonical-regime-research.ts). Add a small test with known prices and expected targets before trying larger datasets. Compare the filter on/off under identical inputs using [the existing comparison example](../../apps/stock/orchestrator/examples/canonical-regime-research.ts). A favorable comparison still needs held-out validation.
|
||||
|
||||
## From source code to a saved candidate
|
||||
|
||||
The strategy page keeps one publication or clone workflow at a time. **Use in backtest**
|
||||
waits until that work is finished or cleared; opening a clone also disables candidate
|
||||
publication, and a loaded candidate package blocks starting a clone. Clear an unpublished
|
||||
package or explicitly discard the clone form to return to ordinary parameter handoff.
|
||||
If a write response was lost, use **Retry same publication** or **Retry clone** to recover
|
||||
the original request and key. These controls preserve the local retry information; they
|
||||
do not cancel work already accepted by the backend. Ordinary validated parameters still
|
||||
transfer directly to backtest setup.
|
||||
|
||||
Source, package, catalog version, execution, and promotion are separate steps:
|
||||
|
||||
1. **Author and test.** The factory returns the selected owner, strategy identity, version, and seed unchanged. Retained candidate factories currently use target mode. Start from the [sandbox test's small source factory and metadata fixture](../../test/integration/candidate-sandbox.test.ts); inspect the [package contract](../../libs/core/types/src/strategy-version.ts) and [candidate declarations](../../apps/stock/config/src/contracts/candidate-execution.ts) for exact fields.
|
||||
2. **Package.** With the pinned candidate sandbox installed, run `bun scripts/package-candidate-strategy.ts metadata.json strategy.ts > candidate-package.json` from the repository root. The [CLI](../../scripts/package-candidate-strategy.ts) validates declarations, transforms TypeScript in isolation, and hashes the output and lockfile. It does not evaluate the strategy or install dependencies. It accepts self-contained source; runtime imports such as the example's `parseFinancialDecimal` import require a self-contained artifact and are rejected by this CLI. Type-only imports erase during transformation. Declare `execution.kind: 'isolated-candidate/v1'` and the required `warmupBars`; that declaration is not proof the warmup is sufficient.
|
||||
3. **Publish.** Upload the package through the strategy catalog UI/API. This retains an immutable version; it does not execute the source. Use a new version for changed behavior. Catalog review records a review but does not grant trusted research execution.
|
||||
4. **Research.** Select that exact version, validate parameters, and submit a saved run or experiment. Candidates run inside the bounded OS sandbox, including reviewed candidates. Rust still owns financial semantics. Read [the backtest walkthrough](backtest-walkthrough.md) for result provenance and replay.
|
||||
5. **Consider paper trading separately.** [Paper promotion](../../apps/stock/web-api/src/services/paper-deployments.service.ts) checks sealed held-out and cost evidence plus build compatibility. Human promotion authorizes the exact bytes as trusted paper-host code: research isolation does not carry over. Binding and activation are separate explicit operations. Publishing, backtesting, and an AI recommendation do not activate paper or live trading.
|
||||
|
||||
The packaging path requires the built artifacts and pinned Linux x64 Docker sandbox, including its installed descriptor; see [repository setup](../../README.md). Missing isolation fails closed. Reading the code and running the pure tests below needs no provider credentials.
|
||||
|
||||
## Checks to use while learning
|
||||
|
||||
Run from the repository root after installing the repository dependencies:
|
||||
|
||||
```sh
|
||||
bun run test:calculations
|
||||
```
|
||||
|
||||
This checks the shared numerical helpers without native backtests.
|
||||
|
||||
After building the native engine and workspace artifacts with `bun run build`:
|
||||
|
||||
```sh
|
||||
bun test test/integration/canonical-regime-research.test.ts
|
||||
bun test test/integration/regime-research-example.test.ts
|
||||
```
|
||||
|
||||
These execute native financial semantics, including the hand-calculated entry/exit oracle and actual worker comparison runs. Run them in an environment that permits child-process IPC; a restricted coding-agent sandbox can stall the worker tests. They do not require a provider connection or a database. Sandbox and PostgreSQL suites have additional explicit prerequisites; use their fixture gates rather than pointing them at your regular trading state.
|
||||
|
||||
## Current scope to keep in mind
|
||||
|
||||
The admitted web research and promoted paper path is currently single-asset, single execution series, and long-only with cash funding. Lower-level replay fixtures cover broader combinations; that does not make every combination available in the product. There is no automatic live-broker activation. Preserve the immutable version, dataset, execution policy, engine build, and result links when you change a strategy: they are what make comparisons explainable.
|
||||
110
design/guide/system-map.md
Normal file
110
design/guide/system-map.md
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
# System map
|
||||
|
||||
[Guide home](README.md) · [Follow a backtest](backtest-walkthrough.md) · [Work on strategies](strategy-development.md)
|
||||
|
||||
This describes the implemented stock platform as of October 24, 2026. The useful starting point is **a TypeScript research application with a Rust financial engine**. TypeScript manages strategies, datasets, experiments, jobs and the web experience. Rust determines what orders can execute and how fills, fees, cash and positions change.
|
||||
|
||||
The repository contains several runnable applications and shared libraries. They share contracts and code; they do not all need to run for every workflow. In particular, replaying a retained dataset does not require fetching its provider again.
|
||||
|
||||
## The connected pieces
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Providers[Market data providers] --> Ingest[Data ingestion]
|
||||
Ingest --> Mongo[(MongoDB: provider records)]
|
||||
Mongo --> Pipeline[Data pipeline: exchange and symbol normalization]
|
||||
Pipeline --> PG[(PostgreSQL: durable application state)]
|
||||
Mongo --> Prepare[Dataset preparation and validation]
|
||||
Prepare -->|Retained bars and content hash| PG
|
||||
Browser[React web application] --> API[TypeScript web API]
|
||||
Agents[Authorized research clients and AI agents] --> API
|
||||
API --> Prepare
|
||||
API <-->|Strategies, experiments, runs and results| PG
|
||||
PG --> Dispatcher[Backtest dispatcher in web API]
|
||||
Dispatcher --> Redis[(Redis: job delivery)]
|
||||
Redis --> Pool[Orchestrator research worker pool]
|
||||
Pool <-->|Claim, heartbeat, result and recovery| PG
|
||||
Pool --> Worker[Bun child process per backtest]
|
||||
Worker --> Strategy[TypeScript strategy decisions]
|
||||
Strategy --> Rust[Rust native financial engine]
|
||||
Rust -->|Financial result| Worker
|
||||
Worker -->|Validated result| Pool
|
||||
```
|
||||
|
||||
The queue wakes a worker; PostgreSQL records whether work is actually pending, claimed, cancelled or finished. A queue message alone is not proof that a run succeeded. The browser reads saved state through the API, with WebSocket updates helping it refresh.
|
||||
|
||||
## Application folders and entrypoints
|
||||
|
||||
| Location | What it does | Start reading here |
|
||||
| --- | --- | --- |
|
||||
| `apps/stock/web-app` | React interface for strategies, research projects, backtests, experiments and paper deployment review. | [App.tsx](../../apps/stock/web-app/src/app/App.tsx) selects pages; [features/](../../apps/stock/web-app/src/features) contains workflows. |
|
||||
| `apps/stock/web-api` | HTTP contracts, research business logic, saved state, dataset preparation and durable job dispatch. | [index.ts](../../apps/stock/web-api/src/index.ts), [server-with-websocket.ts](../../apps/stock/web-api/src/server-with-websocket.ts), then [route composition](../../apps/stock/web-api/src/routes/create-routes.ts). |
|
||||
| `apps/stock/orchestrator` | Claims research work, supervises execution and persists results. An explicitly selected paper role can also own a paper account. | [index.ts](../../apps/stock/orchestrator/src/index.ts) starts it; [container.ts](../../apps/stock/orchestrator/src/container.ts) defines actual runtime composition. |
|
||||
| `apps/stock/engine` | Rust native library: replay, matching, ledger, risk and financial reporting. | [index.mjs](../../apps/stock/engine/index.mjs) loads `dist/engine.node`; [financial/](../../apps/stock/engine/src/financial) holds the canonical financial implementation. |
|
||||
| `apps/stock/data-ingestion` | Provider adapters, fetch/crawl jobs and provider record storage. | [index.ts](../../apps/stock/data-ingestion/src/index.ts), then [handlers/](../../apps/stock/data-ingestion/src/handlers). |
|
||||
| `apps/stock/data-pipeline` | Converts provider exchange/symbol metadata into the SQL catalog and records synchronization status. | [index.ts](../../apps/stock/data-pipeline/src/index.ts), [exchange sync](../../apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-all-exchanges.operations.ts), [symbol sync](../../apps/stock/data-pipeline/src/handlers/symbols/operations/sync-symbols-from-provider.operations.ts). |
|
||||
| `apps/stock/config` | Stock-specific configuration and API/policy contracts used across applications. | [index.ts](../../apps/stock/config/src/index.ts) and [contracts/](../../apps/stock/config/src/contracts). |
|
||||
|
||||
These are process roles within one codebase, not independent implementations of trading. The web API submits research work; the orchestrator executes it. The default orchestrator role is `research-only`. The paper role requires explicit configuration and rejects competing account owners. Both roles currently compose a research pool; selecting paper does not remove that pool.
|
||||
|
||||
The **Rust engine is not an HTTP service**. [NativeBacktestWorker](../../apps/stock/orchestrator/src/backtest/NativeBacktestWorker.ts) starts a Bun child process, and [native-worker.ts](../../apps/stock/orchestrator/src/backtest/native-worker.ts) loads and calls the native addon there. The process boundary lets the parent terminate stuck native work. It does not move accounting into TypeScript.
|
||||
|
||||
An untrusted candidate strategy gets another boundary: [candidate-sandbox.ts](../../apps/stock/orchestrator/src/backtest/candidate-sandbox.ts) runs its decision code in an isolated container. Financial execution stays in the trusted worker. This is distinct from the ordinary child process used for every research run.
|
||||
|
||||
## How stored market data becomes research input
|
||||
|
||||
There are two different kinds of data worth keeping separate:
|
||||
|
||||
1. **Provider storage changes over time.** For example, the [EOD intraday action](../../apps/stock/data-ingestion/src/handlers/eod/actions/intraday.ts) upserts bars into MongoDB collections such as `eodIntraday1M`. These are source records, not a reproducible experiment by themselves.
|
||||
2. **A retained dataset identifies exact research input.** [Stored-source preparation](../../apps/stock/web-api/src/services/stored-dataset-preparation.ts) reads a declared range through [StorageService](../../libs/trading-runtime/src/historical-storage.ts). It requires explicit metadata, converts rows into a v2 dataset, and previews its hash. [Dataset preparation](../../apps/stock/web-api/src/services/dataset-preparation.service.ts) verifies that same hash when retaining it. [Retention](../../libs/trading-runtime/src/retained-dataset.ts) saves the validated bars and manifest in PostgreSQL `backtest_datasets`.
|
||||
|
||||
Runs select that retained content by hash. A later provider correction therefore does not silently change an earlier run's input. Importing an explicit complete dataset is another route into the same validation and retention boundary.
|
||||
|
||||
The stored-source adapter currently accepts **one raw EOD intraday series at `1m`, `5m` or `1h`**, with declared timestamp and availability assumptions. It does not certify those source declarations independently. The exchange/symbol pipeline is a separate catalog workflow; bars do not have to pass through it before retention.
|
||||
|
||||
## What each store owns
|
||||
|
||||
| Store | Role and authority |
|
||||
| --- | --- |
|
||||
| **PostgreSQL** | Durable research state: strategy versions, retained datasets, experiments, run requests, dispatch records, leases and results. It also holds canonical paper execution state and checkpoints. See [web migrations](../../apps/stock/web-api/src/migrations) and [run repository](../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository.ts). Rust computes financial transitions; SQL preserves the committed state. |
|
||||
| **MongoDB** | Provider records and ingestion history, including the EOD bars used by stored-source preparation. Required for that ingestion/preparation path, not for replay of an already retained snapshot. |
|
||||
| **Redis-compatible storage** | BullMQ job delivery and service caches. The durable research run and its result remain in PostgreSQL. See [BacktestDispatcher](../../apps/stock/web-api/src/services/BacktestDispatcher.ts). |
|
||||
| **QuestDB** | An existing time-series adapter and historical storage route. The current web API, ingestion and pipeline entrypoints explicitly disable it in their container composition. Do not add it to the required retained-dataset research path just because the adapter exists. |
|
||||
| **Local build artifacts** | Native binary, worker bundle and retained strategy package identities are verified before execution. They supply executable code; they are not another account database. See [canonical-build.ts](../../libs/trading-runtime/src/canonical-build.ts). |
|
||||
|
||||
DI owns each service/global/proxy cache transport and closes only that container's connections.
|
||||
Their key prefixes and cache DB1 remain unchanged; queue data uses DB0 and each QueueManager
|
||||
owns its batch-cache transports. Direct shared-cache factory callers retain shared ownership.
|
||||
`database.dragonfly.ttl` sets the service/global default cache TTL; `keyPrefix` is a deprecated
|
||||
DI compatibility input and produces a diagnostic when set because service namespaces are fixed.
|
||||
`database.dragonfly.maxRetries` maps to cache/rate-limiter `maxRetriesPerRequest`, and
|
||||
`retryDelay` sets the fixed Redis reconnect delay in milliseconds. BullMQ workers deliberately
|
||||
keep unlimited per-request retries; producers keep their fail-fast request policy.
|
||||
QuestDB `bufferSize` and `flushInterval` are deprecated compatibility settings with no effect:
|
||||
the client does not run a background buffered writer. Nondefault values produce a diagnostic;
|
||||
explicit Influx writer operation options remain the supported batching interface.
|
||||
|
||||
## What the shared libraries are for
|
||||
|
||||
| Library | Why it exists |
|
||||
| --- | --- |
|
||||
| [core/types](../../libs/core/types/src) | Shared domain representations: instruments, datasets, strategies, runs and research results. Application contracts also live under stock config and orchestrator contracts; this is not the only contract folder. |
|
||||
| [core/config](../../libs/core/config/src) | General configuration loading and validation; `apps/stock/config` supplies stock-specific choices. |
|
||||
| [core/di](../../libs/core/di/src) and [core/services](../../libs/core/services/src) | Construct services and describe available capabilities. [ServiceApplication](../../libs/core/di/src/service-application.ts) handles common application startup for ingestion/pipeline. “DI” means dependency injection: passing dependencies into a component instead of constructing them inside it. |
|
||||
| [core/handlers](../../libs/core/handlers/src) and [handler-registry](../../libs/core/handler-registry/src) | Register and route service operations, particularly provider and pipeline jobs. |
|
||||
| [core/queue](../../libs/core/queue/src) and [core/cache](../../libs/core/cache/src) | Shared queue/caching infrastructure. They do not decide portfolio economics. |
|
||||
| [data/postgres](../../libs/data/postgres/src), [data/mongodb](../../libs/data/mongodb/src), [data/questdb](../../libs/data/questdb/src) | Database connection and adapter code. Application repositories define the meaning of stored records. |
|
||||
| [calculations](../../libs/calculations/README.md) | Reusable pure TypeScript indicators, market-data calculations, returns and analytics. Reviewed feature calculations remain useful to strategies; they do not replace Rust's ledger or fill model. |
|
||||
| [core/logger](../../libs/core/logger/src) and [core/shutdown](../../libs/core/shutdown/src) | Common diagnostics and lifecycle cleanup. |
|
||||
|
||||
## Current path versus preserved code
|
||||
|
||||
For current research, follow **web API → durable run → BacktestRunner → native worker → canonical financial core**. [ResearchBacktestPool](../../apps/stock/orchestrator/src/backtest/ResearchBacktestPool.ts) owns independent execution slots; [BacktestRunner](../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts) coordinates claims, cancellation and persistence. Batch experiments schedule this same execution path.
|
||||
|
||||
The [workbench admission gate](../../apps/stock/web-api/src/services/canonical-research.service.ts) currently requires one execution asset and one retained series. Multi-asset structures or exports elsewhere in the repository do not imply the web workbench supports them. Likewise, old simulator classes and native legacy exports are not the supported runtime authority: [container.ts](../../apps/stock/orchestrator/src/container.ts) rejects opting out of the canonical Rust engine.
|
||||
|
||||
Paper execution uses [CanonicalPaperRuntime](../../apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts), with reviewed deployment custody in [PaperDeploymentHost](../../apps/stock/orchestrator/src/paper/PaperDeploymentHost.ts). It shares Rust financial semantics while retaining durable decisions and recovery state. It requires explicit account configuration, a trusted feed and operator activation; a research result does not automatically place a real broker order.
|
||||
|
||||
The calculations package deliberately preserves [legacy APIs and research material](../../libs/calculations/README.md#preserved-legacy-apis). Preservation is not a claim that those formulas are reviewed production behavior. Older design documents and source comments can describe earlier migration stages; use the current entrypoints and their tests to establish what is connected today.
|
||||
|
||||
Continue with the [backtest walkthrough](backtest-walkthrough.md) to follow one request across these boundaries, or the [strategy guide](strategy-development.md) to understand where your own decision logic belongs.
|
||||
72
design/servers.md
Normal file
72
design/servers.md
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
# Infrastructure & Server Topology
|
||||
|
||||
Stock Bot runs across dedicated local-network hardware separating research/data-curation workloads from live/paper broker execution and cold archival storage.
|
||||
|
||||
---
|
||||
|
||||
## 1. Host Inventory
|
||||
|
||||
| Host | Hardware | OS & Storage | Primary Role |
|
||||
| --- | --- | --- | --- |
|
||||
| **`quant` (`12900K`)** (`10.0.0.51`) | Intel Core i9-12900K (16C / 24T), 125 GiB RAM | Ubuntu 24.04 LTS; OS NVMe + **4 TB WD Black SN850X NVMe** mounted at `/mnt/data` (`/home/boki/stockbot` → `/mnt/data/stockbot`, Docker `data-root: /mnt/data/docker`) | Primary QA/Research stack: raw MongoDB corpus, PostgreSQL security master & `trial_ledger`, curated Hive Parquet + DuckDB store, QuestDB `10.2.0` intraday store, `data-pipeline`, `data-ingestion`, `orchestrator`, `web-api`, `web-app`, monitoring |
|
||||
| **`9900K` (ITX)** | Intel Core i9-9900K (8C / 16T), 32 GB RAM, 1 GbE | Ubuntu 24.04 LTS, local NVMe | **Isolated Paper & Live Execution Host (`Milestone M5`):** headless `ib-gateway` (IBC), Python `ib-bridge` (`ib_async`), execution `orchestrator` + Rust `engine`, local Dragonfly state, hot rolling bar window. Zero research jobs or agent shell access |
|
||||
| **`TrueNAS` (`6700K`)** | Intel Core i7-6700K, 32 TB ZFS (`6×8 TB`), 2.5 GbE | TrueNAS SCALE, MinIO (S3-compatible) | Cold backups: immutable curated Parquet dataset snapshots, PostgreSQL `pg_dump` backups, `trial_ledger` & air-gapped vault archives |
|
||||
| **`Proxmox` (`8945HS`)** | AMD Ryzen 9 8945HS (8C / 16T) | Proxmox VE | Network & shared infrastructure: OPNsense, GitLab, Pi-hole |
|
||||
| **Workstation (local)** | Developer desktop | Linux | Interactive code editing, `docker-compose.dev.yml` isolated dev stack, local `marimo` notebooks (`127.0.0.1:2718`), Claude Code & Studio copilot agents |
|
||||
|
||||
---
|
||||
|
||||
## 2. `quant` (`10.0.0.51`) Service & Port Map
|
||||
|
||||
All 16 containers run from `/mnt/data/stockbot` (`docker compose --env-file .env.quant -f docker-compose.yml -f docker-compose.quant.yml`):
|
||||
|
||||
| Category | Container / Service | Host Port(s) | Notes |
|
||||
| --- | --- | --- | --- |
|
||||
| **UI & API** | `web-app` (Nginx) | `80`, `5173` | React dashboard & `/api` reverse proxy to `web-api` |
|
||||
| | `web-api` | `2003` | Research API, dataset/trial admission, WebSocket updates |
|
||||
| | `orchestrator` | `2004` | Durable research & backtest workers (Rust `engine` N-API addon) |
|
||||
| **Data Services** | `data-ingestion` | `2001` | Provider crawlers writing raw collections to MongoDB |
|
||||
| | `data-pipeline` | `2002` | Reads MongoDB strictly via `MONGODB_READ_URI` (`mongoReadOnly: true`); writes PostgreSQL master tables + curated Parquet/QuestDB |
|
||||
| **Databases** | `mongodb` (`stock`) | `27017` | ~638 GB multi-billion-doc raw corpus (`wiredTigerCacheSizeGB` bounded). **Never drop or write from `dev`/tests** |
|
||||
| | `postgres` (`trading_bot`) | `5432` | Security master, `trial_ledger`, backtests, promotions, `vault_evaluations` |
|
||||
| | `questdb` (`10.2.0`) | `9000` (HTTP/UI), `8812` (PGWire), `9009` (ILP) | Intraday `1m`/`5m`/`1h` & hot streaming bars (`listing_id SYMBOL CAPACITY 65536 NOCACHE`) |
|
||||
| | `dragonfly` | `6379` | BullMQ queues, pub/sub, ephemeral cache |
|
||||
| **Curated Files** | `/mnt/data/stockbot/curated/` | Host NVMe | Hive-partitioned Parquet (`bars_1d`, `corporate_actions`, `fundamentals_pit`, `earnings_events_pit`, `short_interest_pit`, `macro_pit`, `fx_rates_1d`, `features/`) queried in-process via DuckDB |
|
||||
| **Ops & Admin** | `grafana` | `3000` | Dashboards (`prometheus` + `loki`) |
|
||||
| | `bull-board` | `3001` | BullMQ job queue inspector |
|
||||
| | `loki` / `prometheus` | `3100` / `9090` | Centralized logs (`promtail`) & metrics |
|
||||
| | `pgadmin` / `mongo-express` | `5050` / `8081` | Database admin UIs (LAN-only) |
|
||||
|
||||
### 2.1 `quant` (`125 GiB` RAM) Memory, Shared-Memory & Kernel Budget
|
||||
|
||||
Enforced via [docker-compose.quant.yml](../docker-compose.quant.yml) + `/etc/sysctl.d/99-stockbot.conf` (`vm.max_map_count = 1048576`):
|
||||
|
||||
| Component | Engine-Internal Cap | Container `mem_limit` | Required OS / Container Settings |
|
||||
| --- | --- | --- | --- |
|
||||
| **MongoDB `7.0.21`** (`stock`) | `--wiredTigerCacheSizeGB 16` (`8` outside bulk ETL) | `24g` | `ulimits.nofile = 1048576` |
|
||||
| **QuestDB `10.2.0`** | `QDB_RAM_USAGE_LIMIT_BYTES=21474836480` (`20 GiB`), JVM `-Xms2g -Xmx4g` | `28g` | `ulimits.nofile = 1048576`, host `vm.max_map_count >= 1048576`, `bars_1m` `PARTITION BY MONTH` |
|
||||
| **PostgreSQL `16.9`** (`trading_bot`) | `shared_buffers=4GB`, `effective_cache_size=16GB`, `work_mem=64MB`, `maintenance_work_mem=1GB` | `10g` | **`shm_size: 2g`** (prevents `64m` `/dev/shm` parallel hash-join/index errors) |
|
||||
| **Dragonfly `v1.30.3`** | `--maxmemory=4gb --proactor_threads=4` | `5g` | Emulated cluster / hashtag locks |
|
||||
| **DuckDB + Workers + `web-api`** | `SET memory_limit='6GB'; SET threads=4; SET temp_directory='/mnt/data/stockbot/tmp/duckdb'` per worker | `30g` total | Prevents DuckDB's default `80%` host-RAM (`~100 GiB`) per-worker allocation |
|
||||
| **Monitoring & Admin** | Prometheus `--storage.tsdb.retention.time=15d` | `4g` total | Pinned versions across Prometheus, Loki, Grafana, Admin UIs |
|
||||
| **Linux OS Page Cache** | — | **~24 GiB unallocated** | Keeps hot SN850X NVMe Parquet & QuestDB `mmap` pages resident |
|
||||
|
||||
---
|
||||
|
||||
## 3. Local Development vs `quant` Separation
|
||||
|
||||
| Environment | Compose File | PostgreSQL | MongoDB (Write) | MongoDB (Read / Pipeline) | Dragonfly | QuestDB |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| **`dev` (workstation)** | `docker-compose.dev.yml` | `localhost:5433` (`trading_bot_dev`) | `localhost:27018` (`stock_dev`) | `quant:27017` or `localhost:27017` (`stock`, **read-only** via `MONGODB_READ_URI`) | `localhost:6380` | `localhost:9100` |
|
||||
| **`qa` (`quant`)** | `docker-compose.yml` + `docker-compose.quant.yml` | `10.0.0.51:5432` (`trading_bot`) | `10.0.0.51:27017` (`stock`) | `10.0.0.51:27017` (`stock`, `MONGODB_READ_URI` for `data-pipeline`) | `10.0.0.51:6379` | `10.0.0.51:9000` |
|
||||
| **Paper / Live (`9900K`)** | `docker-compose.prod.yml` (`M5`) | Isolated execution DB | None | Curated artifact pull only | Local `:6379` | Local `:9000` (90d hot window) |
|
||||
|
||||
> **Side-by-Side Local Execution:** On the `91 GiB` workstation, `docker-compose.dev.yml` (`stock-bot-dev-*` on `5433`/`27018`/`6380`/`9100`) and `docker-compose.yml` (`trading-bot-*` local QA stack on `5432`/`27017`/`6379`/`9000`) use non-overlapping ports, networks, and volume namespaces so both stacks run simultaneously without conflict (`./scripts/docker.sh start --dev && ./scripts/docker.sh start --qa`).
|
||||
|
||||
---
|
||||
|
||||
## 4. Isolation & Resource Rules
|
||||
|
||||
1. **Live/Paper Never Competes with Research:** `9900K` runs only execution processes (`ib-gateway`, `ib-bridge`, execution `orchestrator`, local Dragonfly/QuestDB). Heavy DuckDB sweeps, CPCV folds, and `data-pipeline` backfills run exclusively on `quant` (`12900K`).
|
||||
2. **Air-Gapped Holdout Storage:** On `quant`, the rolling 6-month vault partition (`/mnt/data/stockbot/vault/`) is readable only by the `vault-evaluator` OS/container user, never mounted into `marimo`, agent containers, or `web-api` research workers.
|
||||
3. **MongoDB Cache Discipline:** Keep MongoDB WiredTiger cache bounded on `quant` so OS page cache, DuckDB, PostgreSQL, and QuestDB retain ample headroom across the 125 GiB RAM pool.
|
||||
Loading…
Add table
Add a link
Reference in a new issue