stock-bot/apps/stock/orchestrator/src/container.ts

284 lines
11 KiB
TypeScript

import { asValue, type AwilixContainer } from 'awilix';
import type { ServiceCradle as ServiceDefinitions } from '@stock-bot/di';
import { BacktestEngine } from './backtest/BacktestEngine';
import { BacktestRunner } from './backtest/BacktestRunner';
import type { BacktestExecutionEngine } from './backtest/execution-engine';
import { PostgresBacktestRunRepository } from './backtest/PostgresBacktestRunRepository';
import { UnavailableBacktestRunRepository } from './backtest/run-repository';
import { RustBacktestAdapter } from './backtest/RustBacktestAdapter';
import type { PaperConfigurationInput, PaperRuntime } from './contracts/paper-runtime';
import { ModeManager } from './core/ModeManager';
import { PostgresCanonicalExecutionRepository } from './execution/PostgresCanonicalExecutionRepository';
import { BacktestHandler } from './handlers/backtest/backtest.handler';
import { CanonicalPaperRuntime } from './paper/CanonicalPaperRuntime';
import { validatePaperConfiguration } from './paper/feed';
import { PaperTradingManager } from './paper/PaperTradingManager';
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 { createBuiltinStrategy } from './strategies/canonical-builtins';
import { StrategyManager } from './strategies/StrategyManager';
import type { StrategyRegistry } from './strategies/StrategyRegistry';
import type { OrchestratorServices as IServiceContainer } from './types';
export type OrchestratorRole = 'paper' | 'research-only';
export function assertSupportedComposition(role: OrchestratorRole, useRustEngine: boolean): void {
if (role !== 'paper' && role !== 'research-only') {
throw new Error('Unsupported runtime role: expected paper or research-only');
}
if (typeof useRustEngine !== 'boolean') {
throw new Error('Runtime useRustEngine option must be a boolean');
}
if (role !== 'research-only' && !useRustEngine) {
throw new Error(
'Unsupported runtime combination: TypeScript backtests require a research-only composition; paper requires the isolated native engine'
);
}
}
/**
* Register orchestrator-specific services in the DI container
*/
export async function registerOrchestratorServices(
container: AwilixContainer<ServiceDefinitions>,
options: {
role?: OrchestratorRole;
initializeMode?: boolean;
useRustEngine?: boolean;
allowSyntheticData?: boolean;
syntheticSeed?: number;
nativeExecutionTimeoutMs?: number;
strategyRegistry?: StrategyRegistry;
canonicalPaper?: PaperConfigurationInput;
paperTradingCapital?: number;
} = {}
): Promise<void> {
const role = options.role === undefined ? 'paper' : options.role;
const useRustEngine = options.useRustEngine === undefined ? true : options.useRustEngine;
assertSupportedComposition(role, useRustEngine);
if (options.canonicalPaper !== undefined && role !== 'paper') {
throw new Error('Canonical paper configuration requires a paper composition');
}
const canonicalPaper =
options.canonicalPaper === undefined
? undefined
: validatePaperConfiguration(options.canonicalPaper);
const allowedMode = role === 'research-only' ? 'backtest' : 'paper';
// Create a service adapter that provides the expected interface
const services = container.resolve('serviceContainer') as IServiceContainer;
const custom = services.custom ?? {};
if (!services.custom) {
Object.defineProperty(services, 'custom', { value: custom, enumerable: true });
}
if (
custom.CanonicalPaperRuntime ||
container.hasRegistration('CanonicalPaperRuntime') ||
(canonicalPaper &&
(
[
'ModeManager',
'ExecutionService',
'MarketDataService',
'StrategyManager',
'PaperTradingManager',
'BacktestEngine',
'BacktestRunner',
] as const
).some(key => custom[key] || container.hasRegistration(key)))
) {
throw new Error('Canonical paper requires a fresh runtime composition');
}
// Create storage service first as it's needed by other services
const storageService = new StorageService(
services,
services.mongodb,
services.postgres,
services.questdb || null,
options
);
if (canonicalPaper) {
if (!services.postgres) {
throw new Error('Canonical paper requires durable PostgreSQL custody');
}
const paper = new CanonicalPaperRuntime({
repository: new PostgresCanonicalExecutionRepository(services.postgres),
programs: canonicalPaper.strategies.map(createBuiltinStrategy),
});
const engine = new RustBacktestAdapter(
{ logger: services.logger, storage: storageService },
{ timeoutMs: options.nativeExecutionTimeoutMs }
);
const runner = new BacktestRunner({
engine,
engineName: 'native',
repository: new PostgresBacktestRunRepository(services.postgres),
logger: services.logger,
});
const analytics = new AnalyticsService(services);
// No legacy order gateway, feed listener or mode initializer is exposed in
// this composition. Research still runs in the existing isolated worker.
Object.assign(custom, {
StorageService: storageService,
AnalyticsService: analytics,
CanonicalPaperRuntime: paper,
BacktestEngine: engine,
BacktestRunner: runner,
});
const canonicalContainer = container as AwilixContainer<
ServiceDefinitions & {
StorageService: StorageService;
AnalyticsService: AnalyticsService;
CanonicalPaperRuntime: PaperRuntime;
BacktestEngine: BacktestExecutionEngine;
BacktestRunner: BacktestRunner;
orchestratorServices: IServiceContainer;
}
>;
canonicalContainer.register({
StorageService: asValue(storageService),
AnalyticsService: asValue(analytics),
CanonicalPaperRuntime: asValue(paper),
BacktestEngine: asValue(engine),
BacktestRunner: asValue(runner),
orchestratorServices: asValue(services),
});
container
.resolve('handlerScanner')
.registerHandlerClass(BacktestHandler, { serviceName: 'orchestrator' });
try {
if (options.initializeMode !== false) {
await paper.initialize(canonicalPaper);
}
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 });
} catch (error) {
await paper.shutdown().catch(() => {});
throw error;
}
return;
}
// 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, { allowedMode });
const analyticsService = new AnalyticsService(services);
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({
allowedMode,
logger: services.logger,
marketData: marketDataService,
execution: executionService,
storage: storageService,
strategies: strategyManager,
});
const backtestEngine = useRustEngine
? 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 backtestRunner = new BacktestRunner({
engine: backtestEngine,
engineName: useRustEngine ? 'native' : 'typescript',
repository: services.postgres
? new PostgresBacktestRunRepository(services.postgres)
: new UnavailableBacktestRunRepository(),
logger: services.logger,
prepare: useRustEngine ? undefined : config => modeManager.initializeMode(config),
});
// Store custom services
Object.assign(custom, {
StorageService: storageService,
MarketDataService: marketDataService,
ExecutionService: executionService,
AnalyticsService: analyticsService,
StrategyManager: strategyManager,
BacktestEngine: backtestEngine,
BacktestRunner: backtestRunner,
PaperTradingManager: paperTradingManager,
ModeManager: modeManager,
});
// Register services in the Awilix container for resolution
const orchestratorContainer = container as AwilixContainer<
ServiceDefinitions & {
StorageService: StorageService;
MarketDataService: MarketDataService;
ExecutionService: ExecutionService;
AnalyticsService: AnalyticsService;
StrategyManager: StrategyManager;
BacktestEngine: BacktestExecutionEngine;
BacktestRunner: BacktestRunner;
PaperTradingManager: PaperTradingManager;
ModeManager: ModeManager;
orchestratorServices: IServiceContainer;
}
>;
orchestratorContainer.register({
StorageService: asValue(storageService),
MarketDataService: asValue(marketDataService),
ExecutionService: asValue(executionService),
AnalyticsService: asValue(analyticsService),
StrategyManager: asValue(strategyManager),
BacktestEngine: asValue(backtestEngine),
BacktestRunner: asValue(backtestRunner),
PaperTradingManager: asValue(paperTradingManager),
ModeManager: asValue(modeManager),
orchestratorServices: asValue(services),
});
container
.resolve('handlerScanner')
.registerHandlerClass(BacktestHandler, { serviceName: 'orchestrator' });
// Setup event listeners after all services are registered
strategyManager.setupEventListeners();
// Initialize mode manager with default paper trading mode
if (role === 'paper' && options.initializeMode !== false) {
await modeManager.initializeMode({
mode: 'paper',
startingCapital: options.paperTradingCapital ?? 100000,
});
}
// Start job consumption only after the shared graph and initial mode are ready.
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 });
}
// For backward compatibility, export a container getter
export function getContainer(): IServiceContainer {
throw new Error(
'Container should be accessed through ServiceApplication. Update your code to use dependency injection.'
);
}