diff --git a/README.md b/README.md index b504c0e0..f76df39f 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,15 @@ handler and are released on close/shutdown. Keep runtime composition in `container.ts`; domain code receives explicit capabilities, not the application service container: +Backtest engines, `StrategyManager`, `ModeManager`, and `MarketDataService` receive their +required collaborators directly. The native adapter uses the composed storage instance, +never a fallback it constructs itself. Composition binds strategy factories to the current +mode and provides the feed's strategy-drain callback; factories still receive the existing +`{ modeManager, execution }` contract. `services.custom` remains an HTTP/job/lifecycle adapter +lookup surface, not an internal dependency registry for these components. Direct constructor +callers must supply the explicit dependencies; the strategy manager no longer caches or +exposes the current trading engine, which is owned by `ModeManager`. + - `contracts/` holds runtime validation schemas. Contracts and the native worker protocol cannot load storage, native engines, or server adapters. - `execution/model.ts` owns accounting/risk rules; `execution/repository.ts` is the storage diff --git a/apps/stock/orchestrator/docs/architecture-improvements.md b/apps/stock/orchestrator/docs/architecture-improvements.md index b524bb69..e812262e 100644 --- a/apps/stock/orchestrator/docs/architecture-improvements.md +++ b/apps/stock/orchestrator/docs/architecture-improvements.md @@ -16,6 +16,22 @@ claims, leases, terminal persistence and completion publication. Live routing and native TypeScript callbacks are explicitly unsupported. Do not create another inline executor, call native order submission, or bypass the runner for durable jobs. +## Runtime composition + +`container.ts` creates the runtime graph and binds each required dependency explicitly. +The engines and strategy/mode/market-data lifecycle do not look up peers in `services.custom`. +Both backends receive the same storage instance; the native adapter never constructs one. +The strategy manager accepts a bound `createStrategy` callback instead of loading a registry +or discovering the mode manager. Custom registries supplied through `registerOrchestratorServices` +still receive `{ modeManager, execution }`; no strategy factory or checkpoint migration is needed. + +Deferred callbacks are wired only at composition: market flush awaits strategy delivery, and +factories/backtests obtain the current mode's engine after mode initialization. `ModeManager` +owns that engine; `StrategyManager` no longer caches a second reference or exposes a getter. +Paper restoration still completes before feed startup, and shutdown still flushes the feed +before stopping strategies, execution and storage. HTTP/job adapters retain the existing +application lookup surface, separate from the internal graph. + ## Strategy layout ```text diff --git a/apps/stock/orchestrator/src/backtest/BacktestEngine.ts b/apps/stock/orchestrator/src/backtest/BacktestEngine.ts index 06c2c41a..6fb04aad 100644 --- a/apps/stock/orchestrator/src/backtest/BacktestEngine.ts +++ b/apps/stock/orchestrator/src/backtest/BacktestEngine.ts @@ -1,13 +1,16 @@ import { randomUUID } from 'node:crypto'; import { EventEmitter } from 'node:events'; +import type { TradingEngine } from '@stock-bot/engine'; import { defined } from '@stock-bot/invariants'; +import type { Logger } from '@stock-bot/services'; import { parseBacktestRequest } from '@stock-bot/stock-config/backtest'; import { DataManager } from '../data/DataManager'; import { resolveDataset, type DatasetResolver } from '../data/historical-dataset'; import { amount, decimal } from '../execution/model'; +import type { ExecutionService } from '../services/ExecutionService'; import type { StorageService } from '../services/StorageService'; import type { StrategyManager } from '../strategies/StrategyManager'; -import type { BacktestConfig, OrchestratorServices } from '../types'; +import type { BacktestConfig } from '../types'; import { BacktestMarket } from './BacktestMarket'; import { BacktestPlayback, type PlaybackProgress } from './BacktestPlayback'; import { BacktestReport } from './BacktestReport'; @@ -27,9 +30,13 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng private closing = false; constructor( - private readonly container: OrchestratorServices, - private readonly storageService: StorageService, - private readonly strategyManager: StrategyManager + private readonly dependencies: { + logger: Pick; + storage: Pick; + strategies: Pick; + execution: Pick; + getTradingEngine: () => TradingEngine; + } ) { super(); } @@ -60,12 +67,13 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng resolver?: DatasetResolver ): Promise { const plan = backtestStrategies(config, 'typescript'); - this.container.logger.info('Starting TypeScript backtest', { symbols: config.symbols }); + const { logger, storage, strategies: strategyManager, execution } = this.dependencies; + logger.info('Starting TypeScript backtest', { symbols: config.symbols }); const dataset = await playback.read(() => - resolveDataset(this.storageService, config, resolver, playback.signal) + resolveDataset(storage, config, resolver, playback.signal) ); playback.assertRunning(); - const dataManager = new DataManager(this.storageService); + const dataManager = new DataManager(storage); dataManager.inspectDataset(dataset); const strategies = plan.map(({ name, parameters, index }) => ({ id: name + '-' + index, @@ -75,16 +83,9 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng symbols: config.symbols, allocation: 1 / plan.length, })); - await this.strategyManager.initializeStrategies(strategies); + await strategyManager.initializeStrategies(strategies); playback.assertRunning(); - const trading = defined( - this.strategyManager.getTradingEngine(), - 'Backtest trading engine is not initialized' - ); - const execution = defined( - this.container.custom?.ExecutionService, - 'Backtest execution ledger is not initialized' - ); + const trading = this.dependencies.getTradingEngine(); const market = new BacktestMarket(trading, config.symbols, dataset.manifest.hash); const report = new BacktestReport(config, config.runId ?? randomUUID()); await playback.process( @@ -98,7 +99,7 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng eventId: [dataset.manifest.hash, bar.symbol, bar.timestamp].join(':'), }; market.process(data); - await this.strategyManager.onMarketData(data); + await strategyManager.onMarketData(data); report.record(bar.timestamp, (await execution.getAccount()).equity); }, progress => this.publishProgress(progress) @@ -127,7 +128,7 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng dataManager.getDataQualityReport() ); this.completedReport = report; - this.container.logger.info('TypeScript backtest completed', { trades: result.trades.length }); + logger.info('TypeScript backtest completed', { trades: result.trades.length }); return result; } @@ -135,7 +136,7 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng try { this.emit('progress', progress); } catch (error) { - this.container.logger.error('Backtest progress observer failed', { error }); + this.dependencies.logger.error('Backtest progress observer failed', { error }); } } diff --git a/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts b/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts index cd3b6211..aefe15e5 100644 --- a/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts +++ b/apps/stock/orchestrator/src/backtest/RustBacktestAdapter.ts @@ -1,9 +1,10 @@ import { EventEmitter } from 'node:events'; +import type { Logger } from '@stock-bot/services'; import { parseBacktestRequest } from '@stock-bot/stock-config/backtest'; import { resolveDataset, type DatasetResolver } from '../data/historical-dataset'; import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation'; -import { StorageService } from '../services/StorageService'; -import type { BacktestConfig, OrchestratorServices } from '../types'; +import type { StorageService } from '../services/StorageService'; +import type { BacktestConfig } from '../types'; import { BacktestCancelledError, BacktestTimeoutError, @@ -18,7 +19,6 @@ export type BacktestResult = NativeBacktestResult; /** Storage stays in the parent; all native backtest execution stays in a disposable worker. */ export class RustBacktestAdapter extends EventEmitter implements BacktestExecutionEngine { - private readonly storageService: StorageService; private readonly worker: NativeBacktestWorker; private readonly timeoutMs: number; private active: { controller: AbortController; finished: Promise } | undefined; @@ -27,7 +27,10 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti private currentTime = 0; constructor( - private readonly container: OrchestratorServices, + private readonly dependencies: { + logger: Pick; + storage: Pick; + }, options: { timeoutMs?: number; workerUrl?: URL } = {} ) { super(); @@ -40,14 +43,6 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti throw new Error('Native backtest timeout must be a positive 32-bit integer'); } this.worker = new NativeBacktestWorker(options.workerUrl); - this.storageService = - container.custom?.StorageService ?? - new StorageService( - container, - container.mongodb, - container.postgres, - container.questdb ?? null - ); } async runBacktest( @@ -98,7 +93,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti return result; } catch (error) { if (!(error instanceof BacktestCancelledError)) { - this.container.logger.error('Native backtest failed', { error }); + this.dependencies.logger.error('Native backtest failed', { error }); } if (this.listenerCount('error') > 0) { this.publish('error', error); @@ -118,7 +113,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti resolver?: DatasetResolver ): Promise { signal.throwIfAborted(); - const dataset = await resolveDataset(this.storageService, config, resolver, signal); + const dataset = await resolveDataset(this.dependencies.storage, config, resolver, signal); signal.throwIfAborted(); const data: NativeWorkerRequest['data'] = []; for (const bar of dataset.bars) { @@ -135,7 +130,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti try { this.emit(event, data); } catch (error) { - this.container.logger.error('Native backtest observer failed', { event, error }); + this.dependencies.logger.error('Native backtest observer failed', { event, error }); } } diff --git a/apps/stock/orchestrator/src/container.ts b/apps/stock/orchestrator/src/container.ts index 7f5a57f2..aebf94b9 100644 --- a/apps/stock/orchestrator/src/container.ts +++ b/apps/stock/orchestrator/src/container.ts @@ -13,6 +13,7 @@ import { AnalyticsService } from './services/AnalyticsService'; import { ExecutionService } from './services/ExecutionService'; import { MarketDataService } from './services/MarketDataService'; import { StorageService } from './services/StorageService'; +import { createBuiltinStrategyRegistry } from './strategies/builtin-strategies'; import { StrategyManager } from './strategies/StrategyManager'; import type { StrategyRegistry } from './strategies/StrategyRegistry'; import type { OrchestratorServices as IServiceContainer } from './types'; @@ -47,30 +48,49 @@ export async function registerOrchestratorServices( options ); - // Create other services - const marketDataService = new MarketDataService(services); + // Callbacks are invoked after composition: the feed drains the manager, and + // factories receive the current mode without either service locating its peers. + const marketDataService: MarketDataService = new MarketDataService({ + logger: services.logger, + storage: storageService, + drainStrategies: () => strategyManager.drain(), + }); const executionService = new ExecutionService(services, storageService); const analyticsService = new AnalyticsService(services); - const strategyManager = new StrategyManager(services, options.strategyRegistry); - Object.assign(custom, { StorageService: storageService }); + const registry = options.strategyRegistry ?? createBuiltinStrategyRegistry(); + const strategyManager: StrategyManager = new StrategyManager({ + logger: services.logger, + marketData: marketDataService, + execution: executionService, + createStrategy: config => registry.create(config, { modeManager, execution: executionService }), + }); + const modeManager: ModeManager = new ModeManager({ + logger: services.logger, + marketData: marketDataService, + execution: executionService, + storage: storageService, + strategies: strategyManager, + }); const backtestEngine = options.useRustEngine - ? new RustBacktestAdapter(services, { - timeoutMs: options.nativeExecutionTimeoutMs, - }) - : new BacktestEngine(services, storageService, strategyManager); + ? new RustBacktestAdapter( + { logger: services.logger, storage: storageService }, + { + timeoutMs: options.nativeExecutionTimeoutMs, + } + ) + : new BacktestEngine({ + logger: services.logger, + storage: storageService, + strategies: strategyManager, + execution: executionService, + getTradingEngine: () => modeManager.getTradingEngine(), + }); const paperTradingManager = new PaperTradingManager( services, storageService, marketDataService, executionService ); - const modeManager = new ModeManager( - services, - marketDataService, - executionService, - storageService - ); - const backtestRunner = new BacktestRunner({ engine: backtestEngine, engineName: options.useRustEngine ? 'native' : 'typescript', @@ -82,7 +102,7 @@ export async function registerOrchestratorServices( }); // Store custom services - Object.assign(services.custom ?? {}, { + Object.assign(custom, { StorageService: storageService, MarketDataService: marketDataService, ExecutionService: executionService, @@ -122,12 +142,6 @@ export async function registerOrchestratorServices( orchestratorServices: asValue(services), }); - // Update the serviceContainer to include our custom services - const serviceContainer = container.cradle.serviceContainer; - if (serviceContainer && serviceContainer.custom) { - Object.assign(serviceContainer.custom, services.custom); - } - container .resolve('handlerScanner') .registerHandlerClass(BacktestHandler, { serviceName: 'orchestrator' }); diff --git a/apps/stock/orchestrator/src/core/ModeManager.ts b/apps/stock/orchestrator/src/core/ModeManager.ts index 3ab91b65..570d4304 100644 --- a/apps/stock/orchestrator/src/core/ModeManager.ts +++ b/apps/stock/orchestrator/src/core/ModeManager.ts @@ -1,10 +1,11 @@ import { EventEmitter } from 'events'; import { TradingEngine } from '@stock-bot/engine'; import { defined } from '@stock-bot/invariants'; -import { ExecutionService } from '../services/ExecutionService'; -import { MarketDataService } from '../services/MarketDataService'; -import { StorageService } from '../services/StorageService'; -import type { OrchestratorServices as IServiceContainer } from '../types'; +import type { Logger } from '@stock-bot/services'; +import type { ExecutionService } from '../services/ExecutionService'; +import type { MarketDataService } from '../services/MarketDataService'; +import type { StorageService } from '../services/StorageService'; +import type { StrategyManager } from '../strategies/StrategyManager'; import { BacktestConfigSchema, PaperConfigSchema, @@ -17,16 +18,16 @@ export class ModeManager extends EventEmitter { private config: ModeConfig | null = null; private tradingEngine: TradingEngine | null = null; private isInitialized = false; - private container: IServiceContainer; - constructor( - container: IServiceContainer, - private marketDataService: MarketDataService, - private executionService: ExecutionService, - private storageService: StorageService + private readonly dependencies: { + logger: Pick; + marketData: Pick; + execution: Pick; + storage: Pick; + strategies: Pick; + } ) { super(); - this.container = container; } async initializeMode(config: ModeConfig): Promise { @@ -61,7 +62,7 @@ export class ModeManager extends EventEmitter { this.isInitialized = true; this.emit('modeChanged', config); - this.container.logger.info(`Trading mode initialized: ${config.mode}`); + this.dependencies.logger.info(`Trading mode initialized: ${config.mode}`); } private createEngineConfig(config: ModeConfig) { @@ -104,15 +105,15 @@ export class ModeManager extends EventEmitter { private async initializeServices(config: ModeConfig): Promise { // Configure execution service - await this.executionService.initialize(config, defined(this.tradingEngine)); + await this.dependencies.execution.initialize(config, defined(this.tradingEngine)); // Configure storage - await this.storageService.initialize(config); + await this.dependencies.storage.initialize(config); if (config.mode === 'paper') { - await this.container.custom?.StrategyManager?.restoreStrategies(); + await this.dependencies.strategies.restoreStrategies(); } // Admission is ready before a real-time feed can deliver events. - await this.marketDataService.initialize(config); + await this.dependencies.marketData.initialize(config); } getCurrentMode(): TradingMode { @@ -158,27 +159,27 @@ export class ModeManager extends EventEmitter { return; } - this.container.logger.info(`Shutting down ${this.mode} mode...`); + this.dependencies.logger.info(`Shutting down ${this.mode} mode...`); // Shutdown services let failure: unknown; try { - await this.marketDataService.shutdown(); + await this.dependencies.marketData.shutdown(); } catch (error) { failure = error; } try { - await this.container.custom?.StrategyManager?.shutdown(); + await this.dependencies.strategies.shutdown(); } catch (error) { failure ??= error; } try { - await this.executionService.shutdown(); + await this.dependencies.execution.shutdown(); } catch (error) { failure ??= error; } try { - await this.storageService.shutdown(); + await this.dependencies.storage.shutdown(); } catch (error) { failure ??= error; } diff --git a/apps/stock/orchestrator/src/services/MarketDataService.ts b/apps/stock/orchestrator/src/services/MarketDataService.ts index aa82d477..42d95647 100644 --- a/apps/stock/orchestrator/src/services/MarketDataService.ts +++ b/apps/stock/orchestrator/src/services/MarketDataService.ts @@ -1,7 +1,7 @@ import { EventEmitter } from 'events'; import { io, Socket } from 'socket.io-client'; import { defined } from '@stock-bot/invariants'; -import type { OrchestratorServices as IServiceContainer } from '../types'; +import type { Logger } from '@stock-bot/services'; import { BarSchema, MarketDataSchema, @@ -10,6 +10,7 @@ import { type MarketData, type ModeConfig, } from '../types'; +import type { StorageService } from './StorageService'; export class MarketDataService extends EventEmitter { private mode: 'backtest' | 'paper' | 'live' = 'paper'; @@ -19,11 +20,14 @@ export class MarketDataService extends EventEmitter { private batchTimer: NodeJS.Timeout | null = null; private readonly BATCH_SIZE = 100; private readonly BATCH_INTERVAL_MS = 50; - private container: IServiceContainer; - - constructor(container: IServiceContainer) { + constructor( + private readonly dependencies: { + logger: Pick; + storage: Pick; + drainStrategies: () => Promise; + } + ) { super(); - this.container = container; } async initialize(config: ModeConfig): Promise { @@ -46,7 +50,7 @@ export class MarketDataService extends EventEmitter { }); this.dataIngestionSocket.on('connect', () => { - this.container.logger.info('Connected to data-ingestion service'); + this.dependencies.logger.info('Connected to data-ingestion service'); // Re-subscribe to symbols this.subscriptions.forEach(symbol => { defined(this.dataIngestionSocket).emit('subscribe', { symbol }); @@ -54,7 +58,7 @@ export class MarketDataService extends EventEmitter { }); this.dataIngestionSocket.on('disconnect', () => { - this.container.logger.warn('Disconnected from data-ingestion service'); + this.dependencies.logger.warn('Disconnected from data-ingestion service'); }); this.dataIngestionSocket.on('marketData', data => { @@ -62,7 +66,7 @@ export class MarketDataService extends EventEmitter { }); this.dataIngestionSocket.on('error', error => { - this.container.logger.error('Data ingestion socket error:', error); + this.dependencies.logger.error('Data ingestion socket error:', error); }); } @@ -73,7 +77,7 @@ export class MarketDataService extends EventEmitter { this.dataIngestionSocket.emit('subscribe', { symbol }); } - this.container.logger.debug(`Subscribed to ${symbol}`); + this.dependencies.logger.debug(`Subscribed to ${symbol}`); } async unsubscribeFromSymbol(symbol: string): Promise { @@ -83,7 +87,7 @@ export class MarketDataService extends EventEmitter { this.dataIngestionSocket.emit('unsubscribe', { symbol }); } - this.container.logger.debug(`Unsubscribed from ${symbol}`); + this.dependencies.logger.debug(`Unsubscribed from ${symbol}`); } ingest(input: unknown): void { @@ -91,7 +95,7 @@ export class MarketDataService extends EventEmitter { } async flush(): Promise { this.processBatch(); - await this.container.custom?.StrategyManager?.drain(); + await this.dependencies.drainStrategies(); } private handleMarketData(input: unknown): void { try { @@ -136,7 +140,7 @@ export class MarketDataService extends EventEmitter { }); marketData = { type: 'bar', data: bar }; } else { - this.container.logger.warn('Unknown market data format:', data); + this.dependencies.logger.warn('Unknown market data format:', data); return; } @@ -154,7 +158,7 @@ export class MarketDataService extends EventEmitter { this.batchTimer = setTimeout(() => this.processBatch(), this.BATCH_INTERVAL_MS); } } catch (error) { - this.container.logger.error('Error handling market data:', error); + this.dependencies.logger.error('Error handling market data:', error); } } @@ -182,10 +186,7 @@ export class MarketDataService extends EventEmitter { endTime: Date, interval = '1m' ): Promise { - const storage = defined( - this.container.custom?.StorageService, - 'Historical storage is unavailable' - ); + const { storage } = this.dependencies; const groups = await Promise.all( symbols.map(async symbol => { const bars = await storage.getHistoricalBars(symbol, startTime, endTime, interval); diff --git a/apps/stock/orchestrator/src/strategies/StrategyManager.ts b/apps/stock/orchestrator/src/strategies/StrategyManager.ts index 76e95931..9efcbe93 100644 --- a/apps/stock/orchestrator/src/strategies/StrategyManager.ts +++ b/apps/stock/orchestrator/src/strategies/StrategyManager.ts @@ -1,56 +1,52 @@ import { EventEmitter } from 'events'; -import type { TradingEngine } from '@stock-bot/engine'; -import { defined } from '@stock-bot/invariants'; -import type { OrchestratorServices as IServiceContainer } from '../types'; +import type { Logger } from '@stock-bot/services'; +import type { ExecutionService } from '../services/ExecutionService'; import { type MarketData, type StrategyConfig } from '../types'; -import type { Signal } from './BaseStrategy'; -import { BaseStrategy } from './BaseStrategy'; -import { createBuiltinStrategyRegistry } from './builtin-strategies'; -import type { StrategyRegistry } from './StrategyRegistry'; +import type { BaseStrategy, Signal } from './BaseStrategy'; export class StrategyManager extends EventEmitter { private strategies = new Map(); private activeStrategies = new Set(); - private tradingEngine: TradingEngine | null = null; - private container: IServiceContainer; private delivery: Promise = Promise.resolve(); private listening = false; private recoveryTimer?: ReturnType; - private marketSource?: import('../services/MarketDataService').MarketDataService; private readonly onBatch = (batch: MarketData[]) => { void this.deliverBatch(batch).catch(error => - this.container.logger.error('Market delivery failed', { error }) + this.dependencies.logger.error('Market delivery failed', { error }) ); }; constructor( - container: IServiceContainer, - private readonly registry: StrategyRegistry = createBuiltinStrategyRegistry() + private readonly dependencies: { + logger: Pick; + marketData: Pick; + execution: Pick< + ExecutionService, + | 'requiresDurableCheckpoint' + | 'enqueueMarketData' + | 'recoverStrategies' + | 'registeredStrategies' + | 'registerStrategy' + | 'pauseStrategy' + >; + createStrategy: (config: StrategyConfig) => BaseStrategy | Promise; + } ) { super(); - this.container = container; } setupEventListeners(): void { - const marketDataService = this.container.custom?.MarketDataService; - const executionService = this.container.custom?.ExecutionService; - - if (!marketDataService || !executionService) { - this.container.logger.error('Required services not found in container'); - return; - } - if (this.listening) { return; } this.listening = true; - this.marketSource = marketDataService; + const { marketData: marketDataService, execution: executionService } = this.dependencies; marketDataService.on('marketDataBatch', this.onBatch); // Financial notifications are journal inputs, not volatile observer callbacks. this.recoveryTimer = setInterval(() => { if (executionService.requiresDurableCheckpoint() && this.activeStrategies.size) { void this.recover().catch(error => - this.container.logger.error('Strategy recovery remains pending', { error }) + this.dependencies.logger.error('Strategy recovery remains pending', { error }) ); } }, 1000); @@ -61,7 +57,7 @@ export class StrategyManager extends EventEmitter { const work = this.delivery .catch(() => {}) .then(async () => { - const execution = defined(this.container.custom?.ExecutionService); + const { execution } = this.dependencies; const failures: unknown[] = []; for (const data of batch) { try { @@ -85,7 +81,7 @@ export class StrategyManager extends EventEmitter { const work = this.delivery .catch(() => {}) .then(() => - defined(this.container.custom?.ExecutionService).recoverStrategies( + this.dependencies.execution.recoverStrategies( this.getAllStrategies().filter(s => this.activeStrategies.has(s.getConfig().id)) ) ); @@ -109,12 +105,6 @@ export class StrategyManager extends EventEmitter { this.activeStrategies.clear(); this.setupEventListeners(); - // Get trading engine from mode manager - const modeManager = this.container.custom?.ModeManager; - if (modeManager) { - this.tradingEngine = modeManager.getTradingEngine(); - } - // Initialize new strategies for (const config of configs) { try { @@ -125,9 +115,9 @@ export class StrategyManager extends EventEmitter { await this.enableStrategy(config.id); } - this.container.logger.info(`Initialized strategy: ${config.name} (${config.id})`); + this.dependencies.logger.info(`Initialized strategy: ${config.name} (${config.id})`); } catch (error) { - this.container.logger.error(`Failed to initialize strategy ${config.name}:`, error); + this.dependencies.logger.error(`Failed to initialize strategy ${config.name}:`, error); throw error; } } @@ -135,7 +125,7 @@ export class StrategyManager extends EventEmitter { } async restoreStrategies(): Promise { this.setupEventListeners(); - const configs = await defined(this.container.custom?.ExecutionService).registeredStrategies(); + const configs = await this.dependencies.execution.registeredStrategies(); if (configs.length) { await this.initializeStrategies(configs); } @@ -152,10 +142,7 @@ export class StrategyManager extends EventEmitter { } private async createStrategy(config: StrategyConfig): Promise { - const strategy = await this.registry.create(config, { - modeManager: defined(this.container.custom?.ModeManager), - execution: defined(this.container.custom?.ExecutionService), - }); + const strategy = await this.dependencies.createStrategy(config); // Set up strategy event handlers strategy.on('signal', signal => { @@ -163,7 +150,7 @@ export class StrategyManager extends EventEmitter { }); strategy.on('error', (error: Error) => { - this.container.logger.error(`Strategy ${config.id} error:`, error); + this.dependencies.logger.error(`Strategy ${config.id} error:`, error); }); return strategy; @@ -175,7 +162,7 @@ export class StrategyManager extends EventEmitter { throw new Error(`Strategy ${strategyId} not found`); } - const execution = defined(this.container.custom?.ExecutionService); + const { execution } = this.dependencies; if (execution.requiresDurableCheckpoint() && !strategy.getCheckpointVersion()) { throw new Error('Paper strategies require a versioned checkpoint contract'); } @@ -188,7 +175,7 @@ export class StrategyManager extends EventEmitter { throw error; } this.activeStrategies.add(strategyId); - this.container.logger.info(`Enabled strategy: ${strategyId}`); + this.dependencies.logger.info(`Enabled strategy: ${strategyId}`); } async disableStrategy(strategyId: string): Promise { @@ -198,14 +185,14 @@ export class StrategyManager extends EventEmitter { } // Disable pauses new decisions; pending orders/intents remain explicit ledger work. - await defined(this.container.custom?.ExecutionService).pauseStrategy(strategyId); + await this.dependencies.execution.pauseStrategy(strategyId); await strategy.suspend(); this.activeStrategies.delete(strategyId); - this.container.logger.info(`Disabled strategy: ${strategyId}`); + this.dependencies.logger.info(`Disabled strategy: ${strategyId}`); } private async handleStrategySignal(strategyId: string, signal: Signal): Promise { - this.container.logger.info(`Strategy ${strategyId} generated signal:`, signal); + this.dependencies.logger.info(`Strategy ${strategyId} generated signal:`, signal); // Signals are informational - strategies will convert strong signals to orders } @@ -213,10 +200,6 @@ export class StrategyManager extends EventEmitter { await this.deliverBatch([data]); } - getTradingEngine(): TradingEngine | null { - return this.tradingEngine; - } - getActiveStrategies(): string[] { return Array.from(this.activeStrategies); } @@ -230,11 +213,9 @@ export class StrategyManager extends EventEmitter { } async shutdown(): Promise { - this.container.logger.info('Shutting down strategy manager...'); + this.dependencies.logger.info('Shutting down strategy manager...'); - if (this.marketSource) { - this.marketSource.off('marketDataBatch', this.onBatch); - } + this.dependencies.marketData.off('marketDataBatch', this.onBatch); this.listening = false; if (this.recoveryTimer) { clearInterval(this.recoveryTimer); @@ -243,7 +224,7 @@ export class StrategyManager extends EventEmitter { try { await this.drain(); } catch (error) { - this.container.logger.error('Leaving durable strategy backlog for restart', { error }); + this.dependencies.logger.error('Leaving durable strategy backlog for restart', { error }); } // Disable all strategies for (const strategyId of this.activeStrategies) { @@ -253,6 +234,5 @@ export class StrategyManager extends EventEmitter { // Clear all strategies this.strategies.clear(); this.activeStrategies.clear(); - this.tradingEngine = null; } } diff --git a/scripts/test/architecture.test.ts b/scripts/test/architecture.test.ts index c560f7fd..683f9707 100644 --- a/scripts/test/architecture.test.ts +++ b/scripts/test/architecture.test.ts @@ -76,7 +76,7 @@ describe('orchestrator architecture boundaries', () => { it('the shared backtest contract loads no configuration manager, services or application runtime', async () => { const entry = resolve(root, '../../config/src/contracts/backtest.ts'); expect(runtimeImports(entry).sort()).toEqual(['@stock-bot/types', 'zod']); - const bundle = await Bun.build({ entrypoints: [entry], target: 'browser', write: false }); + const bundle = await Bun.build({ entrypoints: [entry], target: 'browser' }); expect(bundle.success).toBe(true); const code = await bundle.outputs[0]?.text(); expect(code).toBeDefined(); @@ -123,6 +123,29 @@ describe('orchestrator architecture boundaries', () => { ).toEqual(['contracts/strategy-names.ts', 'strategies/StrategyRegistry.ts']); }); + it('backtest and strategy lifecycle collaborators are injected, not located or constructed internally', () => { + for (const file of [ + 'backtest/BacktestEngine.ts', + 'backtest/RustBacktestAdapter.ts', + 'strategies/StrategyManager.ts', + 'core/ModeManager.ts', + 'services/MarketDataService.ts', + ]) { + const source = readFileSync(join(root, file), 'utf8'); + expect(source).not.toMatch(/\b(OrchestratorServices|IServiceContainer)\b/); + const tree = ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true); + function visit(node: ts.Node) { + if (ts.isPropertyAccessExpression(node)) expect(node.name.text).not.toBe('custom'); + if (ts.isElementAccessExpression(node) && ts.isStringLiteral(node.argumentExpression)) { + expect(node.argumentExpression.text).not.toBe('custom'); + } + if (ts.isNewExpression(node)) expect(node.expression.getText(tree)).not.toBe('StorageService'); + ts.forEachChild(node, visit); + } + visit(tree); + } + }); + it('concrete strategies can only be loaded by the registry or other strategy implementations', () => { for (const [file, dependencies] of graph) { const owner = relative(root, file); diff --git a/test/fixtures/backtest-crash-owner.ts b/test/fixtures/backtest-crash-owner.ts index 1822bb96..98f1ca43 100644 --- a/test/fixtures/backtest-crash-owner.ts +++ b/test/fixtures/backtest-crash-owner.ts @@ -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, diff --git a/test/fixtures/strategy-recovery.ts b/test/fixtures/strategy-recovery.ts index beeac304..678227c4 100644 --- a/test/fixtures/strategy-recovery.ts +++ b/test/fixtures/strategy-recovery.ts @@ -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 }; } diff --git a/test/integration/backtest-workflow.test.ts b/test/integration/backtest-workflow.test.ts index 5be19021..72001276 100644 --- a/test/integration/backtest-workflow.test.ts +++ b/test/integration/backtest-workflow.test.ts @@ -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>, - 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(); diff --git a/test/integration/ingestion-backtest.test.ts b/test/integration/ingestion-backtest.test.ts index 0b03e54a..b1630cf5 100644 --- a/test/integration/ingestion-backtest.test.ts +++ b/test/integration/ingestion-backtest.test.ts @@ -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'], diff --git a/test/integration/mode-lifecycle.test.ts b/test/integration/mode-lifecycle.test.ts new file mode 100644 index 00000000..0a485ed8 --- /dev/null +++ b/test/integration/mode-lifecycle.test.ts @@ -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); + } + ); +}); diff --git a/test/integration/order-execution.test.ts b/test/integration/order-execution.test.ts index 25848911..9ba3d9bc 100644 --- a/test/integration/order-execution.test.ts +++ b/test/integration/order-execution.test.ts @@ -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)[] = []; @@ -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( diff --git a/test/integration/strategy-contracts.test.ts b/test/integration/strategy-contracts.test.ts index a526652c..e6515f4e 100644 --- a/test/integration/strategy-contracts.test.ts +++ b/test/integration/strategy-contracts.test.ts @@ -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)[] = []; afterEach(async () => { @@ -75,10 +75,7 @@ async function runtime(parameters: Record = {}, 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( diff --git a/test/integration/strategy-registry.test.ts b/test/integration/strategy-registry.test.ts index 7f05bf19..db8849bb 100644 --- a/test/integration/strategy-registry.test.ts +++ b/test/integration/strategy-registry.test.ts @@ -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)[] = []; 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([]); diff --git a/test/integration/typescript-backtest.test.ts b/test/integration/typescript-backtest.test.ts index 520971f5..aff5b193 100644 --- a/test/integration/typescript-backtest.test.ts +++ b/test/integration/typescript-backtest.test.ts @@ -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 () => { diff --git a/test/postgres/durable-backtest.test.ts b/test/postgres/durable-backtest.test.ts index 551b35a5..7b1323c5 100644 --- a/test/postgres/durable-backtest.test.ts +++ b/test/postgres/durable-backtest.test.ts @@ -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', diff --git a/test/postgres/strategy-recovery.test.ts b/test/postgres/strategy-recovery.test.ts index d27b524d..22da88e7 100644 --- a/test/postgres/strategy-recovery.test.ts +++ b/test/postgres/strategy-recovery.test.ts @@ -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)[] = []; @@ -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(