215 lines
7.2 KiB
TypeScript
215 lines
7.2 KiB
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import { defined } from '@stock-bot/invariants';
|
|
import type { OrderRequest } from '../types';
|
|
import {
|
|
amount,
|
|
applyFill,
|
|
decimal,
|
|
fillPrice,
|
|
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 ? fillPrice(order, quote) : 0;
|
|
const violations = invalid
|
|
? [invalid]
|
|
: riskViolations(
|
|
tx.account,
|
|
request,
|
|
await tx.openOrders(),
|
|
price,
|
|
timestamp,
|
|
order.policy.commission
|
|
);
|
|
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;
|
|
}
|
|
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 = 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),
|
|
order.policy.commission
|
|
);
|
|
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];
|
|
}
|
|
}
|