154 lines
11 KiB
Markdown
154 lines
11 KiB
Markdown
# Architecture baseline and target
|
|
|
|
> **Historical planning baseline.** The observations and example interfaces below describe
|
|
> the pre-migration state and proposed design, not today's runtime. For the implemented
|
|
> connections and current strategy API, start with the [project guide](../../guide/README.md).
|
|
|
|
Planning baseline: commit `b7aeca4`, inspected 2026-10-22. This is a proposed plan, not an implementation or project correctness-gate evidence. [Decisions](../backlog/manifest.json) and [verified findings](../backlog/findings.md) distinguish user mandates, proposed policies and uncertainties.
|
|
|
|
## What exists
|
|
|
|
The React/Vite application already has saved backtest definitions, run selection, charts, trades and metrics. The Hono/Bun API writes a request snapshot and dispatch outbox in one PostgreSQL transaction. The existing dispatcher/queue and fenced runner claim attempts, freeze datasets, heartbeat leases and persist results. PostgreSQL-backed websocket projections and polling support status updates.
|
|
|
|
There are currently two economic implementations: a TypeScript simulation with durable account/decision recovery, and a native Rust backtester with its own fill/accounting behavior. The TS path can switch the shared paper ModeManager. Native TS callback registration is unsupported. Neither path should currently be treated as project-gated research performance.
|
|
|
|
```mermaid
|
|
flowchart LR
|
|
UI[Existing React backtest pages] --> API[Hono v2 backtest API]
|
|
API --> PG[(Postgres definitions / runs / dispatch / results)]
|
|
PG --> DIS[Existing dispatcher and queue]
|
|
DIS --> RUN[Fenced durable runner]
|
|
STORE[Provider storage] --> DATA[Frozen hashed datasets]
|
|
DATA --> RUN
|
|
RUN --> TS[TS BacktestEngine and SimulationExecution]
|
|
RUN --> NW[Native worker / NAPI]
|
|
NW --> OLD[Rust BacktestEngine]
|
|
TS --> MODE[Shared paper ModeManager: interference risk]
|
|
TS --> RESULT[Result adapters]
|
|
OLD --> RESULT
|
|
RESULT --> PG
|
|
PG --> WS[Websocket run projection / polling]
|
|
WS --> UI
|
|
```
|
|
|
|
Evidence: [transactional submission](../../../apps/stock/web-api/src/services/backtest-v2.service.ts#L211), [dataset freeze](../../../apps/stock/orchestrator/src/backtest/BacktestRunner.ts#L190), [recovery](../../../apps/stock/orchestrator/src/execution/StrategyRecovery.ts#L151), [shared mode mutation](../../../apps/stock/orchestrator/src/container.ts#L101).
|
|
|
|
## Target: one product, one financial core
|
|
|
|
```mermaid
|
|
flowchart TB
|
|
WEB[Primary React research workbench] --> API[TS research / strategies / experiments API]
|
|
AI[Authorized AI research client] --> API
|
|
API --> PG[(Existing Postgres metadata / immutable provenance / results)]
|
|
API --> Q[Existing dispatch + durable queue]
|
|
Q --> SUP[TS run supervisor / bounded worker pool]
|
|
DATA[Frozen datasets + retained model artifacts] --> SUP
|
|
SUP --> STR[TS strategy decisions / signal and regime composition]
|
|
SUP --> CORE[Rust replay + matching + owner ledger + risk]
|
|
STR -->|intents only| CORE
|
|
CORE -->|available context and effects| STR
|
|
PLAN[Optional small declarative plan] -.-> CORE
|
|
UNTRUSTED[Restricted TS process: no secrets or future dataset] -->|validated intents via IPC| SUP
|
|
CORE --> RES[Canonical economics / metrics / diagnostic artifacts]
|
|
RES --> PG
|
|
PAPER[TS paper adapter + durable transaction custody] --> CORE
|
|
PAPER --> JOURNAL[(Existing checkpoints / intents / execution journal)]
|
|
PG --> WEB
|
|
LIVE[Future broker adapter: disabled] -.-> CORE
|
|
```
|
|
|
|
This remains a modular monolith with existing operational processes and bounded computation workers—not a new service topology.
|
|
|
|
## Responsibility boundaries
|
|
|
|
| Boundary | TypeScript owns | Rust owns |
|
|
| --- | --- | --- |
|
|
| Product | UI/API, strategies/versions, projects, experiments, findings, configuration | No web business logic |
|
|
| Research | Candidate expansion, bounded scheduling, validation recipes, AI clients; reviewed statistical analytics over canonical results | Deterministic replay and authoritative financial result inputs |
|
|
| Strategy | Arbitrary compatible author logic, feature/signal composition, regime integration, checkpoint payload | Validated read-only context and decision admission |
|
|
| Features | Definitions, metadata, reviewed TS calculations when fast enough | Existing/bulk native calculation where profiling and parity justify it |
|
|
| Finance | Display/transport only; allocation preferences and intent proposals | Accepted quantities, reservations, positions, cost basis, cash, fees, order transitions, risk limits |
|
|
| Durability | Existing PostgreSQL transactions, leases, idempotency custody, retained artifacts | One financial kernel, versioned boundary snapshots and ordered effects |
|
|
| Execution | Provider/broker connectivity and reconciliation orchestration | Simulation semantics; canonical accounting/risk for observed broker facts |
|
|
|
|
A future broker's fills are external facts, not simulated prices. They must be accounted for even when a risk limit is breached, then trigger a halt/reconciliation workflow; they must not be silently discarded to make an invariant look satisfied.
|
|
|
|
## Minimal module shape
|
|
|
|
Keep current app and library boundaries. Add focused modules, not another package/service for every noun:
|
|
|
|
- `apps/stock/engine/src/financial/`: scalar types, ledger, ownership, risk, matching, replay. Adapt `positions/`, `risk/`, `backtest/` and `indicators/`; do not replace all Rust code.
|
|
- `apps/stock/orchestrator/src/strategies/`: versioned TS decision API, registry, built-ins, signals/regime functions.
|
|
- `apps/stock/orchestrator/src/backtest/`: existing durable runner/native worker, session adapter and later pool.
|
|
- `apps/stock/orchestrator/src/execution/`: existing transaction/recovery adapters, eventually without independent arithmetic.
|
|
- `apps/stock/web-api/src/{routes,services}/`: strategy/research/experiment additions alongside current backtests.
|
|
- `apps/stock/web-app/src/features/{backtest,strategies,research,experiments}/`: coherent research journeys.
|
|
- `libs/core/types/src/`: public versioned contracts. `libs/calculations/`: preserve reviewed semantics and migration inventory.
|
|
|
|
## Minimal decision contract
|
|
|
|
Illustrative contract to be implemented by F01/S01, not a new framework:
|
|
|
|
```ts
|
|
type Decimal = string; // validated fixed-scale transport, not JS money arithmetic
|
|
type Intent =
|
|
| { kind: "targetQuantity"; instrumentId: string; quantity: Decimal }
|
|
| { kind: "order"; instrumentId: string; side: "buy" | "sell";
|
|
quantity: Decimal; type: "market" | "limit"; limitPrice?: Decimal;
|
|
timeInForce: "DAY" | "GTC" | "IOC" | "FOK" };
|
|
|
|
interface DecisionContext {
|
|
decisionId: string;
|
|
nowMs: number; // engine availability clock
|
|
strategyInstanceId: string;
|
|
features: Readonly<FeatureSnapshot>; // only available prefix; includes regime inputs
|
|
positions: Readonly<OwnedPositions>;
|
|
portfolio: Readonly<AccountView>;
|
|
risk: Readonly<EffectiveRiskView>; // context, not a mutable policy object
|
|
random(): number; // run/strategy seeded stream
|
|
}
|
|
interface Strategy<State, Params> {
|
|
decisionCadence: { executionSeriesId: string; event: "barClose" };
|
|
initialState(params: Params): State;
|
|
onDecision(ctx: DecisionContext, state: Readonly<State>, params: Params):
|
|
{ nextState: State; intents: readonly Intent[] };
|
|
checkpointVersion: string;
|
|
}
|
|
// Trusted worker drives a pull loop; Rust never needs a reentrant JS callback.
|
|
const step = engine.advance(session, eventBudget);
|
|
switch (step.kind) {
|
|
case "progress": yieldToSupervisor(); break;
|
|
case "decisionBatch": {
|
|
// All contexts are from one immutable ledger revision; RNG is per strategy.
|
|
const staged = step.contexts.map(ctx => evaluateAndStage(ctx));
|
|
engine.submitDecisions(session, step.barrierId, staged.map(x => ({
|
|
strategyInstanceId: x.strategyInstanceId, decisionId: x.decisionId,
|
|
intents: x.intents,
|
|
})));
|
|
commitStagedStates(staged); // business rejections are committed outcomes
|
|
break;
|
|
}
|
|
case "complete": persistCanonicalResult(step.result); break;
|
|
}
|
|
// On exception/ambiguous crash: discard the attempt, never reuse half-advanced state.
|
|
```
|
|
|
|
S01 initially uses prefix-only observations and reviewed incremental calculations; D04 shared caching is optional. S02 ports one SMA first, not every builtin. All due callbacks finish against the same portfolio snapshot before admission.
|
|
|
|
The supervisor stamps owner identity; a strategy cannot forge another owner's ID. Target quantity is an **absolute desired holding**, not an additive order. Rust subtracts owned inventory plus outstanding commitments and applies risk. Repeated target decisions cannot duplicate orders. V1 cancels/replaces owned outstanding target orders deterministically; explicit orders use unique decision-derived IDs.
|
|
|
|
A strategy instance uses target OR explicit-order mode; mixed intent styles reject in v1. The ledger stores remaining cost amounts, not reconstructed rounded-average basis. Statistical report functions reuse reviewed TS calculations over authoritative Rust values; only profiling justifies a native port.
|
|
|
|
Portfolio allocation is initially an explicit TS policy producing per-strategy budgets, not a new optimizer class. Rust enforces both those registered budgets and stricter account constraints. No cross-strategy netting in v1; order priority is stable strategy-instance/intent sequence. Independent models can produce ordinary typed scores; a universal signal schema is unnecessary.
|
|
|
|
## Example end-to-end lifecycle
|
|
|
|
A TS strategy requests SMA20/SMA60, momentum and realized volatility. A volatility classifier consumes the same feature snapshot. After warmup, the strategy combines momentum and trend scores with a mean-reversion score; high-volatility regime lowers its desired quantity. It compares that target with its own holdings and returns one target intent. It cannot modify cash or bypass risk.
|
|
|
|
Rust resolves the target against existing owned orders, reserves fee-inclusive cash and validates portfolio limits. A completed-bar decision becomes eligible at the next interval's open or a subsequent quote, never the just-observed close. Adjacent bars may share a timestamp: ADR-003 explicitly orders close/decision before the next open under a disclosed zero-latency model; the strategy cannot inspect that open in advance. Matching emits an owned fill, fee and account/position effects; strategy state observes committed effects at the next decision. An exit is target zero and follows the same path. Reports reconcile to the ledger, including open terminal positions.
|
|
|
|
Research replays frozen data into this core. Paper sends normalized live observations into the same core through durable SQL transactions. Clock sources and liquidity inputs differ; financial transition rules do not. AI/untrusted decisions run outside the data/engine supervisor, receiving only the available prefix.
|
|
|
|
## What remains intentionally simple
|
|
|
|
No microservices rewrite, event-sourcing platform, generic workflow DAG runtime, universal plugin hierarchy, mandatory Rust strategy rewrite, browser IDE or optimizer framework. Existing journals remain where they already protect recovery. Shorting, corporate-action execution, intrabar stop paths and real brokers require explicit later policies, not permissive defaults.
|