cleanup
This commit is contained in:
parent
e4925ecdfe
commit
b7aeca4888
20 changed files with 490 additions and 248 deletions
6
test/fixtures/backtest-crash-owner.ts
vendored
6
test/fixtures/backtest-crash-owner.ts
vendored
|
|
@ -5,6 +5,7 @@ import { PostgreSQLClient } from '@stock-bot/postgres';
|
|||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
|
|
@ -27,7 +28,10 @@ const postgres = new PostgreSQLClient(
|
|||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
const repository = new PostgresBacktestRunRepository(postgres, 500);
|
||||
const runner = new BacktestRunner({
|
||||
engine: new RustBacktestAdapter({ logger }),
|
||||
engine: new RustBacktestAdapter({
|
||||
logger,
|
||||
storage: new StorageService({ logger }, null, null, null),
|
||||
}),
|
||||
engineName: 'native',
|
||||
repository,
|
||||
logger,
|
||||
|
|
|
|||
36
test/fixtures/strategy-recovery.ts
vendored
36
test/fixtures/strategy-recovery.ts
vendored
|
|
@ -1,3 +1,4 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import { z } from 'zod';
|
||||
import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
|
||||
import type {
|
||||
|
|
@ -12,7 +13,12 @@ import {
|
|||
BaseStrategy,
|
||||
type Signal,
|
||||
} from '../../apps/stock/orchestrator/src/strategies/BaseStrategy';
|
||||
import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies';
|
||||
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
|
||||
import type {
|
||||
StrategyDependencies,
|
||||
StrategyRegistry,
|
||||
} from '../../apps/stock/orchestrator/src/strategies/StrategyRegistry';
|
||||
import type { MarketData, StrategyConfig } from '../../apps/stock/orchestrator/src/types';
|
||||
import { logger } from './execution';
|
||||
|
||||
|
|
@ -24,6 +30,20 @@ export const recoveryConfig: StrategyConfig = {
|
|||
allocation: 1,
|
||||
enabled: true,
|
||||
};
|
||||
export function makeStrategyManager({
|
||||
execution,
|
||||
modeManager,
|
||||
registry = createBuiltinStrategyRegistry(),
|
||||
marketData = new EventEmitter(),
|
||||
}: StrategyDependencies & { registry?: StrategyRegistry; marketData?: EventEmitter }) {
|
||||
return new StrategyManager({
|
||||
logger,
|
||||
execution,
|
||||
marketData,
|
||||
createStrategy: config => registry.create(config, { execution, modeManager }),
|
||||
});
|
||||
}
|
||||
|
||||
export class CounterStrategy extends BaseStrategy {
|
||||
count = 0;
|
||||
equities: number[] = [];
|
||||
|
|
@ -69,8 +89,20 @@ export async function attachCounter(
|
|||
execution: ExecutionService,
|
||||
strategy = new CounterStrategy(execution)
|
||||
) {
|
||||
const manager = new StrategyManager({ logger, custom: { ExecutionService: execution } });
|
||||
await manager.attachStrategy(strategy);
|
||||
const manager = new StrategyManager({
|
||||
logger,
|
||||
execution,
|
||||
marketData: new EventEmitter(),
|
||||
createStrategy: () => {
|
||||
throw new Error('Counter fixtures attach their strategies directly');
|
||||
},
|
||||
});
|
||||
try {
|
||||
await manager.attachStrategy(strategy);
|
||||
} catch (error) {
|
||||
await manager.shutdown();
|
||||
throw error;
|
||||
}
|
||||
return { manager, strategy };
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -128,10 +128,7 @@ async function fixture(
|
|||
);
|
||||
}
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
const engine = new RustBacktestAdapter(
|
||||
{ logger, custom: { StorageService: storage } },
|
||||
engineOptions
|
||||
);
|
||||
const engine = new RustBacktestAdapter({ logger, storage }, engineOptions);
|
||||
const repository = new PostgresBacktestRunRepository(postgres);
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
|
|
@ -147,9 +144,9 @@ async function fixture(
|
|||
return { postgres, mongodb, storage, engine, repository, runner, services, routes };
|
||||
}
|
||||
|
||||
async function typescriptRuntime(
|
||||
async function composedRuntime(
|
||||
f: Awaited<ReturnType<typeof fixture>>,
|
||||
strategyRegistry?: StrategyRegistry
|
||||
options: { strategyRegistry?: StrategyRegistry; useRustEngine?: boolean } = {}
|
||||
) {
|
||||
const di = await new ServiceContainerBuilder()
|
||||
.withOptions({
|
||||
|
|
@ -166,23 +163,60 @@ async function typescriptRuntime(
|
|||
logger,
|
||||
postgres: f.postgres,
|
||||
mongodb: f.mongodb,
|
||||
custom: {},
|
||||
};
|
||||
di.register({ serviceContainer: asValue(services) });
|
||||
await registerOrchestratorServices(di, {
|
||||
initializeMode: false,
|
||||
useRustEngine: false,
|
||||
strategyRegistry,
|
||||
...options,
|
||||
});
|
||||
expect(di.resolve('BacktestRunner')).toBe(services.custom?.BacktestRunner);
|
||||
return services;
|
||||
}
|
||||
|
||||
describe('one backtest execution workflow', () => {
|
||||
for (const backend of ['native', 'typescript'] as const) {
|
||||
test(`${backend} composed runtime uses injected peers when application service lookups are unavailable`, async () => {
|
||||
const f = await fixture();
|
||||
const services = await composedRuntime(f, { useRustEngine: backend === 'native' });
|
||||
const {
|
||||
BacktestRunner: runner,
|
||||
ModeManager: mode,
|
||||
MarketDataService: market,
|
||||
StrategyManager: manager,
|
||||
} = services.custom!;
|
||||
cleanup.unshift(async () => {
|
||||
await runner!.shutdown();
|
||||
await mode!.shutdown();
|
||||
await manager!.shutdown();
|
||||
});
|
||||
for (const key of Object.keys(services.custom!)) {
|
||||
Object.defineProperty(services.custom, key, {
|
||||
get() {
|
||||
throw new Error(`Unexpected runtime service lookup: ${key}`);
|
||||
},
|
||||
});
|
||||
}
|
||||
const history = await market!.loadHistoricalData(
|
||||
config.symbols,
|
||||
new Date(config.startDate),
|
||||
new Date(config.endDate),
|
||||
config.dataFrequency
|
||||
);
|
||||
expect(history).toHaveLength(70);
|
||||
const result = await runner!.runBacktest(config);
|
||||
expect(result.engine).toBe(backend);
|
||||
expect(result.trades.length).toBeGreaterThan(0);
|
||||
expect(market!.listenerCount('marketDataBatch')).toBe(1);
|
||||
await mode!.shutdown();
|
||||
await manager!.shutdown();
|
||||
expect(market!.listenerCount('marketDataBatch')).toBe(0);
|
||||
});
|
||||
}
|
||||
|
||||
for (const backend of ['native', 'typescript'] as const) {
|
||||
test(`${backend} API runs separate mixed execution settings and replay the original configuration`, async () => {
|
||||
const f = await fixture();
|
||||
const services = backend === 'typescript' ? await typescriptRuntime(f) : f.services;
|
||||
const services = backend === 'typescript' ? await composedRuntime(f) : f.services;
|
||||
const runner = services.custom!.BacktestRunner!;
|
||||
cleanup.unshift(async () => {
|
||||
await runner.shutdown();
|
||||
|
|
@ -248,7 +282,7 @@ describe('one backtest execution workflow', () => {
|
|||
return new CounterStrategy(dependencies.execution, definition);
|
||||
}
|
||||
);
|
||||
const services = await typescriptRuntime(f, registry);
|
||||
const services = await composedRuntime(f, { strategyRegistry: registry });
|
||||
const runner = services.custom!.BacktestRunner!;
|
||||
cleanup.unshift(async () => {
|
||||
await runner.shutdown();
|
||||
|
|
@ -376,7 +410,7 @@ describe('one backtest execution workflow', () => {
|
|||
|
||||
test('the TypeScript backend uses the same runner, data policy, and persisted contract', async () => {
|
||||
const f = await fixture();
|
||||
const services = await typescriptRuntime(f);
|
||||
const services = await composedRuntime(f);
|
||||
try {
|
||||
const result = await services.custom!.BacktestRunner!.runBacktest(config);
|
||||
expect(result.engine).toBe('typescript');
|
||||
|
|
@ -402,7 +436,7 @@ describe('one backtest execution workflow', () => {
|
|||
|
||||
test('the maintained multi-strategy example runs through the composed runner and persists real results', async () => {
|
||||
const f = await fixture();
|
||||
const services = await typescriptRuntime(f);
|
||||
const services = await composedRuntime(f);
|
||||
const runner = services.custom!.BacktestRunner!;
|
||||
cleanup.unshift(async () => {
|
||||
await runner.shutdown();
|
||||
|
|
@ -432,7 +466,7 @@ describe('one backtest execution workflow', () => {
|
|||
|
||||
test('undefined one-timestamp statistics survive normalization, persistence and the public result reader as null', async () => {
|
||||
const f = await fixture(false, {}, 1);
|
||||
const services = await typescriptRuntime(f);
|
||||
const services = await composedRuntime(f);
|
||||
const runner = services.custom!.BacktestRunner!;
|
||||
cleanup.unshift(async () => {
|
||||
await runner.shutdown();
|
||||
|
|
@ -452,7 +486,7 @@ describe('one backtest execution workflow', () => {
|
|||
|
||||
test('TypeScript cancellation is persisted without a partial success or completion event', async () => {
|
||||
const f = await fixture();
|
||||
const services = await typescriptRuntime(f);
|
||||
const services = await composedRuntime(f);
|
||||
const runner = services.custom!.BacktestRunner!;
|
||||
cleanup.unshift(async () => {
|
||||
await runner.shutdown();
|
||||
|
|
@ -485,7 +519,7 @@ describe('one backtest execution workflow', () => {
|
|||
|
||||
test('TypeScript ledger failures are persisted as failures, never fabricated equity or results', async () => {
|
||||
const f = await fixture();
|
||||
const services = await typescriptRuntime(f);
|
||||
const services = await composedRuntime(f);
|
||||
const runner = services.custom!.BacktestRunner!;
|
||||
cleanup.unshift(async () => {
|
||||
await runner.shutdown();
|
||||
|
|
|
|||
|
|
@ -260,7 +260,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
slippage: 0,
|
||||
config: { fastPeriod: 3, slowPeriod: 7 },
|
||||
});
|
||||
const engine = new RustBacktestAdapter({ ...services, custom: { StorageService: storage } });
|
||||
const engine = new RustBacktestAdapter({ logger, storage });
|
||||
const first = await engine.runBacktest(config);
|
||||
const second = await engine.runBacktest(config);
|
||||
expect(first.status).toBe('completed');
|
||||
|
|
@ -282,7 +282,8 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
symbols: [identity.eodSearchCode, other.eodSearchCode],
|
||||
config: { fastPeriod: 3, slowPeriod: 7 },
|
||||
};
|
||||
const engine = new RustBacktestAdapter({ logger, mongodb });
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
const engine = new RustBacktestAdapter({ logger, storage });
|
||||
const first = await engine.runBacktest(config);
|
||||
const second = await engine.runBacktest(config);
|
||||
for (const id of config.symbols) {
|
||||
|
|
@ -321,7 +322,8 @@ describe('deterministic ingestion → storage → native backtest', () => {
|
|||
|
||||
test('empty storage and unknown strategies fail without leaving the engine running', async () => {
|
||||
const { mongodb } = memoryStore();
|
||||
const engine = new RustBacktestAdapter({ logger, mongodb });
|
||||
const storage = new StorageService({ logger }, mongodb, null, null);
|
||||
const engine = new RustBacktestAdapter({ logger, storage });
|
||||
const config = BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
symbols: ['FIXTURE.TEST'],
|
||||
|
|
|
|||
94
test/integration/mode-lifecycle.test.ts
Normal file
94
test/integration/mode-lifecycle.test.ts
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
|
||||
import { config, logger } from '../fixtures/execution';
|
||||
|
||||
function fixture(failAt?: string) {
|
||||
const calls: string[] = [];
|
||||
const failure = new Error('injected shutdown failure');
|
||||
const record = async (step: string) => {
|
||||
calls.push(step);
|
||||
if (step === failAt) throw failure;
|
||||
};
|
||||
const mode = new ModeManager({
|
||||
logger,
|
||||
execution: {
|
||||
initialize: () => record('execution.initialize'),
|
||||
shutdown: () => record('execution.shutdown'),
|
||||
},
|
||||
storage: {
|
||||
initialize: () => record('storage.initialize'),
|
||||
shutdown: () => record('storage.shutdown'),
|
||||
},
|
||||
strategies: {
|
||||
restoreStrategies: () => record('strategies.restore'),
|
||||
shutdown: () => record('strategies.shutdown'),
|
||||
},
|
||||
marketData: {
|
||||
initialize: () => record('market.initialize'),
|
||||
shutdown: () => record('market.shutdown'),
|
||||
},
|
||||
});
|
||||
return { mode, calls, failure };
|
||||
}
|
||||
|
||||
describe('explicit mode lifecycle dependencies', () => {
|
||||
test('paper recovery completes before the feed starts; shutdown drains the feed before strategies and execution', async () => {
|
||||
const f = fixture();
|
||||
await f.mode.initializeMode({ mode: 'paper', startingCapital: 10000 });
|
||||
expect(f.calls).toEqual([
|
||||
'execution.initialize',
|
||||
'storage.initialize',
|
||||
'strategies.restore',
|
||||
'market.initialize',
|
||||
]);
|
||||
await f.mode.shutdown();
|
||||
expect(f.calls.slice(4)).toEqual([
|
||||
'market.shutdown',
|
||||
'strategies.shutdown',
|
||||
'execution.shutdown',
|
||||
'storage.shutdown',
|
||||
]);
|
||||
expect(() => f.mode.getTradingEngine()).toThrow('not initialized');
|
||||
await f.mode.shutdown();
|
||||
expect(f.calls).toHaveLength(8);
|
||||
});
|
||||
|
||||
test('backtest mode replaces the current engine without restoring paper strategies', async () => {
|
||||
const f = fixture();
|
||||
await f.mode.initializeMode(config);
|
||||
const prior = f.mode.getTradingEngine();
|
||||
await f.mode.initializeMode(config);
|
||||
expect(f.mode.getTradingEngine()).not.toBe(prior);
|
||||
expect(f.calls).toEqual([
|
||||
'execution.initialize',
|
||||
'storage.initialize',
|
||||
'market.initialize',
|
||||
'market.shutdown',
|
||||
'strategies.shutdown',
|
||||
'execution.shutdown',
|
||||
'storage.shutdown',
|
||||
'execution.initialize',
|
||||
'storage.initialize',
|
||||
'market.initialize',
|
||||
]);
|
||||
await f.mode.shutdown();
|
||||
});
|
||||
|
||||
test.each(['market.shutdown', 'strategies.shutdown', 'execution.shutdown', 'storage.shutdown'])(
|
||||
'%s failure still closes every other dependency and clears the mode engine',
|
||||
async failAt => {
|
||||
const f = fixture(failAt);
|
||||
await f.mode.initializeMode(config);
|
||||
await expect(f.mode.shutdown()).rejects.toBe(f.failure);
|
||||
expect(f.calls.slice(3)).toEqual([
|
||||
'market.shutdown',
|
||||
'strategies.shutdown',
|
||||
'execution.shutdown',
|
||||
'storage.shutdown',
|
||||
]);
|
||||
expect(() => f.mode.getTradingEngine()).toThrow('not initialized');
|
||||
await f.mode.shutdown();
|
||||
expect(f.calls).toHaveLength(7);
|
||||
}
|
||||
);
|
||||
});
|
||||
|
|
@ -5,12 +5,13 @@ 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, OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||
import type { MarketData } from '../../apps/stock/orchestrator/src/types';
|
||||
import { config, logger, makeExecution, order, quote, start } from '../fixtures/execution';
|
||||
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
|
|
@ -173,7 +174,14 @@ describe('one simulation execution gateway', () => {
|
|||
};
|
||||
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);
|
||||
const lifecycle = { initialize: async () => {}, shutdown: async () => {} };
|
||||
const mode = new ModeManager({
|
||||
logger,
|
||||
marketData: lifecycle,
|
||||
execution,
|
||||
storage: lifecycle,
|
||||
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'
|
||||
|
|
@ -197,11 +205,17 @@ describe('one simulation execution gateway', () => {
|
|||
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;
|
||||
const market: MarketDataService = new MarketDataService({
|
||||
logger,
|
||||
storage: new StorageService({ logger }, null, 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(
|
||||
|
|
|
|||
|
|
@ -29,9 +29,9 @@ import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeMan
|
|||
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy';
|
||||
import { SmaCrossoverStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy';
|
||||
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
|
||||
import type { StrategyConfig } from '../../apps/stock/orchestrator/src/types';
|
||||
import { config, logger, makeExecution, start } from '../fixtures/execution';
|
||||
import { makeStrategyManager } from '../fixtures/strategy-recovery';
|
||||
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
@ -75,10 +75,7 @@ async function runtime(parameters: Record<string, unknown> = {}, name = definiti
|
|||
await f.execution.initialize({ ...config, commission: 0 }, f.engine);
|
||||
cleanup.push(() => f.execution.shutdown());
|
||||
const mode = { getTradingEngine: () => f.engine } as ModeManager;
|
||||
const manager = new StrategyManager({
|
||||
logger,
|
||||
custom: { ExecutionService: f.execution, ModeManager: mode },
|
||||
});
|
||||
const manager = makeStrategyManager({ execution: f.execution, modeManager: mode });
|
||||
cleanup.push(() => manager.shutdown());
|
||||
await manager.initializeStrategies([{ ...definition, name, parameters }]);
|
||||
return { ...f, manager, mode, strategy: manager.getStrategy('sma')! };
|
||||
|
|
@ -269,11 +266,13 @@ describe('explicit strategy contracts and shared planning', () => {
|
|||
test('the TypeScript backend rejects invalid settings before calling a dataset resolver', async () => {
|
||||
const f = await runtime();
|
||||
const storage = new StorageService({ logger }, null, null, null);
|
||||
const backend = new BacktestEngine(
|
||||
{ logger, custom: { ExecutionService: f.execution } },
|
||||
const backend = new BacktestEngine({
|
||||
logger,
|
||||
execution: f.execution,
|
||||
storage,
|
||||
f.manager
|
||||
);
|
||||
strategies: f.manager,
|
||||
getTradingEngine: () => f.engine,
|
||||
});
|
||||
cleanup.push(() => backend.shutdown());
|
||||
let reads = 0;
|
||||
await expect(
|
||||
|
|
|
|||
|
|
@ -1,12 +1,16 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
|
||||
import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies';
|
||||
import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy';
|
||||
import { SmaCrossoverStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy';
|
||||
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
|
||||
import { StrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/StrategyRegistry';
|
||||
import { config, logger, makeExecution, quote } from '../fixtures/execution';
|
||||
import { CounterStrategy, recoveryConfig } from '../fixtures/strategy-recovery';
|
||||
import { config, makeExecution, quote } from '../fixtures/execution';
|
||||
import {
|
||||
CounterStrategy,
|
||||
makeStrategyManager,
|
||||
recoveryConfig,
|
||||
} from '../fixtures/strategy-recovery';
|
||||
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
afterEach(async () => {
|
||||
|
|
@ -23,7 +27,6 @@ async function fixture() {
|
|||
return {
|
||||
execution,
|
||||
dependencies: { modeManager, execution },
|
||||
services: { logger, custom: { ModeManager: modeManager, ExecutionService: execution } },
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -40,18 +43,25 @@ describe('strategy registration and expansion', () => {
|
|||
}
|
||||
);
|
||||
expect(created).toBe(0);
|
||||
const manager = new StrategyManager(f.services, registry);
|
||||
const marketData = new EventEmitter();
|
||||
const manager = makeStrategyManager({ ...f.dependencies, registry, marketData });
|
||||
cleanup.push(() => manager.shutdown());
|
||||
await manager.initializeStrategies([{ ...recoveryConfig, name: ' Custom-Alias ' }]);
|
||||
await manager.onMarketData(quote('first'));
|
||||
expect(marketData.listenerCount('marketDataBatch')).toBe(1);
|
||||
marketData.emit('marketDataBatch', [quote('first')]);
|
||||
await manager.drain();
|
||||
expect((manager.getStrategy('counter') as CounterStrategy).count).toBe(1);
|
||||
await manager.shutdown();
|
||||
const restarted = new StrategyManager(f.services, registry);
|
||||
expect(marketData.listenerCount('marketDataBatch')).toBe(0);
|
||||
const restarted = makeStrategyManager({ ...f.dependencies, registry, marketData });
|
||||
cleanup.push(() => restarted.shutdown());
|
||||
await restarted.restoreStrategies();
|
||||
restarted.setupEventListeners();
|
||||
expect(marketData.listenerCount('marketDataBatch')).toBe(1);
|
||||
expect(created).toBe(2);
|
||||
expect((restarted.getStrategy('counter') as CounterStrategy).count).toBe(1);
|
||||
await restarted.onMarketData(quote('second'));
|
||||
marketData.emit('marketDataBatch', [quote('second')]);
|
||||
await restarted.drain();
|
||||
expect((restarted.getStrategy('counter') as CounterStrategy).count).toBe(2);
|
||||
});
|
||||
|
||||
|
|
@ -103,7 +113,7 @@ describe('strategy registration and expansion', () => {
|
|||
const registry = new StrategyRegistry().register(['fixture'], async () => {
|
||||
throw new Error('factory failed');
|
||||
});
|
||||
const manager = new StrategyManager(f.services, registry);
|
||||
const manager = makeStrategyManager({ ...f.dependencies, registry });
|
||||
cleanup.push(() => manager.shutdown());
|
||||
await expect(manager.initializeStrategies([recoveryConfig])).rejects.toThrow('factory failed');
|
||||
expect(manager.getActiveStrategies()).toEqual([]);
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'
|
|||
import { 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 { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies';
|
||||
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
|
||||
import {
|
||||
BacktestConfigSchema,
|
||||
|
|
@ -29,22 +30,37 @@ afterEach(async () => {
|
|||
for (const close of cleanup.splice(0).reverse()) await close();
|
||||
});
|
||||
async function fixture() {
|
||||
const services: OrchestratorServices = { logger, custom: {} };
|
||||
const services: OrchestratorServices = { logger };
|
||||
const storage = new StorageService(services, null, null, null, {
|
||||
allowSyntheticData: true,
|
||||
syntheticSeed: 42,
|
||||
});
|
||||
const market = new MarketDataService(services);
|
||||
const market: MarketDataService = new MarketDataService({
|
||||
logger,
|
||||
storage,
|
||||
drainStrategies: () => manager.drain(),
|
||||
});
|
||||
const execution = new ExecutionService(services, storage);
|
||||
const manager = new StrategyManager(services);
|
||||
const mode = new ModeManager(services, market, execution, storage);
|
||||
const backend = new BacktestEngine(services, storage, manager);
|
||||
Object.assign(services.custom!, {
|
||||
StorageService: storage,
|
||||
ExecutionService: execution,
|
||||
StrategyManager: manager,
|
||||
ModeManager: mode,
|
||||
MarketDataService: market,
|
||||
const registry = createBuiltinStrategyRegistry();
|
||||
const manager: StrategyManager = new StrategyManager({
|
||||
logger,
|
||||
marketData: market,
|
||||
execution,
|
||||
createStrategy: config => registry.create(config, { execution, modeManager: mode }),
|
||||
});
|
||||
const mode: ModeManager = new ModeManager({
|
||||
logger,
|
||||
marketData: market,
|
||||
execution,
|
||||
storage,
|
||||
strategies: manager,
|
||||
});
|
||||
const backend = new BacktestEngine({
|
||||
logger,
|
||||
storage,
|
||||
strategies: manager,
|
||||
execution,
|
||||
getTradingEngine: () => mode.getTradingEngine(),
|
||||
});
|
||||
await mode.initializeMode(config);
|
||||
cleanup.push(async () => {
|
||||
|
|
|
|||
|
|
@ -143,15 +143,7 @@ async function fixture() {
|
|||
});
|
||||
},
|
||||
} as unknown as StorageService;
|
||||
const engine = new RustBacktestAdapter(
|
||||
{
|
||||
logger,
|
||||
custom: {
|
||||
StorageService: storage,
|
||||
},
|
||||
},
|
||||
{ timeoutMs: 5_000 }
|
||||
);
|
||||
const engine = new RustBacktestAdapter({ logger, storage }, { timeoutMs: 5_000 });
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
engineName: 'native',
|
||||
|
|
|
|||
|
|
@ -11,10 +11,16 @@ import type { ExecutionRepository } from '../../apps/stock/orchestrator/src/exec
|
|||
import { 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 { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies';
|
||||
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
|
||||
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
|
||||
import { logger, makeExecution, quote, start } from '../fixtures/execution';
|
||||
import { attachCounter, CounterStrategy, recoveryConfig } from '../fixtures/strategy-recovery';
|
||||
import {
|
||||
attachCounter,
|
||||
CounterStrategy,
|
||||
makeStrategyManager,
|
||||
recoveryConfig,
|
||||
} from '../fixtures/strategy-recovery';
|
||||
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const cleanup: (() => Promise<void>)[] = [];
|
||||
|
|
@ -89,18 +95,15 @@ describe.skipIf(!url)('strategy recovery on real PostgreSQL', () => {
|
|||
name: 'sma-crossover',
|
||||
parameters: { initialCapital: 10000 },
|
||||
};
|
||||
const prior = new StrategyManager({
|
||||
logger,
|
||||
custom: {
|
||||
ExecutionService: original.execution,
|
||||
ModeManager: { getTradingEngine: () => original.engine } as ModeManager,
|
||||
},
|
||||
const prior = makeStrategyManager({
|
||||
execution: original.execution,
|
||||
modeManager: { getTradingEngine: () => original.engine } as ModeManager,
|
||||
});
|
||||
await prior.initializeStrategies([config]);
|
||||
await prior.onMarketData(quote('one'));
|
||||
await prior.shutdown();
|
||||
await original.execution.enqueueMarketData(quote('two', 100, 100, start + 1));
|
||||
const services: OrchestratorServices = { logger, postgres: f.postgres, custom: {} };
|
||||
const services: OrchestratorServices = { logger, postgres: f.postgres };
|
||||
const storage = new StorageService(services, null, f.postgres, null);
|
||||
const execution = new ExecutionService(services, storage, { clock: f.getTime });
|
||||
let feedStarted = false;
|
||||
|
|
@ -111,15 +114,24 @@ describe.skipIf(!url)('strategy recovery on real PostgreSQL', () => {
|
|||
expect((await execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0);
|
||||
}
|
||||
}
|
||||
const market = new OfflineMarket(services);
|
||||
const manager = new StrategyManager(services),
|
||||
mode = new ModeManager(services, market, execution, storage);
|
||||
Object.assign(services.custom!, {
|
||||
StorageService: storage,
|
||||
ExecutionService: execution,
|
||||
MarketDataService: market,
|
||||
StrategyManager: manager,
|
||||
ModeManager: mode,
|
||||
const market: MarketDataService = new OfflineMarket({
|
||||
logger,
|
||||
storage,
|
||||
drainStrategies: () => manager.drain(),
|
||||
});
|
||||
const registry = createBuiltinStrategyRegistry();
|
||||
const manager: StrategyManager = new StrategyManager({
|
||||
logger,
|
||||
execution,
|
||||
marketData: market,
|
||||
createStrategy: config => registry.create(config, { execution, modeManager: mode }),
|
||||
});
|
||||
const mode: ModeManager = new ModeManager({
|
||||
logger,
|
||||
marketData: market,
|
||||
execution,
|
||||
storage,
|
||||
strategies: manager,
|
||||
});
|
||||
cleanup.push(() => mode.shutdown());
|
||||
await mode.initializeMode({
|
||||
|
|
@ -274,14 +286,10 @@ describe.skipIf(!url)('strategy recovery on real PostgreSQL', () => {
|
|||
};
|
||||
const makeManager = async (account: string) => {
|
||||
const runtime = await f.make(account);
|
||||
const services = {
|
||||
logger,
|
||||
custom: {
|
||||
ExecutionService: runtime.execution,
|
||||
ModeManager: { getTradingEngine: () => runtime.engine } as ModeManager,
|
||||
},
|
||||
};
|
||||
const manager = new StrategyManager(services);
|
||||
const manager = makeStrategyManager({
|
||||
execution: runtime.execution,
|
||||
modeManager: { getTradingEngine: () => runtime.engine } as ModeManager,
|
||||
});
|
||||
await manager.initializeStrategies([smaConfig]);
|
||||
cleanup.push(() => manager.shutdown());
|
||||
return { ...runtime, manager };
|
||||
|
|
@ -340,12 +348,9 @@ describe.skipIf(!url)('strategy recovery on real PostgreSQL', () => {
|
|||
test('uncheckpointed ML paper strategies fail before model startup and migration replay preserves history', async () => {
|
||||
const f = await fixture();
|
||||
const { execution, engine } = await f.make();
|
||||
const manager = new StrategyManager({
|
||||
logger,
|
||||
custom: {
|
||||
ExecutionService: execution,
|
||||
ModeManager: { getTradingEngine: () => engine } as ModeManager,
|
||||
},
|
||||
const manager = makeStrategyManager({
|
||||
execution,
|
||||
modeManager: { getTradingEngine: () => engine } as ModeManager,
|
||||
});
|
||||
cleanup.push(() => manager.shutdown());
|
||||
await expect(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue