import { afterEach, describe, expect, test } from 'bun:test'; import { BacktestExecutionRepository } from '../../apps/stock/orchestrator/src/execution/BacktestExecutionRepository'; import { config, makeExecution, order, quote, start } from '../fixtures/execution'; const cleanup: (() => Promise)[] = []; const runId = '00000000-0000-4000-8000-000000000003'; afterEach(async () => { for (const close of cleanup.splice(0).reverse()) { await close(); } }); async function fixture() { const repository = new BacktestExecutionRepository(); const runtime = makeExecution(repository); await runtime.execution.initialize( { ...config, runId, commission: 0.01, riskLimits: { maxOrderSize: 10000, maxPositionSize: 10000, maxDailyLoss: 1000000, maxSymbolExposure: 1000000, maxGrossExposure: 1000000, }, }, runtime.engine ); cleanup.push(() => runtime.execution.shutdown()); return { ...runtime, repository }; } describe('fee-inclusive legacy capital commitments', () => { test('fee_budget_10000: an otherwise fully funded buy rejects without financial mutation', async () => { const { execution } = await fixture(); await execution.onMarketData(quote('q')); const before = await execution.getAccount(); const report = await execution.submitOrder(order('unfunded', 'buy', 100)); expect(report.status).toBe('rejected'); expect(report.rejectionReason).toBe('Unlevered capital exposure limit'); expect(report.fills).toEqual([]); expect(await execution.getAccount()).toEqual(before); expect(await execution.getPositions()).toEqual([]); }); test('fee_budget_99: entry fees leave exactly one unit of cash', async () => { const { execution } = await fixture(); await execution.onMarketData(quote('q')); const report = await execution.submitOrder(order('funded', 'buy', 99)); expect(report.status).toBe('filled'); expect(report.fills.map(fill => fill.commission)).toEqual([99]); expect((await execution.getAccount()).cash).toBe(1); expect((await execution.getAccount()).equity).toBe(9901); expect((await execution.getPositions())[0]?.quantity).toBe(99); }); test('pending_fee_commitments and cancelled_commitment_released: two commitments of 5050 cannot fit 10000', async () => { const { execution } = await fixture(); await execution.onMarketData(quote('a', 100, 0)); await execution.onMarketData(quote('b', 100, 0, start, 'B')); const first = await execution.submitOrder(order('first', 'buy', 50)); expect(first.status).toBe('accepted'); expect(first.fills).toEqual([]); const second = await execution.submitOrder({ ...order('second', 'buy', 50), symbol: 'B' }); expect(second.status).toBe('rejected'); expect(second.rejectionReason).toBe('Unlevered capital exposure limit'); expect((await execution.getAccount()).cash).toBe(10000); expect(await execution.cancelOrder(first.orderId)).toBe(true); const replacement = await execution.submitOrder({ ...order('replacement', 'buy', 99), symbol: 'B', }); expect(replacement.status).toBe('accepted'); await execution.onMarketData(quote('b-fill', 100, 99, start + 1, 'B')); expect((await execution.getOrderStatus(replacement.orderId))?.status).toBe('filled'); expect((await execution.getAccount()).cash).toBe(1); expect((await execution.getOrderStatus(first.orderId))?.fills).toEqual([]); }); test('partial_fee_not_double_counted: fills 10 then 89 charge 99 once, including duplicate events', async () => { const { execution } = await fixture(); const firstQuote = quote('q1', 100, 10); await execution.onMarketData(firstQuote); const first = await execution.submitOrder(order('partial', 'buy', 99)); expect(first.status).toBe('partiallyFilled'); expect(first.fills.map(fill => [fill.quantity, fill.commission])).toEqual([[10, 10]]); expect((await execution.getAccount()).cash).toBe(8990); expect(await execution.submitOrder(order('partial', 'buy', 99))).toEqual(first); expect(await execution.onMarketData(firstQuote)).toBe(false); const nextQuote = quote('q2', 100, 89, start + 1); await execution.onMarketData(nextQuote); const complete = await execution.getOrderStatus(first.orderId); expect(complete?.status).toBe('filled'); expect(complete?.fills.map(fill => [fill.quantity, fill.commission])).toEqual([ [10, 10], [89, 89], ]); expect((await execution.getAccount()).cash).toBe(1); const beforeRetry = await execution.getAccount(); expect(await execution.onMarketData(nextQuote)).toBe(false); expect(await execution.submitOrder(order('partial', 'buy', 99))).toEqual(complete); expect(await execution.getAccount()).toEqual(beforeRetry); }); test('frozen_order_fee_policy: pending commitments retain their original commission', async () => { const { execution, repository } = await fixture(); await execution.onMarketData(quote('q', 100, 0)); const first = await execution.submitOrder(order('first', 'buy', 50)); expect(first.status).toBe('accepted'); await repository.transact(runId, async tx => { tx.account.commission = 0; }); const second = await execution.submitOrder(order('second', 'buy', 50)); expect(second.status).toBe('rejected'); expect(second.rejectionReason).toBe('Unlevered capital exposure limit'); await execution.onMarketData(quote('fill', 100, 50, start + 1)); expect((await execution.getOrderStatus(first.orderId))?.fills[0]?.commission).toBe(50); expect((await execution.getAccount()).cash).toBe(4950); }); test('a partially filled pending order reserves only its unpaid remaining fees for another order', async () => { const { execution } = await fixture(); await execution.onMarketData(quote('q1', 100, 10)); const partial = await execution.submitOrder(order('partial', 'buy', 50)); expect(partial.status).toBe('partiallyFilled'); expect(partial.fills[0]?.commission).toBe(10); const pending = await execution.submitOrder(order('other', 'buy', 49)); expect(pending.status).toBe('accepted'); await execution.onMarketData(quote('q2', 100, 89, start + 1)); const first = await execution.getOrderStatus(partial.orderId); const second = await execution.getOrderStatus(pending.orderId); expect(first?.status).toBe('filled'); expect(first?.fills.map(fill => fill.commission)).toEqual([10, 40]); expect(second?.status).toBe('filled'); expect(second?.fills.map(fill => fill.commission)).toEqual([49]); expect((await execution.getAccount()).cash).toBe(1); }); test('frozen_order_fee_policy: fill-time admission uses stored rather than current commission', async () => { const { execution, repository } = await fixture(); await execution.onMarketData(quote('q', 100, 0)); const pending = await execution.submitOrder(order('pending', 'buy', 99)); expect(pending.status).toBe('accepted'); await repository.transact(runId, async tx => { tx.account.commission = 0.5; }); await execution.onMarketData(quote('fill', 100, 99, start + 1)); const report = await execution.getOrderStatus(pending.orderId); expect(report?.status).toBe('filled'); expect(report?.fills[0]?.commission).toBe(99); expect((await execution.getAccount()).cash).toBe(1); }); test('fill-time repricing cannot consume capital reserved for unpaid fees', async () => { const { execution } = await fixture(); await execution.onMarketData(quote('q', 99, 0)); const pending = await execution.submitOrder(order('pending', 'buy', 100)); expect(pending.status).toBe('accepted'); await execution.onMarketData(quote('gap', 100, 100, start + 1)); const report = await execution.getOrderStatus(pending.orderId); expect(report?.status).toBe('cancelled'); expect(report?.rejectionReason).toBe('Unlevered capital exposure limit'); expect(report?.fills).toEqual([]); expect((await execution.getAccount()).cash).toBe(10000); }); test('existing long/short reversal behavior is unchanged', async () => { const { execution } = await fixture(); await execution.onMarketData(quote('q')); for (const [id, side, quantity] of [ ['long', 'buy', 10], ['reverse', 'sell', 20], ['close', 'buy', 10], ] as const) { expect((await execution.submitOrder(order(id, side, quantity))).status).toBe('filled'); } expect((await execution.getAccount()).cash).toBe(9960); expect((await execution.getPositions())[0]?.quantity).toBe(0); }); test('reducing-order exemption still permits an insolvent short cover under legacy policy', async () => { const { execution } = await fixture(); await execution.onMarketData(quote('short', 100, 99)); expect((await execution.submitOrder(order('short', 'sell', 99))).status).toBe('filled'); await execution.onMarketData(quote('gap', 200, 99, start + 1)); const report = await execution.submitOrder(order('cover', 'buy', 99)); expect(report.status).toBe('filled'); expect(report.fills[0]?.commission).toBe(198); expect((await execution.getAccount()).cash).toBe(-197); expect((await execution.getPositions())[0]?.quantity).toBe(0); }); });