import type { IServiceContainer, MongoDBClient, PostgresClient, 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; timestamp: Date; open: number; high: number; low: number; close: number; volume: number; vwap?: number; interpolated?: boolean; source?: 'eod' | 'questdb' | 'synthetic'; adjustedClose?: number; } 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; constructor( container: IServiceContainer, 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 { this.mode = config.mode; // Clients are already injected via DI if (config.mode !== 'backtest') { await this.createTables(); } } private async createTables(): Promise { // 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): Promise { 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 { 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 { 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, ] ); } /** One historical-data policy for native and TypeScript execution. */ async getHistoricalBars( symbol: string, startTime: Date, endTime: Date, interval = '1m', policy: HistoricalDataPolicy = { adjustment: 'raw', timestamp: interval === '1d' ? 'utc-session-date' : 'utc-instant', }, signal?: AbortSignal ): Promise { signal?.throwIfAborted(); parseInstrumentId(symbol); if ( !Number.isFinite(startTime.getTime()) || !Number.isFinite(endTime.getTime()) || endTime <= startTime ) { throw new Error('Invalid historical date range'); } if (!['1m', '5m', '15m', '1h', '1d'].includes(interval)) { throw new Error('Unsupported historical interval'); } if ( (interval === '1d') !== (policy.timestamp === 'utc-session-date') || (interval === '1d' && (startTime.getTime() % 86400000 !== 0 || endTime.getTime() % 86400000 !== 0)) ) { throw new Error( 'Daily ranges must use UTC midnight session dates; intraday ranges use UTC instants' ); } const rows = await this.readHistoricalBars(symbol, startTime, endTime, interval); signal?.throwIfAborted(); const bars: HistoricalBar[] = []; let processed = 0; for (const row of rows) { if (row.symbol !== symbol) { throw new Error(`Historical instrument identity mismatch for ${symbol}`); } if (typeof row.timestamp === 'string' && !/(Z|[+-]\d{2}:\d{2})$/.test(row.timestamp)) { throw new Error('Historical instants require an explicit UTC offset'); } const timestamp = new Date(row.timestamp); const numeric = (value: unknown) => typeof value === 'number' ? value : typeof value === 'string' && value.trim() ? Number(value) : NaN; let open = numeric(row.open), high = numeric(row.high), low = numeric(row.low), close = numeric(row.close); const volume = numeric(row.volume); if ( !Number.isFinite(timestamp.getTime()) || ![open, high, low, close, volume].every(Number.isFinite) || low <= 0 || high < Math.max(open, close) || low > Math.min(open, close) || volume < 0 || (interval === '1d' && timestamp.getTime() % 86400000 !== 0) ) { throw new Error(`Invalid historical OHLCV data for ${symbol}`); } let vwap = row.vwap === null || row.vwap === undefined ? undefined : numeric(row.vwap); if (policy.adjustment === 'provider-adjusted') { const adjustedClose = numeric(row.adjustedClose); if (!(adjustedClose > 0) || !Number.isFinite(adjustedClose)) { throw new Error(`Provider-adjusted prices unavailable for ${symbol}`); } const factor = adjustedClose / close; open *= factor; high *= factor; low *= factor; close = adjustedClose; if (vwap !== undefined) { vwap *= factor; } } if ( ![open, high, low, close].every(value => Number.isFinite(value) && value > 0) || (vwap !== undefined && (!Number.isFinite(vwap) || vwap <= 0)) ) { throw new Error(`Invalid adjusted historical data for ${symbol}`); } if (timestamp >= startTime && timestamp < endTime) { bars.push({ ...row, symbol, timestamp, open, high, low, close, volume, vwap }); } if (++processed % PREPARATION_BATCH_SIZE === 0) { await preparationCheckpoint(signal); } } signal?.throwIfAborted(); bars.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime()); if (!bars.length) { throw new Error(`No historical data for ${symbol}`); } if ( bars.some( (bar, index) => index > 0 && bars[index - 1]?.timestamp.getTime() === bar.timestamp.getTime() ) ) { throw new Error(`Duplicate historical timestamps for ${symbol}`); } return bars; } private async readHistoricalBars( symbol: string, startTime: Date, endTime: Date, interval: string ): Promise { // If QuestDB is available, use real data if (this.questdb) { if (!['1m', '5m', '15m', '1h', '1d'].includes(interval)) { throw new Error('Unsupported historical interval'); } const result = await this.questdb.query( `SELECT * FROM bars_${interval} WHERE symbol = $1 AND timestamp >= $2 AND timestamp < $3 ORDER BY timestamp`, [symbol, startTime, endTime] ); return result.rows.map(row => ({ ...row, source: 'questdb' })); } if (this.mongodb) { if (interval !== '1d') { throw new Error('Daily provider storage cannot satisfy an intraday request'); } const identity = parseInstrumentId(symbol); const prices = await this.mongodb.find<{ symbol: string; exchange: string; eodSearchCode: string; providerExchange?: string; date: string; open: number; high: number; low: number; close: number; volume: number; adjustedClose?: number; }>( 'eodPrices', { eodSearchCode: identity.id, date: { $gte: startTime.toISOString().slice(0, 10), $lt: endTime.toISOString().slice(0, 10), }, }, { sort: { date: 1 }, projection: { symbol: 1, exchange: 1, eodSearchCode: 1, providerExchange: 1, date: 1, open: 1, high: 1, low: 1, close: 1, volume: 1, adjustedClose: 1, }, } ); return prices.map(price => { if ( price.eodSearchCode !== identity.id || price.symbol !== identity.symbol || (price.providerExchange !== undefined && price.providerExchange !== identity.exchange) ) { throw new Error(`Historical instrument identity mismatch for ${symbol}`); } if ( !/^\d{4}-\d{2}-\d{2}$/.test(price.date) || !Number.isFinite(Date.parse(price.date)) || new Date(price.date).toISOString().slice(0, 10) !== price.date ) { throw new Error(`Invalid historical session date for ${symbol}`); } return { symbol, timestamp: new Date(price.date), open: price.open, high: price.high, low: price.low, close: price.close, volume: price.volume, adjustedClose: price.adjustedClose, source: 'eod' as const, }; }); } if (!this.options.allowSyntheticData) { throw new Error( 'No historical data store configured; synthetic data requires explicit opt-in' ); } return this.generateMockBars(symbol, startTime, endTime, interval).map(bar => ({ ...bar, source: 'synthetic', })); } private generateMockBars( symbol: string, startTime: Date, endTime: Date, interval: string ): HistoricalBar[] { const bars = []; const msPerInterval = this.getIntervalMilliseconds(interval); let currentTime = new Date(startTime); // Synthetic data is only generated with explicit opt-in and a stable seed. const seed = this.options.syntheticSeed ?? 42; const seedMultiplier = (seed % 1000) / 1000; // 0-1 based on milliseconds // Starting price based on symbol with some randomness let basePrice = symbol === 'AAPL' ? 150 + (seedMultiplier * 20 - 10) : symbol === 'MSFT' ? 300 + (seedMultiplier * 30 - 15) : symbol === 'GOOGL' ? 120 + (seedMultiplier * 15 - 7.5) : 100 + (seedMultiplier * 10 - 5); // Random walk seed to make each run different let walkSeed = seedMultiplier; while (currentTime < endTime) { // Use a pseudo-random based on walkSeed for deterministic but different results walkSeed = (walkSeed * 9.73 + 0.27) % 1; // Random walk with trend - increased volatility for testing const trend = 0.0002; // Slight upward trend const volatility = 0.01; // 1% volatility const change = (walkSeed - 0.5 + trend) * volatility; basePrice *= 1 + change; // Generate OHLC data with more realistic volatility const openSeed = (walkSeed * 7.13 + 0.31) % 1; const highSeed = (walkSeed * 5.17 + 0.41) % 1; const lowSeed = (walkSeed * 3.19 + 0.59) % 1; const volumeSeed = (walkSeed * 11.23 + 0.67) % 1; const open = basePrice * (1 + (openSeed - 0.5) * 0.005); const close = basePrice; const high = Math.max(open, close) * (1 + highSeed * 0.008); const low = Math.min(open, close) * (1 - lowSeed * 0.008); const volume = 1000000 + volumeSeed * 500000; bars.push({ symbol, timestamp: new Date(currentTime), open, high, low, close, volume, vwap: (high + low + close) / 3, }); currentTime = new Date(currentTime.getTime() + msPerInterval); } this.container.logger.info( `Generated ${bars.length} mock bars for ${symbol} with seed ${seed}` ); return bars; } private getIntervalMilliseconds(interval: string): number { switch (interval) { case '1m': return 60 * 1000; case '5m': return 5 * 60 * 1000; case '15m': return 15 * 60 * 1000; case '1h': return 60 * 60 * 1000; case '1d': return 24 * 60 * 60 * 1000; default: return 60 * 1000; // Default to 1 minute } } async shutdown(): Promise { // All adapters are borrowed from DI. Only their lifecycle owner may close them. } }