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

@ -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);