feat(research): add strategy catalog and versioned backtest setup
This commit is contained in:
parent
8cca0ee588
commit
d929db707a
44 changed files with 4198 additions and 209 deletions
|
|
@ -209,7 +209,12 @@ export function rejectCatalogVersionReferences(input: unknown): void {
|
|||
return;
|
||||
}
|
||||
const value = input as Record<string, unknown>;
|
||||
if (Object.hasOwn(value, 'strategyVersionId') || Object.hasOwn(value, 'strategyVersionIds')) {
|
||||
if (
|
||||
value.strategy === 'catalog' ||
|
||||
Object.hasOwn(value, 'strategyParameters') ||
|
||||
Object.hasOwn(value, 'strategyVersionId') ||
|
||||
Object.hasOwn(value, 'strategyVersionIds')
|
||||
) {
|
||||
throw new HistoricalDataRequestError(
|
||||
'Retained strategy versions are not supported by the current backtest runner'
|
||||
);
|
||||
|
|
@ -235,11 +240,10 @@ export interface BacktestDefinitionInput {
|
|||
}
|
||||
|
||||
/** Translate the existing API definition shape without changing its stored parameter bag. */
|
||||
export function backtestRequestFromDefinition(
|
||||
export function backtestSettingsFromDefinition(
|
||||
definition: BacktestDefinitionInput,
|
||||
identity: { runId?: string; backtestId?: string; speedMultiplier?: number | null } = {}
|
||||
): BacktestConfig {
|
||||
rejectCatalogVersionReferences(definition);
|
||||
): BacktestExecutionSettings {
|
||||
const parameters = definition.config ?? {};
|
||||
const historical = {
|
||||
symbols: definition.symbols,
|
||||
|
|
@ -260,21 +264,19 @@ export function backtestRequestFromDefinition(
|
|||
if (multiplier !== null && (!Number.isFinite(multiplier) || multiplier <= 0)) {
|
||||
throw new HistoricalDataRequestError('Speed multiplier must be positive or null');
|
||||
}
|
||||
return parseBacktestRequest({
|
||||
return BacktestExecutionSettingsSchema.parse({
|
||||
...historical,
|
||||
runId: identity.runId,
|
||||
backtestId: identity.backtestId,
|
||||
name: definition.name,
|
||||
mode: 'backtest',
|
||||
strategy: definition.strategy,
|
||||
startDate: new Date(historical.startDate).toISOString(),
|
||||
endDate: new Date(historical.endDate).toISOString(),
|
||||
initialCapital: definition.initialCapital,
|
||||
config: parameters,
|
||||
riskLimits: parameters.riskLimits,
|
||||
// Definition APIs historically treat null fees as unset; the parser owns defaults.
|
||||
commission: parameters.commission ?? undefined,
|
||||
slippage: parameters.slippage ?? undefined,
|
||||
commission: parameters.commission ?? BACKTEST_DEFAULTS.commission,
|
||||
slippage: parameters.slippage ?? BACKTEST_DEFAULTS.slippage,
|
||||
speed:
|
||||
multiplier === null
|
||||
? 'max'
|
||||
|
|
@ -287,3 +289,43 @@ export function backtestRequestFromDefinition(
|
|||
: 'realtime',
|
||||
});
|
||||
}
|
||||
|
||||
/** Legacy execution admission remains separate from catalog draft validation. */
|
||||
export function backtestRequestFromDefinition(
|
||||
definition: BacktestDefinitionInput,
|
||||
identity: { runId?: string; backtestId?: string; speedMultiplier?: number | null } = {}
|
||||
): BacktestConfig {
|
||||
rejectCatalogVersionReferences(definition);
|
||||
return parseBacktestRequest({
|
||||
...backtestSettingsFromDefinition(definition, identity),
|
||||
strategy: definition.strategy,
|
||||
config: definition.config ?? {},
|
||||
});
|
||||
}
|
||||
|
||||
/** Catalog strategy parameters never share the run-wide settings bag. */
|
||||
export const CatalogBacktestConfigSchema = BacktestExecutionSettingsSchema.pick({
|
||||
dataFrequency: true,
|
||||
dataPolicy: true,
|
||||
datasetHash: true,
|
||||
dataSource: true,
|
||||
commission: true,
|
||||
slippage: true,
|
||||
riskLimits: true,
|
||||
fillModel: true,
|
||||
})
|
||||
.partial()
|
||||
.strict();
|
||||
export const CatalogBacktestDefinitionSchema = z
|
||||
.object({
|
||||
name: z.string().trim().min(1),
|
||||
strategy: z.literal('catalog'),
|
||||
strategyVersionId: z.string().uuid(),
|
||||
strategyParameters: z.record(z.unknown()),
|
||||
symbols: BacktestExecutionSettingsSchema.shape.symbols,
|
||||
startDate: z.union([z.string(), z.date()]),
|
||||
endDate: z.union([z.string(), z.date()]),
|
||||
initialCapital: BacktestExecutionSettingsSchema.shape.initialCapital,
|
||||
config: CatalogBacktestConfigSchema.default({}),
|
||||
})
|
||||
.strict();
|
||||
|
|
|
|||
|
|
@ -285,6 +285,7 @@ export function validateStrategyParameters(
|
|||
pkg: StrategyVersionPackage,
|
||||
input: unknown
|
||||
): Record<string, StrategyParameterValue> {
|
||||
assertStrategyJsonText(input);
|
||||
checkSchema(pkg.parameterSchema);
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) {
|
||||
throw new Error('Parameters must be an object');
|
||||
|
|
|
|||
|
|
@ -2,7 +2,10 @@ import { randomUUID } from 'node:crypto';
|
|||
import type { PoolClient } from 'pg';
|
||||
import type { TransactionCallback } from '@stock-bot/postgres';
|
||||
import type { PostgresClient } from '@stock-bot/services';
|
||||
import { parseBacktestRequest } from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
parseBacktestRequest,
|
||||
rejectCatalogVersionReferences,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
import type { BacktestRunResult, HistoricalDataset } from '@stock-bot/types';
|
||||
import { prepareDataset } from '../data/historical-dataset';
|
||||
import type { BacktestConfig } from '../types';
|
||||
|
|
@ -36,6 +39,7 @@ export class PostgresBacktestRunRepository implements BacktestRunRepository {
|
|||
}
|
||||
|
||||
async start(config: BacktestConfig): Promise<RunClaim> {
|
||||
rejectCatalogVersionReferences(config);
|
||||
const attemptId = randomUUID();
|
||||
return this.postgres.transaction(async client => {
|
||||
if (config.runId) {
|
||||
|
|
|
|||
|
|
@ -57,7 +57,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
f === '14-backtest-submission.sql' ||
|
||||
f === '15-canonical-paper-intents.sql' ||
|
||||
f === '16-strategy-catalog.sql' ||
|
||||
f === '17-research-retention.sql')
|
||||
f === '17-research-retention.sql' ||
|
||||
f === '18-backtest-strategy-versions.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -10,8 +10,10 @@ import {
|
|||
import {
|
||||
BacktestRetentionError,
|
||||
BacktestServiceV2,
|
||||
CatalogExecutionUnavailableError,
|
||||
RunSubmissionConflictError,
|
||||
} from '../services/backtest-v2.service';
|
||||
import { StrategyCatalogError } from '../services/strategy-catalog.service';
|
||||
|
||||
const logger = getLogger('backtests-v2-routes');
|
||||
|
||||
|
|
@ -60,10 +62,14 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
return c.json({ error: 'autoStart must be a boolean' }, 400);
|
||||
}
|
||||
// Omitted autoStart preserves legacy clients. New web clients explicitly save only.
|
||||
const backtest = await backtestService.createBacktest(body, { autoStart: body.autoStart });
|
||||
const { autoStart, ...definition } = body;
|
||||
const backtest = await backtestService.createBacktest(definition, { autoStart });
|
||||
return c.json(backtest, 201);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create backtest', error);
|
||||
if (error instanceof StrategyCatalogError) {
|
||||
return c.json({ error: error.message }, error.status);
|
||||
}
|
||||
if (isBacktestRequestError(error)) {
|
||||
return c.json({ error: error.message }, 400);
|
||||
}
|
||||
|
|
@ -81,6 +87,9 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
return c.json(backtest);
|
||||
} catch (error) {
|
||||
logger.error('Failed to update backtest', error);
|
||||
if (error instanceof StrategyCatalogError) {
|
||||
return c.json({ error: error.message }, error.status);
|
||||
}
|
||||
if (error instanceof BacktestRetentionError) {
|
||||
return c.json({ error: error.message, code: error.code }, 409);
|
||||
}
|
||||
|
|
@ -155,6 +164,9 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
return c.json(run, 202);
|
||||
} catch (error) {
|
||||
logger.error('Failed to create run', error);
|
||||
if (error instanceof CatalogExecutionUnavailableError) {
|
||||
return c.json({ error: error.message, code: error.code }, 409);
|
||||
}
|
||||
if (error instanceof BacktestRetentionError) {
|
||||
return c.json({ error: error.message, code: error.code }, 409);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,20 +1,33 @@
|
|||
import { createHash, randomUUID as uuidv4 } from 'node:crypto';
|
||||
import type { QueryResultRow } from 'pg';
|
||||
import type { PoolClient, QueryResultRow } from 'pg';
|
||||
import { authenticatedServiceFetch } from '@stock-bot/di';
|
||||
import { at } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import {
|
||||
backtestRequestFromDefinition,
|
||||
backtestSettingsFromDefinition,
|
||||
CatalogBacktestDefinitionSchema,
|
||||
datasetHashSchema,
|
||||
parseBacktestRequest,
|
||||
rejectCatalogVersionReferences,
|
||||
type BacktestDefinitionInput,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
import type { BacktestRunDatasetSelection, BacktestRunResult } from '@stock-bot/types';
|
||||
import {
|
||||
assertStrategyJsonText,
|
||||
validateStrategyParameters,
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import type {
|
||||
BacktestRunDatasetSelection,
|
||||
BacktestRunResult,
|
||||
StrategyParameterValue,
|
||||
} from '@stock-bot/types';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { getWebSocketHandler } from '../websocket/run-updates';
|
||||
import type { WebSocketHandler } from '../websocket/run-updates';
|
||||
import { mapStoredBacktestResult, type StoredBacktestResult } from './backtest-result';
|
||||
import { assertSelectedDatasetMatchesRequest } from './dataset-catalog.service';
|
||||
import { StrategyCatalogError, StrategyCatalogService } from './strategy-catalog.service';
|
||||
|
||||
const logger = getLogger('backtest-v2-service');
|
||||
|
||||
|
|
@ -31,11 +44,15 @@ export interface BacktestRequest {
|
|||
endDate: string;
|
||||
initialCapital: number;
|
||||
config?: Record<string, unknown>;
|
||||
strategyVersionId?: string | null;
|
||||
strategyParameters?: Record<string, StrategyParameterValue> | null;
|
||||
}
|
||||
|
||||
export interface Backtest {
|
||||
id: string;
|
||||
archivedAt: string | null;
|
||||
strategyVersionId: string | null;
|
||||
strategyParameters: Record<string, StrategyParameterValue> | null;
|
||||
name: string;
|
||||
strategy: string;
|
||||
symbols: string[];
|
||||
|
|
@ -82,6 +99,27 @@ export class RunSubmissionConflictError extends Error {
|
|||
this.name = 'RunSubmissionConflictError';
|
||||
}
|
||||
}
|
||||
export class CatalogExecutionUnavailableError extends Error {
|
||||
readonly code = 'catalog_execution_unavailable';
|
||||
constructor() {
|
||||
super(
|
||||
'Catalog strategy execution is unavailable until the canonical runner is integrated (R05); this saved draft cannot run through a legacy strategy'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Strip only DTO metadata from legacy definitions; caller-supplied markers are rejected first. */
|
||||
function legacyDefinition(input: BacktestDefinitionInput): BacktestDefinitionInput {
|
||||
return {
|
||||
name: input.name,
|
||||
strategy: input.strategy,
|
||||
symbols: input.symbols,
|
||||
startDate: input.startDate,
|
||||
endDate: input.endDate,
|
||||
initialCapital: input.initialCapital,
|
||||
config: input.config,
|
||||
};
|
||||
}
|
||||
|
||||
export class BacktestRetentionError extends Error {
|
||||
constructor(
|
||||
|
|
@ -113,28 +151,41 @@ export class BacktestServiceV2 {
|
|||
request: BacktestRequest,
|
||||
options: { autoStart?: boolean } = {}
|
||||
): Promise<Backtest> {
|
||||
await assertSelectedDatasetMatchesRequest(
|
||||
this.container.postgres,
|
||||
backtestRequestFromDefinition(request)
|
||||
);
|
||||
const catalog = request.strategy === 'catalog';
|
||||
if (catalog && options.autoStart !== false) {
|
||||
throw new HistoricalDataRequestError('Catalog drafts require explicit autoStart:false');
|
||||
}
|
||||
if (!catalog) {
|
||||
rejectCatalogVersionReferences(request);
|
||||
}
|
||||
const backtestId = uuidv4();
|
||||
|
||||
const result = await this.container.postgres.query(
|
||||
`INSERT INTO backtests
|
||||
(id, name, strategy, symbols, start_date, end_date, initial_capital, config)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
const result = await this.container.postgres.transaction(async client => {
|
||||
const definition = catalog ? await this.validateCatalogDraft(client, request) : request;
|
||||
if (!catalog) {
|
||||
await assertSelectedDatasetMatchesRequest(
|
||||
client,
|
||||
backtestRequestFromDefinition(definition)
|
||||
);
|
||||
}
|
||||
return client.query(
|
||||
`INSERT INTO backtests
|
||||
(id, name, strategy, symbols, start_date, end_date, initial_capital, config, strategy_version_id, strategy_parameters)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
RETURNING *`,
|
||||
[
|
||||
backtestId,
|
||||
request.name,
|
||||
request.strategy,
|
||||
JSON.stringify(request.symbols),
|
||||
request.startDate,
|
||||
request.endDate,
|
||||
request.initialCapital,
|
||||
JSON.stringify(request.config || {}),
|
||||
]
|
||||
);
|
||||
[
|
||||
backtestId,
|
||||
definition.name,
|
||||
definition.strategy,
|
||||
JSON.stringify(definition.symbols),
|
||||
definition.startDate,
|
||||
definition.endDate,
|
||||
definition.initialCapital,
|
||||
JSON.stringify(definition.config || {}),
|
||||
definition.strategyVersionId ?? null,
|
||||
definition.strategyParameters ? JSON.stringify(definition.strategyParameters) : null,
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
const backtest = this.mapBacktest(at(result.rows, 0));
|
||||
|
||||
|
|
@ -178,39 +229,74 @@ export class BacktestServiceV2 {
|
|||
throw new BacktestRetentionError('backtest_archived');
|
||||
}
|
||||
const existing = this.mapBacktest(locked.rows[0]);
|
||||
const next = { ...existing, ...request };
|
||||
await assertSelectedDatasetMatchesRequest(client, backtestRequestFromDefinition(next));
|
||||
const catalog = existing.strategyVersionId !== null;
|
||||
let next = { ...existing, ...request };
|
||||
if (catalog) {
|
||||
CatalogBacktestDefinitionSchema.partial().parse(request);
|
||||
if (
|
||||
request.strategyVersionId !== undefined &&
|
||||
request.strategyVersionId !== existing.strategyVersionId &&
|
||||
request.strategyParameters === undefined
|
||||
) {
|
||||
throw new HistoricalDataRequestError(
|
||||
'Changing a selected version requires explicit strategyParameters'
|
||||
);
|
||||
}
|
||||
const normalized = await this.validateCatalogDraft(
|
||||
client,
|
||||
{
|
||||
...legacyDefinition(next),
|
||||
strategyVersionId: next.strategyVersionId,
|
||||
strategyParameters: next.strategyParameters,
|
||||
},
|
||||
existing.strategyVersionId
|
||||
);
|
||||
next = { ...next, ...normalized } as typeof next;
|
||||
} else {
|
||||
rejectCatalogVersionReferences(request);
|
||||
await assertSelectedDatasetMatchesRequest(
|
||||
client,
|
||||
backtestRequestFromDefinition(legacyDefinition(next))
|
||||
);
|
||||
}
|
||||
const updates: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
let paramCount = 1;
|
||||
|
||||
if (request.name !== undefined) {
|
||||
updates.push(`name = $${paramCount++}`);
|
||||
values.push(request.name);
|
||||
values.push(catalog ? next.name : request.name);
|
||||
}
|
||||
if (request.strategy !== undefined) {
|
||||
updates.push(`strategy = $${paramCount++}`);
|
||||
values.push(request.strategy);
|
||||
values.push(catalog ? next.strategy : request.strategy);
|
||||
}
|
||||
if (request.symbols !== undefined) {
|
||||
updates.push(`symbols = $${paramCount++}`);
|
||||
values.push(JSON.stringify(request.symbols));
|
||||
values.push(JSON.stringify(catalog ? next.symbols : request.symbols));
|
||||
}
|
||||
if (request.startDate !== undefined) {
|
||||
updates.push(`start_date = $${paramCount++}`);
|
||||
values.push(request.startDate);
|
||||
values.push(catalog ? next.startDate : request.startDate);
|
||||
}
|
||||
if (request.endDate !== undefined) {
|
||||
updates.push(`end_date = $${paramCount++}`);
|
||||
values.push(request.endDate);
|
||||
values.push(catalog ? next.endDate : request.endDate);
|
||||
}
|
||||
if (request.initialCapital !== undefined) {
|
||||
updates.push(`initial_capital = $${paramCount++}`);
|
||||
values.push(request.initialCapital);
|
||||
values.push(catalog ? next.initialCapital : request.initialCapital);
|
||||
}
|
||||
if (request.config !== undefined) {
|
||||
updates.push(`config = $${paramCount++}`);
|
||||
values.push(JSON.stringify(request.config));
|
||||
values.push(JSON.stringify(catalog ? next.config : request.config));
|
||||
}
|
||||
if (catalog) {
|
||||
updates.push(
|
||||
`strategy_version_id = $${paramCount++}`,
|
||||
`strategy_parameters = $${paramCount++}`
|
||||
);
|
||||
values.push(next.strategyVersionId, JSON.stringify(next.strategyParameters));
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
|
|
@ -337,7 +423,10 @@ export class BacktestServiceV2 {
|
|||
throw new BacktestRetentionError('backtest_archived');
|
||||
}
|
||||
const definition = this.mapBacktest(at(parent.rows, 0));
|
||||
const snapshot = backtestRequestFromDefinition(definition, {
|
||||
if (definition.strategyVersionId !== null || definition.strategy === 'catalog') {
|
||||
throw new CatalogExecutionUnavailableError();
|
||||
}
|
||||
const snapshot = backtestRequestFromDefinition(legacyDefinition(definition), {
|
||||
runId,
|
||||
backtestId: definition.id,
|
||||
speedMultiplier: multiplier,
|
||||
|
|
@ -486,10 +575,62 @@ export class BacktestServiceV2 {
|
|||
}
|
||||
|
||||
// Private methods
|
||||
private async validateCatalogDraft(
|
||||
client: PoolClient,
|
||||
input: unknown,
|
||||
previousVersionId?: string | null
|
||||
): Promise<BacktestRequest> {
|
||||
try {
|
||||
assertStrategyJsonText(input);
|
||||
} catch (error) {
|
||||
throw new HistoricalDataRequestError(
|
||||
error instanceof Error ? error.message : 'Invalid catalog draft text'
|
||||
);
|
||||
}
|
||||
const draft = CatalogBacktestDefinitionSchema.parse(input);
|
||||
let parameters: Record<string, StrategyParameterValue>;
|
||||
const pkg = await new StrategyCatalogService(this.container).getVersionArtifact(
|
||||
draft.strategyVersionId,
|
||||
client
|
||||
);
|
||||
try {
|
||||
assertStrategyJsonText(draft);
|
||||
parameters = validateStrategyParameters(pkg, draft.strategyParameters);
|
||||
} catch (error) {
|
||||
throw new HistoricalDataRequestError(
|
||||
error instanceof Error ? error.message : 'Invalid strategy parameters'
|
||||
);
|
||||
}
|
||||
const family = (
|
||||
await client.query(
|
||||
`SELECT s.archived_at FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id WHERE v.id=$1 FOR UPDATE OF s`,
|
||||
[draft.strategyVersionId]
|
||||
)
|
||||
).rows[0];
|
||||
if (!family) {
|
||||
throw new StrategyCatalogError(404, 'Strategy version not found');
|
||||
}
|
||||
if (previousVersionId !== draft.strategyVersionId && family.archived_at) {
|
||||
throw new StrategyCatalogError(
|
||||
409,
|
||||
'Strategy is archived; restore it before selecting a new version'
|
||||
);
|
||||
}
|
||||
const settings = backtestSettingsFromDefinition(draft);
|
||||
await assertSelectedDatasetMatchesRequest(client, settings);
|
||||
return {
|
||||
...draft,
|
||||
startDate: settings.startDate,
|
||||
endDate: settings.endDate,
|
||||
strategyParameters: parameters,
|
||||
};
|
||||
}
|
||||
private mapBacktest(row: QueryResultRow): Backtest {
|
||||
return {
|
||||
id: row.id,
|
||||
archivedAt: row.archived_at ? new Date(row.archived_at).toISOString() : null,
|
||||
strategyVersionId: row.strategy_version_id ?? null,
|
||||
strategyParameters: row.strategy_parameters ?? null,
|
||||
name: row.name,
|
||||
strategy: row.strategy,
|
||||
symbols: row.symbols,
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { rejectCatalogVersionReferences } from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
BacktestServiceV2,
|
||||
type Backtest,
|
||||
|
|
@ -37,6 +38,7 @@ export class BacktestService {
|
|||
}
|
||||
|
||||
async createBacktest(request: BacktestRequest): Promise<BacktestJob> {
|
||||
rejectCatalogVersionReferences(request);
|
||||
const backtest = await this.service.createBacktest(
|
||||
{
|
||||
...request,
|
||||
|
|
|
|||
|
|
@ -3,7 +3,6 @@ import {
|
|||
assertDatasetMatchesRequest,
|
||||
datasetHashSchema,
|
||||
validateDatasetManifestMetadata,
|
||||
type BacktestConfig,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
import { HistoricalDataRequestError, type HistoricalDatasetCatalogEntry } from '@stock-bot/types';
|
||||
|
||||
|
|
@ -112,7 +111,7 @@ export class DatasetCatalogService {
|
|||
/** Acceptance uses metadata only. The existing runner still verifies full content. */
|
||||
export async function assertSelectedDatasetMatchesRequest(
|
||||
database: DatasetCatalogQuery,
|
||||
config: BacktestConfig
|
||||
config: Parameters<typeof assertDatasetMatchesRequest>[1]
|
||||
): Promise<void> {
|
||||
if (config.datasetHash === undefined) {
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -9,7 +9,15 @@ import {
|
|||
parseStrategyVersionPackage,
|
||||
validateStrategyParameters,
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import type { StrategyVersionPackage } from '@stock-bot/types';
|
||||
import type {
|
||||
ParameterValidationResult,
|
||||
StrategyRecord,
|
||||
StrategyReviewEvent,
|
||||
StrategyVersionPackage,
|
||||
StrategyVersionSummary,
|
||||
} from '@stock-bot/types';
|
||||
|
||||
export type { StrategyRecord, StrategyVersionSummary } from '@stock-bot/types';
|
||||
|
||||
export type StrategyActor = 'operator' | 'service';
|
||||
export class StrategyCatalogError extends Error {
|
||||
|
|
@ -74,33 +82,6 @@ const metadata = `v.id,v.strategy_id,v.ordinal,v.parent_version_id,v.created_by,
|
|||
(v.envelope #- '{artifact,content}' #- '{dependencyLock,content}') AS package,
|
||||
COALESCE((SELECT CASE r.decision WHEN 'approve' THEN 'approved' ELSE 'revoked' END
|
||||
FROM strategy_review_events r WHERE r.version_id=v.id ORDER BY r.ordinal DESC LIMIT 1),'pending') AS review_status`;
|
||||
type PackageMetadata = Omit<StrategyVersionPackage, 'artifact' | 'dependencyLock'> & {
|
||||
artifact: Omit<StrategyVersionPackage['artifact'], 'content'>;
|
||||
dependencyLock: Omit<StrategyVersionPackage['dependencyLock'], 'content'>;
|
||||
};
|
||||
export interface StrategyRecord {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
ownerPrincipal: StrategyActor;
|
||||
updatedBy: StrategyActor;
|
||||
archived: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
export interface StrategyVersionSummary {
|
||||
id: string;
|
||||
strategyId: string;
|
||||
ordinal: number;
|
||||
parentVersionId: string | null;
|
||||
createdBy: StrategyActor;
|
||||
origin: 'candidate' | 'builtin';
|
||||
createdAt: string;
|
||||
package: PackageMetadata;
|
||||
reviewStatus: 'pending' | 'approved' | 'revoked';
|
||||
runnable: false;
|
||||
reason: string;
|
||||
}
|
||||
const strategy = (row: QueryResultRow): StrategyRecord => ({
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
|
|
@ -218,9 +199,14 @@ export class StrategyCatalogService {
|
|||
}
|
||||
return version(row);
|
||||
}
|
||||
async getVersionArtifact(versionId: string): Promise<StrategyVersionPackage> {
|
||||
async getVersionArtifact(
|
||||
versionId: string,
|
||||
database: {
|
||||
query(text: string, values?: unknown[]): Promise<{ rows: QueryResultRow[] }>;
|
||||
} = this.database
|
||||
): Promise<StrategyVersionPackage> {
|
||||
const row = (
|
||||
await this.database.query('SELECT envelope FROM strategy_versions WHERE id=$1', [
|
||||
await database.query('SELECT envelope FROM strategy_versions WHERE id=$1', [
|
||||
id.parse(versionId),
|
||||
])
|
||||
).rows[0];
|
||||
|
|
@ -229,7 +215,7 @@ export class StrategyCatalogService {
|
|||
}
|
||||
return checkedPackage(row.envelope);
|
||||
}
|
||||
async getVersionReviews(versionId: string) {
|
||||
async getVersionReviews(versionId: string): Promise<StrategyReviewEvent[]> {
|
||||
await this.getVersion(versionId);
|
||||
return (
|
||||
await this.database.query(
|
||||
|
|
@ -245,7 +231,10 @@ export class StrategyCatalogService {
|
|||
createdAt: new Date(row.created_at).toISOString(),
|
||||
}));
|
||||
}
|
||||
async validateVersionParameters(versionId: string, input: unknown) {
|
||||
async validateVersionParameters(
|
||||
versionId: string,
|
||||
input: unknown
|
||||
): Promise<ParameterValidationResult> {
|
||||
const pkg = await this.getVersionArtifact(versionId);
|
||||
let parameters;
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { DashboardPage } from '@/features/dashboard';
|
|||
import { ExchangesPage } from '@/features/exchanges';
|
||||
import { MonitoringPage } from '@/features/monitoring';
|
||||
import { PipelinePage } from '@/features/pipeline';
|
||||
import { StrategyDetailPage, StrategyListPage, StrategyVersionPage } from '@/features/strategies';
|
||||
import { SymbolDetailPage, SymbolsPage } from '@/features/symbols';
|
||||
import { AuthGate } from './AuthGate';
|
||||
|
||||
|
|
@ -25,10 +26,12 @@ export function App() {
|
|||
path="portfolio"
|
||||
element={<div className="p-4">Portfolio Page - Coming Soon</div>}
|
||||
/>
|
||||
<Route
|
||||
path="strategies"
|
||||
element={<div className="p-4">Strategies Page - Coming Soon</div>}
|
||||
/>
|
||||
<Route path="strategies">
|
||||
<Route index element={<StrategyListPage />} />
|
||||
<Route path="versions/:versionId" element={<StrategyVersionPage />} />
|
||||
<Route path=":strategyId" element={<StrategyDetailPage />} />
|
||||
<Route path=":strategyId/versions/:versionId" element={<StrategyDetailPage />} />
|
||||
</Route>
|
||||
<Route
|
||||
path="analytics"
|
||||
element={<div className="p-4">Analytics Page - Coming Soon</div>}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
import { ArrowLeftIcon, PlusIcon } from '@heroicons/react/24/outline';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom';
|
||||
import {
|
||||
catalogExecutionReason,
|
||||
supportedLegacyStrategy,
|
||||
} from '@/features/strategies/components/StrategySelection';
|
||||
import { useWebSocket } from '@/hooks/useWebSocket';
|
||||
import { ArchiveBacktestDialog } from './components/ArchiveBacktestDialog';
|
||||
import { BacktestConfiguration } from './components/BacktestConfiguration';
|
||||
|
|
@ -50,7 +54,11 @@ export function BacktestDetailPageV2() {
|
|||
refreshRun,
|
||||
} = useBacktestV2();
|
||||
const archived = Boolean(backtest?.archivedAt);
|
||||
const canSubmit = !archived || hasPendingSubmission;
|
||||
const catalog = Boolean(backtest?.strategyVersionId) || backtest?.strategy === 'catalog';
|
||||
const unsupportedLegacy = Boolean(
|
||||
backtest && !catalog && !supportedLegacyStrategy(backtest.strategy)
|
||||
);
|
||||
const canSubmit = (!archived && !catalog && !unsupportedLegacy) || hasPendingSubmission;
|
||||
|
||||
// Notifications invalidate the same persisted-state reader used by polling.
|
||||
useWebSocket({
|
||||
|
|
@ -93,18 +101,29 @@ export function BacktestDetailPageV2() {
|
|||
return;
|
||||
}
|
||||
|
||||
const executionConfig = { ...backtest?.config };
|
||||
if (catalog) {
|
||||
delete executionConfig.speedMultiplier;
|
||||
} else {
|
||||
executionConfig.speedMultiplier = config.speedMultiplier;
|
||||
}
|
||||
await updateBacktest(id, {
|
||||
name: config.name,
|
||||
strategy: config.strategy,
|
||||
...(config.strategyVersionId
|
||||
? {
|
||||
strategyVersionId: config.strategyVersionId,
|
||||
strategyParameters: config.strategyParameters,
|
||||
}
|
||||
: {}),
|
||||
symbols: config.symbols,
|
||||
startDate: config.startDate,
|
||||
endDate: config.endDate,
|
||||
initialCapital: config.initialCapital,
|
||||
config: {
|
||||
...backtest?.config,
|
||||
...executionConfig,
|
||||
commission: config.commission,
|
||||
slippage: config.slippage,
|
||||
speedMultiplier: config.speedMultiplier,
|
||||
dataFrequency: config.dataFrequency,
|
||||
dataSource: config.dataSource,
|
||||
datasetHash: config.datasetHash,
|
||||
|
|
@ -118,7 +137,7 @@ export function BacktestDetailPageV2() {
|
|||
},
|
||||
});
|
||||
},
|
||||
[id, updateBacktest, backtest, archived]
|
||||
[id, updateBacktest, backtest, archived, catalog]
|
||||
);
|
||||
|
||||
// Handle new run creation
|
||||
|
|
@ -154,6 +173,8 @@ export function BacktestDetailPageV2() {
|
|||
initialCapital: backtest.initialCapital,
|
||||
symbols: backtest.symbols,
|
||||
strategy: backtest.strategy,
|
||||
strategyVersionId: backtest.strategyVersionId,
|
||||
strategyParameters: backtest.strategyParameters,
|
||||
speedMultiplier: 1,
|
||||
dataFrequency: (backtest.config?.dataFrequency ??
|
||||
'1d') as BacktestConfig['dataFrequency'],
|
||||
|
|
@ -239,7 +260,7 @@ export function BacktestDetailPageV2() {
|
|||
<h3 className="text-lg font-medium text-text-primary">Run History</h3>
|
||||
<button
|
||||
onClick={() => setShowNewRun(true)}
|
||||
disabled={archived}
|
||||
disabled={archived || catalog || unsupportedLegacy}
|
||||
className="inline-flex items-center px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
|
||||
>
|
||||
<PlusIcon className="w-4 h-4 mr-2" />
|
||||
|
|
@ -422,6 +443,7 @@ export function BacktestDetailPageV2() {
|
|||
isSubmitting={isSubmitting}
|
||||
hasPendingSubmission={hasPendingSubmission}
|
||||
archived={archived}
|
||||
executionUnavailable={catalog || unsupportedLegacy}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
|
@ -430,6 +452,33 @@ export function BacktestDetailPageV2() {
|
|||
|
||||
{/* Tab Content */}
|
||||
<div className="flex flex-col flex-1 min-h-0 overflow-hidden py-4">
|
||||
{catalog && (
|
||||
<p
|
||||
role="status"
|
||||
className="mb-4 p-3 border border-border rounded-lg text-sm text-text-secondary"
|
||||
>
|
||||
{catalogExecutionReason}
|
||||
{backtest?.strategyVersionId && (
|
||||
<>
|
||||
{' '}
|
||||
Selected immutable version:{' '}
|
||||
<Link
|
||||
className="text-primary-500"
|
||||
to={`/strategies/versions/${backtest.strategyVersionId}`}
|
||||
>
|
||||
{backtest.strategyVersionId}
|
||||
</Link>
|
||||
.
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
{unsupportedLegacy && (
|
||||
<p role="status" className="mb-4 text-sm text-text-secondary">
|
||||
This legacy strategy is not supported for new submissions by this form. Its existing
|
||||
history remains readable.
|
||||
</p>
|
||||
)}
|
||||
{archived && (
|
||||
<p
|
||||
role="status"
|
||||
|
|
|
|||
|
|
@ -1,17 +1,21 @@
|
|||
import { PlusIcon } from '@heroicons/react/24/solid';
|
||||
import type { ColumnDef } from '@tanstack/react-table';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { DataTable } from '@/components/ui/DataTable/DataTable';
|
||||
import type { Parameters } from '@/features/strategies/services/strategyApi';
|
||||
import { CreateBacktestDialog } from './components/CreateBacktestDialog';
|
||||
import { backtestApiV2, type Backtest } from './services/backtestApiV2';
|
||||
|
||||
export function BacktestListPageV2() {
|
||||
const navigate = useNavigate();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const location = useLocation();
|
||||
const selectedVersion = searchParams.get('strategyVersionId');
|
||||
const [backtests, setBacktests] = useState<Backtest[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [showCreateDialog, setShowCreateDialog] = useState(false);
|
||||
const [showCreateDialog, setShowCreateDialog] = useState(Boolean(selectedVersion));
|
||||
const [includeArchived, setIncludeArchived] = useState(false);
|
||||
const request = useRef<AbortController | null>(null);
|
||||
|
||||
|
|
@ -43,6 +47,12 @@ export function BacktestListPageV2() {
|
|||
return () => request.current?.abort();
|
||||
}, [loadBacktests]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedVersion) {
|
||||
setShowCreateDialog(true);
|
||||
}
|
||||
}, [selectedVersion]);
|
||||
|
||||
const columns: ColumnDef<Backtest>[] = [
|
||||
{
|
||||
accessorKey: 'name',
|
||||
|
|
@ -62,7 +72,11 @@ export function BacktestListPageV2() {
|
|||
header: 'Strategy',
|
||||
size: 150,
|
||||
cell: ({ row }) => (
|
||||
<span className="capitalize text-text-primary">{row.original.strategy}</span>
|
||||
<span className="text-text-primary">
|
||||
{row.original.strategyVersionId
|
||||
? `Catalog draft · ${row.original.strategyVersionId}`
|
||||
: row.original.strategy}
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
|
|
@ -168,8 +182,21 @@ export function BacktestListPageV2() {
|
|||
|
||||
{showCreateDialog && (
|
||||
<CreateBacktestDialog
|
||||
key={selectedVersion ?? 'legacy'}
|
||||
initialSelection={
|
||||
selectedVersion
|
||||
? {
|
||||
strategyVersionId: selectedVersion,
|
||||
strategyParameters: (location.state as { strategyParameters?: Parameters } | null)
|
||||
?.strategyParameters,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onClose={() => {
|
||||
setShowCreateDialog(false);
|
||||
if (selectedVersion) {
|
||||
setSearchParams({}, { replace: true });
|
||||
}
|
||||
void loadBacktests();
|
||||
}}
|
||||
onCreated={(created, run) => {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,8 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
LegacyStrategySelect,
|
||||
StrategySelection,
|
||||
} from '@/features/strategies/components/StrategySelection';
|
||||
import type { BacktestConfig } from '../types';
|
||||
import { HistoricalDataSelection } from './HistoricalDataSelection';
|
||||
|
||||
|
|
@ -31,20 +35,28 @@ export function BacktestConfiguration({
|
|||
}
|
||||
);
|
||||
|
||||
const catalog = formData.strategy === 'catalog' || Boolean(formData.strategyVersionId);
|
||||
const [strategyValid, setStrategyValid] = useState(false);
|
||||
const [selectionEpoch, setSelectionEpoch] = useState(0);
|
||||
const authoritativeConfig = useRef(initialConfig);
|
||||
const [historicalValid, setHistoricalValid] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saveError, setSaveError] = useState<string | null>(null);
|
||||
const locked = disabled || saving;
|
||||
|
||||
useEffect(() => {
|
||||
if (initialConfig) {
|
||||
if (initialConfig && initialConfig !== authoritativeConfig.current) {
|
||||
authoritativeConfig.current = initialConfig;
|
||||
setFormData(initialConfig);
|
||||
setStrategyValid(false);
|
||||
setSaveError(null);
|
||||
setSelectionEpoch(value => value + 1);
|
||||
}
|
||||
}, [initialConfig]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!historicalValid || locked) {
|
||||
if (!historicalValid || (catalog && !strategyValid) || locked) {
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
|
|
@ -111,30 +123,26 @@ export function BacktestConfiguration({
|
|||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">Strategy</label>
|
||||
<select
|
||||
name="strategy"
|
||||
{catalog ? (
|
||||
<StrategySelection
|
||||
key={selectionEpoch}
|
||||
allowArchivedSelection
|
||||
value={formData}
|
||||
onChange={selection => setFormData(previous => ({ ...previous, ...selection }))}
|
||||
onValidityChange={setStrategyValid}
|
||||
disabled={Boolean(locked)}
|
||||
/>
|
||||
) : (
|
||||
<LegacyStrategySelect
|
||||
value={formData.strategy}
|
||||
onChange={handleChange}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
|
||||
disabled={locked}
|
||||
>
|
||||
<option value="sma-crossover">SMA Crossover</option>
|
||||
<option value="mean-reversion">Mean Reversion</option>
|
||||
<option value="ml-enhanced">ML Enhanced (Advanced)</option>
|
||||
<option value="momentum">Momentum (Coming Soon)</option>
|
||||
<option value="pairs-trading">Pairs Trading (Coming Soon)</option>
|
||||
</select>
|
||||
<p className="text-xs text-text-muted mt-1">
|
||||
{formData.strategy === 'sma-crossover' && 'Trades on 10/20 day moving average crossovers'}
|
||||
{formData.strategy === 'mean-reversion' &&
|
||||
'Trades when price deviates from mean by 2+ std devs'}
|
||||
{formData.strategy === 'ml-enhanced' && 'Uses machine learning for signal generation'}
|
||||
{formData.strategy === 'momentum' && 'Follows strong price trends'}
|
||||
{formData.strategy === 'pairs-trading' && 'Trades correlated asset pairs'}
|
||||
</p>
|
||||
</div>
|
||||
onChange={strategy => setFormData(previous => ({ ...previous, strategy }))}
|
||||
disabled={Boolean(locked)}
|
||||
/>
|
||||
)}
|
||||
<p className="text-xs text-text-muted">
|
||||
This saved template keeps its strategy mode. Create another backtest to switch between
|
||||
catalog and legacy modes.
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
|
|
@ -172,28 +180,30 @@ export function BacktestConfiguration({
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">
|
||||
Speed Multiplier
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
name="speedMultiplier"
|
||||
value={formData.speedMultiplier}
|
||||
onChange={handleChange}
|
||||
min="0.1"
|
||||
max="1000"
|
||||
step="0.1"
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
|
||||
disabled={locked}
|
||||
/>
|
||||
<p className="text-xs text-text-muted mt-1">1x = real-time, 10x = 10x faster</p>
|
||||
</div>
|
||||
{!catalog && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-1">
|
||||
Speed Multiplier
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
name="speedMultiplier"
|
||||
value={formData.speedMultiplier}
|
||||
onChange={handleChange}
|
||||
min="0.1"
|
||||
max="1000"
|
||||
step="0.1"
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
|
||||
disabled={locked}
|
||||
/>
|
||||
<p className="text-xs text-text-muted mt-1">1x = real-time, 10x = 10x faster</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
className="w-full px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
disabled={locked || !historicalValid}
|
||||
disabled={locked || !historicalValid || (catalog && !strategyValid)}
|
||||
>
|
||||
Save
|
||||
</button>
|
||||
|
|
|
|||
|
|
@ -1,15 +1,29 @@
|
|||
import { XMarkIcon } from '@heroicons/react/24/solid';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
LegacyStrategySelect,
|
||||
StrategySelection,
|
||||
type CatalogSelection,
|
||||
} from '@/features/strategies/components/StrategySelection';
|
||||
import {
|
||||
confirmDiscard,
|
||||
useUnsavedWarning,
|
||||
} from '@/features/strategies/components/useUnsavedWarning';
|
||||
import { backtestApiV2, type Backtest, type Run } from '../services/backtestApiV2';
|
||||
import type { HistoricalSelection } from '../services/historical-selection';
|
||||
import { HistoricalDataSelection } from './HistoricalDataSelection';
|
||||
|
||||
interface CreateBacktestDialogProps {
|
||||
initialSelection?: CatalogSelection;
|
||||
onClose: () => void;
|
||||
onCreated: (backtest: Backtest, run?: Run) => void;
|
||||
}
|
||||
|
||||
export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialogProps) {
|
||||
export function CreateBacktestDialog({
|
||||
onClose,
|
||||
onCreated,
|
||||
initialSelection,
|
||||
}: CreateBacktestDialogProps) {
|
||||
const [formData, setFormData] = useState<
|
||||
HistoricalSelection & {
|
||||
name: string;
|
||||
|
|
@ -32,6 +46,11 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
|
|||
dataSource: 'auto',
|
||||
});
|
||||
|
||||
const [catalogMode, setCatalogMode] = useState(Boolean(initialSelection?.strategyVersionId));
|
||||
const [selection, setSelection] = useState<CatalogSelection>(initialSelection ?? {});
|
||||
const [strategyValid, setStrategyValid] = useState(false);
|
||||
const [edited, setEdited] = useState(false);
|
||||
useUnsavedWarning(edited);
|
||||
const [historicalValid, setHistoricalValid] = useState(true);
|
||||
const [phase, setPhase] = useState<'idle' | 'saving' | 'submitting'>('idle');
|
||||
const isSubmitting = phase !== 'idle';
|
||||
|
|
@ -53,12 +72,20 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
|
|||
if (pending.current && !saved.current) {
|
||||
return;
|
||||
}
|
||||
if (!saved.current && !confirmDiscard(edited)) {
|
||||
return;
|
||||
}
|
||||
active.current = false;
|
||||
onClose();
|
||||
};
|
||||
|
||||
const handleSubmit = async (runAfterSave: boolean) => {
|
||||
if (pending.current || !active.current || (!saved.current && !historicalValid)) {
|
||||
if (
|
||||
pending.current ||
|
||||
!active.current ||
|
||||
(!saved.current && (!historicalValid || (catalogMode && !strategyValid))) ||
|
||||
(runAfterSave && catalogMode)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -74,7 +101,8 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
|
|||
if (!saved.current) {
|
||||
const created = await backtestApiV2.createBacktest({
|
||||
name: formData.name,
|
||||
strategy: formData.strategy,
|
||||
strategy: catalogMode ? 'catalog' : formData.strategy,
|
||||
...(catalogMode ? selection : {}),
|
||||
symbols: formData.symbols,
|
||||
startDate: formData.startDate,
|
||||
endDate: formData.endDate,
|
||||
|
|
@ -152,6 +180,7 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
|
|||
void handleSubmit(saved.current !== null);
|
||||
}}
|
||||
className="space-y-6"
|
||||
onChange={() => setEdited(true)}
|
||||
>
|
||||
<fieldset disabled={isSubmitting || saved.current !== null} className="space-y-6">
|
||||
<div>
|
||||
|
|
@ -168,20 +197,35 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
|
|||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-2">Strategy</label>
|
||||
<label className="block text-sm text-text-secondary">
|
||||
Strategy mode
|
||||
<select
|
||||
value={formData.strategy}
|
||||
onChange={e => setFormData({ ...formData, strategy: e.target.value })}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-md text-text-primary focus:outline-none focus:ring-1 focus:ring-primary-500"
|
||||
aria-label="Strategy mode"
|
||||
value={catalogMode ? 'catalog' : 'legacy'}
|
||||
onChange={event => {
|
||||
if (confirmDiscard(Boolean(selection.strategyVersionId))) {
|
||||
setCatalogMode(event.target.value === 'catalog');
|
||||
}
|
||||
}}
|
||||
className="w-full px-3 py-2 bg-background border border-border rounded-md"
|
||||
>
|
||||
<option value="moving-average">Moving Average</option>
|
||||
<option value="momentum">Momentum</option>
|
||||
<option value="mean-reversion">Mean Reversion</option>
|
||||
<option value="pairs-trading">Pairs Trading</option>
|
||||
<option value="custom">Custom</option>
|
||||
<option value="legacy">Legacy strategy</option>
|
||||
<option value="catalog">Catalog version (save only)</option>
|
||||
</select>
|
||||
</div>
|
||||
</label>
|
||||
{catalogMode ? (
|
||||
<StrategySelection
|
||||
value={selection}
|
||||
onChange={setSelection}
|
||||
onValidityChange={setStrategyValid}
|
||||
disabled={isSubmitting || saved.current !== null}
|
||||
/>
|
||||
) : (
|
||||
<LegacyStrategySelect
|
||||
value={formData.strategy}
|
||||
onChange={strategy => setFormData(previous => ({ ...previous, strategy }))}
|
||||
/>
|
||||
)}
|
||||
|
||||
<HistoricalDataSelection
|
||||
value={formData}
|
||||
|
|
@ -251,7 +295,10 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
|
|||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSubmitting || (!saved.current && !historicalValid)}
|
||||
disabled={
|
||||
isSubmitting ||
|
||||
(!saved.current && (!historicalValid || (catalogMode && !strategyValid)))
|
||||
}
|
||||
className="px-4 py-2 bg-primary-500 text-white rounded-md text-sm font-medium hover:bg-primary-600 transition-colors"
|
||||
>
|
||||
{isSubmitting
|
||||
|
|
@ -263,7 +310,7 @@ export function CreateBacktestDialog({ onClose, onCreated }: CreateBacktestDialo
|
|||
{!saved.current && (
|
||||
<button
|
||||
type="button"
|
||||
disabled={isSubmitting || (!saved.current && !historicalValid)}
|
||||
disabled={isSubmitting || catalogMode || (!saved.current && !historicalValid)}
|
||||
onClick={e => {
|
||||
if (e.currentTarget.form?.reportValidity()) {
|
||||
void handleSubmit(true);
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ interface RunControlsCompactProps {
|
|||
isSubmitting?: boolean;
|
||||
hasPendingSubmission?: boolean;
|
||||
archived?: boolean;
|
||||
executionUnavailable?: boolean;
|
||||
}
|
||||
|
||||
export function RunControlsCompact({
|
||||
|
|
@ -19,6 +20,7 @@ export function RunControlsCompact({
|
|||
isSubmitting = false,
|
||||
hasPendingSubmission = false,
|
||||
archived = false,
|
||||
executionUnavailable = false,
|
||||
}: RunControlsCompactProps) {
|
||||
const active = ['pending', 'running', 'paused'].includes(run.status);
|
||||
const requested = active && (cancelRequested || run.cancelRequested);
|
||||
|
|
@ -44,7 +46,7 @@ export function RunControlsCompact({
|
|||
)}
|
||||
<button
|
||||
onClick={() => onRerun(null)}
|
||||
disabled={isSubmitting || (archived && !hasPendingSubmission)}
|
||||
disabled={isSubmitting || ((archived || executionUnavailable) && !hasPendingSubmission)}
|
||||
className="p-1 rounded hover:bg-surface-tertiary transition-colors disabled:opacity-50"
|
||||
title={hasPendingSubmission ? 'Retry submission' : 'Run current settings'}
|
||||
aria-label={hasPendingSubmission ? 'Retry submission' : 'Run current settings'}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,8 @@
|
|||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
catalogExecutionReason,
|
||||
supportedLegacyStrategy,
|
||||
} from '@/features/strategies/components/StrategySelection';
|
||||
import { backtestApiV2, RunResultsUnavailableError } from '../services/backtestApiV2';
|
||||
import type { Backtest, CreateBacktestRequest, Run, RunResult } from '../services/backtestApiV2';
|
||||
|
||||
|
|
@ -330,6 +334,16 @@ export function useBacktestV2() {
|
|||
if (!backtest || backtest.id !== loadedBacktestId.current || submission.current?.pending) {
|
||||
return undefined;
|
||||
}
|
||||
if ((backtest.strategyVersionId || backtest.strategy === 'catalog') && !submission.current) {
|
||||
setSubmissionError(catalogExecutionReason);
|
||||
return undefined;
|
||||
}
|
||||
if (!supportedLegacyStrategy(backtest.strategy) && !submission.current) {
|
||||
setSubmissionError(
|
||||
'This legacy strategy is not supported for new submissions by this form.'
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
if (backtest.archivedAt && !submission.current) {
|
||||
setSubmissionError('Restore this archived backtest before starting a new run.');
|
||||
return undefined;
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import type {
|
|||
BacktestRunDatasetSelection,
|
||||
BacktestRunResult,
|
||||
HistoricalDatasetCatalogEntry,
|
||||
StrategyParameterValue,
|
||||
} from '@stock-bot/types';
|
||||
import { API_BASE_URL, apiFetch as fetch } from '@/lib/api';
|
||||
|
||||
|
|
@ -9,6 +10,8 @@ export interface Backtest {
|
|||
id: string;
|
||||
name: string;
|
||||
strategy: string;
|
||||
strategyVersionId?: string | null;
|
||||
strategyParameters?: Record<string, StrategyParameterValue> | null;
|
||||
symbols: string[];
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
|
|
@ -41,6 +44,8 @@ export interface Run {
|
|||
export interface CreateBacktestRequest {
|
||||
name: string;
|
||||
strategy: string;
|
||||
strategyVersionId?: string | null;
|
||||
strategyParameters?: Record<string, StrategyParameterValue> | null;
|
||||
symbols: string[];
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import type { StrategyParameterValue } from '@stock-bot/types';
|
||||
import type { HistoricalSelection } from '../services/historical-selection';
|
||||
|
||||
export type BacktestStatus =
|
||||
|
|
@ -13,6 +14,8 @@ export interface BacktestConfig extends HistoricalSelection {
|
|||
name: string;
|
||||
initialCapital: number;
|
||||
strategy: string;
|
||||
strategyVersionId?: string | null;
|
||||
strategyParameters?: Record<string, StrategyParameterValue> | null;
|
||||
speedMultiplier: number;
|
||||
commission: number;
|
||||
slippage: number;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,756 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, Navigate, useNavigate, useParams } from 'react-router-dom';
|
||||
import type {
|
||||
StrategyRecord,
|
||||
StrategyVersionPackage,
|
||||
StrategyVersionSummary,
|
||||
} from '@stock-bot/types';
|
||||
import { actionClass, fieldClass, StrategyParameterForm } from './components/StrategyParameterForm';
|
||||
import { versionPath } from './components/StrategySelection';
|
||||
import { confirmDiscard, useUnsavedWarning } from './components/useUnsavedWarning';
|
||||
import { strategyApi, type Parameters } from './services/strategyApi';
|
||||
|
||||
export function StrategyDetailPage() {
|
||||
const { strategyId = '', versionId } = useParams<{ strategyId: string; versionId?: string }>();
|
||||
return <StrategyDetail key={strategyId} strategyId={strategyId} versionId={versionId} />;
|
||||
}
|
||||
function StrategyDetail({ strategyId, versionId }: { strategyId: string; versionId?: string }) {
|
||||
const navigate = useNavigate();
|
||||
const [strategy, setStrategy] = useState<StrategyRecord | null>(null);
|
||||
const [versions, setVersions] = useState<StrategyVersionSummary[]>([]);
|
||||
const [version, setVersion] = useState<StrategyVersionSummary | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [versionLoading, setVersionLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [versionError, setVersionError] = useState<string | null>(null);
|
||||
const [retry, setRetry] = useState(0);
|
||||
const [versionRetry, setVersionRetry] = useState(0);
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saveError, setSaveError] = useState<string | null>(null);
|
||||
const [parameters, setParameters] = useState<Parameters>({});
|
||||
const [validParameters, setValidParameters] = useState(false);
|
||||
const [parameterEdits, setParameterEdits] = useState(false);
|
||||
const [cloneOpen, setCloneOpen] = useState(false);
|
||||
const [cloneName, setCloneName] = useState('');
|
||||
const [cloneDescription, setCloneDescription] = useState('');
|
||||
const [cloning, setCloning] = useState(false);
|
||||
const [cloneError, setCloneError] = useState<string | null>(null);
|
||||
const cloneIntent = useRef<{
|
||||
versionId: string;
|
||||
versionOrdinal: number;
|
||||
body: { name: string; description: string };
|
||||
key: string;
|
||||
} | null>(null);
|
||||
const [cloneFrozen, setCloneFrozen] = useState(false);
|
||||
const mounted = useRef(true);
|
||||
const selectedVersionId = useRef(versionId);
|
||||
selectedVersionId.current = versionId;
|
||||
const metadataDirty = Boolean(
|
||||
strategy && (name !== strategy.name || description !== strategy.description)
|
||||
);
|
||||
const dirty =
|
||||
metadataDirty || parameterEdits || (cloneOpen && Boolean(cloneName || cloneDescription));
|
||||
useUnsavedWarning(dirty);
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
void Promise.all([
|
||||
strategyApi.get(strategyId, controller.signal),
|
||||
strategyApi.versions(strategyId, controller.signal),
|
||||
])
|
||||
.then(([record, history]) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setStrategy(record.strategy);
|
||||
setName(record.strategy.name);
|
||||
setDescription(record.strategy.description);
|
||||
setVersions(history.versions);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [strategyId, retry]);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setVersion(null);
|
||||
setVersionError(null);
|
||||
setValidParameters(false);
|
||||
setParameterEdits(false);
|
||||
if (!versionId) {
|
||||
setVersionLoading(false);
|
||||
return () => controller.abort();
|
||||
}
|
||||
setVersionLoading(true);
|
||||
void strategyApi
|
||||
.version(versionId, controller.signal)
|
||||
.then(result => {
|
||||
if (controller.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
if (result.version.strategyId !== strategyId) {
|
||||
throw new Error('This version belongs to a different strategy family.');
|
||||
}
|
||||
setVersion(result.version);
|
||||
})
|
||||
.catch(cause => {
|
||||
if (!controller.signal.aborted) {
|
||||
setVersionError(cause.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setVersionLoading(false);
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [strategyId, versionId, versionRetry]);
|
||||
const update = async (body: { name?: string; description?: string; archived?: boolean }) => {
|
||||
if (saving) {
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setSaveError(null);
|
||||
try {
|
||||
const result = await strategyApi.update(strategyId, body);
|
||||
if (mounted.current) {
|
||||
setStrategy(result.strategy);
|
||||
setName(result.strategy.name);
|
||||
setDescription(result.strategy.description);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (mounted.current) {
|
||||
setSaveError(cause instanceof Error ? cause.message : 'Could not save strategy');
|
||||
}
|
||||
} finally {
|
||||
if (mounted.current) {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const clone = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!version || cloning || !cloneName.trim()) {
|
||||
return;
|
||||
}
|
||||
const intent = (cloneIntent.current ??= {
|
||||
versionId: version.id,
|
||||
versionOrdinal: version.ordinal,
|
||||
body: { name: cloneName, description: cloneDescription },
|
||||
key: crypto.randomUUID(),
|
||||
});
|
||||
setCloneFrozen(true);
|
||||
setCloning(true);
|
||||
setCloneError(null);
|
||||
try {
|
||||
const result = await strategyApi.clone(intent.versionId, intent.body, intent.key);
|
||||
if (mounted.current && selectedVersionId.current === intent.versionId) {
|
||||
navigate(versionPath(result.version));
|
||||
}
|
||||
} catch (cause) {
|
||||
if (mounted.current && selectedVersionId.current === intent.versionId) {
|
||||
setCloneError(
|
||||
`${cause instanceof Error ? cause.message : 'Clone failed'}. Retry clone to recover the same immutable version.`
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (mounted.current) {
|
||||
setCloning(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className="space-y-5 text-text-primary">
|
||||
<Link
|
||||
className="text-primary-500 text-sm"
|
||||
to="/strategies"
|
||||
onClick={event => {
|
||||
if (!confirmDiscard(dirty)) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}}
|
||||
>
|
||||
All strategies
|
||||
</Link>
|
||||
{loading && <p role="status">Loading strategy...</p>}
|
||||
{error && (
|
||||
<div>
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
<button
|
||||
className={actionClass}
|
||||
onClick={() => {
|
||||
if (confirmDiscard(dirty)) {
|
||||
setRetry(value => value + 1);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Retry strategy
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{!loading && !error && strategy && (
|
||||
<>
|
||||
<h1 className="text-lg font-bold">
|
||||
{strategy.name}
|
||||
{strategy.archived ? ' — Archived' : ''}
|
||||
</h1>
|
||||
<form
|
||||
className="space-y-3 border border-border rounded-md p-4"
|
||||
onSubmit={event => {
|
||||
event.preventDefault();
|
||||
void update({ name, description });
|
||||
}}
|
||||
>
|
||||
<label className="block text-sm">
|
||||
Strategy name
|
||||
<input
|
||||
aria-label="Strategy name"
|
||||
className={fieldClass}
|
||||
required
|
||||
disabled={saving}
|
||||
value={name}
|
||||
onChange={event => setName(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
Strategy description
|
||||
<textarea
|
||||
aria-label="Strategy description"
|
||||
className={fieldClass}
|
||||
disabled={saving}
|
||||
value={description}
|
||||
onChange={event => setDescription(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{metadataDirty && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
Unsaved strategy metadata. Save or discard before leaving.
|
||||
</p>
|
||||
)}
|
||||
{saveError && (
|
||||
<p role="alert" className="text-error text-sm">
|
||||
{saveError}
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
className={actionClass}
|
||||
disabled={saving || !metadataDirty || !name.trim()}
|
||||
>
|
||||
Save metadata
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={saving || !metadataDirty}
|
||||
onClick={() => {
|
||||
if (confirmDiscard(metadataDirty)) {
|
||||
setName(strategy.name);
|
||||
setDescription(strategy.description);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Discard metadata changes
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={saving}
|
||||
onClick={() => {
|
||||
if (
|
||||
confirmDiscard(metadataDirty) &&
|
||||
window.confirm(
|
||||
strategy.archived
|
||||
? 'Restore this strategy family?'
|
||||
: 'Archive this strategy family? Saved versions and history remain available.'
|
||||
)
|
||||
) {
|
||||
void update({ archived: !strategy.archived });
|
||||
}
|
||||
}}
|
||||
>
|
||||
{strategy.archived ? 'Restore strategy' : 'Archive strategy'}
|
||||
</button>
|
||||
</form>
|
||||
<section className="space-y-3">
|
||||
<h2 className="font-semibold">Immutable versions</h2>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Publish version packages using the existing catalog API. Metadata edits do not change
|
||||
retained code.
|
||||
</p>
|
||||
<label className="block text-sm">
|
||||
Strategy version
|
||||
<select
|
||||
aria-label="Strategy version"
|
||||
className={fieldClass}
|
||||
value={versionId ?? ''}
|
||||
disabled={cloning || cloneFrozen}
|
||||
onChange={event => {
|
||||
if (confirmDiscard(parameterEdits)) {
|
||||
navigate(
|
||||
event.target.value
|
||||
? `/strategies/${strategyId}/versions/${event.target.value}`
|
||||
: `/strategies/${strategyId}`
|
||||
);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<option value="">Select an immutable version</option>
|
||||
{versions.map(item => (
|
||||
<option key={item.id} value={item.id}>
|
||||
Version {item.ordinal} — {item.id}
|
||||
</option>
|
||||
))}
|
||||
{versionId && !versions.some(item => item.id === versionId) && (
|
||||
<option value={versionId}>{versionId}</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
{!versions.length && (
|
||||
<p role="status">
|
||||
No immutable versions have been published. Publish a package or clone an existing
|
||||
version from another family.
|
||||
</p>
|
||||
)}
|
||||
{versionLoading && <p role="status">Loading strategy version...</p>}
|
||||
{versionError && (
|
||||
<div>
|
||||
<p role="alert" className="text-error">
|
||||
{versionError}
|
||||
</p>
|
||||
<button className={actionClass} onClick={() => setVersionRetry(value => value + 1)}>
|
||||
Retry version
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{version && version.id === versionId && (
|
||||
<>
|
||||
<VersionIdentity version={version} />
|
||||
<VersionComparison key={version.id} version={version} versions={versions} />
|
||||
<StrategyParameterForm
|
||||
key={version.id}
|
||||
versionId={version.id}
|
||||
schema={version.package.parameterSchema}
|
||||
onEdit={() => setParameterEdits(true)}
|
||||
onChange={(next, valid) => {
|
||||
setParameters(next);
|
||||
setValidParameters(valid);
|
||||
if (valid) {
|
||||
setParameterEdits(true);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
className={actionClass}
|
||||
disabled={!validParameters || strategy.archived}
|
||||
onClick={() => {
|
||||
if (confirmDiscard(metadataDirty)) {
|
||||
navigate(`/backtests?strategyVersionId=${version.id}`, {
|
||||
state: { strategyParameters: parameters },
|
||||
});
|
||||
}
|
||||
}}
|
||||
>
|
||||
Use in backtest
|
||||
</button>
|
||||
{strategy.archived && (
|
||||
<p className="text-sm text-text-secondary">
|
||||
Restore this family before selecting its versions for a new backtest.
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
className={actionClass}
|
||||
disabled={cloneOpen}
|
||||
onClick={() => {
|
||||
setCloneOpen(true);
|
||||
setCloneName(`${strategy.name} (copy)`);
|
||||
setCloneDescription(strategy.description);
|
||||
}}
|
||||
>
|
||||
Clone version
|
||||
</button>
|
||||
{cloneOpen && (
|
||||
<form
|
||||
onSubmit={event => void clone(event)}
|
||||
className="space-y-3 border border-border rounded-md p-4"
|
||||
>
|
||||
<h3 className="font-medium">
|
||||
Clone immutable version{' '}
|
||||
{cloneIntent.current?.versionOrdinal ?? version.ordinal}
|
||||
</h3>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Clone source version ID:{' '}
|
||||
<code>{cloneIntent.current?.versionId ?? version.id}</code>
|
||||
</p>
|
||||
{cloneIntent.current && cloneIntent.current.versionId !== version.id && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
This pending clone and its retries still use version{' '}
|
||||
{cloneIntent.current.versionOrdinal} ({cloneIntent.current.versionId}), even
|
||||
while you view version {version.ordinal} ({version.id}). Retrying recovers
|
||||
the original clone; it does not clone the currently displayed version.
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm text-text-secondary">
|
||||
The clone retains exact artifact bytes and parent lineage. It is a new
|
||||
candidate awaiting review; cloning does not enable execution.
|
||||
</p>
|
||||
<label className="block text-sm">
|
||||
Clone name
|
||||
<input
|
||||
aria-label="Clone name"
|
||||
className={fieldClass}
|
||||
disabled={cloneFrozen}
|
||||
required
|
||||
value={cloneName}
|
||||
onChange={event => setCloneName(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
Clone description
|
||||
<textarea
|
||||
aria-label="Clone description"
|
||||
className={fieldClass}
|
||||
disabled={cloneFrozen}
|
||||
value={cloneDescription}
|
||||
onChange={event => setCloneDescription(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
{cloneError && (
|
||||
<p role="alert" className="text-error text-sm">
|
||||
{cloneError}
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
className={actionClass}
|
||||
disabled={cloning || !cloneName.trim()}
|
||||
>
|
||||
{cloning ? 'Cloning...' : cloneFrozen ? 'Retry clone' : 'Create clone'}
|
||||
</button>{' '}
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={cloning}
|
||||
onClick={() => {
|
||||
if (
|
||||
window.confirm(
|
||||
cloneFrozen
|
||||
? 'Abandon this clone receipt? If the response was lost, the clone may already exist. Check the catalog before creating another.'
|
||||
: 'Discard clone metadata?'
|
||||
)
|
||||
) {
|
||||
setCloneOpen(false);
|
||||
setCloneFrozen(false);
|
||||
cloneIntent.current = null;
|
||||
setCloneError(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Close clone
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
<section className="text-sm text-text-secondary space-y-2">
|
||||
<h3 className="font-medium text-text-primary">Version history</h3>
|
||||
<p>
|
||||
No runs using retained versions are available yet. Legacy name-based runs are
|
||||
not evidence for this version.
|
||||
</p>
|
||||
<p>Deployment history is not available in this catalog yet.</p>
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function VersionIdentity({ version }: { version: StrategyVersionSummary }) {
|
||||
const pkg = version.package;
|
||||
return (
|
||||
<div className="space-y-2 text-sm border border-border rounded-md p-4">
|
||||
<h3 className="font-medium">Version {version.ordinal}</h3>
|
||||
<p>
|
||||
Immutable version ID: <code>{version.id}</code>
|
||||
</p>
|
||||
<p>
|
||||
Origin: {version.origin} · Review: {version.reviewStatus}
|
||||
</p>
|
||||
<p role="status">
|
||||
{version.origin === 'candidate'
|
||||
? 'Candidate execution is unavailable until isolated execution is supported.'
|
||||
: 'Execution of this retained built-in version is not available from the workbench yet.'}
|
||||
</p>
|
||||
<p>
|
||||
Program: {pkg.program.strategyId} / {pkg.program.strategyVersion}
|
||||
</p>
|
||||
<p>
|
||||
API: {pkg.program.apiVersion} · Checkpoint: {pkg.program.checkpointVersion}
|
||||
</p>
|
||||
<p className="break-all">Artifact SHA256: {pkg.artifact.sha256}</p>
|
||||
<p className="break-all">Dependency lock SHA256: {pkg.dependencyLock.sha256}</p>
|
||||
<p className="break-all">
|
||||
Source revision: {pkg.source.revision} (
|
||||
{pkg.source.dirty ? 'dirty working tree' : 'clean working tree'})
|
||||
</p>
|
||||
<p>
|
||||
Build: {pkg.build.tool} {pkg.build.version} / {pkg.build.target}
|
||||
</p>
|
||||
{version.parentVersionId && <p>Parent version: {version.parentVersionId}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
function VersionComparison({
|
||||
version,
|
||||
versions,
|
||||
}: {
|
||||
version: StrategyVersionSummary;
|
||||
versions: StrategyVersionSummary[];
|
||||
}) {
|
||||
const [showArtifact, setShowArtifact] = useState(false);
|
||||
const [compareId, setCompareId] = useState('');
|
||||
const [artifact, setArtifact] = useState<StrategyVersionPackage | null>(null);
|
||||
const [comparison, setComparison] = useState<StrategyVersionPackage | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [retry, setRetry] = useState(0);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setComparison(null);
|
||||
setError(null);
|
||||
if (!showArtifact && !compareId) {
|
||||
setLoading(false);
|
||||
return () => controller.abort();
|
||||
}
|
||||
setLoading(true);
|
||||
void Promise.all([
|
||||
strategyApi.artifact(version.id, controller.signal),
|
||||
compareId ? strategyApi.artifact(compareId, controller.signal) : Promise.resolve(null),
|
||||
])
|
||||
.then(([current, other]) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setArtifact(current.package);
|
||||
setComparison(other?.package ?? null);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [version.id, showArtifact, compareId, retry]);
|
||||
const options = versions.filter(item => item.id !== version.id);
|
||||
return (
|
||||
<section className="space-y-3">
|
||||
<button className={actionClass} onClick={() => setShowArtifact(value => !value)}>
|
||||
{showArtifact ? 'Hide bundled JavaScript' : 'View bundled JavaScript'}
|
||||
</button>
|
||||
<label className="block text-sm">
|
||||
Compare with version
|
||||
<select
|
||||
aria-label="Compare with version"
|
||||
className={fieldClass}
|
||||
value={compareId}
|
||||
onChange={event => setCompareId(event.target.value)}
|
||||
>
|
||||
<option value="">No comparison</option>
|
||||
{options.map(item => (
|
||||
<option key={item.id} value={item.id}>
|
||||
Version {item.ordinal} — {item.id}
|
||||
</option>
|
||||
))}
|
||||
{version.parentVersionId &&
|
||||
!options.some(item => item.id === version.parentVersionId) && (
|
||||
<option value={version.parentVersionId}>
|
||||
Parent version — {version.parentVersionId}
|
||||
</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
{(showArtifact || compareId) && (
|
||||
<p className="text-sm text-text-secondary">
|
||||
Retained bundled JavaScript, not original TypeScript. Displayed as text; never executed in
|
||||
the browser.
|
||||
</p>
|
||||
)}
|
||||
{loading && <p role="status">Loading retained artifacts...</p>}
|
||||
{error && (
|
||||
<div>
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
<button className={actionClass} onClick={() => setRetry(value => value + 1)}>
|
||||
Retry artifacts
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{!loading && !error && artifact && (showArtifact || compareId) && (
|
||||
<>
|
||||
{comparison && (
|
||||
<>
|
||||
<h3 className="font-medium">Version comparison</h3>
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="text-left">Retained field</th>
|
||||
<th className="text-left">Comparison</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{(['program', 'parameterSchema', 'source', 'build'] as const).map(key => (
|
||||
<tr key={key}>
|
||||
<td>{key}</td>
|
||||
<td>
|
||||
{JSON.stringify(artifact[key]) === JSON.stringify(comparison[key])
|
||||
? 'Unchanged'
|
||||
: 'Changed'}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
<tr>
|
||||
<td>Artifact SHA256</td>
|
||||
<td>
|
||||
{artifact.artifact.sha256 === comparison.artifact.sha256
|
||||
? 'Identical artifact bytes'
|
||||
: 'Different artifact bytes'}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>Dependency lock SHA256</td>
|
||||
<td>
|
||||
{artifact.dependencyLock.sha256 === comparison.dependencyLock.sha256
|
||||
? 'Unchanged'
|
||||
: 'Changed'}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div>
|
||||
<h4>Selected version metadata</h4>
|
||||
<pre className="overflow-auto text-xs max-h-64">
|
||||
{JSON.stringify(
|
||||
{
|
||||
program: artifact.program,
|
||||
parameterSchema: artifact.parameterSchema,
|
||||
source: artifact.source,
|
||||
build: artifact.build,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</pre>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Compared version metadata</h4>
|
||||
<pre className="overflow-auto text-xs max-h-64">
|
||||
{JSON.stringify(
|
||||
{
|
||||
program: comparison.program,
|
||||
parameterSchema: comparison.parameterSchema,
|
||||
source: comparison.source,
|
||||
build: comparison.build,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div className={comparison ? 'grid gap-4 md:grid-cols-2' : ''}>
|
||||
<div>
|
||||
<h4>Selected bundled JavaScript</h4>
|
||||
<pre
|
||||
aria-label="Selected bundled JavaScript"
|
||||
className="overflow-auto max-h-96 text-xs p-3 border border-border rounded-md"
|
||||
>
|
||||
{artifact.artifact.content}
|
||||
</pre>
|
||||
</div>
|
||||
{comparison && (
|
||||
<div>
|
||||
<h4>Compared bundled JavaScript</h4>
|
||||
<pre
|
||||
aria-label="Compared bundled JavaScript"
|
||||
className="overflow-auto max-h-96 text-xs p-3 border border-border rounded-md"
|
||||
>
|
||||
{comparison.artifact.content}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** Saved backtests retain version identity without duplicating the mutable family metadata. */
|
||||
export function StrategyVersionPage() {
|
||||
const { versionId = '' } = useParams<{ versionId: string }>();
|
||||
const [version, setVersion] = useState<StrategyVersionSummary | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [retry, setRetry] = useState(0);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setVersion(null);
|
||||
setError(null);
|
||||
void strategyApi
|
||||
.version(versionId, controller.signal)
|
||||
.then(result => {
|
||||
if (!controller.signal.aborted) {
|
||||
setVersion(result.version);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause.message);
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [versionId, retry]);
|
||||
if (version) {
|
||||
return <Navigate to={versionPath(version)} replace />;
|
||||
}
|
||||
return (
|
||||
<div className="space-y-3 text-text-primary">
|
||||
{error ? (
|
||||
<>
|
||||
<p role="alert">{error}</p>
|
||||
<button className={actionClass} onClick={() => setRetry(value => value + 1)}>
|
||||
Retry version
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<p role="status">Loading strategy version...</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
201
apps/stock/web-app/src/features/strategies/StrategyListPage.tsx
Normal file
201
apps/stock/web-app/src/features/strategies/StrategyListPage.tsx
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import type { StrategyRecord } from '@stock-bot/types';
|
||||
import { actionClass, fieldClass } from './components/StrategyParameterForm';
|
||||
import { confirmDiscard, useUnsavedWarning } from './components/useUnsavedWarning';
|
||||
import { strategyApi } from './services/strategyApi';
|
||||
|
||||
export function StrategyListPage() {
|
||||
const navigate = useNavigate();
|
||||
const mounted = useRef(true);
|
||||
const pendingCreate = useRef(false);
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
return () => {
|
||||
mounted.current = false;
|
||||
};
|
||||
}, []);
|
||||
const [strategies, setStrategies] = useState<StrategyRecord[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [retry, setRetry] = useState(0);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [showCreate, setShowCreate] = useState(false);
|
||||
const [name, setName] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [createError, setCreateError] = useState<string | null>(null);
|
||||
const [showArchived, setShowArchived] = useState(false);
|
||||
const dirty = showCreate && Boolean(name || description);
|
||||
useUnsavedWarning(dirty);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
void strategyApi
|
||||
.list(controller.signal)
|
||||
.then(result => {
|
||||
if (!controller.signal.aborted) {
|
||||
setStrategies(result.strategies);
|
||||
}
|
||||
})
|
||||
.catch(cause => {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [retry]);
|
||||
const create = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (pendingCreate.current || !name.trim()) {
|
||||
return;
|
||||
}
|
||||
pendingCreate.current = true;
|
||||
setCreating(true);
|
||||
setCreateError(null);
|
||||
try {
|
||||
const result = await strategyApi.create({ name, description });
|
||||
if (mounted.current) {
|
||||
navigate(`/strategies/${result.strategy.id}`);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (mounted.current) {
|
||||
setCreateError(
|
||||
`${cause instanceof Error ? cause.message : 'Could not create strategy'}. Refresh the catalog before retrying if the response was lost; the strategy may already have been created.`
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
pendingCreate.current = false;
|
||||
if (mounted.current) {
|
||||
setCreating(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
const visible = strategies.filter(item => showArchived || !item.archived);
|
||||
return (
|
||||
<div className="space-y-5 text-text-primary">
|
||||
<div className="flex justify-between items-center">
|
||||
<h1 className="text-lg font-bold">Strategies</h1>
|
||||
<button className={actionClass} onClick={() => setShowCreate(true)}>
|
||||
New strategy
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Organize immutable strategy packages and prepare backtest drafts. Catalog execution is not
|
||||
available yet.
|
||||
</p>
|
||||
{showCreate && (
|
||||
<form
|
||||
className="space-y-3 border border-border rounded-md p-4"
|
||||
onSubmit={event => void create(event)}
|
||||
>
|
||||
<label className="block text-sm">
|
||||
Strategy name
|
||||
<input
|
||||
className={fieldClass}
|
||||
aria-label="Strategy name"
|
||||
value={name}
|
||||
onChange={event => setName(event.target.value)}
|
||||
required
|
||||
disabled={creating}
|
||||
/>
|
||||
</label>
|
||||
<label className="block text-sm">
|
||||
Strategy description
|
||||
<textarea
|
||||
className={fieldClass}
|
||||
aria-label="Strategy description"
|
||||
value={description}
|
||||
onChange={event => setDescription(event.target.value)}
|
||||
disabled={creating}
|
||||
/>
|
||||
</label>
|
||||
{dirty && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
Unsaved strategy metadata. Save or discard before leaving.
|
||||
</p>
|
||||
)}
|
||||
{createError && (
|
||||
<p role="alert" className="text-sm text-error">
|
||||
{createError}
|
||||
</p>
|
||||
)}
|
||||
<button className={actionClass} disabled={creating || !name.trim()} type="submit">
|
||||
{creating ? 'Creating strategy...' : 'Create strategy'}
|
||||
</button>{' '}
|
||||
<button
|
||||
className={actionClass}
|
||||
disabled={creating}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
if (confirmDiscard(dirty)) {
|
||||
setShowCreate(false);
|
||||
setName('');
|
||||
setDescription('');
|
||||
setCreateError(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Discard
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
<label className="flex gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={showArchived}
|
||||
onChange={event => setShowArchived(event.target.checked)}
|
||||
/>
|
||||
Show archived strategies
|
||||
</label>
|
||||
{loading && <p role="status">Loading strategies...</p>}
|
||||
{error && (
|
||||
<div>
|
||||
<p role="alert" className="text-error">
|
||||
{error}
|
||||
</p>
|
||||
<button className={actionClass} onClick={() => setRetry(value => value + 1)}>
|
||||
Retry strategies
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{!loading && !error && !visible.length && (
|
||||
<p role="status">
|
||||
No strategies found. Create a strategy family, then publish an immutable package through
|
||||
the existing catalog API.
|
||||
</p>
|
||||
)}
|
||||
{!loading && !error && (
|
||||
<ul className="space-y-3">
|
||||
{visible.map(strategy => (
|
||||
<li className="border border-border rounded-md p-4" key={strategy.id}>
|
||||
<Link
|
||||
className="text-primary-500 font-medium"
|
||||
to={`/strategies/${strategy.id}`}
|
||||
onClick={event => {
|
||||
if (!confirmDiscard(dirty)) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{strategy.name}
|
||||
</Link>
|
||||
{strategy.archived && <span className="ml-2 text-xs">Archived</span>}
|
||||
<p className="text-sm text-text-secondary whitespace-pre-wrap">
|
||||
{strategy.description || 'No description yet.'}
|
||||
</p>
|
||||
<p className="text-xs text-text-muted">
|
||||
Owner: {strategy.ownerPrincipal} · {strategy.id}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,251 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { StrategyParameterSchema, StrategyParameterValue } from '@stock-bot/types';
|
||||
import { strategyApi, type Parameters } from '../services/strategyApi';
|
||||
|
||||
export const fieldClass =
|
||||
'w-full px-3 py-2 bg-background border border-border rounded-md text-sm text-text-primary disabled:opacity-50';
|
||||
export const actionClass =
|
||||
'px-3 py-2 rounded-md border border-border text-sm text-primary-500 disabled:opacity-50';
|
||||
|
||||
export function parameterFields(
|
||||
schema: StrategyParameterSchema,
|
||||
raw: Record<string, string>,
|
||||
included: Record<string, boolean>
|
||||
) {
|
||||
const parameters: Parameters = Object.create(null);
|
||||
const errors: Record<string, string> = Object.create(null);
|
||||
for (const key of Object.keys(raw)) {
|
||||
if (!Object.prototype.hasOwnProperty.call(schema.properties, key)) {
|
||||
errors[key] = 'Unknown parameter';
|
||||
}
|
||||
}
|
||||
for (const [name, rule] of Object.entries(schema.properties)) {
|
||||
const text = raw[name] ?? '';
|
||||
const stringValue = rule.type === 'string' && !rule.enum;
|
||||
if ((stringValue && !included[name]) || (!stringValue && text === '')) {
|
||||
if (schema.required.includes(name) && rule.default === undefined) {
|
||||
errors[name] = 'Required';
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let value: StrategyParameterValue;
|
||||
if (rule.enum) {
|
||||
const choice = rule.enum.find(item => JSON.stringify(item) === text);
|
||||
if (choice === undefined) {
|
||||
errors[name] = 'Choose a listed value';
|
||||
continue;
|
||||
}
|
||||
value = choice;
|
||||
} else if (rule.type === 'boolean') {
|
||||
if (text !== 'true' && text !== 'false') {
|
||||
errors[name] = 'Choose true or false';
|
||||
continue;
|
||||
}
|
||||
value = text === 'true';
|
||||
} else if (rule.type === 'string') {
|
||||
value = text;
|
||||
} else {
|
||||
value = Number(text);
|
||||
if (
|
||||
text.trim() === '' ||
|
||||
!Number.isFinite(value) ||
|
||||
(rule.type === 'integer' && !Number.isInteger(value))
|
||||
) {
|
||||
errors[name] = `Enter a finite ${rule.type}`;
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
(rule.minimum !== undefined && value < rule.minimum) ||
|
||||
(rule.maximum !== undefined && value > rule.maximum) ||
|
||||
(rule.exclusiveMinimum !== undefined && value <= rule.exclusiveMinimum) ||
|
||||
(rule.exclusiveMaximum !== undefined && value >= rule.exclusiveMaximum)
|
||||
) {
|
||||
errors[name] = 'Value is outside the allowed range';
|
||||
continue;
|
||||
}
|
||||
}
|
||||
parameters[name] = value;
|
||||
}
|
||||
return { parameters, errors };
|
||||
}
|
||||
function initialFields(
|
||||
schema: StrategyParameterSchema,
|
||||
values: Parameters
|
||||
): { raw: Record<string, string>; included: Record<string, boolean> } {
|
||||
const raw: Record<string, string> = Object.create(null);
|
||||
const included: Record<string, boolean> = Object.create(null);
|
||||
for (const name of new Set([...Object.keys(schema.properties), ...Object.keys(values)])) {
|
||||
const rule = schema.properties[name];
|
||||
const value = Object.prototype.hasOwnProperty.call(values, name) ? values[name] : rule?.default;
|
||||
raw[name] = value === undefined ? '' : rule?.enum ? JSON.stringify(value) : String(value);
|
||||
included[name] = value !== undefined;
|
||||
}
|
||||
return { raw, included };
|
||||
}
|
||||
|
||||
/** Key this component by immutable version ID. Server validation remains authoritative. */
|
||||
export function StrategyParameterForm({
|
||||
versionId,
|
||||
schema,
|
||||
initialParameters = {},
|
||||
disabled = false,
|
||||
onChange,
|
||||
onEdit,
|
||||
}: {
|
||||
versionId: string;
|
||||
schema: StrategyParameterSchema;
|
||||
initialParameters?: Parameters;
|
||||
disabled?: boolean;
|
||||
onChange: (parameters: Parameters, valid: boolean) => void;
|
||||
onEdit?: () => void;
|
||||
}) {
|
||||
const [{ raw, included }, setFields] = useState(() => initialFields(schema, initialParameters));
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [validating, setValidating] = useState(false);
|
||||
const [validated, setValidated] = useState(false);
|
||||
const generation = useRef(0);
|
||||
const changed = useRef(onChange);
|
||||
changed.current = onChange;
|
||||
const parsed = parameterFields(schema, raw, included);
|
||||
useEffect(() => {
|
||||
changed.current(parameterFields(schema, raw, included).parameters, false);
|
||||
return () => {
|
||||
generation.current++;
|
||||
};
|
||||
// Parent keys this form by immutable version, preserving raw edits during unrelated renders.
|
||||
}, []);
|
||||
const edit = (name: string, text: string, include = true) => {
|
||||
onEdit?.();
|
||||
generation.current++;
|
||||
const next = { ...raw, [name]: text };
|
||||
const nextIncluded = { ...included, [name]: include };
|
||||
setFields({ raw: next, included: nextIncluded });
|
||||
setValidated(false);
|
||||
setValidating(false);
|
||||
setError(null);
|
||||
onChange(parameterFields(schema, next, nextIncluded).parameters, false);
|
||||
};
|
||||
const validate = async () => {
|
||||
if (disabled || Object.keys(parsed.errors).length) {
|
||||
return;
|
||||
}
|
||||
const current = ++generation.current;
|
||||
setValidating(true);
|
||||
setValidated(false);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await strategyApi.validate(versionId, parsed.parameters);
|
||||
if (current !== generation.current) {
|
||||
return;
|
||||
}
|
||||
setFields(initialFields(schema, result.parameters));
|
||||
setValidated(true);
|
||||
onChange(result.parameters, true);
|
||||
} catch (cause) {
|
||||
if (current === generation.current) {
|
||||
setError(cause instanceof Error ? cause.message : 'Parameter validation failed');
|
||||
onChange(parsed.parameters, false);
|
||||
}
|
||||
} finally {
|
||||
if (current === generation.current) {
|
||||
setValidating(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<h3 className="font-medium text-text-primary">Strategy parameters</h3>
|
||||
<p className="text-xs text-text-muted">
|
||||
Blank optional numeric fields are omitted; declared defaults apply. Use Include for string
|
||||
values to distinguish omitted values from empty text. Included strings are kept exactly as
|
||||
entered.
|
||||
</p>
|
||||
{Object.entries(schema.properties).map(([name, rule]) => (
|
||||
<div key={name}>
|
||||
{rule.type === 'string' && !rule.enum && (
|
||||
<label className="flex items-center gap-2 text-xs text-text-secondary">
|
||||
<input
|
||||
type="checkbox"
|
||||
aria-label={`Include ${name}`}
|
||||
checked={included[name] ?? false}
|
||||
disabled={disabled}
|
||||
onChange={event => edit(name, raw[name] ?? '', event.target.checked)}
|
||||
/>
|
||||
Include {name} (empty text is a value)
|
||||
</label>
|
||||
)}
|
||||
<label className="block text-sm text-text-secondary">
|
||||
{name}
|
||||
{schema.required.includes(name) ? ' *' : ''}
|
||||
{rule.enum || rule.type === 'boolean' ? (
|
||||
<select
|
||||
aria-label={name}
|
||||
value={raw[name] ?? ''}
|
||||
disabled={disabled}
|
||||
className={fieldClass}
|
||||
onChange={event => edit(name, event.target.value)}
|
||||
>
|
||||
<option value="">
|
||||
{schema.required.includes(name)
|
||||
? 'Select a value'
|
||||
: 'Omit (use default if defined)'}
|
||||
</option>
|
||||
{(rule.enum ?? [true, false]).map(value => (
|
||||
<option key={JSON.stringify(value)} value={JSON.stringify(value)}>
|
||||
{String(value)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<input
|
||||
aria-label={name}
|
||||
type="text"
|
||||
inputMode={rule.type === 'string' ? 'text' : 'decimal'}
|
||||
className={fieldClass}
|
||||
disabled={disabled || (rule.type === 'string' && !included[name])}
|
||||
value={raw[name] ?? ''}
|
||||
onChange={event => edit(name, event.target.value)}
|
||||
aria-invalid={Boolean(parsed.errors[name])}
|
||||
/>
|
||||
)}
|
||||
</label>
|
||||
{rule.description && <p className="text-xs text-text-muted">{rule.description}</p>}
|
||||
{parsed.errors[name] && (
|
||||
<p role="alert" className="text-sm text-error">
|
||||
{name}: {parsed.errors[name]}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{Object.keys(parsed.errors)
|
||||
.filter(name => !Object.prototype.hasOwnProperty.call(schema.properties, name))
|
||||
.map(name => (
|
||||
<p key={name} role="alert" className="text-sm text-error">
|
||||
{name}: Unknown parameter. Select another version or correct the saved parameters
|
||||
through the API.
|
||||
</p>
|
||||
))}
|
||||
{Object.keys(schema.properties).length === 0 && (
|
||||
<p className="text-sm text-text-muted">This version has no parameters.</p>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className={actionClass}
|
||||
disabled={disabled || validating || Object.keys(parsed.errors).length > 0}
|
||||
onClick={() => void validate()}
|
||||
>
|
||||
{validating ? 'Validating parameters...' : 'Validate parameters'}
|
||||
</button>
|
||||
{validated && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
Parameters validated for this immutable version. Execution remains unavailable.
|
||||
</p>
|
||||
)}
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-error">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,312 @@
|
|||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { StrategyRecord, StrategyVersionSummary } from '@stock-bot/types';
|
||||
import { strategyApi, type Parameters } from '../services/strategyApi';
|
||||
import { actionClass, fieldClass, StrategyParameterForm } from './StrategyParameterForm';
|
||||
|
||||
export interface CatalogSelection {
|
||||
strategyVersionId?: string | null;
|
||||
strategyParameters?: Parameters | null;
|
||||
}
|
||||
export const catalogExecutionReason =
|
||||
'Catalog versions are save-only. Execution of retained versions is not available yet.';
|
||||
export function versionPath(version: Pick<StrategyVersionSummary, 'strategyId' | 'id'>) {
|
||||
return `/strategies/${encodeURIComponent(version.strategyId)}/versions/${encodeURIComponent(version.id)}`;
|
||||
}
|
||||
|
||||
export function StrategySelection({
|
||||
value,
|
||||
onChange,
|
||||
onValidityChange,
|
||||
disabled = false,
|
||||
allowArchivedSelection = false,
|
||||
}: {
|
||||
value: CatalogSelection;
|
||||
onChange: (value: CatalogSelection) => void;
|
||||
onValidityChange: (valid: boolean) => void;
|
||||
disabled?: boolean;
|
||||
allowArchivedSelection?: boolean;
|
||||
}) {
|
||||
const [families, setFamilies] = useState<StrategyRecord[]>([]);
|
||||
const [familyId, setFamilyId] = useState('');
|
||||
const [family, setFamily] = useState<StrategyRecord | null>(null);
|
||||
const [versions, setVersions] = useState<StrategyVersionSummary[]>([]);
|
||||
const [selected, setSelected] = useState<StrategyVersionSummary | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [catalogLoading, setCatalogLoading] = useState(true);
|
||||
const [versionsLoading, setVersionsLoading] = useState(false);
|
||||
const [catalogError, setCatalogError] = useState<string | null>(null);
|
||||
const [selectionError, setSelectionError] = useState<string | null>(null);
|
||||
const [versionsError, setVersionsError] = useState<string | null>(null);
|
||||
const [retry, setRetry] = useState(0);
|
||||
const callbacks = useRef({ onChange, onValidityChange });
|
||||
callbacks.current = { onChange, onValidityChange };
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setCatalogError(null);
|
||||
setCatalogLoading(true);
|
||||
void strategyApi
|
||||
.list(controller.signal)
|
||||
.then(result => {
|
||||
if (!controller.signal.aborted) {
|
||||
setFamilies(result.strategies);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
if (!controller.signal.aborted) {
|
||||
setCatalogError(error.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setCatalogLoading(false);
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [retry]);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setSelected(null);
|
||||
setFamily(null);
|
||||
setSelectionError(null);
|
||||
callbacks.current.onValidityChange(false);
|
||||
const selectedId = value.strategyVersionId;
|
||||
if (!selectedId) {
|
||||
setLoading(false);
|
||||
return () => controller.abort();
|
||||
}
|
||||
setLoading(true);
|
||||
void (async () => {
|
||||
try {
|
||||
const result = await strategyApi.version(selectedId, controller.signal);
|
||||
const owner = await strategyApi.get(result.version.strategyId, controller.signal);
|
||||
if (!controller.signal.aborted) {
|
||||
setSelected(result.version);
|
||||
setFamily(owner.strategy);
|
||||
setFamilyId(result.version.strategyId);
|
||||
}
|
||||
} catch (cause) {
|
||||
if (!controller.signal.aborted) {
|
||||
setSelectionError(cause instanceof Error ? cause.message : 'Version unavailable');
|
||||
}
|
||||
} finally {
|
||||
if (!controller.signal.aborted) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
})();
|
||||
return () => controller.abort();
|
||||
}, [value.strategyVersionId, retry]);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setVersions([]);
|
||||
setVersionsError(null);
|
||||
setVersionsLoading(Boolean(familyId));
|
||||
if (familyId) {
|
||||
void strategyApi
|
||||
.versions(familyId, controller.signal)
|
||||
.then(result => {
|
||||
if (!controller.signal.aborted) {
|
||||
setVersions(result.versions);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
if (!controller.signal.aborted) {
|
||||
setVersionsError(error.message);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) {
|
||||
setVersionsLoading(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
return () => controller.abort();
|
||||
}, [familyId, retry]);
|
||||
const activeFamilies = families.filter(item => !item.archived);
|
||||
const displayedFamilies = family?.archived ? [family, ...activeFamilies] : activeFamilies;
|
||||
const displayedVersions =
|
||||
selected && !versions.some(item => item.id === selected.id)
|
||||
? [selected, ...versions]
|
||||
: versions;
|
||||
return (
|
||||
<div className="space-y-3 border border-border rounded-md p-3">
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
{catalogExecutionReason}
|
||||
</p>
|
||||
<label className="block text-sm text-text-secondary">
|
||||
Strategy family
|
||||
<select
|
||||
aria-label="Strategy family"
|
||||
className={fieldClass}
|
||||
disabled={disabled || Boolean(catalogError)}
|
||||
value={familyId}
|
||||
onChange={event => {
|
||||
setFamilyId(event.target.value);
|
||||
callbacks.current.onValidityChange(false);
|
||||
onChange({ strategyVersionId: null, strategyParameters: {} });
|
||||
}}
|
||||
>
|
||||
<option value="">Select a strategy family</option>
|
||||
{displayedFamilies.map(item => (
|
||||
<option key={item.id} value={item.id} disabled={item.archived}>
|
||||
{item.name}
|
||||
{item.archived ? ' (archived — retained selection)' : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{catalogLoading && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
Loading strategy catalog...
|
||||
</p>
|
||||
)}
|
||||
{!catalogLoading && !catalogError && !activeFamilies.length && (
|
||||
<p className="text-sm text-text-secondary">
|
||||
No strategies available.{' '}
|
||||
<Link to="/strategies" className="text-primary-500">
|
||||
Open strategy catalog
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
<label className="block text-sm text-text-secondary">
|
||||
Immutable strategy version
|
||||
<select
|
||||
aria-label="Immutable strategy version"
|
||||
className={fieldClass}
|
||||
value={value.strategyVersionId ?? ''}
|
||||
disabled={disabled || !familyId || Boolean(family?.archived) || Boolean(versionsError)}
|
||||
onChange={event => {
|
||||
callbacks.current.onValidityChange(false);
|
||||
onChange({ strategyVersionId: event.target.value || null, strategyParameters: {} });
|
||||
}}
|
||||
>
|
||||
<option value="">Select an immutable version</option>
|
||||
{displayedVersions.map(item => (
|
||||
<option key={item.id} value={item.id}>
|
||||
Version {item.ordinal} — {item.id} ({item.origin}, {item.reviewStatus})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{versionsLoading && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
Loading available versions...
|
||||
</p>
|
||||
)}
|
||||
{familyId && !versionsLoading && !versionsError && !versions.length && !loading && (
|
||||
<p className="text-sm text-text-secondary">No versions published for this family.</p>
|
||||
)}
|
||||
{loading && <p role="status">Loading selected strategy version...</p>}
|
||||
{[catalogError, versionsError, selectionError].filter(Boolean).map((error, index) => (
|
||||
<p key={index} role="alert" className="text-sm text-error">
|
||||
{error}
|
||||
</p>
|
||||
))}
|
||||
{(catalogError || versionsError || selectionError) && (
|
||||
<button type="button" className={actionClass} onClick={() => setRetry(value => value + 1)}>
|
||||
Retry strategy catalog
|
||||
</button>
|
||||
)}
|
||||
{value.strategyVersionId && !selected && !loading && (
|
||||
<p role="alert" className="text-sm text-error">
|
||||
Selected version {value.strategyVersionId} is unavailable. The selection has been
|
||||
retained; saving is disabled.
|
||||
</p>
|
||||
)}
|
||||
{selected && selected.id === value.strategyVersionId && (
|
||||
<>
|
||||
<Link className="text-sm text-primary-500" to={versionPath(selected)}>
|
||||
View immutable version {selected.ordinal}
|
||||
</Link>
|
||||
<p className="text-xs text-text-muted">
|
||||
{selected.origin === 'candidate'
|
||||
? 'Candidate execution is unavailable until isolated execution is supported.'
|
||||
: 'This retained built-in version cannot be executed from the workbench yet.'}
|
||||
</p>
|
||||
{family?.archived && (
|
||||
<p role="status" className="text-sm text-text-secondary">
|
||||
This strategy family is archived. Its retained version remains readable; restore the
|
||||
family before selecting it for a new backtest.
|
||||
</p>
|
||||
)}
|
||||
<StrategyParameterForm
|
||||
key={selected.id}
|
||||
versionId={selected.id}
|
||||
schema={selected.package.parameterSchema}
|
||||
initialParameters={value.strategyParameters ?? {}}
|
||||
disabled={disabled || Boolean(family?.archived && !allowArchivedSelection)}
|
||||
onChange={(parameters, valid) => {
|
||||
onChange({ strategyVersionId: selected.id, strategyParameters: parameters });
|
||||
callbacks.current.onValidityChange(
|
||||
valid && (!family?.archived || allowArchivedSelection)
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function LegacyStrategySelect({
|
||||
value,
|
||||
onChange,
|
||||
disabled = false,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const options = [
|
||||
['moving-average', 'Moving Average'],
|
||||
...(value === 'sma-crossover' || value === 'sma' || value === 'sma_crossover'
|
||||
? [[value, 'SMA Crossover']]
|
||||
: []),
|
||||
['momentum', 'Momentum'],
|
||||
['mean-reversion', 'Mean Reversion'],
|
||||
...(value === 'mean_reversion' ? [[value, 'Mean Reversion']] : []),
|
||||
];
|
||||
const supported = options.some(([id]) => id === value);
|
||||
return (
|
||||
<div>
|
||||
<label className="block text-sm text-text-secondary">
|
||||
Legacy strategy
|
||||
<select
|
||||
aria-label="Legacy strategy"
|
||||
className={fieldClass}
|
||||
value={value}
|
||||
onChange={event => onChange(event.target.value)}
|
||||
disabled={disabled}
|
||||
>
|
||||
{!supported && (
|
||||
<option value={value} disabled>
|
||||
{value} (not supported by this form)
|
||||
</option>
|
||||
)}
|
||||
{options.map(([id, label]) => (
|
||||
<option value={id} key={id}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p className="text-xs text-text-muted">
|
||||
Legacy name-based workflow. These runs do not execute retained catalog versions or provide
|
||||
canonical strategy-version provenance.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function supportedLegacyStrategy(value: string) {
|
||||
return [
|
||||
'moving-average',
|
||||
'sma-crossover',
|
||||
'sma',
|
||||
'sma_crossover',
|
||||
'momentum',
|
||||
'mean-reversion',
|
||||
'mean_reversion',
|
||||
].includes(value);
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
import { useEffect } from 'react';
|
||||
|
||||
export function useUnsavedWarning(dirty: boolean) {
|
||||
useEffect(() => {
|
||||
if (!dirty) {
|
||||
return;
|
||||
}
|
||||
const warn = (event: BeforeUnloadEvent) => {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
};
|
||||
window.addEventListener('beforeunload', warn);
|
||||
return () => window.removeEventListener('beforeunload', warn);
|
||||
}, [dirty]);
|
||||
}
|
||||
export const confirmDiscard = (dirty: boolean) =>
|
||||
!dirty || window.confirm('Discard unsaved changes?');
|
||||
2
apps/stock/web-app/src/features/strategies/index.ts
Normal file
2
apps/stock/web-app/src/features/strategies/index.ts
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export { StrategyListPage } from './StrategyListPage';
|
||||
export { StrategyDetailPage, StrategyVersionPage } from './StrategyDetailPage';
|
||||
|
|
@ -0,0 +1,60 @@
|
|||
import type {
|
||||
ParameterValidationResult,
|
||||
StrategyParameterValue,
|
||||
StrategyRecord,
|
||||
StrategyReviewEvent,
|
||||
StrategyVersionPackage,
|
||||
StrategyVersionSummary,
|
||||
} from '@stock-bot/types';
|
||||
import { API_BASE_URL, apiFetch } from '@/lib/api';
|
||||
|
||||
export type Parameters = Record<string, StrategyParameterValue>;
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const response = await apiFetch(`${API_BASE_URL}/api/v2/${path}`, init);
|
||||
const body = await response.json().catch(() => null);
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
typeof body?.error === 'string' ? body.error : `Strategy request failed (${response.status})`
|
||||
);
|
||||
}
|
||||
return body as T;
|
||||
}
|
||||
const json = (method: string, body: unknown, key?: string): RequestInit => ({
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json', ...(key ? { 'Idempotency-Key': key } : {}) },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const id = encodeURIComponent;
|
||||
export const strategyApi = {
|
||||
list: (signal?: AbortSignal) =>
|
||||
request<{ strategies: StrategyRecord[] }>('strategies', { signal }),
|
||||
get: (strategyId: string, signal?: AbortSignal) =>
|
||||
request<{ strategy: StrategyRecord }>(`strategies/${id(strategyId)}`, { signal }),
|
||||
create: (body: { name: string; description: string }) =>
|
||||
request<{ strategy: StrategyRecord }>('strategies', json('POST', body)),
|
||||
update: (strategyId: string, body: { name?: string; description?: string; archived?: boolean }) =>
|
||||
request<{ strategy: StrategyRecord }>(`strategies/${id(strategyId)}`, json('PATCH', body)),
|
||||
versions: (strategyId: string, signal?: AbortSignal) =>
|
||||
request<{ versions: StrategyVersionSummary[] }>(`strategies/${id(strategyId)}/versions`, {
|
||||
signal,
|
||||
}),
|
||||
version: (versionId: string, signal?: AbortSignal) =>
|
||||
request<{ version: StrategyVersionSummary; reviews: StrategyReviewEvent[] }>(
|
||||
`strategy-versions/${id(versionId)}`,
|
||||
{ signal }
|
||||
),
|
||||
artifact: (versionId: string, signal?: AbortSignal) =>
|
||||
request<{ package: StrategyVersionPackage }>(`strategy-versions/${id(versionId)}/artifact`, {
|
||||
signal,
|
||||
}),
|
||||
validate: (versionId: string, parameters: Parameters) =>
|
||||
request<ParameterValidationResult>(
|
||||
`strategy-versions/${id(versionId)}/validate`,
|
||||
json('POST', { parameters })
|
||||
),
|
||||
clone: (versionId: string, body: { name: string; description: string }, key: string) =>
|
||||
request<{ strategy: StrategyRecord; version: StrategyVersionSummary }>(
|
||||
`strategy-versions/${id(versionId)}/clone`,
|
||||
json('POST', body, key)
|
||||
),
|
||||
};
|
||||
Loading…
Add table
Add a link
Reference in a new issue