refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack

- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched)
- Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations()
- Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation
- Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims
- Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution
- Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
This commit is contained in:
Boki 2026-11-27 00:11:50 -05:00
parent ce9e2df67c
commit 4cd6038063
432 changed files with 1247 additions and 44469 deletions

View file

@ -1,294 +0,0 @@
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;
}
}

View file

@ -10,9 +10,9 @@ import {
type CanonicalExecutionIdentity,
type CanonicalMatchingConfig,
type FinancialTransactionRequest,
} from '../contracts/canonical-execution';
import type { StrategyProgram } from '../contracts/canonical-strategy';
import { nativeAdmissionOrders, type DecisionContext } from '../contracts/native-replay';
} from '@stock-bot/stock-config/canonical-execution';
import type { StrategyProgram } from '@stock-bot/research/strategy-api';
import { nativeAdmissionOrders, type DecisionContext } from '@stock-bot/stock-config/canonical-replay';
import {
freeze,
increment,
@ -34,7 +34,7 @@ import {
type CanonicalPaperInput,
type CanonicalTransaction,
} from './canonical-paper';
import { ExecutionConflictError } from './repository';
import { ExecutionConflictError } from './canonical-paper';
const callback = new AsyncLocalStorage<boolean>();
function outsideCallback() {

View file

@ -12,7 +12,7 @@ import {
type CanonicalPostgres,
type CanonicalTransaction,
} from './canonical-paper';
import { ExecutionConflictError } from './repository';
import { ExecutionConflictError } from './canonical-paper';
function accountState(raw: unknown): CanonicalAccount {
const result = canonicalAccountSchema.safeParse(raw);

View file

@ -1,213 +0,0 @@
import type { PostgresClient } from '@stock-bot/services';
import { refuseCanonicalAccount } from './canonical-paper';
import type { Account, Fill, StoredOrder } from './model';
import {
ExecutionConflictError,
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'>) {}
async initialize(id: string, initial: Account) {
await this.postgres.transaction(async client => {
await client.query(
`INSERT INTO simulation_accounts (id, state) VALUES ($1,$2::jsonb) ON CONFLICT (id) DO NOTHING`,
[id, JSON.stringify(initial)]
);
const result = await client.query(
'SELECT state FROM simulation_accounts WHERE id = $1 FOR UPDATE',
[id]
);
refuseCanonicalAccount(result.rows[0].state);
const account: Account = result.rows[0].state;
if (account.initialCapital !== initial.initialCapital) {
throw new ExecutionConflictError(
'Existing account capital differs; use a new account ID, not an implicit reset'
);
}
Object.assign(account, {
limits: initial.limits,
commission: initial.commission,
slippage: initial.slippage,
maxQuoteAgeMs: initial.maxQuoteAgeMs,
});
await client.query('UPDATE simulation_accounts SET state = $2::jsonb WHERE id = $1', [
id,
JSON.stringify(account),
]);
});
}
transact<T>(id: string, work: (tx: ExecutionTransaction) => Promise<T>): Promise<T> {
return this.postgres.transaction(async client => {
const state = await client.query(
'SELECT state FROM simulation_accounts WHERE id = $1 FOR UPDATE',
[id]
);
if (!state.rows[0]) {
throw new Error('Execution account is not initialized');
}
refuseCanonicalAccount(state.rows[0].state);
const readOrder = async (column: 'id' | 'client_order_id', key: string) => {
const result = await client.query(
`SELECT payload FROM simulation_orders WHERE account_id = $1 AND ${column} = $2`,
[id, key]
);
return result.rows[0]?.payload as StoredOrder | undefined;
};
const result = await work({
account: state.rows[0].state as Account,
findOrder: key => readOrder('client_order_id', key),
getOrder: key => readOrder('id', key),
async openOrders() {
const result = await client.query(
`SELECT payload FROM simulation_orders WHERE account_id = $1 AND status IN ('accepted','partiallyFilled') ORDER BY created_at,id`,
[id]
);
return result.rows.map(r => r.payload as StoredOrder);
},
async putOrder(order) {
await client.query(
`INSERT INTO simulation_orders (id,account_id,client_order_id,status,payload)
VALUES ($1,$2,$3,$4,$5::jsonb) ON CONFLICT (id) DO UPDATE SET status = EXCLUDED.status,payload = EXCLUDED.payload`,
[
order.report.orderId,
id,
order.report.clientOrderId,
order.report.status,
JSON.stringify(order),
]
);
},
async insertFill(orderId: string, fill: Fill) {
const inserted = await client.query(
`INSERT INTO simulation_fills (account_id,id,order_id,payload)
VALUES ($1,$2,$3,$4::jsonb) ON CONFLICT (account_id,id) DO NOTHING RETURNING id`,
[id, fill.id, orderId, JSON.stringify(fill)]
);
return inserted.rows.length > 0;
},
async recordEvent(eventId, hash) {
const inserted = await client.query(
`INSERT INTO simulation_events (account_id,id,fingerprint)
VALUES ($1,$2,$3) ON CONFLICT (account_id,id) DO NOTHING RETURNING id`,
[id, eventId, hash]
);
if (inserted.rows.length) {
return true;
}
const previous = await client.query(
'SELECT fingerprint FROM simulation_events WHERE account_id = $1 AND id = $2',
[id, eventId]
);
if (previous.rows[0]?.fingerprint !== hash) {
throw new ExecutionConflictError('Conflicting market event identity');
}
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',
[id, JSON.stringify(state.rows[0].state)]
);
return result;
});
}
}

View file

@ -1,215 +0,0 @@
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];
}
}

View file

@ -1,288 +0,0 @@
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;
}
}
});
}
}

View file

@ -6,13 +6,13 @@ import {
canonicalExecutionCheckpointSchema,
financialTransactionResultSchema,
matchingCommandSchema,
} from '../contracts/canonical-execution';
} from '@stock-bot/stock-config/canonical-execution';
import {
nativeFinancialViewSchema,
nativeManagedOrderSchema,
stepSchema,
} from '../contracts/native-replay';
import { paperConfigurationSchema, paperConnectionSchema } from '../contracts/paper-runtime';
} from '@stock-bot/stock-config/canonical-replay';
import { paperConfigurationSchema, paperConnectionSchema } from '@stock-bot/stock-config/paper-runtime';
import { metadataSchema, stateCopy } from '../strategies/strategy-decision';
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
@ -195,7 +195,8 @@ export interface CanonicalExecutionRepository {
transact<T>(accountId: string, work: (tx: CanonicalTransaction) => Promise<T>): Promise<T>;
}
export type CanonicalPostgres = Pick<PostgresClient, 'transaction'>;
export { compareEventKeys } from '../contracts/canonical-execution';
export class ExecutionConflictError extends Error {}
export { compareEventKeys } from '@stock-bot/stock-config/canonical-execution';
/** Legacy callers must never reinterpret any version of a canonical envelope. */
export function refuseCanonicalAccount(state: unknown): void {
if (state && typeof state === 'object' && 'kind' in state) {

View file

@ -1,268 +0,0 @@
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<string, number>;
initialCapital: number;
cash: number;
realizedPnl: number;
dailyPnl: number;
day: string;
commission: number;
slippage: number;
limits: RiskLimits;
maxQuoteAgeMs: number;
positions: Record<string, Position>;
quotes: Record<string, Quote>;
strategyPositions: Record<string, Record<string, number>>;
}
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<typeof Decimal>[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, 'pnl'>
): 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<string, { long: number; short: number }>();
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;
}

View file

@ -1,31 +0,0 @@
import type { Account, Fill, StoredOrder } from './model';
import type {
MarketInput,
StrategyCheckpoint,
StrategyJournalEvent,
StrategyJournalPayload,
StrategyOrderIntent,
} from './strategy-recovery';
export interface ExecutionTransaction {
account: Account;
findOrder(clientOrderId: string): Promise<StoredOrder | undefined>;
getOrder(orderId: string): Promise<StoredOrder | undefined>;
openOrders(): Promise<StoredOrder[]>;
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 {}

View file

@ -1,49 +0,0 @@
import { createHash } from 'node:crypto';
import { canonicalJson } from '../canonical-json';
import type { MarketData, OrderRequest, StrategyConfig } from '../types';
import type { Account, ExecutionReport, Fill } from './model';
export { canonicalJson } from '../canonical-json';
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>;
}