427 lines
15 KiB
TypeScript
427 lines
15 KiB
TypeScript
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,
|
|
decimal,
|
|
defaultRiskLimits,
|
|
identity,
|
|
terminal,
|
|
type Account,
|
|
type ExecutionChange,
|
|
type ExecutionReport,
|
|
type Fill,
|
|
type Quote,
|
|
} from '../execution/model';
|
|
import { PostgresExecutionRepository } from '../execution/PostgresExecutionRepository';
|
|
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,
|
|
OrderRequestSchema,
|
|
type MarketData,
|
|
type ModeConfig,
|
|
type OrchestratorServices,
|
|
type OrderRequest,
|
|
} from '../types';
|
|
import type { StorageService } from './StorageService';
|
|
|
|
export type { ExecutionReport, Fill } from '../execution/model';
|
|
export type StrategyOrderUpdate = ExecutionReport;
|
|
export interface StrategyFill extends Fill {
|
|
orderId: string;
|
|
symbol: string;
|
|
side: 'buy' | 'sell';
|
|
strategyId?: string;
|
|
positionUpdate?: unknown;
|
|
}
|
|
export class UnsupportedExecutionError extends Error {}
|
|
|
|
/** Sole runtime order gateway. Paper state commits atomically; backtests opt into a run-local ledger. */
|
|
export class ExecutionService extends EventEmitter {
|
|
private repository?: ExecutionRepository;
|
|
private accountId = '';
|
|
private mode: 'paper' | 'backtest' | undefined;
|
|
private engine?: TradingEngine;
|
|
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>) {
|
|
this.observer = observer;
|
|
}
|
|
async initialize(input: ModeConfig, engine: TradingEngine): Promise<void> {
|
|
const config = ModeConfigSchema.parse(input);
|
|
if (config.mode === 'live') {
|
|
throw new UnsupportedExecutionError(
|
|
'Live trading is disabled: no real broker adapter exists'
|
|
);
|
|
}
|
|
await this.tail;
|
|
this.closing = false;
|
|
this.mode = undefined;
|
|
const repository =
|
|
this.options.repository ??
|
|
(config.mode === 'backtest'
|
|
? new BacktestExecutionRepository()
|
|
: this.container.postgres
|
|
? new PostgresExecutionRepository(this.container.postgres)
|
|
: undefined);
|
|
if (!repository) {
|
|
throw new UnsupportedExecutionError(
|
|
'Paper execution requires the PostgreSQL simulation ledger'
|
|
);
|
|
}
|
|
if (config.mode === 'paper' && repository instanceof BacktestExecutionRepository) {
|
|
throw new UnsupportedExecutionError('Run-local storage cannot back a paper account');
|
|
}
|
|
const now = this.options.clock?.() ?? Date.now();
|
|
const initialCapital = config.mode === 'paper' ? config.startingCapital : config.initialCapital;
|
|
const account: Account = {
|
|
initialCapital,
|
|
cash: initialCapital,
|
|
realizedPnl: 0,
|
|
dailyPnl: 0,
|
|
day: new Date(now).toISOString().slice(0, 10),
|
|
commission: config.commission ?? 0.001,
|
|
slippage: config.slippage ?? 0.0001,
|
|
limits: config.riskLimits ?? { ...defaultRiskLimits },
|
|
maxQuoteAgeMs:
|
|
config.mode === 'paper' ? (config.maxQuoteAgeMs ?? 60000) : Number.MAX_SAFE_INTEGER,
|
|
positions: {},
|
|
quotes: {},
|
|
strategyPositions: {},
|
|
};
|
|
const id =
|
|
config.mode === 'paper'
|
|
? (config.accountId ?? 'paper-default')
|
|
: (config.runId ?? randomUUID());
|
|
await repository.initialize(id, account);
|
|
this.repository = repository;
|
|
this.accountId = id;
|
|
this.mode = config.mode;
|
|
this.engine = engine;
|
|
engine.updateRiskLimits(account.limits);
|
|
}
|
|
private serialized<T>(work: () => Promise<T>): Promise<T> {
|
|
const result = this.tail.then(work);
|
|
this.tail = result.catch(() => {});
|
|
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'
|
|
);
|
|
}
|
|
return this.repository;
|
|
}
|
|
private now(quote?: Quote) {
|
|
return this.mode === 'backtest'
|
|
? (quote?.timestamp ?? 0)
|
|
: (this.options.clock?.() ?? Date.now());
|
|
}
|
|
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 => {
|
|
return this.simulation.acceptOrder(tx, request, context.strategyId);
|
|
});
|
|
await this.publish(change);
|
|
return change.report;
|
|
});
|
|
}
|
|
/** 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(() =>
|
|
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 false;
|
|
}
|
|
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');
|
|
}
|
|
if (this.mode === 'paper' && !this.freshQuote(tx.account, quote)) {
|
|
throw new Error('Stale or future market data');
|
|
}
|
|
const sequence = (tx.account.inputSequence ?? 0) + 1;
|
|
if (!Number.isSafeInteger(sequence)) {
|
|
throw new Error('Market input sequence exhausted');
|
|
}
|
|
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 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 () => {
|
|
const change = await this.store().transact(this.accountId, async tx => {
|
|
const order = await tx.getOrder(id);
|
|
if (!order || terminal(order.report.status)) {
|
|
return undefined;
|
|
}
|
|
order.report.status = 'cancelled';
|
|
await tx.putOrder(order);
|
|
const change = { report: order.report, fills: [] };
|
|
await this.simulation.journalChange(tx, change);
|
|
return change;
|
|
});
|
|
if (change) {
|
|
await this.publish(change);
|
|
}
|
|
return !!change;
|
|
});
|
|
}
|
|
async getOrderStatus(id: string) {
|
|
return this.store().transact(
|
|
this.accountId,
|
|
async tx => (await tx.getOrder(id))?.report ?? null
|
|
);
|
|
}
|
|
async getAccount() {
|
|
const decisionAccount = this.recovery.decisionAccount();
|
|
if (decisionAccount) {
|
|
return decisionAccount;
|
|
}
|
|
return this.store().transact(this.accountId, async tx => ({
|
|
...tx.account,
|
|
...accountMetrics(tx.account),
|
|
}));
|
|
}
|
|
async getStrategySnapshot(id: string) {
|
|
return this.store().transact(this.accountId, async tx => ({
|
|
positions: tx.account.strategyPositions[id] ?? {},
|
|
orders: (await tx.openOrders()).filter(o => o.report.strategyId === id),
|
|
}));
|
|
}
|
|
async getPositions() {
|
|
const account = await this.getAccount();
|
|
return Object.values(account.positions).map(p => ({
|
|
...p,
|
|
unrealizedPnl: amount(
|
|
decimal(
|
|
account.quotes[p.symbol]
|
|
? (defined(account.quotes[p.symbol]).bid + defined(account.quotes[p.symbol]).ask) / 2
|
|
: p.averagePrice
|
|
)
|
|
.minus(p.averagePrice)
|
|
.times(p.quantity)
|
|
),
|
|
}));
|
|
}
|
|
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,
|
|
symbol: change.report.symbol,
|
|
side: change.report.side,
|
|
strategyId: change.report.strategyId,
|
|
}));
|
|
// Native analytics is a run-local projection only. Paper positions always read the SQL ledger.
|
|
if (this.mode === 'backtest') {
|
|
for (const fill of fills) {
|
|
defined(this.engine).advanceTime(fill.timestamp);
|
|
defined(this.engine).processFillWithMetadata(
|
|
fill.symbol,
|
|
fill.price,
|
|
fill.quantity,
|
|
fill.side,
|
|
fill.commission,
|
|
fill.orderId,
|
|
fill.strategyId ?? null
|
|
);
|
|
}
|
|
}
|
|
try {
|
|
await this.observer?.(change.report, fills);
|
|
this.emit('orderUpdate', change.report);
|
|
for (const fill of fills) {
|
|
this.emit('fill', fill);
|
|
}
|
|
} catch (error) {
|
|
this.container.logger.error('Execution observer failed after commit', { error });
|
|
}
|
|
}
|
|
async routeOrderToExchange(_order: OrderRequest, _exchange: string): Promise<void> {
|
|
throw new UnsupportedExecutionError('Exchange/broker routing is disabled');
|
|
}
|
|
async shutdown() {
|
|
this.closing = true;
|
|
await this.tail;
|
|
this.mode = undefined;
|
|
this.engine = undefined;
|
|
}
|
|
}
|