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 { readonly writes = new Map(); constructor(private readonly base: Map) {} 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 { 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; clients: Map; openOrders: Set; fills: Set; events: Map; journal: StrategyJournalEvent[]; strategies: Map; intents: Map; pendingIntents: Set; inputs: Map; pendingInputs: Set; } 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(ids: Set, table: TransactionMap): Iterable { 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 = Promise.resolve(); async initialize(_id: string, account: Account): Promise { 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(_id: string, work: (tx: ExecutionTransaction) => Promise): Promise { 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(); 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; } }