Refactor execution boundaries and add durable strategy recovery
This commit is contained in:
parent
d6b09eb635
commit
694c48bbdb
36 changed files with 3077 additions and 491 deletions
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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',
|
||||
|
|
|
|||
219
apps/stock/orchestrator/src/execution/SimulationExecution.ts
Normal file
219
apps/stock/orchestrator/src/execution/SimulationExecution.ts
Normal 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];
|
||||
}
|
||||
}
|
||||
288
apps/stock/orchestrator/src/execution/StrategyRecovery.ts
Normal file
288
apps/stock/orchestrator/src/execution/StrategyRecovery.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
70
apps/stock/orchestrator/src/execution/strategy-recovery.ts
Normal file
70
apps/stock/orchestrator/src/execution/strategy-recovery.ts
Normal 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>;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue