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

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']);