123 lines
10 KiB
Markdown
123 lines
10 KiB
Markdown
# 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.
|