229 lines
10 KiB
TypeScript
229 lines
10 KiB
TypeScript
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);
|
|
});
|
|
});
|