cleanup
This commit is contained in:
parent
e4925ecdfe
commit
b7aeca4888
20 changed files with 490 additions and 248 deletions
|
|
@ -16,6 +16,22 @@ claims, leases, terminal persistence and completion publication.
|
|||
Live routing and native TypeScript callbacks are explicitly unsupported. Do not create
|
||||
another inline executor, call native order submission, or bypass the runner for durable jobs.
|
||||
|
||||
## Runtime composition
|
||||
|
||||
`container.ts` creates the runtime graph and binds each required dependency explicitly.
|
||||
The engines and strategy/mode/market-data lifecycle do not look up peers in `services.custom`.
|
||||
Both backends receive the same storage instance; the native adapter never constructs one.
|
||||
The strategy manager accepts a bound `createStrategy` callback instead of loading a registry
|
||||
or discovering the mode manager. Custom registries supplied through `registerOrchestratorServices`
|
||||
still receive `{ modeManager, execution }`; no strategy factory or checkpoint migration is needed.
|
||||
|
||||
Deferred callbacks are wired only at composition: market flush awaits strategy delivery, and
|
||||
factories/backtests obtain the current mode's engine after mode initialization. `ModeManager`
|
||||
owns that engine; `StrategyManager` no longer caches a second reference or exposes a getter.
|
||||
Paper restoration still completes before feed startup, and shutdown still flushes the feed
|
||||
before stopping strategies, execution and storage. HTTP/job adapters retain the existing
|
||||
application lookup surface, separate from the internal graph.
|
||||
|
||||
## Strategy layout
|
||||
|
||||
```text
|
||||
|
|
|
|||
|
|
@ -1,13 +1,16 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import type { TradingEngine } from '@stock-bot/engine';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import type { Logger } from '@stock-bot/services';
|
||||
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||
import { DataManager } from '../data/DataManager';
|
||||
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
||||
import { amount, decimal } from '../execution/model';
|
||||
import type { ExecutionService } from '../services/ExecutionService';
|
||||
import type { StorageService } from '../services/StorageService';
|
||||
import type { StrategyManager } from '../strategies/StrategyManager';
|
||||
import type { BacktestConfig, OrchestratorServices } from '../types';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import { BacktestMarket } from './BacktestMarket';
|
||||
import { BacktestPlayback, type PlaybackProgress } from './BacktestPlayback';
|
||||
import { BacktestReport } from './BacktestReport';
|
||||
|
|
@ -27,9 +30,13 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
|||
private closing = false;
|
||||
|
||||
constructor(
|
||||
private readonly container: OrchestratorServices,
|
||||
private readonly storageService: StorageService,
|
||||
private readonly strategyManager: StrategyManager
|
||||
private readonly dependencies: {
|
||||
logger: Pick<Logger, 'info' | 'error'>;
|
||||
storage: Pick<StorageService, 'getHistoricalBars'>;
|
||||
strategies: Pick<StrategyManager, 'initializeStrategies' | 'onMarketData'>;
|
||||
execution: Pick<ExecutionService, 'getAccount'>;
|
||||
getTradingEngine: () => TradingEngine;
|
||||
}
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
|
@ -60,12 +67,13 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
|||
resolver?: DatasetResolver
|
||||
): Promise<BacktestResult> {
|
||||
const plan = backtestStrategies(config, 'typescript');
|
||||
this.container.logger.info('Starting TypeScript backtest', { symbols: config.symbols });
|
||||
const { logger, storage, strategies: strategyManager, execution } = this.dependencies;
|
||||
logger.info('Starting TypeScript backtest', { symbols: config.symbols });
|
||||
const dataset = await playback.read(() =>
|
||||
resolveDataset(this.storageService, config, resolver, playback.signal)
|
||||
resolveDataset(storage, config, resolver, playback.signal)
|
||||
);
|
||||
playback.assertRunning();
|
||||
const dataManager = new DataManager(this.storageService);
|
||||
const dataManager = new DataManager(storage);
|
||||
dataManager.inspectDataset(dataset);
|
||||
const strategies = plan.map(({ name, parameters, index }) => ({
|
||||
id: name + '-' + index,
|
||||
|
|
@ -75,16 +83,9 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
|||
symbols: config.symbols,
|
||||
allocation: 1 / plan.length,
|
||||
}));
|
||||
await this.strategyManager.initializeStrategies(strategies);
|
||||
await strategyManager.initializeStrategies(strategies);
|
||||
playback.assertRunning();
|
||||
const trading = defined(
|
||||
this.strategyManager.getTradingEngine(),
|
||||
'Backtest trading engine is not initialized'
|
||||
);
|
||||
const execution = defined(
|
||||
this.container.custom?.ExecutionService,
|
||||
'Backtest execution ledger is not initialized'
|
||||
);
|
||||
const trading = this.dependencies.getTradingEngine();
|
||||
const market = new BacktestMarket(trading, config.symbols, dataset.manifest.hash);
|
||||
const report = new BacktestReport(config, config.runId ?? randomUUID());
|
||||
await playback.process(
|
||||
|
|
@ -98,7 +99,7 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
|||
eventId: [dataset.manifest.hash, bar.symbol, bar.timestamp].join(':'),
|
||||
};
|
||||
market.process(data);
|
||||
await this.strategyManager.onMarketData(data);
|
||||
await strategyManager.onMarketData(data);
|
||||
report.record(bar.timestamp, (await execution.getAccount()).equity);
|
||||
},
|
||||
progress => this.publishProgress(progress)
|
||||
|
|
@ -127,7 +128,7 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
|||
dataManager.getDataQualityReport()
|
||||
);
|
||||
this.completedReport = report;
|
||||
this.container.logger.info('TypeScript backtest completed', { trades: result.trades.length });
|
||||
logger.info('TypeScript backtest completed', { trades: result.trades.length });
|
||||
return result;
|
||||
}
|
||||
|
||||
|
|
@ -135,7 +136,7 @@ export class BacktestEngine extends EventEmitter implements BacktestExecutionEng
|
|||
try {
|
||||
this.emit('progress', progress);
|
||||
} catch (error) {
|
||||
this.container.logger.error('Backtest progress observer failed', { error });
|
||||
this.dependencies.logger.error('Backtest progress observer failed', { error });
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
import { EventEmitter } from 'node:events';
|
||||
import type { Logger } from '@stock-bot/services';
|
||||
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||
import { resolveDataset, type DatasetResolver } from '../data/historical-dataset';
|
||||
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation';
|
||||
import { StorageService } from '../services/StorageService';
|
||||
import type { BacktestConfig, OrchestratorServices } from '../types';
|
||||
import type { StorageService } from '../services/StorageService';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import {
|
||||
BacktestCancelledError,
|
||||
BacktestTimeoutError,
|
||||
|
|
@ -18,7 +19,6 @@ export type BacktestResult = NativeBacktestResult;
|
|||
|
||||
/** Storage stays in the parent; all native backtest execution stays in a disposable worker. */
|
||||
export class RustBacktestAdapter extends EventEmitter implements BacktestExecutionEngine {
|
||||
private readonly storageService: StorageService;
|
||||
private readonly worker: NativeBacktestWorker;
|
||||
private readonly timeoutMs: number;
|
||||
private active: { controller: AbortController; finished: Promise<void> } | undefined;
|
||||
|
|
@ -27,7 +27,10 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
private currentTime = 0;
|
||||
|
||||
constructor(
|
||||
private readonly container: OrchestratorServices,
|
||||
private readonly dependencies: {
|
||||
logger: Pick<Logger, 'error'>;
|
||||
storage: Pick<StorageService, 'getHistoricalBars'>;
|
||||
},
|
||||
options: { timeoutMs?: number; workerUrl?: URL } = {}
|
||||
) {
|
||||
super();
|
||||
|
|
@ -40,14 +43,6 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
throw new Error('Native backtest timeout must be a positive 32-bit integer');
|
||||
}
|
||||
this.worker = new NativeBacktestWorker(options.workerUrl);
|
||||
this.storageService =
|
||||
container.custom?.StorageService ??
|
||||
new StorageService(
|
||||
container,
|
||||
container.mongodb,
|
||||
container.postgres,
|
||||
container.questdb ?? null
|
||||
);
|
||||
}
|
||||
|
||||
async runBacktest(
|
||||
|
|
@ -98,7 +93,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
return result;
|
||||
} catch (error) {
|
||||
if (!(error instanceof BacktestCancelledError)) {
|
||||
this.container.logger.error('Native backtest failed', { error });
|
||||
this.dependencies.logger.error('Native backtest failed', { error });
|
||||
}
|
||||
if (this.listenerCount('error') > 0) {
|
||||
this.publish('error', error);
|
||||
|
|
@ -118,7 +113,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
resolver?: DatasetResolver
|
||||
): Promise<NativeWorkerRequest['data']> {
|
||||
signal.throwIfAborted();
|
||||
const dataset = await resolveDataset(this.storageService, config, resolver, signal);
|
||||
const dataset = await resolveDataset(this.dependencies.storage, config, resolver, signal);
|
||||
signal.throwIfAborted();
|
||||
const data: NativeWorkerRequest['data'] = [];
|
||||
for (const bar of dataset.bars) {
|
||||
|
|
@ -135,7 +130,7 @@ export class RustBacktestAdapter extends EventEmitter implements BacktestExecuti
|
|||
try {
|
||||
this.emit(event, data);
|
||||
} catch (error) {
|
||||
this.container.logger.error('Native backtest observer failed', { event, error });
|
||||
this.dependencies.logger.error('Native backtest observer failed', { event, error });
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import { AnalyticsService } from './services/AnalyticsService';
|
|||
import { ExecutionService } from './services/ExecutionService';
|
||||
import { MarketDataService } from './services/MarketDataService';
|
||||
import { StorageService } from './services/StorageService';
|
||||
import { createBuiltinStrategyRegistry } from './strategies/builtin-strategies';
|
||||
import { StrategyManager } from './strategies/StrategyManager';
|
||||
import type { StrategyRegistry } from './strategies/StrategyRegistry';
|
||||
import type { OrchestratorServices as IServiceContainer } from './types';
|
||||
|
|
@ -47,30 +48,49 @@ export async function registerOrchestratorServices(
|
|||
options
|
||||
);
|
||||
|
||||
// Create other services
|
||||
const marketDataService = new MarketDataService(services);
|
||||
// Callbacks are invoked after composition: the feed drains the manager, and
|
||||
// factories receive the current mode without either service locating its peers.
|
||||
const marketDataService: MarketDataService = new MarketDataService({
|
||||
logger: services.logger,
|
||||
storage: storageService,
|
||||
drainStrategies: () => strategyManager.drain(),
|
||||
});
|
||||
const executionService = new ExecutionService(services, storageService);
|
||||
const analyticsService = new AnalyticsService(services);
|
||||
const strategyManager = new StrategyManager(services, options.strategyRegistry);
|
||||
Object.assign(custom, { StorageService: storageService });
|
||||
const registry = options.strategyRegistry ?? createBuiltinStrategyRegistry();
|
||||
const strategyManager: StrategyManager = new StrategyManager({
|
||||
logger: services.logger,
|
||||
marketData: marketDataService,
|
||||
execution: executionService,
|
||||
createStrategy: config => registry.create(config, { modeManager, execution: executionService }),
|
||||
});
|
||||
const modeManager: ModeManager = new ModeManager({
|
||||
logger: services.logger,
|
||||
marketData: marketDataService,
|
||||
execution: executionService,
|
||||
storage: storageService,
|
||||
strategies: strategyManager,
|
||||
});
|
||||
const backtestEngine = options.useRustEngine
|
||||
? new RustBacktestAdapter(services, {
|
||||
timeoutMs: options.nativeExecutionTimeoutMs,
|
||||
})
|
||||
: new BacktestEngine(services, storageService, strategyManager);
|
||||
? new RustBacktestAdapter(
|
||||
{ logger: services.logger, storage: storageService },
|
||||
{
|
||||
timeoutMs: options.nativeExecutionTimeoutMs,
|
||||
}
|
||||
)
|
||||
: new BacktestEngine({
|
||||
logger: services.logger,
|
||||
storage: storageService,
|
||||
strategies: strategyManager,
|
||||
execution: executionService,
|
||||
getTradingEngine: () => modeManager.getTradingEngine(),
|
||||
});
|
||||
const paperTradingManager = new PaperTradingManager(
|
||||
services,
|
||||
storageService,
|
||||
marketDataService,
|
||||
executionService
|
||||
);
|
||||
const modeManager = new ModeManager(
|
||||
services,
|
||||
marketDataService,
|
||||
executionService,
|
||||
storageService
|
||||
);
|
||||
|
||||
const backtestRunner = new BacktestRunner({
|
||||
engine: backtestEngine,
|
||||
engineName: options.useRustEngine ? 'native' : 'typescript',
|
||||
|
|
@ -82,7 +102,7 @@ export async function registerOrchestratorServices(
|
|||
});
|
||||
|
||||
// Store custom services
|
||||
Object.assign(services.custom ?? {}, {
|
||||
Object.assign(custom, {
|
||||
StorageService: storageService,
|
||||
MarketDataService: marketDataService,
|
||||
ExecutionService: executionService,
|
||||
|
|
@ -122,12 +142,6 @@ export async function registerOrchestratorServices(
|
|||
orchestratorServices: asValue(services),
|
||||
});
|
||||
|
||||
// Update the serviceContainer to include our custom services
|
||||
const serviceContainer = container.cradle.serviceContainer;
|
||||
if (serviceContainer && serviceContainer.custom) {
|
||||
Object.assign(serviceContainer.custom, services.custom);
|
||||
}
|
||||
|
||||
container
|
||||
.resolve('handlerScanner')
|
||||
.registerHandlerClass(BacktestHandler, { serviceName: 'orchestrator' });
|
||||
|
|
|
|||
|
|
@ -1,10 +1,11 @@
|
|||
import { EventEmitter } from 'events';
|
||||
import { TradingEngine } from '@stock-bot/engine';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import { ExecutionService } from '../services/ExecutionService';
|
||||
import { MarketDataService } from '../services/MarketDataService';
|
||||
import { StorageService } from '../services/StorageService';
|
||||
import type { OrchestratorServices as IServiceContainer } from '../types';
|
||||
import type { Logger } from '@stock-bot/services';
|
||||
import type { ExecutionService } from '../services/ExecutionService';
|
||||
import type { MarketDataService } from '../services/MarketDataService';
|
||||
import type { StorageService } from '../services/StorageService';
|
||||
import type { StrategyManager } from '../strategies/StrategyManager';
|
||||
import {
|
||||
BacktestConfigSchema,
|
||||
PaperConfigSchema,
|
||||
|
|
@ -17,16 +18,16 @@ export class ModeManager extends EventEmitter {
|
|||
private config: ModeConfig | null = null;
|
||||
private tradingEngine: TradingEngine | null = null;
|
||||
private isInitialized = false;
|
||||
private container: IServiceContainer;
|
||||
|
||||
constructor(
|
||||
container: IServiceContainer,
|
||||
private marketDataService: MarketDataService,
|
||||
private executionService: ExecutionService,
|
||||
private storageService: StorageService
|
||||
private readonly dependencies: {
|
||||
logger: Pick<Logger, 'info'>;
|
||||
marketData: Pick<MarketDataService, 'initialize' | 'shutdown'>;
|
||||
execution: Pick<ExecutionService, 'initialize' | 'shutdown'>;
|
||||
storage: Pick<StorageService, 'initialize' | 'shutdown'>;
|
||||
strategies: Pick<StrategyManager, 'restoreStrategies' | 'shutdown'>;
|
||||
}
|
||||
) {
|
||||
super();
|
||||
this.container = container;
|
||||
}
|
||||
|
||||
async initializeMode(config: ModeConfig): Promise<void> {
|
||||
|
|
@ -61,7 +62,7 @@ export class ModeManager extends EventEmitter {
|
|||
this.isInitialized = true;
|
||||
this.emit('modeChanged', config);
|
||||
|
||||
this.container.logger.info(`Trading mode initialized: ${config.mode}`);
|
||||
this.dependencies.logger.info(`Trading mode initialized: ${config.mode}`);
|
||||
}
|
||||
|
||||
private createEngineConfig(config: ModeConfig) {
|
||||
|
|
@ -104,15 +105,15 @@ export class ModeManager extends EventEmitter {
|
|||
|
||||
private async initializeServices(config: ModeConfig): Promise<void> {
|
||||
// Configure execution service
|
||||
await this.executionService.initialize(config, defined(this.tradingEngine));
|
||||
await this.dependencies.execution.initialize(config, defined(this.tradingEngine));
|
||||
|
||||
// Configure storage
|
||||
await this.storageService.initialize(config);
|
||||
await this.dependencies.storage.initialize(config);
|
||||
if (config.mode === 'paper') {
|
||||
await this.container.custom?.StrategyManager?.restoreStrategies();
|
||||
await this.dependencies.strategies.restoreStrategies();
|
||||
}
|
||||
// Admission is ready before a real-time feed can deliver events.
|
||||
await this.marketDataService.initialize(config);
|
||||
await this.dependencies.marketData.initialize(config);
|
||||
}
|
||||
|
||||
getCurrentMode(): TradingMode {
|
||||
|
|
@ -158,27 +159,27 @@ export class ModeManager extends EventEmitter {
|
|||
return;
|
||||
}
|
||||
|
||||
this.container.logger.info(`Shutting down ${this.mode} mode...`);
|
||||
this.dependencies.logger.info(`Shutting down ${this.mode} mode...`);
|
||||
|
||||
// Shutdown services
|
||||
let failure: unknown;
|
||||
try {
|
||||
await this.marketDataService.shutdown();
|
||||
await this.dependencies.marketData.shutdown();
|
||||
} catch (error) {
|
||||
failure = error;
|
||||
}
|
||||
try {
|
||||
await this.container.custom?.StrategyManager?.shutdown();
|
||||
await this.dependencies.strategies.shutdown();
|
||||
} catch (error) {
|
||||
failure ??= error;
|
||||
}
|
||||
try {
|
||||
await this.executionService.shutdown();
|
||||
await this.dependencies.execution.shutdown();
|
||||
} catch (error) {
|
||||
failure ??= error;
|
||||
}
|
||||
try {
|
||||
await this.storageService.shutdown();
|
||||
await this.dependencies.storage.shutdown();
|
||||
} catch (error) {
|
||||
failure ??= error;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { EventEmitter } from 'events';
|
||||
import { io, Socket } from 'socket.io-client';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import type { OrchestratorServices as IServiceContainer } from '../types';
|
||||
import type { Logger } from '@stock-bot/services';
|
||||
import {
|
||||
BarSchema,
|
||||
MarketDataSchema,
|
||||
|
|
@ -10,6 +10,7 @@ import {
|
|||
type MarketData,
|
||||
type ModeConfig,
|
||||
} from '../types';
|
||||
import type { StorageService } from './StorageService';
|
||||
|
||||
export class MarketDataService extends EventEmitter {
|
||||
private mode: 'backtest' | 'paper' | 'live' = 'paper';
|
||||
|
|
@ -19,11 +20,14 @@ export class MarketDataService extends EventEmitter {
|
|||
private batchTimer: NodeJS.Timeout | null = null;
|
||||
private readonly BATCH_SIZE = 100;
|
||||
private readonly BATCH_INTERVAL_MS = 50;
|
||||
private container: IServiceContainer;
|
||||
|
||||
constructor(container: IServiceContainer) {
|
||||
constructor(
|
||||
private readonly dependencies: {
|
||||
logger: Pick<Logger, 'info' | 'warn' | 'error' | 'debug'>;
|
||||
storage: Pick<StorageService, 'getHistoricalBars'>;
|
||||
drainStrategies: () => Promise<void>;
|
||||
}
|
||||
) {
|
||||
super();
|
||||
this.container = container;
|
||||
}
|
||||
|
||||
async initialize(config: ModeConfig): Promise<void> {
|
||||
|
|
@ -46,7 +50,7 @@ export class MarketDataService extends EventEmitter {
|
|||
});
|
||||
|
||||
this.dataIngestionSocket.on('connect', () => {
|
||||
this.container.logger.info('Connected to data-ingestion service');
|
||||
this.dependencies.logger.info('Connected to data-ingestion service');
|
||||
// Re-subscribe to symbols
|
||||
this.subscriptions.forEach(symbol => {
|
||||
defined(this.dataIngestionSocket).emit('subscribe', { symbol });
|
||||
|
|
@ -54,7 +58,7 @@ export class MarketDataService extends EventEmitter {
|
|||
});
|
||||
|
||||
this.dataIngestionSocket.on('disconnect', () => {
|
||||
this.container.logger.warn('Disconnected from data-ingestion service');
|
||||
this.dependencies.logger.warn('Disconnected from data-ingestion service');
|
||||
});
|
||||
|
||||
this.dataIngestionSocket.on('marketData', data => {
|
||||
|
|
@ -62,7 +66,7 @@ export class MarketDataService extends EventEmitter {
|
|||
});
|
||||
|
||||
this.dataIngestionSocket.on('error', error => {
|
||||
this.container.logger.error('Data ingestion socket error:', error);
|
||||
this.dependencies.logger.error('Data ingestion socket error:', error);
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -73,7 +77,7 @@ export class MarketDataService extends EventEmitter {
|
|||
this.dataIngestionSocket.emit('subscribe', { symbol });
|
||||
}
|
||||
|
||||
this.container.logger.debug(`Subscribed to ${symbol}`);
|
||||
this.dependencies.logger.debug(`Subscribed to ${symbol}`);
|
||||
}
|
||||
|
||||
async unsubscribeFromSymbol(symbol: string): Promise<void> {
|
||||
|
|
@ -83,7 +87,7 @@ export class MarketDataService extends EventEmitter {
|
|||
this.dataIngestionSocket.emit('unsubscribe', { symbol });
|
||||
}
|
||||
|
||||
this.container.logger.debug(`Unsubscribed from ${symbol}`);
|
||||
this.dependencies.logger.debug(`Unsubscribed from ${symbol}`);
|
||||
}
|
||||
|
||||
ingest(input: unknown): void {
|
||||
|
|
@ -91,7 +95,7 @@ export class MarketDataService extends EventEmitter {
|
|||
}
|
||||
async flush(): Promise<void> {
|
||||
this.processBatch();
|
||||
await this.container.custom?.StrategyManager?.drain();
|
||||
await this.dependencies.drainStrategies();
|
||||
}
|
||||
private handleMarketData(input: unknown): void {
|
||||
try {
|
||||
|
|
@ -136,7 +140,7 @@ export class MarketDataService extends EventEmitter {
|
|||
});
|
||||
marketData = { type: 'bar', data: bar };
|
||||
} else {
|
||||
this.container.logger.warn('Unknown market data format:', data);
|
||||
this.dependencies.logger.warn('Unknown market data format:', data);
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -154,7 +158,7 @@ export class MarketDataService extends EventEmitter {
|
|||
this.batchTimer = setTimeout(() => this.processBatch(), this.BATCH_INTERVAL_MS);
|
||||
}
|
||||
} catch (error) {
|
||||
this.container.logger.error('Error handling market data:', error);
|
||||
this.dependencies.logger.error('Error handling market data:', error);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -182,10 +186,7 @@ export class MarketDataService extends EventEmitter {
|
|||
endTime: Date,
|
||||
interval = '1m'
|
||||
): Promise<MarketData[]> {
|
||||
const storage = defined(
|
||||
this.container.custom?.StorageService,
|
||||
'Historical storage is unavailable'
|
||||
);
|
||||
const { storage } = this.dependencies;
|
||||
const groups = await Promise.all(
|
||||
symbols.map(async symbol => {
|
||||
const bars = await storage.getHistoricalBars(symbol, startTime, endTime, interval);
|
||||
|
|
|
|||
|
|
@ -1,56 +1,52 @@
|
|||
import { EventEmitter } from 'events';
|
||||
import type { TradingEngine } from '@stock-bot/engine';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import type { OrchestratorServices as IServiceContainer } from '../types';
|
||||
import type { Logger } from '@stock-bot/services';
|
||||
import type { ExecutionService } from '../services/ExecutionService';
|
||||
import { type MarketData, type StrategyConfig } from '../types';
|
||||
import type { Signal } from './BaseStrategy';
|
||||
import { BaseStrategy } from './BaseStrategy';
|
||||
import { createBuiltinStrategyRegistry } from './builtin-strategies';
|
||||
import type { StrategyRegistry } from './StrategyRegistry';
|
||||
import type { BaseStrategy, Signal } from './BaseStrategy';
|
||||
|
||||
export class StrategyManager extends EventEmitter {
|
||||
private strategies = new Map<string, BaseStrategy>();
|
||||
private activeStrategies = new Set<string>();
|
||||
private tradingEngine: TradingEngine | null = null;
|
||||
private container: IServiceContainer;
|
||||
private delivery: Promise<unknown> = Promise.resolve();
|
||||
private listening = false;
|
||||
private recoveryTimer?: ReturnType<typeof setInterval>;
|
||||
private marketSource?: import('../services/MarketDataService').MarketDataService;
|
||||
private readonly onBatch = (batch: MarketData[]) => {
|
||||
void this.deliverBatch(batch).catch(error =>
|
||||
this.container.logger.error('Market delivery failed', { error })
|
||||
this.dependencies.logger.error('Market delivery failed', { error })
|
||||
);
|
||||
};
|
||||
|
||||
constructor(
|
||||
container: IServiceContainer,
|
||||
private readonly registry: StrategyRegistry = createBuiltinStrategyRegistry()
|
||||
private readonly dependencies: {
|
||||
logger: Pick<Logger, 'info' | 'error'>;
|
||||
marketData: Pick<EventEmitter, 'on' | 'off'>;
|
||||
execution: Pick<
|
||||
ExecutionService,
|
||||
| 'requiresDurableCheckpoint'
|
||||
| 'enqueueMarketData'
|
||||
| 'recoverStrategies'
|
||||
| 'registeredStrategies'
|
||||
| 'registerStrategy'
|
||||
| 'pauseStrategy'
|
||||
>;
|
||||
createStrategy: (config: StrategyConfig) => BaseStrategy | Promise<BaseStrategy>;
|
||||
}
|
||||
) {
|
||||
super();
|
||||
this.container = container;
|
||||
}
|
||||
|
||||
setupEventListeners(): void {
|
||||
const marketDataService = this.container.custom?.MarketDataService;
|
||||
const executionService = this.container.custom?.ExecutionService;
|
||||
|
||||
if (!marketDataService || !executionService) {
|
||||
this.container.logger.error('Required services not found in container');
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.listening) {
|
||||
return;
|
||||
}
|
||||
this.listening = true;
|
||||
this.marketSource = marketDataService;
|
||||
const { marketData: marketDataService, execution: executionService } = this.dependencies;
|
||||
marketDataService.on('marketDataBatch', this.onBatch);
|
||||
// Financial notifications are journal inputs, not volatile observer callbacks.
|
||||
this.recoveryTimer = setInterval(() => {
|
||||
if (executionService.requiresDurableCheckpoint() && this.activeStrategies.size) {
|
||||
void this.recover().catch(error =>
|
||||
this.container.logger.error('Strategy recovery remains pending', { error })
|
||||
this.dependencies.logger.error('Strategy recovery remains pending', { error })
|
||||
);
|
||||
}
|
||||
}, 1000);
|
||||
|
|
@ -61,7 +57,7 @@ export class StrategyManager extends EventEmitter {
|
|||
const work = this.delivery
|
||||
.catch(() => {})
|
||||
.then(async () => {
|
||||
const execution = defined(this.container.custom?.ExecutionService);
|
||||
const { execution } = this.dependencies;
|
||||
const failures: unknown[] = [];
|
||||
for (const data of batch) {
|
||||
try {
|
||||
|
|
@ -85,7 +81,7 @@ export class StrategyManager extends EventEmitter {
|
|||
const work = this.delivery
|
||||
.catch(() => {})
|
||||
.then(() =>
|
||||
defined(this.container.custom?.ExecutionService).recoverStrategies(
|
||||
this.dependencies.execution.recoverStrategies(
|
||||
this.getAllStrategies().filter(s => this.activeStrategies.has(s.getConfig().id))
|
||||
)
|
||||
);
|
||||
|
|
@ -109,12 +105,6 @@ export class StrategyManager extends EventEmitter {
|
|||
this.activeStrategies.clear();
|
||||
this.setupEventListeners();
|
||||
|
||||
// Get trading engine from mode manager
|
||||
const modeManager = this.container.custom?.ModeManager;
|
||||
if (modeManager) {
|
||||
this.tradingEngine = modeManager.getTradingEngine();
|
||||
}
|
||||
|
||||
// Initialize new strategies
|
||||
for (const config of configs) {
|
||||
try {
|
||||
|
|
@ -125,9 +115,9 @@ export class StrategyManager extends EventEmitter {
|
|||
await this.enableStrategy(config.id);
|
||||
}
|
||||
|
||||
this.container.logger.info(`Initialized strategy: ${config.name} (${config.id})`);
|
||||
this.dependencies.logger.info(`Initialized strategy: ${config.name} (${config.id})`);
|
||||
} catch (error) {
|
||||
this.container.logger.error(`Failed to initialize strategy ${config.name}:`, error);
|
||||
this.dependencies.logger.error(`Failed to initialize strategy ${config.name}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
|
@ -135,7 +125,7 @@ export class StrategyManager extends EventEmitter {
|
|||
}
|
||||
async restoreStrategies(): Promise<void> {
|
||||
this.setupEventListeners();
|
||||
const configs = await defined(this.container.custom?.ExecutionService).registeredStrategies();
|
||||
const configs = await this.dependencies.execution.registeredStrategies();
|
||||
if (configs.length) {
|
||||
await this.initializeStrategies(configs);
|
||||
}
|
||||
|
|
@ -152,10 +142,7 @@ export class StrategyManager extends EventEmitter {
|
|||
}
|
||||
|
||||
private async createStrategy(config: StrategyConfig): Promise<BaseStrategy> {
|
||||
const strategy = await this.registry.create(config, {
|
||||
modeManager: defined(this.container.custom?.ModeManager),
|
||||
execution: defined(this.container.custom?.ExecutionService),
|
||||
});
|
||||
const strategy = await this.dependencies.createStrategy(config);
|
||||
|
||||
// Set up strategy event handlers
|
||||
strategy.on('signal', signal => {
|
||||
|
|
@ -163,7 +150,7 @@ export class StrategyManager extends EventEmitter {
|
|||
});
|
||||
|
||||
strategy.on('error', (error: Error) => {
|
||||
this.container.logger.error(`Strategy ${config.id} error:`, error);
|
||||
this.dependencies.logger.error(`Strategy ${config.id} error:`, error);
|
||||
});
|
||||
|
||||
return strategy;
|
||||
|
|
@ -175,7 +162,7 @@ export class StrategyManager extends EventEmitter {
|
|||
throw new Error(`Strategy ${strategyId} not found`);
|
||||
}
|
||||
|
||||
const execution = defined(this.container.custom?.ExecutionService);
|
||||
const { execution } = this.dependencies;
|
||||
if (execution.requiresDurableCheckpoint() && !strategy.getCheckpointVersion()) {
|
||||
throw new Error('Paper strategies require a versioned checkpoint contract');
|
||||
}
|
||||
|
|
@ -188,7 +175,7 @@ export class StrategyManager extends EventEmitter {
|
|||
throw error;
|
||||
}
|
||||
this.activeStrategies.add(strategyId);
|
||||
this.container.logger.info(`Enabled strategy: ${strategyId}`);
|
||||
this.dependencies.logger.info(`Enabled strategy: ${strategyId}`);
|
||||
}
|
||||
|
||||
async disableStrategy(strategyId: string): Promise<void> {
|
||||
|
|
@ -198,14 +185,14 @@ export class StrategyManager extends EventEmitter {
|
|||
}
|
||||
|
||||
// Disable pauses new decisions; pending orders/intents remain explicit ledger work.
|
||||
await defined(this.container.custom?.ExecutionService).pauseStrategy(strategyId);
|
||||
await this.dependencies.execution.pauseStrategy(strategyId);
|
||||
await strategy.suspend();
|
||||
this.activeStrategies.delete(strategyId);
|
||||
this.container.logger.info(`Disabled strategy: ${strategyId}`);
|
||||
this.dependencies.logger.info(`Disabled strategy: ${strategyId}`);
|
||||
}
|
||||
|
||||
private async handleStrategySignal(strategyId: string, signal: Signal): Promise<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
|
||||
}
|
||||
|
||||
|
|
@ -213,10 +200,6 @@ export class StrategyManager extends EventEmitter {
|
|||
await this.deliverBatch([data]);
|
||||
}
|
||||
|
||||
getTradingEngine(): TradingEngine | null {
|
||||
return this.tradingEngine;
|
||||
}
|
||||
|
||||
getActiveStrategies(): string[] {
|
||||
return Array.from(this.activeStrategies);
|
||||
}
|
||||
|
|
@ -230,11 +213,9 @@ export class StrategyManager extends EventEmitter {
|
|||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
this.container.logger.info('Shutting down strategy manager...');
|
||||
this.dependencies.logger.info('Shutting down strategy manager...');
|
||||
|
||||
if (this.marketSource) {
|
||||
this.marketSource.off('marketDataBatch', this.onBatch);
|
||||
}
|
||||
this.dependencies.marketData.off('marketDataBatch', this.onBatch);
|
||||
this.listening = false;
|
||||
if (this.recoveryTimer) {
|
||||
clearInterval(this.recoveryTimer);
|
||||
|
|
@ -243,7 +224,7 @@ export class StrategyManager extends EventEmitter {
|
|||
try {
|
||||
await this.drain();
|
||||
} catch (error) {
|
||||
this.container.logger.error('Leaving durable strategy backlog for restart', { error });
|
||||
this.dependencies.logger.error('Leaving durable strategy backlog for restart', { error });
|
||||
}
|
||||
// Disable all strategies
|
||||
for (const strategyId of this.activeStrategies) {
|
||||
|
|
@ -253,6 +234,5 @@ export class StrategyManager extends EventEmitter {
|
|||
// Clear all strategies
|
||||
this.strategies.clear();
|
||||
this.activeStrategies.clear();
|
||||
this.tradingEngine = null;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue