import type { MongoDBClient } from '@stock-bot/services'; import { storedSourceCoverageSchema, storedSourceInspectionSchema, storedSourceQuerySchema, storedSourceSelectionSchema, type StoredSourceCoverage, type StoredSourceInspection, } from '@stock-bot/stock-config/stored-source'; import { parseInstrumentId } from '@stock-bot/types'; import { PREPARATION_BATCH_SIZE, preparationCheckpoint, } from '@stock-bot/trading-runtime/preparation'; const collections = { '1m': 'eodIntraday1M', '5m': 'eodIntraday5M', '1h': 'eodIntraday1H', } as const; type Store = Pick; type Row = Record; type Code = StoredSourceInspection['issues'][number]['code']; export class StoredSourceInspectionError extends Error { constructor( readonly status: 400 | 503, message: string ) { super(message); } } function required(store: Store | null | undefined): Store { if (!store) { throw new StoredSourceInspectionError(503, 'Stored EOD data is unavailable'); } return store; } function timestamp(value: unknown): number | null { return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && Number.isSafeInteger(value * 1000) && Number.isFinite(new Date(value * 1000).getTime()) ? value * 1000 : null; } /** Inspect one indexed source series; first/last rows do not establish complete sessions. */ export async function storedSourceCoverage( store: Store | null | undefined, input: unknown, signal: AbortSignal ): Promise { signal.throwIfAborted(); const parsed = storedSourceSelectionSchema.safeParse(input); if (!parsed.success) { throw new StoredSourceInspectionError( 400, 'Select one qualified instrument and supported timeframe' ); } const query = parsed.data; const groups = await required(store).aggregate(collections[query.interval], [ { $match: { eodSearchCode: query.instrumentId } }, { $project: { _id: 0, validTimestamp: { $cond: [ // Decimal128 remains an object in the JS reader. Only these BSON types // can become its finite integer Unix-seconds number. { $in: [{ $type: '$timestamp' }, ['double', 'int', 'long']] }, { $cond: [ { $and: [ { $gte: ['$timestamp', 0] }, { $lte: ['$timestamp', 8_640_000_000_000] }, { $eq: ['$timestamp', { $trunc: '$timestamp' }] }, ], }, '$timestamp', null, ], }, null, ], }, }, }, { $group: { _id: null, rowCount: { $sum: 1 }, firstTimestamp: { $min: '$validTimestamp' }, lastTimestamp: { $max: '$validTimestamp' }, invalidTimestampRows: { $sum: { $cond: [{ $eq: ['$validTimestamp', null] }, 1, 0] } }, }, }, ]); signal.throwIfAborted(); const series = groups.map(group => { if ( !Number.isSafeInteger(group.rowCount) || Number(group.rowCount) < 0 || !Number.isSafeInteger(group.invalidTimestampRows) || Number(group.invalidTimestampRows) < 0 || Number(group.invalidTimestampRows) > Number(group.rowCount) ) { throw new Error('Invalid stored source coverage'); } return { ...query, rowCount: Number(group.rowCount), firstTimestamp: timestamp(group.firstTimestamp), lastTimestamp: timestamp(group.lastTimestamp), invalidTimestampRows: Number(group.invalidTimestampRows), }; }); return storedSourceCoverageSchema.parse({ version: 'stored-eod-coverage/v1', observedAt: Date.now(), query, series, }); } /** Explain raw field problems without changing rows or making financial eligibility decisions. */ export async function inspectStoredSource( store: Store | null | undefined, input: unknown, signal: AbortSignal ): Promise { signal.throwIfAborted(); const parsed = storedSourceQuerySchema.safeParse(input); if (!parsed.success) { throw new StoredSourceInspectionError( 400, 'Select an instrument, supported timeframe and valid UTC start/end range' ); } const query = parsed.data; const identity = parseInstrumentId(query.instrumentId); const rows = await required(store).find( collections[query.interval], { eodSearchCode: identity.id, timestamp: { $gte: query.start / 1000, $lt: query.end / 1000 }, }, { sort: { timestamp: 1 }, projection: { _id: 0, eodSearchCode: 1, symbol: 1, exchange: 1, timestamp: 1, open: 1, high: 1, low: 1, close: 1, volume: 1, }, } ); signal.throwIfAborted(); const bad = new Set(); const issues = new Map }>(); const byTimestamp = new Map(); const instants: Array = []; const issue = (code: Code, index: number, at: number | null) => { bad.add(index); const existing = issues.get(code) ?? { rowCount: 0, timestamps: [] }; existing.rowCount++; existing.timestamps.push(at); issues.set(code, existing); }; const numeric = (value: unknown) => typeof value === 'number' ? value : typeof value === 'string' && value.trim() ? Number(value) : NaN; let nullVolumeRows = 0; for (const [index, row] of rows.entries()) { const at = timestamp(row.timestamp); instants.push(at); if ( row.eodSearchCode !== identity.id || row.symbol !== identity.symbol || row.exchange !== identity.exchange ) { issue('identity-mismatch', index, at); } if (at === null) { issue('invalid-timestamp', index, at); } else { if (at < query.start || at >= query.end) { issue('outside-range', index, at); } const same = byTimestamp.get(at) ?? []; same.push(index); byTimestamp.set(at, same); } const open = numeric(row.open); const high = numeric(row.high); const low = numeric(row.low); const close = numeric(row.close); if ( ![open, high, low, close].every( value => typeof value === 'number' && Number.isFinite(value) && value > 0 ) || high < Math.max(open, close) || low > Math.min(open, close) ) { issue('invalid-prices', index, at); } if (row.volume === null || row.volume === undefined) { nullVolumeRows++; issue('null-volume', index, at); } else if (!Number.isFinite(numeric(row.volume)) || numeric(row.volume) < 0) { issue('invalid-volume', index, at); } if ((index + 1) % PREPARATION_BATCH_SIZE === 0) { await preparationCheckpoint(signal); } } let duplicateRows = 0; for (const [at, indices] of byTimestamp) { if (indices.length > 1) { duplicateRows += indices.length - 1; for (const index of indices) { issue('duplicate-timestamp', index, at); } } } const days = new Map(); let firstTimestamp: number | null = null, lastTimestamp: number | null = null; for (let index = 0; index < instants.length; index++) { const at = instants[index]; if (at === null || at === undefined) { continue; } firstTimestamp = firstTimestamp === null ? at : Math.min(firstTimestamp, at); lastTimestamp = lastTimestamp === null ? at : Math.max(lastTimestamp, at); const date = new Date(at).toISOString().slice(0, 10); const day = days.get(date) ?? { date, rowCount: 0, invalidRows: 0 }; day.rowCount++; if (bad.has(index)) { day.invalidRows++; } days.set(date, day); } signal.throwIfAborted(); return storedSourceInspectionSchema.parse({ version: 'stored-eod-inspection/v1', observedAt: Date.now(), query, rowCount: rows.length, invalidRows: bad.size, nullVolumeRows, duplicateRows, firstTimestamp, lastTimestamp, days: [...days.values()].sort((a, b) => a.date.localeCompare(b.date)), issues: [...issues].map(([code, detail]) => ({ code, ...detail })), }); }