397 lines
14 KiB
TypeScript
397 lines
14 KiB
TypeScript
import { useEffect, useState } from 'react';
|
||
import { parseInstrumentId, type HistoricalDatasetCatalogEntry } from '@stock-bot/types';
|
||
import { backtestApiV2 } from '../services/backtestApiV2';
|
||
import {
|
||
historicalDateInput,
|
||
historicalIntervals,
|
||
historicalSelectionError,
|
||
retainedDatasetSelection,
|
||
type HistoricalSelection,
|
||
} from '../services/historical-selection';
|
||
|
||
const inputClass =
|
||
'w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary disabled:opacity-60';
|
||
const buttonClass = 'text-sm text-primary-500 disabled:opacity-50';
|
||
|
||
export function HistoricalDataSelection({
|
||
value,
|
||
onChange,
|
||
onValidityChange,
|
||
disabled = false,
|
||
}: {
|
||
value: HistoricalSelection;
|
||
onChange: (value: HistoricalSelection) => void;
|
||
onValidityChange: (valid: boolean) => void;
|
||
disabled?: boolean;
|
||
}) {
|
||
const [entries, setEntries] = useState<HistoricalDatasetCatalogEntry[]>([]);
|
||
const [page, setPage] = useState(0);
|
||
const [retry, setRetry] = useState(0);
|
||
const [loading, setLoading] = useState(true);
|
||
const [more, setMore] = useState(false);
|
||
const [catalogError, setCatalogError] = useState<string | null>(null);
|
||
const [detail, setDetail] = useState<HistoricalDatasetCatalogEntry | null>(null);
|
||
const [detailError, setDetailError] = useState<string | null>(null);
|
||
const [detailLoading, setDetailLoading] = useState(false);
|
||
const [symbol, setSymbol] = useState('');
|
||
const [symbolError, setSymbolError] = useState<string | null>(null);
|
||
const frozen = value.datasetHash !== undefined;
|
||
const selected =
|
||
entries.find(entry => entry.hash === value.datasetHash) ??
|
||
(detail?.hash === value.datasetHash ? detail : null);
|
||
const frequency = value.dataFrequency ?? '1d';
|
||
const validation =
|
||
frozen && !value.datasetHash
|
||
? 'Choose a frozen dataset'
|
||
: historicalSelectionError(value, selected);
|
||
|
||
useEffect(() => {
|
||
const controller = new AbortController();
|
||
setLoading(true);
|
||
setCatalogError(null);
|
||
backtestApiV2
|
||
.listDatasets(50, page * 50, controller.signal)
|
||
.then(rows => {
|
||
if (controller.signal.aborted) {
|
||
return;
|
||
}
|
||
setEntries(previous => [
|
||
...new Map(
|
||
(page === 0 ? rows : [...previous, ...rows]).map(row => [row.hash, row])
|
||
).values(),
|
||
]);
|
||
setMore(rows.length === 50);
|
||
})
|
||
.catch(error => {
|
||
if (!controller.signal.aborted) {
|
||
setCatalogError(
|
||
error instanceof Error ? error.message : 'Could not load frozen datasets'
|
||
);
|
||
}
|
||
})
|
||
.finally(() => {
|
||
if (!controller.signal.aborted) {
|
||
setLoading(false);
|
||
}
|
||
});
|
||
return () => controller.abort();
|
||
}, [page, retry]);
|
||
|
||
useEffect(() => {
|
||
const controller = new AbortController();
|
||
setDetailError(null);
|
||
if (!value.datasetHash || entries.some(entry => entry.hash === value.datasetHash)) {
|
||
setDetailLoading(false);
|
||
return () => controller.abort();
|
||
}
|
||
setDetailLoading(true);
|
||
backtestApiV2
|
||
.getDataset(value.datasetHash, controller.signal)
|
||
.then(entry => {
|
||
if (!controller.signal.aborted) {
|
||
setDetail(entry);
|
||
}
|
||
})
|
||
.catch(error => {
|
||
if (!controller.signal.aborted) {
|
||
setDetailError(
|
||
error instanceof Error ? error.message : 'Selected dataset is unavailable'
|
||
);
|
||
}
|
||
})
|
||
.finally(() => {
|
||
if (!controller.signal.aborted) {
|
||
setDetailLoading(false);
|
||
}
|
||
});
|
||
return () => controller.abort();
|
||
}, [value.datasetHash, entries, retry]);
|
||
|
||
useEffect(
|
||
() => onValidityChange(validation === null && !detailError),
|
||
[validation, detailError, onValidityChange]
|
||
);
|
||
|
||
const choose = (hash: string) => {
|
||
const entry =
|
||
entries.find(item => item.hash === hash) ?? (detail?.hash === hash ? detail : null);
|
||
if (!entry) {
|
||
return;
|
||
}
|
||
onChange(retainedDatasetSelection(entry));
|
||
};
|
||
const addSymbol = () => {
|
||
const id = symbol.trim().toUpperCase();
|
||
try {
|
||
parseInstrumentId(id);
|
||
} catch {
|
||
setSymbolError('Enter an exchange-qualified instrument, for example AAPL.US');
|
||
return;
|
||
}
|
||
setSymbolError(null);
|
||
if (!value.symbols.includes(id)) {
|
||
onChange({ ...value, symbols: [...value.symbols, id] });
|
||
}
|
||
setSymbol('');
|
||
};
|
||
const choices =
|
||
detail && !entries.some(entry => entry.hash === detail.hash) ? [detail, ...entries] : entries;
|
||
|
||
return (
|
||
<section aria-label="Historical data" className="space-y-4 border border-border rounded-lg p-4">
|
||
<label className="block text-sm text-text-secondary">
|
||
Historical data input
|
||
<select
|
||
aria-label="Historical data input"
|
||
className={inputClass}
|
||
disabled={disabled}
|
||
value={frozen ? 'frozen' : 'source'}
|
||
onChange={event =>
|
||
onChange({ ...value, datasetHash: event.target.value === 'frozen' ? '' : undefined })
|
||
}
|
||
>
|
||
<option value="source">Source request</option>
|
||
<option value="frozen">Frozen dataset</option>
|
||
</select>
|
||
</label>
|
||
{frozen ? (
|
||
<div className="space-y-2">
|
||
<label className="block text-sm text-text-secondary">
|
||
Frozen dataset
|
||
<select
|
||
aria-label="Frozen dataset"
|
||
className={inputClass}
|
||
disabled={disabled}
|
||
value={value.datasetHash ?? ''}
|
||
onChange={event => choose(event.target.value)}
|
||
>
|
||
<option value="">Choose a frozen dataset</option>
|
||
{value.datasetHash && !choices.some(entry => entry.hash === value.datasetHash) && (
|
||
<option value={value.datasetHash}>
|
||
{value.datasetHash} — metadata unavailable
|
||
</option>
|
||
)}
|
||
{choices.map(entry => (
|
||
<option key={entry.hash} value={entry.hash} disabled={entry.status !== 'available'}>
|
||
{entry.hash} —{' '}
|
||
{entry.manifest?.instruments.map(instrument => instrument.id).join(', ') ??
|
||
`Version ${entry.version ?? 'unknown'}`}{' '}
|
||
· {entry.manifest?.interval ?? entry.status}
|
||
{entry.status !== 'available' ? ` · ${entry.reason ?? entry.status}` : ''}
|
||
</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
{(loading || detailLoading) && (
|
||
<p role="status" className="text-sm text-text-secondary">
|
||
Loading frozen dataset metadata...
|
||
</p>
|
||
)}
|
||
{!loading && !entries.length && !catalogError && (
|
||
<p className="text-sm text-text-secondary">
|
||
No frozen datasets yet. Run a source request to prepare one.
|
||
</p>
|
||
)}
|
||
{(catalogError || detailError) && (
|
||
<p role="alert" className="text-sm text-error">
|
||
{detailError ?? catalogError}
|
||
</p>
|
||
)}
|
||
{(catalogError || detailError) && (
|
||
<button
|
||
type="button"
|
||
className={buttonClass}
|
||
disabled={disabled || loading || detailLoading}
|
||
onClick={() => setRetry(value => value + 1)}
|
||
>
|
||
Retry datasets
|
||
</button>
|
||
)}
|
||
{more && (
|
||
<button
|
||
type="button"
|
||
className={buttonClass}
|
||
disabled={disabled || loading}
|
||
onClick={() => setPage(value => value + 1)}
|
||
>
|
||
Load more datasets
|
||
</button>
|
||
)}
|
||
{selected && (
|
||
<div className="text-sm text-text-secondary space-y-1 break-words">
|
||
<p>Dataset hash: {selected.hash}</p>
|
||
{selected.reason && <p>{selected.reason}</p>}
|
||
{selected.manifest && (
|
||
<>
|
||
<p>
|
||
Requested range: {selected.manifest.startDate} to {selected.manifest.endDate}{' '}
|
||
(end exclusive).
|
||
</p>
|
||
<p>
|
||
Sources:{' '}
|
||
{selected.manifest.sources
|
||
.map(
|
||
source => `${source.instrumentId}: ${source.provider} (${source.revision})`
|
||
)
|
||
.join('; ')}
|
||
</p>
|
||
<p>
|
||
Bars: {selected.manifest.barCount}. Coverage: unknown. Content integrity: not
|
||
verified by this catalog; the runner validates retained content before
|
||
execution.
|
||
</p>
|
||
</>
|
||
)}
|
||
{selected.status === 'available' && validation && (
|
||
<button
|
||
type="button"
|
||
className={buttonClass}
|
||
disabled={disabled}
|
||
onClick={() => choose(selected.hash)}
|
||
>
|
||
Apply dataset settings
|
||
</button>
|
||
)}
|
||
</div>
|
||
)}
|
||
</div>
|
||
) : (
|
||
<>
|
||
<p className="text-sm text-text-secondary">
|
||
Source request — unpinned. Historical data will be prepared asynchronously and frozen
|
||
before execution; this request is not yet a reproducible dataset.
|
||
</p>
|
||
<label className="block text-sm text-text-secondary">
|
||
Historical source
|
||
<select
|
||
aria-label="Historical source"
|
||
className={inputClass}
|
||
disabled={disabled}
|
||
value={value.dataSource ?? 'auto'}
|
||
onChange={event =>
|
||
onChange({
|
||
...value,
|
||
dataSource: event.target.value as HistoricalSelection['dataSource'],
|
||
})
|
||
}
|
||
>
|
||
<option value="auto">Automatic configured source</option>
|
||
<option value="questdb">QuestDB</option>
|
||
<option value="eod">EOD historical storage</option>
|
||
</select>
|
||
</label>
|
||
</>
|
||
)}
|
||
<fieldset disabled={disabled || frozen} className="space-y-4">
|
||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||
<label className="block text-sm text-text-secondary">
|
||
Timeframe
|
||
<select
|
||
aria-label="Timeframe"
|
||
className={inputClass}
|
||
value={frequency}
|
||
onChange={event =>
|
||
onChange({
|
||
...value,
|
||
dataFrequency: event.target.value as HistoricalSelection['dataFrequency'],
|
||
})
|
||
}
|
||
>
|
||
{historicalIntervals.map(interval => (
|
||
<option key={interval}>{interval}</option>
|
||
))}
|
||
</select>
|
||
</label>
|
||
<label className="block text-sm text-text-secondary">
|
||
Historical prices
|
||
<select
|
||
aria-label="Historical prices"
|
||
className={inputClass}
|
||
value={value.priceAdjustment ?? 'raw'}
|
||
onChange={event =>
|
||
onChange({
|
||
...value,
|
||
priceAdjustment:
|
||
event.target.value === 'provider-adjusted' ? 'provider-adjusted' : 'raw',
|
||
})
|
||
}
|
||
>
|
||
<option value="raw">Raw prices (no corporate-action adjustment)</option>
|
||
<option value="provider-adjusted">Provider adjusted (reported volume)</option>
|
||
</select>
|
||
</label>
|
||
</div>
|
||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||
{(['startDate', 'endDate'] as const).map(key => {
|
||
const label = `${key === 'startDate' ? 'Start' : 'End'} ${frequency === '1d' ? 'date' : 'instant'} (UTC)`;
|
||
return (
|
||
<label key={key} className="block text-sm text-text-secondary">
|
||
{label}
|
||
<input
|
||
aria-label={label}
|
||
className={inputClass}
|
||
type={frequency === '1d' ? 'date' : 'text'}
|
||
value={historicalDateInput(value[key], frequency)}
|
||
placeholder="2024-01-01T09:30:00.000Z"
|
||
required
|
||
onChange={event => onChange({ ...value, [key]: event.target.value })}
|
||
/>
|
||
</label>
|
||
);
|
||
})}
|
||
</div>
|
||
<p className="text-xs text-text-secondary">
|
||
End is exclusive. Intraday instants require an explicit UTC offset; milliseconds are
|
||
preserved.
|
||
</p>
|
||
<div>
|
||
<label className="block text-sm text-text-secondary">
|
||
Instrument ID
|
||
<input
|
||
aria-label="Instrument ID"
|
||
className={inputClass}
|
||
value={symbol}
|
||
placeholder="AAPL.US"
|
||
onChange={event => setSymbol(event.target.value)}
|
||
onKeyDown={event => {
|
||
if (event.key === 'Enter') {
|
||
event.preventDefault();
|
||
addSymbol();
|
||
}
|
||
}}
|
||
/>
|
||
</label>
|
||
<button type="button" className={buttonClass} onClick={addSymbol}>
|
||
Add instrument
|
||
</button>
|
||
{symbolError && (
|
||
<p role="alert" className="text-sm text-error">
|
||
{symbolError}
|
||
</p>
|
||
)}
|
||
<div className="flex flex-wrap gap-2 mt-2">
|
||
{value.symbols.map(id => (
|
||
<span key={id} className="px-2 py-1 rounded bg-background text-sm text-text-primary">
|
||
{id}{' '}
|
||
<button
|
||
type="button"
|
||
aria-label={`Remove ${id}`}
|
||
onClick={() =>
|
||
onChange({ ...value, symbols: value.symbols.filter(item => item !== id) })
|
||
}
|
||
>
|
||
×
|
||
</button>
|
||
</span>
|
||
))}
|
||
</div>
|
||
</div>
|
||
</fieldset>
|
||
{validation && !(frozen && (loading || detailLoading || detailError)) && (
|
||
<p role="alert" className="text-sm text-error">
|
||
{validation}
|
||
</p>
|
||
)}
|
||
</section>
|
||
);
|
||
}
|