refactor(orchestrator): narrow historical storage to reads (CL17)

This commit is contained in:
Boki 2026-10-26 20:30:40 -04:00
parent 03518c8ae4
commit 984dc1a9cc
17 changed files with 88 additions and 232 deletions

View file

@ -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.
}
}