250 lines
11 KiB
TypeScript
250 lines
11 KiB
TypeScript
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 { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
|
import {
|
|
BaseStrategy,
|
|
type Signal,
|
|
} from '../../apps/stock/orchestrator/src/strategies/BaseStrategy';
|
|
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
|
|
import type { MarketData } 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 lifecycle = { initialize: async () => {}, shutdown: async () => {} };
|
|
const mode = new ModeManager({
|
|
logger,
|
|
marketData: lifecycle,
|
|
execution,
|
|
strategies: { restoreStrategies: async () => {}, shutdown: async () => {} },
|
|
});
|
|
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 market: MarketDataService = new MarketDataService({
|
|
logger,
|
|
storage: new StorageService(logger, null, null),
|
|
drainStrategies: () => manager.drain(),
|
|
});
|
|
const manager: StrategyManager = new StrategyManager({
|
|
logger,
|
|
execution,
|
|
marketData: market,
|
|
createStrategy: config => new Strategy(config, {} as ModeManager, execution),
|
|
});
|
|
manager.setupEventListeners();
|
|
manager.setupEventListeners();
|
|
const strategy = new Strategy(
|
|
{
|
|
id: 'strategy',
|
|
name: 'fixture',
|
|
enabled: true,
|
|
parameters: {},
|
|
symbols: ['A'],
|
|
allocation: 1,
|
|
},
|
|
{} as ModeManager,
|
|
execution
|
|
);
|
|
// Inject only the strategy fixture; market delivery, gateway, accounting, and native projection are real.
|
|
await manager.attachStrategy(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);
|
|
});
|
|
});
|