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'; 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 type HistoricalStorageProvider = 'questdb' | 'eod'; export type HistoricalStorageErrorCode = | 'unsupported-provider' | 'unsupported-interval' | 'provider-unavailable' | 'missing-range'; /** Storage routing failures are distinct from invalid records and transport failures. */ export class HistoricalStorageError extends Error { constructor( readonly code: HistoricalStorageErrorCode, message: string, readonly provider?: HistoricalStorageProvider | 'synthetic' ) { super(message); this.name = 'HistoricalStorageError'; } } const historicalIntervals = ['1m', '5m', '15m', '1h', '1d'] as const; const eodIntradayCollections: Readonly> = { '1m': 'eodIntraday1M', '5m': 'eodIntraday5M', '1h': 'eodIntraday1H', }; /** Historical reads over borrowed adapters; ingestion and migrations own all writes. */ export class StorageService { private readonly questdb: QuestDBClient | null; private readonly mongodb: MongoDBClient | null; constructor( private readonly logger: Pick, mongoClient: MongoDBClient | null | undefined, questdbClient: QuestDBClient | null, private readonly options: { allowSyntheticData?: boolean; syntheticSeed?: number } = {} ) { this.mongodb = mongoClient ?? null; this.questdb = questdbClient; } /** Adapter support and current connectivity, not evidence of stored range coverage. */ getHistoricalCapabilities() { return [ { provider: 'questdb' as const, configured: this.questdb !== null, connected: this.questdb?.connected ?? false, intervals: [...historicalIntervals], }, { provider: 'eod' as const, configured: this.mongodb !== null, connected: this.mongodb?.connected ?? false, intervals: ['1m', '5m', '1h', '1d'] as const, }, ]; } private selectHistoricalProvider( requested: HistoricalStorageProvider | 'auto' ): HistoricalStorageProvider | 'synthetic' { if (!['auto', 'questdb', 'eod'].includes(requested)) { throw new HistoricalStorageError('unsupported-provider', 'Unsupported historical provider'); } if (requested === 'questdb' || (requested === 'auto' && this.questdb)) { if (!this.questdb) { throw new HistoricalStorageError( 'provider-unavailable', 'QuestDB historical storage is unavailable', 'questdb' ); } return 'questdb'; } if (requested === 'eod' || (requested === 'auto' && this.mongodb)) { if (!this.mongodb) { throw new HistoricalStorageError( 'provider-unavailable', 'EOD historical storage is unavailable', 'eod' ); } return 'eod'; } if (this.options.allowSyntheticData) { return 'synthetic'; } throw new HistoricalStorageError( 'provider-unavailable', 'No historical data store configured; synthetic data requires explicit opt-in' ); } /** 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, provider: HistoricalStorageProvider | 'auto' = 'auto' ): Promise { signal?.throwIfAborted(); parseInstrumentId(symbol); if ( !Number.isFinite(startTime.getTime()) || !Number.isFinite(endTime.getTime()) || endTime <= startTime ) { throw new Error('Invalid historical date range'); } if (!(historicalIntervals as readonly string[]).includes(interval)) { throw new HistoricalStorageError('unsupported-interval', '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 selectedProvider = this.selectHistoricalProvider(provider); const rows = await this.readHistoricalBars( symbol, startTime, endTime, interval, selectedProvider, signal ); 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 HistoricalStorageError( 'missing-range', `No historical data for ${symbol} in the requested range`, selectedProvider ); } 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, provider: HistoricalStorageProvider | 'synthetic', signal?: AbortSignal ): Promise { // Select once, before reading: empty ranges/errors never switch providers. if (provider === 'questdb' && this.questdb) { 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 (provider === 'eod' && this.mongodb) { const identity = parseInstrumentId(symbol); if (interval !== '1d') { const collection = eodIntradayCollections[interval]; if (!collection) { throw new HistoricalStorageError( 'unsupported-interval', `EOD historical storage does not support ${interval}`, 'eod' ); } // fetchIntraday writes raw bar-start UTC Unix seconds, not local datetime labels. // https://eodhd.com/financial-apis/intraday-historical-data-api // This instant is not publication time; availability/calendar policy belongs to datasets. const records = await this.mongodb.find<{ symbol: string; exchange: string; eodSearchCode: string; timestamp: number; open: number; high: number; low: number; close: number; volume: number; }>( collection, { eodSearchCode: identity.id, timestamp: { $gte: startTime.getTime() / 1000, $lt: endTime.getTime() / 1000 }, }, { sort: { timestamp: 1 }, projection: { symbol: 1, exchange: 1, eodSearchCode: 1, timestamp: 1, open: 1, high: 1, low: 1, close: 1, volume: 1, }, } ); signal?.throwIfAborted(); const bars: HistoricalBar[] = []; for (const record of records) { if ( record.eodSearchCode !== identity.id || record.symbol !== identity.symbol || record.exchange !== identity.exchange ) { throw new Error(`Historical instrument identity mismatch for ${symbol}`); } const milliseconds = record.timestamp * 1000; if ( !Number.isSafeInteger(record.timestamp) || !Number.isSafeInteger(milliseconds) || !Number.isFinite(new Date(milliseconds).getTime()) ) { throw new Error(`Invalid historical Unix-seconds timestamp for ${symbol}`); } bars.push({ symbol, timestamp: new Date(milliseconds), open: record.open, high: record.high, low: record.low, close: record.close, volume: record.volume, source: 'eod', }); if (bars.length % PREPARATION_BATCH_SIZE === 0) { await preparationCheckpoint(signal); } } return bars; } 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, }; }); } 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.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 } } }