# Strategy architecture and extension guide ## Supported execution paths HTTP and decorated backtest jobs use `BacktestRunner`, which owns input snapshots, claims, leases, terminal persistence and completion publication. - TypeScript backtests and paper trading use `StrategyManager` and `BaseStrategy`. Signals become captured order intents, then pass through `ExecutionService`. - Native backtests use `RustBacktestAdapter` and a disposable native worker process. The worker registers Rust strategies, not TypeScript callbacks. - The simulation ledger owns cash, positions, fills, pending reservations and risk admission. Strategy checkpoints contain decision state and journal-derived projections; they are not a second account ledger. Native market/analytics projections are not the paper account. Live routing and native TypeScript callbacks are explicitly unsupported. Do not create another inline executor, call native order submission, or bypass the runner for durable jobs. ## Runtime composition `container.ts` creates the runtime graph and binds each required dependency explicitly. The engines and strategy/mode/market-data lifecycle do not look up peers in `services.custom`. Both backends receive the same storage instance; the native adapter never constructs one. The strategy manager accepts a bound `createStrategy` callback instead of loading a registry or discovering the mode manager. Custom registries supplied through `registerOrchestratorServices` still receive `{ modeManager, execution }`; no strategy factory or checkpoint migration is needed. Deferred callbacks are wired only at composition: market flush awaits strategy delivery, and factories/backtests obtain the current mode's engine after mode initialization. `ModeManager` owns that engine; `StrategyManager` no longer caches a second reference or exposes a getter. Paper restoration still completes before feed startup, and shutdown still flushes the feed before stopping strategies, execution and storage. HTTP/job adapters retain the existing application lookup surface, separate from the internal graph. ## Strategy layout ```text src/strategies/ BaseStrategy.ts common signal, intent and checkpoint lifecycle StrategyManager.ts registration, delivery and restart recovery StrategyRegistry.ts injectable factory/alias registry builtin-strategies.ts lazy composition of concrete implementations builtin/ SmaCrossoverStrategy.ts canonical registered SMA implementation MeanReversionStrategy.ts canonical registered mean reversion experimental/ MLEnhancedStrategy.ts optional, run-local experiment ``` Core/API code loads concrete strategies through the registry, not direct imports. Built-ins cannot depend on experimental implementations. Parameter schemas live in `src/contracts/strategies.ts`; alias identity lives in `strategy-names.ts`. `backtest/strategy-plan.ts` gives both backends the same global-default/per-strategy-override precedence while retaining explicit backend-specific parameters and behavior. Run-wide fields are defined by `BacktestExecutionSettingsSchema` in the portable `@stock-bot/stock-config/backtest` contract. The planner projects legacy mixed configs into built-in parameters using that schema; do not add another manual execution-field exclusion list. Per-strategy copies of execution settings never override the run. Unknown parameter keys remain visible to strict strategy validation. Custom TypeScript factories keep their factory-owned extension fields, and original request/result configs stay intact for replay. The legacy `useTypeScriptImplementation` hint never changes the selected backend; `true` is rejected by the native path. Persisted aliases and checkpoint versions remain stable across this source relocation: SMA still reports `sma-crossover-fixed/v2`, and mean reversion reports `mean-reversion/v2`. The word `fixed` in the persisted version is compatibility metadata, not a second implementation. No financial data or saved checkpoints are rewritten. The earlier v1-to-v2 cutover requirement in the [root README](../../../../README.md#durable-strategy-recovery) still applies; this layout cleanup introduces no additional version change. ## Adding a strategy 1. Extend `BaseStrategy`, adding a focused module under `builtin/` for supported behavior or `experimental/` for research. Keep helpers independent of strategy lifecycle where possible. 2. Validate configuration at construction and inactive edits. Use explicit units, finite values and bounded periods. Existing built-in contracts reject unsupported keys instead of ignoring them. 3. Implement bounded per-instrument indicator state in `updateIndicators` and return a `Signal | null` from `generateSignal`. Reuse `@stock-bot/calculations/indicators` for trailing scalar SMA/deviation/crossovers, or the documented native indicator wrapper for other math. 4. For paper execution, provide a version string and complete finite-JSON capture/restore contract for custom state. Version changes and changed configurations require deliberate new strategy IDs; never reset an existing account or coerce an incompatible checkpoint. 5. Register a lazy factory and stable aliases in `createBuiltinStrategyRegistry()`, or inject a custom registry through `registerOrchestratorServices`. A custom registry must also be provided on restart. No manager switch or alternate execution loop is needed. 6. Test schema rejection, warm-up, multiple instruments, fill-based position changes and checkpoint/restart equivalence. Use real gateway admission and repository transactions, including rollback and duplicate-delivery cases. Callbacks run within a durable decision scope and must be deterministic and bounded. Do not perform external I/O, use wall-clock/random decision inputs, train models, launch fire-and-forget state mutations, or directly submit orders from callbacks. ExecutionService applies the account-level limits even when a strategy adds its own signal/sizing constraints. Do not recreate strategy-local cash/P&L books or a separate risk-admission manager. The [registry/recovery fixture](../../../../test/fixtures/strategy-recovery.ts) and [registry integration tests](../../../../test/integration/strategy-registry.test.ts) show an injected extension using the same lifecycle. The supported built-ins show complete configuration and indicator-checkpoint implementations. ## Experiments and examples ML remains lazy-loaded and explicitly experimental. It has no replay-safe model artifact or complete checkpoint contract, so paper activation fails before TensorFlow/model startup. Moving it under `experimental/` does not make its training deterministic or production-ready. [The multi-strategy example](../examples/multi-strategy-backtest.ts) accepts the application's already-composed TypeScript `BacktestRunner` and a qualified historical range. Importing it starts no services and executes nothing. The caller owns service shutdown; results come from the ordinary ledger-backed workflow and are persisted by the runner. For example: ```ts await runMultiStrategyBacktest(runner, { symbols: ['AAPL.US'], startDate: '2024-01-01T00:00:00.000Z', endDate: '2024-04-01T00:00:00.000Z', }); ``` This needs actual stored daily bars; it does not manufacture benchmark returns, correlations or broker features. The example is included in root type checking and exercised by the backtest workflow integration tests. Other old diagnostic scripts in `examples/` are not the supported extension contract. ## Retired paths The unused TypeScript `RustBacktestEngine`/`RustStrategy` callback wrapper and inline `StrategyExecutor` were removed. The unregistered original/V2/Rust SMA variants, `AdvancedMultiIndicatorStrategy`, `IndicatorBasedStrategy` and their private indicator/position/risk/signal-manager framework were also removed. They are recoverable from Git history (before this cleanup, commit `4207bf2`), not maintained runtime alternatives. Deep imports of those internal files must migrate to the registry or canonical implementation. The native SDK's explicit unsupported-operation errors remain as safety boundaries. ## Verification From the repository root: ```sh bun run check bun test test/integration/strategy-registry.test.ts test/integration/strategy-contracts.test.ts ``` The root gate checks cycles, registry-only strategy loading, retired entry points, worker-only native backtest access and the prohibition on direct strategy order submission. See the root README for disposable PostgreSQL/Redis safety tests; never run fixture resets against a development or production account.