255 lines
8.8 KiB
TypeScript
255 lines
8.8 KiB
TypeScript
/** Pure durable research contracts. Importing these never loads a native engine or strategy. */
|
|
import { z } from 'zod';
|
|
import type {
|
|
BacktestRunResult,
|
|
CanonicalBacktestAnalytics,
|
|
financialDecimal,
|
|
FinancialDecimal,
|
|
HistoricalDatasetInputV2,
|
|
HistoricalDatasetManifestV2,
|
|
} from '@stock-bot/types';
|
|
import { parseFinancialDecimal } from '@stock-bot/types';
|
|
import { builtinStrategySelectionSchema } from './builtin-strategy';
|
|
import {
|
|
candidateExecutionSchema,
|
|
retainedProgramSelectionSchema,
|
|
type CandidateExecution,
|
|
} from './candidate-execution';
|
|
import {
|
|
parseReplayReportValue,
|
|
replayConfigSchema,
|
|
type ReplayReportResult,
|
|
} from './canonical-replay';
|
|
import { parseStrategyVersionPackage, validateStrategyParameters } from './strategy';
|
|
|
|
export type { financialDecimal };
|
|
|
|
const hash = z.string().regex(/^[a-f0-9]{64}$/);
|
|
const decimal: z.ZodType<FinancialDecimal, z.ZodTypeDef, string> = z
|
|
.string()
|
|
.transform((value, context) => {
|
|
try {
|
|
return parseFinancialDecimal(value);
|
|
} catch {
|
|
context.addIssue({
|
|
code: z.ZodIssueCode.custom,
|
|
message: 'Use a finite decimal with at most eight fractional places',
|
|
fatal: true,
|
|
});
|
|
return z.NEVER;
|
|
}
|
|
});
|
|
const nonnegative = decimal.refine(value => !value.startsWith('-'));
|
|
const positive = nonnegative.refine(value => value !== '0.00000000');
|
|
const rate = nonnegative.refine(value => BigInt(value.replace('.', '')) <= 100000000n);
|
|
const adversePriceRate = rate.refine(value => value !== '1.00000000');
|
|
const duration = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
|
|
|
/** Explicit canonical quantities/notionals; legacy percentage risk settings are not converted. */
|
|
export const canonicalResearchSettingsSchema = z
|
|
.object({
|
|
version: z.literal(1),
|
|
seed: z.number().int().min(0).max(0xffffffff),
|
|
ownerBudget: positive,
|
|
feeRate: rate,
|
|
halfSpreadRate: adversePriceRate,
|
|
slippageRate: adversePriceRate,
|
|
latencyMs: duration,
|
|
participationRate: rate.refine(value => value !== '0.00000000'),
|
|
maxOrderQuantity: positive,
|
|
maxPositionQuantity: positive,
|
|
maxSymbolExposure: positive,
|
|
maxGrossExposure: positive,
|
|
maxDailyLoss: nonnegative,
|
|
maxDrawdownAmount: nonnegative,
|
|
maxMarkAgeMs: duration,
|
|
periodsPerYear: z.number().finite().positive(),
|
|
annualRiskFreeRate: z.number().finite().nullable(),
|
|
})
|
|
.strict();
|
|
export type CanonicalResearchSettings = z.input<typeof canonicalResearchSettingsSchema>;
|
|
|
|
export const canonicalBuildIdentitySchema = z
|
|
.object({
|
|
version: z.literal(1),
|
|
workerSha256: hash,
|
|
engineWrapperSha256: hash,
|
|
engineBinarySha256: hash,
|
|
dependencyLockSha256: hash,
|
|
runtime: z.literal('bun'),
|
|
runtimeVersion: z.string().min(1),
|
|
platform: z.string().min(1),
|
|
arch: z.string().min(1),
|
|
})
|
|
.strict();
|
|
export type CanonicalBuildIdentity = z.infer<typeof canonicalBuildIdentitySchema>;
|
|
|
|
const metricsPolicy = z
|
|
.object({
|
|
version: z.literal(1),
|
|
periodsPerYear: z.number().finite().positive(),
|
|
annualRiskFreeRate: z.number().finite().nullable(),
|
|
benchmark: z.null(),
|
|
})
|
|
.strict();
|
|
const admitted = z
|
|
.object({
|
|
kind: z.literal('canonical-research/v1'),
|
|
runId: z.string().uuid(),
|
|
backtestId: z.string().uuid(),
|
|
name: z.string().min(1),
|
|
strategy: z.discriminatedUnion('origin', [
|
|
z
|
|
.object({
|
|
familyId: z.string().uuid(),
|
|
versionId: z.string().uuid(),
|
|
origin: z.literal('builtin'),
|
|
reviewId: z.string().uuid(),
|
|
package: z.unknown().transform(parseStrategyVersionPackage),
|
|
selection: builtinStrategySelectionSchema,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
familyId: z.string().uuid(),
|
|
versionId: z.string().uuid(),
|
|
origin: z.literal('candidate'),
|
|
baselineVersionId: z.string().uuid(),
|
|
reviewId: z.string().uuid().nullable(),
|
|
package: z.unknown().transform(parseStrategyVersionPackage),
|
|
selection: retainedProgramSelectionSchema,
|
|
execution: candidateExecutionSchema,
|
|
})
|
|
.strict(),
|
|
]),
|
|
datasetHash: hash,
|
|
policy: replayConfigSchema,
|
|
analyticsPolicy: metricsPolicy,
|
|
build: canonicalBuildIdentitySchema,
|
|
modelArtifacts: z.tuple([]),
|
|
})
|
|
.strict();
|
|
|
|
export const canonicalRunRequestSchema = admitted.superRefine((value, context) => {
|
|
const { strategy, policy } = value;
|
|
const selection = strategy.selection;
|
|
const ledger = policy.matching.risk.ledger;
|
|
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
|
|
const valid =
|
|
(strategy.origin === 'candidate'
|
|
? strategy.package.execution?.kind === 'isolated-candidate/v1'
|
|
: strategy.package.execution === undefined) &&
|
|
strategy.package.program.strategyId === selection.strategyId &&
|
|
strategy.package.program.strategyVersion === selection.strategyVersion &&
|
|
ledger.sessionId === value.runId &&
|
|
ledger.accountId === `research:${value.runId}` &&
|
|
ledger.baseCurrency === 'USD' &&
|
|
ledger.reserveOwnerId === 'reserve' &&
|
|
selection.ownerId === `strategy:${strategy.versionId}` &&
|
|
same(ledger.ownerIds, [selection.ownerId]) &&
|
|
same(policy.matching.owners, [{ ownerId: selection.ownerId, mode: 'Target' }]) &&
|
|
same(policy.matching.series, [
|
|
{ instrumentId: selection.instrumentId, seriesId: selection.seriesId, mode: 'Open' },
|
|
]) &&
|
|
same(policy.cadence, [{ owner_id: selection.ownerId, series_ids: [selection.seriesId] }]) &&
|
|
!policy.allow_exploratory &&
|
|
BigInt(selection.ownerBudget.replace('.', '')) <=
|
|
BigInt(ledger.initialCapital.replace('.', ''));
|
|
if (!valid) {
|
|
context.addIssue({
|
|
code: z.ZodIssueCode.custom,
|
|
message: 'Unsupported or inconsistent single-asset canonical request',
|
|
});
|
|
}
|
|
try {
|
|
validateStrategyParameters(strategy.package, selection.parameters);
|
|
} catch (error) {
|
|
context.addIssue({ code: z.ZodIssueCode.custom, message: String(error) });
|
|
}
|
|
});
|
|
export type CanonicalRunRequest = z.infer<typeof canonicalRunRequestSchema>;
|
|
/** Derive execution from the strict origin branch, never from an independent client flag. */
|
|
export function canonicalStrategyExecution(request: CanonicalRunRequest) {
|
|
return request.strategy.origin === 'candidate'
|
|
? ('typescript-isolated-candidate/v1' as const)
|
|
: ('typescript-retained-builtin/v1' as const);
|
|
}
|
|
|
|
export interface CanonicalRunResult {
|
|
kind: 'canonical-result/v1';
|
|
runId: string;
|
|
backtestId: string;
|
|
status: 'completed';
|
|
completedAt: string;
|
|
executionTime: number;
|
|
financialEngine: 'rust';
|
|
strategyExecution: 'typescript-retained-builtin/v1' | 'typescript-isolated-candidate/v1';
|
|
request: CanonicalRunRequest;
|
|
financial: ReplayReportResult;
|
|
analytics: CanonicalBacktestAnalytics;
|
|
}
|
|
export type ResearchRunResult = BacktestRunResult | CanonicalRunResult;
|
|
export function isCanonicalRunResult(value: ResearchRunResult): value is CanonicalRunResult {
|
|
return 'kind' in value && value.kind === 'canonical-result/v1';
|
|
}
|
|
export interface CanonicalRunCapability {
|
|
execution?: CandidateExecution;
|
|
available: boolean;
|
|
reason: string | null;
|
|
}
|
|
export interface CanonicalDatasetCatalogEntry {
|
|
hash: string;
|
|
createdAt: string;
|
|
manifest: HistoricalDatasetManifestV2 | null;
|
|
available: boolean;
|
|
reason: string | null;
|
|
}
|
|
|
|
/** Normalized source export; availability describes current workbench support. */
|
|
export interface CanonicalDatasetPreparation {
|
|
version: 'canonical-dataset-preparation/v1';
|
|
hash: string;
|
|
manifest: HistoricalDatasetManifestV2;
|
|
available: boolean;
|
|
reason: string | null;
|
|
}
|
|
|
|
/** One materialized storage read; retention must use this input without requerying. */
|
|
export interface CanonicalStoredSourcePreparation {
|
|
input: HistoricalDatasetInputV2;
|
|
preparation: CanonicalDatasetPreparation;
|
|
}
|
|
|
|
/** Validate the authoritative financial envelope without legacy metric conversion. */
|
|
export function parseCanonicalFinancialResult(input: unknown, request: CanonicalRunRequest) {
|
|
return parseReplayReportValue(
|
|
input,
|
|
{
|
|
version: 1,
|
|
sessionId: request.runId,
|
|
datasetHash: request.datasetHash,
|
|
},
|
|
request.policy
|
|
);
|
|
}
|
|
|
|
/** Reproduce retained inputs on the exact installed build; no historical binary provisioning. */
|
|
export interface CanonicalReproductionPreview {
|
|
originalRunId: string;
|
|
backtestId: string;
|
|
available: boolean;
|
|
reason: string | null;
|
|
request: CanonicalRunRequest | null;
|
|
/** Current approval required for a fresh admission; historical approval stays in request. */
|
|
currentReviewId: string | null;
|
|
}
|
|
export interface CanonicalReproductionComparison {
|
|
version: 'canonical-reproduction/v1';
|
|
runId: string;
|
|
backtestId: string;
|
|
originalRunId: string | null;
|
|
status: 'not-reproduction' | 'pending' | 'unavailable' | 'match' | 'mismatch';
|
|
reason: string | null;
|
|
originalHash: string | null;
|
|
reproducedHash: string | null;
|
|
}
|