import { useCallback, useEffect, useRef, useState } from 'react'; import { canonicalResearchSettingsSchema, type CanonicalDatasetCatalogEntry, type CanonicalResearchSettings, } from '@stock-bot/stock-config/canonical-research'; import { parseFinancialDecimal } from '@stock-bot/types'; import { actionClass, fieldClass } from '@/components/ui/formStyles'; import { StrategySelection, type CatalogSelection, } from '@/features/strategies/components/StrategySelection'; import { confirmDiscard, useUnsavedWarning } from '@/hooks/useUnsavedWarning'; import { backtestApiV2, type Backtest, type CreateBacktestRequest, } from '../services/backtestApiV2'; import { DatasetDownload } from './DatasetDownload'; import { DatasetPreparation, type DatasetPreparationState } from './DatasetPreparation'; type PolicyKey = Exclude; const policyFields: { key: PolicyKey; label: string; group: string; kind: 'decimal' | 'number' | 'nullable'; description: string; }[] = [ { key: 'ownerBudget', label: 'Owner budget', group: 'Strategy sizing', kind: 'decimal', description: 'USD sizing input supplied to the strategy. Rust enforces the separate position, exposure and cash constraints. This input cannot exceed initial capital.', }, { key: 'feeRate', label: 'Fee rate', group: 'Execution', kind: 'decimal', description: 'Fraction of fill notional charged once per fill. 0.001 means 0.1%.', }, { key: 'halfSpreadRate', label: 'Half-spread rate', group: 'Execution', kind: 'decimal', description: 'Fractional price adjustment for one side of the simulated spread.', }, { key: 'slippageRate', label: 'Slippage rate', group: 'Execution', kind: 'decimal', description: 'Additional adverse price fraction per fill.', }, { key: 'participationRate', label: 'Volume participation rate', group: 'Execution', kind: 'decimal', description: 'Maximum fraction of previously available completed-bar volume used for liquidity; this is not contemporaneous liquidity.', }, { key: 'latencyMs', label: 'Order latency (ms)', group: 'Execution', kind: 'number', description: 'Nonnegative delay before an order becomes eligible.', }, { key: 'maxOrderQuantity', label: 'Maximum order quantity', group: 'Financial constraints', kind: 'decimal', description: 'Absolute asset quantity per order.', }, { key: 'maxPositionQuantity', label: 'Maximum position quantity', group: 'Financial constraints', kind: 'decimal', description: 'Absolute asset quantity held by the strategy.', }, { key: 'maxSymbolExposure', label: 'Maximum asset exposure', group: 'Financial constraints', kind: 'decimal', description: 'USD notional exposure to the selected asset.', }, { key: 'maxGrossExposure', label: 'Maximum gross exposure', group: 'Financial constraints', kind: 'decimal', description: 'USD gross exposure across the account.', }, { key: 'maxDailyLoss', label: 'Maximum risk-period loss', group: 'Financial constraints', kind: 'decimal', description: 'USD loss from the declared risk-period baseline; zero is an active zero threshold.', }, { key: 'maxDrawdownAmount', label: 'Maximum drawdown amount', group: 'Financial constraints', kind: 'decimal', description: 'USD decline from peak equity; zero is an active zero threshold.', }, { key: 'maxMarkAgeMs', label: 'Maximum mark age (ms)', group: 'Financial constraints', kind: 'number', description: 'Maximum age of an available mark for financial admission.', }, { key: 'seed', label: 'Random seed', group: 'Research and reporting', kind: 'number', description: 'Integer seed retained with the run.', }, { key: 'periodsPerYear', label: 'Reporting periods per year', group: 'Research and reporting', kind: 'number', description: 'Explicit annualization convention for complete declared risk periods.', }, { key: 'annualRiskFreeRate', label: 'Annual risk-free rate', group: 'Research and reporting', kind: 'nullable', description: 'Fraction per year. Leave blank for unknown; zero is an explicit assumption.', }, ]; type RawPolicy = Record; function defaults(capital: number): CanonicalResearchSettings { return { version: 1, ownerBudget: String(capital), feeRate: '0.001', halfSpreadRate: '0.0005', slippageRate: '0.0005', participationRate: '0.1', latencyMs: 0, maxOrderQuantity: '1000000', maxPositionQuantity: '1000000', maxSymbolExposure: String(capital), maxGrossExposure: String(capital), maxDailyLoss: '1000', maxDrawdownAmount: '2000', maxMarkAgeMs: 604800000, seed: 1, periodsPerYear: 252, annualRiskFreeRate: null, }; } function initialPolicy(backtest: Backtest): RawPolicy { const input = backtest.config?.canonical; const source = input && typeof input === 'object' ? input : defaults(backtest.initialCapital); return Object.fromEntries( policyFields.map(({ key }) => { const value = Reflect.get(source, key); return [key, value === undefined || value === null ? '' : String(value)]; }) ) as RawPolicy; } export function canonicalDatasetFields(entry: CanonicalDatasetCatalogEntry) { const manifest = entry.manifest; if ( !entry.available || !manifest || manifest.version !== 2 || manifest.hash !== entry.hash || manifest.eligibility !== 'eligible' || manifest.executionSeries.length !== 1 ) { throw new Error(entry.reason ?? 'Choose an eligible single-asset canonical dataset.'); } const execution = manifest.executionSeries[0]; if (!execution) { throw new Error('Dataset execution series is missing.'); } const series = manifest.series.find( item => item.id === execution.seriesId && item.instrumentId === execution.instrumentId ); if (!series) { throw new Error('Dataset execution series is unavailable.'); } const startDate = new Date(manifest.bounds.tradeStart).toISOString(); const endDate = new Date(manifest.bounds.tradeEnd).toISOString(); return { symbols: [execution.instrumentId], startDate, endDate, warmupStart: new Date(manifest.bounds.warmupStart).toISOString(), dataFrequency: series.interval, }; } function parsePolicy(raw: RawPolicy): { settings?: CanonicalResearchSettings; errors: Partial>; } { const values: Record = { version: 1 }; const errors: Partial> = {}; for (const field of policyFields) { const text = raw[field.key]; try { if (field.kind === 'nullable' && text.trim() === '') { values[field.key] = null; } else if (field.kind === 'decimal') { values[field.key] = parseFinancialDecimal(text); } else { if (text.trim() === '' || !Number.isFinite(Number(text))) { throw new Error('Enter a finite number.'); } values[field.key] = Number(text); } } catch (cause) { errors[field.key] = cause instanceof Error ? cause.message : 'Invalid value'; } } if (Object.keys(errors).length) { return { errors }; } const parsed = canonicalResearchSettingsSchema.safeParse(values); if (!parsed.success) { for (const issue of parsed.error.issues) { const key = issue.path[0] as PolicyKey; errors[key] = issue.message; } return { errors }; } return { settings: parsed.data, errors }; } export function CanonicalSetup({ backtest, disabled = false, onSave, onClose, }: { backtest: Backtest; disabled?: boolean; onSave: (request: CreateBacktestRequest) => Promise; onClose?: () => void; }) { const [name, setName] = useState(backtest.name); const [capital, setCapital] = useState(String(backtest.initialCapital)); const [raw, setRaw] = useState(() => initialPolicy(backtest)); const [hash, setHash] = useState( typeof backtest.config?.canonical === 'object' && typeof backtest.config?.datasetHash === 'string' ? backtest.config?.datasetHash : '' ); const [selection, setSelection] = useState({ strategyVersionId: backtest.strategyVersionId, strategyParameters: backtest.strategyParameters, }); const [strategyValid, setStrategyValid] = useState(false); const [epoch, setEpoch] = useState(0); const [catalog, setCatalog] = useState([]); const [dataset, setDataset] = useState(null); const [catalogLoading, setCatalogLoading] = useState(true); const [datasetLoading, setDatasetLoading] = useState(false); const [catalogError, setCatalogError] = useState(null); const [datasetError, setDatasetError] = useState(null); const [retry, setRetry] = useState(0); const [detailRetry, setDetailRetry] = useState(0); const [knownHash, setKnownHash] = useState(''); const [knownHashError, setKnownHashError] = useState(null); const [hasMore, setHasMore] = useState(false); const nextOffset = useRef(0); const catalogRequest = useRef(null); const datasetRequest = useRef(null); const selectedHash = useRef(hash); const invalidHashDraft = useRef(false); const [saving, setSaving] = useState(false); const [error, setError] = useState(null); const [dirty, setDirty] = useState(false); const authoritative = useRef(backtest); const currentBacktest = useRef(backtest); currentBacktest.current = backtest; const preparationRef = useRef({ busy: false, blocking: false }); const [preparation, setPreparation] = useState(preparationRef.current); const preparationChanged = useCallback((value: DatasetPreparationState) => { preparationRef.current = value; setPreparation(value); if (value.blocking) { setDirty(true); } }, []); const pending = useRef(false); const active = useRef(true); useUnsavedWarning(dirty); useEffect(() => { active.current = true; return () => { active.current = false; }; }, []); useEffect(() => { if (backtest === authoritative.current) { return; } authoritative.current = backtest; catalogRequest.current?.abort(); datasetRequest.current?.abort(); setDataset(null); invalidHashDraft.current = false; setName(backtest.name); setCapital(String(backtest.initialCapital)); setRaw(initialPolicy(backtest)); setHash( typeof backtest.config?.canonical === 'object' && typeof backtest.config?.datasetHash === 'string' ? backtest.config?.datasetHash : '' ); selectedHash.current = typeof backtest.config?.canonical === 'object' && typeof backtest.config?.datasetHash === 'string' ? backtest.config?.datasetHash : ''; setKnownHash(''); setKnownHashError(null); setSelection({ strategyVersionId: backtest.strategyVersionId, strategyParameters: backtest.strategyParameters, }); setStrategyValid(false); setEpoch(value => value + 1); preparationRef.current = { busy: false, blocking: false }; setPreparation(preparationRef.current); setDirty(false); setError(null); }, [backtest]); const loadCatalog = useCallback(async (offset: number, replace = false) => { if (!replace && catalogRequest.current) { return; } catalogRequest.current?.abort(); const controller = new AbortController(); catalogRequest.current = controller; setCatalogLoading(true); setCatalogError(null); if (replace) { nextOffset.current = 0; setCatalog([]); setHasMore(false); } try { const entries = await backtestApiV2.listCanonicalDatasets(50, offset, controller.signal); if (!controller.signal.aborted && active.current) { setCatalog(previous => [ ...new Map( [...(replace ? [] : previous), ...entries].map(entry => [entry.hash, entry]) ).values(), ]); nextOffset.current = offset + entries.length; setHasMore(entries.length === 50); } } catch (cause) { if (!controller.signal.aborted && active.current) { setCatalogError( cause instanceof Error ? cause.message : 'Could not load canonical datasets' ); } } finally { if (!controller.signal.aborted && active.current) { catalogRequest.current = null; setCatalogLoading(false); } } }, []); useEffect(() => { void loadCatalog(0, true); return () => { catalogRequest.current?.abort(); }; }, [retry, epoch, loadCatalog]); useEffect(() => { const controller = new AbortController(); datasetRequest.current = controller; setDataset(null); setDatasetError(null); setDatasetLoading(Boolean(hash)); if (hash) { void backtestApiV2 .canonicalDataset(hash, controller.signal) .then(entry => { if (!controller.signal.aborted && selectedHash.current === hash && active.current) { if (entry.hash !== hash) { throw new Error('Dataset lookup returned a different hash.'); } setDataset(entry); } }) .catch(cause => { if (!controller.signal.aborted && selectedHash.current === hash && active.current) { setDatasetError(cause.message); } }) .finally(() => { if (!controller.signal.aborted && selectedHash.current === hash && active.current) { setDatasetLoading(false); } }); } return () => controller.abort(); }, [hash, retry, detailRetry, epoch]); const chooseHash = (next: string) => { datasetRequest.current?.abort(); selectedHash.current = next; setHash(next); setDataset(null); setDatasetError(null); setDatasetLoading(Boolean(next)); setKnownHashError(null); invalidHashDraft.current = false; setDetailRetry(value => value + 1); setDirty(true); }; const refreshDatasets = () => { catalogRequest.current?.abort(); datasetRequest.current?.abort(); setDataset(null); setDatasetLoading(Boolean(selectedHash.current)); setRetry(value => value + 1); }; const parsed = parsePolicy(raw); let selectedFields: ReturnType | undefined; let compatibilityError: string | null = null; if (dataset && dataset.hash === hash) { try { selectedFields = canonicalDatasetFields(dataset); } catch (cause) { compatibilityError = cause instanceof Error ? cause.message : 'Dataset is unsupported'; } } const validCapital = capital.trim() !== '' && Number.isFinite(Number(capital)) && Number(capital) > 0; const locked = disabled || saving; const valid = Boolean( name.trim() && validCapital && selectedFields && !datasetLoading && !knownHashError && parsed.settings && selection.strategyVersionId && strategyValid ); const save = async (event: React.FormEvent) => { event.preventDefault(); if ( locked || pending.current || selectedHash.current !== hash || invalidHashDraft.current || datasetRequest.current?.signal.aborted || preparationRef.current.busy || preparationRef.current.blocking || !valid || !selectedFields || !parsed.settings ) { return; } pending.current = true; setSaving(true); setError(null); try { await onSave({ name, strategy: 'catalog', strategyVersionId: selection.strategyVersionId, strategyParameters: selection.strategyParameters, symbols: selectedFields.symbols, startDate: selectedFields.startDate, endDate: selectedFields.endDate, initialCapital: Number(capital), config: { datasetHash: hash, dataFrequency: selectedFields.dataFrequency, canonical: parsed.settings, }, }); if (active.current) { setDirty(false); } } catch (cause) { if (active.current) { setError(cause instanceof Error ? cause.message : 'Could not save canonical setup'); } } finally { pending.current = false; if (active.current) { setSaving(false); } } }; const options = dataset && !catalog.some(entry => entry.hash === dataset.hash) ? [dataset, ...catalog] : catalog; return (
void save(event)} onChange={() => setDirty(true)} >

Canonical research setup

Review every policy below. Rust enforces accounting, fills and financial limits. This workflow supports one asset and reviewed built-in versions; saving does not start a run.

{dirty && (

Unsaved canonical setup. Save or discard before leaving.

)}
{!validCapital && (

Initial capital must be a positive finite number.

)}
{hasMore && ( )}
event.stopPropagation()}>
{catalogLoading &&

Loading canonical datasets...

} {!catalogLoading && !catalogError && !catalog.length && (

No canonical datasets are listed. Use a known retained hash or prepare a dataset with explicit sessions and availability.

)} {datasetLoading &&

Loading selected canonical dataset...

} {[catalogError, datasetError, compatibilityError, knownHashError] .filter(Boolean) .map((message, index) => (

{message}

))} {catalogError && ( )} {(datasetError || compatibilityError) && ( )} {hash && !selectedFields && !datasetLoading && (

The selected hash has not been verified for this setup. Saving stays disabled until compatible retained metadata is available.

)} {selectedFields && (
Execution asset
{selectedFields.symbols.join(', ')}
Execution interval
{selectedFields.dataFrequency}
Trading start (UTC)
{selectedFields.startDate}
Trading end (UTC, exclusive)
{selectedFields.endDate}
Warmup start (UTC)
{selectedFields.warmupStart}
)} {selectedFields && }
Prepare dataset from source export !disabled && !pending.current && active.current && currentBacktest.current === backtest } onStateChange={preparationChanged} onRetained={(retainedHash, available) => { if (!active.current || currentBacktest.current !== backtest) { return; } if (available) { chooseHash(retainedHash); } refreshDatasets(); setDirty(true); }} />
{[...new Set(policyFields.map(field => field.group))].map(group => (

{group}

{policyFields .filter(field => field.group === group) .map(field => ( ))}
))}
{error && (

{error}

)} {preparation.blocking && (

Retain an available dataset or clear source preparation before saving this setup.

)} {' '} {onClose && ( )}
); }