800 lines
26 KiB
TypeScript
800 lines
26 KiB
TypeScript
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 '@/features/strategies/components/StrategyParameterForm';
|
|
import {
|
|
StrategySelection,
|
|
type CatalogSelection,
|
|
} from '@/features/strategies/components/StrategySelection';
|
|
import {
|
|
confirmDiscard,
|
|
useUnsavedWarning,
|
|
} from '@/features/strategies/components/useUnsavedWarning';
|
|
import {
|
|
backtestApiV2,
|
|
type Backtest,
|
|
type CreateBacktestRequest,
|
|
} from '../services/backtestApiV2';
|
|
import { DatasetDownload } from './DatasetDownload';
|
|
import { DatasetPreparation, type DatasetPreparationState } from './DatasetPreparation';
|
|
|
|
type PolicyKey = Exclude<keyof CanonicalResearchSettings, 'version'>;
|
|
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<PolicyKey, string>;
|
|
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<Record<PolicyKey, string>>;
|
|
} {
|
|
const values: Record<string, unknown> = { version: 1 };
|
|
const errors: Partial<Record<PolicyKey, string>> = {};
|
|
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<void>;
|
|
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<CatalogSelection>({
|
|
strategyVersionId: backtest.strategyVersionId,
|
|
strategyParameters: backtest.strategyParameters,
|
|
});
|
|
const [strategyValid, setStrategyValid] = useState(false);
|
|
const [epoch, setEpoch] = useState(0);
|
|
const [catalog, setCatalog] = useState<CanonicalDatasetCatalogEntry[]>([]);
|
|
const [dataset, setDataset] = useState<CanonicalDatasetCatalogEntry | null>(null);
|
|
const [catalogLoading, setCatalogLoading] = useState(true);
|
|
const [datasetLoading, setDatasetLoading] = useState(false);
|
|
const [catalogError, setCatalogError] = useState<string | null>(null);
|
|
const [datasetError, setDatasetError] = useState<string | null>(null);
|
|
const [retry, setRetry] = useState(0);
|
|
const [detailRetry, setDetailRetry] = useState(0);
|
|
const [knownHash, setKnownHash] = useState('');
|
|
const [knownHashError, setKnownHashError] = useState<string | null>(null);
|
|
const [hasMore, setHasMore] = useState(false);
|
|
const nextOffset = useRef(0);
|
|
const catalogRequest = useRef<AbortController | null>(null);
|
|
const datasetRequest = useRef<AbortController | null>(null);
|
|
const selectedHash = useRef(hash);
|
|
const invalidHashDraft = useRef(false);
|
|
const [saving, setSaving] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [dirty, setDirty] = useState(false);
|
|
const authoritative = useRef(backtest);
|
|
const currentBacktest = useRef(backtest);
|
|
currentBacktest.current = backtest;
|
|
const preparationRef = useRef<DatasetPreparationState>({ 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<typeof canonicalDatasetFields> | 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 (
|
|
<form
|
|
className="space-y-5"
|
|
onSubmit={event => void save(event)}
|
|
onChange={() => setDirty(true)}
|
|
>
|
|
<h3 className="font-semibold text-text-primary">Canonical research setup</h3>
|
|
<p className="text-sm text-text-secondary">
|
|
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.
|
|
</p>
|
|
{dirty && (
|
|
<p role="status" className="text-sm text-text-secondary">
|
|
Unsaved canonical setup. Save or discard before leaving.
|
|
</p>
|
|
)}
|
|
<fieldset disabled={locked} className="space-y-4">
|
|
<label className="block text-sm">
|
|
Backtest name
|
|
<input
|
|
aria-label="Backtest name"
|
|
className={fieldClass}
|
|
value={name}
|
|
onChange={event => setName(event.target.value)}
|
|
required
|
|
/>
|
|
</label>
|
|
<label className="block text-sm">
|
|
Initial capital (USD)
|
|
<input
|
|
aria-label="Initial capital (USD)"
|
|
className={fieldClass}
|
|
value={capital}
|
|
onChange={event => setCapital(event.target.value)}
|
|
inputMode="decimal"
|
|
/>
|
|
</label>
|
|
{!validCapital && (
|
|
<p role="alert" className="text-error text-sm">
|
|
Initial capital must be a positive finite number.
|
|
</p>
|
|
)}
|
|
<label className="block text-sm">
|
|
Canonical dataset
|
|
<select
|
|
aria-label="Canonical dataset"
|
|
className={fieldClass}
|
|
value={hash}
|
|
onChange={event => chooseHash(event.target.value)}
|
|
>
|
|
<option value="">Select a retained single-asset dataset</option>
|
|
{hash && !options.some(entry => entry.hash === hash) && (
|
|
<option value={hash}>{hash} — selected hash</option>
|
|
)}
|
|
{options.map(entry => (
|
|
<option key={entry.hash} value={entry.hash} disabled={!entry.available}>
|
|
{entry.hash} —{' '}
|
|
{entry.manifest?.executionSeries.map(item => item.instrumentId).join(', ') ||
|
|
'Unknown asset'}
|
|
{entry.available ? '' : ` (${entry.reason ?? 'Unavailable'})`}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
<div className="flex flex-wrap gap-2">
|
|
{hasMore && (
|
|
<button
|
|
type="button"
|
|
className={actionClass}
|
|
disabled={catalogLoading}
|
|
onClick={() => void loadCatalog(nextOffset.current)}
|
|
>
|
|
Load more canonical datasets
|
|
</button>
|
|
)}
|
|
<button type="button" className={actionClass} onClick={refreshDatasets}>
|
|
Refresh canonical datasets
|
|
</button>
|
|
</div>
|
|
<div className="space-y-2" onChange={event => event.stopPropagation()}>
|
|
<label className="block text-sm">
|
|
Retained dataset hash
|
|
<input
|
|
aria-label="Retained dataset hash"
|
|
className={fieldClass}
|
|
value={knownHash}
|
|
onChange={event => {
|
|
setKnownHash(event.target.value);
|
|
invalidHashDraft.current = false;
|
|
setKnownHashError(null);
|
|
}}
|
|
onKeyDown={event => {
|
|
if (event.key === 'Enter') {
|
|
event.preventDefault();
|
|
}
|
|
}}
|
|
placeholder="64-character retained hash"
|
|
/>
|
|
</label>
|
|
<button
|
|
type="button"
|
|
className={actionClass}
|
|
onClick={() => {
|
|
const value = knownHash.trim();
|
|
if (!/^[a-f0-9]{64}$/.test(value)) {
|
|
invalidHashDraft.current = true;
|
|
setKnownHashError(
|
|
'Enter a retained dataset hash of 64 lowercase hexadecimal characters.'
|
|
);
|
|
return;
|
|
}
|
|
chooseHash(value);
|
|
}}
|
|
>
|
|
Use dataset hash
|
|
</button>
|
|
</div>
|
|
{catalogLoading && <p role="status">Loading canonical datasets...</p>}
|
|
{!catalogLoading && !catalogError && !catalog.length && (
|
|
<p role="status">
|
|
No canonical datasets are listed. Use a known retained hash or prepare a dataset with
|
|
explicit sessions and availability.
|
|
</p>
|
|
)}
|
|
{datasetLoading && <p role="status">Loading selected canonical dataset...</p>}
|
|
{[catalogError, datasetError, compatibilityError, knownHashError]
|
|
.filter(Boolean)
|
|
.map((message, index) => (
|
|
<p key={index} role="alert" className="text-error text-sm">
|
|
{message}
|
|
</p>
|
|
))}
|
|
{catalogError && (
|
|
<button
|
|
type="button"
|
|
className={actionClass}
|
|
disabled={catalogLoading}
|
|
onClick={() => void loadCatalog(nextOffset.current, nextOffset.current === 0)}
|
|
>
|
|
Retry canonical datasets
|
|
</button>
|
|
)}
|
|
{(datasetError || compatibilityError) && (
|
|
<button type="button" className={actionClass} onClick={() => chooseHash(hash)}>
|
|
Retry selected dataset
|
|
</button>
|
|
)}
|
|
{hash && !selectedFields && !datasetLoading && (
|
|
<p className="text-sm text-text-secondary">
|
|
The selected hash has not been verified for this setup. Saving stays disabled until
|
|
compatible retained metadata is available.
|
|
</p>
|
|
)}
|
|
{selectedFields && (
|
|
<dl aria-label="Canonical dataset bounds" className="grid gap-2 text-sm sm:grid-cols-2">
|
|
<div>
|
|
<dt>Execution asset</dt>
|
|
<dd>{selectedFields.symbols.join(', ')}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Execution interval</dt>
|
|
<dd>{selectedFields.dataFrequency}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Trading start (UTC)</dt>
|
|
<dd>{selectedFields.startDate}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Trading end (UTC, exclusive)</dt>
|
|
<dd>{selectedFields.endDate}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Warmup start (UTC)</dt>
|
|
<dd>{selectedFields.warmupStart}</dd>
|
|
</div>
|
|
</dl>
|
|
)}
|
|
{selectedFields && <DatasetDownload hash={hash} />}
|
|
<details className="space-y-3 rounded-md border border-border p-3">
|
|
<summary className="cursor-pointer font-medium">
|
|
Prepare dataset from source export
|
|
</summary>
|
|
<DatasetPreparation
|
|
key={`${backtest.id}:${epoch}`}
|
|
disabled={locked}
|
|
begin={() =>
|
|
!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);
|
|
}}
|
|
/>
|
|
</details>
|
|
<StrategySelection
|
|
key={epoch}
|
|
allowArchivedSelection
|
|
value={selection}
|
|
onChange={setSelection}
|
|
onValidityChange={setStrategyValid}
|
|
disabled={locked}
|
|
/>
|
|
{[...new Set(policyFields.map(field => field.group))].map(group => (
|
|
<section key={group} className="space-y-3 border border-border rounded-md p-3">
|
|
<h4 className="font-medium text-text-primary">{group}</h4>
|
|
<div className="grid gap-4 sm:grid-cols-2">
|
|
{policyFields
|
|
.filter(field => field.group === group)
|
|
.map(field => (
|
|
<label key={field.key} className="block text-sm text-text-secondary">
|
|
{field.label}
|
|
<input
|
|
aria-label={field.label}
|
|
className={fieldClass}
|
|
type="text"
|
|
inputMode="decimal"
|
|
value={raw[field.key]}
|
|
onChange={event =>
|
|
setRaw(previous => ({ ...previous, [field.key]: event.target.value }))
|
|
}
|
|
aria-invalid={Boolean(parsed.errors[field.key])}
|
|
/>
|
|
<span className="block text-xs text-text-muted">{field.description}</span>
|
|
{parsed.errors[field.key] && (
|
|
<span role="alert" className="block text-error">
|
|
{parsed.errors[field.key]}
|
|
</span>
|
|
)}
|
|
</label>
|
|
))}
|
|
</div>
|
|
</section>
|
|
))}
|
|
</fieldset>
|
|
{error && (
|
|
<p role="alert" className="text-error text-sm">
|
|
{error}
|
|
</p>
|
|
)}
|
|
{preparation.blocking && (
|
|
<p role="status">
|
|
Retain an available dataset or clear source preparation before saving this setup.
|
|
</p>
|
|
)}
|
|
<button
|
|
type="submit"
|
|
className={actionClass}
|
|
disabled={locked || preparation.busy || preparation.blocking || !valid}
|
|
>
|
|
{saving ? 'Saving canonical setup...' : 'Save canonical setup'}
|
|
</button>{' '}
|
|
{onClose && (
|
|
<button
|
|
type="button"
|
|
className={actionClass}
|
|
disabled={saving || preparation.busy}
|
|
onClick={() => {
|
|
if (pending.current || preparationRef.current.busy) {
|
|
return;
|
|
}
|
|
if (confirmDiscard(dirty || preparationRef.current.blocking)) {
|
|
onClose();
|
|
}
|
|
}}
|
|
>
|
|
Back to draft settings
|
|
</button>
|
|
)}
|
|
</form>
|
|
);
|
|
}
|