import { describe, expect, test } from 'bun:test'; import { getLogger, setLoggerConfig } from '@stock-bot/logger'; import type { MongoDBClient, QuestDBClient } from '@stock-bot/services'; import { persistEodPrices, type EodPrice, } from '../../apps/stock/data-ingestion/src/handlers/eod/shared/price-storage'; import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter'; import { loadDataset, validateDataset, } from '../../apps/stock/orchestrator/src/data/historical-dataset'; import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types'; setLoggerConfig({ logLevel: 'fatal', logConsole: false }); const logger = getLogger('replay-test'); const identity = { symbol: 'FIXTURE', exchange: 'TEST', eodSearchCode: 'FIXTURE.TEST' }; const start = new Date('2024-01-01T00:00:00.000Z'); const end = new Date('2024-03-15T00:00:00.000Z'); const fixture: EodPrice[] = Array.from({ length: 70 }, (_, i) => { const close = 100 + Math.sin((i * Math.PI) / 6) * 8 + i * 0.02; return { date: new Date(start.getTime() + i * 86400000).toISOString().slice(0, 10), open: close - 0.1, high: close + 1, low: close - 1, close, volume: 1_000_000, }; }); /** Only the database transport is replaced; normalization, storage reads, and engine are real. */ function memoryStore() { const documents: Array = []; const transport = { async batchUpsert(collection: string, rows: typeof documents) { expect(collection).toBe('eodPrices'); for (const row of rows) { const index = documents.findIndex( old => old.date === row.date && old.eodSearchCode === row.eodSearchCode ); if (index >= 0) documents[index] = row; else documents.push(row); } return { insertedCount: rows.length, modifiedCount: 0, matchedCount: 0, upsertedCount: rows.length, }; }, async find( collection: string, filter: { eodSearchCode: string; date: { $gte: string; $lt: string } } ) { expect(collection).toBe('eodPrices'); return documents .filter( row => row.eodSearchCode === filter.eodSearchCode && row.date >= filter.date.$gte && row.date < filter.date.$lt ) .sort((a, b) => a.date.localeCompare(b.date)); }, }; return { documents, mongodb: transport as unknown as MongoDBClient }; } describe('deterministic ingestion → storage → native backtest', () => { test('intraday queries bind qualified IDs and reject timezone-less instants or wrong listings', async () => { let timestamp = '2024-01-01T10:00:00-05:00'; let symbol = identity.eodSearchCode; const questdb = { async query(_sql: string, parameters: unknown[]) { expect(parameters[0]).toBe(identity.eodSearchCode); return { rows: [ { symbol, timestamp, open: 100, high: 101, low: 99, close: 100, volume: 1000, vwap: null, }, ], }; }, } as unknown as QuestDBClient; const storage = new StorageService({ logger }, null, null, questdb); const bars = await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1m'); expect(bars[0]?.timestamp.toISOString()).toBe('2024-01-01T15:00:00.000Z'); timestamp = '2024-01-01T10:00:00'; await expect( storage.getHistoricalBars(identity.eodSearchCode, start, end, '1m') ).rejects.toThrow('explicit UTC offset'); timestamp = '2024-01-01T15:00:00Z'; symbol = 'FIXTURE.OTHER'; await expect( storage.getHistoricalBars(identity.eodSearchCode, start, end, '1m') ).rejects.toThrow('identity mismatch'); }); test('provider routing namespaces remain distinct from venue metadata, including legacy rows', async () => { const { documents, mongodb } = memoryStore(); const listing = { symbol: 'FIXTURE', exchange: 'NASDAQ', eodSearchCode: 'FIXTURE.US' }; await persistEodPrices(mongodb, listing, [fixture[0]!]); expect(documents[0]?.exchange).toBe('NASDAQ'); expect((documents[0] as unknown as { providerExchange: string }).providerExchange).toBe('US'); const storage = new StorageService({ logger }, mongodb, null, null); expect( (await storage.getHistoricalBars(listing.eodSearchCode, start, end, '1d'))[0]?.symbol ).toBe('FIXTURE.US'); delete (documents[0] as unknown as { providerExchange?: string }).providerExchange; expect( (await storage.getHistoricalBars(listing.eodSearchCode, start, end, '1d'))[0]?.close ).toBe(fixture[0]!.close); }); test('same ticker on different exchanges never shares bars and bare tickers fail closed', async () => { const { mongodb } = memoryStore(); const other = { symbol: 'FIXTURE', exchange: 'OTHER', eodSearchCode: 'FIXTURE.OTHER' }; await persistEodPrices(mongodb, identity, [fixture[0]!]); await persistEodPrices(mongodb, other, [ { ...fixture[0]!, open: 200, high: 201, low: 199, close: 200 }, ]); const storage = new StorageService({ logger }, mongodb, null, null); expect( (await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d'))[0]?.close ).toBe(fixture[0]!.close); expect((await storage.getHistoricalBars(other.eodSearchCode, start, end, '1d'))[0]?.close).toBe( 200 ); await expect(storage.getHistoricalBars('FIXTURE', start, end, '1d')).rejects.toThrow( 'exchange-qualified' ); expect( BacktestConfigSchema.safeParse({ ...datasetConfig(), symbols: ['FIXTURE'] }).success ).toBe(false); }); test('split and dividend adjusted-close factors apply to every OHLC price, never to reported volume', async () => { const { mongodb } = memoryStore(); const prices = [ { ...fixture[0]!, open: 100, high: 110, low: 90, close: 100, adjusted_close: 50, volume: 1000, }, { ...fixture[1]!, open: 50, high: 55, low: 45, close: 50, adjusted_close: 49, volume: 2000 }, ]; await persistEodPrices(mongodb, identity, prices); const storage = new StorageService({ logger }, mongodb, null, null); const raw = await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d'); const adjusted = await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d', { adjustment: 'provider-adjusted', timestamp: 'utc-session-date', }); expect(raw.map(b => b.close)).toEqual([100, 50]); expect(adjusted.map(b => [b.open, b.high, b.low, b.close, b.volume])).toEqual([ [50, 55, 45, 50, 1000], [49, 53.9, 44.1, 49, 2000], ]); const a = await loadDataset(storage, datasetConfig()); const b = await loadDataset(storage, { ...datasetConfig(), dataPolicy: { adjustment: 'provider-adjusted', timestamp: 'utc-session-date' }, }); expect(a.manifest.hash).not.toBe(b.manifest.hash); }); test('missing provider factors cannot silently turn adjusted requests into raw data', async () => { const { mongodb } = memoryStore(); await persistEodPrices(mongodb, identity, [fixture[0]!]); const storage = new StorageService({ logger }, mongodb, null, null); await expect( storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d', { adjustment: 'provider-adjusted', timestamp: 'utc-session-date', }) ).rejects.toThrow('unavailable'); await expect( persistEodPrices(mongodb, identity, [{ ...fixture[0]!, adjusted_close: 0 }]) ).rejects.toThrow('Invalid OHLCV'); await expect( persistEodPrices(mongodb, { ...identity, symbol: 'WRONG' }, [fixture[0]!]) ).rejects.toThrow('identity mismatch'); }); test('daily timestamps are UTC session labels with aligned, exclusive ranges', async () => { const { mongodb } = memoryStore(); await persistEodPrices(mongodb, identity, fixture.slice(0, 3)); const storage = new StorageService({ logger }, mongodb, null, null); const bars = await storage.getHistoricalBars( identity.eodSearchCode, start, new Date(start.getTime() + 86400000), '1d' ); expect(bars).toHaveLength(1); expect(bars[0]?.timestamp.toISOString()).toBe('2024-01-01T00:00:00.000Z'); await expect( storage.getHistoricalBars( identity.eodSearchCode, new Date(start.getTime() + 3600000), end, '1d' ) ).rejects.toThrow('UTC midnight'); await expect( persistEodPrices(mongodb, identity, [{ ...fixture[0]!, date: '2024-02-30' }]) ).rejects.toThrow('Invalid OHLCV'); }); test('dataset hashes survive JSON key reordering and reject tampering or mismatched requests', async () => { const { mongodb } = memoryStore(); await persistEodPrices(mongodb, identity, fixture); const storage = new StorageService({ logger }, mongodb, null, null); const first = await loadDataset(storage, datasetConfig()); const reordered = JSON.parse(JSON.stringify(first), (_key, value) => value && !Array.isArray(value) && typeof value === 'object' ? Object.fromEntries(Object.entries(value).reverse()) : value ); expect(validateDataset(reordered, datasetConfig())).toEqual(first); const changed = structuredClone(first); changed.bars[0]!.volume++; expect(() => validateDataset(changed)).toThrow('hash/content'); expect(() => validateDataset(first, { ...datasetConfig(), symbols: ['FIXTURE.OTHER'] }) ).toThrow('does not match'); expect(() => validateDataset(first, { ...datasetConfig(), datasetHash: 'f'.repeat(64) }) ).toThrow('does not match'); }); test('replays stored provider fixtures and produces identical trades and metrics', async () => { const { documents, mongodb } = memoryStore(); await persistEodPrices(mongodb, identity, fixture); await persistEodPrices(mongodb, identity, fixture); expect(documents).toHaveLength(fixture.length); expect(documents.every(row => row.source === 'eod')).toBe(true); const services = { logger, mongodb }; const storage = new StorageService(services, mongodb, null, null); const config = BacktestConfigSchema.parse({ mode: 'backtest', name: 'Fixed replay', symbols: ['FIXTURE.TEST'], strategy: 'sma-crossover', startDate: start.toISOString(), endDate: end.toISOString(), initialCapital: 100000, dataFrequency: '1d', commission: 0, slippage: 0, config: { fastPeriod: 3, slowPeriod: 7 }, }); const engine = new RustBacktestAdapter({ logger, storage }); const first = await engine.runBacktest(config); const second = await engine.runBacktest(config); expect(first.status).toBe('completed'); expect(first.trades.length).toBeGreaterThan(0); expect(first.trades).toEqual(second.trades); expect(first.metrics).toEqual(second.metrics); expect(first.equity).toEqual(second.equity); expect(first.metrics.totalReturn).toBeFinite(); expect(engine.getStatus().isRunning).toBe(false); }); test('all listings retain their first same-timestamp bar and deterministic tie ordering', async () => { const { mongodb } = memoryStore(); const other = { ...identity, exchange: 'OTHER', eodSearchCode: 'FIXTURE.OTHER' }; await persistEodPrices(mongodb, identity, fixture); await persistEodPrices(mongodb, other, fixture); const config = { ...datasetConfig(), symbols: [identity.eodSearchCode, other.eodSearchCode], config: { fastPeriod: 3, slowPeriod: 7 }, }; const storage = new StorageService({ logger }, mongodb, null, null); const engine = new RustBacktestAdapter({ logger, storage }); const first = await engine.runBacktest(config); const second = await engine.runBacktest(config); for (const id of config.symbols) { expect(first.ohlcData[id]).toHaveLength(fixture.length); expect(first.ohlcData[id]?.[0]?.timestamp).toBe(start.getTime()); } expect(first.trades).toEqual(second.trades); expect(first.metrics).toEqual(second.metrics); expect(first.equity).toEqual(second.equity); }); test('rejects malformed provider records before writing anything', async () => { const { documents, mongodb } = memoryStore(); await expect( persistEodPrices(mongodb, identity, [{ ...fixture[0]!, low: -1 }]) ).rejects.toThrow('Invalid OHLCV'); expect(documents).toHaveLength(0); }); test('missing storage never silently produces synthetic prices', async () => { const storage = new StorageService({ logger }, null, null, null); await expect(storage.getHistoricalBars('FIXTURE.TEST', start, end, '1d')).rejects.toThrow( 'explicit opt-in' ); }); test('explicit synthetic fixtures use a stable seed', async () => { const storage = new StorageService({ logger }, null, null, null, { allowSyntheticData: true, syntheticSeed: 7, }); expect(await storage.getHistoricalBars('FIXTURE.TEST', start, end, '1d')).toEqual( await storage.getHistoricalBars('FIXTURE.TEST', start, end, '1d') ); }); test('empty storage and unknown strategies fail without leaving the engine running', async () => { const { mongodb } = memoryStore(); const storage = new StorageService({ logger }, mongodb, null, null); const engine = new RustBacktestAdapter({ logger, storage }); const config = BacktestConfigSchema.parse({ mode: 'backtest', symbols: ['FIXTURE.TEST'], strategy: 'sma-crossover', startDate: start.toISOString(), endDate: end.toISOString(), initialCapital: 100000, dataFrequency: '1d', }); await expect(engine.runBacktest(config)).rejects.toThrow('No historical data'); await expect(engine.runBacktest({ ...config, strategy: 'does-not-exist' })).rejects.toThrow( 'Unknown native strategy' ); expect(engine.getStatus().isRunning).toBe(false); }); }); function datasetConfig() { return BacktestConfigSchema.parse({ mode: 'backtest', symbols: [identity.eodSearchCode], strategy: 'sma-crossover', startDate: start.toISOString(), endDate: end.toISOString(), initialCapital: 100000, dataFrequency: '1d', }); }