import { createHash } from 'node:crypto'; import Decimal from 'decimal.js-light'; import { defined } from '@stock-bot/invariants'; import type { MarketData, OrderRequest } from '../types'; export interface RiskLimits { maxPositionSize: number; maxOrderSize: number; maxDailyLoss: number; maxGrossExposure: number; maxSymbolExposure: number; } export const defaultRiskLimits: RiskLimits = { maxPositionSize: 10000, maxOrderSize: 1000, maxDailyLoss: 5000, maxGrossExposure: 200000, maxSymbolExposure: 50000, }; export interface Fill { id: string; price: number; quantity: number; commission: number; timestamp: number; pnl: number; } export interface ExecutionReport { orderId: string; clientOrderId: string; symbol: string; side: 'buy' | 'sell'; quantity: number; status: 'pending' | 'accepted' | 'partiallyFilled' | 'filled' | 'cancelled' | 'rejected'; fills: Fill[]; rejectionReason?: string; 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; averagePrice: number; realizedPnl: number; } export interface Quote { bid: number; ask: number; bidSize: number; askSize: number; timestamp: number; eventId: string; } export interface Account { /** Account-row-locked journal sequence, safe integer checked before increment. */ strategySequence?: number; inputSequence?: number; admittedTimes?: Record; initialCapital: number; cash: number; realizedPnl: number; dailyPnl: number; day: string; commission: number; slippage: number; limits: RiskLimits; maxQuoteAgeMs: number; positions: Record; quotes: Record; strategyPositions: Record>; } export interface StoredOrder { request: OrderRequest; report: ExecutionReport; fingerprint: string; policy: { commission: number; slippage: number }; } export const terminal = (status: ExecutionReport['status']) => ['filled', 'cancelled', 'rejected'].includes(status); type DecimalValue = ConstructorParameters[0]; export const decimal = (value: DecimalValue) => new Decimal(value); export function amount(value: DecimalValue) { const result = decimal(value).toDecimalPlaces(8).toNumber(); if (!Number.isFinite(result)) { throw new Error('Non-finite accounting value'); } return result; } export function identity(data: MarketData): string { return data.eventId ?? createHash('sha256').update(JSON.stringify(data)).digest('hex'); } export function fingerprint(order: OrderRequest, strategyId?: string) { return JSON.stringify([ order.symbol, order.side, order.quantity, order.orderType, order.limitPrice ?? null, order.stopPrice ?? null, order.timeInForce, strategyId ?? null, ]); } export function applyFill( account: Account, symbol: string, side: 'buy' | 'sell', fill: Omit ): Fill { const old = account.positions[symbol] ?? { symbol, quantity: 0, averagePrice: 0, realizedPnl: 0 }; const signed = decimal(fill.quantity).times(side === 'buy' ? 1 : -1); const next = decimal(old.quantity).plus(signed); const closes = old.quantity !== 0 && Math.sign(old.quantity) !== Math.sign(signed.toNumber()); const closed = closes ? Math.min(Math.abs(old.quantity), fill.quantity) : 0; const pnl = amount( decimal(fill.price) .minus(old.averagePrice) .times(closed) .times(Math.sign(old.quantity)) .minus(fill.commission) ); let averagePrice = old.averagePrice; if (next.isZero()) { averagePrice = 0; } else if (!closes) { averagePrice = amount( decimal(old.averagePrice) .times(Math.abs(old.quantity)) .plus(decimal(fill.price).times(fill.quantity)) .div(next.abs()) ); } else if (Math.sign(next.toNumber()) !== Math.sign(old.quantity)) { averagePrice = fill.price; } account.positions[symbol] = { symbol, quantity: amount(next), averagePrice, realizedPnl: amount(decimal(old.realizedPnl).plus(pnl)), }; account.cash = amount( decimal(account.cash).minus(signed.times(fill.price)).minus(fill.commission) ); account.realizedPnl = amount(decimal(account.realizedPnl).plus(pnl)); account.dailyPnl = amount(decimal(account.dailyPnl).plus(pnl)); return { ...fill, pnl }; } export function accountMetrics(account: Account) { let marketValue = decimal(0), grossExposure = decimal(0), unrealized = decimal(0); for (const position of Object.values(account.positions)) { const quote = account.quotes[position.symbol]; const mark = quote ? (quote.bid + quote.ask) / 2 : position.averagePrice; marketValue = marketValue.plus(decimal(position.quantity).times(mark)); grossExposure = grossExposure.plus(decimal(position.quantity).abs().times(mark)); unrealized = unrealized.plus( decimal(mark).minus(position.averagePrice).times(position.quantity) ); } return { cash: account.cash, realizedPnl: account.realizedPnl, unrealizedPnl: amount(unrealized), equity: amount(decimal(account.cash).plus(marketValue)), grossExposure: amount(grossExposure), dailyPnl: account.dailyPnl, }; } /** The same stored pricing policy values both fills and their unpaid commissions. */ export function 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 ); } /** Quantities are shares; exposure/loss limits are account-currency notional amounts. */ export function riskViolations( account: Account, request: OrderRequest, reservations: StoredOrder[], price: number, timestamp: number, commission: number ): string[] { const violations: string[] = []; if (request.quantity > account.limits.maxOrderSize) { violations.push('Order quantity limit'); } const current = account.positions[request.symbol]?.quantity ?? 0; const signed = request.side === 'buy' ? request.quantity : -request.quantity; const reducing = current * signed < 0 && Math.abs(signed) <= Math.abs(current); if (account.dailyPnl <= -account.limits.maxDailyLoss && !reducing) { violations.push('Daily loss limit'); } const quantities = new Map(); for (const p of Object.values(account.positions)) { quantities.set(p.symbol, { long: p.quantity, short: p.quantity }); } const proposed = current + signed; quantities.set(request.symbol, { long: proposed, short: proposed }); // Paid fees already reduce equity. Reserve only the remaining, unpaid liability. let unpaidFees = decimal(amount(decimal(request.quantity).times(price).times(commission))); for (const order of reservations) { if (terminal(order.report.status)) { continue; } const qty = amount( decimal(order.request.quantity).minus(order.report.fills.reduce((n, f) => n + f.quantity, 0)) ); const quote = account.quotes[order.request.symbol]; if (quote) { unpaidFees = unpaidFees.plus( amount(decimal(qty).times(fillPrice(order, quote)).times(order.policy.commission)) ); } const q = quantities.get(order.request.symbol) ?? { long: 0, short: 0 }; if (order.request.side === 'buy') { q.long = amount(decimal(q.long).plus(qty)); } else { q.short = amount(decimal(q.short).minus(qty)); } quantities.set(order.request.symbol, q); } let gross = decimal(0); for (const [symbol, q] of quantities) { const quantity = Math.max(Math.abs(q.long), Math.abs(q.short)); if (!quantity) { continue; } const quote = account.quotes[symbol]; if (quote && timestamp - quote.timestamp > account.maxQuoteAgeMs && !reducing) { violations.push(`Stale valuation for ${symbol}`); } const mark = symbol === request.symbol ? Math.max(price, quote?.ask ?? price) : quote?.ask; if (!mark || !Number.isFinite(mark)) { violations.push(`Missing valuation for ${symbol}`); continue; } const exposure = decimal(quantity).times(mark); if (quantity > account.limits.maxPositionSize && !(reducing && symbol === request.symbol)) { violations.push(`Position quantity limit: ${symbol}`); } if (exposure.gt(account.limits.maxSymbolExposure) && !(reducing && symbol === request.symbol)) { violations.push(`Symbol notional limit: ${symbol}`); } gross = gross.plus(exposure); } if (gross.gt(account.limits.maxGrossExposure) && !reducing) { violations.push('Gross notional limit'); } if (gross.plus(unpaidFees).gt(Math.max(0, accountMetrics(account).equity)) && !reducing) { violations.push('Unlevered capital exposure limit'); } return violations; }