feat(research): run retained strategies through durable canonical engine
This commit is contained in:
parent
d929db707a
commit
618fb9e33c
58 changed files with 6596 additions and 779 deletions
|
|
@ -58,7 +58,8 @@ export async function runMigrations(container: IServiceContainer): Promise<void>
|
|||
f === '15-canonical-paper-intents.sql' ||
|
||||
f === '16-strategy-catalog.sql' ||
|
||||
f === '17-research-retention.sql' ||
|
||||
f === '18-backtest-strategy-versions.sql')
|
||||
f === '18-backtest-strategy-versions.sql' ||
|
||||
f === '19-canonical-research.sql')
|
||||
) // Explicit additive migration allowlist; never replay destructive init migrations
|
||||
.sort();
|
||||
|
||||
|
|
|
|||
|
|
@ -55,6 +55,10 @@ export function createBacktestV2Routes(container: IServiceContainer) {
|
|||
}
|
||||
});
|
||||
|
||||
app.get('/api/v2/backtests/:id/canonical-capability', async c =>
|
||||
c.json(await backtestService.canonicalCapability(c.req.param('id')))
|
||||
);
|
||||
|
||||
app.post('/api/v2/backtests', async c => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { Hono } from 'hono';
|
|||
import { getLogger } from '@stock-bot/logger';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { canonicalDatasetEntry } from '../services/canonical-research.service';
|
||||
import { DatasetCatalogService } from '../services/dataset-catalog.service';
|
||||
|
||||
const logger = getLogger('dataset-catalog-routes');
|
||||
|
|
@ -9,6 +10,57 @@ const logger = getLogger('dataset-catalog-routes');
|
|||
export function createDatasetRoutes(container: IServiceContainer) {
|
||||
const app = new Hono();
|
||||
const catalog = new DatasetCatalogService(requireServices(container, 'postgres').postgres);
|
||||
const database = requireServices(container, 'postgres').postgres;
|
||||
app.get('/api/v2/datasets/canonical', async c => {
|
||||
try {
|
||||
const limit = c.req.query('limit') ?? '50';
|
||||
const offset = c.req.query('offset') ?? '0';
|
||||
if (
|
||||
!/^\d+$/.test(limit) ||
|
||||
!/^\d+$/.test(offset) ||
|
||||
!Number.isSafeInteger(Number(limit)) ||
|
||||
Number(limit) < 1 ||
|
||||
!Number.isSafeInteger(Number(offset))
|
||||
) {
|
||||
return c.json(
|
||||
{ error: 'Dataset pagination requires a positive limit and nonnegative offset' },
|
||||
400
|
||||
);
|
||||
}
|
||||
const rows = await database.query<{ hash: string; created_at: Date }>(
|
||||
"SELECT hash,created_at FROM backtest_datasets WHERE payload#>>'{manifest,version}'='2' ORDER BY created_at DESC,hash LIMIT $1 OFFSET $2",
|
||||
[Number(limit), Number(offset)]
|
||||
);
|
||||
const datasets = [];
|
||||
for (const row of rows.rows) {
|
||||
datasets.push(await canonicalDatasetEntry(database, row));
|
||||
}
|
||||
return c.json({ datasets });
|
||||
} catch (error) {
|
||||
logger.error('Failed to list canonical datasets', error);
|
||||
return c.json({ error: 'Failed to list canonical datasets' }, 500);
|
||||
}
|
||||
});
|
||||
app.get('/api/v2/datasets/canonical/:hash', async c => {
|
||||
try {
|
||||
const hash = c.req.param('hash');
|
||||
if (!/^[a-f0-9]{64}$/.test(hash)) {
|
||||
return c.json({ error: 'Invalid dataset hash' }, 400);
|
||||
}
|
||||
const row = (
|
||||
await database.query<{ hash: string; created_at: Date }>(
|
||||
'SELECT hash,created_at FROM backtest_datasets WHERE hash=$1',
|
||||
[hash]
|
||||
)
|
||||
).rows[0];
|
||||
return row
|
||||
? c.json({ dataset: await canonicalDatasetEntry(database, row) })
|
||||
: c.json({ error: 'Dataset not found' }, 404);
|
||||
} catch (error) {
|
||||
logger.error('Failed to get canonical dataset', error);
|
||||
return c.json({ error: 'Failed to get canonical dataset' }, 500);
|
||||
}
|
||||
});
|
||||
app.get('/api/v2/datasets', async c => {
|
||||
try {
|
||||
const limit = c.req.query('limit') ?? '50';
|
||||
|
|
|
|||
|
|
@ -13,19 +13,25 @@ import {
|
|||
rejectCatalogVersionReferences,
|
||||
type BacktestDefinitionInput,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
canonicalRunRequestSchema,
|
||||
parseCanonicalFinancialResult,
|
||||
type CanonicalRunCapability,
|
||||
type CanonicalRunResult,
|
||||
type ResearchRunResult,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
assertStrategyJsonText,
|
||||
canonicalStrategyJson,
|
||||
validateStrategyParameters,
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import type {
|
||||
BacktestRunDatasetSelection,
|
||||
BacktestRunResult,
|
||||
StrategyParameterValue,
|
||||
} from '@stock-bot/types';
|
||||
import type { BacktestRunDatasetSelection, StrategyParameterValue } from '@stock-bot/types';
|
||||
import { HistoricalDataRequestError } from '@stock-bot/types';
|
||||
import { buildCanonicalBacktestReport } from '../../../orchestrator/src/backtest/canonical-result';
|
||||
import { getWebSocketHandler } from '../websocket/run-updates';
|
||||
import type { WebSocketHandler } from '../websocket/run-updates';
|
||||
import { mapStoredBacktestResult, type StoredBacktestResult } from './backtest-result';
|
||||
import { admitCanonicalRequest, validateCanonicalSetup } from './canonical-research.service';
|
||||
import { assertSelectedDatasetMatchesRequest } from './dataset-catalog.service';
|
||||
import { StrategyCatalogError, StrategyCatalogService } from './strategy-catalog.service';
|
||||
|
||||
|
|
@ -101,9 +107,10 @@ export class RunSubmissionConflictError extends Error {
|
|||
}
|
||||
export class CatalogExecutionUnavailableError extends Error {
|
||||
readonly code = 'catalog_execution_unavailable';
|
||||
constructor() {
|
||||
constructor(reason?: string) {
|
||||
super(
|
||||
'Catalog strategy execution is unavailable until the canonical runner is integrated (R05); this saved draft cannot run through a legacy strategy'
|
||||
reason ??
|
||||
'Configure an approved built-in, eligible v2 dataset and canonical policy before execution'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -423,20 +430,44 @@ export class BacktestServiceV2 {
|
|||
throw new BacktestRetentionError('backtest_archived');
|
||||
}
|
||||
const definition = this.mapBacktest(at(parent.rows, 0));
|
||||
if (definition.strategyVersionId !== null || definition.strategy === 'catalog') {
|
||||
throw new CatalogExecutionUnavailableError();
|
||||
const catalog = definition.strategyVersionId !== null || definition.strategy === 'catalog';
|
||||
if (catalog && multiplier !== null) {
|
||||
throw new CatalogExecutionUnavailableError('Canonical research runs at maximum speed');
|
||||
}
|
||||
let canonical;
|
||||
if (catalog) {
|
||||
try {
|
||||
canonical = await admitCanonicalRequest(
|
||||
client,
|
||||
this.container,
|
||||
definition,
|
||||
definition.id,
|
||||
runId
|
||||
);
|
||||
} catch (error) {
|
||||
throw new CatalogExecutionUnavailableError(
|
||||
error instanceof Error ? error.message : 'Canonical execution unavailable'
|
||||
);
|
||||
}
|
||||
}
|
||||
const snapshot =
|
||||
canonical ??
|
||||
backtestRequestFromDefinition(legacyDefinition(definition), {
|
||||
runId,
|
||||
backtestId: definition.id,
|
||||
speedMultiplier: multiplier,
|
||||
});
|
||||
if (!canonical) {
|
||||
await assertSelectedDatasetMatchesRequest(
|
||||
client,
|
||||
snapshot as ReturnType<typeof backtestRequestFromDefinition>
|
||||
);
|
||||
}
|
||||
const snapshot = backtestRequestFromDefinition(legacyDefinition(definition), {
|
||||
runId,
|
||||
backtestId: definition.id,
|
||||
speedMultiplier: multiplier,
|
||||
});
|
||||
await assertSelectedDatasetMatchesRequest(client, snapshot);
|
||||
const result = await client.query(
|
||||
`INSERT INTO runs
|
||||
(id, backtest_id, run_number, speed_multiplier, status, request_snapshot,
|
||||
(id, backtest_id, run_number, speed_multiplier, status, request_snapshot, dataset_hash,
|
||||
submission_principal, submission_key, submission_hash)
|
||||
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status, $4::jsonb, $5, $6, $7
|
||||
SELECT $1, $2, COALESCE(MAX(run_number), 0) + 1, $3, 'pending'::run_status, $4::jsonb, $8, $5, $6, $7
|
||||
FROM runs WHERE backtest_id = $2
|
||||
${submission ? 'ON CONFLICT (submission_principal, submission_key) DO NOTHING' : ''}
|
||||
RETURNING *`,
|
||||
|
|
@ -448,6 +479,7 @@ export class BacktestServiceV2 {
|
|||
submission?.principal ?? null,
|
||||
submission?.key ?? null,
|
||||
submissionHash,
|
||||
canonical?.datasetHash ?? null,
|
||||
]
|
||||
);
|
||||
// Different parent locks can race for one principal/key. The unique index waits for
|
||||
|
|
@ -548,12 +580,18 @@ export class BacktestServiceV2 {
|
|||
}
|
||||
|
||||
// Get run results
|
||||
async getRunResults(runId: string): Promise<BacktestRunResult | null> {
|
||||
const result = await this.container.postgres.query<StoredBacktestResult>(
|
||||
async getRunResults(runId: string): Promise<ResearchRunResult | null> {
|
||||
const result = await this.container.postgres.query<
|
||||
StoredBacktestResult & {
|
||||
canonical_result?: CanonicalRunResult | null;
|
||||
request_snapshot?: unknown;
|
||||
}
|
||||
>(
|
||||
`SELECT
|
||||
br.*,
|
||||
r.backtest_id,
|
||||
r.status as run_status,
|
||||
r.request_snapshot,
|
||||
b.strategy,
|
||||
b.symbols,
|
||||
b.start_date,
|
||||
|
|
@ -571,7 +609,54 @@ export class BacktestServiceV2 {
|
|||
return null;
|
||||
}
|
||||
|
||||
return mapStoredBacktestResult(at(result.rows, 0));
|
||||
const row = at(result.rows, 0);
|
||||
if (row.canonical_result !== null && row.canonical_result !== undefined) {
|
||||
const saved = row.canonical_result;
|
||||
const request = canonicalRunRequestSchema.parse(row.request_snapshot);
|
||||
const financial = parseCanonicalFinancialResult(saved.financial, request);
|
||||
if (
|
||||
saved.kind !== 'canonical-result/v1' ||
|
||||
saved.runId !== runId ||
|
||||
saved.backtestId !== row.backtest_id ||
|
||||
saved.status !== 'completed' ||
|
||||
saved.financialEngine !== 'rust' ||
|
||||
saved.strategyExecution !== 'typescript-retained-builtin/v1' ||
|
||||
!Number.isFinite(Date.parse(saved.completedAt)) ||
|
||||
!Number.isFinite(saved.executionTime) ||
|
||||
saved.executionTime < 0 ||
|
||||
canonicalStrategyJson(saved.request) !== canonicalStrategyJson(request) ||
|
||||
canonicalStrategyJson(saved.analytics) !==
|
||||
canonicalStrategyJson(
|
||||
buildCanonicalBacktestReport(financial, request.analyticsPolicy).analytics
|
||||
)
|
||||
) {
|
||||
throw new Error('Saved canonical result does not match its admitted request');
|
||||
}
|
||||
return saved;
|
||||
}
|
||||
if ((row.request_snapshot as { kind?: unknown } | null)?.kind === 'canonical-research/v1') {
|
||||
throw new Error('Canonical result is missing; no legacy projection is available');
|
||||
}
|
||||
return mapStoredBacktestResult(row);
|
||||
}
|
||||
|
||||
async canonicalCapability(id: string): Promise<CanonicalRunCapability> {
|
||||
try {
|
||||
await this.container.postgres.transaction(async client => {
|
||||
const row = (await client.query('SELECT * FROM backtests WHERE id=$1 FOR UPDATE', [id]))
|
||||
.rows[0];
|
||||
if (!row || row.archived_at !== null) {
|
||||
throw new Error('Backtest is missing or archived');
|
||||
}
|
||||
await admitCanonicalRequest(client, this.container, this.mapBacktest(row), id);
|
||||
});
|
||||
return { available: true, reason: null };
|
||||
} catch (error) {
|
||||
return {
|
||||
available: false,
|
||||
reason: error instanceof Error ? error.message : 'Canonical execution unavailable',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Private methods
|
||||
|
|
@ -616,6 +701,15 @@ export class BacktestServiceV2 {
|
|||
'Strategy is archived; restore it before selecting a new version'
|
||||
);
|
||||
}
|
||||
if (draft.config.canonical) {
|
||||
await validateCanonicalSetup(client, { ...draft, strategyParameters: parameters });
|
||||
return {
|
||||
...draft,
|
||||
startDate: new Date(draft.startDate).toISOString(),
|
||||
endDate: new Date(draft.endDate).toISOString(),
|
||||
strategyParameters: parameters,
|
||||
};
|
||||
}
|
||||
const settings = backtestSettingsFromDefinition(draft);
|
||||
await assertSelectedDatasetMatchesRequest(client, settings);
|
||||
return {
|
||||
|
|
@ -675,6 +769,15 @@ export class BacktestServiceV2 {
|
|||
export function datasetSelectionForRun(row: QueryResultRow): BacktestRunDatasetSelection {
|
||||
const hash = datasetHashSchema.safeParse(row.dataset_hash);
|
||||
const pinnedHash = hash.success ? hash.data : null;
|
||||
if ((row.request_snapshot as { kind?: unknown } | null)?.kind === 'canonical-research/v1') {
|
||||
const canonical = canonicalRunRequestSchema.safeParse(row.request_snapshot);
|
||||
return {
|
||||
requestedHash: canonical.success ? canonical.data.datasetHash : null,
|
||||
pinnedHash,
|
||||
source: null,
|
||||
state: canonical.success ? (pinnedHash ? 'pinned' : 'unavailable') : 'unknown',
|
||||
};
|
||||
}
|
||||
let snapshot;
|
||||
try {
|
||||
snapshot = parseBacktestRequest(row.request_snapshot);
|
||||
|
|
|
|||
273
apps/stock/web-api/src/services/canonical-research.service.ts
Normal file
273
apps/stock/web-api/src/services/canonical-research.service.ts
Normal file
|
|
@ -0,0 +1,273 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import type { PoolClient } from 'pg';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import {
|
||||
canonicalResearchSettingsSchema,
|
||||
canonicalRunRequestSchema,
|
||||
type CanonicalDatasetCatalogEntry,
|
||||
type CanonicalRunRequest,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { builtinStrategySelectionSchema } from '@stock-bot/stock-config/strategy';
|
||||
import {
|
||||
HistoricalDataRequestError,
|
||||
parseFinancialDecimal,
|
||||
type HistoricalDatasetV2,
|
||||
type StrategyParameterValue,
|
||||
} from '@stock-bot/types';
|
||||
import { readCanonicalBuildIdentity } from '../../../orchestrator/src/backtest/canonical-build';
|
||||
import { validateDatasetV2 } from '../../../orchestrator/src/data/historical-dataset-v2';
|
||||
import type { DatasetCatalogQuery } from './dataset-catalog.service';
|
||||
import { StrategyCatalogService } from './strategy-catalog.service';
|
||||
|
||||
export interface CanonicalTemplate {
|
||||
name: string;
|
||||
strategyVersionId?: string | null;
|
||||
strategyParameters?: Record<string, StrategyParameterValue> | null;
|
||||
symbols: string[];
|
||||
startDate: string | Date;
|
||||
endDate: string | Date;
|
||||
initialCapital: number;
|
||||
config?: Record<string, unknown>;
|
||||
}
|
||||
const invalid = (message: string): never => {
|
||||
throw new HistoricalDataRequestError(message);
|
||||
};
|
||||
|
||||
export async function readCanonicalDataset(
|
||||
database: DatasetCatalogQuery,
|
||||
hash: unknown
|
||||
): Promise<HistoricalDatasetV2> {
|
||||
if (typeof hash !== 'string' || !/^[a-f0-9]{64}$/.test(hash)) {
|
||||
return invalid('Choose an explicitly retained v2 dataset');
|
||||
}
|
||||
const row = (await database.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [hash]))
|
||||
.rows[0];
|
||||
if (!row) {
|
||||
return invalid('Selected canonical dataset was not found');
|
||||
}
|
||||
let dataset;
|
||||
try {
|
||||
dataset = validateDatasetV2(row.payload);
|
||||
} catch {
|
||||
return invalid('Retained v2 dataset failed content validation');
|
||||
}
|
||||
if (dataset.manifest.hash !== hash) {
|
||||
return invalid('Retained dataset identity mismatch');
|
||||
}
|
||||
if (dataset.manifest.eligibility !== 'eligible') {
|
||||
return invalid(
|
||||
'Canonical research requires an eligible dataset with known timing and action coverage'
|
||||
);
|
||||
}
|
||||
if (
|
||||
dataset.manifest.executionSeries.length !== 1 ||
|
||||
dataset.manifest.series.length !== 1 ||
|
||||
dataset.manifest.universe.instrumentIds.length !== 1
|
||||
) {
|
||||
return invalid(
|
||||
'Canonical workbench currently supports one execution asset and one retained series'
|
||||
);
|
||||
}
|
||||
return dataset;
|
||||
}
|
||||
|
||||
export async function canonicalDatasetEntry(
|
||||
database: DatasetCatalogQuery,
|
||||
row: { hash: string; created_at: Date }
|
||||
): Promise<CanonicalDatasetCatalogEntry> {
|
||||
try {
|
||||
const dataset = await readCanonicalDataset(database, row.hash);
|
||||
return {
|
||||
hash: row.hash,
|
||||
createdAt: new Date(row.created_at).toISOString(),
|
||||
manifest: dataset.manifest,
|
||||
available: true,
|
||||
reason: null,
|
||||
};
|
||||
} catch (error) {
|
||||
if (!(error instanceof HistoricalDataRequestError)) {
|
||||
throw error;
|
||||
}
|
||||
return {
|
||||
hash: row.hash,
|
||||
createdAt: new Date(row.created_at).toISOString(),
|
||||
manifest: null,
|
||||
available: false,
|
||||
reason: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** Separate v2 boundary: never round exchange-session times through the v1 daily parser. */
|
||||
export async function validateCanonicalSetup(
|
||||
database: DatasetCatalogQuery,
|
||||
template: CanonicalTemplate
|
||||
) {
|
||||
const config = template.config ?? {};
|
||||
if (
|
||||
Object.keys(config).some(key => !['datasetHash', 'dataFrequency', 'canonical'].includes(key))
|
||||
) {
|
||||
return invalid('Canonical settings cannot include legacy fees, risk controls or fill models');
|
||||
}
|
||||
const settings = canonicalResearchSettingsSchema.parse(config.canonical);
|
||||
const dataset = await readCanonicalDataset(database, config.datasetHash);
|
||||
const execution = dataset.manifest.executionSeries[0];
|
||||
const series = dataset.manifest.series.find(item => item.id === execution?.seriesId);
|
||||
if (!execution || !series) {
|
||||
return invalid('Retained dataset is missing its execution series');
|
||||
}
|
||||
if (
|
||||
template.symbols.length !== 1 ||
|
||||
template.symbols[0] !== execution.instrumentId ||
|
||||
config.dataFrequency !== series.interval ||
|
||||
new Date(template.startDate).getTime() !== dataset.manifest.bounds.tradeStart ||
|
||||
new Date(template.endDate).getTime() !== dataset.manifest.bounds.tradeEnd
|
||||
) {
|
||||
return invalid(
|
||||
'Canonical symbols, interval and exact trade bounds must match the retained dataset'
|
||||
);
|
||||
}
|
||||
let initial;
|
||||
try {
|
||||
initial = parseFinancialDecimal(String(template.initialCapital));
|
||||
} catch {
|
||||
return invalid('Initial capital must be an exact supported financial decimal');
|
||||
}
|
||||
const units = BigInt(initial.replace('.', ''));
|
||||
if (units <= 0n || units % 1000000n !== 0n) {
|
||||
return invalid('Saved initial capital must be positive USD with at most two decimal places');
|
||||
}
|
||||
if (BigInt(settings.ownerBudget.replace('.', '')) > units) {
|
||||
return invalid('Strategy owner budget cannot exceed initial capital');
|
||||
}
|
||||
return { settings, dataset, execution, series, initial };
|
||||
}
|
||||
|
||||
/** Called under the backtest lock; this also serializes with family review/archive. */
|
||||
export async function admitCanonicalRequest(
|
||||
client: PoolClient,
|
||||
container: IServiceContainer,
|
||||
template: CanonicalTemplate,
|
||||
backtestId: string,
|
||||
runId = randomUUID()
|
||||
): Promise<CanonicalRunRequest> {
|
||||
if (!template.strategyVersionId || !template.strategyParameters) {
|
||||
return invalid('Select an immutable strategy version and validated parameters');
|
||||
}
|
||||
const selected = (
|
||||
await client.query(
|
||||
`SELECT v.strategy_id,v.origin,s.archived_at FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id
|
||||
WHERE v.id=$1 FOR UPDATE OF s`,
|
||||
[template.strategyVersionId]
|
||||
)
|
||||
).rows[0];
|
||||
if (!selected || selected.archived_at !== null || selected.origin !== 'builtin') {
|
||||
return invalid(
|
||||
'Only active, server-seeded built-in versions can execute; candidates require isolation'
|
||||
);
|
||||
}
|
||||
const review = (
|
||||
await client.query(
|
||||
'SELECT id,decision FROM strategy_review_events WHERE version_id=$1 ORDER BY ordinal DESC LIMIT 1',
|
||||
[template.strategyVersionId]
|
||||
)
|
||||
).rows[0];
|
||||
if (review?.decision !== 'approve') {
|
||||
return invalid('An operator must approve this built-in version before execution');
|
||||
}
|
||||
const pkg = await new StrategyCatalogService(container).getVersionArtifact(
|
||||
template.strategyVersionId,
|
||||
client
|
||||
);
|
||||
const { settings, dataset, execution, series, initial } = await validateCanonicalSetup(
|
||||
client,
|
||||
template
|
||||
);
|
||||
const calendar = dataset.manifest.calendars.find(item => item.id === series.calendarId);
|
||||
if (!calendar) {
|
||||
return invalid('Retained dataset is missing its execution calendar');
|
||||
}
|
||||
const { warmupStart, tradeEnd } = dataset.manifest.bounds;
|
||||
const initialSession = calendar.sessions.filter(session => session.open <= warmupStart).at(-1);
|
||||
if (!initialSession) {
|
||||
return invalid('Retained calendar needs an account-session opening at or before warmup start');
|
||||
}
|
||||
// The account resets at this retained calendar's opens. This declared clock is
|
||||
// distinct from venue order expiry; its identity and every boundary are frozen.
|
||||
const riskSession = (session: typeof initialSession) => ({
|
||||
calendarId: calendar.id,
|
||||
calendarRevision: calendar.revision,
|
||||
sessionId: session.date,
|
||||
startsAt: session.open,
|
||||
});
|
||||
const ownerId = `strategy:${template.strategyVersionId}`;
|
||||
const selection = builtinStrategySelectionSchema.parse({
|
||||
strategyId: pkg.program.strategyId,
|
||||
strategyVersion: pkg.program.strategyVersion,
|
||||
ownerId,
|
||||
seed: settings.seed,
|
||||
instrumentId: execution.instrumentId,
|
||||
seriesId: execution.seriesId,
|
||||
ownerBudget: settings.ownerBudget,
|
||||
parameters: template.strategyParameters,
|
||||
// API/checkpoint identities are retained in the package, not selection fields.
|
||||
});
|
||||
return canonicalRunRequestSchema.parse({
|
||||
kind: 'canonical-research/v1',
|
||||
runId,
|
||||
backtestId,
|
||||
name: template.name,
|
||||
strategy: {
|
||||
familyId: selected.strategy_id,
|
||||
versionId: template.strategyVersionId,
|
||||
origin: 'builtin',
|
||||
reviewId: review.id,
|
||||
package: pkg,
|
||||
selection,
|
||||
},
|
||||
datasetHash: dataset.manifest.hash,
|
||||
policy: {
|
||||
matching: {
|
||||
risk: {
|
||||
ledger: {
|
||||
version: 1,
|
||||
sessionId: runId,
|
||||
accountId: `research:${runId}`,
|
||||
baseCurrency: 'USD',
|
||||
reserveOwnerId: 'reserve',
|
||||
ownerIds: [ownerId],
|
||||
initialCapital: initial,
|
||||
riskSession: riskSession(initialSession),
|
||||
},
|
||||
feeRate: settings.feeRate,
|
||||
maxOrderQuantity: settings.maxOrderQuantity,
|
||||
maxPositionQuantity: settings.maxPositionQuantity,
|
||||
maxSymbolExposure: settings.maxSymbolExposure,
|
||||
maxGrossExposure: settings.maxGrossExposure,
|
||||
maxDailyLoss: settings.maxDailyLoss,
|
||||
maxDrawdownAmount: settings.maxDrawdownAmount,
|
||||
maxMarkAgeMs: settings.maxMarkAgeMs,
|
||||
},
|
||||
owners: [{ ownerId, mode: 'Target' }],
|
||||
series: [{ ...execution, mode: 'Open' }],
|
||||
halfSpreadRate: settings.halfSpreadRate,
|
||||
slippageRate: settings.slippageRate,
|
||||
latencyMs: settings.latencyMs,
|
||||
},
|
||||
participation_rate: settings.participationRate,
|
||||
cadence: [{ owner_id: ownerId, series_ids: [execution.seriesId] }],
|
||||
allow_exploratory: false,
|
||||
risk_boundaries: calendar.sessions
|
||||
.filter(session => session.open > warmupStart && session.open <= tradeEnd)
|
||||
.map(riskSession),
|
||||
},
|
||||
analyticsPolicy: {
|
||||
version: 1,
|
||||
periodsPerYear: settings.periodsPerYear,
|
||||
annualRiskFreeRate: settings.annualRiskFreeRate,
|
||||
benchmark: null,
|
||||
},
|
||||
build: await readCanonicalBuildIdentity(),
|
||||
modelArtifacts: [],
|
||||
});
|
||||
}
|
||||
|
|
@ -105,7 +105,9 @@ const version = (row: QueryResultRow): StrategyVersionSummary => ({
|
|||
runnable: false,
|
||||
reason:
|
||||
row.origin === 'builtin'
|
||||
? 'Catalog versions require canonical workbench integration (R05) before execution.'
|
||||
? row.review_status === 'approved'
|
||||
? 'Configure a supported canonical dataset and explicit financial policy before execution.'
|
||||
: 'An operator must approve this built-in version before configuring execution.'
|
||||
: 'Candidate execution requires isolation (A02); publication and approval do not execute code.',
|
||||
});
|
||||
class ReceiptRace extends Error {}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue