docs: add guided system and strategy walkthroughs

This commit is contained in:
Boki 2026-10-24 18:59:25 -04:00
parent e4b31145da
commit 138aa047e2
5 changed files with 424 additions and 0 deletions

98
docs/guide/system-map.md Normal file
View file

@ -0,0 +1,98 @@
# 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](../../apps/stock/orchestrator/src/services/StorageService.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](../../apps/stock/orchestrator/src/data/retained-research-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](../../apps/stock/orchestrator/src/backtest/canonical-build.ts). |
## 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.