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

14 KiB

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: 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, and strategy authors import only types from @stock-bot/research/strategy-api.

createResearchServices() 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, while components render their state.

Guide home · System map · Backtest walkthrough · Strategy authoring

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. 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. 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() Revalidates dataset bytes, matches execution series, and converts prices and names into the native wire format. It does not calculate strategy features.
runStrategyReplay() Creates the controller and native session for a fresh attempt. Success includes diagnostics; failure retains the last confirmed diagnostics.
NativeReplaySession.advance() 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() 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() 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() Constructs the owner-specific context, provides the seeded RNG, rejects async/lossy state, and stamps the decision identity.
NativeReplaySession.submit() Sends the complete batch to Rust and reads admission feedback. Later eligible market events determine actual fills.
StrategyController.committed() 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, then:

Module and symbols What they own
Replay::events, advance, submit 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 Reconcile targets/orders, preserve correctly sized pending orders, apply execution eligibility and distribute finite fill capacity.
RiskAccount::apply, reservation 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 Post actual fills/fees, maintain owner cost basis and shared cash, and value remaining inventory. Checked decimal arithmetic lives in 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() 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() 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() 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() 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() 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() → NativeBacktestWorker.execute() → 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, then its caller 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.
An indicator used in several places libs/calculations, with its warmup/alignment semantics and fixtures.
Which retained inputs can run validateCanonicalSetup() / admitCanonicalRequest() and shared canonical-research contracts.
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:

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.