Refactor execution boundaries and add durable strategy recovery

This commit is contained in:
Boki 2026-10-21 12:23:43 -04:00
parent d6b09eb635
commit 694c48bbdb
36 changed files with 3077 additions and 491 deletions

101
README.md
View file

@ -65,6 +65,38 @@ Handler initializers receive their scanner/registry explicitly through the DI ap
initialization context. WebSocket connections and completion timers belong to the socket
handler and are released on close/shutdown.
## Orchestrator boundaries and extension points
Keep runtime composition in `container.ts`; domain code receives explicit capabilities,
not the application service container:
- `contracts/` holds runtime validation schemas. Contracts and the native worker protocol
cannot load storage, native engines, or server adapters.
- `execution/model.ts` owns accounting/risk rules; `execution/repository.ts` is the storage
port, independent of either implementation.
- `SimulationExecution` applies order admission, matching and accounting inside the caller's
transaction. It does not open transactions or publish notifications.
- `StrategyRecovery` owns decision scopes, checkpoint/cursor commits and outbox replay.
Its typed runtime port preserves the gateway's transaction and serialization boundaries.
- `ExecutionService` composes those components, owns lifecycle/market admission, selects the
repository, and publishes only after commit. HTTP and strategies continue using this gateway.
- `StrategyManager` owns lifecycle/delivery; `StrategyRegistry` owns strategy factories and
aliases. Add a lazy factory to `createBuiltinStrategyRegistry()`, or provide a custom
`strategyRegistry` to `registerOrchestratorServices`. No manager switch needs updating.
Keep persisted aliases stable; a custom registry must also be supplied on restart.
New paper strategies must provide a complete versioned checkpoint contract and recovery
tests. Registering a factory does not bypass risk checks or the durable-checkpoint requirement.
The experimental ML strategy remains unavailable for paper execution.
Architecture tests run in `bun run check`, checking runtime dependency cycles and the
contract/domain/adapter boundaries. The run-local ledger stages only transaction writes,
indexes active work and client IDs, and binary-searches the journal; retained history is not
deep-copied for every read. Reads/writes remain detached and failed transactions publish
nothing. History is still retained in memory for the run; this is not a streaming/retention
solution. Run `bun run scripts/benchmark-execution.ts` for a local journal-read microbenchmark,
not an end-to-end backtest performance estimate.
## Backtest data integrity
Historical storage no longer invents prices when a database is unavailable. Configure a
@ -130,6 +162,68 @@ and an explicit retention policy before scaling.
## Simulation order execution
### Durable strategy recovery
Apply additive migration `13-strategy-recovery.sql` through the web API before starting
the orchestrator. Paper startup restores registered strategy configurations and their
checkpoints before connecting the feed. No running database is migrated by the tests.
The recovery path has four checked transaction boundaries:
1. Validate and durably admit a uniquely identified market payload into
`simulation_market_inputs`; retries cannot append a second input or change its payload.
2. Apply the next input's quote/account changes and resting-order fills, journal the
execution notifications and market payload, and mark the input applied atomically.
3. Restore each strategy's latest checkpoint under the account row lock, evaluate its
next journal record, then commit indicator/base state, cursor, and order intents together.
4. Dispatch an intent through the ordinary risk/idempotency gateway; order/fill accounting,
its execution journal notification, and the intent's dispatched status commit together.
New inputs can queue during an outage or strategy error. Later inputs and new manual
orders cannot advance past unfinished enabled-strategy delivery or pending intents.
Idempotent order retries still return their committed report; explicit cancellations remain
available. Execution/fill notifications have their own durable cursor delivery, not a
volatile callback. Strategy reads use the journal's as-of account view, not future quotes.
Competing service instances always restore the locked checkpoint before evaluating a step.
The manager retries recovery every second without requiring another feed tick, and
`GET /api/recovery` exposes pending work and per-strategy cursor lag behind normal API auth.
SMA (both implementations) and mean reversion have explicit versioned indicator contracts.
Base checkpoints include positions, pending orders, performance and a bounded recent-fill
cache; the durable cursor, not the cache size, guarantees delivery deduplication. A changed
configuration or checkpoint/implementation version requires an explicit new strategy ID;
there is no implicit state reset or best-effort schema coercion. Developers must bump the
strategy version when its state or decision semantics change. Custom paper strategies must
implement and validate their complete finite-JSON checkpoint. Uncheckpointed/experimental
ML paper strategies fail **before** model startup: asynchronous model training and weights
do not yet have a replay-safe artifact contract. Run-local backtests can still use explicitly
unversioned experimental strategies, without claiming restart recovery for their custom state.
Strategy evaluation must be bounded and deterministic: no fire-and-forget state mutation,
wall-clock/random decisions, broker calls, model training or external I/O in callbacks.
Repository I/O/direct submissions from a callback fail closed; use the as-of account view
and captured order intents. These callbacks run under an account lock, so an unbounded
custom callback stalls that account until its owner exits; isolation/time limits for arbitrary
third-party code are not provided here. Noncritical signal/UI observers run after commit;
their failure cannot erase a financial intent, but those observations are not a durable bus.
Graceful shutdown suspends strategies without cancelling durable orders or erasing indicators.
`StrategyManager.disableStrategy` pauses **new decisions**, preserving already committed
intents and open orders; it is not an emergency order-cancel switch. Disabled-period market
records do not become retroactive signals on re-enable. To cancel, use the explicit order
API (or an intentional strategy stop). If a recovered paper quote has aged out, its indicator
state is recovered but it cannot generate fabricated historical fills: resulting stale-price
orders are rejected by the normal gateway.
Legacy fingerprints without payloads are preserved, not invented into replay history.
New registrations begin at the current journal boundary with the existing financial
projection; pre-migration indicators/performance cannot be reconstructed automatically.
This guarantees recovery of **admitted** inputs, not delivery from an upstream socket before
admission. A provider replay/acknowledgement protocol is still required for that boundary.
Journal/input/history tables currently retain JSONB payloads and as-of account snapshots;
configure an archival/retention design before high-volume production use. Do not delete
history still needed by a paused strategy's cursor.
`ExecutionService` is the runtime order gateway for REST, Socket.IO (when enabled), and
TypeScript strategies. `PaperTradingManager` is a compatibility facade, not a separate
simulator. Strategies consume only the ordered batch stream; individual-event broadcasts
@ -156,7 +250,8 @@ Paper configuration accepts `accountId` (default `paper-default`), `riskLimits`,
`slippage`, and `maxQuoteAgeMs` (default 60000). Restarting the same account restores cash,
positions, per-strategy quantities, consumed quote liquidity, and unfilled orders; it never
resets capital. A different starting capital requires an explicit new account ID. Strategy
indicator state is not checkpointed; strategies still need their normal warm-up. Pending
indicator state is checkpointed for supported strategies; a new strategy still needs its
normal warm-up. Pending
orders retain the commission/slippage policy under which they were accepted.
Order HTTP/Socket.IO submissions require a nonempty `clientOrderId`. Retrying an identical
@ -164,8 +259,8 @@ request returns the existing order; reuse with different fields is a conflict (H
Strategies derive stable IDs from the strategy and source event. Supply a stable, unique
`eventId` on market data; identical replay is ignored, conflicting reuse is rejected. Without
an ID, a deterministic hash of the canonical event is used (identical same-timestamp payloads
are indistinguishable). Source events commit before strategy callbacks; a crash in that gap
can omit a signal, so this is not an exactly-once strategy-state recovery guarantee.
are indistinguishable). Admitted source events, strategy delivery and financial notifications
now have durable recovery as described above; this is not a real-broker exactly-once guarantee.
The deterministic simulator supports market/limit orders and DAY/GTC/IOC/FOK. Quote depth
is consumed across orders, partial fills await fresh events, and limit orders never fill

View file

@ -1,6 +1,6 @@
import { z } from 'zod';
import type { BacktestRunResult, HistoricalDatasetManifest } from '@stock-bot/types';
import { datasetManifestSchema } from '../data/historical-dataset';
import { datasetManifestSchema } from '../contracts/historical';
import type { BacktestConfig } from '../types';
import type { NativeBacktestResult } from './native-result';
import type { RunIdentity } from './run-repository';

View file

@ -14,6 +14,7 @@ import { ExecutionService } from './services/ExecutionService';
import { MarketDataService } from './services/MarketDataService';
import { StorageService } from './services/StorageService';
import { StrategyManager } from './strategies/StrategyManager';
import type { StrategyRegistry } from './strategies/StrategyRegistry';
import type { OrchestratorServices as IServiceContainer } from './types';
/**
@ -27,6 +28,7 @@ export async function registerOrchestratorServices(
allowSyntheticData?: boolean;
syntheticSeed?: number;
nativeExecutionTimeoutMs?: number;
strategyRegistry?: StrategyRegistry;
} = {}
): Promise<void> {
// Create a service adapter that provides the expected interface
@ -49,7 +51,7 @@ export async function registerOrchestratorServices(
const marketDataService = new MarketDataService(services);
const executionService = new ExecutionService(services, storageService);
const analyticsService = new AnalyticsService(services, storageService);
const strategyManager = new StrategyManager(services);
const strategyManager = new StrategyManager(services, options.strategyRegistry);
Object.assign(custom, { StorageService: storageService });
const backtestEngine = options.useRustEngine
? new RustBacktestAdapter(services, { timeoutMs: options.nativeExecutionTimeoutMs })

View file

@ -0,0 +1,61 @@
import { z } from 'zod';
import { parseInstrumentId } from '@stock-bot/types';
export const instrumentIdSchema = z.string().refine(id => {
try {
parseInstrumentId(id);
return true;
} catch {
return false;
}
}, 'Use an exchange-qualified instrument ID, for example AAPL.US');
export const historicalDataPolicySchema = z
.object({
adjustment: z.enum(['raw', 'provider-adjusted']),
timestamp: z.enum(['utc-session-date', 'utc-instant']),
})
.strict();
export const datasetHashSchema = z.string().regex(/^[a-f0-9]{64}$/);
const positive = z.number().finite().positive();
export const datasetBarSchema = z
.object({
symbol: instrumentIdSchema,
timestamp: z.number().int().nonnegative(),
open: positive,
high: positive,
low: positive,
close: positive,
volume: z.number().finite().nonnegative(),
vwap: positive,
})
.strict();
export const datasetManifestSchema = z
.object({
version: z.literal(1),
hash: datasetHashSchema,
instruments: z
.array(
z.object({ id: instrumentIdSchema, symbol: z.string(), exchange: z.string() }).strict()
)
.min(1),
startDate: z.string().datetime(),
endDate: z.string().datetime(),
interval: z.enum(['1m', '5m', '15m', '1h', '1d']),
policy: historicalDataPolicySchema,
volumePolicy: z.literal('reported'),
qualityPolicy: z.literal('reject-invalid-no-interpolation'),
sources: z.array(
z
.object({
instrumentId: instrumentIdSchema,
provider: z.enum(['eod', 'questdb', 'synthetic']),
revision: z.string().min(1),
})
.strict()
),
barCount: z.number().int().positive(),
})
.strict();
export const datasetSchema = z
.object({ manifest: datasetManifestSchema, bars: z.array(datasetBarSchema).min(1) })
.strict();

View file

@ -108,6 +108,9 @@ export class ModeManager extends EventEmitter {
// Configure storage
await this.storageService.initialize(config);
if (config.mode === 'paper') {
await this.container.custom?.StrategyManager?.restoreStrategies();
}
// Admission is ready before a real-time feed can deliver events.
await this.marketDataService.initialize(config);
}
@ -158,14 +161,35 @@ export class ModeManager extends EventEmitter {
this.container.logger.info(`Shutting down ${this.mode} mode...`);
// Shutdown services
await this.marketDataService.shutdown();
await this.executionService.shutdown();
await this.storageService.shutdown();
let failure: unknown;
try {
await this.marketDataService.shutdown();
} catch (error) {
failure = error;
}
try {
await this.container.custom?.StrategyManager?.shutdown();
} catch (error) {
failure ??= error;
}
try {
await this.executionService.shutdown();
} catch (error) {
failure ??= error;
}
try {
await this.storageService.shutdown();
} catch (error) {
failure ??= error;
}
// Cleanup trading engine
this.tradingEngine = null;
this.isInitialized = false;
this.emit('shutdown');
if (failure) {
throw failure;
}
}
}

View file

@ -1,73 +1,14 @@
import { createHash } from 'node:crypto';
import { z } from 'zod';
import {
parseInstrumentId,
validateHistoricalDataRequest,
type HistoricalDataPolicy,
type HistoricalDataset,
} from '@stock-bot/types';
import { datasetSchema } from '../contracts/historical';
import type { StorageService } from '../services/StorageService';
import type { BacktestConfig } from '../types';
export const instrumentIdSchema = z.string().refine(id => {
try {
parseInstrumentId(id);
return true;
} catch {
return false;
}
}, 'Use an exchange-qualified instrument ID, for example AAPL.US');
export const historicalDataPolicySchema = z
.object({
adjustment: z.enum(['raw', 'provider-adjusted']),
timestamp: z.enum(['utc-session-date', 'utc-instant']),
})
.strict();
export const datasetHashSchema = z.string().regex(/^[a-f0-9]{64}$/);
const positive = z.number().finite().positive();
export const datasetBarSchema = z
.object({
symbol: instrumentIdSchema,
timestamp: z.number().int().nonnegative(),
open: positive,
high: positive,
low: positive,
close: positive,
volume: z.number().finite().nonnegative(),
vwap: positive,
})
.strict();
export const datasetManifestSchema = z
.object({
version: z.literal(1),
hash: datasetHashSchema,
instruments: z
.array(
z.object({ id: instrumentIdSchema, symbol: z.string(), exchange: z.string() }).strict()
)
.min(1),
startDate: z.string().datetime(),
endDate: z.string().datetime(),
interval: z.enum(['1m', '5m', '15m', '1h', '1d']),
policy: historicalDataPolicySchema,
volumePolicy: z.literal('reported'),
qualityPolicy: z.literal('reject-invalid-no-interpolation'),
sources: z.array(
z
.object({
instrumentId: instrumentIdSchema,
provider: z.enum(['eod', 'questdb', 'synthetic']),
revision: z.string().min(1),
})
.strict()
),
barCount: z.number().int().positive(),
})
.strict();
const datasetSchema = z
.object({ manifest: datasetManifestSchema, bars: z.array(datasetBarSchema).min(1) })
.strict();
export type DatasetResolver = (
load: () => Promise<HistoricalDataset>
) => Promise<HistoricalDataset>;

View file

@ -0,0 +1,294 @@
import { defined } from '@stock-bot/invariants';
import type { Account, StoredOrder } from './model';
import {
ExecutionConflictError,
type ExecutionRepository,
type ExecutionTransaction,
} from './repository';
import {
canonicalJson,
type MarketInput,
type StrategyCheckpoint,
type StrategyJournalEvent,
type StrategyOrderIntent,
} from './strategy-recovery';
/** Only transaction writes are staged; committed history is never copied on entry. */
class TransactionMap<T> {
readonly writes = new Map<string, T>();
constructor(private readonly base: Map<string, T>) {}
get(key: string): T | undefined {
return this.writes.get(key) ?? this.base.get(key);
}
put(key: string, value: T): void {
this.writes.set(key, structuredClone(value));
}
*values(): Iterable<T> {
for (const [key, value] of this.base) {
yield this.writes.get(key) ?? value;
}
for (const [key, value] of this.writes) {
if (!this.base.has(key)) {
yield value;
}
}
}
commit(): void {
for (const [key, value] of this.writes) {
this.base.set(key, value);
}
}
}
interface RunState {
account: Account;
orders: Map<string, StoredOrder>;
clients: Map<string, string>;
openOrders: Set<string>;
fills: Set<string>;
events: Map<string, string>;
journal: StrategyJournalEvent[];
strategies: Map<string, StrategyCheckpoint>;
intents: Map<string, StrategyOrderIntent>;
pendingIntents: Set<string>;
inputs: Map<string, MarketInput>;
pendingInputs: Set<string>;
}
const compareText = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
const isOpen = (order: StoredOrder) =>
order.report.status === 'accepted' || order.report.status === 'partiallyFilled';
const compareIntents = (a: StrategyOrderIntent, b: StrategyOrderIntent) =>
a.sequence - b.sequence ||
compareText(a.strategyId, b.strategyId) ||
compareText(a.clientOrderId, b.clientOrderId);
/** Binary search works with nonzero initial sequence numbers as well as empty journals. */
function after(journal: StrategyJournalEvent[], cursor: number): StrategyJournalEvent | undefined {
let low = 0,
high = journal.length;
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (defined(journal[mid]).sequence <= cursor) {
low = mid + 1;
} else {
high = mid;
}
}
return journal[low];
}
/** Iterate only active IDs plus staged writes, never the retained applied/dispatched history. */
function* candidates<T>(ids: Set<string>, table: TransactionMap<T>): Iterable<T> {
for (const id of ids) {
const value = table.get(id);
if (value !== undefined) {
yield value;
}
}
for (const [id, value] of table.writes) {
if (!ids.has(id)) {
yield value;
}
}
}
/** Explicit run-local backtest store, never a fallback for paper or live execution. */
export class BacktestExecutionRepository implements ExecutionRepository {
private state?: RunState;
private tail: Promise<unknown> = Promise.resolve();
async initialize(_id: string, account: Account): Promise<void> {
await this.tail;
this.state = {
account: structuredClone(account),
orders: new Map(),
clients: new Map(),
openOrders: new Set(),
fills: new Set(),
events: new Map(),
journal: [],
strategies: new Map(),
intents: new Map(),
pendingIntents: new Set(),
inputs: new Map(),
pendingInputs: new Set(),
};
}
transact<T>(_id: string, work: (tx: ExecutionTransaction) => Promise<T>): Promise<T> {
const task = this.tail.then(async () => {
const state = this.state;
if (!state) {
throw new Error('Execution account is not initialized');
}
const account = structuredClone(state.account);
const orders = new TransactionMap(state.orders);
const clients = new TransactionMap(state.clients);
const events = new TransactionMap(state.events);
const strategies = new TransactionMap(state.strategies);
const intents = new TransactionMap(state.intents);
const inputs = new TransactionMap(state.inputs);
const fills = new Set<string>();
const journal: StrategyJournalEvent[] = [];
let open = true;
const assertOpen = () => {
if (!open) {
throw new Error('Execution transaction has finished');
}
};
try {
const result = await work({
account,
async findOrder(id) {
assertOpen();
const orderId = clients.get(id);
return structuredClone(orderId === undefined ? undefined : orders.get(orderId));
},
async getOrder(id) {
assertOpen();
return structuredClone(orders.get(id));
},
async openOrders() {
assertOpen();
return structuredClone([...candidates(state.openOrders, orders)].filter(isOpen));
},
async putOrder(order) {
assertOpen();
const id = order.report.orderId;
const clientId = order.report.clientOrderId;
const existingId = clients.get(clientId);
if (existingId !== undefined && existingId !== id) {
throw new ExecutionConflictError('Client order ID already exists');
}
const old = orders.get(id);
if (old && old.report.clientOrderId !== clientId) {
throw new ExecutionConflictError('Order client ID cannot change');
}
orders.put(id, order);
clients.put(clientId, id);
},
async insertFill(_orderId, fill) {
assertOpen();
if (state.fills.has(fill.id) || fills.has(fill.id)) {
return false;
}
fills.add(fill.id);
return true;
},
async recordEvent(id, hash) {
assertOpen();
const previous = events.get(id);
if (previous !== undefined && previous !== hash) {
throw new ExecutionConflictError('Conflicting market event identity');
}
if (previous !== undefined) {
return false;
}
events.put(id, hash);
return true;
},
async appendJournal(payload) {
assertOpen();
const sequence = (account.strategySequence ?? 0) + 1;
if (!Number.isSafeInteger(sequence)) {
throw new Error('Strategy journal sequence exhausted');
}
account.strategySequence = sequence;
journal.push({ sequence, payload: structuredClone(payload) });
},
async nextJournal(cursor) {
assertOpen();
return structuredClone(after(state.journal, cursor) ?? after(journal, cursor));
},
async strategies() {
assertOpen();
return structuredClone(
[...strategies.values()].sort((a, b) => compareText(a.strategyId, b.strategyId))
);
},
async putStrategy(checkpoint) {
assertOpen();
strategies.put(checkpoint.strategyId, checkpoint);
},
async nextIntent() {
assertOpen();
let next: StrategyOrderIntent | undefined;
for (const intent of candidates(state.pendingIntents, intents)) {
if (intent.status === 'pending' && (!next || compareIntents(intent, next) < 0)) {
next = intent;
}
}
return structuredClone(next);
},
async putIntent(intent) {
assertOpen();
const old = intents.get(intent.clientOrderId);
if (
old &&
(old.strategyId !== intent.strategyId ||
old.sequence !== intent.sequence ||
canonicalJson(old.request) !== canonicalJson(intent.request) ||
(old.status === 'dispatched' && intent.status !== 'dispatched'))
) {
throw new ExecutionConflictError('Conflicting strategy order intent');
}
intents.put(intent.clientOrderId, intent);
},
async nextInput() {
assertOpen();
let next: MarketInput | undefined;
for (const input of candidates(state.pendingInputs, inputs)) {
if (input.status === 'pending' && (!next || input.sequence < next.sequence)) {
next = input;
}
}
return structuredClone(next);
},
async putInput(input) {
assertOpen();
inputs.put(input.id, input);
},
});
// Clone anything the callback can retain before publishing any staged writes.
const detachedResult = structuredClone(result);
state.account = structuredClone(account);
for (const table of [orders, clients, events, strategies, intents, inputs]) {
table.commit();
}
for (const [id, order] of orders.writes) {
if (isOpen(order)) {
state.openOrders.add(id);
} else {
state.openOrders.delete(id);
}
}
for (const [id, intent] of intents.writes) {
if (intent.status === 'pending') {
state.pendingIntents.add(id);
} else {
state.pendingIntents.delete(id);
}
}
for (const [id, input] of inputs.writes) {
if (input.status === 'pending') {
state.pendingInputs.add(id);
} else {
state.pendingInputs.delete(id);
}
}
for (const id of fills) {
state.fills.add(id);
}
for (const event of journal) {
state.journal.push(event);
}
return detachedResult;
} finally {
open = false;
}
});
this.tail = task.catch(() => {});
return task;
}
}

View file

@ -5,6 +5,13 @@ import {
type ExecutionRepository,
type ExecutionTransaction,
} from './repository';
import {
canonicalJson,
type MarketInput,
type StrategyCheckpoint,
type StrategyJournalPayload,
type StrategyOrderIntent,
} from './strategy-recovery';
export class PostgresExecutionRepository implements ExecutionRepository {
constructor(private readonly postgres: Pick<PostgresClient, 'transaction'>) {}
@ -102,6 +109,96 @@ export class PostgresExecutionRepository implements ExecutionRepository {
}
return false;
},
async appendJournal(payload: StrategyJournalPayload) {
const account = state.rows[0].state as Account;
const sequence = (account.strategySequence ?? 0) + 1;
if (!Number.isSafeInteger(sequence)) {
throw new Error('Strategy journal sequence exhausted');
}
account.strategySequence = sequence;
await client.query(
'INSERT INTO simulation_strategy_journal (account_id,sequence,payload) VALUES ($1,$2,$3::jsonb)',
[id, sequence, JSON.stringify(payload)]
);
},
async nextJournal(cursor) {
const result = await client.query(
'SELECT sequence,payload FROM simulation_strategy_journal WHERE account_id = $1 AND sequence > $2 ORDER BY sequence LIMIT 1',
[id, cursor]
);
const row = result.rows[0];
if (!row) {
return undefined;
}
const sequence = Number(row.sequence);
if (!Number.isSafeInteger(sequence)) {
throw new Error('Invalid strategy journal sequence');
}
return { sequence, payload: row.payload as StrategyJournalPayload };
},
async strategies() {
const result = await client.query(
'SELECT payload FROM simulation_strategy_checkpoints WHERE account_id = $1 ORDER BY strategy_id COLLATE "C"',
[id]
);
return result.rows.map(row => row.payload as StrategyCheckpoint);
},
async putStrategy(checkpoint) {
await client.query(
`INSERT INTO simulation_strategy_checkpoints (account_id,strategy_id,payload) VALUES ($1,$2,$3::jsonb)
ON CONFLICT (account_id,strategy_id) DO UPDATE SET payload = EXCLUDED.payload`,
[id, checkpoint.strategyId, JSON.stringify(checkpoint)]
);
},
async nextIntent() {
const result = await client.query(
`SELECT payload FROM simulation_strategy_intents WHERE account_id = $1 AND status = 'pending' ORDER BY sequence,strategy_id COLLATE "C",client_order_id COLLATE "C" LIMIT 1`,
[id]
);
return result.rows[0]?.payload as StrategyOrderIntent | undefined;
},
async putIntent(intent) {
const previous = await client.query(
'SELECT payload FROM simulation_strategy_intents WHERE account_id = $1 AND client_order_id = $2',
[id, intent.clientOrderId]
);
const old = previous.rows[0]?.payload as StrategyOrderIntent | undefined;
if (
old &&
(old.strategyId !== intent.strategyId ||
old.sequence !== intent.sequence ||
canonicalJson(old.request) !== canonicalJson(intent.request) ||
(old.status === 'dispatched' && intent.status !== 'dispatched'))
) {
throw new ExecutionConflictError('Conflicting strategy order intent');
}
await client.query(
`INSERT INTO simulation_strategy_intents (account_id,client_order_id,strategy_id,sequence,status,payload) VALUES ($1,$2,$3,$4,$5,$6::jsonb)
ON CONFLICT (account_id,client_order_id) DO UPDATE SET status = EXCLUDED.status,payload = EXCLUDED.payload`,
[
id,
intent.clientOrderId,
intent.strategyId,
intent.sequence,
intent.status,
JSON.stringify(intent),
]
);
},
async nextInput() {
const result = await client.query(
`SELECT payload FROM simulation_market_inputs WHERE account_id = $1 AND status = 'pending' ORDER BY sequence LIMIT 1`,
[id]
);
return result.rows[0]?.payload as MarketInput | undefined;
},
async putInput(input) {
await client.query(
`INSERT INTO simulation_market_inputs (account_id,id,sequence,status,payload) VALUES ($1,$2,$3,$4,$5::jsonb)
ON CONFLICT (account_id,id) DO UPDATE SET status = EXCLUDED.status,payload = EXCLUDED.payload`,
[id, input.id, input.sequence, input.status, JSON.stringify(input)]
);
},
});
await client.query(
'UPDATE simulation_accounts SET state = $2::jsonb,updated_at = NOW() WHERE id = $1',

View file

@ -0,0 +1,219 @@
import { randomUUID } from 'node:crypto';
import { defined } from '@stock-bot/invariants';
import type { OrderRequest } from '../types';
import {
amount,
applyFill,
decimal,
fingerprint,
riskViolations,
terminal,
type Account,
type ExecutionChange,
type Fill,
type Quote,
type StoredOrder,
} from './model';
import { ExecutionConflictError, type ExecutionTransaction } from './repository';
export interface ExecutionClock {
now(quote?: Quote): number;
isBacktest(): boolean;
}
/** Transaction-scoped simulation rules; the caller owns commit, serialization and publication. */
export class SimulationExecution {
constructor(private readonly clock: ExecutionClock) {}
rollDay(account: Account, time: number) {
const day = new Date(time).toISOString().slice(0, 10);
if (day > account.day || (this.clock.isBacktest() && !Object.keys(account.quotes).length)) {
account.day = day;
account.dailyPnl = 0;
}
}
private async assertRecovered(tx: ExecutionTransaction) {
if (
(await tx.nextInput()) ||
(await tx.nextIntent()) ||
(await tx.strategies()).some(s => s.enabled && s.cursor < (tx.account.strategySequence ?? 0))
) {
throw new ExecutionConflictError(
'Strategy recovery backlog must drain before new order admission'
);
}
}
async journalChange(tx: ExecutionTransaction, change: ExecutionChange) {
if (change.report.strategyId) {
await tx.appendJournal({
kind: 'execution',
report: change.report,
fills: change.fills,
account: structuredClone(tx.account),
});
}
}
async acceptOrder(
tx: ExecutionTransaction,
request: OrderRequest,
strategyId?: string,
internal = false
): Promise<ExecutionChange> {
const hash = fingerprint(request, strategyId);
const existing = await tx.findOrder(defined(request.clientOrderId));
if (existing) {
if (existing.fingerprint !== hash) {
throw new ExecutionConflictError('Client order ID reused with a different request');
}
return { report: existing.report, fills: [] };
}
if (!internal) {
await this.assertRecovered(tx);
}
const quote = tx.account.quotes[request.symbol];
const timestamp = this.clock.now(quote);
this.rollDay(tx.account, timestamp);
const order: StoredOrder = {
request,
fingerprint: hash,
policy: { commission: tx.account.commission, slippage: tx.account.slippage },
report: {
orderId: randomUUID(),
clientOrderId: defined(request.clientOrderId),
strategyId: strategyId,
symbol: request.symbol,
side: request.side,
quantity: request.quantity,
status: 'accepted',
fills: [],
timestamp,
},
};
const invalid = !['market', 'limit'].includes(request.orderType)
? 'Unsupported order type'
: !['DAY', 'GTC', 'IOC', 'FOK'].includes(request.timeInForce)
? 'Unsupported time in force'
: request.orderType === 'limit' &&
(!request.limitPrice || !Number.isFinite(request.limitPrice) || request.limitPrice <= 0)
? 'Valid limit price required'
: !quote ||
timestamp - quote.timestamp > tx.account.maxQuoteAgeMs ||
quote.timestamp > timestamp
? 'Missing, stale, or future market quote'
: undefined;
const price = quote && !invalid ? this.fillPrice(order, quote) : 0;
const violations = invalid
? [invalid]
: riskViolations(tx.account, request, await tx.openOrders(), price, timestamp);
if (violations.length) {
order.report.status = 'rejected';
order.report.rejectionReason = violations.join('; ');
}
await tx.putOrder(order); // Fill FK and acknowledgement are in the same transaction.
const fills =
order.report.status === 'rejected' || !quote
? []
: await this.fill(tx, order, quote, await tx.openOrders());
await tx.putOrder(order);
const change = { report: order.report, fills };
await this.journalChange(tx, change);
return change;
}
private fillPrice(order: StoredOrder, quote: Quote) {
const raw =
order.request.side === 'buy'
? quote.ask * (1 + order.policy.slippage)
: quote.bid * (1 - order.policy.slippage);
return amount(
order.request.orderType === 'limit'
? order.request.side === 'buy'
? Math.min(raw, defined(order.request.limitPrice))
: Math.max(raw, defined(order.request.limitPrice))
: raw
);
}
async fill(
tx: ExecutionTransaction,
order: StoredOrder,
quote: Quote,
reservations: StoredOrder[]
): Promise<Fill[]> {
if (terminal(order.report.status)) {
return [];
}
const request = order.request;
if (
request.timeInForce === 'DAY' &&
new Date(order.report.timestamp).toISOString().slice(0, 10) !==
new Date(quote.timestamp).toISOString().slice(0, 10)
) {
order.report.status = 'cancelled';
return [];
}
const crosses =
request.orderType === 'market' ||
(request.side === 'buy'
? quote.ask <= defined(request.limitPrice)
: quote.bid >= defined(request.limitPrice));
const remaining = amount(
decimal(request.quantity).minus(order.report.fills.reduce((n, f) => n + f.quantity, 0))
);
const available = request.side === 'buy' ? quote.askSize : quote.bidSize;
const quantity = crosses ? Math.min(remaining, available) : 0;
if (!quantity || (request.timeInForce === 'FOK' && quantity < remaining)) {
if (request.timeInForce === 'IOC' || request.timeInForce === 'FOK') {
order.report.status = 'cancelled';
}
return [];
}
const price = this.fillPrice(order, quote);
const violations = riskViolations(
tx.account,
{ ...request, quantity: remaining },
reservations.filter(o => o.report.orderId !== order.report.orderId),
price,
this.clock.now(quote)
);
if (violations.length) {
order.report.status = 'cancelled';
order.report.rejectionReason = violations.join('; ');
return [];
}
const fill = {
id: order.report.orderId + ':' + quote.eventId,
price,
quantity,
commission: amount(decimal(quantity).times(price).times(order.policy.commission)),
timestamp: quote.timestamp,
pnl: 0,
};
const projected = structuredClone(tx.account);
const applied = applyFill(projected, request.symbol, request.side, fill);
if (!(await tx.insertFill(order.report.orderId, applied))) {
return [];
}
// Keep the same quote object so consumed liquidity is persisted with the accounting change.
Object.assign(tx.account, { ...projected, quotes: tx.account.quotes });
if (order.report.strategyId) {
const book = (tx.account.strategyPositions[order.report.strategyId] ??= {});
book[request.symbol] = amount(
decimal(book[request.symbol] ?? 0).plus(request.side === 'buy' ? quantity : -quantity)
);
}
// Store the actual delta, not cumulative realized P&L.
// The returned fill is also appended to the durable report in this transaction.
order.report.fills.push(applied);
if (request.side === 'buy') {
quote.askSize = amount(decimal(quote.askSize).minus(quantity));
} else {
quote.bidSize = amount(decimal(quote.bidSize).minus(quantity));
}
order.report.status =
quantity >= remaining
? 'filled'
: request.timeInForce === 'IOC'
? 'cancelled'
: 'partiallyFilled';
return [applied];
}
}

View file

@ -0,0 +1,288 @@
import { AsyncLocalStorage } from 'node:async_hooks';
import { OrderRequestSchema, type OrderRequest } from '../types';
import { accountMetrics, identity, type Account, type ExecutionChange } from './model';
import { ExecutionConflictError, type ExecutionTransaction } from './repository';
import {
canonicalJson,
strategyConfigHash,
type RecoverableStrategy,
type StrategyCheckpoint,
type StrategyOrderIntent,
} from './strategy-recovery';
/** Explicit ports keep recovery independent of the service container and storage adapters. */
export interface StrategyRecoveryRuntime {
accountId(): string;
isBacktest(): boolean;
serialized<T>(work: () => Promise<T>): Promise<T>;
transact<T>(work: (tx: ExecutionTransaction) => Promise<T>): Promise<T>;
dispatch(tx: ExecutionTransaction, intent: StrategyOrderIntent): Promise<ExecutionChange>;
publish(change: ExecutionChange): Promise<void>;
consumeMarketInput(): Promise<boolean>;
observationFailed(error: unknown): void;
}
/** Owns checkpoints, decision scopes and outbox replay; never opens a nested transaction. */
export class StrategyRecovery {
private readonly decision = new AsyncLocalStorage<{
account: Account;
strategyId: string;
intents: StrategyOrderIntent[];
sequence: number;
open: boolean;
observations: (() => void)[];
}>();
constructor(private readonly runtime: StrategyRecoveryRuntime) {}
assertExternalIO(): void {
if (this.decision.getStore()) {
throw new Error(
'Strategy callbacks cannot perform repository I/O; use the decision account view and order intents'
);
}
}
decisionAccount() {
const context = this.decision.getStore();
if (!context) {
return undefined;
}
if (!context.open) {
throw new Error('Strategy evaluation has finished');
}
return { ...structuredClone(context.account), ...accountMetrics(context.account) };
}
captureStrategyOrder(request: OrderRequest, strategyId: string): void {
const context = this.decision.getStore();
if (!context?.open || context.strategyId !== strategyId) {
throw new Error('Strategy orders require an active checkpoint transaction');
}
const order = OrderRequestSchema.parse(request);
if (!order.clientOrderId) {
throw new Error('Strategy intent requires a stable client order ID');
}
if (context.intents.some(intent => intent.clientOrderId === order.clientOrderId)) {
throw new ExecutionConflictError('Duplicate intent in one decision');
}
context.intents.push({
strategyId,
clientOrderId: order.clientOrderId,
sequence: context.sequence,
request: order,
status: 'pending',
});
}
afterStrategyCommit(observation: () => void): void {
const context = this.decision.getStore();
if (!context?.open) {
throw new Error('No active strategy decision');
}
context.observations.push(observation);
}
async getRecoveryStatus() {
return this.runtime.transact(async tx => ({
accountId: this.runtime.accountId(),
pendingInputs: !!(await tx.nextInput()),
pendingIntents: !!(await tx.nextIntent()),
strategies: (await tx.strategies()).map(s => ({
strategyId: s.strategyId,
enabled: s.enabled,
version: s.version,
cursor: s.cursor,
journalTail: tx.account.strategySequence ?? 0,
lag: (tx.account.strategySequence ?? 0) - s.cursor,
})),
}));
}
async registerStrategy(strategy: RecoverableStrategy): Promise<void> {
const config = structuredClone(strategy.getConfig());
const version =
strategy.getCheckpointVersion() ??
(this.runtime.isBacktest() ? 'run-local-unversioned' : undefined);
if (!version) {
throw new Error('Paper strategies require a versioned checkpoint contract');
}
const hash = strategyConfigHash(config, version);
const initialState = JSON.parse(canonicalJson(strategy.captureCheckpoint()));
strategy.restoreCheckpoint(initialState);
const saved = await this.runtime.serialized(() =>
this.runtime.transact(async tx => {
const existing = (await tx.strategies()).find(s => s.strategyId === config.id);
if (existing && (existing.version !== version || existing.configHash !== hash)) {
throw new ExecutionConflictError(
'Strategy configuration/checkpoint version changed; use an explicit new strategy ID'
);
}
const checkpoint: StrategyCheckpoint = existing ?? {
strategyId: config.id,
config,
configHash: hash,
version,
enabled: true,
cursor: tx.account.strategySequence ?? 0,
state: initialState,
};
strategy.restoreCheckpoint(checkpoint.state);
await tx.putStrategy({ ...checkpoint, enabled: true });
return checkpoint;
})
);
strategy.restoreCheckpoint(saved.state);
}
async registeredStrategies() {
return this.runtime.transact(async tx =>
(await tx.strategies()).map(s => ({ ...s.config, enabled: s.enabled }))
);
}
async pauseStrategy(strategyId: string) {
await this.runtime.serialized(() =>
this.runtime.transact(async tx => {
const checkpoint = (await tx.strategies()).find(s => s.strategyId === strategyId);
if (checkpoint) {
await tx.putStrategy({ ...checkpoint, enabled: false });
}
})
);
}
/** Account row locks serialize owners. Restore before EVERY step, not just startup. */
async recoverStrategies(strategies: RecoverableStrategy[]): Promise<void> {
await this.runtime.serialized(async () => {
const byId = new Map(strategies.map(strategy => [strategy.getConfig().id, strategy]));
const enabled = await this.runtime.transact(async tx =>
(await tx.strategies()).filter(s => s.enabled)
);
for (const checkpoint of enabled) {
const strategy = byId.get(checkpoint.strategyId);
if (!strategy) {
throw new ExecutionConflictError(
'An enabled strategy must be restored before processing its account'
);
}
const version = strategy.getCheckpointVersion() ?? 'run-local-unversioned';
if (
checkpoint.version !== version ||
checkpoint.configHash !== strategyConfigHash(strategy.getConfig(), version)
) {
throw new ExecutionConflictError('Strategy checkpoint definition mismatch');
}
}
while (true) {
const dispatched = await this.runtime.transact(async tx => {
const intent = await tx.nextIntent();
if (!intent) {
return undefined;
}
const change = await this.runtime.dispatch(tx, intent);
await tx.putIntent({ ...intent, status: 'dispatched', orderId: change.report.orderId });
return change;
});
if (dispatched) {
await this.runtime.publish(dispatched);
continue;
}
let progressed = false;
const registrations = await this.runtime.transact(tx => tx.strategies());
for (const registration of registrations.filter(s => s.enabled)) {
const strategy = byId.get(registration.strategyId);
if (!strategy) {
throw new ExecutionConflictError(
'An enabled strategy must be restored before processing its account'
);
}
let before = strategy.captureCheckpoint();
let observations: (() => void)[] = [];
try {
const advanced = await this.runtime.transact(async tx => {
const checkpoint = (await tx.strategies()).find(
s => s.strategyId === registration.strategyId
);
if (!checkpoint?.enabled) {
return false;
}
const version = strategy.getCheckpointVersion() ?? 'run-local-unversioned';
if (
strategyConfigHash(strategy.getConfig(), version) !== checkpoint.configHash ||
checkpoint.version !== version
) {
throw new ExecutionConflictError('Strategy checkpoint definition mismatch');
}
strategy.restoreCheckpoint(checkpoint.state);
before = checkpoint.state;
const event = await tx.nextJournal(checkpoint.cursor);
if (!event) {
return false;
}
const context = {
account: event.payload.account,
strategyId: checkpoint.strategyId,
intents: [] as StrategyOrderIntent[],
sequence: event.sequence,
open: true,
observations: [] as (() => void)[],
};
try {
await this.decision.run(context, async () => {
const payload = event.payload;
if (
payload.kind === 'market' &&
payload.recipients.includes(checkpoint.strategyId) &&
strategy.getConfig().symbols.includes(payload.market.data.symbol)
) {
await strategy.onMarketData({
...payload.market,
eventId: identity(payload.market),
});
} else if (
payload.kind === 'execution' &&
payload.report.strategyId === checkpoint.strategyId
) {
for (const fill of payload.fills) {
await strategy.onFill({
...fill,
orderId: payload.report.orderId,
symbol: payload.report.symbol,
side: payload.report.side,
strategyId: checkpoint.strategyId,
});
}
await strategy.onOrderUpdate(payload.report);
}
});
} finally {
context.open = false;
}
const state = JSON.parse(canonicalJson(strategy.captureCheckpoint()));
await tx.putStrategy({ ...checkpoint, cursor: event.sequence, state });
for (const intent of context.intents) {
await tx.putIntent(intent);
}
observations = context.observations;
return true;
});
progressed ||= advanced;
for (const observe of observations) {
try {
observe();
} catch (error) {
this.runtime.observationFailed(error);
}
}
} catch (error) {
strategy.restoreCheckpoint(before);
throw error;
}
}
if (progressed) {
continue;
}
if (!(await this.runtime.consumeMarketInput())) {
break;
}
}
});
}
}

View file

@ -36,6 +36,11 @@ export interface ExecutionReport {
timestamp: number;
strategyId?: string;
}
/** A committed order report and only the new fills from that transaction. */
export interface ExecutionChange {
report: ExecutionReport;
fills: Fill[];
}
export interface Position {
symbol: string;
quantity: number;
@ -51,6 +56,10 @@ export interface Quote {
eventId: string;
}
export interface Account {
/** Account-row-locked journal sequence, safe integer checked before increment. */
strategySequence?: number;
inputSequence?: number;
admittedTimes?: Record<string, number>;
initialCapital: number;
cash: number;
realizedPnl: number;

View file

@ -1,4 +1,11 @@
import type { Account, Fill, StoredOrder } from './model';
import type {
MarketInput,
StrategyCheckpoint,
StrategyJournalEvent,
StrategyJournalPayload,
StrategyOrderIntent,
} from './strategy-recovery';
export interface ExecutionTransaction {
account: Account;
@ -8,69 +15,17 @@ export interface ExecutionTransaction {
putOrder(order: StoredOrder): Promise<void>;
insertFill(orderId: string, fill: Fill): Promise<boolean>;
recordEvent(eventId: string, fingerprint: string): Promise<boolean>;
appendJournal(payload: StrategyJournalPayload): Promise<void>;
nextJournal(cursor: number): Promise<StrategyJournalEvent | undefined>;
strategies(): Promise<StrategyCheckpoint[]>;
putStrategy(checkpoint: StrategyCheckpoint): Promise<void>;
putIntent(intent: StrategyOrderIntent): Promise<void>;
nextIntent(): Promise<StrategyOrderIntent | undefined>;
nextInput(): Promise<MarketInput | undefined>;
putInput(input: MarketInput): Promise<void>;
}
export interface ExecutionRepository {
initialize(accountId: string, initial: Account): Promise<void>;
transact<T>(accountId: string, work: (tx: ExecutionTransaction) => Promise<T>): Promise<T>;
}
export class ExecutionConflictError extends Error {}
/** Explicit run-local backtest store, never a fallback for paper or live execution. */
export class BacktestExecutionRepository implements ExecutionRepository {
private state?: {
account: Account;
orders: Record<string, StoredOrder>;
fills: Record<string, Fill>;
events: Record<string, string>;
};
private tail: Promise<unknown> = Promise.resolve();
async initialize(_id: string, account: Account) {
this.state = { account: structuredClone(account), orders: {}, fills: {}, events: {} };
}
transact<T>(_id: string, work: (tx: ExecutionTransaction) => Promise<T>): Promise<T> {
const task = this.tail.then(async () => {
if (!this.state) {
throw new Error('Execution account is not initialized');
}
const state = structuredClone(this.state);
const result = await work({
account: state.account,
async findOrder(id) {
return Object.values(state.orders).find(o => o.report.clientOrderId === id);
},
async getOrder(id) {
return state.orders[id];
},
async openOrders() {
return Object.values(state.orders).filter(o =>
['accepted', 'partiallyFilled'].includes(o.report.status)
);
},
async putOrder(order) {
state.orders[order.report.orderId] = order;
},
async insertFill(_orderId, fill) {
if (state.fills[fill.id]) {
return false;
}
state.fills[fill.id] = fill;
return true;
},
async recordEvent(id, hash) {
if (state.events[id] && state.events[id] !== hash) {
throw new ExecutionConflictError('Conflicting market event identity');
}
if (state.events[id]) {
return false;
}
state.events[id] = hash;
return true;
},
});
this.state = state;
return structuredClone(result);
});
this.tail = task.catch(() => {});
return task;
}
}

View file

@ -0,0 +1,70 @@
import { createHash } from 'node:crypto';
import type { MarketData, OrderRequest, StrategyConfig } from '../types';
import type { Account, ExecutionReport, Fill } from './model';
/** Only JSON values are checkpointable; reject lossy JSON.stringify conversions. */
export function canonicalJson(value: unknown): string {
const visit = (input: unknown): unknown => {
if (input === null || typeof input === 'string' || typeof input === 'boolean') {
return input;
}
if (typeof input === 'number' && Number.isFinite(input)) {
return input;
}
if (Array.isArray(input)) {
return Array.from(input, visit);
}
if (input && typeof input === 'object' && Object.getPrototypeOf(input) === Object.prototype) {
return Object.fromEntries(
Object.entries(input)
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
.map(([key, item]) => [key, visit(item)])
);
}
throw new Error('Strategy checkpoints require finite, plain JSON values');
};
return JSON.stringify(visit(value));
}
export function strategyConfigHash(config: StrategyConfig, version: string): string {
const { enabled: _enabled, ...definition } = config;
return createHash('sha256').update(canonicalJson({ definition, version })).digest('hex');
}
export type StrategyJournalPayload = { account: Account } & (
| { kind: 'market'; market: MarketData; recipients: string[] }
| { kind: 'execution'; report: ExecutionReport; fills: Fill[] }
);
export type StrategyJournalEvent = { sequence: number; payload: StrategyJournalPayload };
export interface MarketInput {
id: string;
sequence: number;
market: MarketData;
status: 'pending' | 'applied';
}
export interface StrategyCheckpoint {
strategyId: string;
config: StrategyConfig;
configHash: string;
version: string;
enabled: boolean;
cursor: number;
state: unknown;
}
export interface StrategyOrderIntent {
clientOrderId: string;
strategyId: string;
sequence: number;
request: OrderRequest;
status: 'pending' | 'dispatched';
orderId?: string;
}
export interface RecoverableStrategy {
getConfig(): Readonly<StrategyConfig>;
getCheckpointVersion(): string | undefined;
captureCheckpoint(): unknown;
restoreCheckpoint(state: unknown): void;
onMarketData(data: MarketData): Promise<void>;
onFill(
fill: Fill & { orderId: string; symbol: string; side: 'buy' | 'sell'; strategyId?: string }
): Promise<void>;
onOrderUpdate(report: ExecutionReport): Promise<void>;
}

View file

@ -26,6 +26,18 @@ export function createRoutes(services: IServiceContainer, io?: SocketIOServer):
});
// Mount REST API routes
app.get('/api/recovery', async c => {
try {
const execution = services.custom?.ExecutionService;
if (!execution) {
return c.json({ error: 'Execution gateway unavailable' }, 503);
}
return c.json(await execution.getRecoveryStatus());
} catch (error) {
services.logger.error('Could not read strategy recovery status', { error });
return c.json({ error: 'Strategy recovery status unavailable' }, 503);
}
});
app.route('/api/orders', createOrderRoutes(services));
app.route('/api/positions', createPositionRoutes(services));
app.route('/api/analytics', createAnalyticsRoutes(services));

View file

@ -2,29 +2,25 @@ import { createHash, randomUUID } from 'node:crypto';
import { EventEmitter } from 'node:events';
import type { TradingEngine } from '@stock-bot/engine';
import { defined } from '@stock-bot/invariants';
import { BacktestExecutionRepository } from '../execution/BacktestExecutionRepository';
import {
accountMetrics,
amount,
applyFill,
decimal,
defaultRiskLimits,
fingerprint,
identity,
riskViolations,
terminal,
type Account,
type ExecutionChange,
type ExecutionReport,
type Fill,
type Quote,
type StoredOrder,
} from '../execution/model';
import { PostgresExecutionRepository } from '../execution/PostgresExecutionRepository';
import {
BacktestExecutionRepository,
ExecutionConflictError,
type ExecutionRepository,
type ExecutionTransaction,
} from '../execution/repository';
import { ExecutionConflictError, type ExecutionRepository } from '../execution/repository';
import { SimulationExecution } from '../execution/SimulationExecution';
import type { RecoverableStrategy } from '../execution/strategy-recovery';
import { StrategyRecovery } from '../execution/StrategyRecovery';
import {
MarketDataSchema,
ModeConfigSchema,
@ -45,7 +41,6 @@ export interface StrategyFill extends Fill {
strategyId?: string;
positionUpdate?: unknown;
}
type Change = { report: ExecutionReport; fills: Fill[] };
export class UnsupportedExecutionError extends Error {}
/** Sole runtime order gateway. Paper state commits atomically; backtests opt into a run-local ledger. */
@ -57,12 +52,35 @@ export class ExecutionService extends EventEmitter {
private observer?: (report: ExecutionReport, fills: StrategyFill[]) => Promise<void>;
private tail: Promise<unknown> = Promise.resolve();
private closing = false;
private readonly simulation: SimulationExecution;
private readonly recovery: StrategyRecovery;
requiresDurableCheckpoint(): boolean {
return this.mode === 'paper';
}
constructor(
private readonly container: OrchestratorServices,
_storage: StorageService,
private readonly options: { repository?: ExecutionRepository; clock?: () => number } = {}
) {
super();
this.simulation = new SimulationExecution({
now: quote => this.now(quote),
isBacktest: () => this.mode === 'backtest',
});
this.recovery = new StrategyRecovery({
accountId: () => this.accountId,
isBacktest: () => this.mode === 'backtest',
serialized: work => this.serialized(work),
transact: work => this.store().transact(this.accountId, work),
dispatch: (tx, intent) =>
this.simulation.acceptOrder(tx, intent.request, intent.strategyId, true),
publish: change => this.publish(change),
consumeMarketInput: () => this.consumeMarketInput(),
observationFailed: error =>
this.container.logger.error('Strategy observation failed after checkpoint commit', {
error,
}),
});
}
setObserver(observer: (report: ExecutionReport, fills: StrategyFill[]) => Promise<void>) {
@ -127,6 +145,7 @@ export class ExecutionService extends EventEmitter {
return result;
}
private store() {
this.recovery.assertExternalIO();
if (!this.repository || !this.mode || this.closing) {
throw new UnsupportedExecutionError(
'Execution gateway is not initialized or is shutting down'
@ -139,260 +158,152 @@ export class ExecutionService extends EventEmitter {
? (quote?.timestamp ?? 0)
: (this.options.clock?.() ?? Date.now());
}
private rollDay(account: Account, time: number) {
const day = new Date(time).toISOString().slice(0, 10);
if (day > account.day || (this.mode === 'backtest' && !Object.keys(account.quotes).length)) {
account.day = day;
account.dailyPnl = 0;
}
}
async submitOrder(
input: OrderRequest,
context: { strategyId?: string } = {}
): Promise<ExecutionReport> {
this.recovery.assertExternalIO();
const request = OrderRequestSchema.parse(input);
// The API must supply stable IDs for retried requests; strategy IDs are derived from source events.
request.clientOrderId ??= randomUUID();
return this.serialized(async () => {
const change = await this.store().transact(this.accountId, async tx => {
const hash = fingerprint(request, context.strategyId);
const existing = await tx.findOrder(defined(request.clientOrderId));
if (existing) {
if (existing.fingerprint !== hash) {
throw new ExecutionConflictError('Client order ID reused with a different request');
}
return { report: existing.report, fills: [] };
}
const quote = tx.account.quotes[request.symbol];
const timestamp = this.now(quote);
this.rollDay(tx.account, timestamp);
const order: StoredOrder = {
request,
fingerprint: hash,
policy: { commission: tx.account.commission, slippage: tx.account.slippage },
report: {
orderId: randomUUID(),
clientOrderId: defined(request.clientOrderId),
strategyId: context.strategyId,
symbol: request.symbol,
side: request.side,
quantity: request.quantity,
status: 'accepted',
fills: [],
timestamp,
},
};
const invalid = !['market', 'limit'].includes(request.orderType)
? 'Unsupported order type'
: !['DAY', 'GTC', 'IOC', 'FOK'].includes(request.timeInForce)
? 'Unsupported time in force'
: request.orderType === 'limit' &&
(!request.limitPrice ||
!Number.isFinite(request.limitPrice) ||
request.limitPrice <= 0)
? 'Valid limit price required'
: !quote ||
timestamp - quote.timestamp > tx.account.maxQuoteAgeMs ||
quote.timestamp > timestamp
? 'Missing, stale, or future market quote'
: undefined;
const price = quote && !invalid ? this.fillPrice(tx.account, order, quote) : 0;
const violations = invalid
? [invalid]
: riskViolationsFor(tx, request, await tx.openOrders(), price, timestamp);
if (violations.length) {
order.report.status = 'rejected';
order.report.rejectionReason = violations.join('; ');
}
await tx.putOrder(order); // Fill FK and acknowledgement are in the same transaction.
const fills =
order.report.status === 'rejected' || !quote
? []
: await this.fill(tx, order, quote, await tx.openOrders());
await tx.putOrder(order);
return { report: order.report, fills };
return this.simulation.acceptOrder(tx, request, context.strategyId);
});
await this.publish(change);
return change.report;
});
}
private fillPrice(_account: Account, order: StoredOrder, quote: Quote) {
const raw =
order.request.side === 'buy'
? quote.ask * (1 + order.policy.slippage)
: quote.bid * (1 - order.policy.slippage);
return amount(
order.request.orderType === 'limit'
? order.request.side === 'buy'
? Math.min(raw, defined(order.request.limitPrice))
: Math.max(raw, defined(order.request.limitPrice))
: raw
);
}
private async fill(
tx: ExecutionTransaction,
order: StoredOrder,
quote: Quote,
reservations: StoredOrder[]
): Promise<Fill[]> {
if (terminal(order.report.status)) {
return [];
}
const request = order.request;
if (
request.timeInForce === 'DAY' &&
new Date(order.report.timestamp).toISOString().slice(0, 10) !==
new Date(quote.timestamp).toISOString().slice(0, 10)
) {
order.report.status = 'cancelled';
return [];
}
const crosses =
request.orderType === 'market' ||
(request.side === 'buy'
? quote.ask <= defined(request.limitPrice)
: quote.bid >= defined(request.limitPrice));
const remaining = amount(
decimal(request.quantity).minus(order.report.fills.reduce((n, f) => n + f.quantity, 0))
);
const available = request.side === 'buy' ? quote.askSize : quote.bidSize;
const quantity = crosses ? Math.min(remaining, available) : 0;
if (!quantity || (request.timeInForce === 'FOK' && quantity < remaining)) {
if (request.timeInForce === 'IOC' || request.timeInForce === 'FOK') {
order.report.status = 'cancelled';
}
return [];
}
const price = this.fillPrice(tx.account, order, quote);
const violations = riskViolationsFor(
tx,
{ ...request, quantity: remaining },
reservations.filter(o => o.report.orderId !== order.report.orderId),
price,
this.now(quote)
);
if (violations.length) {
order.report.status = 'cancelled';
order.report.rejectionReason = violations.join('; ');
return [];
}
const fill = {
id: order.report.orderId + ':' + quote.eventId,
price,
quantity,
commission: amount(decimal(quantity).times(price).times(order.policy.commission)),
timestamp: quote.timestamp,
pnl: 0,
};
const projected = structuredClone(tx.account);
const applied = applyFill(projected, request.symbol, request.side, fill);
if (!(await tx.insertFill(order.report.orderId, applied))) {
return [];
}
// Keep the same quote object so consumed liquidity is persisted with the accounting change.
Object.assign(tx.account, { ...projected, quotes: tx.account.quotes });
if (order.report.strategyId) {
const book = (tx.account.strategyPositions[order.report.strategyId] ??= {});
book[request.symbol] = amount(
decimal(book[request.symbol] ?? 0).plus(request.side === 'buy' ? quantity : -quantity)
);
}
// Store the actual delta, not cumulative realized P&L.
// The returned fill is also appended to the durable report in this transaction.
order.report.fills.push(applied);
if (request.side === 'buy') {
quote.askSize = amount(decimal(quote.askSize).minus(quantity));
} else {
quote.bidSize = amount(decimal(quote.bidSize).minus(quantity));
}
order.report.status =
quantity >= remaining
? 'filled'
: request.timeInForce === 'IOC'
? 'cancelled'
: 'partiallyFilled';
return [applied];
}
async onMarketData(input: MarketData): Promise<boolean> {
/** Durable admission precedes processing; a strategy failure cannot discard later inputs. */
async enqueueMarketData(input: MarketData): Promise<boolean> {
const data = MarketDataSchema.parse(input);
return this.serialized(async () => {
const outcome = await this.store().transact(this.accountId, async tx => {
return this.serialized(() =>
this.store().transact(this.accountId, async tx => {
const key = identity(data);
const hash = createHash('sha256').update(JSON.stringify(data)).digest('hex');
if (!(await tx.recordEvent(key, hash))) {
return { processed: false, changes: [] as Change[] };
return false;
}
const previous = tx.account.quotes[data.data.symbol];
if (previous && data.data.timestamp < previous.timestamp) {
const quote = this.quoteFor(data);
const previous =
tx.account.admittedTimes?.[data.data.symbol] ??
tx.account.quotes[data.data.symbol]?.timestamp;
if (previous !== undefined && quote.timestamp < previous) {
throw new ExecutionConflictError('Out-of-order market data');
}
const quote: Quote =
data.type === 'quote'
? { ...data.data, eventId: key }
: data.type === 'bar'
? {
bid: data.data.close,
ask: data.data.close,
bidSize: data.data.volume,
askSize: data.data.volume,
timestamp: data.data.timestamp,
eventId: key,
}
: {
bid: data.data.price,
ask: data.data.price,
bidSize: data.data.size,
askSize: data.data.size,
timestamp: data.data.timestamp,
eventId: key,
};
if (
![quote.bid, quote.ask, quote.bidSize, quote.askSize, quote.timestamp].every(
Number.isFinite
) ||
quote.bid <= 0 ||
quote.ask < quote.bid ||
quote.bidSize < 0 ||
quote.askSize < 0
) {
throw new Error('Invalid market quote/liquidity');
}
const time = this.now(quote);
if (
this.mode === 'paper' &&
(time - quote.timestamp > tx.account.maxQuoteAgeMs || quote.timestamp > time)
) {
if (this.mode === 'paper' && !this.freshQuote(tx.account, quote)) {
throw new Error('Stale or future market data');
}
this.rollDay(tx.account, quote.timestamp);
tx.account.quotes[data.data.symbol] = quote;
const orders = await tx.openOrders();
const changes: Change[] = [];
for (const order of orders) {
const before = order.report.status;
const expired =
order.request.timeInForce === 'DAY' &&
new Date(order.report.timestamp).toISOString().slice(0, 10) <
new Date(quote.timestamp).toISOString().slice(0, 10);
if (expired) {
order.report.status = 'cancelled';
}
const fills =
!expired && order.request.symbol === data.data.symbol
? await this.fill(tx, order, quote, orders)
: [];
await tx.putOrder(order);
if (fills.length || before !== order.report.status) {
changes.push({ report: order.report, fills });
}
const sequence = (tx.account.inputSequence ?? 0) + 1;
if (!Number.isSafeInteger(sequence)) {
throw new Error('Market input sequence exhausted');
}
return { processed: true, changes };
});
for (const change of outcome.changes) {
await this.publish(change);
tx.account.inputSequence = sequence;
(tx.account.admittedTimes ??= {})[data.data.symbol] = quote.timestamp;
await tx.putInput({ id: key, sequence, market: data, status: 'pending' });
return true;
})
);
}
async onMarketData(input: MarketData): Promise<boolean> {
const admitted = await this.enqueueMarketData(input);
await this.serialized(async () => {
while (await this.consumeMarketInput()) {
/* drain unblocked inputs */
}
return outcome.processed;
});
return admitted;
}
private quoteFor(data: MarketData): Quote {
const quote: Quote =
data.type === 'quote'
? { ...data.data, eventId: identity(data) }
: {
bid: data.type === 'bar' ? data.data.close : data.data.price,
ask: data.type === 'bar' ? data.data.close : data.data.price,
bidSize: data.type === 'bar' ? data.data.volume : data.data.size,
askSize: data.type === 'bar' ? data.data.volume : data.data.size,
timestamp: data.data.timestamp,
eventId: identity(data),
};
if (
![quote.bid, quote.ask, quote.bidSize, quote.askSize, quote.timestamp].every(
Number.isFinite
) ||
quote.bid <= 0 ||
quote.ask < quote.bid ||
quote.bidSize < 0 ||
quote.askSize < 0
) {
throw new Error('Invalid market quote/liquidity');
}
return quote;
}
private freshQuote(account: Account, quote: Quote) {
const now = this.now(quote);
return quote.timestamp <= now && now - quote.timestamp <= account.maxQuoteAgeMs;
}
private async consumeMarketInput(): Promise<boolean> {
const outcome = await this.store().transact(this.accountId, async tx => {
const registrations = await tx.strategies();
if (
(await tx.nextIntent()) ||
registrations.some(s => s.enabled && s.cursor < (tx.account.strategySequence ?? 0))
) {
return undefined;
}
const input = await tx.nextInput();
if (!input) {
return undefined;
}
const data = input.market,
quote = this.quoteFor(data);
this.simulation.rollDay(tx.account, quote.timestamp);
tx.account.quotes[data.data.symbol] = quote;
const orders = await tx.openOrders(),
changes: ExecutionChange[] = [];
for (const order of orders) {
const before = order.report.status;
const expired =
order.request.timeInForce === 'DAY' &&
new Date(order.report.timestamp).toISOString().slice(0, 10) <
new Date(quote.timestamp).toISOString().slice(0, 10);
if (expired) {
order.report.status = 'cancelled';
}
// Recovery must not fill paper orders on quotes that have become stale.
const fills =
!expired &&
order.request.symbol === data.data.symbol &&
this.freshQuote(tx.account, quote)
? await this.simulation.fill(tx, order, quote, orders)
: [];
await tx.putOrder(order);
if (fills.length || before !== order.report.status) {
const change = { report: order.report, fills };
changes.push(change);
await this.simulation.journalChange(tx, change);
}
}
await tx.appendJournal({
kind: 'market',
market: data,
recipients: registrations.filter(s => s.enabled).map(s => s.strategyId),
account: structuredClone(tx.account),
});
await tx.putInput({ ...input, status: 'applied' });
return changes;
});
if (!outcome) {
return false;
}
for (const change of outcome) {
await this.publish(change);
}
return true;
}
async cancelOrder(id: string): Promise<boolean> {
return this.serialized(async () => {
@ -403,7 +314,9 @@ export class ExecutionService extends EventEmitter {
}
order.report.status = 'cancelled';
await tx.putOrder(order);
return { report: order.report, fills: [] };
const change = { report: order.report, fills: [] };
await this.simulation.journalChange(tx, change);
return change;
});
if (change) {
await this.publish(change);
@ -418,6 +331,10 @@ export class ExecutionService extends EventEmitter {
);
}
async getAccount() {
const decisionAccount = this.recovery.decisionAccount();
if (decisionAccount) {
return decisionAccount;
}
return this.store().transact(this.accountId, async tx => ({
...tx.account,
...accountMetrics(tx.account),
@ -444,7 +361,28 @@ export class ExecutionService extends EventEmitter {
),
}));
}
private async publish(change: Change) {
captureStrategyOrder(request: OrderRequest, strategyId: string): void {
this.recovery.captureStrategyOrder(request, strategyId);
}
afterStrategyCommit(observation: () => void): void {
this.recovery.afterStrategyCommit(observation);
}
getRecoveryStatus() {
return this.recovery.getRecoveryStatus();
}
registerStrategy(strategy: RecoverableStrategy): Promise<void> {
return this.recovery.registerStrategy(strategy);
}
registeredStrategies() {
return this.recovery.registeredStrategies();
}
pauseStrategy(strategyId: string): Promise<void> {
return this.recovery.pauseStrategy(strategyId);
}
recoverStrategies(strategies: RecoverableStrategy[]): Promise<void> {
return this.recovery.recoverStrategies(strategies);
}
private async publish(change: ExecutionChange) {
const fills = change.fills.map(fill => ({
...fill,
orderId: change.report.orderId,
@ -487,11 +425,3 @@ export class ExecutionService extends EventEmitter {
this.engine = undefined;
}
}
const riskViolationsFor = (
tx: ExecutionTransaction,
request: OrderRequest,
reservations: StoredOrder[],
price: number,
timestamp: number
) => riskViolations(tx.account, request, reservations, price, timestamp);

View file

@ -1,13 +1,40 @@
import { EventEmitter } from 'events';
import { createHash } from 'node:crypto';
import { z } from 'zod';
import { defined } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import { ModeManager } from '../core/ModeManager';
import type { StrategyFill, StrategyOrderUpdate } from '../services/ExecutionService';
import { ExecutionService } from '../services/ExecutionService';
import { type MarketData, type OrderRequest, type StrategyConfig } from '../types';
import type { ModeManager } from '../core/ModeManager';
import { identity } from '../execution/model';
import type {
ExecutionService,
StrategyFill,
StrategyOrderUpdate,
} from '../services/ExecutionService';
import {
OrderRequestSchema,
type MarketData,
type OrderRequest,
type StrategyConfig,
} from '../types';
const logger = getLogger('BaseStrategy');
const finite = z.number().finite();
const checkpointSchema = z.object({
version: z.literal(1),
positions: z.array(z.tuple([z.string(), finite])),
pendingOrders: z.array(z.tuple([z.string(), OrderRequestSchema])),
seenFills: z.array(z.string()).max(2048),
performance: z.object({
trades: finite.nonnegative(),
wins: finite.nonnegative(),
losses: finite.nonnegative(),
totalPnl: finite,
maxDrawdown: finite,
currentDrawdown: finite,
peakEquity: finite,
}),
indicators: z.unknown(),
});
export interface Signal {
type: 'buy' | 'sell' | 'close';
@ -70,6 +97,7 @@ export abstract class BaseStrategy extends EventEmitter {
async stop(): Promise<void> {
this.isActive = false;
await this.executionService.pauseStrategy(this.config.id);
// Cancel pending orders
for (const [orderId, _order] of this.pendingOrders) {
@ -82,10 +110,46 @@ export abstract class BaseStrategy extends EventEmitter {
}
async shutdown(): Promise<void> {
await this.stop();
await this.suspend();
this.removeAllListeners();
logger.info(`Shutdown strategy: ${this.config.name}`);
}
/** Process shutdown is not an instruction to cancel durable orders or erase indicators. */
async suspend(): Promise<void> {
this.isActive = false;
}
getCheckpointVersion(): string | undefined {
return undefined;
}
protected captureIndicators(): unknown {
return null;
}
protected restoreIndicators(state: unknown): void {
if (state !== null) {
throw new Error('Unexpected checkpoint state for a stateless strategy');
}
}
captureCheckpoint(): unknown {
return {
version: 1,
positions: [...this.positions],
pendingOrders: [...this.pendingOrders],
seenFills: [...this.seenFills].slice(-2048),
performance: { ...this.performance },
indicators: this.captureIndicators(),
};
}
restoreCheckpoint(input: unknown): void {
const state = checkpointSchema.parse(input);
this.restoreIndicators(state.indicators);
this.positions = new Map(state.positions);
this.pendingOrders = new Map(state.pendingOrders);
this.seenFills.clear();
for (const id of state.seenFills) {
this.seenFills.add(id);
}
this.performance = state.performance;
}
// Market data handling
async onMarketData(data: MarketData): Promise<void> {
@ -96,31 +160,26 @@ export abstract class BaseStrategy extends EventEmitter {
return;
}
try {
// Update any indicators or state
this.updateIndicators(data);
this.eventIdentity = identity(data);
// Update any indicators or state
this.updateIndicators(data);
// Generate signals
const signal = await this.generateSignal(data);
// Generate signals
const signal = await this.generateSignal(data);
if (signal) {
if (signal) {
this.executionService.afterStrategyCommit(() => {
this.emit('signal', signal);
});
// Convert signal to order if strong enough
const order = await this.signalToOrder(signal);
if (order) {
const clientOrderId = createHash('sha256')
.update(JSON.stringify([this.config.id, this.eventIdentity, order]))
.digest('hex');
const report = await this.executionService.submitOrder(
{ ...order, clientOrderId },
{ strategyId: this.config.id }
);
this.emit('order', report); // Observation only; no second submission path.
}
// Convert signal to order if strong enough
const order = await this.signalToOrder(signal);
if (order) {
const clientOrderId = createHash('sha256')
.update(JSON.stringify([this.config.id, this.eventIdentity, order]))
.digest('hex');
this.executionService.captureStrategyOrder({ ...order, clientOrderId }, this.config.id);
}
} catch (error) {
logger.error(`Strategy ${this.config.id} error:`, error);
}
}
@ -167,6 +226,9 @@ export abstract class BaseStrategy extends EventEmitter {
return;
}
this.seenFills.add(fill.id);
if (this.seenFills.size > 2048) {
this.seenFills.delete(defined(this.seenFills.values().next().value));
}
const quantity =
(this.positions.get(fill.symbol) ?? 0) +
(fill.side === 'buy' ? fill.quantity : -fill.quantity);
@ -205,6 +267,11 @@ export abstract class BaseStrategy extends EventEmitter {
// Configuration
async updateConfig(updates: Partial<StrategyConfig>): Promise<void> {
if (this.isActive) {
throw new Error(
'Active strategy configuration is immutable; use an explicit new strategy ID'
);
}
this.config = { ...this.config, ...updates };
logger.info(`Updated config for strategy ${this.config.id}`);

View file

@ -1,11 +1,12 @@
import { EventEmitter } from 'events';
import { TradingEngine } from '@stock-bot/engine';
import type { TradingEngine } from '@stock-bot/engine';
import { defined } from '@stock-bot/invariants';
import { identity } from '../execution/model';
import type { OrchestratorServices as IServiceContainer } from '../types';
import { type MarketData, type StrategyConfig } from '../types';
import type { Signal } from './BaseStrategy';
import { BaseStrategy } from './BaseStrategy';
import { createBuiltinStrategyRegistry } from './builtin-strategies';
import type { StrategyRegistry } from './StrategyRegistry';
export class StrategyManager extends EventEmitter {
private strategies = new Map<string, BaseStrategy>();
@ -14,6 +15,7 @@ export class StrategyManager extends EventEmitter {
private container: IServiceContainer;
private delivery: Promise<unknown> = Promise.resolve();
private listening = false;
private recoveryTimer?: ReturnType<typeof setInterval>;
private marketSource?: import('../services/MarketDataService').MarketDataService;
private readonly onBatch = (batch: MarketData[]) => {
void this.deliverBatch(batch).catch(error =>
@ -21,7 +23,10 @@ export class StrategyManager extends EventEmitter {
);
};
constructor(container: IServiceContainer) {
constructor(
container: IServiceContainer,
private readonly registry: StrategyRegistry = createBuiltinStrategyRegistry()
) {
super();
this.container = container;
}
@ -41,25 +46,50 @@ export class StrategyManager extends EventEmitter {
this.listening = true;
this.marketSource = marketDataService;
marketDataService.on('marketDataBatch', this.onBatch);
executionService.setObserver(async (report, fills) => {
const strategy = report.strategyId ? this.strategies.get(report.strategyId) : undefined;
if (!strategy) {
return;
// Financial notifications are journal inputs, not volatile observer callbacks.
this.recoveryTimer = setInterval(() => {
if (executionService.requiresDurableCheckpoint() && this.activeStrategies.size) {
void this.recover().catch(error =>
this.container.logger.error('Strategy recovery remains pending', { error })
);
}
for (const fill of fills) {
await strategy.onFill(fill);
}
await strategy.onOrderUpdate(report);
});
}, 1000);
this.recoveryTimer.unref();
}
private deliverBatch(batch: MarketData[]): Promise<void> {
const work = this.delivery.then(async () => {
for (const data of batch) {
await this.handleMarketData(data);
}
});
this.delivery = work.catch(() => {});
const work = this.delivery
.catch(() => {})
.then(async () => {
const execution = defined(this.container.custom?.ExecutionService);
const failures: unknown[] = [];
for (const data of batch) {
try {
await execution.enqueueMarketData(data);
} catch (error) {
failures.push(error);
}
}
await execution.recoverStrategies(
this.getAllStrategies().filter(s => this.activeStrategies.has(s.getConfig().id))
);
if (failures.length) {
throw new AggregateError(failures, 'Some market inputs were rejected');
}
});
this.delivery = work;
return work;
}
recover(): Promise<void> {
const work = this.delivery
.catch(() => {})
.then(() =>
defined(this.container.custom?.ExecutionService).recoverStrategies(
this.getAllStrategies().filter(s => this.activeStrategies.has(s.getConfig().id))
)
);
this.delivery = work;
return work;
}
@ -68,12 +98,16 @@ export class StrategyManager extends EventEmitter {
}
async initializeStrategies(configs: StrategyConfig[]): Promise<void> {
if (new Set(configs.map(config => config.id)).size !== configs.length) {
throw new Error('Duplicate strategy IDs');
}
// Clear existing strategies
for (const [_id, strategy] of this.strategies) {
await strategy.shutdown();
}
this.strategies.clear();
this.activeStrategies.clear();
this.setupEventListeners();
// Get trading engine from mode manager
const modeManager = this.container.custom?.ModeManager;
@ -97,49 +131,31 @@ export class StrategyManager extends EventEmitter {
throw error;
}
}
await this.recover();
}
async restoreStrategies(): Promise<void> {
this.setupEventListeners();
const configs = await defined(this.container.custom?.ExecutionService).registeredStrategies();
if (configs.length) {
await this.initializeStrategies(configs);
}
}
async attachStrategy(strategy: BaseStrategy): Promise<void> {
this.setupEventListeners();
const config = strategy.getConfig();
if (this.strategies.has(config.id)) {
throw new Error('Strategy ID already attached');
}
this.strategies.set(config.id, strategy);
await this.enableStrategy(config.id);
await this.recover();
}
private async createStrategy(config: StrategyConfig): Promise<BaseStrategy> {
// Load strategy based on name
let strategy: BaseStrategy;
switch (config.name.toLowerCase()) {
case 'meanreversion':
case 'mean-reversion': {
const { MeanReversionStrategy } = await import('./examples/MeanReversionStrategy');
strategy = new MeanReversionStrategy(
config,
defined(this.container.custom?.ModeManager),
defined(this.container.custom?.ExecutionService)
);
break;
}
case 'smacrossover':
case 'sma-crossover':
case 'moving-average': {
const { SimpleMovingAverageCrossover } = await import(
'./examples/SimpleMovingAverageCrossoverFixed'
);
strategy = new SimpleMovingAverageCrossover(
config,
defined(this.container.custom?.ModeManager),
defined(this.container.custom?.ExecutionService)
);
break;
}
case 'mlenhanced':
case 'ml-enhanced': {
const { MLEnhancedStrategy } = await import('./examples/MLEnhancedStrategy');
strategy = new MLEnhancedStrategy(
config,
defined(this.container.custom?.ModeManager),
defined(this.container.custom?.ExecutionService)
);
break;
}
default:
throw new Error(`Unknown strategy: ${config.name}`);
}
const strategy = await this.registry.create(config, {
modeManager: defined(this.container.custom?.ModeManager),
execution: defined(this.container.custom?.ExecutionService),
});
// Set up strategy event handlers
strategy.on('signal', signal => {
@ -159,8 +175,18 @@ export class StrategyManager extends EventEmitter {
throw new Error(`Strategy ${strategyId} not found`);
}
const execution = defined(this.container.custom?.ExecutionService);
if (execution.requiresDurableCheckpoint() && !strategy.getCheckpointVersion()) {
throw new Error('Paper strategies require a versioned checkpoint contract');
}
await strategy.initialize();
await strategy.start(); // Start the strategy to make it active
try {
await execution.registerStrategy(strategy);
} catch (error) {
await strategy.suspend();
throw error;
}
this.activeStrategies.add(strategyId);
this.container.logger.info(`Enabled strategy: ${strategyId}`);
}
@ -171,33 +197,13 @@ export class StrategyManager extends EventEmitter {
throw new Error(`Strategy ${strategyId} not found`);
}
await strategy.shutdown();
// Disable pauses new decisions; pending orders/intents remain explicit ledger work.
await defined(this.container.custom?.ExecutionService).pauseStrategy(strategyId);
await strategy.suspend();
this.activeStrategies.delete(strategyId);
this.container.logger.info(`Disabled strategy: ${strategyId}`);
}
private async handleMarketData(data: MarketData): Promise<void> {
const execution = defined(this.container.custom?.ExecutionService);
if (!(await execution.onMarketData(data))) {
return;
}
for (const strategyId of this.activeStrategies) {
const strategy = this.strategies.get(strategyId);
if (strategy && strategy.isInterestedInSymbol(data.data.symbol)) {
try {
strategy.setMarketEvent(identity(data));
await strategy.onMarketData(data);
} catch (error) {
this.container.logger.error(
`Error processing market data for strategy ${strategyId}:`,
error
);
}
}
}
}
private async handleStrategySignal(strategyId: string, signal: Signal): Promise<void> {
this.container.logger.info(`Strategy ${strategyId} generated signal:`, signal);
// Signals are informational - strategies will convert strong signals to orders
@ -230,10 +236,18 @@ export class StrategyManager extends EventEmitter {
this.marketSource.off('marketDataBatch', this.onBatch);
}
this.listening = false;
await this.drain();
if (this.recoveryTimer) {
clearInterval(this.recoveryTimer);
this.recoveryTimer = undefined;
}
try {
await this.drain();
} catch (error) {
this.container.logger.error('Leaving durable strategy backlog for restart', { error });
}
// Disable all strategies
for (const strategyId of this.activeStrategies) {
await this.disableStrategy(strategyId);
await this.strategies.get(strategyId)?.suspend();
}
// Clear all strategies

View file

@ -0,0 +1,42 @@
import type { ModeManager } from '../core/ModeManager';
import type { ExecutionService } from '../services/ExecutionService';
import type { StrategyConfig } from '../types';
import type { BaseStrategy } from './BaseStrategy';
export interface StrategyDependencies {
modeManager: ModeManager;
execution: ExecutionService;
}
export type StrategyFactory = (
config: StrategyConfig,
dependencies: StrategyDependencies
) => BaseStrategy | Promise<BaseStrategy>;
/** Registration belongs to composition; strategy lifecycle belongs to the manager. */
export class StrategyRegistry {
private readonly factories = new Map<string, StrategyFactory>();
register(names: readonly string[], factory: StrategyFactory): this {
const keys = names.map(name => name.trim().toLowerCase());
if (!keys.length || keys.some(key => !key) || new Set(keys).size !== keys.length) {
throw new Error('Strategy aliases must be nonempty and distinct');
}
for (const key of keys) {
if (this.factories.has(key)) {
throw new Error(`Strategy alias already registered: ${key}`);
}
}
for (const key of keys) {
this.factories.set(key, factory);
}
return this;
}
async create(config: StrategyConfig, dependencies: StrategyDependencies): Promise<BaseStrategy> {
const factory = this.factories.get(config.name.trim().toLowerCase());
if (!factory) {
throw new Error(`Unknown strategy: ${config.name}`);
}
return factory(config, dependencies);
}
}

View file

@ -0,0 +1,23 @@
import { StrategyRegistry } from './StrategyRegistry';
/** Lazy factories avoid loading every strategy (and ML dependency) at startup. */
export function createBuiltinStrategyRegistry(): StrategyRegistry {
return new StrategyRegistry()
.register(['meanreversion', 'mean-reversion'], async (config, { modeManager, execution }) => {
const { MeanReversionStrategy } = await import('./examples/MeanReversionStrategy');
return new MeanReversionStrategy(config, modeManager, execution);
})
.register(
['smacrossover', 'sma-crossover', 'moving-average'],
async (config, { modeManager, execution }) => {
const { SimpleMovingAverageCrossover } = await import(
'./examples/SimpleMovingAverageCrossoverFixed'
);
return new SimpleMovingAverageCrossover(config, modeManager, execution);
}
)
.register(['mlenhanced', 'ml-enhanced'], async (config, { modeManager, execution }) => {
const { MLEnhancedStrategy } = await import('./examples/MLEnhancedStrategy');
return new MLEnhancedStrategy(config, modeManager, execution);
});
}

View file

@ -0,0 +1,15 @@
import { z } from 'zod';
export const priceHistoryState = z.array(
z.tuple([z.string(), z.array(z.number().finite().positive()).max(60)])
);
export const barCounterState = z.array(z.tuple([z.string(), z.number().int().nonnegative()]));
export const crossoverCheckpointSchema = z
.object({
priceHistory: priceHistoryState,
barCount: barCounterState,
lastSignalBar: barCounterState,
totalSignals: z.number().int().nonnegative(),
lastCrossoverType: z.array(z.tuple([z.string(), z.enum(['golden', 'death']).nullable()])),
})
.strict();

View file

@ -1,9 +1,11 @@
import { z } from 'zod';
import { defined } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
import { at } from '@stock-bot/utils';
import type { StrategyConfig } from '../../types';
import { type MarketData } from '../../types';
import { BaseStrategy, type Signal } from '../BaseStrategy';
import { priceHistoryState } from '../checkpoint-schemas';
const logger = getLogger('MeanReversionStrategy');
@ -18,6 +20,29 @@ interface MeanReversionIndicators {
export class MeanReversionStrategy extends BaseStrategy {
private priceHistory = new Map<string, number[]>();
private indicators = new Map<string, MeanReversionIndicators>();
override getCheckpointVersion() {
return 'mean-reversion/v1';
}
protected override captureIndicators() {
return { priceHistory: [...this.priceHistory], indicators: [...this.indicators] };
}
protected override restoreIndicators(input: unknown) {
const finite = z.number().finite();
const state = z
.object({
priceHistory: priceHistoryState,
indicators: z.array(
z.tuple([
z.string(),
z.object({ sma20: finite, sma50: finite, stdDev: finite, zScore: finite, rsi: finite }),
])
),
})
.strict()
.parse(input);
this.priceHistory = new Map(state.priceHistory);
this.indicators = new Map(state.indicators);
}
// Strategy parameters
private readonly LOOKBACK_PERIOD = 20;

View file

@ -5,6 +5,7 @@ import type { ExecutionService, StrategyFill } from '../../services/ExecutionSer
import type { OrderRequest, StrategyConfig } from '../../types';
import { type MarketData } from '../../types';
import { BaseStrategy, type Signal } from '../BaseStrategy';
import { crossoverCheckpointSchema } from '../checkpoint-schemas';
const logger = getLogger('SimpleMovingAverageCrossover');
@ -13,6 +14,25 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
private lastTradeTime = new Map<string, number>();
private barCount = new Map<string, number>();
private totalSignals = 0;
override getCheckpointVersion() {
return 'sma-crossover-original/v1';
}
protected override captureIndicators() {
return {
priceHistory: [...this.priceHistory],
lastSignalBar: [...this.lastTradeTime],
barCount: [...this.barCount],
totalSignals: this.totalSignals,
lastCrossoverType: [],
};
}
protected override restoreIndicators(input: unknown) {
const state = crossoverCheckpointSchema.parse(input);
this.priceHistory = new Map(state.priceHistory);
this.lastTradeTime = new Map(state.lastSignalBar);
this.barCount = new Map(state.barCount);
this.totalSignals = state.totalSignals;
}
// Strategy parameters
private readonly FAST_PERIOD = 5; // Changed from 10 to generate more signals

View file

@ -5,6 +5,7 @@ import type { ExecutionService, StrategyFill } from '../../services/ExecutionSer
import type { StrategyConfig } from '../../types';
import { type MarketData } from '../../types';
import { BaseStrategy, type Signal } from '../BaseStrategy';
import { crossoverCheckpointSchema } from '../checkpoint-schemas';
const logger = getLogger('SimpleMovingAverageCrossover');
@ -14,6 +15,26 @@ export class SimpleMovingAverageCrossover extends BaseStrategy {
private barCount = new Map<string, number>();
private totalSignals = 0;
private lastCrossoverType = new Map<string, 'golden' | 'death' | null>();
override getCheckpointVersion() {
return 'sma-crossover-fixed/v1';
}
protected override captureIndicators() {
return {
priceHistory: [...this.priceHistory],
lastSignalBar: [...this.lastSignalBar],
barCount: [...this.barCount],
totalSignals: this.totalSignals,
lastCrossoverType: [...this.lastCrossoverType],
};
}
protected override restoreIndicators(input: unknown) {
const state = crossoverCheckpointSchema.parse(input);
this.priceHistory = new Map(state.priceHistory);
this.lastSignalBar = new Map(state.lastSignalBar);
this.barCount = new Map(state.barCount);
this.totalSignals = state.totalSignals;
this.lastCrossoverType = new Map(state.lastCrossoverType);
}
// Strategy parameters
private readonly FAST_PERIOD = 5; // Changed from 10 to generate more signals

View file

@ -3,7 +3,7 @@ import {
datasetHashSchema,
historicalDataPolicySchema,
instrumentIdSchema,
} from './data/historical-dataset';
} from './contracts/historical';
// Trading modes
export const TradingModeSchema = z.enum(['backtest', 'paper', 'live']);

View file

@ -47,7 +47,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
f === '09-backtest-run-contract.sql' ||
f === '10-durable-backtest-dispatch.sql' ||
f === '11-simulation-execution-ledger.sql' ||
f === '12-historical-datasets.sql')
f === '12-historical-datasets.sql' ||
f === '13-strategy-recovery.sql')
) // Explicit additive migration allowlist; never replay destructive init migrations
.sort();

View file

@ -0,0 +1,23 @@
-- Append-only market/execution inputs, bounded strategy checkpoints, transactional order outbox.
-- Legacy event fingerprints have no payload and cannot be fabricated into replayable history.
CREATE TABLE IF NOT EXISTS simulation_market_inputs (
account_id TEXT NOT NULL REFERENCES simulation_accounts(id), id TEXT NOT NULL,
sequence BIGINT NOT NULL, status TEXT NOT NULL CHECK(status IN ('pending','applied')),
payload JSONB NOT NULL, PRIMARY KEY(account_id,id), UNIQUE(account_id,sequence)
);
CREATE INDEX IF NOT EXISTS simulation_pending_inputs ON simulation_market_inputs(account_id,status,sequence);
CREATE TABLE IF NOT EXISTS simulation_strategy_journal (
account_id TEXT NOT NULL REFERENCES simulation_accounts(id), sequence BIGINT NOT NULL,
payload JSONB NOT NULL, PRIMARY KEY(account_id,sequence)
);
CREATE TABLE IF NOT EXISTS simulation_strategy_checkpoints (
account_id TEXT NOT NULL REFERENCES simulation_accounts(id), strategy_id TEXT NOT NULL,
payload JSONB NOT NULL, PRIMARY KEY(account_id,strategy_id)
);
CREATE TABLE IF NOT EXISTS simulation_strategy_intents (
account_id TEXT NOT NULL, client_order_id TEXT NOT NULL, strategy_id TEXT NOT NULL,
sequence BIGINT NOT NULL, status TEXT NOT NULL CHECK(status IN ('pending','dispatched')),
payload JSONB NOT NULL, PRIMARY KEY(account_id,client_order_id),
FOREIGN KEY(account_id,strategy_id) REFERENCES simulation_strategy_checkpoints(account_id,strategy_id)
);
CREATE INDEX IF NOT EXISTS simulation_pending_intents ON simulation_strategy_intents(account_id,status,sequence);

View file

@ -0,0 +1,47 @@
/** Local, deterministic workload; no native engine, database, network or trading credentials. */
import { defaultRiskLimits, type Account } from '../apps/stock/orchestrator/src/execution/model';
import { BacktestExecutionRepository } from '../apps/stock/orchestrator/src/execution/BacktestExecutionRepository';
const account: Account = {
initialCapital: 10000,
cash: 10000,
realizedPnl: 0,
dailyPnl: 0,
day: '2024-01-01',
commission: 0.001,
slippage: 0,
limits: { ...defaultRiskLimits },
maxQuoteAgeMs: 60000,
positions: {},
quotes: {},
strategyPositions: {},
};
for (const history of [0, 1000, 10000]) {
const repository = new BacktestExecutionRepository();
await repository.initialize('benchmark', account);
await repository.transact('benchmark', async tx => {
for (let i = 0; i < history; i++) {
await tx.appendJournal({
kind: 'market',
market: {
type: 'trade',
eventId: String(i),
data: { symbol: 'A.US', price: 100, size: 1, side: 'buy', timestamp: i },
},
recipients: [],
account,
});
}
});
const start = performance.now();
for (let i = 0; i < 200; i++) {
await repository.transact('benchmark', async tx => ({
cash: tx.account.cash,
next: await tx.nextJournal(history),
}));
}
process.stdout.write(
`${history} journal events: ${((performance.now() - start) / 200).toFixed(3)} ms/transaction\n`
);
}

View file

@ -0,0 +1,101 @@
import { existsSync, readFileSync } from 'node:fs';
import { dirname, join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'bun:test';
import ts from 'typescript';
const root = fileURLToPath(new URL('../../apps/stock/orchestrator/src/', import.meta.url));
const files = [...new Bun.Glob('**/*.ts').scanSync({ cwd: root })].map(file => join(root, file));
/** Include static imports/re-exports and lazy imports; type-only edges do not load code. */
function runtimeImports(file: string): string[] {
const source = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);
const imports = new Set<string>();
function visit(node: ts.Node) {
if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {
const clause = node.importClause;
const bindings = clause?.namedBindings;
const typesOnly = clause?.isTypeOnly ||
(clause && !clause.name && bindings && ts.isNamedImports(bindings) &&
bindings.elements.length > 0 && bindings.elements.every(item => item.isTypeOnly));
if (!typesOnly) imports.add(node.moduleSpecifier.text);
}
if (ts.isExportDeclaration(node) && !node.isTypeOnly && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {
const clause = node.exportClause;
if (!clause || !ts.isNamedExports(clause) || !clause.elements.length || clause.elements.some(item => !item.isTypeOnly)) {
imports.add(node.moduleSpecifier.text);
}
}
if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments[0] && ts.isStringLiteral(node.arguments[0])) {
imports.add(node.arguments[0].text);
}
ts.forEachChild(node, visit);
}
visit(source);
return [...imports];
}
const imports = new Map(files.map(file => [file, runtimeImports(file)]));
function localFile(from: string, specifier: string): string | undefined {
if (!specifier.startsWith('.')) return undefined;
const path = resolve(dirname(from), specifier);
const target = [path, `${path}.ts`, join(path, 'index.ts')].find(file => existsSync(file) && imports.has(file));
if (!target) throw new Error(`Unresolved local runtime import: ${relative(root, from)} -> ${specifier}`);
return target;
}
const graph = new Map([...imports].map(([file, dependencies]) => [file,
dependencies.map(specifier => localFile(file, specifier)).filter((file): file is string => !!file),
]));
function reachable(file: string, seen = new Set<string>()): Set<string> {
if (seen.has(file)) return seen;
seen.add(file);
for (const next of graph.get(file) ?? []) reachable(next, seen);
return seen;
}
describe('orchestrator architecture boundaries', () => {
it('local runtime dependencies are acyclic', () => {
const done = new Set<string>();
function visit(file: string, stack: string[]) {
if (stack.includes(file)) throw new Error(`Runtime dependency cycle: ${[...stack, file].map(file => relative(root, file)).join(' -> ')}`);
if (done.has(file)) return;
for (const next of graph.get(file) ?? []) visit(next, [...stack, file]);
done.add(file);
}
for (const file of files) visit(file, []);
});
it('contracts and native worker protocol cannot load services, storage or server adapters', () => {
const contracts = files.filter(file => file.startsWith(join(root, 'contracts/')));
for (const entry of [...contracts, join(root, 'types.ts'), join(root, 'backtest/native-worker-protocol.ts')]) {
for (const file of reachable(entry)) {
const path = relative(root, file);
expect(path === 'types.ts' || path.startsWith('contracts/') || path === 'backtest/native-worker-protocol.ts').toBe(true);
for (const specifier of imports.get(file) ?? []) {
expect(specifier.startsWith('.') || ['zod', '@stock-bot/types'].includes(specifier)).toBe(true);
}
}
}
});
it('recovery and the ledger port do not depend on concrete adapters, strategies or the service container', () => {
for (const entry of ['execution/SimulationExecution.ts', 'execution/StrategyRecovery.ts', 'execution/repository.ts', 'execution/strategy-recovery.ts', 'execution/model.ts']) {
for (const file of reachable(join(root, entry))) {
expect(relative(root, file)).not.toMatch(/^(services|strategies|core|data)\//);
expect(relative(root, file)).not.toMatch(/(Postgres|Backtest)ExecutionRepository/);
for (const specifier of imports.get(file) ?? []) {
expect(['@stock-bot/services', '@stock-bot/di', '@stock-bot/engine', 'awilix'].includes(specifier)).toBe(false);
}
}
}
expect(imports.get(join(root, 'execution/repository.ts'))).toEqual([]);
});
it('the strategy manager cannot select or directly import concrete strategies', () => {
const file = join(root, 'strategies/StrategyManager.ts');
expect(imports.get(file)?.some(specifier => specifier.includes('/examples/'))).toBe(false);
expect(readFileSync(file, 'utf8')).not.toMatch(/switch\s*\(\s*config\.name/);
expect(imports.get(join(root, 'strategies/StrategyRegistry.ts'))).toEqual([]);
});
});

56
test/fixtures/strategy-crash-owner.ts vendored Normal file
View file

@ -0,0 +1,56 @@
/** Disposable process used only against an isolated stock_bot_safety schema. */
import { Pool } from 'pg';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository';
import { logger, makeExecution, start } from './execution';
import { attachCounter, CounterStrategy, FaultRepository } from './strategy-recovery';
const url = process.env.PIPELINE_TEST_DATABASE_URL,
schema = process.env.STRATEGY_FIXTURE_SCHEMA,
phase = process.env.STRATEGY_FIXTURE_PHASE;
if (
!url ||
!new URL(url).pathname.startsWith('/stock_bot_safety') ||
!schema ||
!/^stock_bot_safety_[a-f0-9]+$/.test(schema) ||
!['decision', 'checkpoint', 'dispatch'].includes(phase ?? '')
) {
throw new Error('Unsafe strategy crash fixture');
}
const pool = new Pool({ connectionString: url, options: '-c search_path=' + schema });
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
const repository = new FaultRepository(new PostgresExecutionRepository(postgres));
const { execution, engine } = makeExecution(repository, () => start + 100);
await execution.initialize(
{
mode: 'paper',
accountId: 'fixture',
startingCapital: 10000,
commission: 0.001,
slippage: 0,
maxQuoteAgeMs: 1000,
},
engine
);
const blocked = async () => {
process.send?.({ phase });
await new Promise<void>(() => {});
};
const strategy = new CounterStrategy(execution);
if (phase === 'decision') {
strategy.onDecision = blocked;
} else {
repository.fault = {
method: 'putIntent',
stage: 'commit',
matches: value =>
(value as { status: string }).status === (phase === 'checkpoint' ? 'pending' : 'dispatched'),
hook: blocked,
};
}
await attachCounter(execution, strategy);
throw new Error('Crash fixture did not reach its requested boundary');

126
test/fixtures/strategy-recovery.ts vendored Normal file
View file

@ -0,0 +1,126 @@
import { z } from 'zod';
import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
import type {
ExecutionRepository,
ExecutionTransaction,
} from '../../apps/stock/orchestrator/src/execution/repository';
import type {
ExecutionService,
StrategyFill,
} from '../../apps/stock/orchestrator/src/services/ExecutionService';
import {
BaseStrategy,
type Signal,
} from '../../apps/stock/orchestrator/src/strategies/BaseStrategy';
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
import type { MarketData, StrategyConfig } from '../../apps/stock/orchestrator/src/types';
import { logger } from './execution';
export const recoveryConfig: StrategyConfig = {
id: 'counter',
name: 'fixture',
symbols: ['A'],
parameters: {},
allocation: 1,
enabled: true,
};
export class CounterStrategy extends BaseStrategy {
count = 0;
equities: number[] = [];
failDecision = false;
failFill = false;
onDecision?: () => Promise<void>;
version = 'counter/v1';
constructor(execution: ExecutionService, config = recoveryConfig) {
super(config, {} as ModeManager, execution);
}
override getCheckpointVersion() {
return this.version;
}
protected override captureIndicators() {
return { count: this.count, equities: this.equities };
}
protected override restoreIndicators(input: unknown) {
const state = z
.object({ count: z.number().int().nonnegative(), equities: z.array(z.number().finite()) })
.parse(input);
this.count = state.count;
this.equities = state.equities;
}
protected updateIndicators() {
this.count++;
}
protected async generateSignal(data: MarketData): Promise<Signal | null> {
this.equities.push((await this.executionService.getAccount()).equity);
await this.onDecision?.();
if (this.failDecision) {
throw new Error('injected decision failure');
}
return { type: 'buy', symbol: data.data.symbol, strength: 1, metadata: { quantity: 1 } };
}
override async onFill(fill: StrategyFill) {
await super.onFill(fill);
if (this.failFill) {
throw new Error('injected fill callback failure');
}
}
}
export async function attachCounter(
execution: ExecutionService,
strategy = new CounterStrategy(execution)
) {
const manager = new StrategyManager({ logger, custom: { ExecutionService: execution } });
await manager.attachStrategy(strategy);
return { manager, strategy };
}
export class FaultRepository implements ExecutionRepository {
fault?: {
method: keyof ExecutionTransaction;
matches: (argument: unknown) => boolean;
stage: 'before' | 'after' | 'commit';
hook?: () => Promise<void>;
};
constructor(private readonly delegate: ExecutionRepository) {}
initialize(...args: Parameters<ExecutionRepository['initialize']>) {
return this.delegate.initialize(...args);
}
async transact<T>(account: string, work: (tx: ExecutionTransaction) => Promise<T>): Promise<T> {
let matched: typeof this.fault;
const result = await this.delegate.transact(account, tx =>
work(
new Proxy(tx, {
get: (target, key: keyof ExecutionTransaction) => {
const value = target[key];
if (typeof value !== 'function') {
return value;
}
return async (...args: unknown[]) => {
const fault = this.fault;
const hit = fault && key === fault.method && fault.matches(args[0]);
if (hit) {
this.fault = undefined;
matched = fault;
}
if (hit && fault.stage === 'before') {
throw new Error('injected transaction failure');
}
const answer = await Reflect.apply(value, target, args);
if (hit && fault.stage === 'after') {
throw new Error('injected transaction failure');
}
return answer;
};
},
})
)
);
if (matched?.stage === 'commit') {
if (matched.hook) {
await matched.hook();
}
throw new Error('injected lost commit acknowledgement');
}
return result;
}
}

View file

@ -0,0 +1,334 @@
import { describe, expect, test } from 'bun:test';
import { BacktestExecutionRepository } from '../../apps/stock/orchestrator/src/execution/BacktestExecutionRepository';
import {
defaultRiskLimits,
type Account,
type StoredOrder,
} from '../../apps/stock/orchestrator/src/execution/model';
import type { ExecutionTransaction } from '../../apps/stock/orchestrator/src/execution/repository';
import type {
MarketInput,
StrategyCheckpoint,
StrategyOrderIntent,
} from '../../apps/stock/orchestrator/src/execution/strategy-recovery';
const initial: Account = {
initialCapital: 10000,
cash: 10000,
realizedPnl: 0,
dailyPnl: 0,
day: '2024-01-01',
commission: 0.001,
slippage: 0,
limits: { ...defaultRiskLimits },
maxQuoteAgeMs: 60000,
positions: {},
quotes: {},
strategyPositions: {},
};
const input: MarketInput = {
id: '10',
sequence: 1,
status: 'pending',
market: {
type: 'trade',
data: { symbol: 'A.US', price: 100, size: 1, side: 'buy', timestamp: 1 },
},
};
const request = {
symbol: 'A.US',
side: 'buy',
quantity: 1,
orderType: 'market',
timeInForce: 'DAY',
clientOrderId: '__proto__',
} as const;
const order: StoredOrder = {
request,
fingerprint: 'fingerprint',
policy: { commission: 0.001, slippage: 0 },
report: {
orderId: 'order',
clientOrderId: request.clientOrderId,
symbol: request.symbol,
side: request.side,
quantity: 1,
status: 'accepted',
fills: [],
timestamp: 1,
},
};
const checkpoint: StrategyCheckpoint = {
strategyId: 'strategy',
config: {
id: 'strategy',
name: 'test',
enabled: true,
symbols: ['A.US'],
parameters: {},
allocation: 1,
},
configHash: 'hash',
version: 'v1',
enabled: true,
cursor: 0,
state: { count: 0 },
};
const intent: StrategyOrderIntent = {
clientOrderId: request.clientOrderId,
strategyId: checkpoint.strategyId,
sequence: 1,
request,
status: 'pending',
};
const fill = { id: '__proto__', price: 100, quantity: 1, commission: 0.1, timestamp: 1, pnl: 0 };
const journal = {
kind: 'market' as const,
market: input.market,
recipients: ['strategy'],
account: initial,
};
async function fixture(account = initial) {
const repository = new BacktestExecutionRepository();
await repository.initialize('run', account);
return {
repository,
transact: <T>(work: (tx: ExecutionTransaction) => Promise<T>) =>
repository.transact('run', work),
};
}
describe('run-local execution transaction isolation', () => {
test('uninitialized stores fail explicitly', async () => {
await expect(new BacktestExecutionRepository().transact('run', async () => 1)).rejects.toThrow(
'not initialized'
);
});
test('a failed transaction rolls back every table, index, sequence and account mutation', async () => {
const f = await fixture();
await expect(
f.transact(async tx => {
tx.account.cash = 1;
await tx.putOrder(order);
await tx.insertFill(order.report.orderId, fill);
await tx.recordEvent('__proto__', 'hash');
await tx.putStrategy(checkpoint);
await tx.putIntent(intent);
await tx.putInput(input);
await tx.appendJournal(journal);
expect(await tx.findOrder('__proto__')).toEqual(order);
expect(await tx.nextJournal(0)).toMatchObject({ sequence: 1 });
throw new Error('rollback');
})
).rejects.toThrow('rollback');
await f.transact(async tx => {
expect(tx.account.cash).toBe(10000);
expect(tx.account.strategySequence).toBeUndefined();
expect(await tx.findOrder('__proto__')).toBeUndefined();
expect(await tx.getOrder('order')).toBeUndefined();
expect(await tx.openOrders()).toEqual([]);
expect(await tx.strategies()).toEqual([]);
expect(await tx.nextIntent()).toBeUndefined();
expect(await tx.nextInput()).toBeUndefined();
expect(await tx.nextJournal(0)).toBeUndefined();
expect(await tx.recordEvent('__proto__', 'hash')).toBe(true);
expect(await tx.insertFill('order', fill)).toBe(true);
});
});
test('caller-owned objects, returned reads and retained transaction references cannot mutate commits', async () => {
const seed = structuredClone(initial);
const f = await fixture(seed);
seed.cash = 0;
const writes = structuredClone({ order, checkpoint, intent, input, journal });
let escaped!: ExecutionTransaction;
const result = await f.transact(async tx => {
escaped = tx;
await tx.putOrder(writes.order);
await tx.putStrategy(writes.checkpoint);
await tx.putIntent(writes.intent);
await tx.putInput(writes.input);
await tx.appendJournal(writes.journal);
return tx.account;
});
result.cash = 2;
escaped.account.cash = 3;
writes.order.report.status = 'rejected';
writes.checkpoint.enabled = false;
writes.intent.status = 'dispatched';
writes.input.status = 'applied';
writes.journal.account.cash = 4;
await expect(escaped.putInput(input)).rejects.toThrow('finished');
await f.transact(async tx => {
expect(tx.account.cash).toBe(10000);
(await tx.getOrder('order'))!.report.status = 'rejected';
(await tx.strategies())[0]!.enabled = false;
(await tx.nextInput())!.status = 'applied';
(await tx.nextIntent())!.status = 'dispatched';
(await tx.nextJournal(0))!.payload.account.cash = 5;
});
await f.transact(async tx => {
expect(await tx.openOrders()).toEqual([order]);
expect(await tx.strategies()).toEqual([checkpoint]);
expect(await tx.nextInput()).toEqual(input);
expect(await tx.nextIntent()).toEqual(intent);
expect((await tx.nextJournal(0))?.payload.account.cash).toBe(10000);
});
});
test('uncloneable callback results roll back before publishing any staged writes', async () => {
const f = await fixture();
await expect(
f.transact(async tx => {
tx.account.cash = 0;
await tx.putOrder(order);
return () => {};
})
).rejects.toThrow();
await f.transact(async tx => {
expect(tx.account.cash).toBe(10000);
expect(await tx.openOrders()).toEqual([]);
});
});
test('transactions serialize and a failed predecessor does not poison the queue', async () => {
const f = await fixture();
const results = await Promise.allSettled([
f.transact(async tx => {
tx.account.cash -= 1;
await Promise.resolve();
}),
f.transact(async tx => {
tx.account.cash = -1;
throw new Error('rollback');
}),
f.transact(async tx => {
tx.account.cash -= 2;
}),
]);
expect(results.map(result => result.status)).toEqual(['fulfilled', 'rejected', 'fulfilled']);
expect(await f.transact(async tx => tx.account.cash)).toBe(9997);
});
test('pending indexes reflect staged updates, and rollback preserves their previous heads', async () => {
const f = await fixture();
await f.transact(async tx => {
await tx.putOrder(order);
await tx.putInput(input);
await tx.putInput({ ...input, id: '2', sequence: 2 });
await tx.putIntent(intent);
await tx.putIntent({
...intent,
clientOrderId: 'next',
sequence: 2,
request: { ...request, clientOrderId: 'next' },
});
});
const drain = async (tx: ExecutionTransaction) => {
await tx.putOrder({ ...order, report: { ...order.report, status: 'filled' } });
await tx.putInput({ ...input, status: 'applied' });
await tx.putIntent({ ...intent, status: 'dispatched' });
expect(await tx.openOrders()).toEqual([]);
expect((await tx.nextInput())?.id).toBe('2');
expect((await tx.nextIntent())?.clientOrderId).toBe('next');
};
await expect(
f.transact(async tx => {
await drain(tx);
throw new Error('rollback');
})
).rejects.toThrow('rollback');
await f.transact(async tx => {
expect(await tx.openOrders()).toEqual([order]);
expect(await tx.nextInput()).toEqual(input);
expect(await tx.nextIntent()).toEqual(intent);
await drain(tx);
});
await f.transact(async tx => {
expect(await tx.openOrders()).toEqual([]);
expect((await tx.nextInput())?.id).toBe('2');
expect((await tx.nextIntent())?.clientOrderId).toBe('next');
});
});
test('journal lookup supports nonzero sequences, gaps at the cursor and staged appends', async () => {
const f = await fixture({ ...initial, strategySequence: 20 });
await f.transact(async tx => {
await tx.appendJournal(journal);
await tx.appendJournal(journal);
});
await f.transact(async tx => {
await tx.appendJournal(journal);
for (const [cursor, expected] of [
[-1, 21],
[20, 21],
[21, 22],
[22, 23],
[23, undefined],
[100, undefined],
]) {
expect((await tx.nextJournal(cursor!))?.sequence).toBe(expected);
}
});
});
test('sequence exhaustion cannot commit a partial journal or account change', async () => {
const f = await fixture({ ...initial, strategySequence: Number.MAX_SAFE_INTEGER });
await expect(
f.transact(async tx => {
tx.account.cash = 1;
await tx.appendJournal(journal);
})
).rejects.toThrow('exhausted');
expect(await f.transact(async tx => tx.account.cash)).toBe(10000);
});
test('pending-intent ties use deterministic sequence, strategy and client ID order', async () => {
const f = await fixture();
await f.transact(async tx => {
for (const [strategyId, clientOrderId, sequence] of [
['b', '1', 1],
['a', '2', 1],
['a', '10', 1],
['0', '0', 2],
] as const) {
await tx.putIntent({
...intent,
strategyId,
clientOrderId,
sequence,
request: { ...request, clientOrderId },
});
}
});
for (const expected of ['10', '2', '1', '0']) {
await f.transact(async tx => {
const next = (await tx.nextIntent())!;
expect(next.clientOrderId).toBe(expected);
await tx.putIntent({ ...next, status: 'dispatched' });
});
}
expect(await f.transact(tx => tx.nextIntent())).toBeUndefined();
});
test('duplicate financial identities are indexed safely, including special JavaScript keys', async () => {
const f = await fixture();
await f.transact(async tx => {
await tx.putOrder(order);
expect(await tx.findOrder('__proto__')).toEqual(order);
expect(await tx.insertFill('order', fill)).toBe(true);
expect(await tx.insertFill('order', fill)).toBe(false);
expect(await tx.recordEvent('constructor', 'hash')).toBe(true);
expect(await tx.recordEvent('constructor', 'hash')).toBe(false);
});
await expect(
f.transact(tx => tx.putOrder({ ...order, report: { ...order.report, orderId: 'duplicate' } }))
).rejects.toThrow('already exists');
await expect(f.transact(tx => tx.recordEvent('constructor', 'different'))).rejects.toThrow(
'Conflicting'
);
expect(await f.transact(tx => tx.insertFill('order', fill))).toBe(false);
});
});

View file

@ -216,11 +216,8 @@ describe('one simulation execution gateway', () => {
{} as ModeManager,
execution
);
await strategy.initialize();
await strategy.start();
// Inject only the strategy fixture; market delivery, gateway, accounting, and native projection are real.
Object.defineProperty(manager, 'strategies', { value: new Map([['strategy', strategy]]) });
Object.defineProperty(manager, 'activeStrategies', { value: new Set(['strategy']) });
await manager.attachStrategy(strategy);
cleanup.push(() => manager.shutdown());
const first = quote('1');
const second = quote('2', 100, 100, start + 1);

View file

@ -0,0 +1,192 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { BacktestExecutionRepository } from '../../apps/stock/orchestrator/src/execution/BacktestExecutionRepository';
import { canonicalJson } from '../../apps/stock/orchestrator/src/execution/strategy-recovery';
import { config, makeExecution, order, quote, start } from '../fixtures/execution';
import {
attachCounter,
CounterStrategy,
FaultRepository,
recoveryConfig,
} from '../fixtures/strategy-recovery';
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
async function fixture() {
const repository = new FaultRepository(new BacktestExecutionRepository());
const { execution, engine } = makeExecution(repository);
await execution.initialize(config, engine);
cleanup.push(() => execution.shutdown());
const { manager, strategy } = await attachCounter(execution);
cleanup.push(() => manager.shutdown());
return { repository, execution, manager, strategy };
}
const isPending = (value: unknown) => (value as { status?: string }).status === 'pending';
const isDispatched = (value: unknown) => (value as { status?: string }).status === 'dispatched';
describe('transactional strategy recovery', () => {
test('input order is its admission sequence, not JavaScript numeric object-key enumeration', async () => {
const f = await fixture();
await f.execution.enqueueMarketData(quote('10'));
await f.execution.enqueueMarketData(quote('2', 110, 100, start + 1));
await f.manager.recover();
expect(f.strategy.equities).toEqual([10000, 10009.9]);
});
test('a failed decision restores indicators and leaves later admitted inputs recoverable', async () => {
const f = await fixture();
f.strategy.failDecision = true;
await f.execution.enqueueMarketData(quote('one'));
await f.execution.enqueueMarketData(quote('two', 110, 100, start + 1));
await expect(f.manager.recover()).rejects.toThrow('decision failure');
expect(f.strategy.count).toBe(0);
expect(f.strategy.getPosition('A')).toBe(0);
expect((await f.execution.getRecoveryStatus()).pendingInputs).toBe(true);
await expect(f.execution.submitOrder(order('manual'))).rejects.toThrow('backlog');
f.strategy.failDecision = false;
await f.manager.recover();
expect(f.strategy.count).toBe(2);
expect(f.strategy.getPosition('A')).toBe(2);
expect(f.strategy.equities).toEqual([10000, 10009.9]);
expect((await f.execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0);
await f.manager.onMarketData(quote('one'));
expect(f.strategy.count).toBe(2);
});
test.each(['before', 'after'] as const)(
'checkpoint + intent roll back together on a %s intent-write failure',
async stage => {
const f = await fixture();
f.repository.fault = { method: 'putIntent', matches: isPending, stage };
await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow('transaction failure');
expect(f.strategy.count).toBe(0);
expect((await f.execution.getAccount()).cash).toBe(10000);
expect((await f.execution.getRecoveryStatus()).pendingIntents).toBe(false);
await f.manager.recover();
expect(f.strategy.count).toBe(1);
expect(f.strategy.getPosition('A')).toBe(1);
}
);
test('a lost checkpoint commit acknowledgement resumes from durable state, not a second decision', async () => {
const f = await fixture();
f.repository.fault = { method: 'putIntent', matches: isPending, stage: 'commit' };
await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow('commit acknowledgement');
expect((await f.execution.getRecoveryStatus()).pendingIntents).toBe(true);
await f.manager.shutdown();
const restarted = await attachCounter(f.execution);
cleanup.push(() => restarted.manager.shutdown());
expect(restarted.strategy.count).toBe(1);
expect(restarted.strategy.getPosition('A')).toBe(1);
expect(restarted.strategy.getPerformance().trades).toBe(1);
await restarted.manager.onMarketData(quote('one'));
expect(restarted.strategy.count).toBe(1);
});
test.each(['after', 'commit'] as const)(
'outbox dispatch is idempotent after a %s dispatch-status failure',
async stage => {
const f = await fixture();
f.repository.fault = { method: 'putIntent', matches: isDispatched, stage };
await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow('injected');
await f.manager.recover();
expect(f.strategy.count).toBe(1);
expect(f.strategy.getPosition('A')).toBe(1);
expect(f.strategy.getPerformance().trades).toBe(1);
expect((await f.execution.getAccount()).cash).toBe(9899.9);
expect((await f.execution.getRecoveryStatus()).pendingIntents).toBe(false);
}
);
test('fill callback failure cannot lose a committed fill or advance its checkpoint', async () => {
const f = await fixture();
f.strategy.failFill = true;
await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow('fill callback');
expect((await f.execution.getAccount()).strategyPositions.counter?.A).toBe(1);
expect(f.strategy.getPosition('A')).toBe(0);
expect(f.strategy.getPerformance().trades).toBe(0);
f.strategy.failFill = false;
await f.manager.recover();
await f.manager.recover();
expect(f.strategy.getPosition('A')).toBe(1);
expect(f.strategy.getPerformance().trades).toBe(1);
});
test('shutdown preserves unfilled orders, indicator history, and committed cursor', async () => {
const f = await fixture();
await f.manager.onMarketData(quote('one', 100, 0));
const before = f.strategy.captureCheckpoint();
await f.manager.shutdown();
const restarted = await attachCounter(f.execution);
cleanup.push(() => restarted.manager.shutdown());
expect(restarted.strategy.captureCheckpoint()).toEqual(before);
expect((await f.execution.getStrategySnapshot('counter')).orders).toHaveLength(1);
await restarted.manager.onMarketData(quote('two', 100, 100, start + 1));
expect(restarted.strategy.getPerformance().trades).toBe(2);
});
test('configuration and implementation versions cannot silently reset an existing strategy', async () => {
const f = await fixture();
await f.manager.onMarketData(quote('one'));
await f.manager.shutdown();
const changed = new CounterStrategy(f.execution, {
...recoveryConfig,
parameters: { changed: true },
});
await expect(attachCounter(f.execution, changed)).rejects.toThrow('version changed');
const version = new CounterStrategy(f.execution);
version.version = 'counter/v2';
await expect(attachCounter(f.execution, version)).rejects.toThrow('version changed');
expect((await f.execution.getAccount()).strategyPositions.counter?.A).toBe(1);
});
test('disabled-period inputs do not become retroactive trades when re-enabled', async () => {
const f = await fixture();
await f.manager.onMarketData(quote('one'));
await f.manager.disableStrategy('counter');
await f.manager.onMarketData(quote('two', 100, 100, start + 1));
await f.manager.enableStrategy('counter');
await f.manager.recover();
expect(f.strategy.count).toBe(1);
await f.manager.onMarketData(quote('three', 100, 100, start + 2));
expect(f.strategy.count).toBe(2);
});
test('observers run only after checkpoint commit and cannot roll back financial intent', async () => {
const f = await fixture();
let signals = 0;
f.strategy.on('signal', () => {
signals++;
throw new Error('observer');
});
f.execution.setObserver(async () => {
throw new Error('observer');
});
await f.manager.onMarketData(quote('one'));
expect(signals).toBe(1);
expect(f.strategy.count).toBe(1);
expect(f.strategy.getPosition('A')).toBe(1);
});
test('checkpoint serialization rejects lossy or non-finite state', () => {
for (const value of [NaN, Infinity, undefined, new Map(), new Date(), { hidden: undefined }]) {
expect(() => canonicalJson(value)).toThrow('plain JSON');
}
expect(canonicalJson({ b: 1, a: [2] })).toBe(canonicalJson({ a: [2], b: 1 }));
});
test('a callback cannot open a nested repository transaction and deadlock its account', async () => {
const f = await fixture();
f.strategy.onDecision = async () => {
await f.execution.getOrderStatus('anything');
};
await expect(f.manager.onMarketData(quote('one'))).rejects.toThrow(
'cannot perform repository I/O'
);
expect(f.strategy.count).toBe(0);
});
test('a reused intent ID cannot replace a dispatched request or advance its next decision', async () => {
const f = await fixture();
f.strategy.onDecision = async () => {
f.execution.captureStrategyOrder(order('fixed-id', 'buy', 1), 'counter');
};
await f.manager.onMarketData(quote('one'));
await expect(f.manager.onMarketData(quote('two', 100, 100, start + 1))).rejects.toThrow(
'Conflicting strategy order intent'
);
expect(f.strategy.count).toBe(1);
expect((await f.execution.getAccount()).strategyPositions.counter?.A).toBe(2);
});
});

View file

@ -0,0 +1,110 @@
import { afterEach, describe, expect, test } from 'bun:test';
import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies';
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
import { StrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/StrategyRegistry';
import { config, logger, makeExecution, quote } from '../fixtures/execution';
import { CounterStrategy, recoveryConfig } from '../fixtures/strategy-recovery';
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
async function fixture() {
const { execution, engine } = makeExecution();
await execution.initialize(config, engine);
cleanup.push(() => execution.shutdown());
const modeManager = { getTradingEngine: () => engine } as ModeManager;
return {
execution,
dependencies: { modeManager, execution },
services: { logger, custom: { ModeManager: modeManager, ExecutionService: execution } },
};
}
describe('strategy registration and expansion', () => {
test('custom lazy factories integrate with ordinary initialization, recovery and restart', async () => {
const f = await fixture();
let created = 0;
const registry = new StrategyRegistry().register(
['fixture', 'custom-alias'],
(config, dependencies) => {
created++;
expect(dependencies.execution).toBe(f.execution);
return new CounterStrategy(dependencies.execution, config);
}
);
expect(created).toBe(0);
const manager = new StrategyManager(f.services, registry);
cleanup.push(() => manager.shutdown());
await manager.initializeStrategies([{ ...recoveryConfig, name: ' Custom-Alias ' }]);
await manager.onMarketData(quote('first'));
expect((manager.getStrategy('counter') as CounterStrategy).count).toBe(1);
await manager.shutdown();
const restarted = new StrategyManager(f.services, registry);
cleanup.push(() => restarted.shutdown());
await restarted.restoreStrategies();
expect(created).toBe(2);
expect((restarted.getStrategy('counter') as CounterStrategy).count).toBe(1);
await restarted.onMarketData(quote('second'));
expect((restarted.getStrategy('counter') as CounterStrategy).count).toBe(2);
});
test('aliases are normalized and registration conflicts fail atomically', async () => {
const f = await fixture();
const registry = new StrategyRegistry().register(
['fixture'],
config => new CounterStrategy(f.execution, config)
);
const factory = () => new CounterStrategy(f.execution);
expect(() => registry.register(['new', 'FIXTURE'], factory)).toThrow('already registered');
await expect(
registry.create({ ...recoveryConfig, name: 'new' }, f.dependencies)
).rejects.toThrow('Unknown strategy');
for (const aliases of [[], [''], [' '], ['duplicate', 'DUPLICATE']]) {
expect(() => registry.register(aliases, factory)).toThrow('nonempty and distinct');
}
expect(
(await registry.create({ ...recoveryConfig, name: ' FIXTURE ' }, f.dependencies)).getConfig()
.id
).toBe('counter');
});
test('built-in aliases keep their implementations and unknown names fail closed', async () => {
const f = await fixture();
const registry = createBuiltinStrategyRegistry();
for (const name of ['meanreversion', 'mean-reversion']) {
expect(
(await registry.create({ ...recoveryConfig, name }, f.dependencies)).getCheckpointVersion()
).toBe('mean-reversion/v1');
}
for (const name of ['smacrossover', 'sma-crossover', 'moving-average']) {
expect(
(await registry.create({ ...recoveryConfig, name }, f.dependencies)).getCheckpointVersion()
).toBe('sma-crossover-fixed/v1');
}
for (const name of ['mlenhanced', 'ml-enhanced']) {
expect(
(await registry.create({ ...recoveryConfig, name }, f.dependencies)).getCheckpointVersion()
).toBeUndefined();
}
await expect(
registry.create({ ...recoveryConfig, name: 'missing' }, f.dependencies)
).rejects.toThrow('Unknown strategy: missing');
});
test('factory failures propagate before an invalid strategy can be activated', async () => {
const f = await fixture();
const registry = new StrategyRegistry().register(['fixture'], async () => {
throw new Error('factory failed');
});
const manager = new StrategyManager(f.services, registry);
cleanup.push(() => manager.shutdown());
await expect(manager.initializeStrategies([recoveryConfig])).rejects.toThrow('factory failed');
expect(manager.getActiveStrategies()).toEqual([]);
expect(await f.execution.registeredStrategies()).toEqual([]);
});
});

View file

@ -30,6 +30,12 @@ async function fixture() {
);
await pool.query(sql);
await pool.query(sql);
await pool.query(
readFileSync(
new URL('../../database/postgres/init/13-strategy-recovery.sql', import.meta.url),
'utf8'
)
);
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
logger

View file

@ -0,0 +1,369 @@
import { fork } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, test } from 'bun:test';
import { Pool } from 'pg';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository';
import type { ExecutionRepository } from '../../apps/stock/orchestrator/src/execution/repository';
import { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService';
import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService';
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { logger, makeExecution, quote, start } from '../fixtures/execution';
import { attachCounter, CounterStrategy, recoveryConfig } from '../fixtures/strategy-recovery';
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
async function fixture() {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Dedicated safety database required');
}
const schema = 'stock_bot_safety_' + randomUUID().replaceAll('-', '');
const admin = new Pool({ connectionString: url });
await admin.query('CREATE SCHEMA ' + schema);
const pool = new Pool({ connectionString: url, options: '-c search_path=' + schema });
cleanup.push(async () => {
await pool.end();
await admin.query('DROP SCHEMA ' + schema + ' CASCADE');
await admin.end();
});
for (const migration of ['11-simulation-execution-ledger.sql', '13-strategy-recovery.sql']) {
await pool.query(
readFileSync(new URL('../../database/postgres/init/' + migration, import.meta.url), 'utf8')
);
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
let now = start + 100;
const make = async (
accountId = 'fixture',
repository: ExecutionRepository = new PostgresExecutionRepository(postgres)
) => {
const runtime = makeExecution(repository, () => now);
await runtime.execution.initialize(
{
mode: 'paper',
accountId,
startingCapital: 10000,
commission: 0.001,
slippage: 0,
maxQuoteAgeMs: 1000,
},
runtime.engine
);
cleanup.push(() => runtime.execution.shutdown());
return runtime;
};
return {
pool,
postgres,
schema,
make,
setTime: (time: number) => {
now = time;
},
getTime: () => now,
};
}
describe.skipIf(!url)('strategy recovery on real PostgreSQL', () => {
test('paper mode restores registered strategies and drains their inbox before starting the feed', async () => {
const f = await fixture();
const original = await f.make();
const config = {
...recoveryConfig,
id: 'sma',
name: 'sma-crossover',
parameters: { initialCapital: 10000 },
};
const prior = new StrategyManager({
logger,
custom: {
ExecutionService: original.execution,
ModeManager: { getTradingEngine: () => original.engine } as ModeManager,
},
});
await prior.initializeStrategies([config]);
await prior.onMarketData(quote('one'));
await prior.shutdown();
await original.execution.enqueueMarketData(quote('two', 100, 100, start + 1));
const services: OrchestratorServices = { logger, postgres: f.postgres, custom: {} };
const storage = new StorageService(services, null, f.postgres, null);
const execution = new ExecutionService(services, storage, { clock: f.getTime });
let feedStarted = false;
class OfflineMarket extends MarketDataService {
override async initialize() {
feedStarted = true;
expect((await execution.getRecoveryStatus()).pendingInputs).toBe(false);
expect((await execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0);
}
}
const market = new OfflineMarket(services);
const manager = new StrategyManager(services),
mode = new ModeManager(services, market, execution, storage);
Object.assign(services.custom!, {
StorageService: storage,
ExecutionService: execution,
MarketDataService: market,
StrategyManager: manager,
ModeManager: mode,
});
cleanup.push(() => mode.shutdown());
await mode.initializeMode({
mode: 'paper',
accountId: 'fixture',
startingCapital: 10000,
commission: 0.001,
slippage: 0,
maxQuoteAgeMs: 1000,
});
expect(feedStarted).toBe(true);
expect(manager.getActiveStrategies()).toEqual(['sma']);
});
test.each(['decision', 'checkpoint', 'dispatch'] as const)(
'hard kill at %s resumes without skipped decisions or duplicate fills',
async phase => {
const f = await fixture();
const { execution } = await f.make();
const initial = await attachCounter(execution);
await initial.manager.shutdown();
await execution.enqueueMarketData(quote('one'));
const child = fork(
fileURLToPath(new URL('../fixtures/strategy-crash-owner.ts', import.meta.url)),
[],
{
execPath: process.execPath,
execArgv: [],
stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
env: { ...process.env, STRATEGY_FIXTURE_SCHEMA: f.schema, STRATEGY_FIXTURE_PHASE: phase },
}
);
const exited = new Promise<void>(resolve => child.once('exit', () => resolve()));
cleanup.push(async () => {
child.kill('SIGKILL');
await exited;
});
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error('Crash fixture boundary timeout')), 5000);
child.once('message', message => {
clearTimeout(timeout);
if ((message as { phase: string }).phase === phase) {
resolve();
} else {
reject(new Error('Wrong crash boundary'));
}
});
child.once('exit', () => {
clearTimeout(timeout);
reject(new Error('Crash fixture exited before its boundary'));
});
});
child.kill('SIGKILL');
await exited;
const restarted = await f.make();
const resumed = await attachCounter(restarted.execution);
cleanup.push(() => resumed.manager.shutdown());
expect(resumed.strategy.count).toBe(1);
expect(resumed.strategy.getPosition('A')).toBe(1);
expect(resumed.strategy.getPerformance().trades).toBe(1);
expect((await f.pool.query('SELECT * FROM simulation_orders')).rows).toHaveLength(1);
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1);
await resumed.manager.onMarketData(quote('one'));
expect(resumed.strategy.count).toBe(1);
expect((await restarted.execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0);
}
);
test('checkpoint and order-intent SQL writes roll back together on an injected trigger failure', async () => {
const f = await fixture();
const { execution } = await f.make();
const { manager, strategy } = await attachCounter(execution);
cleanup.push(() => manager.shutdown());
await f.pool
.query(`CREATE FUNCTION reject_intent() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected intent failure'; END $$;
CREATE TRIGGER reject_intent BEFORE INSERT ON simulation_strategy_intents FOR EACH ROW EXECUTE FUNCTION reject_intent()`);
await expect(manager.onMarketData(quote('one'))).rejects.toThrow('intent failure');
expect(strategy.count).toBe(0);
expect(
(await f.pool.query('SELECT payload FROM simulation_strategy_checkpoints')).rows[0].payload
.cursor
).toBe(0);
expect((await f.pool.query('SELECT * FROM simulation_strategy_intents')).rows).toHaveLength(0);
await f.pool.query('DROP TRIGGER reject_intent ON simulation_strategy_intents');
await manager.recover();
expect(strategy.count).toBe(1);
expect(strategy.getPosition('A')).toBe(1);
});
test('input admission survives a rollback before quote application and journal creation', async () => {
const f = await fixture();
const { execution } = await f.make();
const { manager } = await attachCounter(execution);
cleanup.push(() => manager.shutdown());
await f.pool
.query(`CREATE FUNCTION reject_input_apply() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected application failure'; END $$;
CREATE TRIGGER reject_input_apply BEFORE UPDATE ON simulation_market_inputs FOR EACH ROW EXECUTE FUNCTION reject_input_apply()`);
await expect(manager.onMarketData(quote('one'))).rejects.toThrow('application failure');
expect((await execution.getAccount()).quotes.A).toBeUndefined();
expect((await f.pool.query('SELECT * FROM simulation_strategy_journal')).rows).toHaveLength(0);
expect((await execution.getRecoveryStatus()).pendingInputs).toBe(true);
await manager.shutdown();
await f.pool.query('DROP TRIGGER reject_input_apply ON simulation_market_inputs');
const restarted = await f.make();
const resumed = await attachCounter(restarted.execution);
cleanup.push(() => resumed.manager.shutdown());
expect(resumed.strategy.count).toBe(1);
expect(resumed.strategy.getPosition('A')).toBe(1);
});
test('competing owners restore the locked checkpoint before every decision and consume one intent', async () => {
const f = await fixture();
const one = await f.make(),
two = await f.make();
const first = await attachCounter(one.execution),
second = await attachCounter(two.execution);
cleanup.push(
() => first.manager.shutdown(),
() => second.manager.shutdown()
);
await one.execution.enqueueMarketData(quote('one'));
await Promise.all([first.manager.recover(), second.manager.recover()]);
await Promise.all([first.manager.recover(), second.manager.recover()]);
expect(first.strategy.count).toBe(1);
expect(second.strategy.count).toBe(1);
expect(first.strategy.getPosition('A')).toBe(1);
expect(second.strategy.getPosition('A')).toBe(1);
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1);
});
test('stale admitted inputs restore indicators but never fabricate stale paper fills', async () => {
const f = await fixture();
const { execution } = await f.make();
const { manager, strategy } = await attachCounter(execution);
cleanup.push(() => manager.shutdown());
await execution.enqueueMarketData(quote('one'));
f.setTime(start + 5000);
await manager.recover();
expect(strategy.count).toBe(1);
expect(strategy.getPosition('A')).toBe(0);
const orders = (await f.pool.query('SELECT payload FROM simulation_orders')).rows;
expect(orders[0].payload.report.status).toBe('rejected');
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(0);
});
test('real SMA indicator checkpoints reproduce an uninterrupted run across process replacement', async () => {
const f = await fixture();
const smaConfig = {
...recoveryConfig,
id: 'sma',
name: 'sma-crossover',
parameters: { initialCapital: 10000 },
};
const makeManager = async (account: string) => {
const runtime = await f.make(account);
const services = {
logger,
custom: {
ExecutionService: runtime.execution,
ModeManager: { getTradingEngine: () => runtime.engine } as ModeManager,
},
};
const manager = new StrategyManager(services);
await manager.initializeStrategies([smaConfig]);
cleanup.push(() => manager.shutdown());
return { ...runtime, manager };
};
const bars = Array.from({ length: 45 }, (_, index) => {
const price = 100 + Math.sin(index / 3) * 8;
return {
type: 'bar' as const,
eventId: 'bar-' + index,
data: {
symbol: 'A',
timestamp: start + index * 86400000,
open: price,
high: price + 1,
low: price - 1,
close: price,
volume: 100000,
},
};
});
const baseline = await makeManager('baseline');
for (const bar of bars) {
f.setTime(bar.data.timestamp);
await baseline.manager.onMarketData(bar);
}
f.setTime(start);
const interrupted = await makeManager('interrupted');
for (const bar of bars.slice(0, 22)) {
f.setTime(bar.data.timestamp);
await interrupted.manager.onMarketData(bar);
}
await interrupted.manager.shutdown();
const restarted = await makeManager('interrupted');
for (const bar of bars.slice(22)) {
f.setTime(bar.data.timestamp);
await restarted.manager.onMarketData(bar);
}
const meaningfulState = (manager: StrategyManager) => {
const {
seenFills: _seenFills,
pendingOrders: _pendingOrders,
...state
} = manager.getStrategy('sma')!.captureCheckpoint() as Record<string, unknown>;
return state;
};
expect(meaningfulState(restarted.manager)).toEqual(meaningfulState(baseline.manager));
expect((await restarted.execution.getAccount()).cash).toBe(
(await baseline.execution.getAccount()).cash
);
expect(
(await f.pool.query("SELECT * FROM simulation_fills WHERE account_id = 'baseline'")).rows
.length
).toBeGreaterThan(0);
});
test('uncheckpointed ML paper strategies fail before model startup and migration replay preserves history', async () => {
const f = await fixture();
const { execution, engine } = await f.make();
const manager = new StrategyManager({
logger,
custom: {
ExecutionService: execution,
ModeManager: { getTradingEngine: () => engine } as ModeManager,
},
});
cleanup.push(() => manager.shutdown());
await expect(
manager.initializeStrategies([{ ...recoveryConfig, name: 'ml-enhanced' }])
).rejects.toThrow('versioned checkpoint');
expect((await f.pool.query('SELECT * FROM simulation_strategy_checkpoints')).rows).toHaveLength(
0
);
const active = await attachCounter(execution);
cleanup.push(() => active.manager.shutdown());
await active.manager.onMarketData(quote('one'));
await f.pool.query(
readFileSync(
new URL('../../database/postgres/init/13-strategy-recovery.sql', import.meta.url),
'utf8'
)
);
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1);
expect((await execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0);
});
});