import { z } from 'zod'; import { datasetUnavailableReason, manifestSchema, preparationManifestSchema, } from '@stock-bot/research/dataset-contracts'; import { candidateExecutionSchema } from '@stock-bot/stock-config/candidate-execution'; import { canonicalRunRequestSchema, declaredStoredSourceWindows, } from '@stock-bot/stock-config/canonical-research'; import type { CanonicalDatasetCatalogEntry, CanonicalDatasetPreparation, CanonicalReproductionComparison, CanonicalReproductionPreview, CanonicalRunCapability, CanonicalStoredSourcePreparation, ResearchRunResult, } from '@stock-bot/stock-config/canonical-research'; import { backtestResponseSchema, runResponseSchema, type BacktestResponse as Backtest, type RunResponse as Run, } from '@stock-bot/stock-config/product-responses'; import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy'; import type { BacktestRunResult, HistoricalDatasetCatalogEntry, StrategyParameterValue, } from '@stock-bot/types'; import { API_BASE_URL, apiFetch as fetch } from '@/lib/api'; import { requestJson } from '@/lib/requestJson'; export type { BacktestResponse as Backtest, RunResponse as Run, } from '@stock-bot/stock-config/product-responses'; export interface CreateBacktestRequest { name: string; strategy: string; strategyVersionId?: string | null; strategyParameters?: Record | null; symbols: string[]; startDate: string; endDate: string; initialCapital: number; config?: Record; } export interface CreateRunRequest { speedMultiplier?: number | null; } export type RunResult = BacktestRunResult; export type { ResearchRunResult }; export class RunResultsUnavailableError extends Error { constructor() { super('Completed run results are not available'); this.name = 'RunResultsUnavailableError'; } } async function requestError(response: Response, fallback: string): Promise { const payload: unknown = await response.json().catch(() => null); const message = payload && typeof payload === 'object' && 'error' in payload && typeof payload.error === 'string' ? payload.error : `${fallback}: ${response.status} ${response.statusText}`; return new Error(message); } export class ReproductionSubmissionError extends Error { constructor( message: string, public readonly status: number | null ) { super(message); } get ambiguous() { return this.status === null || this.status >= 500; } } function productRequest( path: string, init: RequestInit, status: number, parse: (body: unknown) => T ): Promise { return requestJson(`${API_BASE_URL}/api/v2/${path}`, init, status, parse, { create: message => new Error(message), invalid: () => new Error( 'The backtest response could not be verified. Check saved runs before submitting again.' ), lostMessage: 'The backtest response was lost. Check saved runs before submitting again.', failureLabel: 'Backtest request failed', }); } const jsonRequest = (method: string, body: unknown): RequestInit => ({ method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); const acknowledgement = z.object({ message: z.string() }); const isRecord = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value); const nullableText = (value: unknown) => value === null || typeof value === 'string'; const hashOrNull = (value: unknown) => value === null || (typeof value === 'string' && /^[a-f0-9]{64}$/.test(value)); const preparationText = z.string().min(1); const preparationHash = z.string().regex(/^[a-f0-9]{64}$/); const preparationInstant = z.number().int().nonnegative().max(8_640_000_000_000_000); const preparationManifest = preparationManifestSchema; const datasetPreparationSchema = z .object({ version: z.literal('canonical-dataset-preparation/v1'), hash: preparationHash, manifest: preparationManifest, available: z.boolean(), reason: preparationText.nullable(), }) .strict(); export function parseDatasetPreparation( raw: unknown, expectedHash?: string ): CanonicalDatasetPreparation { const value = datasetPreparationSchema.parse(raw), manifest = value.manifest; const available = datasetUnavailableReason(manifest) === null; if ( value.hash !== manifest.hash || (expectedHash !== undefined && value.hash !== expectedHash) || value.available !== available || (value.available ? value.reason !== null : value.reason === null) || new Set(manifest.series.map(item => item.id)).size !== manifest.series.length || new Set(manifest.calendars.map(item => item.id)).size !== manifest.calendars.length || manifest.series.some( item => !manifest.calendars.some( calendar => calendar.id === item.calendarId && calendar.venue === item.venue ) ) || manifest.executionSeries.some( item => !manifest.series.some( series => series.id === item.seriesId && series.instrumentId === item.instrumentId ) ) ) { throw new Error('The dataset preparation response could not be verified.'); } return value; } const canonicalDatasetEntrySchema = z .object({ hash: preparationHash, createdAt: z.string().min(1), manifest: manifestSchema.nullable(), available: z.boolean(), reason: preparationText.nullable(), }) .strict() .refine(entry => { const manifest = entry.manifest; return ( (entry.available ? manifest !== null && entry.reason === null && datasetUnavailableReason(manifest) === null : entry.reason !== null) && (!manifest || (manifest.hash === entry.hash && manifest.bounds.warmupStart <= manifest.bounds.tradeStart && manifest.bounds.tradeStart < manifest.bounds.tradeEnd && manifest.calendars.every(calendar => calendar.sessions.every(session => session.open < session.close) ))) ); }, 'Invalid canonical dataset descriptor'); const preparationMetadata = preparationManifest.pick({ calendars: true, series: true, executionSeries: true, bounds: true, universe: true, corporateActions: true, }); const storedSourceInput = z .object({ metadata: preparationMetadata, bars: z .array( z .object({ seriesId: preparationText, timestamp: preparationInstant, sourceSequence: z.number().int().nonnegative().safe(), open: z.number().finite().positive(), high: z.number().finite().positive(), low: z.number().finite().positive(), close: z.number().finite().positive(), volume: z.number().finite().nonnegative(), vwap: z.number().finite().positive().nullable().optional(), }) .strict() ) .min(1), }) .strict(); type PreparationMetadata = z.infer; const compareText = (left: string, right: string) => (left < right ? -1 : left > right ? 1 : 0); /** Compare declarations across server-normalized collection order; never normalize bars or calculate hashes. */ function metadataIdentity(value: PreparationMetadata) { return canonicalStrategyJson({ ...value, calendars: value.calendars .map(calendar => ({ ...calendar, sessions: [...calendar.sessions].sort((a, b) => compareText(a.date, b.date)), })) .sort((a, b) => compareText(a.id, b.id)), series: [...value.series].sort((a, b) => compareText(a.id, b.id)), executionSeries: [...value.executionSeries].sort((a, b) => compareText(a.instrumentId, b.instrumentId) ), universe: { ...value.universe, instrumentIds: [...value.universe.instrumentIds].sort(compareText), }, corporateActions: value.corporateActions .map(coverage => ({ ...coverage, actions: [...coverage.actions].sort( (a, b) => a.effectiveAt - b.effectiveAt || compareText(a.reference, b.reference) ), })) .sort((a, b) => compareText(a.instrumentId, b.instrumentId)), }); } /** Preview caller declarations only; the server still validates the complete metadata and bars. */ export function storedSourceSessionScope(raw: unknown) { const parsed = preparationMetadata.safeParse(raw); return parsed.success && parsed.data.series.length === 1 ? declaredStoredSourceWindows(parsed.data) : null; } export function parseStoredDatasetPreparation( raw: unknown, suppliedMetadata: unknown, selection?: CanonicalStoredSourcePreparation['selection'] ): CanonicalStoredSourcePreparation { const envelope = z .object({ input: storedSourceInput, preparation: z.unknown(), selection: z.literal('declared-sessions').optional(), }) .strict() .parse(raw); if (envelope.selection !== selection) { throw new Error('The stored source response does not match the requested selection.'); } const preparation = parseDatasetPreparation(envelope.preparation); const expected = preparationMetadata.parse(suppliedMetadata); const { calendars, series, executionSeries, bounds, universe, corporateActions } = preparation.manifest; const retainedMetadata = { calendars, series, executionSeries, bounds, universe, corporateActions, }; const input = envelope.input, metadata = input.metadata, selected = metadata.series[0]; if ( !selected || metadata.series.length !== 1 || metadata.executionSeries.length !== 1 || metadata.universe.instrumentIds.length !== 1 || selected.source.provider !== 'eod' || !['1m', '5m', '1h'].includes(selected.interval) || selected.adjustment !== 'raw' || selected.timestamp !== 'interval-start' || selected.availability !== 'interval-end-assumption' || metadata.executionSeries[0]?.seriesId !== selected.id || metadata.executionSeries[0]?.instrumentId !== selected.instrumentId || metadata.universe.instrumentIds[0] !== selected.instrumentId || metadataIdentity(metadata) !== metadataIdentity(expected) || metadataIdentity(metadata) !== metadataIdentity(preparationMetadata.parse(retainedMetadata)) || input.bars.length !== preparation.manifest.barCount || input.bars.some( (bar, index) => bar.seriesId !== selected.id || bar.sourceSequence !== index || bar.timestamp < metadata.bounds.warmupStart || bar.timestamp >= metadata.bounds.tradeEnd || (index > 0 && bar.timestamp <= (input.bars[index - 1]?.timestamp ?? Infinity)) ) ) { throw new Error('The stored source response does not match its metadata and prepared dataset.'); } return { input, preparation, ...(selection ? { selection } : {}) }; } export class DatasetPreparationRequestError extends Error { constructor( message: string, public readonly status: number ) { super(message); this.name = 'DatasetPreparationRequestError'; } } async function prepareDatasetRequest( body: { input: unknown; expectedHash?: string }, signal?: AbortSignal ): Promise { const operation = body.expectedHash === undefined ? 'preview' : 'retain'; const response = await fetch(`${API_BASE_URL}/api/v2/datasets/canonical/${operation}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal, }); if (!response.ok) { throw new DatasetPreparationRequestError( (await requestError(response, `Could not ${operation} dataset`)).message, response.status ); } try { if (response.status !== 200) { throw new Error('Unexpected dataset preparation status'); } const envelope = z .object({ preparation: z.unknown() }) .strict() .parse(await response.json()); return parseDatasetPreparation(envelope.preparation, body.expectedHash); } catch { throw new Error('The dataset preparation response could not be verified.'); } } export const backtestApiV2 = { async downloadCanonicalDataset(hash: string, signal?: AbortSignal): Promise { if (!/^[a-f0-9]{64}$/.test(hash)) { throw new Error('Enter a retained dataset hash of 64 lowercase hexadecimal characters.'); } signal?.throwIfAborted(); const response = await fetch( `${API_BASE_URL}/api/v2/datasets/canonical/${encodeURIComponent(hash)}/export`, { signal } ); if (!response.ok) { throw await requestError(response, 'Could not download retained dataset'); } try { if ( response.status !== 200 || response.headers.get('Content-Type')?.split(';')[0]?.trim().toLowerCase() !== 'application/json' ) { throw new Error('Unexpected dataset download response'); } const text = await response.text(); signal?.throwIfAborted(); const value = z .object({ manifest: manifestSchema, bars: z.array(z.unknown()) }) .strict() .parse(JSON.parse(text)); if (value.manifest.hash !== hash || value.manifest.barCount !== value.bars.length) { throw new Error('Unexpected dataset download identity'); } // Preserve the received representation. Full content/hash validation belongs to the server. return text; } catch { throw new Error('The retained dataset download response could not be verified.'); } }, previewDataset: (input: unknown, signal?: AbortSignal) => prepareDatasetRequest({ input }, signal), retainDataset: (input: unknown, expectedHash: string, signal?: AbortSignal) => prepareDatasetRequest({ input, expectedHash }, signal), async previewStoredDataset( metadata: unknown, signal?: AbortSignal, selection?: CanonicalStoredSourcePreparation['selection'] ): Promise { const response = await fetch(`${API_BASE_URL}/api/v2/datasets/canonical/stored-source`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ metadata, ...(selection ? { selection } : {}) }), signal, }); if (!response.ok) { throw await requestError(response, 'Could not load stored EOD bars'); } try { if (response.status !== 200) { throw new Error('Unexpected stored source status'); } return parseStoredDatasetPreparation(await response.json(), metadata, selection); } catch { throw new Error('The stored source response could not be verified.'); } }, async reproductionPreview( id: string, signal?: AbortSignal ): Promise { const response = await fetch( `${API_BASE_URL}/api/v2/runs/${encodeURIComponent(id)}/reproduction`, { signal } ); if (!response.ok) { throw await requestError(response, 'Could not check original-run reproduction'); } const body: unknown = await response.json(); if ( !isRecord(body) || body.originalRunId !== id || typeof body.backtestId !== 'string' || typeof body.available !== 'boolean' || !nullableText(body.reason) || !nullableText(body.currentReviewId) ) { throw new Error('The original-run preview response could not be verified'); } const request = body.request === null ? null : canonicalRunRequestSchema.parse(body.request); if ( (request && (request.runId !== id || request.backtestId !== body.backtestId)) || (body.available && (!request || (request.strategy.origin === 'builtin' && !body.currentReviewId))) ) { throw new Error('The original-run preview does not match its retained source'); } return { originalRunId: id, backtestId: body.backtestId, available: body.available, reason: body.reason as string | null, currentReviewId: body.currentReviewId as string | null, request, }; }, async reproduceRun(originalRunId: string, submissionKey: string): Promise { return requestJson( `${API_BASE_URL}/api/v2/runs/${encodeURIComponent(originalRunId)}/reproduce`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Idempotency-Key': submissionKey }, body: '{}', }, 202, body => { const run = runResponseSchema.parse(body); if (run.id === originalRunId || run.originalRunId !== originalRunId) { throw new Error('Wrong original run identity'); } return run; }, { create: (message, status) => new ReproductionSubmissionError(message, status), invalid: () => new ReproductionSubmissionError( 'The accepted reproduction response could not be verified. Retry with this same submission key.', null ), lostMessage: 'The reproduction response was lost. Retry with this same submission key to recover the accepted run.', failureLabel: 'Could not reproduce original run', } ); }, async reproductionComparison( id: string, signal?: AbortSignal ): Promise { const response = await fetch( `${API_BASE_URL}/api/v2/runs/${encodeURIComponent(id)}/reproduction-comparison`, { signal } ); if (!response.ok) { throw await requestError(response, 'Could not load reproduction comparison'); } const body: unknown = await response.json(); if ( !isRecord(body) || body.version !== 'canonical-reproduction/v1' || body.runId !== id || typeof body.backtestId !== 'string' || !nullableText(body.originalRunId) || !nullableText(body.reason) || !hashOrNull(body.originalHash) || !hashOrNull(body.reproducedHash) || !['not-reproduction', 'pending', 'unavailable', 'match', 'mismatch'].includes( String(body.status) ) || (['match', 'mismatch'].includes(String(body.status)) && (!body.originalRunId || !body.originalHash || !body.reproducedHash)) || (body.status === 'match' && body.originalHash !== body.reproducedHash) || (body.status === 'mismatch' && body.originalHash === body.reproducedHash) ) { throw new Error('The reproduction comparison response could not be verified'); } return body as unknown as CanonicalReproductionComparison; }, async canonicalCapability(id: string, signal?: AbortSignal): Promise { const response = await fetch( `${API_BASE_URL}/api/v2/backtests/${encodeURIComponent(id)}/canonical-capability`, { signal } ); if (!response.ok) { throw await requestError(response, 'Could not check canonical execution eligibility'); } const capability = z .object({ available: z.boolean(), reason: z.string().nullable(), execution: candidateExecutionSchema.optional(), }) .strict() .parse(await response.json()); if (capability.execution && !capability.available) { throw new Error('Unavailable execution cannot advertise an admitted sandbox profile'); } return capability; }, async listCanonicalDatasets( limit = 50, offset = 0, signal?: AbortSignal ): Promise { if (!Number.isSafeInteger(limit) || limit < 1 || !Number.isSafeInteger(offset) || offset < 0) { throw new Error( 'Canonical dataset pagination requires a positive limit and nonnegative offset' ); } const response = await fetch( `${API_BASE_URL}/api/v2/datasets/canonical?limit=${limit}&offset=${offset}`, { signal } ); if (!response.ok) { throw await requestError(response, 'Could not load canonical datasets'); } try { const value = z .object({ datasets: canonicalDatasetEntrySchema.array() }) .strict() .parse(await response.json()); signal?.throwIfAborted(); if (response.status !== 200 || value.datasets.length > limit) { throw new Error('Unexpected canonical dataset page'); } return value.datasets; } catch { throw new Error('The canonical dataset catalog response could not be verified.'); } }, async canonicalDataset( hash: string, signal?: AbortSignal ): Promise { if (!/^[a-f0-9]{64}$/.test(hash)) { throw new Error('Enter a retained dataset hash of 64 lowercase hexadecimal characters.'); } const response = await fetch( `${API_BASE_URL}/api/v2/datasets/canonical/${encodeURIComponent(hash)}`, { signal } ); if (!response.ok) { throw await requestError(response, 'Could not load canonical dataset'); } try { const value = z .object({ dataset: canonicalDatasetEntrySchema }) .strict() .parse(await response.json()); signal?.throwIfAborted(); if (response.status !== 200 || value.dataset.hash !== hash) { throw new Error('Unexpected canonical dataset identity'); } return value.dataset; } catch { throw new Error( 'The canonical dataset response could not be verified for the requested hash.' ); } }, async listDatasets( limit = 50, offset = 0, signal?: AbortSignal ): Promise { const response = await fetch( `${API_BASE_URL}/api/v2/datasets?limit=${limit}&offset=${offset}`, { signal } ); if (!response.ok) { throw await requestError(response, 'Failed to load frozen datasets'); } return (await response.json()).datasets; }, async getDataset(hash: string, signal?: AbortSignal): Promise { const response = await fetch(`${API_BASE_URL}/api/v2/datasets/${encodeURIComponent(hash)}`, { signal, }); if (!response.ok) { throw await requestError(response, 'Failed to load frozen dataset'); } return (await response.json()).dataset; }, // Templates are saved separately from durable run submission. createBacktest(request: CreateBacktestRequest): Promise { return productRequest( 'backtests', jsonRequest('POST', { ...request, autoStart: false }), 201, backtestResponseSchema.parse ); }, getBacktest(id: string): Promise { return productRequest( `backtests/${encodeURIComponent(id)}`, {}, 200, backtestResponseSchema.parse ); }, listBacktests( limit = 50, offset = 0, includeArchived = false, signal?: AbortSignal ): Promise { return productRequest( `backtests?limit=${limit}&offset=${offset}${includeArchived ? '&includeArchived=true' : ''}`, { signal }, 200, backtestResponseSchema.array().parse ); }, updateBacktest(id: string, updates: Partial): Promise { return productRequest( `backtests/${encodeURIComponent(id)}`, jsonRequest('PUT', updates), 200, backtestResponseSchema.parse ); }, deleteBacktest(id: string): Promise { return productRequest( `backtests/${encodeURIComponent(id)}`, { method: 'DELETE' }, 204, z.undefined().parse ); }, setBacktestArchived(id: string, archived: boolean): Promise { return productRequest( `backtests/${encodeURIComponent(id)}/archive`, jsonRequest('POST', { archived }), 200, backtestResponseSchema.parse ); }, createRun(backtestId: string, request?: CreateRunRequest, submissionKey?: string): Promise { return productRequest( `backtests/${encodeURIComponent(backtestId)}/runs`, { ...jsonRequest('POST', request || {}), headers: { 'Content-Type': 'application/json', ...(submissionKey ? { 'Idempotency-Key': submissionKey } : {}), }, }, 202, body => { const run = runResponseSchema.parse(body); if (run.backtestId !== backtestId) { throw new Error('Wrong backtest identity'); } return run; } ); }, listRuns(backtestId: string): Promise { return productRequest( `backtests/${encodeURIComponent(backtestId)}/runs`, {}, 200, runResponseSchema.array().parse ); }, getRun(id: string, signal?: AbortSignal): Promise { return productRequest( `runs/${encodeURIComponent(id)}`, { signal }, 200, runResponseSchema.parse ); }, async getRunResults(runId: string, signal?: AbortSignal): Promise { const response = await fetch(`${API_BASE_URL}/api/v2/runs/${runId}/results`, { signal }); if (response.status === 404) { throw new RunResultsUnavailableError(); } if (!response.ok) { throw await requestError(response, 'Failed to get run results'); } return response.json(); }, async pauseRun(id: string): Promise { await productRequest( `runs/${encodeURIComponent(id)}/pause`, { method: 'POST' }, 200, acknowledgement.parse ); }, async resumeRun(id: string): Promise { await productRequest( `runs/${encodeURIComponent(id)}/resume`, { method: 'POST' }, 200, acknowledgement.parse ); }, async cancelRun(id: string, signal?: AbortSignal): Promise { await productRequest( `runs/${encodeURIComponent(id)}/cancel`, { method: 'POST', signal }, 202, acknowledgement.parse ); }, async updateRunSpeed(id: string, speedMultiplier: number | null): Promise { await productRequest( `runs/${encodeURIComponent(id)}/speed`, jsonRequest('PUT', { speedMultiplier }), 200, acknowledgement.parse ); }, // Note: WebSocket connections are handled by the useWebSocket hook // which connects to ws://localhost:2003/ws?runId={runId} };