398 lines
15 KiB
TypeScript
398 lines
15 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
|
import { Link, useNavigate } from 'react-router-dom';
|
|
import { type CostScenario } from '@stock-bot/stock-config/cost-sensitivity';
|
|
import { MAX_EXPERIMENT_TRIALS } from '@stock-bot/stock-config/experiments';
|
|
import { Button } from '@/components/ui/Button';
|
|
import {
|
|
StrategySelection,
|
|
type CatalogSelection,
|
|
} from '@/features/strategies/components/StrategySelection';
|
|
import { useUnsavedWarning } from '@/features/strategies/components/useUnsavedWarning';
|
|
import { useExperimentSubmission } from '../hooks/useExperimentSubmission';
|
|
import { useExperimentTemplates } from '../hooks/useExperimentTemplates';
|
|
import { ChronologicalValidationPreflight } from './ChronologicalValidationPreflight';
|
|
import { ExperimentInputs } from './ExperimentInputs';
|
|
import { WalkForwardPreflight } from './WalkForwardPreflight';
|
|
|
|
const fieldClass =
|
|
'mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary disabled:opacity-60';
|
|
export function ExperimentEditor({
|
|
initialBacktestId,
|
|
onDirty,
|
|
}: {
|
|
initialBacktestId: string;
|
|
onDirty: (dirty: boolean) => void;
|
|
}) {
|
|
const navigate = useNavigate();
|
|
const [mode, setMode] = useState<'parameters' | 'cost-sensitivity'>('parameters');
|
|
const modeRef = useRef(mode);
|
|
const [scenarios, setScenarios] = useState<CostScenario[]>([{ feeRate: '', slippageRate: '' }]);
|
|
const [backtestId, setBacktestId] = useState(initialBacktestId);
|
|
const [name, setName] = useState('');
|
|
const [grid, setGrid] = useState('{}');
|
|
const [useCandidate, setUseCandidate] = useState(false);
|
|
const [candidateSelection, setCandidateSelection] = useState<CatalogSelection>({});
|
|
const [candidateValid, setCandidateValid] = useState(false);
|
|
const candidateRevision = useRef(0);
|
|
const candidateValidity = useRef(false);
|
|
const renderedCandidateRevision = candidateRevision.current;
|
|
const candidate =
|
|
useCandidate && candidateSelection.strategyVersionId
|
|
? {
|
|
versionId: candidateSelection.strategyVersionId,
|
|
parameters: candidateSelection.strategyParameters ?? {},
|
|
}
|
|
: undefined;
|
|
const [validationDirty, setValidationDirty] = useState(false);
|
|
const [walkForwardDirty, setWalkForwardDirty] = useState(false);
|
|
const { backtests, templateLoading, templateError, setTemplateReload, moreTemplates, setLimit } =
|
|
useExperimentTemplates(initialBacktestId);
|
|
const {
|
|
submissionOwner,
|
|
lockedBy,
|
|
claimSubmission,
|
|
releaseSubmission,
|
|
preview,
|
|
previewLoading,
|
|
error,
|
|
hasIntent,
|
|
submitting,
|
|
ambiguous,
|
|
invalidate,
|
|
prepare,
|
|
submit,
|
|
newIntent,
|
|
} = useExperimentSubmission({
|
|
backtestId,
|
|
name,
|
|
grid,
|
|
modeRef,
|
|
scenarios,
|
|
candidate,
|
|
candidateRevision,
|
|
renderedCandidateRevision,
|
|
useCandidate,
|
|
candidateValid,
|
|
onAccepted: id => navigate(`/experiments/${encodeURIComponent(id)}`),
|
|
});
|
|
const dirty =
|
|
hasIntent ||
|
|
validationDirty ||
|
|
walkForwardDirty ||
|
|
Boolean(
|
|
name ||
|
|
useCandidate ||
|
|
grid !== '{}' ||
|
|
backtestId !== initialBacktestId ||
|
|
mode !== 'parameters' ||
|
|
scenarios.length !== 1 ||
|
|
scenarios.some(item => item.feeRate || item.slippageRate)
|
|
);
|
|
useUnsavedWarning(dirty);
|
|
useEffect(() => {
|
|
onDirty(dirty);
|
|
}, [dirty, onDirty]);
|
|
|
|
return (
|
|
<section
|
|
aria-label="Create experiment"
|
|
className="rounded-lg border border-border bg-surface p-4 space-y-4"
|
|
>
|
|
<h2 className="font-semibold text-text-primary">
|
|
{mode === 'parameters' ? 'New parameter sweep' : 'New cost sensitivity experiment'}
|
|
</h2>
|
|
<p className="text-sm text-text-secondary">
|
|
{mode === 'parameters'
|
|
? 'Choose a saved canonical backtest and vary its strategy parameters. Preview validates every combination before any trials are submitted.'
|
|
: 'Compare explicit execution costs using fixed saved strategy parameters and dataset. Every scenario reruns the authoritative financial engine.'}
|
|
</p>
|
|
{templateLoading && <p role="status">Loading saved backtests...</p>}
|
|
{templateError && (
|
|
<div role="alert">
|
|
{templateError}{' '}
|
|
<Button variant="outline" size="sm" onClick={() => setTemplateReload(value => value + 1)}>
|
|
Retry saved backtests
|
|
</Button>
|
|
</div>
|
|
)}
|
|
{!templateLoading && !templateError && backtests.length === 0 && (
|
|
<p>
|
|
No saved canonical backtests are available.{' '}
|
|
<Link className="text-primary-500" to="/backtests">
|
|
Configure a backtest
|
|
</Link>{' '}
|
|
with a retained dataset and strategy version.
|
|
</p>
|
|
)}
|
|
<div className="grid gap-4 sm:grid-cols-2 text-sm">
|
|
<label>
|
|
Saved backtest
|
|
<select
|
|
className={fieldClass}
|
|
value={backtestId}
|
|
disabled={Boolean(lockedBy) || templateLoading}
|
|
onChange={event => invalidate(() => setBacktestId(event.target.value))}
|
|
>
|
|
<option value="">Select a saved canonical backtest</option>
|
|
{initialBacktestId && !backtests.some(item => item.id === initialBacktestId) && (
|
|
<option value={initialBacktestId}>Selected backtest is unavailable</option>
|
|
)}
|
|
{backtests.map(item => (
|
|
<option key={item.id} value={item.id}>
|
|
{item.name}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</label>
|
|
<label>
|
|
Experiment name
|
|
<input
|
|
className={fieldClass}
|
|
value={name}
|
|
disabled={Boolean(lockedBy)}
|
|
onChange={event => invalidate(() => setName(event.target.value))}
|
|
/>
|
|
</label>
|
|
</div>
|
|
{moreTemplates && (
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
disabled={templateLoading || Boolean(lockedBy)}
|
|
onClick={() => setLimit(value => value + 50)}
|
|
>
|
|
Load more backtests
|
|
</Button>
|
|
)}
|
|
<label className="block text-sm">
|
|
<input
|
|
type="checkbox"
|
|
checked={useCandidate}
|
|
disabled={Boolean(lockedBy)}
|
|
onChange={event => {
|
|
if (submissionOwner.current) {
|
|
return;
|
|
}
|
|
candidateRevision.current++;
|
|
invalidate(() => setUseCandidate(event.target.checked));
|
|
}}
|
|
/>{' '}
|
|
Use an isolated candidate version
|
|
</label>
|
|
{useCandidate && (
|
|
<section aria-label="Candidate experiment strategy" className="space-y-2">
|
|
<p className="text-sm">
|
|
Select an immutable candidate and validate its base parameters. The saved backtest
|
|
supplies the dataset, capital and financial policy. Preview checks candidate
|
|
eligibility.
|
|
</p>
|
|
<StrategySelection
|
|
value={candidateSelection}
|
|
onChange={value => {
|
|
if (submissionOwner.current) {
|
|
return;
|
|
}
|
|
candidateRevision.current++;
|
|
invalidate(() => setCandidateSelection(value));
|
|
}}
|
|
onValidityChange={valid => {
|
|
if (submissionOwner.current || valid === candidateValidity.current) {
|
|
return;
|
|
}
|
|
candidateValidity.current = valid;
|
|
candidateRevision.current++;
|
|
invalidate(() => setCandidateValid(valid));
|
|
}}
|
|
disabled={Boolean(lockedBy)}
|
|
/>
|
|
</section>
|
|
)}
|
|
<label className="block text-sm">
|
|
Experiment type
|
|
<select
|
|
className={fieldClass}
|
|
value={mode}
|
|
disabled={Boolean(lockedBy)}
|
|
onChange={event =>
|
|
invalidate(() => {
|
|
const next =
|
|
event.target.value === 'cost-sensitivity' ? 'cost-sensitivity' : 'parameters';
|
|
modeRef.current = next;
|
|
setMode(next);
|
|
})
|
|
}
|
|
>
|
|
<option value="parameters">Parameter sweep</option>
|
|
<option value="cost-sensitivity">Cost sensitivity</option>
|
|
</select>
|
|
</label>
|
|
{mode === 'parameters' ? (
|
|
<>
|
|
<label className="block text-sm">
|
|
Parameter grid (JSON)
|
|
<textarea
|
|
className={`${fieldClass} font-mono`}
|
|
rows={4}
|
|
value={grid}
|
|
disabled={Boolean(lockedBy)}
|
|
onChange={event => invalidate(() => setGrid(event.target.value))}
|
|
aria-describedby="experiment-grid-help"
|
|
/>
|
|
</label>
|
|
<p id="experiment-grid-help" className="text-xs text-text-secondary">
|
|
Use parameter names from the selected strategy with arrays of values, e.g.{' '}
|
|
{'{"fastPeriod":[5,10],"slowPeriod":[20,30]}'}. All combinations must be valid. {'{}'}{' '}
|
|
runs the unchanged parameters once. Maximum {MAX_EXPERIMENT_TRIALS} trials per
|
|
experiment; this does not promise concurrent execution.
|
|
</p>
|
|
<h3 className="font-semibold text-text-primary">Ordinary parameter sweep</h3>
|
|
<p className="text-xs text-text-secondary">
|
|
Ordinary submission uses the template's retained window. Chronological preflight below
|
|
does not change or execute this sweep.
|
|
</p>
|
|
</>
|
|
) : (
|
|
<section aria-label="Cost scenarios" className="space-y-3">
|
|
<h3 className="font-semibold">Cost sensitivity · template diagnostics</h3>
|
|
<p className="text-sm">
|
|
Baseline is automatic and uses the saved template's original costs. Add up to{' '}
|
|
{MAX_EXPERIMENT_TRIALS - 1} explicit fee/slippage pairs; no parameter grid or held-out
|
|
selection is performed.
|
|
</p>
|
|
<p className="text-xs text-text-secondary">
|
|
Rates are decimal fractions: 0.001 is 10 basis points (0.1%). Fees are charged once per
|
|
fill; slippage is an adverse price fraction. Strategy parameters, half-spread, capital
|
|
and risk limits stay fixed. Duplicate cost pairs, including baseline, are rejected.
|
|
</p>
|
|
{scenarios.map((scenario, index) => (
|
|
<fieldset
|
|
key={index}
|
|
disabled={Boolean(lockedBy)}
|
|
className="grid gap-2 sm:grid-cols-3 rounded border border-border p-3"
|
|
>
|
|
<legend className="px-1">Scenario {index + 1}</legend>
|
|
{(['feeRate', 'slippageRate'] as const).map(key => (
|
|
<label className="text-sm" key={key}>
|
|
Scenario {index + 1} {key === 'feeRate' ? 'fee rate' : 'slippage rate'}
|
|
<input
|
|
type="text"
|
|
inputMode="decimal"
|
|
className={fieldClass}
|
|
value={scenario[key]}
|
|
onChange={event =>
|
|
invalidate(() =>
|
|
setScenarios(current =>
|
|
current.map((item, i) =>
|
|
i === index ? { ...item, [key]: event.target.value } : item
|
|
)
|
|
)
|
|
)
|
|
}
|
|
/>
|
|
</label>
|
|
))}
|
|
<Button
|
|
variant="outline"
|
|
disabled={Boolean(lockedBy) || scenarios.length === 1}
|
|
onClick={() =>
|
|
invalidate(() => setScenarios(current => current.filter((_, i) => i !== index)))
|
|
}
|
|
>
|
|
Remove scenario {index + 1}
|
|
</Button>
|
|
</fieldset>
|
|
))}
|
|
<Button
|
|
variant="outline"
|
|
disabled={Boolean(lockedBy) || scenarios.length >= MAX_EXPERIMENT_TRIALS - 1}
|
|
onClick={() =>
|
|
invalidate(() =>
|
|
setScenarios(current => [...current, { feeRate: '', slippageRate: '' }])
|
|
)
|
|
}
|
|
>
|
|
Add cost scenario
|
|
</Button>
|
|
</section>
|
|
)}
|
|
<Button
|
|
variant="outline"
|
|
disabled={
|
|
Boolean(lockedBy) ||
|
|
previewLoading ||
|
|
(useCandidate && !candidateValid) ||
|
|
!backtests.some(item => item.id === backtestId) ||
|
|
!name.trim()
|
|
}
|
|
onClick={() => void prepare()}
|
|
>
|
|
Preview experiment
|
|
</Button>
|
|
{previewLoading && <p role="status">Validating experiment inputs...</p>}
|
|
{preview && <ExperimentInputs preview={preview} />}
|
|
{error && (
|
|
<p role="alert" className="text-error">
|
|
{error}
|
|
</p>
|
|
)}
|
|
{hasIntent && (
|
|
<p role="status" className="text-sm text-text-secondary">
|
|
{ambiguous ? 'Acceptance is unconfirmed. ' : ''}This submission keeps its exact inputs and
|
|
key. Retry to recover the same experiment; check saved experiments before starting
|
|
another.
|
|
</p>
|
|
)}
|
|
{(preview || hasIntent) && (
|
|
<div className="flex flex-wrap gap-2">
|
|
<Button
|
|
disabled={submitting || (lockedBy !== null && lockedBy !== 'ordinary')}
|
|
onClick={() => void submit()}
|
|
>
|
|
{submitting
|
|
? 'Submitting experiment...'
|
|
: hasIntent
|
|
? 'Retry experiment submission'
|
|
: 'Confirm experiment'}
|
|
</Button>
|
|
{hasIntent && (
|
|
<Button variant="outline" disabled={submitting} onClick={newIntent}>
|
|
Start new experiment
|
|
</Button>
|
|
)}
|
|
</div>
|
|
)}
|
|
<div hidden={mode !== 'parameters'}>
|
|
<ChronologicalValidationPreflight
|
|
backtestId={backtestId}
|
|
name={name}
|
|
grid={grid}
|
|
candidate={candidate}
|
|
disabled={mode !== 'parameters' || (lockedBy !== null && lockedBy !== 'chronological')}
|
|
eligible={
|
|
!templateLoading &&
|
|
(!useCandidate || candidateValid) &&
|
|
backtests.some(item => item.id === backtestId)
|
|
}
|
|
onDirty={setValidationDirty}
|
|
claimSubmission={claimSubmission}
|
|
releaseSubmission={releaseSubmission}
|
|
/>
|
|
<WalkForwardPreflight
|
|
backtestId={backtestId}
|
|
name={name}
|
|
grid={grid}
|
|
candidate={candidate}
|
|
disabled={mode !== 'parameters' || (lockedBy !== null && lockedBy !== 'walk-forward')}
|
|
eligible={
|
|
!templateLoading &&
|
|
(!useCandidate || candidateValid) &&
|
|
backtests.some(item => item.id === backtestId)
|
|
}
|
|
onDirty={setWalkForwardDirty}
|
|
claimSubmission={claimSubmission}
|
|
releaseSubmission={releaseSubmission}
|
|
/>
|
|
</div>
|
|
</section>
|
|
);
|
|
}
|