refactor(orchestrator): narrow historical storage to reads (CL17)
This commit is contained in:
parent
03518c8ae4
commit
984dc1a9cc
17 changed files with 88 additions and 232 deletions
|
|
@ -21,7 +21,7 @@ export async function createExampleRuntime() {
|
|||
})
|
||||
.build();
|
||||
const container = di.resolve('serviceContainer') as OrchestratorServices;
|
||||
const storageService = new StorageService(container, null, null, null, {
|
||||
const storageService = new StorageService(container.logger, null, null, {
|
||||
allowSyntheticData: true,
|
||||
syntheticSeed: 42,
|
||||
});
|
||||
|
|
@ -45,7 +45,6 @@ export async function createExampleRuntime() {
|
|||
logger: container.logger,
|
||||
marketData: marketDataService,
|
||||
execution: executionService,
|
||||
storage: storageService,
|
||||
strategies: strategyManager,
|
||||
});
|
||||
const custom = container.custom ?? {};
|
||||
|
|
|
|||
|
|
@ -123,9 +123,8 @@ export async function registerOrchestratorServices(
|
|||
|
||||
// Create storage service first as it's needed by other services
|
||||
const storageService = new StorageService(
|
||||
services,
|
||||
services.logger,
|
||||
services.mongodb,
|
||||
services.postgres,
|
||||
services.questdb || null,
|
||||
options
|
||||
);
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import { defined } from '@stock-bot/invariants';
|
|||
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,
|
||||
|
|
@ -13,7 +12,7 @@ import {
|
|||
type TradingMode,
|
||||
} from '../types';
|
||||
|
||||
const shutdownOrder = ['marketData', 'strategies', 'execution', 'storage'] as const;
|
||||
const shutdownOrder = ['marketData', 'strategies', 'execution'] as const;
|
||||
type LifecycleService = (typeof shutdownOrder)[number];
|
||||
|
||||
export class ModeManager extends EventEmitter {
|
||||
|
|
@ -27,7 +26,6 @@ export class ModeManager extends EventEmitter {
|
|||
logger: Pick<Logger, 'info'>;
|
||||
marketData: Pick<MarketDataService, 'initialize' | 'shutdown'>;
|
||||
execution: Pick<ExecutionService, 'initialize' | 'shutdown'>;
|
||||
storage: Pick<StorageService, 'initialize' | 'shutdown'>;
|
||||
strategies: Pick<StrategyManager, 'restoreStrategies' | 'shutdown'>;
|
||||
}
|
||||
) {
|
||||
|
|
@ -132,9 +130,6 @@ export class ModeManager extends EventEmitter {
|
|||
attempted.add('execution');
|
||||
await this.dependencies.execution.initialize(config, defined(this.tradingEngine));
|
||||
|
||||
// Configure storage
|
||||
attempted.add('storage');
|
||||
await this.dependencies.storage.initialize(config);
|
||||
if (config.mode === 'paper') {
|
||||
attempted.add('strategies');
|
||||
await this.dependencies.strategies.restoreStrategies();
|
||||
|
|
|
|||
|
|
@ -1,12 +1,6 @@
|
|||
import type {
|
||||
IServiceContainer,
|
||||
MongoDBClient,
|
||||
PostgresClient,
|
||||
QuestDBClient,
|
||||
} from '@stock-bot/services';
|
||||
import type { Logger, MongoDBClient, QuestDBClient } from '@stock-bot/services';
|
||||
import { parseInstrumentId, type HistoricalDataPolicy } from '@stock-bot/types';
|
||||
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation';
|
||||
import type { MarketData, ModeConfig, PerformanceMetrics } from '../types';
|
||||
|
||||
export interface HistoricalBar {
|
||||
symbol: string;
|
||||
|
|
@ -48,151 +42,21 @@ const eodIntradayCollections: Readonly<Record<string, string | undefined>> = {
|
|||
'1h': 'eodIntraday1H',
|
||||
};
|
||||
|
||||
/** Historical reads over borrowed adapters; ingestion and migrations own all writes. */
|
||||
export class StorageService {
|
||||
private questdb: QuestDBClient | null = null;
|
||||
private postgres: PostgresClient | null = null;
|
||||
private mongodb: MongoDBClient | null = null;
|
||||
private mode: 'backtest' | 'paper' | 'live' = 'paper';
|
||||
private container: IServiceContainer;
|
||||
private readonly questdb: QuestDBClient | null;
|
||||
private readonly mongodb: MongoDBClient | null;
|
||||
|
||||
constructor(
|
||||
container: IServiceContainer,
|
||||
private readonly logger: Pick<Logger, 'info'>,
|
||||
mongoClient: MongoDBClient | null | undefined,
|
||||
postgresClient: PostgresClient | null | undefined,
|
||||
questdbClient: QuestDBClient | null,
|
||||
private readonly options: { allowSyntheticData?: boolean; syntheticSeed?: number } = {}
|
||||
) {
|
||||
this.container = container;
|
||||
this.mongodb = mongoClient ?? null;
|
||||
this.postgres = postgresClient ?? null;
|
||||
this.questdb = questdbClient;
|
||||
}
|
||||
|
||||
async initialize(config: ModeConfig): Promise<void> {
|
||||
this.mode = config.mode;
|
||||
// Clients are already injected via DI
|
||||
if (config.mode !== 'backtest') {
|
||||
await this.createTables();
|
||||
}
|
||||
}
|
||||
|
||||
private async createTables(): Promise<void> {
|
||||
// Create tables if they don't exist
|
||||
if (this.postgres) {
|
||||
// Strategy performance table
|
||||
await this.postgres.query(`
|
||||
CREATE TABLE IF NOT EXISTS strategy_performance (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
strategy_id VARCHAR(255) NOT NULL,
|
||||
timestamp TIMESTAMP NOT NULL,
|
||||
total_return DECIMAL(20, 8),
|
||||
sharpe_ratio DECIMAL(20, 8),
|
||||
max_drawdown DECIMAL(20, 8),
|
||||
win_rate DECIMAL(20, 8),
|
||||
total_trades INTEGER,
|
||||
mode VARCHAR(10) NOT NULL
|
||||
)
|
||||
`);
|
||||
}
|
||||
}
|
||||
|
||||
private async insertTimeSeries(table: string, data: Record<string, unknown>): Promise<void> {
|
||||
if (!this.questdb) {
|
||||
throw new Error('QuestDB is unavailable');
|
||||
}
|
||||
if (!/^[a-z0-9_]+$/.test(table)) {
|
||||
throw new Error('Invalid time-series table');
|
||||
}
|
||||
const columns = Object.keys(data);
|
||||
const placeholders = columns.map((_, i) => '$' + (i + 1));
|
||||
await this.questdb.query(
|
||||
`INSERT INTO ${table} (${columns.join(', ')}) VALUES (${placeholders.join(', ')})`,
|
||||
Object.values(data)
|
||||
);
|
||||
}
|
||||
|
||||
async storeMarketData(data: MarketData[]): Promise<void> {
|
||||
if (!this.questdb) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const item of data) {
|
||||
try {
|
||||
parseInstrumentId(item.data.symbol);
|
||||
switch (item.type) {
|
||||
case 'quote':
|
||||
await this.insertTimeSeries('quotes', {
|
||||
symbol: item.data.symbol,
|
||||
bid: item.data.bid,
|
||||
ask: item.data.ask,
|
||||
bid_size: item.data.bidSize,
|
||||
ask_size: item.data.askSize,
|
||||
timestamp: new Date(item.data.timestamp),
|
||||
});
|
||||
break;
|
||||
|
||||
case 'trade':
|
||||
await this.insertTimeSeries('trades', {
|
||||
symbol: item.data.symbol,
|
||||
price: item.data.price,
|
||||
size: item.data.size,
|
||||
side: item.data.side,
|
||||
timestamp: new Date(item.data.timestamp),
|
||||
});
|
||||
break;
|
||||
|
||||
case 'bar': {
|
||||
const interval = '1m'; // Would be determined from context
|
||||
await this.insertTimeSeries(`bars_${interval}`, {
|
||||
symbol: item.data.symbol,
|
||||
open: item.data.open,
|
||||
high: item.data.high,
|
||||
low: item.data.low,
|
||||
close: item.data.close,
|
||||
volume: item.data.volume,
|
||||
vwap: item.data.vwap || null,
|
||||
timestamp: new Date(item.data.timestamp),
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
this.container.logger.error('Error storing market data:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async storeStrategyPerformance(
|
||||
strategyId: string,
|
||||
metrics: Pick<
|
||||
PerformanceMetrics,
|
||||
'totalReturn' | 'sharpeRatio' | 'maxDrawdown' | 'winRate' | 'totalTrades'
|
||||
>
|
||||
): Promise<void> {
|
||||
if (!this.postgres) {
|
||||
return;
|
||||
}
|
||||
|
||||
await this.postgres.query(
|
||||
`
|
||||
INSERT INTO strategy_performance (
|
||||
strategy_id, timestamp, total_return, sharpe_ratio,
|
||||
max_drawdown, win_rate, total_trades, mode
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
`,
|
||||
[
|
||||
strategyId,
|
||||
new Date(),
|
||||
metrics.totalReturn,
|
||||
metrics.sharpeRatio,
|
||||
metrics.maxDrawdown,
|
||||
metrics.winRate,
|
||||
metrics.totalTrades,
|
||||
this.mode,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/** Adapter support and current connectivity, not evidence of stored range coverage. */
|
||||
getHistoricalCapabilities() {
|
||||
return [
|
||||
|
|
@ -602,9 +466,7 @@ export class StorageService {
|
|||
currentTime = new Date(currentTime.getTime() + msPerInterval);
|
||||
}
|
||||
|
||||
this.container.logger.info(
|
||||
`Generated ${bars.length} mock bars for ${symbol} with seed ${seed}`
|
||||
);
|
||||
this.logger.info(`Generated ${bars.length} mock bars for ${symbol} with seed ${seed}`);
|
||||
|
||||
return bars;
|
||||
}
|
||||
|
|
@ -625,8 +487,4 @@ export class StorageService {
|
|||
return 60 * 1000; // Default to 1 minute
|
||||
}
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
// All adapters are borrowed from DI. Only their lifecycle owner may close them.
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ export function createDatasetRoutes(container: IServiceContainer) {
|
|||
try {
|
||||
const body = await readBody(c.req.raw);
|
||||
// Request-local read adapter: no initialization, mode changes or shared trading runtime.
|
||||
const storage = new StorageService(container, container.mongodb, null, null);
|
||||
const storage = new StorageService(container.logger, container.mongodb, null);
|
||||
const prepared = await prepareStoredDataset(body, storage, c.req.raw.signal);
|
||||
c.req.raw.signal.throwIfAborted();
|
||||
return c.json(prepared);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue