stock-bot/design/guide/system-map.md
2026-11-27 00:12:48 -05:00

13 KiB

System map

Guide home · Follow a backtest · Work on strategies

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

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 selects pages; features/ contains workflows.
apps/stock/web-api HTTP contracts, research business logic, saved state, dataset preparation and durable job dispatch. index.ts, server-with-websocket.ts, then route composition.
apps/stock/orchestrator Claims research work, supervises execution and persists results. An explicitly selected paper role can also own a paper account. index.ts starts it; container.ts defines actual runtime composition.
apps/stock/engine Rust native library: replay, matching, ledger, risk and financial reporting. index.mjs loads dist/engine.node; financial/ holds the canonical financial implementation.
apps/stock/data-ingestion Provider adapters, fetch/crawl jobs and provider record storage. index.ts, then handlers/.
apps/stock/data-pipeline Converts provider exchange/symbol metadata into the SQL catalog and records synchronization status. index.ts, exchange sync, symbol sync.
apps/stock/config Stock-specific configuration and API/policy contracts used across applications. index.ts and 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 starts a Bun child process, and 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 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 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 reads a declared range through StorageService. It requires explicit metadata, converts rows into a v2 dataset, and previews its hash. Dataset preparation verifies that same hash when retaining it. Retention 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 and run repository. 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.
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.

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 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 General configuration loading and validation; apps/stock/config supplies stock-specific choices.
core/di and core/services Construct services and describe available capabilities. ServiceApplication handles common application startup for ingestion/pipeline. “DI” means dependency injection: passing dependencies into a component instead of constructing them inside it.
core/handlers and handler-registry Register and route service operations, particularly provider and pipeline jobs.
core/queue and core/cache Shared queue/caching infrastructure. They do not decide portfolio economics.
data/postgres, data/mongodb, data/questdb Database connection and adapter code. Application repositories define the meaning of stored records.
calculations 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 and core/shutdown 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 owns independent execution slots; BacktestRunner coordinates claims, cancellation and persistence. Batch experiments schedule this same execution path.

The workbench admission gate 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 rejects opting out of the canonical Rust engine.

Paper execution uses CanonicalPaperRuntime, with reviewed deployment custody in PaperDeploymentHost. 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. 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 to follow one request across these boundaries, or the strategy guide to understand where your own decision logic belongs.