docs: add guided system and strategy walkthroughs
This commit is contained in:
parent
e4b31145da
commit
138aa047e2
5 changed files with 424 additions and 0 deletions
80
docs/guide/README.md
Normal file
80
docs/guide/README.md
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
# 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? |
|
||||
|
||||
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.
|
||||
|
||||
## 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](../../apps/stock/orchestrator/src/contracts/canonical-strategy.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.
|
||||
- [Backlog](../development/backlog/README.md) and [roadmap](../development/ROADMAP.md): work history, completion evidence and conditional future tasks.
|
||||
|
||||
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.
|
||||
120
docs/guide/backtest-walkthrough.md
Normal file
120
docs/guide/backtest-walkthrough.md
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
# 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()`](../../apps/stock/orchestrator/src/backtest/canonical-result.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.
|
||||
|
||||
## 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
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
123
docs/guide/strategy-development.md
Normal file
123
docs/guide/strategy-development.md
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
# 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 |
|
||||
| --- | --- |
|
||||
| [canonical-strategy.ts](../../apps/stock/orchestrator/src/contracts/canonical-strategy.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 across owners. Filter by **both** `ownerId` and `instrumentId` when reading your strategy's holding. |
|
||||
| `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
|
||||
|
||||
This is a deliberately simple **in-repository source example**, using imports as if placed beside `canonical-sma.ts`. It requests one share when its series is fresh; it is not an 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 '../contracts/canonical-strategy';
|
||||
|
||||
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'),
|
||||
}]
|
||||
: [],
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
`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/orchestrator/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
|
||||
|
||||
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.
|
||||
98
docs/guide/system-map.md
Normal file
98
docs/guide/system-map.md
Normal 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.
|
||||
Loading…
Add table
Add a link
Reference in a new issue