This commit is contained in:
Boki 2026-10-22 09:46:29 -04:00
parent e4925ecdfe
commit b7aeca4888
20 changed files with 490 additions and 248 deletions

View file

@ -101,6 +101,15 @@ handler and are released on close/shutdown.
Keep runtime composition in `container.ts`; domain code receives explicit capabilities, Keep runtime composition in `container.ts`; domain code receives explicit capabilities,
not the application service container: 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 - `contracts/` holds runtime validation schemas. Contracts and the native worker protocol
cannot load storage, native engines, or server adapters. cannot load storage, native engines, or server adapters.
- `execution/model.ts` owns accounting/risk rules; `execution/repository.ts` is the storage - `execution/model.ts` owns accounting/risk rules; `execution/repository.ts` is the storage

View file

@ -16,6 +16,22 @@ claims, leases, terminal persistence and completion publication.
Live routing and native TypeScript callbacks are explicitly unsupported. Do not create 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. 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 ## Strategy layout
```text ```text

View file

@ -1,13 +1,16 @@
import { randomUUID } from 'node:crypto'; import { randomUUID } from 'node:crypto';
import { EventEmitter } from 'node:events'; import { EventEmitter } from 'node:events';
import type { TradingEngine } from '@stock-bot/engine';
import { defined } from '@stock-bot/invariants'; import { defined } from '@stock-bot/invariants';
import type { Logger } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest'; import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
import { DataManager } from '../data/DataManager'; import { DataManager } from '../data/DataManager';
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset'; import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
import { amount, decimal } from '../execution/model'; import { amount, decimal } from '../execution/model';
import type { ExecutionService } from '../services/ExecutionService';
import type { StorageService } from '../services/StorageService'; import type { StorageService } from '../services/StorageService';
import type { StrategyManager } from '../strategies/StrategyManager'; import type { StrategyManager } from '../strategies/StrategyManager';
import type { BacktestConfig, OrchestratorServices } from '../types'; import type { BacktestConfig } from '../types';
import { BacktestMarket } from './BacktestMarket'; import { BacktestMarket } from './BacktestMarket';
import { BacktestPlayback, type PlaybackProgress } from './BacktestPlayback'; import { BacktestPlayback, type PlaybackProgress } from './BacktestPlayback';
import { BacktestReport } from './BacktestReport'; import { BacktestReport } from './BacktestReport';
@ -27,9 +30,13 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
private closing = false; private closing = false;
constructor( constructor(
private readonly container: OrchestratorServices, private readonly dependencies: {
private readonly storageService: StorageService, logger: Pick<Logger, 'info' | 'error'>;
private readonly strategyManager: StrategyManager storage: Pick<StorageService, 'getHistoricalBars'>;
strategies: Pick<StrategyManager, 'initializeStrategies' | 'onMarketData'>;
execution: Pick<ExecutionService, 'getAccount'>;
getTradingEngine: () => TradingEngine;
}
) { ) {
super(); super();
} }
@ -60,12 +67,13 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
resolver?: DatasetResolver resolver?: DatasetResolver
): Promise<BacktestResult> { ): Promise<BacktestResult> {
const plan = backtestStrategies(config, 'typescript'); 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(() => const dataset = await playback.read(() =>
resolveDataset(this.storageService, config, resolver, playback.signal) resolveDataset(storage, config, resolver, playback.signal)
); );
playback.assertRunning(); playback.assertRunning();
const dataManager = new DataManager(this.storageService); const dataManager = new DataManager(storage);
dataManager.inspectDataset(dataset); dataManager.inspectDataset(dataset);
const strategies = plan.map(({ name, parameters, index }) => ({ const strategies = plan.map(({ name, parameters, index }) => ({
id: name + '-' + index, id: name + '-' + index,
@ -75,16 +83,9 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
symbols: config.symbols, symbols: config.symbols,
allocation: 1 / plan.length, allocation: 1 / plan.length,
})); }));
await this.strategyManager.initializeStrategies(strategies); await strategyManager.initializeStrategies(strategies);
playback.assertRunning(); playback.assertRunning();
const trading = defined( const trading = this.dependencies.getTradingEngine();
this.strategyManager.getTradingEngine(),
'Backtest trading engine is not initialized'
);
const execution = defined(
this.container.custom?.ExecutionService,
'Backtest execution ledger is not initialized'
);
const market = new BacktestMarket(trading, config.symbols, dataset.manifest.hash); const market = new BacktestMarket(trading, config.symbols, dataset.manifest.hash);
const report = new BacktestReport(config, config.runId ?? randomUUID()); const report = new BacktestReport(config, config.runId ?? randomUUID());
await playback.process( await playback.process(
@ -98,7 +99,7 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
eventId: [dataset.manifest.hash, bar.symbol, bar.timestamp].join(':'), eventId: [dataset.manifest.hash, bar.symbol, bar.timestamp].join(':'),
}; };
market.process(data); market.process(data);
await this.strategyManager.onMarketData(data); await strategyManager.onMarketData(data);
report.record(bar.timestamp, (await execution.getAccount()).equity); report.record(bar.timestamp, (await execution.getAccount()).equity);
}, },
progress => this.publishProgress(progress) progress => this.publishProgress(progress)
@ -127,7 +128,7 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
dataManager.getDataQualityReport() dataManager.getDataQualityReport()
); );
this.completedReport = report; 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; return result;
} }
@ -135,7 +136,7 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
try { try {
this.emit('progress', progress); this.emit('progress', progress);
} catch (error) { } catch (error) {
this.container.logger.error('Backtest progress observer failed', { error }); this.dependencies.logger.error('Backtest progress observer failed', { error });
} }
} }

View file

@ -1,9 +1,10 @@
import { EventEmitter } from 'node:events'; import { EventEmitter } from 'node:events';
import type { Logger } from '@stock-bot/services';
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest'; import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset'; import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation'; import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation';
import { StorageService } from '../services/StorageService'; import type { StorageService } from '../services/StorageService';
import type { BacktestConfig, OrchestratorServices } from '../types'; import type { BacktestConfig } from '../types';
import { import {
BacktestCancelledError, BacktestCancelledError,
BacktestTimeoutError, BacktestTimeoutError,
@ -18,7 +19,6 @@ export type BacktestResult = NativeBacktestResult;
/** Storage stays in the parent; all native backtest execution stays in a disposable worker. */ /** Storage stays in the parent; all native backtest execution stays in a disposable worker. */
export class RustBacktestAdapter extends EventEmitter implements BacktestExecutionEngine { export class RustBacktestAdapter extends EventEmitter implements BacktestExecutionEngine {
private readonly storageService: StorageService;
private readonly worker: NativeBacktestWorker; private readonly worker: NativeBacktestWorker;
private readonly timeoutMs: number; private readonly timeoutMs: number;
private active: { controller: AbortController; finished: Promise<void> } | undefined; private active: { controller: AbortController; finished: Promise<void> } | undefined;
@ -27,7 +27,10 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
private currentTime = 0; private currentTime = 0;
constructor( constructor(
private readonly container: OrchestratorServices, private readonly dependencies: {
logger: Pick<Logger, 'error'>;
storage: Pick<StorageService, 'getHistoricalBars'>;
},
options: { timeoutMs?: number; workerUrl?: URL } = {} options: { timeoutMs?: number; workerUrl?: URL } = {}
) { ) {
super(); 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'); throw new Error('Native backtest timeout must be a positive 32-bit integer');
} }
this.worker = new NativeBacktestWorker(options.workerUrl); this.worker = new NativeBacktestWorker(options.workerUrl);
this.storageService =
container.custom?.StorageService ??
new StorageService(
container,
container.mongodb,
container.postgres,
container.questdb ?? null
);
} }
async runBacktest( async runBacktest(
@ -98,7 +93,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
return result; return result;
} catch (error) { } catch (error) {
if (!(error instanceof BacktestCancelledError)) { 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) { if (this.listenerCount('error') > 0) {
this.publish('error', error); this.publish('error', error);
@ -118,7 +113,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
resolver?: DatasetResolver resolver?: DatasetResolver
): Promise<NativeWorkerRequest['data']> { ): Promise<NativeWorkerRequest['data']> {
signal.throwIfAborted(); signal.throwIfAborted();
const dataset = await resolveDataset(this.storageService, config, resolver, signal); const dataset = await resolveDataset(this.dependencies.storage, config, resolver, signal);
signal.throwIfAborted(); signal.throwIfAborted();
const data: NativeWorkerRequest['data'] = []; const data: NativeWorkerRequest['data'] = [];
for (const bar of dataset.bars) { for (const bar of dataset.bars) {
@ -135,7 +130,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
try { try {
this.emit(event, data); this.emit(event, data);
} catch (error) { } catch (error) {
this.container.logger.error('Native backtest observer failed', { event, error }); this.dependencies.logger.error('Native backtest observer failed', { event, error });
} }
} }

View file

@ -13,6 +13,7 @@ import { AnalyticsService } from './services/AnalyticsService';
import { ExecutionService } from './services/ExecutionService'; import { ExecutionService } from './services/ExecutionService';
import { MarketDataService } from './services/MarketDataService'; import { MarketDataService } from './services/MarketDataService';
import { StorageService } from './services/StorageService'; import { StorageService } from './services/StorageService';
import { createBuiltinStrategyRegistry } from './strategies/builtin-strategies';
import { StrategyManager } from './strategies/StrategyManager'; import { StrategyManager } from './strategies/StrategyManager';
import type { StrategyRegistry } from './strategies/StrategyRegistry'; import type { StrategyRegistry } from './strategies/StrategyRegistry';
import type { OrchestratorServices as IServiceContainer } from './types'; import type { OrchestratorServices as IServiceContainer } from './types';
@ -47,30 +48,49 @@ export async function registerOrchestratorServices(
options options
); );
// Create other services // Callbacks are invoked after composition: the feed drains the manager, and
const marketDataService = new MarketDataService(services); // 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 executionService = new ExecutionService(services, storageService);
const analyticsService = new AnalyticsService(services); const analyticsService = new AnalyticsService(services);
const strategyManager = new StrategyManager(services, options.strategyRegistry); const registry = options.strategyRegistry ?? createBuiltinStrategyRegistry();
Object.assign(custom, { StorageService: storageService }); 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 const backtestEngine = options.useRustEngine
? new RustBacktestAdapter(services, { ? new RustBacktestAdapter(
{ logger: services.logger, storage: storageService },
{
timeoutMs: options.nativeExecutionTimeoutMs, timeoutMs: options.nativeExecutionTimeoutMs,
}) }
: new BacktestEngine(services, storageService, strategyManager); )
: new BacktestEngine({
logger: services.logger,
storage: storageService,
strategies: strategyManager,
execution: executionService,
getTradingEngine: () => modeManager.getTradingEngine(),
});
const paperTradingManager = new PaperTradingManager( const paperTradingManager = new PaperTradingManager(
services, services,
storageService, storageService,
marketDataService, marketDataService,
executionService executionService
); );
const modeManager = new ModeManager(
services,
marketDataService,
executionService,
storageService
);
const backtestRunner = new BacktestRunner({ const backtestRunner = new BacktestRunner({
engine: backtestEngine, engine: backtestEngine,
engineName: options.useRustEngine ? 'native' : 'typescript', engineName: options.useRustEngine ? 'native' : 'typescript',
@ -82,7 +102,7 @@ export async function registerOrchestratorServices(
}); });
// Store custom services // Store custom services
Object.assign(services.custom ?? {}, { Object.assign(custom, {
StorageService: storageService, StorageService: storageService,
MarketDataService: marketDataService, MarketDataService: marketDataService,
ExecutionService: executionService, ExecutionService: executionService,
@ -122,12 +142,6 @@ export async function registerOrchestratorServices(
orchestratorServices: asValue(services), 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 container
.resolve('handlerScanner') .resolve('handlerScanner')
.registerHandlerClass(BacktestHandler, { serviceName: 'orchestrator' }); .registerHandlerClass(BacktestHandler, { serviceName: 'orchestrator' });

View file

@ -1,10 +1,11 @@
import { EventEmitter } from 'events'; import { EventEmitter } from 'events';
import { TradingEngine } from '@stock-bot/engine'; import { TradingEngine } from '@stock-bot/engine';
import { defined } from '@stock-bot/invariants'; import { defined } from '@stock-bot/invariants';
import { ExecutionService } from '../services/ExecutionService'; import type { Logger } from '@stock-bot/services';
import { MarketDataService } from '../services/MarketDataService'; import type { ExecutionService } from '../services/ExecutionService';
import { StorageService } from '../services/StorageService'; import type { MarketDataService } from '../services/MarketDataService';
import type { OrchestratorServices as IServiceContainer } from '../types'; import type { StorageService } from '../services/StorageService';
import type { StrategyManager } from '../strategies/StrategyManager';
import { import {
BacktestConfigSchema, BacktestConfigSchema,
PaperConfigSchema, PaperConfigSchema,
@ -17,16 +18,16 @@ export class ModeManager extends EventEmitter {
private config: ModeConfig | null = null; private config: ModeConfig | null = null;
private tradingEngine: TradingEngine | null = null; private tradingEngine: TradingEngine | null = null;
private isInitialized = false; private isInitialized = false;
private container: IServiceContainer;
constructor( constructor(
container: IServiceContainer, private readonly dependencies: {
private marketDataService: MarketDataService, logger: Pick<Logger, 'info'>;
private executionService: ExecutionService, marketData: Pick<MarketDataService, 'initialize' | 'shutdown'>;
private storageService: StorageService execution: Pick<ExecutionService, 'initialize' | 'shutdown'>;
storage: Pick<StorageService, 'initialize' | 'shutdown'>;
strategies: Pick<StrategyManager, 'restoreStrategies' | 'shutdown'>;
}
) { ) {
super(); super();
this.container = container;
} }
async initializeMode(config: ModeConfig): Promise<void> { async initializeMode(config: ModeConfig): Promise<void> {
@ -61,7 +62,7 @@ export class ModeManager extends EventEmitter {
this.isInitialized = true; this.isInitialized = true;
this.emit('modeChanged', config); 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) { private createEngineConfig(config: ModeConfig) {
@ -104,15 +105,15 @@ export class ModeManager extends EventEmitter {
private async initializeServices(config: ModeConfig): Promise<void> { private async initializeServices(config: ModeConfig): Promise<void> {
// Configure execution service // Configure execution service
await this.executionService.initialize(config, defined(this.tradingEngine)); await this.dependencies.execution.initialize(config, defined(this.tradingEngine));
// Configure storage // Configure storage
await this.storageService.initialize(config); await this.dependencies.storage.initialize(config);
if (config.mode === 'paper') { 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. // Admission is ready before a real-time feed can deliver events.
await this.marketDataService.initialize(config); await this.dependencies.marketData.initialize(config);
} }
getCurrentMode(): TradingMode { getCurrentMode(): TradingMode {
@ -158,27 +159,27 @@ export class ModeManager extends EventEmitter {
return; return;
} }
this.container.logger.info(`Shutting down ${this.mode} mode...`); this.dependencies.logger.info(`Shutting down ${this.mode} mode...`);
// Shutdown services // Shutdown services
let failure: unknown; let failure: unknown;
try { try {
await this.marketDataService.shutdown(); await this.dependencies.marketData.shutdown();
} catch (error) { } catch (error) {
failure = error; failure = error;
} }
try { try {
await this.container.custom?.StrategyManager?.shutdown(); await this.dependencies.strategies.shutdown();
} catch (error) { } catch (error) {
failure ??= error; failure ??= error;
} }
try { try {
await this.executionService.shutdown(); await this.dependencies.execution.shutdown();
} catch (error) { } catch (error) {
failure ??= error; failure ??= error;
} }
try { try {
await this.storageService.shutdown(); await this.dependencies.storage.shutdown();
} catch (error) { } catch (error) {
failure ??= error; failure ??= error;
} }

View file

@ -1,7 +1,7 @@
import { EventEmitter } from 'events'; import { EventEmitter } from 'events';
import { io, Socket } from 'socket.io-client'; import { io, Socket } from 'socket.io-client';
import { defined } from '@stock-bot/invariants'; import { defined } from '@stock-bot/invariants';
import type { OrchestratorServices as IServiceContainer } from '../types'; import type { Logger } from '@stock-bot/services';
import { import {
BarSchema, BarSchema,
MarketDataSchema, MarketDataSchema,
@ -10,6 +10,7 @@ import {
type MarketData, type MarketData,
type ModeConfig, type ModeConfig,
} from '../types'; } from '../types';
import type { StorageService } from './StorageService';
export class MarketDataService extends EventEmitter { export class MarketDataService extends EventEmitter {
private mode: 'backtest' | 'paper' | 'live' = 'paper'; private mode: 'backtest' | 'paper' | 'live' = 'paper';
@ -19,11 +20,14 @@ export class MarketDataService extends EventEmitter {
private batchTimer: NodeJS.Timeout | null = null; private batchTimer: NodeJS.Timeout | null = null;
private readonly BATCH_SIZE = 100; private readonly BATCH_SIZE = 100;
private readonly BATCH_INTERVAL_MS = 50; private readonly BATCH_INTERVAL_MS = 50;
private container: IServiceContainer; constructor(
private readonly dependencies: {
constructor(container: IServiceContainer) { logger: Pick<Logger, 'info' | 'warn' | 'error' | 'debug'>;
storage: Pick<StorageService, 'getHistoricalBars'>;
drainStrategies: () => Promise<void>;
}
) {
super(); super();
this.container = container;
} }
async initialize(config: ModeConfig): Promise<void> { async initialize(config: ModeConfig): Promise<void> {
@ -46,7 +50,7 @@ export class MarketDataService extends EventEmitter {
}); });
this.dataIngestionSocket.on('connect', () => { 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 // Re-subscribe to symbols
this.subscriptions.forEach(symbol => { this.subscriptions.forEach(symbol => {
defined(this.dataIngestionSocket).emit('subscribe', { symbol }); defined(this.dataIngestionSocket).emit('subscribe', { symbol });
@ -54,7 +58,7 @@ export class MarketDataService extends EventEmitter {
}); });
this.dataIngestionSocket.on('disconnect', () => { 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 => { this.dataIngestionSocket.on('marketData', data => {
@ -62,7 +66,7 @@ export class MarketDataService extends EventEmitter {
}); });
this.dataIngestionSocket.on('error', error => { 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.dataIngestionSocket.emit('subscribe', { symbol });
} }
this.container.logger.debug(`Subscribed to ${symbol}`); this.dependencies.logger.debug(`Subscribed to ${symbol}`);
} }
async unsubscribeFromSymbol(symbol: string): Promise<void> { async unsubscribeFromSymbol(symbol: string): Promise<void> {
@ -83,7 +87,7 @@ export class MarketDataService extends EventEmitter {
this.dataIngestionSocket.emit('unsubscribe', { symbol }); this.dataIngestionSocket.emit('unsubscribe', { symbol });
} }
this.container.logger.debug(`Unsubscribed from ${symbol}`); this.dependencies.logger.debug(`Unsubscribed from ${symbol}`);
} }
ingest(input: unknown): void { ingest(input: unknown): void {
@ -91,7 +95,7 @@ export class MarketDataService extends EventEmitter {
} }
async flush(): Promise<void> { async flush(): Promise<void> {
this.processBatch(); this.processBatch();
await this.container.custom?.StrategyManager?.drain(); await this.dependencies.drainStrategies();
} }
private handleMarketData(input: unknown): void { private handleMarketData(input: unknown): void {
try { try {
@ -136,7 +140,7 @@ export class MarketDataService extends EventEmitter {
}); });
marketData = { type: 'bar', data: bar }; marketData = { type: 'bar', data: bar };
} else { } else {
this.container.logger.warn('Unknown market data format:', data); this.dependencies.logger.warn('Unknown market data format:', data);
return; return;
} }
@ -154,7 +158,7 @@ export class MarketDataService extends EventEmitter {
this.batchTimer = setTimeout(() => this.processBatch(), this.BATCH_INTERVAL_MS); this.batchTimer = setTimeout(() => this.processBatch(), this.BATCH_INTERVAL_MS);
} }
} catch (error) { } 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, endTime: Date,
interval = '1m' interval = '1m'
): Promise<MarketData[]> { ): Promise<MarketData[]> {
const storage = defined( const { storage } = this.dependencies;
this.container.custom?.StorageService,
'Historical storage is unavailable'
);
const groups = await Promise.all( const groups = await Promise.all(
symbols.map(async symbol => { symbols.map(async symbol => {
const bars = await storage.getHistoricalBars(symbol, startTime, endTime, interval); const bars = await storage.getHistoricalBars(symbol, startTime, endTime, interval);

View file

@ -1,56 +1,52 @@
import { EventEmitter } from 'events'; import { EventEmitter } from 'events';
import type { TradingEngine } from '@stock-bot/engine'; import type { Logger } from '@stock-bot/services';
import { defined } from '@stock-bot/invariants'; import type { ExecutionService } from '../services/ExecutionService';
import type { OrchestratorServices as IServiceContainer } from '../types';
import { type MarketData, type StrategyConfig } from '../types'; import { type MarketData, type StrategyConfig } from '../types';
import type { Signal } from './BaseStrategy'; import type { BaseStrategy, Signal } from './BaseStrategy';
import { BaseStrategy } from './BaseStrategy';
import { createBuiltinStrategyRegistry } from './builtin-strategies';
import type { StrategyRegistry } from './StrategyRegistry';
export class StrategyManager extends EventEmitter { export class StrategyManager extends EventEmitter {
private strategies = new Map<string, BaseStrategy>(); private strategies = new Map<string, BaseStrategy>();
private activeStrategies = new Set<string>(); private activeStrategies = new Set<string>();
private tradingEngine: TradingEngine | null = null;
private container: IServiceContainer;
private delivery: Promise<unknown> = Promise.resolve(); private delivery: Promise<unknown> = Promise.resolve();
private listening = false; private listening = false;
private recoveryTimer?: ReturnType<typeof setInterval>; private recoveryTimer?: ReturnType<typeof setInterval>;
private marketSource?: import('../services/MarketDataService').MarketDataService;
private readonly onBatch = (batch: MarketData[]) => { private readonly onBatch = (batch: MarketData[]) => {
void this.deliverBatch(batch).catch(error => void this.deliverBatch(batch).catch(error =>
this.container.logger.error('Market delivery failed', { error }) this.dependencies.logger.error('Market delivery failed', { error })
); );
}; };
constructor( constructor(
container: IServiceContainer, private readonly dependencies: {
private readonly registry: StrategyRegistry = createBuiltinStrategyRegistry() logger: Pick<Logger, 'info' | 'error'>;
marketData: Pick<EventEmitter, 'on' | 'off'>;
execution: Pick<
ExecutionService,
| 'requiresDurableCheckpoint'
| 'enqueueMarketData'
| 'recoverStrategies'
| 'registeredStrategies'
| 'registerStrategy'
| 'pauseStrategy'
>;
createStrategy: (config: StrategyConfig) => BaseStrategy | Promise<BaseStrategy>;
}
) { ) {
super(); super();
this.container = container;
} }
setupEventListeners(): void { 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) { if (this.listening) {
return; return;
} }
this.listening = true; this.listening = true;
this.marketSource = marketDataService; const { marketData: marketDataService, execution: executionService } = this.dependencies;
marketDataService.on('marketDataBatch', this.onBatch); marketDataService.on('marketDataBatch', this.onBatch);
// Financial notifications are journal inputs, not volatile observer callbacks. // Financial notifications are journal inputs, not volatile observer callbacks.
this.recoveryTimer = setInterval(() => { this.recoveryTimer = setInterval(() => {
if (executionService.requiresDurableCheckpoint() && this.activeStrategies.size) { if (executionService.requiresDurableCheckpoint() && this.activeStrategies.size) {
void this.recover().catch(error => void this.recover().catch(error =>
this.container.logger.error('Strategy recovery remains pending', { error }) this.dependencies.logger.error('Strategy recovery remains pending', { error })
); );
} }
}, 1000); }, 1000);
@ -61,7 +57,7 @@ export class StrategyManager extends EventEmitter {
const work = this.delivery const work = this.delivery
.catch(() => {}) .catch(() => {})
.then(async () => { .then(async () => {
const execution = defined(this.container.custom?.ExecutionService); const { execution } = this.dependencies;
const failures: unknown[] = []; const failures: unknown[] = [];
for (const data of batch) { for (const data of batch) {
try { try {
@ -85,7 +81,7 @@ export class StrategyManager extends EventEmitter {
const work = this.delivery const work = this.delivery
.catch(() => {}) .catch(() => {})
.then(() => .then(() =>
defined(this.container.custom?.ExecutionService).recoverStrategies( this.dependencies.execution.recoverStrategies(
this.getAllStrategies().filter(s => this.activeStrategies.has(s.getConfig().id)) this.getAllStrategies().filter(s => this.activeStrategies.has(s.getConfig().id))
) )
); );
@ -109,12 +105,6 @@ export class StrategyManager extends EventEmitter {
this.activeStrategies.clear(); this.activeStrategies.clear();
this.setupEventListeners(); this.setupEventListeners();
// Get trading engine from mode manager
const modeManager = this.container.custom?.ModeManager;
if (modeManager) {
this.tradingEngine = modeManager.getTradingEngine();
}
// Initialize new strategies // Initialize new strategies
for (const config of configs) { for (const config of configs) {
try { try {
@ -125,9 +115,9 @@ export class StrategyManager extends EventEmitter {
await this.enableStrategy(config.id); 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) { } 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; throw error;
} }
} }
@ -135,7 +125,7 @@ export class StrategyManager extends EventEmitter {
} }
async restoreStrategies(): Promise<void> { async restoreStrategies(): Promise<void> {
this.setupEventListeners(); this.setupEventListeners();
const configs = await defined(this.container.custom?.ExecutionService).registeredStrategies(); const configs = await this.dependencies.execution.registeredStrategies();
if (configs.length) { if (configs.length) {
await this.initializeStrategies(configs); await this.initializeStrategies(configs);
} }
@ -152,10 +142,7 @@ export class StrategyManager extends EventEmitter {
} }
private async createStrategy(config: StrategyConfig): Promise<BaseStrategy> { private async createStrategy(config: StrategyConfig): Promise<BaseStrategy> {
const strategy = await this.registry.create(config, { const strategy = await this.dependencies.createStrategy(config);
modeManager: defined(this.container.custom?.ModeManager),
execution: defined(this.container.custom?.ExecutionService),
});
// Set up strategy event handlers // Set up strategy event handlers
strategy.on('signal', signal => { strategy.on('signal', signal => {
@ -163,7 +150,7 @@ export class StrategyManager extends EventEmitter {
}); });
strategy.on('error', (error: Error) => { 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; return strategy;
@ -175,7 +162,7 @@ export class StrategyManager extends EventEmitter {
throw new Error(`Strategy ${strategyId} not found`); throw new Error(`Strategy ${strategyId} not found`);
} }
const execution = defined(this.container.custom?.ExecutionService); const { execution } = this.dependencies;
if (execution.requiresDurableCheckpoint() && !strategy.getCheckpointVersion()) { if (execution.requiresDurableCheckpoint() && !strategy.getCheckpointVersion()) {
throw new Error('Paper strategies require a versioned checkpoint contract'); throw new Error('Paper strategies require a versioned checkpoint contract');
} }
@ -188,7 +175,7 @@ export class StrategyManager extends EventEmitter {
throw error; throw error;
} }
this.activeStrategies.add(strategyId); this.activeStrategies.add(strategyId);
this.container.logger.info(`Enabled strategy: ${strategyId}`); this.dependencies.logger.info(`Enabled strategy: ${strategyId}`);
} }
async disableStrategy(strategyId: string): Promise<void> { async disableStrategy(strategyId: string): Promise<void> {
@ -198,14 +185,14 @@ export class StrategyManager extends EventEmitter {
} }
// Disable pauses new decisions; pending orders/intents remain explicit ledger work. // 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(); await strategy.suspend();
this.activeStrategies.delete(strategyId); 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<void> { private async handleStrategySignal(strategyId: string, signal: Signal): Promise<void> {
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 // Signals are informational - strategies will convert strong signals to orders
} }
@ -213,10 +200,6 @@ export class StrategyManager extends EventEmitter {
await this.deliverBatch([data]); await this.deliverBatch([data]);
} }
getTradingEngine(): TradingEngine | null {
return this.tradingEngine;
}
getActiveStrategies(): string[] { getActiveStrategies(): string[] {
return Array.from(this.activeStrategies); return Array.from(this.activeStrategies);
} }
@ -230,11 +213,9 @@ export class StrategyManager extends EventEmitter {
} }
async shutdown(): Promise<void> { async shutdown(): Promise<void> {
this.container.logger.info('Shutting down strategy manager...'); this.dependencies.logger.info('Shutting down strategy manager...');
if (this.marketSource) { this.dependencies.marketData.off('marketDataBatch', this.onBatch);
this.marketSource.off('marketDataBatch', this.onBatch);
}
this.listening = false; this.listening = false;
if (this.recoveryTimer) { if (this.recoveryTimer) {
clearInterval(this.recoveryTimer); clearInterval(this.recoveryTimer);
@ -243,7 +224,7 @@ export class StrategyManager extends EventEmitter {
try { try {
await this.drain(); await this.drain();
} catch (error) { } 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 // Disable all strategies
for (const strategyId of this.activeStrategies) { for (const strategyId of this.activeStrategies) {
@ -253,6 +234,5 @@ export class StrategyManager extends EventEmitter {
// Clear all strategies // Clear all strategies
this.strategies.clear(); this.strategies.clear();
this.activeStrategies.clear(); this.activeStrategies.clear();
this.tradingEngine = null;
} }
} }

View file

@ -76,7 +76,7 @@ describe('orchestrator architecture boundaries', () => {
it('the shared backtest contract loads no configuration manager, services or application runtime', async () => { it('the shared backtest contract loads no configuration manager, services or application runtime', async () => {
const entry = resolve(root, '../../config/src/contracts/backtest.ts'); const entry = resolve(root, '../../config/src/contracts/backtest.ts');
expect(runtimeImports(entry).sort()).toEqual(['@stock-bot/types', 'zod']); 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); expect(bundle.success).toBe(true);
const code = await bundle.outputs[0]?.text(); const code = await bundle.outputs[0]?.text();
expect(code).toBeDefined(); expect(code).toBeDefined();
@ -123,6 +123,29 @@ describe('orchestrator architecture boundaries', () => {
).toEqual(['contracts/strategy-names.ts', 'strategies/StrategyRegistry.ts']); ).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', () => { it('concrete strategies can only be loaded by the registry or other strategy implementations', () => {
for (const [file, dependencies] of graph) { for (const [file, dependencies] of graph) {
const owner = relative(root, file); const owner = relative(root, file);

View file

@ -5,6 +5,7 @@ import { PostgreSQLClient } from '@stock-bot/postgres';
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner'; import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository'; import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
setLoggerConfig({ logLevel: 'fatal', logConsole: false }); setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const url = process.env.PIPELINE_TEST_DATABASE_URL; const url = process.env.PIPELINE_TEST_DATABASE_URL;
@ -27,7 +28,10 @@ const postgres = new PostgreSQLClient(
Object.defineProperty(postgres, 'connectionPool', { get: () => pool }); Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
const repository = new PostgresBacktestRunRepository(postgres, 500); const repository = new PostgresBacktestRunRepository(postgres, 500);
const runner = new BacktestRunner({ const runner = new BacktestRunner({
engine: new RustBacktestAdapter({ logger }), engine: new RustBacktestAdapter({
logger,
storage: new StorageService({ logger }, null, null, null),
}),
engineName: 'native', engineName: 'native',
repository, repository,
logger, logger,

View file

@ -1,3 +1,4 @@
import { EventEmitter } from 'node:events';
import { z } from 'zod'; import { z } from 'zod';
import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'; import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
import type { import type {
@ -12,7 +13,12 @@ import {
BaseStrategy, BaseStrategy,
type Signal, type Signal,
} from '../../apps/stock/orchestrator/src/strategies/BaseStrategy'; } 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 { 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 type { MarketData, StrategyConfig } from '../../apps/stock/orchestrator/src/types';
import { logger } from './execution'; import { logger } from './execution';
@ -24,6 +30,20 @@ export const recoveryConfig: StrategyConfig = {
allocation: 1, allocation: 1,
enabled: true, 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 { export class CounterStrategy extends BaseStrategy {
count = 0; count = 0;
equities: number[] = []; equities: number[] = [];
@ -69,8 +89,20 @@ export async function attachCounter(
execution: ExecutionService, execution: ExecutionService,
strategy = new CounterStrategy(execution) strategy = new CounterStrategy(execution)
) { ) {
const manager = new StrategyManager({ logger, custom: { ExecutionService: execution } }); const manager = new StrategyManager({
logger,
execution,
marketData: new EventEmitter(),
createStrategy: () => {
throw new Error('Counter fixtures attach their strategies directly');
},
});
try {
await manager.attachStrategy(strategy); await manager.attachStrategy(strategy);
} catch (error) {
await manager.shutdown();
throw error;
}
return { manager, strategy }; return { manager, strategy };
} }

View file

@ -128,10 +128,7 @@ async function fixture(
); );
} }
const storage = new StorageService({ logger }, mongodb, null, null); const storage = new StorageService({ logger }, mongodb, null, null);
const engine = new RustBacktestAdapter( const engine = new RustBacktestAdapter({ logger, storage }, engineOptions);
{ logger, custom: { StorageService: storage } },
engineOptions
);
const repository = new PostgresBacktestRunRepository(postgres); const repository = new PostgresBacktestRunRepository(postgres);
const runner = new BacktestRunner({ const runner = new BacktestRunner({
engine, engine,
@ -147,9 +144,9 @@ async function fixture(
return { postgres, mongodb, storage, engine, repository, runner, services, routes }; return { postgres, mongodb, storage, engine, repository, runner, services, routes };
} }
async function typescriptRuntime( async function composedRuntime(
f: Awaited<ReturnType<typeof fixture>>, f: Awaited<ReturnType<typeof fixture>>,
strategyRegistry?: StrategyRegistry options: { strategyRegistry?: StrategyRegistry; useRustEngine?: boolean } = {}
) { ) {
const di = await new ServiceContainerBuilder() const di = await new ServiceContainerBuilder()
.withOptions({ .withOptions({
@ -166,23 +163,60 @@ async function typescriptRuntime(
logger, logger,
postgres: f.postgres, postgres: f.postgres,
mongodb: f.mongodb, mongodb: f.mongodb,
custom: {},
}; };
di.register({ serviceContainer: asValue(services) }); di.register({ serviceContainer: asValue(services) });
await registerOrchestratorServices(di, { await registerOrchestratorServices(di, {
initializeMode: false, initializeMode: false,
useRustEngine: false, ...options,
strategyRegistry,
}); });
expect(di.resolve('BacktestRunner')).toBe(services.custom?.BacktestRunner); expect(di.resolve('BacktestRunner')).toBe(services.custom?.BacktestRunner);
return services; return services;
} }
describe('one backtest execution workflow', () => { 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) { for (const backend of ['native', 'typescript'] as const) {
test(`${backend} API runs separate mixed execution settings and replay the original configuration`, async () => { test(`${backend} API runs separate mixed execution settings and replay the original configuration`, async () => {
const f = await fixture(); 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!; const runner = services.custom!.BacktestRunner!;
cleanup.unshift(async () => { cleanup.unshift(async () => {
await runner.shutdown(); await runner.shutdown();
@ -248,7 +282,7 @@ describe('one backtest execution workflow', () => {
return new CounterStrategy(dependencies.execution, definition); return new CounterStrategy(dependencies.execution, definition);
} }
); );
const services = await typescriptRuntime(f, registry); const services = await composedRuntime(f, { strategyRegistry: registry });
const runner = services.custom!.BacktestRunner!; const runner = services.custom!.BacktestRunner!;
cleanup.unshift(async () => { cleanup.unshift(async () => {
await runner.shutdown(); 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 () => { test('the TypeScript backend uses the same runner, data policy, and persisted contract', async () => {
const f = await fixture(); const f = await fixture();
const services = await typescriptRuntime(f); const services = await composedRuntime(f);
try { try {
const result = await services.custom!.BacktestRunner!.runBacktest(config); const result = await services.custom!.BacktestRunner!.runBacktest(config);
expect(result.engine).toBe('typescript'); 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 () => { test('the maintained multi-strategy example runs through the composed runner and persists real results', async () => {
const f = await fixture(); const f = await fixture();
const services = await typescriptRuntime(f); const services = await composedRuntime(f);
const runner = services.custom!.BacktestRunner!; const runner = services.custom!.BacktestRunner!;
cleanup.unshift(async () => { cleanup.unshift(async () => {
await runner.shutdown(); 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 () => { test('undefined one-timestamp statistics survive normalization, persistence and the public result reader as null', async () => {
const f = await fixture(false, {}, 1); const f = await fixture(false, {}, 1);
const services = await typescriptRuntime(f); const services = await composedRuntime(f);
const runner = services.custom!.BacktestRunner!; const runner = services.custom!.BacktestRunner!;
cleanup.unshift(async () => { cleanup.unshift(async () => {
await runner.shutdown(); 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 () => { test('TypeScript cancellation is persisted without a partial success or completion event', async () => {
const f = await fixture(); const f = await fixture();
const services = await typescriptRuntime(f); const services = await composedRuntime(f);
const runner = services.custom!.BacktestRunner!; const runner = services.custom!.BacktestRunner!;
cleanup.unshift(async () => { cleanup.unshift(async () => {
await runner.shutdown(); 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 () => { test('TypeScript ledger failures are persisted as failures, never fabricated equity or results', async () => {
const f = await fixture(); const f = await fixture();
const services = await typescriptRuntime(f); const services = await composedRuntime(f);
const runner = services.custom!.BacktestRunner!; const runner = services.custom!.BacktestRunner!;
cleanup.unshift(async () => { cleanup.unshift(async () => {
await runner.shutdown(); await runner.shutdown();

View file

@ -260,7 +260,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
slippage: 0, slippage: 0,
config: { fastPeriod: 3, slowPeriod: 7 }, 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 first = await engine.runBacktest(config);
const second = await engine.runBacktest(config); const second = await engine.runBacktest(config);
expect(first.status).toBe('completed'); expect(first.status).toBe('completed');
@ -282,7 +282,8 @@ describe('deterministic ingestion → storage → native backtest', () => {
symbols: [identity.eodSearchCode, other.eodSearchCode], symbols: [identity.eodSearchCode, other.eodSearchCode],
config: { fastPeriod: 3, slowPeriod: 7 }, 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 first = await engine.runBacktest(config);
const second = await engine.runBacktest(config); const second = await engine.runBacktest(config);
for (const id of config.symbols) { 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 () => { test('empty storage and unknown strategies fail without leaving the engine running', async () => {
const { mongodb } = memoryStore(); 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({ const config = BacktestConfigSchema.parse({
mode: 'backtest', mode: 'backtest',
symbols: ['FIXTURE.TEST'], symbols: ['FIXTURE.TEST'],

View 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);
}
);
});

View file

@ -5,12 +5,13 @@ import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'
import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/repository'; import { ExecutionConflictError } from '../../apps/stock/orchestrator/src/execution/repository';
import type { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService'; import type { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService';
import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService'; import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService';
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
import { import {
BaseStrategy, BaseStrategy,
type Signal, type Signal,
} from '../../apps/stock/orchestrator/src/strategies/BaseStrategy'; } from '../../apps/stock/orchestrator/src/strategies/BaseStrategy';
import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager'; 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'; import { config, logger, makeExecution, order, quote, start } from '../fixtures/execution';
const cleanup: (() => Promise<void>)[] = []; 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'); await expect(execution.initialize(live, engine)).rejects.toThrow('Live trading is disabled');
expect((await execution.getAccount()).cash).toBe(10000); 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'); await expect(mode.initializeMode(live)).rejects.toThrow('Live trading is disabled');
expect(() => new TradingEngine('live', { broker: 'none', accountId: 'none' })).toThrow( expect(() => new TradingEngine('live', { broker: 'none', accountId: 'none' })).toThrow(
'Live trading is disabled' 'Live trading is disabled'
@ -197,11 +205,17 @@ describe('one simulation execution gateway', () => {
protected async onStop() {} protected async onStop() {}
protected onConfigUpdate() {} protected onConfigUpdate() {}
} }
const services: OrchestratorServices = { logger, custom: { ExecutionService: execution } }; const market: MarketDataService = new MarketDataService({
const market = new MarketDataService(services); logger,
services.custom!.MarketDataService = market; storage: new StorageService({ logger }, null, null, null),
const manager = new StrategyManager(services); drainStrategies: () => manager.drain(),
services.custom!.StrategyManager = manager; });
const manager: StrategyManager = new StrategyManager({
logger,
execution,
marketData: market,
createStrategy: config => new Strategy(config, {} as ModeManager, execution),
});
manager.setupEventListeners(); manager.setupEventListeners();
manager.setupEventListeners(); manager.setupEventListeners();
const strategy = new Strategy( const strategy = new Strategy(

View file

@ -29,9 +29,9 @@ import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeMan
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy'; import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy';
import { SmaCrossoverStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy'; 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 type { StrategyConfig } from '../../apps/stock/orchestrator/src/types';
import { config, logger, makeExecution, start } from '../fixtures/execution'; import { config, logger, makeExecution, start } from '../fixtures/execution';
import { makeStrategyManager } from '../fixtures/strategy-recovery';
const cleanup: (() => Promise<void>)[] = []; const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => { afterEach(async () => {
@ -75,10 +75,7 @@ async function runtime(parameters: Record<string, unknown> = {}, name = definiti
await f.execution.initialize({ ...config, commission: 0 }, f.engine); await f.execution.initialize({ ...config, commission: 0 }, f.engine);
cleanup.push(() => f.execution.shutdown()); cleanup.push(() => f.execution.shutdown());
const mode = { getTradingEngine: () => f.engine } as ModeManager; const mode = { getTradingEngine: () => f.engine } as ModeManager;
const manager = new StrategyManager({ const manager = makeStrategyManager({ execution: f.execution, modeManager: mode });
logger,
custom: { ExecutionService: f.execution, ModeManager: mode },
});
cleanup.push(() => manager.shutdown()); cleanup.push(() => manager.shutdown());
await manager.initializeStrategies([{ ...definition, name, parameters }]); await manager.initializeStrategies([{ ...definition, name, parameters }]);
return { ...f, manager, mode, strategy: manager.getStrategy('sma')! }; 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 () => { test('the TypeScript backend rejects invalid settings before calling a dataset resolver', async () => {
const f = await runtime(); const f = await runtime();
const storage = new StorageService({ logger }, null, null, null); const storage = new StorageService({ logger }, null, null, null);
const backend = new BacktestEngine( const backend = new BacktestEngine({
{ logger, custom: { ExecutionService: f.execution } }, logger,
execution: f.execution,
storage, storage,
f.manager strategies: f.manager,
); getTradingEngine: () => f.engine,
});
cleanup.push(() => backend.shutdown()); cleanup.push(() => backend.shutdown());
let reads = 0; let reads = 0;
await expect( await expect(

View file

@ -1,12 +1,16 @@
import { EventEmitter } from 'node:events';
import { afterEach, describe, expect, test } from 'bun:test'; import { afterEach, describe, expect, test } from 'bun:test';
import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'; import type { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager';
import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies'; import { createBuiltinStrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/builtin-strategies';
import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy'; import { MeanReversionStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/MeanReversionStrategy';
import { SmaCrossoverStrategy } from '../../apps/stock/orchestrator/src/strategies/builtin/SmaCrossoverStrategy'; 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 { StrategyRegistry } from '../../apps/stock/orchestrator/src/strategies/StrategyRegistry';
import { config, logger, makeExecution, quote } from '../fixtures/execution'; import { config, makeExecution, quote } from '../fixtures/execution';
import { CounterStrategy, recoveryConfig } from '../fixtures/strategy-recovery'; import {
CounterStrategy,
makeStrategyManager,
recoveryConfig,
} from '../fixtures/strategy-recovery';
const cleanup: (() => Promise<void>)[] = []; const cleanup: (() => Promise<void>)[] = [];
afterEach(async () => { afterEach(async () => {
@ -23,7 +27,6 @@ async function fixture() {
return { return {
execution, execution,
dependencies: { modeManager, execution }, dependencies: { modeManager, execution },
services: { logger, custom: { ModeManager: modeManager, ExecutionService: execution } },
}; };
} }
@ -40,18 +43,25 @@ describe('strategy registration and expansion', () => {
} }
); );
expect(created).toBe(0); 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()); cleanup.push(() => manager.shutdown());
await manager.initializeStrategies([{ ...recoveryConfig, name: ' Custom-Alias ' }]); 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); expect((manager.getStrategy('counter') as CounterStrategy).count).toBe(1);
await manager.shutdown(); 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()); cleanup.push(() => restarted.shutdown());
await restarted.restoreStrategies(); await restarted.restoreStrategies();
restarted.setupEventListeners();
expect(marketData.listenerCount('marketDataBatch')).toBe(1);
expect(created).toBe(2); expect(created).toBe(2);
expect((restarted.getStrategy('counter') as CounterStrategy).count).toBe(1); 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); 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 () => { const registry = new StrategyRegistry().register(['fixture'], async () => {
throw new Error('factory failed'); throw new Error('factory failed');
}); });
const manager = new StrategyManager(f.services, registry); const manager = makeStrategyManager({ ...f.dependencies, registry });
cleanup.push(() => manager.shutdown()); cleanup.push(() => manager.shutdown());
await expect(manager.initializeStrategies([recoveryConfig])).rejects.toThrow('factory failed'); await expect(manager.initializeStrategies([recoveryConfig])).rejects.toThrow('factory failed');
expect(manager.getActiveStrategies()).toEqual([]); expect(manager.getActiveStrategies()).toEqual([]);

View file

@ -5,6 +5,7 @@ import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'
import { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService'; import { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService';
import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService'; import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService';
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; 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 { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
import { import {
BacktestConfigSchema, BacktestConfigSchema,
@ -29,22 +30,37 @@ afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) await close(); for (const close of cleanup.splice(0).reverse()) await close();
}); });
async function fixture() { async function fixture() {
const services: OrchestratorServices = { logger, custom: {} }; const services: OrchestratorServices = { logger };
const storage = new StorageService(services, null, null, null, { const storage = new StorageService(services, null, null, null, {
allowSyntheticData: true, allowSyntheticData: true,
syntheticSeed: 42, syntheticSeed: 42,
}); });
const market = new MarketDataService(services); const market: MarketDataService = new MarketDataService({
logger,
storage,
drainStrategies: () => manager.drain(),
});
const execution = new ExecutionService(services, storage); const execution = new ExecutionService(services, storage);
const manager = new StrategyManager(services); const registry = createBuiltinStrategyRegistry();
const mode = new ModeManager(services, market, execution, storage); const manager: StrategyManager = new StrategyManager({
const backend = new BacktestEngine(services, storage, manager); logger,
Object.assign(services.custom!, { marketData: market,
StorageService: storage, execution,
ExecutionService: execution, createStrategy: config => registry.create(config, { execution, modeManager: mode }),
StrategyManager: manager, });
ModeManager: mode, const mode: ModeManager = new ModeManager({
MarketDataService: market, logger,
marketData: market,
execution,
storage,
strategies: manager,
});
const backend = new BacktestEngine({
logger,
storage,
strategies: manager,
execution,
getTradingEngine: () => mode.getTradingEngine(),
}); });
await mode.initializeMode(config); await mode.initializeMode(config);
cleanup.push(async () => { cleanup.push(async () => {

View file

@ -143,15 +143,7 @@ async function fixture() {
}); });
}, },
} as unknown as StorageService; } as unknown as StorageService;
const engine = new RustBacktestAdapter( const engine = new RustBacktestAdapter({ logger, storage }, { timeoutMs: 5_000 });
{
logger,
custom: {
StorageService: storage,
},
},
{ timeoutMs: 5_000 }
);
const runner = new BacktestRunner({ const runner = new BacktestRunner({
engine, engine,
engineName: 'native', engineName: 'native',

View file

@ -11,10 +11,16 @@ import type { ExecutionRepository } from '../../apps/stock/orchestrator/src/exec
import { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService'; import { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService';
import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService'; import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService';
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; 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 { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager';
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types'; import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { logger, makeExecution, quote, start } from '../fixtures/execution'; 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 url = process.env.PIPELINE_TEST_DATABASE_URL;
const cleanup: (() => Promise<void>)[] = []; const cleanup: (() => Promise<void>)[] = [];
@ -89,18 +95,15 @@ describe.skipIf(!url)('strategy recovery on real PostgreSQL', () => {
name: 'sma-crossover', name: 'sma-crossover',
parameters: { initialCapital: 10000 }, parameters: { initialCapital: 10000 },
}; };
const prior = new StrategyManager({ const prior = makeStrategyManager({
logger, execution: original.execution,
custom: { modeManager: { getTradingEngine: () => original.engine } as ModeManager,
ExecutionService: original.execution,
ModeManager: { getTradingEngine: () => original.engine } as ModeManager,
},
}); });
await prior.initializeStrategies([config]); await prior.initializeStrategies([config]);
await prior.onMarketData(quote('one')); await prior.onMarketData(quote('one'));
await prior.shutdown(); await prior.shutdown();
await original.execution.enqueueMarketData(quote('two', 100, 100, start + 1)); 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 storage = new StorageService(services, null, f.postgres, null);
const execution = new ExecutionService(services, storage, { clock: f.getTime }); const execution = new ExecutionService(services, storage, { clock: f.getTime });
let feedStarted = false; let feedStarted = false;
@ -111,15 +114,24 @@ describe.skipIf(!url)('strategy recovery on real PostgreSQL', () => {
expect((await execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0); expect((await execution.getRecoveryStatus()).strategies[0]?.lag).toBe(0);
} }
} }
const market = new OfflineMarket(services); const market: MarketDataService = new OfflineMarket({
const manager = new StrategyManager(services), logger,
mode = new ModeManager(services, market, execution, storage); storage,
Object.assign(services.custom!, { drainStrategies: () => manager.drain(),
StorageService: storage, });
ExecutionService: execution, const registry = createBuiltinStrategyRegistry();
MarketDataService: market, const manager: StrategyManager = new StrategyManager({
StrategyManager: manager, logger,
ModeManager: mode, 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()); cleanup.push(() => mode.shutdown());
await mode.initializeMode({ await mode.initializeMode({
@ -274,14 +286,10 @@ describe.skipIf(!url)('strategy recovery on real PostgreSQL', () => {
}; };
const makeManager = async (account: string) => { const makeManager = async (account: string) => {
const runtime = await f.make(account); const runtime = await f.make(account);
const services = { const manager = makeStrategyManager({
logger, execution: runtime.execution,
custom: { modeManager: { getTradingEngine: () => runtime.engine } as ModeManager,
ExecutionService: runtime.execution, });
ModeManager: { getTradingEngine: () => runtime.engine } as ModeManager,
},
};
const manager = new StrategyManager(services);
await manager.initializeStrategies([smaConfig]); await manager.initializeStrategies([smaConfig]);
cleanup.push(() => manager.shutdown()); cleanup.push(() => manager.shutdown());
return { ...runtime, manager }; 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 () => { test('uncheckpointed ML paper strategies fail before model startup and migration replay preserves history', async () => {
const f = await fixture(); const f = await fixture();
const { execution, engine } = await f.make(); const { execution, engine } = await f.make();
const manager = new StrategyManager({ const manager = makeStrategyManager({
logger, execution,
custom: { modeManager: { getTradingEngine: () => engine } as ModeManager,
ExecutionService: execution,
ModeManager: { getTradingEngine: () => engine } as ModeManager,
},
}); });
cleanup.push(() => manager.shutdown()); cleanup.push(() => manager.shutdown());
await expect( await expect(