170 lines
7.4 KiB
TypeScript
170 lines
7.4 KiB
TypeScript
import { asValue } from 'awilix';
|
|
import { afterEach, describe, expect, test } from 'bun:test';
|
|
import { Hono } from 'hono';
|
|
import { createHttpSecurity, ServiceContainerBuilder } from '@stock-bot/di';
|
|
import { parseFinancialDecimal } from '@stock-bot/types';
|
|
import { createPaperRoutes } from '../../apps/stock/orchestrator/src/api/rest/paper';
|
|
import { registerOrchestratorServices } from '../../apps/stock/orchestrator/src/container';
|
|
import { builtinStrategySelectionSchema } from '../../apps/stock/orchestrator/src/contracts/builtin-strategy';
|
|
import type { PaperRuntime } from '../../apps/stock/orchestrator/src/contracts/paper-runtime';
|
|
import { createBuiltinStrategy } from '../../apps/stock/orchestrator/src/strategies/canonical-builtins';
|
|
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
|
import { canonicalAdmissionFixture } from '../fixtures/canonical-admission';
|
|
import { logger } from '../fixtures/execution';
|
|
import { paperConfig, paperFixture, paperFrame } from '../fixtures/paper-runtime';
|
|
|
|
const adminToken = 'paper-http-test-admin-token-not-real-123456';
|
|
const serviceToken = 'paper-http-test-service-token-not-real-123456';
|
|
const cleanup: (() => Promise<void>)[] = [];
|
|
afterEach(async () => {
|
|
for (const close of cleanup.splice(0).reverse()) {
|
|
await close();
|
|
}
|
|
});
|
|
function api(runtime: PaperRuntime) {
|
|
const app = new Hono();
|
|
createHttpSecurity({ adminToken, serviceToken }).mount(app);
|
|
app.route(
|
|
'/api/paper',
|
|
createPaperRoutes({ logger, custom: { CanonicalPaperRuntime: runtime } })
|
|
);
|
|
return async (path: string, body: unknown, producer = false) => {
|
|
const response = await app.request(`/api/paper/${path}`, {
|
|
method: 'POST',
|
|
headers: {
|
|
Authorization: `Bearer ${producer ? serviceToken : adminToken}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify(body),
|
|
});
|
|
const result = await response.json();
|
|
expect(response.status, JSON.stringify(result)).toBe(200);
|
|
return result;
|
|
};
|
|
}
|
|
|
|
describe.skipIf(!process.env.PIPELINE_TEST_DATABASE_URL)(
|
|
'canonical paper HTTP and composition',
|
|
() => {
|
|
test('authenticated feed -> actual SMA -> next quote Rust fill -> durable restart without capital reset', async () => {
|
|
const config = paperConfig();
|
|
config.matching.risk.ledger.initialCapital = '1234';
|
|
config.strategies[0]!.ownerBudget = '20';
|
|
const program = createBuiltinStrategy(
|
|
builtinStrategySelectionSchema.parse(config.strategies[0])
|
|
);
|
|
const f = await paperFixture(config, program);
|
|
cleanup.push(f.close);
|
|
let post = api(f.runtime);
|
|
const connection = { sourceId: 'fixture', connectionId: 'one' };
|
|
await post('feed/connect', connection, true);
|
|
await post('feed/frames', paperFrame(1), true);
|
|
await post('activate', {});
|
|
const send = async (sequence: number, price: string, bars = true) => {
|
|
f.clock(sequence * 10);
|
|
const frame = paperFrame(sequence);
|
|
frame.quotes[0]!.bid = frame.quotes[0]!.ask = parseFinancialDecimal(price);
|
|
frame.observations = bars
|
|
? frame.observations.map(row => ({
|
|
...row,
|
|
open: parseFinancialDecimal(price),
|
|
high: parseFinancialDecimal(price),
|
|
low: parseFinancialDecimal(price),
|
|
close: parseFinancialDecimal(price),
|
|
}))
|
|
: [];
|
|
await post('feed/frames', frame, true);
|
|
};
|
|
await send(2, '11');
|
|
await send(3, '9');
|
|
await send(4, '10');
|
|
const decision = await f.snapshot();
|
|
expect(decision.account.view.portfolio.positions).toHaveLength(0);
|
|
expect(decision.owners[0]!.diagnostic.nextDecisionSequence).toBe(3);
|
|
await send(5, '10', false);
|
|
const filled = await f.snapshot();
|
|
expect(filled.account.view.portfolio.positions[0]!.quantity).toBe(parseFinancialDecimal('2'));
|
|
expect(filled.account.view.portfolio.cash).toBe(parseFinancialDecimal('1213.8'));
|
|
expect(filled.account.view.equity).toBe(parseFinancialDecimal('1233.8'));
|
|
expect(filled.journal.filter(row => row.payload.kind === 'effect')).not.toHaveLength(0);
|
|
await post('halt', { reason: 'restart fixture' });
|
|
const restored = await f.make();
|
|
post = api(restored);
|
|
expect(await restored.status()).toMatchObject({
|
|
operatorHalted: true,
|
|
active: false,
|
|
connected: false,
|
|
});
|
|
expect((await f.snapshot()).account.view).toEqual(filled.account.view);
|
|
expect((await f.snapshot()).account.checkpoint).toEqual(filled.account.checkpoint);
|
|
expect((await f.snapshot()).journal).toEqual(filled.journal);
|
|
expect((await f.snapshot()).owners).toEqual(filled.owners);
|
|
await post('feed/connect', { ...connection, connectionId: 'two' }, true);
|
|
f.clock(60);
|
|
await post('feed/frames', paperFrame(6, 60, 'two'), true);
|
|
await post('activate', {});
|
|
expect((await f.snapshot()).account.view).toEqual(filled.account.view);
|
|
expect((await f.snapshot()).account.checkpoint).toEqual(filled.account.checkpoint);
|
|
expect((await f.snapshot()).journal).toEqual(filled.journal);
|
|
});
|
|
|
|
test('opt-in composition exposes canonical custody only and research cannot change its state', async () => {
|
|
const config = paperConfig();
|
|
const f = await paperFixture(
|
|
config,
|
|
createBuiltinStrategy(builtinStrategySelectionSchema.parse(config.strategies[0]))
|
|
);
|
|
cleanup.push(f.close);
|
|
const container = await new ServiceContainerBuilder()
|
|
.withOptions({
|
|
enableCache: false,
|
|
enableQueue: false,
|
|
enableMongoDB: false,
|
|
enablePostgres: false,
|
|
enableQuestDB: false,
|
|
enableBrowser: false,
|
|
enableProxy: false,
|
|
})
|
|
.build();
|
|
const services: OrchestratorServices = { logger, postgres: f.postgres };
|
|
container.register({ serviceContainer: asValue(services) });
|
|
await registerOrchestratorServices(container, {
|
|
role: 'paper',
|
|
canonicalPaper: config,
|
|
nativeExecutionTimeoutMs: 10000,
|
|
});
|
|
const custom = services.custom!;
|
|
cleanup.push(async () => {
|
|
await custom.CanonicalPaperRuntime!.shutdown();
|
|
await custom.BacktestRunner!.shutdown();
|
|
await container.dispose();
|
|
});
|
|
expect(custom.CanonicalPaperRuntime).toBeDefined();
|
|
for (const key of [
|
|
'ExecutionService',
|
|
'ModeManager',
|
|
'StrategyManager',
|
|
'MarketDataService',
|
|
'PaperTradingManager',
|
|
] as const) {
|
|
expect(custom[key]).toBeUndefined();
|
|
expect(container.hasRegistration(key)).toBe(false);
|
|
}
|
|
expect((await custom.CanonicalPaperRuntime!.status()).active).toBe(false);
|
|
const before = await f.snapshot();
|
|
const research = await canonicalAdmissionFixture(f.pool, f.postgres);
|
|
custom.StorageService!.getHistoricalBars = async () => {
|
|
throw new Error('Canonical execution cannot query providers');
|
|
};
|
|
const run = await research.api.createRun({ backtestId: research.draft.id });
|
|
expect((await custom.BacktestRunner!.runQueued(run.id)).status).toBe('completed');
|
|
expect(await f.snapshot()).toEqual(before);
|
|
await expect(
|
|
registerOrchestratorServices(container, { role: 'paper', canonicalPaper: config })
|
|
).rejects.toThrow('fresh runtime composition');
|
|
await expect(registerOrchestratorServices(container)).rejects.toThrow(
|
|
'fresh runtime composition'
|
|
);
|
|
});
|
|
}
|
|
);
|