stock-bot/apps/stock/web-app/src/features/backtest/services/backtestApiV2.ts

812 lines
26 KiB
TypeScript

import { z } from 'zod';
import { candidateExecutionSchema } from '@stock-bot/stock-config/candidate-execution';
import { canonicalRunRequestSchema } from '@stock-bot/stock-config/canonical-research';
import type {
CanonicalDatasetCatalogEntry,
CanonicalDatasetPreparation,
CanonicalReproductionComparison,
CanonicalReproductionPreview,
CanonicalRunCapability,
CanonicalStoredSourcePreparation,
ResearchRunResult,
} from '@stock-bot/stock-config/canonical-research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import type {
BacktestRunDatasetSelection,
BacktestRunResult,
HistoricalDatasetCatalogEntry,
StrategyParameterValue,
} from '@stock-bot/types';
import { API_BASE_URL, apiFetch as fetch } from '@/lib/api';
export interface Backtest {
id: string;
name: string;
strategy: string;
strategyVersionId?: string | null;
strategyParameters?: Record<string, StrategyParameterValue> | null;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
config: Record<string, unknown>;
createdAt: string;
updatedAt: string;
archivedAt: string | null;
}
export interface Run {
id: string;
originalRunId?: string | null;
backtestId: string;
runNumber: number;
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled' | 'paused';
speedMultiplier: number | null;
error?: string;
startedAt?: string;
completedAt?: string;
pausedAt?: string;
progress: number;
cancelRequested?: boolean;
attemptNumber?: number;
currentSimulationDate?: string;
createdAt: string;
updatedAt: string;
dataset?: BacktestRunDatasetSelection;
}
export interface CreateBacktestRequest {
name: string;
strategy: string;
strategyVersionId?: string | null;
strategyParameters?: Record<string, StrategyParameterValue> | null;
symbols: string[];
startDate: string;
endDate: string;
initialCapital: number;
config?: Record<string, unknown>;
}
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<Error> {
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;
}
}
const isRecord = (value: unknown): value is Record<string, unknown> =>
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 preparationDay = z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/)
.refine(
value =>
Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value
);
const preparationManifest = z
.object({
version: z.literal(2),
hash: preparationHash,
normalizationRevision: z.literal('historical-normalization-v2'),
parentDatasetHash: z.null(),
volumePolicy: z.literal('reported'),
qualityPolicy: z.literal('reject-invalid-no-interpolation'),
intradayPolicy: z.literal('full-duration-session-contained'),
eligibility: z.enum(['eligible', 'exploratory', 'ineligible']),
limitations: z.array(preparationText),
barCount: z.number().int().positive().safe(),
calendars: z
.array(
z
.object({
id: preparationText,
venue: preparationText,
timeZone: preparationText,
source: preparationText,
revision: preparationText,
startDate: preparationDay,
endDate: preparationDay,
sessions: z
.array(
z
.object({
date: preparationDay,
open: preparationInstant,
close: preparationInstant,
})
.strict()
.refine(value => value.open < value.close)
)
.min(1),
})
.strict()
)
.min(1),
series: z
.array(
z
.object({
id: preparationText,
instrumentId: preparationText,
interval: z.enum(['1m', '5m', '15m', '1h', '1d']),
calendarId: preparationText,
venue: preparationText,
source: z.object({ provider: preparationText, revision: preparationText }).strict(),
timestamp: z.enum(['session-date', 'interval-start', 'interval-end']),
availability: z.enum(['explicit', 'interval-end-assumption']),
adjustment: z.enum(['raw', 'provider-adjusted']),
})
.strict()
)
.min(1),
executionSeries: z
.array(z.object({ instrumentId: preparationText, seriesId: preparationText }).strict())
.min(1),
bounds: z
.object({
warmupStart: preparationInstant,
tradeStart: preparationInstant,
tradeEnd: preparationInstant,
})
.strict()
.refine(value => value.warmupStart <= value.tradeStart && value.tradeStart < value.tradeEnd),
universe: z
.object({
selection: z.enum(['point-in-time', 'current-constituents', 'unknown']),
asOf: preparationInstant.nullable(),
revision: preparationText,
instrumentIds: z.array(preparationText).min(1),
})
.strict(),
corporateActions: z
.array(
z
.object({
instrumentId: preparationText,
status: z.enum(['unknown', 'action-free', 'known-actions']),
start: preparationInstant,
end: preparationInstant,
revision: preparationText,
actions: z.array(
z
.object({
effectiveAt: preparationInstant,
kind: z.enum(['split', 'dividend', 'other']),
reference: preparationText,
})
.strict()
),
})
.strict()
)
.min(1),
})
.strict();
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 =
manifest.eligibility === 'eligible' &&
manifest.executionSeries.length === 1 &&
manifest.series.length === 1 &&
manifest.universe.instrumentIds.length === 1;
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 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<typeof preparationMetadata>;
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)),
});
}
export function parseStoredDatasetPreparation(
raw: unknown,
suppliedMetadata: unknown
): CanonicalStoredSourcePreparation {
const envelope = z
.object({ input: storedSourceInput, preparation: z.unknown() })
.strict()
.parse(raw);
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 };
}
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<CanonicalDatasetPreparation> {
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 = {
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
): Promise<CanonicalStoredSourcePreparation> {
const response = await fetch(`${API_BASE_URL}/api/v2/datasets/canonical/stored-source`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ metadata }),
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);
} catch {
throw new Error('The stored source response could not be verified.');
}
},
async reproductionPreview(
id: string,
signal?: AbortSignal
): Promise<CanonicalReproductionPreview> {
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 || !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<Run> {
let response: Response;
try {
response = await fetch(
`${API_BASE_URL}/api/v2/runs/${encodeURIComponent(originalRunId)}/reproduce`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': submissionKey },
body: '{}',
}
);
} catch {
throw new ReproductionSubmissionError(
'The reproduction response was lost. Retry with this same submission key to recover the accepted run.',
null
);
}
if (!response.ok) {
const error = await requestError(response, 'Could not reproduce original run');
throw new ReproductionSubmissionError(error.message, response.status);
}
const body: unknown = await response.json().catch(() => null);
if (
response.status !== 202 ||
!isRecord(body) ||
typeof body.id !== 'string' ||
!body.id ||
body.id === originalRunId ||
typeof body.backtestId !== 'string' ||
body.originalRunId !== originalRunId ||
!['pending', 'running', 'completed', 'failed', 'cancelled', 'paused'].includes(
String(body.status)
)
) {
throw new ReproductionSubmissionError(
'The accepted reproduction response could not be verified. Retry with this same submission key.',
null
);
}
return body as unknown as Run;
},
async reproductionComparison(
id: string,
signal?: AbortSignal
): Promise<CanonicalReproductionComparison> {
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<CanonicalRunCapability> {
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(signal?: AbortSignal): Promise<CanonicalDatasetCatalogEntry[]> {
const response = await fetch(`${API_BASE_URL}/api/v2/datasets/canonical?limit=50&offset=0`, {
signal,
});
if (!response.ok) {
throw await requestError(response, 'Could not load canonical datasets');
}
return (await response.json()).datasets;
},
async canonicalDataset(
hash: string,
signal?: AbortSignal
): Promise<CanonicalDatasetCatalogEntry> {
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');
}
return (await response.json()).dataset;
},
async listDatasets(
limit = 50,
offset = 0,
signal?: AbortSignal
): Promise<HistoricalDatasetCatalogEntry[]> {
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<HistoricalDatasetCatalogEntry> {
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;
},
// Backtest operations
async createBacktest(request: CreateBacktestRequest): Promise<Backtest> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
// Web saves are deliberately separate from durable run submission.
body: JSON.stringify({ ...request, autoStart: false }),
});
if (!response.ok) {
throw await requestError(response, 'Failed to create backtest');
}
return response.json();
},
async getBacktest(id: string): Promise<Backtest> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`);
if (!response.ok) {
throw new Error(`Failed to get backtest: ${response.statusText}`);
}
return response.json();
},
async listBacktests(
limit = 50,
offset = 0,
includeArchived = false,
signal?: AbortSignal
): Promise<Backtest[]> {
const response = await fetch(
`${API_BASE_URL}/api/v2/backtests?limit=${limit}&offset=${offset}${includeArchived ? '&includeArchived=true' : ''}`,
{ signal }
);
if (!response.ok) {
throw await requestError(response, 'Failed to list backtests');
}
return response.json();
},
async updateBacktest(id: string, updates: Partial<CreateBacktestRequest>): Promise<Backtest> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updates),
});
if (!response.ok) {
throw await requestError(response, 'Failed to update backtest');
}
return response.json();
},
async deleteBacktest(id: string): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}`, {
method: 'DELETE',
});
if (!response.ok) {
throw await requestError(response, 'Failed to delete backtest');
}
},
async setBacktestArchived(id: string, archived: boolean): Promise<Backtest> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${id}/archive`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ archived }),
});
if (!response.ok) {
throw await requestError(response, 'Failed to change archive status');
}
return response.json();
},
// Run operations
async createRun(
backtestId: string,
request?: CreateRunRequest,
submissionKey?: string
): Promise<Run> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(submissionKey ? { 'Idempotency-Key': submissionKey } : {}),
},
body: JSON.stringify(request || {}),
});
if (!response.ok) {
throw await requestError(response, 'Failed to create run');
}
return response.json();
},
async listRuns(backtestId: string): Promise<Run[]> {
const response = await fetch(`${API_BASE_URL}/api/v2/backtests/${backtestId}/runs`);
if (!response.ok) {
throw new Error(`Failed to list runs: ${response.statusText}`);
}
return response.json();
},
async getRun(id: string, signal?: AbortSignal): Promise<Run> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}`, { signal });
if (!response.ok) {
throw new Error(`Failed to get run: ${response.statusText}`);
}
return response.json();
},
async getRunResults(runId: string, signal?: AbortSignal): Promise<ResearchRunResult> {
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<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/pause`, {
method: 'POST',
});
if (!response.ok) {
throw new Error(`Failed to pause run: ${response.statusText}`);
}
},
async resumeRun(id: string): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/resume`, {
method: 'POST',
});
if (!response.ok) {
throw new Error(`Failed to resume run: ${response.statusText}`);
}
},
async cancelRun(id: string, signal?: AbortSignal): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/cancel`, {
method: 'POST',
signal,
});
if (!response.ok) {
throw new Error(`Failed to cancel run: ${response.statusText}`);
}
},
async updateRunSpeed(id: string, speedMultiplier: number | null): Promise<void> {
const response = await fetch(`${API_BASE_URL}/api/v2/runs/${id}/speed`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ speedMultiplier }),
});
if (!response.ok) {
throw new Error(`Failed to update run speed: ${response.statusText}`);
}
},
// Note: WebSocket connections are handled by the useWebSocket hook
// which connects to ws://localhost:2003/ws?runId={runId}
};