feat(research): cut over canonical runtime and enforce agent budgets
This commit is contained in:
parent
ab08db82fd
commit
bbf0dd4453
103 changed files with 6138 additions and 3112 deletions
|
|
@ -1,26 +1,18 @@
|
|||
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';
|
||||
|
|
@ -32,10 +24,8 @@ export function assertSupportedComposition(role: OrchestratorRole, useRustEngine
|
|||
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'
|
||||
);
|
||||
if (!useRustEngine) {
|
||||
throw new Error('Legacy financial execution is retired; the canonical Rust engine is required');
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -51,12 +41,10 @@ export async function registerOrchestratorServices(
|
|||
allowSyntheticData?: boolean;
|
||||
syntheticSeed?: number;
|
||||
nativeExecutionTimeoutMs?: number;
|
||||
strategyRegistry?: StrategyRegistry;
|
||||
canonicalPaper?: PaperConfigurationInput;
|
||||
paperTradingCapital?: number;
|
||||
} = {}
|
||||
): Promise<void> {
|
||||
const role = options.role === undefined ? 'paper' : options.role;
|
||||
const role = options.role === undefined ? 'research-only' : options.role;
|
||||
const useRustEngine = options.useRustEngine === undefined ? true : options.useRustEngine;
|
||||
assertSupportedComposition(role, useRustEngine);
|
||||
if (options.canonicalPaper !== undefined && role !== 'paper') {
|
||||
|
|
@ -66,7 +54,11 @@ export async function registerOrchestratorServices(
|
|||
options.canonicalPaper === undefined
|
||||
? undefined
|
||||
: validatePaperConfiguration(options.canonicalPaper);
|
||||
const allowedMode = role === 'research-only' ? 'backtest' : 'paper';
|
||||
if (role === 'paper' && !canonicalPaper) {
|
||||
throw new Error(
|
||||
'Paper composition requires explicit canonicalPaper configuration; accounts are never migrated automatically'
|
||||
);
|
||||
}
|
||||
|
||||
// Create a service adapter that provides the expected interface
|
||||
const services = container.resolve('serviceContainer') as IServiceContainer;
|
||||
|
|
@ -75,22 +67,18 @@ export async function registerOrchestratorServices(
|
|||
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)))
|
||||
[
|
||||
'CanonicalPaperRuntime',
|
||||
'ModeManager',
|
||||
'ExecutionService',
|
||||
'MarketDataService',
|
||||
'StrategyManager',
|
||||
'PaperTradingManager',
|
||||
'BacktestEngine',
|
||||
'BacktestRunner',
|
||||
].some(key => custom[key as keyof typeof custom] || container.hasRegistration(key))
|
||||
) {
|
||||
throw new Error('Canonical paper requires a fresh runtime composition');
|
||||
throw new Error('Canonical execution requires a fresh runtime composition');
|
||||
}
|
||||
|
||||
// Create storage service first as it's needed by other services
|
||||
|
|
@ -102,181 +90,71 @@ export async function registerOrchestratorServices(
|
|||
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;
|
||||
if (canonicalPaper && !services.postgres) {
|
||||
throw new Error('Canonical paper requires durable PostgreSQL custody');
|
||||
}
|
||||
|
||||
// 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 paper =
|
||||
canonicalPaper && services.postgres
|
||||
? new CanonicalPaperRuntime({
|
||||
repository: new PostgresCanonicalExecutionRepository(services.postgres),
|
||||
programs: canonicalPaper.strategies.map(createBuiltinStrategy),
|
||||
})
|
||||
: undefined;
|
||||
const engine = new RustBacktestAdapter(
|
||||
{ logger: services.logger, storage: storageService },
|
||||
{ timeoutMs: options.nativeExecutionTimeoutMs }
|
||||
);
|
||||
const backtestRunner = new BacktestRunner({
|
||||
engine: backtestEngine,
|
||||
engineName: useRustEngine ? 'native' : 'typescript',
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
engineName: 'native',
|
||||
repository: services.postgres
|
||||
? new PostgresBacktestRunRepository(services.postgres)
|
||||
: new UnavailableBacktestRunRepository(),
|
||||
logger: services.logger,
|
||||
prepare: useRustEngine ? undefined : config => modeManager.initializeMode(config),
|
||||
});
|
||||
|
||||
// Store custom services
|
||||
const analytics = new AnalyticsService(services);
|
||||
// Both roles share canonical research. Only an explicitly configured paper
|
||||
// composition owns account custody; startup never activates it.
|
||||
Object.assign(custom, {
|
||||
StorageService: storageService,
|
||||
MarketDataService: marketDataService,
|
||||
ExecutionService: executionService,
|
||||
AnalyticsService: analyticsService,
|
||||
StrategyManager: strategyManager,
|
||||
BacktestEngine: backtestEngine,
|
||||
BacktestRunner: backtestRunner,
|
||||
PaperTradingManager: paperTradingManager,
|
||||
ModeManager: modeManager,
|
||||
AnalyticsService: analytics,
|
||||
BacktestEngine: engine,
|
||||
BacktestRunner: runner,
|
||||
...(paper ? { CanonicalPaperRuntime: paper } : {}),
|
||||
});
|
||||
|
||||
// Register services in the Awilix container for resolution
|
||||
const orchestratorContainer = container as AwilixContainer<
|
||||
const canonicalContainer = container as AwilixContainer<
|
||||
ServiceDefinitions & {
|
||||
StorageService: StorageService;
|
||||
MarketDataService: MarketDataService;
|
||||
ExecutionService: ExecutionService;
|
||||
AnalyticsService: AnalyticsService;
|
||||
StrategyManager: StrategyManager;
|
||||
CanonicalPaperRuntime: PaperRuntime;
|
||||
BacktestEngine: BacktestExecutionEngine;
|
||||
BacktestRunner: BacktestRunner;
|
||||
PaperTradingManager: PaperTradingManager;
|
||||
ModeManager: ModeManager;
|
||||
orchestratorServices: IServiceContainer;
|
||||
}
|
||||
>;
|
||||
orchestratorContainer.register({
|
||||
canonicalContainer.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),
|
||||
AnalyticsService: asValue(analytics),
|
||||
BacktestEngine: asValue(engine),
|
||||
BacktestRunner: asValue(runner),
|
||||
orchestratorServices: asValue(services),
|
||||
...(paper ? { CanonicalPaperRuntime: asValue(paper) } : {}),
|
||||
});
|
||||
|
||||
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,
|
||||
});
|
||||
try {
|
||||
if (paper && canonicalPaper && options.initializeMode !== false) {
|
||||
await paper.initialize(canonicalPaper);
|
||||
}
|
||||
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 });
|
||||
} catch (error) {
|
||||
await paper?.shutdown().catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
// 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
|
||||
// Kept only as an explicit diagnostic for obsolete integration code.
|
||||
export function getContainer(): IServiceContainer {
|
||||
throw new Error(
|
||||
'Container should be accessed through ServiceApplication. Update your code to use dependency injection.'
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue