renames docs

This commit is contained in:
Boki 2026-11-27 00:12:48 -05:00
parent 4cd6038063
commit 13eb8352f3
25 changed files with 0 additions and 0 deletions

87
design/guide/README.md Normal file
View 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.

View 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.

View 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.

View 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
View 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.