Unify simulation order execution and persist paper accounting

This commit is contained in:
Boki 2026-10-20 21:35:56 -04:00
parent 7dec0be3b4
commit 63c3856797
37 changed files with 3901 additions and 3043 deletions

55
test/fixtures/execution.ts vendored Normal file
View file

@ -0,0 +1,55 @@
import { TradingEngine } from '@stock-bot/engine';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import type { ExecutionRepository } from '../../apps/stock/orchestrator/src/execution/repository';
import { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService';
import type { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
import {
BacktestConfigSchema,
type MarketData,
type OrderRequest,
} from '../../apps/stock/orchestrator/src/types';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
export const logger = getLogger('execution-test');
export const start = Date.parse('2024-01-01T00:00:00Z');
export const config = BacktestConfigSchema.parse({
mode: 'backtest',
strategy: 'sma-crossover',
symbols: ['A', 'B'],
startDate: new Date(start).toISOString(),
endDate: '2025-01-01T00:00:00Z',
initialCapital: 10000,
dataFrequency: '1d',
commission: 0.001,
slippage: 0,
});
export function quote(
id: string,
price = 100,
size = 100,
timestamp = start,
symbol = 'A'
): MarketData {
return {
type: 'quote',
eventId: id,
data: { symbol, bid: price, ask: price, bidSize: size, askSize: size, timestamp },
};
}
export function order(
clientOrderId: string,
side: 'buy' | 'sell' = 'buy',
quantity = 10
): OrderRequest {
return { symbol: 'A', side, quantity, orderType: 'market', timeInForce: 'DAY', clientOrderId };
}
export function makeExecution(repository?: ExecutionRepository, clock = () => start) {
const engine = new TradingEngine('backtest', {
startTime: start,
endTime: Date.parse(config.endDate),
speedMultiplier: 0,
initialCapital: 10000,
});
const execution = new ExecutionService({ logger }, {} as StorageService, { repository, clock });
return { execution, engine };
}

View file

@ -0,0 +1,240 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { TradingEngine } from '@stock-bot/engine';
import { createOrderRoutes } from '../../apps/stock/orchestrator/src/api/rest/orders';
import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/repository';
import type { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService';
import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService';
import {
BaseStrategy,
type Signal,
} from '../../apps/stock/orchestrator/src/strategies/BaseStrategy';
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
import type { MarketData, OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { config, logger, makeExecution, order, quote, start } from '../fixtures/execution';
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) await close();
});
async function fixture() {
const runtime = makeExecution();
await runtime.execution.initialize(config, runtime.engine);
cleanup.push(() => runtime.execution.shutdown());
return runtime;
}
describe('one simulation execution gateway', () => {
test('identical client IDs return one order/fill; conflicting retries cannot mutate accounting', async () => {
const { execution } = await fixture();
await execution.onMarketData(quote('q1'));
const reports = await Promise.all([
execution.submitOrder(order('id')),
execution.submitOrder(order('id')),
]);
expect(reports[0]).toEqual(reports[1]);
expect(reports[0]!.status).toBe('filled');
expect((await execution.getPositions())[0]?.quantity).toBe(10);
await expect(execution.submitOrder(order('id', 'buy', 11))).rejects.toBeInstanceOf(
ExecutionConflictError
);
expect((await execution.getAccount()).cash).toBe(8999);
});
test('quote liquidity is consumed once; partial fills complete across distinct events only', async () => {
const { execution } = await fixture();
await execution.onMarketData(quote('q1', 100, 3));
const first = await execution.submitOrder(order('partial', 'buy', 10));
expect(first.status).toBe('partiallyFilled');
expect(first.fills[0]?.quantity).toBe(3);
expect(await execution.onMarketData(quote('q1', 100, 3))).toBe(false);
await execution.onMarketData(quote('q2', 100, 4, start + 1));
expect((await execution.getOrderStatus(first.orderId))?.fills.map(f => f.quantity)).toEqual([
3, 4,
]);
await execution.onMarketData(quote('q3', 100, 50, start + 2));
const report = await execution.getOrderStatus(first.orderId);
expect(report?.status).toBe('filled');
expect(report?.fills.map(f => f.quantity)).toEqual([3, 4, 3]);
expect((await execution.getAccount()).cash).toBe(8999);
expect((await execution.getPositions())[0]?.quantity).toBe(10);
});
test('long/short partial closes and reversals conserve equity and charge commission exactly once', async () => {
const { execution, engine } = await fixture();
for (const [i, side, price, quantity] of [
[0, 'buy', 100, 10],
[1, 'sell', 110, 4],
[2, 'sell', 90, 10],
[3, 'buy', 80, 4],
] as const) {
await execution.onMarketData(quote('q' + i, price, 100, start + i));
await execution.submitOrder(order('o' + i, side, quantity));
}
const account = await execution.getAccount();
expect(account.cash).toBeCloseTo(10017.34, 8);
expect(account.equity).toBe(account.cash);
expect(account.realizedPnl).toBeCloseTo(17.34, 8);
expect(account.dailyPnl).toBe(account.realizedPnl);
expect(account.positions.A?.quantity).toBe(0);
expect(account.positions.A?.averagePrice).toBe(0);
const [native] = engine.getTotalPnl();
expect(native).toBeCloseTo(account.realizedPnl, 8);
});
test('pending reservations and projected notional enforce limits across symbols', async () => {
const { execution, engine } = await fixture();
await execution.initialize(
{
...config,
riskLimits: {
maxOrderSize: 100,
maxPositionSize: 100,
maxDailyLoss: 100,
maxSymbolExposure: 800,
maxGrossExposure: 1000,
},
},
engine
);
await execution.onMarketData(quote('a', 100, 0));
await execution.onMarketData(quote('b', 100, 0, start, 'B'));
expect((await execution.submitOrder(order('pending', 'buy', 6))).status).toBe('accepted');
expect((await execution.submitOrder(order('over', 'buy', 3))).status).toBe('rejected');
const other = { ...order('b', 'buy', 5), symbol: 'B' };
expect((await execution.submitOrder(other)).status).toBe('rejected');
expect(await execution.getPositions()).toHaveLength(0);
});
test('IOC/FOK and limits have truthful states; cancellations cannot cancel an already filled order', async () => {
const { execution } = await fixture();
await execution.onMarketData(quote('q', 100, 3));
const fok = await execution.submitOrder({ ...order('fok'), timeInForce: 'FOK' });
expect(fok.status).toBe('cancelled');
expect(fok.fills).toHaveLength(0);
const ioc = await execution.submitOrder({ ...order('ioc'), timeInForce: 'IOC' });
expect(ioc.status).toBe('cancelled');
expect(ioc.fills[0]?.quantity).toBe(3);
const limit = await execution.submitOrder({
...order('limit', 'buy', 1),
orderType: 'limit',
limitPrice: 90,
});
expect(limit.status).toBe('accepted');
expect(await execution.cancelOrder(limit.orderId)).toBe(true);
await execution.onMarketData(quote('q2', 80, 100, start + 1));
expect((await execution.getOrderStatus(limit.orderId))?.fills).toHaveLength(0);
const filled = await execution.submitOrder(order('filled', 'buy', 1));
expect(await execution.cancelOrder(filled.orderId)).toBe(false);
});
test('invalid/stale state cannot masquerade as acceptance and event conflicts roll back', async () => {
const { execution } = await fixture();
expect((await execution.submitOrder(order('missing'))).status).toBe('rejected');
await execution.onMarketData(quote('q'));
await expect(execution.onMarketData(quote('q', 101))).rejects.toBeInstanceOf(
ExecutionConflictError
);
await expect(
execution.onMarketData(quote('older', 100, 100, start - 1))
).rejects.toBeInstanceOf(ExecutionConflictError);
const stop = await execution.submitOrder({
...order('stop'),
orderType: 'stop',
stopPrice: 100,
});
expect(stop.status).toBe('rejected');
expect(stop.rejectionReason).toContain('Unsupported');
expect((await execution.getAccount()).cash).toBe(10000);
});
test('HTTP requires an idempotency ID and returns conflict for mismatched reuse', async () => {
const { execution } = await fixture();
await execution.onMarketData(quote('q'));
const routes = createOrderRoutes({ logger, custom: { ExecutionService: execution } });
const send = (body: object) =>
routes.request('/', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const { clientOrderId: _, ...missing } = order('id');
expect((await send(missing)).status).toBe(400);
expect((await send(order('id'))).status).toBe(201);
expect((await send(order('id', 'buy', 20))).status).toBe(409);
});
test('unsupported live initialization cannot alter an existing simulation account', async () => {
const { execution, engine } = await fixture();
const live = {
mode: 'live' as const,
broker: 'none',
accountId: 'none',
accountType: 'cash' as const,
riskLimits: {
maxOrderSize: 10,
maxPositionSize: 10,
maxDailyLoss: 10,
maxSymbolExposure: 100,
maxGrossExposure: 100,
},
};
await expect(execution.initialize(live, engine)).rejects.toThrow('Live trading is disabled');
expect((await execution.getAccount()).cash).toBe(10000);
const mode = new ModeManager({ logger }, {} as never, execution, {} as never);
await expect(mode.initializeMode(live)).rejects.toThrow('Live trading is disabled');
expect(() => new TradingEngine('live', { broker: 'none', accountId: 'none' })).toThrow(
'Live trading is disabled'
);
expect(() => engine.submitOrder({ ...order('direct'), id: 'direct' })).toThrow(
'execution gateway'
);
});
test('batch delivery is ordered, subscribed once, deduplicated, and routes every strategy order through risk', async () => {
const { execution } = await fixture();
class Strategy extends BaseStrategy {
calls: number[] = [];
protected updateIndicators(data: MarketData) {
this.calls.push(data.data.timestamp);
}
protected async generateSignal(data: MarketData): Promise<Signal | null> {
await new Promise(resolve => setTimeout(resolve, 5));
return { type: 'buy', symbol: data.data.symbol, strength: 1, metadata: { quantity: 1 } };
}
protected async onStart() {}
protected async onStop() {}
protected onConfigUpdate() {}
}
const services: OrchestratorServices = { logger, custom: { ExecutionService: execution } };
const market = new MarketDataService(services);
services.custom!.MarketDataService = market;
const manager = new StrategyManager(services);
services.custom!.StrategyManager = manager;
manager.setupEventListeners();
manager.setupEventListeners();
const strategy = new Strategy(
{
id: 'strategy',
name: 'fixture',
enabled: true,
parameters: {},
symbols: ['A'],
allocation: 1,
},
{} as ModeManager,
execution
);
await strategy.initialize();
await strategy.start();
// Inject only the strategy fixture; market delivery, gateway, accounting, and native projection are real.
Object.defineProperty(manager, 'strategies', { value: new Map([['strategy', strategy]]) });
Object.defineProperty(manager, 'activeStrategies', { value: new Set(['strategy']) });
cleanup.push(() => manager.shutdown());
const first = quote('1');
const second = quote('2', 100, 100, start + 1);
market.emit('marketDataBatch', [first]);
market.emit('marketData', first);
market.emit('marketDataBatch', [first, second]);
await manager.drain();
expect(strategy.calls).toEqual([start, start + 1]);
expect(strategy.getPosition('A')).toBe(2);
expect((await execution.getAccount()).strategyPositions.strategy?.A).toBe(2);
expect(market.listenerCount('marketDataBatch')).toBe(1);
market.ingest(quote('3', 100, 100, start + 2));
await market.flush();
expect(strategy.calls).toEqual([start, start + 1, start + 2]);
expect(strategy.getPosition('A')).toBe(3);
});
});

View file

@ -0,0 +1,229 @@
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { afterEach, describe, expect, test } from 'bun:test';
import { Pool } from 'pg';
import { PostgreSQLClient } from '@stock-bot/postgres';
import { PostgresExecutionRepository } from '../../apps/stock/orchestrator/src/execution/PostgresExecutionRepository';
import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/repository';
import { config, logger, makeExecution, order, quote, start } from '../fixtures/execution';
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) await close();
});
async function fixture() {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety'))
throw new Error('Dedicated safety database required');
const schema = 'stock_bot_safety_' + randomUUID().replaceAll('-', '');
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({ connectionString: url, options: '-c search_path=' + schema });
cleanup.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
const sql = readFileSync(
new URL('../../database/postgres/init/11-simulation-execution-ledger.sql', import.meta.url),
'utf8'
);
await pool.query(sql);
await pool.query(sql);
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', user: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
let now = start;
const make = async (
limits = {
maxOrderSize: 100,
maxPositionSize: 100,
maxDailyLoss: 100,
maxGrossExposure: 10000,
maxSymbolExposure: 10000,
}
) => {
const runtime = makeExecution(new PostgresExecutionRepository(postgres), () => now);
await runtime.execution.initialize(
{
mode: 'paper',
accountId: 'fixture',
startingCapital: config.initialCapital,
commission: 0.001,
slippage: 0,
maxQuoteAgeMs: 1000,
riskLimits: limits,
},
runtime.engine
);
cleanup.push(() => runtime.execution.shutdown());
return runtime.execution;
};
const execution = await make();
return {
pool,
postgres,
execution,
make,
setTime(time: number) {
now = time;
},
};
}
describe.skipIf(!url)('paper execution ledger on real PostgreSQL', () => {
test('competing service instances deduplicate the same client ID, fill and account transaction', async () => {
const f = await fixture();
const second = await f.make();
await f.execution.onMarketData(quote('q'));
const reports = await Promise.all([
f.execution.submitOrder(order('id')),
second.submitOrder(order('id')),
]);
expect(reports[0]).toEqual(reports[1]);
expect((await f.pool.query('SELECT * FROM simulation_orders')).rows).toHaveLength(1);
const fills = (await f.pool.query('SELECT payload FROM simulation_fills')).rows;
expect(fills).toHaveLength(1);
expect(fills[0].payload.pnl).toBe(-1);
expect((await second.getAccount()).cash).toBe(8999);
expect((await second.getPositions())[0]?.quantity).toBe(10);
await expect(second.submitOrder(order('id', 'buy', 11))).rejects.toBeInstanceOf(
ExecutionConflictError
);
});
test('a fill-write failure rolls back acceptance and cash/positions together; retry has no phantom fill', async () => {
const f = await fixture();
await f.execution.onMarketData(quote('q'));
let events = 0;
f.execution.on('fill', () => events++);
await f.pool.query(`CREATE FUNCTION reject_fill() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
RAISE EXCEPTION 'injected fill failure'; END $$;
CREATE TRIGGER reject_fill BEFORE INSERT ON simulation_fills FOR EACH ROW EXECUTE FUNCTION reject_fill();`);
await expect(f.execution.submitOrder(order('id'))).rejects.toThrow('injected fill failure');
expect((await f.pool.query('SELECT * FROM simulation_orders')).rows).toHaveLength(0);
expect((await f.execution.getAccount()).cash).toBe(10000);
expect(events).toBe(0);
await f.pool.query('DROP TRIGGER reject_fill ON simulation_fills');
expect((await f.execution.submitOrder(order('id'))).status).toBe('filled');
expect(events).toBe(1);
});
test('restart restores partial orders, consumed liquidity, cash and strategy positions without refilling duplicates', async () => {
const f = await fixture();
await f.execution.onMarketData(quote('q1', 100, 3));
const first = await f.execution.submitOrder(order('id'), { strategyId: 'strategy' });
expect(first.status).toBe('partiallyFilled');
await f.execution.shutdown();
const second = await f.make();
expect((await second.getStrategySnapshot('strategy')).positions.A).toBe(3);
expect((await second.getStrategySnapshot('strategy')).orders).toHaveLength(1);
expect(await second.onMarketData(quote('q1', 100, 3))).toBe(false);
f.setTime(start + 1);
await second.onMarketData(quote('q2', 100, 7, start + 1));
expect((await second.getOrderStatus(first.orderId))?.status).toBe('filled');
expect((await second.getAccount()).cash).toBe(8999);
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(2);
});
test('account locking serializes projected-risk reservations across producers', async () => {
const f = await fixture();
const limits = {
maxOrderSize: 100,
maxPositionSize: 100,
maxDailyLoss: 100,
maxGrossExposure: 1000,
maxSymbolExposure: 1000,
};
const first = await f.make(limits),
second = await f.make(limits);
await first.onMarketData(quote('q', 100, 0));
const reports = await Promise.all([
first.submitOrder(order('a', 'buy', 7)),
second.submitOrder(order('b', 'buy', 7)),
]);
expect(reports.map(r => r.status).sort()).toEqual(['accepted', 'rejected']);
expect((await f.execution.getAccount()).cash).toBe(10000);
});
test('duplicate and conflicting market IDs cannot reapply fills, even after a restart', async () => {
const f = await fixture();
await f.execution.onMarketData(quote('q', 100, 3));
const report = await f.execution.submitOrder(order('id'));
const second = await f.make();
await expect(second.onMarketData(quote('q', 200, 3))).rejects.toBeInstanceOf(
ExecutionConflictError
);
expect(await second.onMarketData(quote('q', 100, 3))).toBe(false);
expect((await second.getOrderStatus(report.orderId))?.fills).toHaveLength(1);
expect((await second.getAccount()).cash).toBe(9699.7);
});
test('daily P&L uses deltas; loss limit blocks new risk but permits reduction and resets at UTC midnight', async () => {
const f = await fixture();
const e = await f.make({
maxOrderSize: 100,
maxPositionSize: 100,
maxDailyLoss: 1,
maxGrossExposure: 10000,
maxSymbolExposure: 10000,
});
await e.onMarketData(quote('q'));
await e.submitOrder(order('open'));
expect((await e.submitOrder(order('blocked', 'buy', 1))).status).toBe('rejected');
expect((await e.submitOrder(order('close', 'sell', 10))).status).toBe('filled');
expect((await e.getAccount()).dailyPnl).toBe(-2);
f.setTime(start + 86400000);
await e.onMarketData(quote('new-day', 100, 100, start + 86400000));
expect((await e.getAccount()).dailyPnl).toBe(0);
expect((await e.submitOrder(order('new-day-order', 'buy', 1))).status).toBe('filled');
});
test('stale quotes reject submission; day orders expire and unfilled cancellation survives restart', async () => {
const f = await fixture();
await f.execution.onMarketData(quote('q', 100, 0));
const day = await f.execution.submitOrder(order('day'));
const gtc = await f.execution.submitOrder({ ...order('gtc'), timeInForce: 'GTC' });
f.setTime(start + 2000);
expect((await f.execution.submitOrder(order('stale'))).rejectionReason).toContain('stale');
await expect(f.execution.onMarketData(quote('old', 100, 100, start + 1))).rejects.toThrow(
'Stale'
);
f.setTime(start + 86400000);
await f.execution.onMarketData(quote('next', 100, 0, start + 86400000));
expect((await f.execution.getOrderStatus(day.orderId))?.status).toBe('cancelled');
expect(await f.execution.cancelOrder(gtc.orderId)).toBe(true);
const second = await f.make();
expect((await second.getOrderStatus(gtc.orderId))?.status).toBe('cancelled');
});
test('observer exceptions cannot change committed fills into reported failure or trigger another fill', async () => {
const f = await fixture();
await f.execution.onMarketData(quote('q'));
f.execution.setObserver(async () => {
throw new Error('observer disconnected');
});
const report = await f.execution.submitOrder(order('id'));
expect(report.status).toBe('filled');
expect((await f.execution.submitOrder(order('id'))).orderId).toBe(report.orderId);
expect((await f.pool.query('SELECT * FROM simulation_fills')).rows).toHaveLength(1);
});
test('pending orders retain their accepted commission policy after account configuration changes', async () => {
const f = await fixture();
await f.execution.onMarketData(quote('q1', 100, 3));
const original = await f.execution.submitOrder(order('pending'));
const changed = makeExecution(new PostgresExecutionRepository(f.postgres), () => start + 1);
await changed.execution.initialize(
{
mode: 'paper',
accountId: 'fixture',
startingCapital: 10000,
commission: 0.01,
slippage: 0,
},
changed.engine
);
cleanup.push(() => changed.execution.shutdown());
await changed.execution.onMarketData(quote('q2', 100, 10, start + 1));
const report = await changed.execution.getOrderStatus(original.orderId);
expect(report?.fills.reduce((n, fill) => n + fill.commission, 0)).toBe(1);
const next = await changed.execution.submitOrder(order('new', 'buy', 1));
expect(next.fills[0]?.commission).toBe(1);
});
});