333 lines
11 KiB
TypeScript
333 lines
11 KiB
TypeScript
/** Pure catalog contracts. Importing this module never constructs or executes a strategy. */
|
|
import { z } from 'zod';
|
|
import type {
|
|
StrategyParameterProperty,
|
|
StrategyParameterSchema,
|
|
StrategyParameterValue,
|
|
StrategyVersionPackage,
|
|
} from '@stock-bot/types';
|
|
import {
|
|
meanReversionStrategySelectionSchema,
|
|
smaStrategySelectionSchema,
|
|
} from './builtin-strategy';
|
|
import { candidatePackageExecutionSchema } from './candidate-execution';
|
|
import { maxStrategyPeriod } from './strategy-names';
|
|
|
|
export * from './builtin-strategy';
|
|
export * from './strategy-names';
|
|
|
|
/** PostgreSQL JSONB and retained UTF-8 bytes must represent the exact same strings. */
|
|
export function assertStrategyJsonText(input: unknown): void {
|
|
if (typeof input === 'string') {
|
|
for (let i = 0; i < input.length; i++) {
|
|
const code = input.charCodeAt(i);
|
|
if (code === 0 || (code >= 0xdc00 && code <= 0xdfff)) {
|
|
throw new Error('Strategy text must be valid UTF-8 without NUL characters');
|
|
}
|
|
if (code >= 0xd800 && code <= 0xdbff) {
|
|
const next = input.charCodeAt(++i);
|
|
if (!(next >= 0xdc00 && next <= 0xdfff)) {
|
|
throw new Error('Strategy text must be valid UTF-8 without NUL characters');
|
|
}
|
|
}
|
|
}
|
|
} else if (Array.isArray(input)) {
|
|
input.forEach(assertStrategyJsonText);
|
|
} else if (input && typeof input === 'object') {
|
|
for (const [key, value] of Object.entries(input)) {
|
|
if (['__proto__', 'constructor', 'prototype'].includes(key)) {
|
|
throw new Error('Unsupported strategy metadata key');
|
|
}
|
|
assertStrategyJsonText(key);
|
|
assertStrategyJsonText(value);
|
|
}
|
|
}
|
|
}
|
|
|
|
const scalar = z.union([z.string(), z.number().finite(), z.boolean()]);
|
|
const propertySchema = z
|
|
.object({
|
|
type: z.enum(['integer', 'number', 'string', 'boolean']),
|
|
minimum: z.number().finite().optional(),
|
|
maximum: z.number().finite().optional(),
|
|
exclusiveMinimum: z.number().finite().optional(),
|
|
exclusiveMaximum: z.number().finite().optional(),
|
|
enum: z.array(scalar).nonempty().optional(),
|
|
default: scalar.optional(),
|
|
description: z.string().optional(),
|
|
})
|
|
.strict();
|
|
const parameterSchema = z
|
|
.object({
|
|
version: z.literal(1),
|
|
type: z.literal('object'),
|
|
additionalProperties: z.literal(false),
|
|
properties: z.record(propertySchema),
|
|
required: z.array(z.string()),
|
|
})
|
|
.strict();
|
|
const hash = z.string().regex(/^[a-f0-9]{64}$/);
|
|
const text = z.string().min(1);
|
|
const packageSchema = z
|
|
.object({
|
|
version: z.literal(1),
|
|
execution: candidatePackageExecutionSchema.optional(),
|
|
program: z
|
|
.object({
|
|
strategyId: text,
|
|
strategyVersion: text,
|
|
apiVersion: text,
|
|
checkpointVersion: text,
|
|
})
|
|
.strict(),
|
|
artifact: z
|
|
.object({
|
|
format: z.literal('esm-bundle/v1'),
|
|
entryExport: z.string().regex(/^[A-Za-z_$][\w$]*$/),
|
|
content: text,
|
|
sha256: hash,
|
|
})
|
|
.strict(),
|
|
dependencyLock: z
|
|
.object({ format: z.literal('bun-lock/v1'), content: text, sha256: hash })
|
|
.strict(),
|
|
parameterSchema,
|
|
source: z
|
|
.object({ revision: z.string().regex(/^[a-f0-9]{40,64}$/), dirty: z.boolean() })
|
|
.strict(),
|
|
build: z
|
|
.object({ tool: z.literal('bun'), version: text, target: z.literal('browser') })
|
|
.strict(),
|
|
})
|
|
.strict();
|
|
|
|
// Response contracts reuse the retained package shape without evaluating executable bytes.
|
|
export {
|
|
parameterSchema as strategyParameterSchema,
|
|
packageSchema as strategyVersionPackageSchema,
|
|
};
|
|
|
|
const period = (minimum: number): StrategyParameterProperty => ({
|
|
type: 'integer',
|
|
minimum,
|
|
maximum: maxStrategyPeriod,
|
|
});
|
|
export interface BuiltinCatalogDescriptor {
|
|
name: string;
|
|
description: string;
|
|
program: StrategyVersionPackage['program'];
|
|
entryExport: string;
|
|
parameterSchema: StrategyParameterSchema;
|
|
}
|
|
export const builtinCatalogDescriptors: BuiltinCatalogDescriptor[] = [
|
|
{
|
|
name: 'SMA crossover (canonical)',
|
|
description: 'Long-only reviewed crossover program; Rust enforces financial constraints.',
|
|
program: {
|
|
strategyId: 'sma_crossover',
|
|
strategyVersion: 'sma-crossover-long-only/v1',
|
|
apiVersion: 'canonical-ts/v1',
|
|
checkpointVersion: 'sma-state/v1',
|
|
},
|
|
entryExport: 'createSmaStrategy',
|
|
parameterSchema: {
|
|
version: 1,
|
|
type: 'object',
|
|
additionalProperties: false,
|
|
properties: {
|
|
fastPeriod: { ...period(1), default: 5 },
|
|
slowPeriod: { ...period(2), default: 15 },
|
|
},
|
|
required: [],
|
|
},
|
|
},
|
|
{
|
|
name: 'Mean reversion with volatility regime (canonical)',
|
|
description: 'Long-only fixed signal composition; no claim of validated profitability.',
|
|
program: {
|
|
strategyId: 'mean_reversion',
|
|
strategyVersion: 'mean-reversion-regime-long-only/v1',
|
|
apiVersion: 'canonical-ts/v1',
|
|
checkpointVersion: 'mean-reversion-state/v1',
|
|
},
|
|
entryExport: 'createMeanReversionStrategy',
|
|
parameterSchema: {
|
|
version: 1,
|
|
type: 'object',
|
|
additionalProperties: false,
|
|
properties: {
|
|
lookbackPeriod: period(2),
|
|
trendPeriod: period(3),
|
|
momentumPeriod: period(1),
|
|
volatilityPeriod: period(2),
|
|
entryZScore: { type: 'number', exclusiveMinimum: 0 },
|
|
exitZScore: { type: 'number', minimum: 0 },
|
|
minTrendReturn: { type: 'number', exclusiveMinimum: -1 },
|
|
minMomentumReturn: { type: 'number', exclusiveMinimum: -1 },
|
|
maxVolatility: { type: 'number', minimum: 0 },
|
|
minNotionalVolume: { type: 'string' },
|
|
regimeFilter: { type: 'string', enum: ['volatility', 'none'] },
|
|
},
|
|
required: [
|
|
'lookbackPeriod',
|
|
'trendPeriod',
|
|
'momentumPeriod',
|
|
'volatilityPeriod',
|
|
'entryZScore',
|
|
'exitZScore',
|
|
'minTrendReturn',
|
|
'minMomentumReturn',
|
|
'maxVolatility',
|
|
'minNotionalVolume',
|
|
'regimeFilter',
|
|
],
|
|
},
|
|
},
|
|
];
|
|
|
|
/** Stable JSON object-key order; array order and all executable content remain significant. */
|
|
export function canonicalStrategyJson(value: unknown): string {
|
|
if (Array.isArray(value)) {
|
|
return `[${value.map(canonicalStrategyJson).join(',')}]`;
|
|
}
|
|
if (value && typeof value === 'object') {
|
|
return `{${Object.keys(value)
|
|
.sort()
|
|
.map(
|
|
key =>
|
|
`${JSON.stringify(key)}:${canonicalStrategyJson((value as Record<string, unknown>)[key])}`
|
|
)
|
|
.join(',')}}`;
|
|
}
|
|
const result = JSON.stringify(value);
|
|
if (result === undefined) {
|
|
throw new Error('Strategy metadata must be JSON');
|
|
}
|
|
return result;
|
|
}
|
|
function checkValue(
|
|
name: string,
|
|
rule: StrategyParameterProperty,
|
|
value: unknown
|
|
): asserts value is StrategyParameterValue {
|
|
const numeric = rule.type === 'integer' || rule.type === 'number';
|
|
if (
|
|
(numeric
|
|
? typeof value !== 'number' ||
|
|
!Number.isFinite(value) ||
|
|
(rule.type === 'integer' && !Number.isInteger(value))
|
|
: typeof value !== rule.type) ||
|
|
(typeof value === 'number' &&
|
|
((rule.minimum !== undefined && value < rule.minimum) ||
|
|
(rule.maximum !== undefined && value > rule.maximum) ||
|
|
(rule.exclusiveMinimum !== undefined && value <= rule.exclusiveMinimum) ||
|
|
(rule.exclusiveMaximum !== undefined && value >= rule.exclusiveMaximum))) ||
|
|
(rule.enum && !rule.enum.includes(value as StrategyParameterValue))
|
|
) {
|
|
throw new Error(`Invalid parameter: ${name}`);
|
|
}
|
|
}
|
|
function checkSchema(schema: StrategyParameterSchema) {
|
|
const properties = schema.properties;
|
|
if (
|
|
new Set(schema.required).size !== schema.required.length ||
|
|
schema.required.some(key => !Object.hasOwn(properties, key))
|
|
) {
|
|
throw new Error('Invalid required parameter names');
|
|
}
|
|
for (const [name, rule] of Object.entries(properties)) {
|
|
if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(name) || ['constructor', 'prototype'].includes(name)) {
|
|
throw new Error('Invalid parameter name');
|
|
}
|
|
const numeric = rule.type === 'integer' || rule.type === 'number';
|
|
const bounds = [rule.minimum, rule.maximum, rule.exclusiveMinimum, rule.exclusiveMaximum];
|
|
if (!numeric && bounds.some(v => v !== undefined)) {
|
|
throw new Error('Only numeric parameters accept bounds');
|
|
}
|
|
const low = Math.max(rule.minimum ?? -Infinity, rule.exclusiveMinimum ?? -Infinity);
|
|
const high = Math.min(rule.maximum ?? Infinity, rule.exclusiveMaximum ?? Infinity);
|
|
if (
|
|
low > high ||
|
|
(low === high && (rule.exclusiveMinimum === low || rule.exclusiveMaximum === high))
|
|
) {
|
|
throw new Error('Invalid parameter bounds');
|
|
}
|
|
if (rule.enum) {
|
|
if (new Set(rule.enum).size !== rule.enum.length) {
|
|
throw new Error('Duplicate parameter enum value');
|
|
}
|
|
for (const value of rule.enum) {
|
|
checkValue(name, rule, value);
|
|
}
|
|
}
|
|
if (rule.default !== undefined) {
|
|
checkValue(name, rule, rule.default);
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Structural validation only. Storage must separately verify artifact/lock SHA256 bytes. */
|
|
export function parseStrategyVersionPackage(input: unknown): StrategyVersionPackage {
|
|
assertStrategyJsonText(input);
|
|
const parsed = packageSchema.parse(input);
|
|
checkSchema(parsed.parameterSchema);
|
|
const builtin = builtinCatalogDescriptors.find(
|
|
d =>
|
|
d.program.strategyId === parsed.program.strategyId &&
|
|
d.program.strategyVersion === parsed.program.strategyVersion
|
|
);
|
|
if (
|
|
builtin &&
|
|
(canonicalStrategyJson(parsed.program) !== canonicalStrategyJson(builtin.program) ||
|
|
parsed.artifact.entryExport !== builtin.entryExport ||
|
|
canonicalStrategyJson(parsed.parameterSchema) !==
|
|
canonicalStrategyJson(builtin.parameterSchema))
|
|
) {
|
|
throw new Error('A known built-in contract cannot be overridden by published metadata');
|
|
}
|
|
return parsed;
|
|
}
|
|
|
|
/** No schema-supplied code, regex, references or custom validators are executed. */
|
|
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');
|
|
}
|
|
const raw = input as Record<string, unknown>;
|
|
const properties = pkg.parameterSchema.properties;
|
|
for (const key of Object.keys(raw)) {
|
|
if (!Object.hasOwn(properties, key)) {
|
|
throw new Error(`Unknown parameter: ${key}`);
|
|
}
|
|
}
|
|
const result: Record<string, StrategyParameterValue> = {};
|
|
for (const [name, rule] of Object.entries(properties)) {
|
|
const value = Object.hasOwn(raw, name) ? raw[name] : rule.default;
|
|
if (value === undefined) {
|
|
if (pkg.parameterSchema.required.includes(name)) {
|
|
throw new Error(`Missing parameter: ${name}`);
|
|
}
|
|
continue;
|
|
}
|
|
checkValue(name, rule, value);
|
|
result[name] = value;
|
|
}
|
|
if (
|
|
pkg.program.strategyId === 'sma_crossover' &&
|
|
pkg.program.strategyVersion === 'sma-crossover-long-only/v1'
|
|
) {
|
|
return smaStrategySelectionSchema.shape.parameters.parse(result);
|
|
}
|
|
if (
|
|
pkg.program.strategyId === 'mean_reversion' &&
|
|
pkg.program.strategyVersion === 'mean-reversion-regime-long-only/v1'
|
|
) {
|
|
return meanReversionStrategySelectionSchema.shape.parameters.parse(result);
|
|
}
|
|
return result;
|
|
}
|