refactor(runtime): expose shared admission and artifact boundaries (CL26)

This commit is contained in:
Boki 2026-10-28 14:02:03 -04:00
parent 2165a2efa8
commit b4589d5af1
49 changed files with 1790 additions and 1565 deletions

View file

@ -92,12 +92,12 @@ export class NativeBacktestWorker {
retainedRequest &&
this.workerUrl &&
realpathSync(fileURLToPath(this.workerUrl)) !==
realpathSync(fileURLToPath(canonicalWorkerUrl))
realpathSync(fileURLToPath(canonicalWorkerUrl()))
) {
throw new Error('Retained strategy execution requires the canonical bundled worker');
}
const workerUrl = retainedRequest
? canonicalWorkerUrl
? canonicalWorkerUrl()
: (this.workerUrl ??
new URL(
import.meta.url.endsWith('.ts') ? './native-worker.ts' : './native-worker.js',

View file

@ -1,18 +1,21 @@
/** Trusted launcher. Candidate code is never imported in this process. */
import { execFile, spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
import { createHash } from 'node:crypto';
import { mkdtemp, readFile, realpath, rm } from 'node:fs/promises';
import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
import { join } from 'node:path';
import {
candidateExecutionSchema,
candidateSandboxLimits,
type CandidateExecution,
} from '@stock-bot/stock-config/candidate-execution';
import type { CanonicalRunRequest } from '@stock-bot/stock-config/canonical-research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import {
daemon,
docker,
dockerRead,
environment,
readCandidateExecution,
verifyCandidateExecution,
} from '@stock-bot/trading-runtime/candidate-environment';
import { parseFinancialStrategyDecision } from '@stock-bot/types';
import type { ReplaySubmissionOutcome } from '../contracts/native-replay';
import {
@ -28,100 +31,13 @@ import type {
ReplayIdentity,
} from './native-replay';
const runFile = promisify(execFile);
const docker = '/usr/bin/docker';
const daemon = ['--host', 'unix:///var/run/docker.sock'];
const environment = (config: string) => ({ PATH: '/usr/bin:/bin', DOCKER_CONFIG: config });
const root = resolve(dirname(fileURLToPath(import.meta.resolve('@stock-bot/engine'))), '../../..');
export const candidateDescriptorPath = resolve(
root,
'apps/stock/orchestrator/dist/candidate-sandbox.json'
);
export class CandidateSandboxUnavailable extends Error {
readonly code = 'candidate_sandbox_unavailable';
}
export {
candidateDescriptorPath,
CandidateSandboxUnavailable,
readCandidateExecution,
verifyCandidateExecution,
} from '@stock-bot/trading-runtime/candidate-environment';
async function dockerRead(args: string[]) {
const config = await mkdtemp(join(tmpdir(), 'stock-bot-docker-client-'));
try {
return (
await runFile(docker, [...daemon, ...args], {
env: environment(config),
timeout: 10000,
maxBuffer: 65536,
})
).stdout.trim();
} finally {
await rm(config, { recursive: true, force: true });
}
}
export async function readCandidateExecution(): Promise<CandidateExecution> {
try {
if (process.platform !== 'linux' || process.arch !== 'x64') {
throw new Error('Unsupported candidate platform');
}
const execution = candidateExecutionSchema.parse(
JSON.parse(await readFile(candidateDescriptorPath, 'utf8'))
);
const files = [
resolve(root, 'apps/stock/orchestrator/dist/candidate-host.js'),
resolve(root, 'apps/stock/orchestrator/dist/candidate-guardian'),
await realpath(process.execPath),
];
const hashes = await Promise.all(
files.map(async path =>
createHash('sha256')
.update(await readFile(path))
.digest('hex')
)
);
if (
hashes[0] !== execution.profile.hostSha256 ||
hashes[1] !== execution.profile.guardianSha256 ||
hashes[2] !== execution.profile.bunSha256
) {
throw new Error('Candidate installed host/runtime bytes differ');
}
const info = JSON.parse(await dockerRead(['info', '--format', '{{json .}}'])) as Record<
string,
unknown
>;
if (
info.OSType !== 'linux' ||
info.CgroupVersion !== '2' ||
info.MemoryLimit !== true ||
info.SwapLimit !== true ||
info.CpuCfsQuota !== true ||
info.PidsLimit !== true ||
!Array.isArray(info.SecurityOptions) ||
!info.SecurityOptions.some(v => String(v).startsWith('name=seccomp')) ||
!info.SecurityOptions.some(v => String(v).startsWith('name=apparmor'))
) {
throw new Error('Candidate cgroup/seccomp/AppArmor isolation is unavailable');
}
if (
(await dockerRead(['image', 'inspect', execution.imageId, '--format', '{{.Id}}'])) !==
execution.imageId
) {
throw new Error('Candidate exact image is unavailable');
}
return execution;
} catch (cause) {
throw new CandidateSandboxUnavailable('The exact isolated candidate runtime is unavailable', {
cause,
});
}
}
export async function verifyCandidateExecution(expected: CandidateExecution): Promise<void> {
if (
canonicalStrategyJson(await readCandidateExecution()) !==
canonicalStrategyJson(candidateExecutionSchema.parse(expected))
) {
throw new CandidateSandboxUnavailable(
'The retained isolated candidate runtime is not installed'
);
}
}
export function validateCandidateContainerName(value: string): string {
if (!/^stock-bot-candidate-[0-9a-f-]{36}$/.test(value)) {
throw new Error('Invalid owned candidate container name');

View file

@ -1,79 +1,2 @@
/** Read-only build identity. This module never imports the native addon or strategy code. */
import { createHash } from 'node:crypto';
import { realpathSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { dirname, isAbsolute, relative, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import {
canonicalBuildIdentitySchema,
type CanonicalBuildIdentity,
} from '@stock-bot/stock-config/canonical-research';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
const engineWrapper = realpathSync(fileURLToPath(import.meta.resolve('@stock-bot/engine')));
const repositoryRoot = resolve(dirname(engineWrapper), '../../..');
const ownPath = relative(repositoryRoot, realpathSync(fileURLToPath(import.meta.url)));
if (isAbsolute(ownPath) || ownPath === '..' || ownPath.startsWith('../')) {
throw new Error('Canonical engine resolves outside this checkout');
}
if (engineWrapper !== resolve(repositoryRoot, 'apps/stock/engine/index.mjs')) {
throw new Error('Unsupported canonical engine wrapper location');
}
export const canonicalWorkerUrl = pathToFileURL(
resolve(repositoryRoot, 'apps/stock/orchestrator/dist/native-worker.js')
);
async function hashLocalFile(path: string): Promise<string> {
if (realpathSync(path) !== path) {
throw new Error('Canonical build artifacts must belong to this checkout');
}
return createHash('sha256')
.update(await readFile(path))
.digest('hex');
}
/** Capture all executable worker/native bytes and the runtime that interprets them. */
export async function readCanonicalBuildIdentity(): Promise<CanonicalBuildIdentity> {
if (typeof Bun === 'undefined') {
throw new Error('Canonical research requires the Bun runtime');
}
const [workerSha256, engineWrapperSha256, engineBinarySha256, dependencyLockSha256] =
await Promise.all([
hashLocalFile(fileURLToPath(canonicalWorkerUrl)),
hashLocalFile(engineWrapper),
hashLocalFile(resolve(repositoryRoot, 'apps/stock/engine/dist/engine.node')),
hashLocalFile(resolve(repositoryRoot, 'bun.lock')),
]);
return canonicalBuildIdentitySchema.parse({
version: 1,
workerSha256,
engineWrapperSha256,
engineBinarySha256,
dependencyLockSha256,
runtime: 'bun',
runtimeVersion: Bun.version,
platform: process.platform,
arch: process.arch,
});
}
/** The running child supplies its own module URL, never a URL from the request. */
export async function verifyCanonicalWorkerBuild(
expected: CanonicalBuildIdentity,
actualWorkerUrl: string
): Promise<CanonicalBuildIdentity> {
if (
realpathSync(fileURLToPath(actualWorkerUrl)) !== realpathSync(fileURLToPath(canonicalWorkerUrl))
) {
throw new Error('Canonical research requires the bundled worker from this checkout');
}
const actual = await readCanonicalBuildIdentity();
if (
canonicalStrategyJson(actual) !==
canonicalStrategyJson(canonicalBuildIdentitySchema.parse(expected))
) {
throw new Error('Canonical worker/native/runtime build identity mismatch');
}
return actual;
}
/** Shared read-only artifact inspection. */
export * from '@stock-bot/trading-runtime/canonical-build';

View file

@ -1,287 +1,2 @@
/** Trusted durable-host wire boundary. Native checkpoints are opaque custody,
* not a TypeScript accounting implementation or a strategy mutation API. */
import { z } from 'zod';
import {
parseFinancialDecimal,
parseFinancialEffects,
parseFinancialStrategyDecision,
} from '@stock-bot/types';
import {
nativeFinancialViewSchema,
nativeManagedOrderSchema,
nativeMatchingOutcomeSchema,
replayConfigSchema,
} from './native-replay';
const id = z
.string()
.min(1)
.refine(value =>
[...value].every(char => char.charCodeAt(0) >= 32 && char.charCodeAt(0) !== 127)
);
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
const time = z.number().int().min(-Number.MAX_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER);
const decimal = z.string().transform(value => parseFinancialDecimal(value));
const nonnegative = decimal.refine(value => !value.startsWith('-'));
const positive = nonnegative.refine(value => value !== '0.00000000');
const identitySchema = z.object({ sessionId: id, accountId: id }).strict();
export type CanonicalExecutionIdentity = z.infer<typeof identitySchema>;
export const canonicalMatchingConfigSchema = replayConfigSchema.shape.matching.extend({
series: z.array(
replayConfigSchema.shape.matching.shape.series.element.extend({
mode: z.enum(['Open', 'Quote']),
})
),
});
export type CanonicalMatchingConfig = z.input<typeof canonicalMatchingConfigSchema>;
const eventKeySchema = z
.object({
at: time,
phase: z.enum(['Observation', 'Decision', 'Execution', 'SessionClose']),
instrumentId: id,
sourceSequence: counter,
})
.strict();
const venueSessionSchema = z.object({ sessionId: id, opensAt: time, closesAt: time }).strict();
const riskSessionSchema =
replayConfigSchema.shape.matching.shape.risk.shape.ledger.shape.riskSession;
export const matchingCommandSchema = z
.object({
commandId: id,
key: eventKeySchema,
body: z.discriminatedUnion('kind', [
z
.object({
kind: z.literal('submit'),
decisions: z.array(z.unknown().transform(value => parseFinancialStrategyDecision(value))),
})
.strict(),
z
.object({
kind: z.literal('execute'),
seriesId: id,
observation: z.discriminatedUnion('kind', [
z
.object({
kind: z.literal('open'),
opensAt: time,
price: positive,
capacity: nonnegative,
})
.strict(),
z
.object({
kind: z.literal('quote'),
observedAt: time,
bid: positive,
ask: positive,
bidSize: nonnegative,
askSize: nonnegative,
})
.strict(),
]),
})
.strict(),
z
.object({ kind: z.literal('mark'), seriesId: id, price: positive, observedAt: time })
.strict(),
z.object({ kind: z.literal('openSession'), session: venueSessionSchema }).strict(),
z.object({ kind: z.literal('closeSession'), sessionId: id }).strict(),
z.object({ kind: z.literal('riskSessionBoundary'), riskSession: riskSessionSchema }).strict(),
z.object({ kind: z.literal('finish') }).strict(),
]),
})
.strict();
export type CanonicalMatchingCommand = z.input<typeof matchingCommandSchema>;
/** Event ordering must agree with Rust, including UTF-8 instrument identity ties. */
export function compareEventKeys(
a: CanonicalMatchingCommand['key'],
b: CanonicalMatchingCommand['key']
): number {
const phases = { Observation: 0, Decision: 1, Execution: 2, SessionClose: 3 };
return (
a.at - b.at ||
phases[a.phase] - phases[b.phase] ||
Buffer.compare(Buffer.from(a.instrumentId), Buffer.from(b.instrumentId)) ||
a.sourceSequence - b.sourceSequence
);
}
/** Metadata and shapes only. Rust restores and validates all nested receipts,
* reservations, accounting and indexes before any transition. */
export const canonicalExecutionCheckpointSchema = z
.object({
version: z.literal(1),
config: canonicalMatchingConfigSchema,
risk: z.record(z.unknown()),
revision: counter,
status: nativeMatchingOutcomeSchema.shape.status,
cursor: eventKeySchema.nullable(),
orders: z.array(nativeManagedOrderSchema),
sessions: z.array(z.tuple([id, venueSessionSchema])),
receipts: z.array(z.record(z.unknown())),
})
.strict();
export type CanonicalExecutionCheckpoint = z.infer<typeof canonicalExecutionCheckpointSchema>;
export const financialTransactionRequestSchema = z.discriminatedUnion('kind', [
z
.object({
version: z.literal(1),
kind: z.literal('initialize'),
identity: identitySchema,
config: canonicalMatchingConfigSchema,
})
.strict(),
z
.object({
version: z.literal(1),
kind: z.literal('apply'),
identity: identitySchema,
checkpoint: canonicalExecutionCheckpointSchema,
command: matchingCommandSchema,
})
.strict(),
]);
export type FinancialTransactionRequest = z.input<typeof financialTransactionRequestSchema>;
const riskOutcomeSchema = z
.object({
replayed: z.boolean(),
revision: counter,
disposition: z.union([z.literal('Accepted'), nativeManagedOrderSchema.shape.status.options[1]]),
financial: z
.object({
replayed: z.boolean(),
effects: z.unknown().transform(value => parseFinancialEffects(value)),
})
.strict()
.nullable(),
remaining: z.record(z.unknown()).nullable(),
releasedOrder: id.nullable(),
resetBaseline: nonnegative.nullable(),
})
.strict();
const matchingEffectSchema = z.union([
z.object({ Order: nativeManagedOrderSchema }).strict(),
z
.object({
Risk: z.object({ command: z.record(z.unknown()), outcome: riskOutcomeSchema }).strict(),
})
.strict(),
z
.object({
Operator: z.object({ command: z.record(z.unknown()), outcome: riskOutcomeSchema }).strict(),
})
.strict(),
]);
export const financialTransactionResultSchema = z
.object({
version: z.literal(1),
identity: identitySchema,
checkpoint: canonicalExecutionCheckpointSchema,
view: nativeFinancialViewSchema,
outcome: nativeMatchingOutcomeSchema.nullable(),
journal: z.array(
z
.object({
index: counter,
effect: matchingEffectSchema,
viewAfter: nativeFinancialViewSchema,
})
.strict()
),
})
.strict();
export type FinancialTransactionResult = z.infer<typeof financialTransactionResultSchema>;
export type CanonicalFinancialView = z.infer<typeof nativeFinancialViewSchema>;
// JSON object key order is not semantically significant (including opaque commands).
function equalJson(left: unknown, right: unknown): boolean {
if (left === right) {
return true;
}
if (left === null || right === null || typeof left !== 'object' || typeof right !== 'object') {
return false;
}
if (Array.isArray(left) || Array.isArray(right)) {
return (
Array.isArray(left) &&
Array.isArray(right) &&
left.length === right.length &&
left.every((value, index) => equalJson(value, right[index]))
);
}
const a = left as Record<string, unknown>,
b = right as Record<string, unknown>;
return (
Object.keys(a).length === Object.keys(b).length &&
Object.keys(a).every(key => Object.hasOwn(b, key) && equalJson(a[key], b[key]))
);
}
export function parseFinancialTransactionResult(
input: string,
expectedIdentity: CanonicalExecutionIdentity
): FinancialTransactionResult {
const result = financialTransactionResultSchema.parse(JSON.parse(input));
const expected = identitySchema.parse(expectedIdentity),
ledger = result.checkpoint.config.risk.ledger;
if (
!equalJson(result.identity, expected) ||
ledger.sessionId !== expected.sessionId ||
ledger.accountId !== expected.accountId ||
result.view.admissionRevision !== result.checkpoint.revision
) {
throw new Error('Native financial transaction identity or revision mismatch');
}
const checkView = (view: CanonicalFinancialView) => {
if (
view.portfolio.sessionId !== expected.sessionId ||
view.portfolio.accountId !== expected.accountId ||
view.portfolio.baseCurrency !== ledger.baseCurrency ||
view.portfolio.reserveOwnerId !== ledger.reserveOwnerId
) {
throw new Error('Native financial transaction view identity mismatch');
}
};
checkView(result.view);
if (result.outcome === null) {
if (
result.checkpoint.revision !== 0 ||
result.checkpoint.status !== 'Running' ||
result.checkpoint.cursor !== null ||
result.checkpoint.orders.length !== 0 ||
result.checkpoint.sessions.length !== 0 ||
result.view.orders.length !== 0 ||
result.view.reservations.length !== 0 ||
result.journal.length !== 0 ||
result.checkpoint.receipts.length !== 0
) {
throw new Error('Invalid initialized financial transaction');
}
} else if (result.outcome.replayed) {
if (result.journal.length !== 0 || result.outcome.revision > result.checkpoint.revision) {
throw new Error('Replayed financial transaction cannot publish effects');
}
} else {
if (
result.outcome.revision !== result.checkpoint.revision ||
!equalJson(result.outcome.status, result.checkpoint.status) ||
result.journal.length !== result.outcome.effects.length
) {
throw new Error('Native financial transaction outcome mismatch');
}
for (const [index, row] of result.journal.entries()) {
checkView(row.viewAfter);
if (
row.index !== index ||
row.viewAfter.admissionRevision !== result.checkpoint.revision - 1 ||
!equalJson(row.effect, matchingEffectSchema.parse(result.outcome.effects[index]))
) {
throw new Error('Native financial transaction journal mismatch');
}
}
}
return result;
}
/** Shared financial wire contract. */
export * from '@stock-bot/stock-config/canonical-execution';

View file

@ -1,119 +1,2 @@
/** Explicit trusted producer boundary. No legacy timestamp repair or broker capabilities. */
import { z } from 'zod';
import {
deployedPaperConfigurationSchema,
paperPolicySchema,
} from '@stock-bot/stock-config/paper-deployments';
import { parseFinancialDecimal } from '@stock-bot/types';
import { builtinStrategySelectionSchema } from './builtin-strategy';
import { canonicalMatchingConfigSchema, matchingCommandSchema } from './canonical-execution';
import { stepSchema } from './native-replay';
const id = matchingCommandSchema.shape.key.shape.instrumentId;
const time = matchingCommandSchema.shape.key.shape.at;
const counter = matchingCommandSchema.shape.key.shape.sourceSequence;
const decimal = z.string().transform(value => parseFinancialDecimal(value));
export { paperPolicySchema } from '@stock-bot/stock-config/paper-deployments';
const legacyPaperConfigurationSchema = z
.object({
version: z.literal(1),
matching: canonicalMatchingConfigSchema,
strategies: z.array(builtinStrategySelectionSchema).min(1),
policy: paperPolicySchema,
})
.strict();
export const paperConfigurationSchema = z.union([
legacyPaperConfigurationSchema,
deployedPaperConfigurationSchema,
]);
/** availableAt is the producer's atomic release time for the whole quote frame.
* Quotes retain their original physical timestamp and source sequence. The
* supplied completed bars were available by this release; quotes never synthesize bars. */
export const paperFrameSchema = z
.object({
version: z.literal(1),
sourceId: id,
connectionId: id,
id,
sequence: counter,
availableAt: time,
quotes: z
.array(
z
.object({
instrumentId: id,
seriesId: id,
observedAt: time,
sourceSequence: counter,
bid: decimal,
ask: decimal,
bidSize: decimal,
askSize: decimal,
})
.strict()
)
.min(1),
observations: z.array(stepSchema.shape.observations.element),
})
.strict();
export const paperConnectionSchema = z.object({ sourceId: id, connectionId: id }).strict();
export const paperActivationSchema = z
.object({ recoverPending: z.boolean().default(false) })
.strict();
export const paperHaltSchema = z.object({ reason: z.string().trim().min(1) }).strict();
export type PaperConfigurationInput = z.input<typeof paperConfigurationSchema>;
export type PaperConfiguration = z.output<typeof paperConfigurationSchema>;
export type PaperPolicy = z.output<typeof paperPolicySchema>;
export type PaperFrameInput = z.input<typeof paperFrameSchema>;
export type PaperFrame = z.output<typeof paperFrameSchema>;
export type PaperConnection = z.infer<typeof paperConnectionSchema>;
export class PaperRuntimeError extends Error {
constructor(
readonly kind: 'invalid-input' | 'not-ready' | 'conflict',
message: string
) {
super(message);
this.name = 'PaperRuntimeError';
}
}
export interface PaperReadiness {
configured: boolean;
accountId: string | null;
sourceId: string | null;
active: boolean;
ready: boolean;
operatorHalted: boolean;
connected: boolean;
reasons: string[];
lastReceivedAt: number | null;
lastAvailableAt: number | null;
requiresHistoricalRecovery: boolean;
pendingInput: string | null;
pendingBatch: string | null;
pendingDecisionSequence: number | null;
nativeStatus: 'Running' | 'Complete' | { Failed: { diagnostic: string } } | null;
risk: { dailyHalted: boolean; drawdownHalted: boolean } | null;
}
export interface PaperRuntime {
initialize(configuration: PaperConfigurationInput): Promise<void>;
connect(connection: PaperConnection): Promise<PaperReadiness>;
ingest(frame: PaperFrameInput): Promise<{
duplicate: boolean;
disposition: 'health-only' | 'admitted';
readiness: PaperReadiness;
}>;
disconnect(connection: PaperConnection): Promise<PaperReadiness>;
activate(options: { recoverPending: boolean }): Promise<PaperReadiness>;
halt(reason: string): Promise<PaperReadiness>;
status(): Promise<PaperReadiness>;
shutdown(): Promise<void>;
}
/** Shared financial wire contract. */
export * from '@stock-bot/stock-config/paper-runtime';

View file

@ -1,10 +1,2 @@
import { setImmediate } from 'node:timers/promises';
export const PREPARATION_BATCH_SIZE = 2048;
/** Yield to cancellation, timeouts and lease heartbeats between bounded CPU batches. */
export async function preparationCheckpoint(signal?: AbortSignal): Promise<void> {
signal?.throwIfAborted();
await setImmediate();
signal?.throwIfAborted();
}
/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */
export * from '@stock-bot/trading-runtime/preparation';

View file

@ -1,23 +1,2 @@
import { validateDatasetV2 } from './historical-dataset-v2';
export interface RetainedDatasetStore {
query(text: string, values?: unknown[]): Promise<{ rows: Record<string, unknown>[] }>;
}
/** Content-addressed custody shared by explicit CLI import and web source preparation. */
export async function retainResearchDataset(database: RetainedDatasetStore, input: unknown) {
const dataset = validateDatasetV2(input);
await database.query(
'INSERT INTO backtest_datasets(hash,payload) VALUES($1,$2::jsonb) ON CONFLICT(hash) DO NOTHING',
[dataset.manifest.hash, JSON.stringify(dataset)]
);
const stored = (
await database.query('SELECT payload FROM backtest_datasets WHERE hash=$1', [
dataset.manifest.hash,
])
).rows[0];
if (!stored || validateDatasetV2(stored.payload).manifest.hash !== dataset.manifest.hash) {
throw new Error('Retained dataset content does not match the imported identity');
}
return dataset.manifest;
}
/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */
export * from '@stock-bot/trading-runtime/retained-dataset';

View file

@ -80,7 +80,7 @@ export class PaperDeploymentHost {
return this.status(id);
}
const { deployment, pkg } = await this.authorized(id);
const url = new URL(paperHostUrl);
const url = new URL(paperHostUrl());
url.searchParams.set('sha256', deployment.preview.host.hostSha256);
const module = (await import(url.href)) as {
createPromotedPaperRuntime: typeof createPromotedPaperRuntime;

View file

@ -8,11 +8,9 @@ import {
type CanonicalMatchingCommand,
} from '../contracts/canonical-execution';
import {
paperConfigurationSchema,
paperFrameSchema,
PaperRuntimeError,
type PaperConfiguration,
type PaperConfigurationInput,
type PaperFrame,
type PaperFrameInput,
} from '../contracts/paper-runtime';
@ -75,119 +73,7 @@ function activeSession(config: PaperConfiguration, instrumentId: string, at: num
return session;
}
export function validatePaperConfiguration(input: PaperConfigurationInput): PaperConfiguration {
const config = parseInput(paperConfigurationSchema, input);
const { matching, policy, strategies } = config;
if (!matching.series.length || matching.series.some(series => series.mode !== 'Quote')) {
invalid('Canonical paper feed supports Quote execution only');
}
unique(
matching.series.map(item => item.instrumentId),
'execution instrument'
);
unique(
matching.series.map(item => item.seriesId),
'execution series'
);
unique(
matching.owners.map(item => item.ownerId),
'owner'
);
unique(matching.risk.ledger.ownerIds, 'ledger owner');
unique(
strategies.map(item => item.ownerId),
'strategy owner'
);
unique(
policy.observations.map(item => item.seriesId),
'observation series'
);
unique(
policy.cadence.map(item => item.ownerId),
'cadence owner'
);
unique(
policy.calendars.map(item => item.instrumentId),
'calendar instrument'
);
const owners = matching.owners.map(item => item.ownerId).sort(compareText);
if (
matching.owners.some(item => item.mode !== 'Target') ||
!isDeepStrictEqual(owners, [...matching.risk.ledger.ownerIds].sort(compareText)) ||
!isDeepStrictEqual(owners, strategies.map(item => item.ownerId).sort(compareText)) ||
!isDeepStrictEqual(owners, policy.cadence.map(item => item.ownerId).sort(compareText))
) {
invalid('Paper built-ins must exactly match the target owner and cadence cohort');
}
const instruments = matching.series.map(item => item.instrumentId).sort(compareText);
if (
!isDeepStrictEqual(
instruments,
policy.calendars.map(item => item.instrumentId).sort(compareText)
)
) {
invalid('Paper calendars must exactly cover execution instruments');
}
for (const observation of policy.observations) {
if (!instruments.includes(observation.instrumentId)) {
invalid('Paper observation references an unknown instrument');
}
}
for (const cadence of policy.cadence) {
unique(cadence.seriesIds, 'cadence series');
if (cadence.seriesIds.some(id => !policy.observations.some(item => item.seriesId === id))) {
invalid('Paper cadence references an unknown observation series');
}
cadence.seriesIds.sort(compareText);
}
for (const strategy of strategies) {
const series = policy.observations.find(item => item.seriesId === strategy.seriesId);
if (
series?.instrumentId !== strategy.instrumentId ||
!policy.cadence
.find(item => item.ownerId === strategy.ownerId)
?.seriesIds.includes(strategy.seriesId)
) {
invalid('Paper strategy requires its bound instrument/observation series in its cadence');
}
}
const initial = matching.risk.ledger.riskSession;
for (const calendar of policy.calendars) {
unique(
calendar.sessions.map(item => item.sessionId),
'venue session'
);
calendar.sessions.sort((a, b) => a.opensAt - b.opensAt);
let previousClose = initial.startsAt;
for (const session of calendar.sessions) {
if (session.opensAt < previousClose || session.opensAt >= session.closesAt) {
invalid('Paper venue sessions overlap, are invalid, or precede the initial risk clock');
}
previousClose = session.closesAt;
}
}
unique([initial.sessionId, ...policy.riskBoundaries.map(item => item.sessionId)], 'risk session');
policy.riskBoundaries.sort((a, b) => a.startsAt - b.startsAt);
let previousRisk = initial.startsAt;
for (const boundary of policy.riskBoundaries) {
if (
boundary.calendarId !== initial.calendarId ||
boundary.calendarRevision !== initial.calendarRevision ||
boundary.startsAt <= previousRisk
) {
invalid('Paper risk boundaries must advance the declared account calendar revision');
}
previousRisk = boundary.startsAt;
}
matching.owners.sort((a, b) => compareText(a.ownerId, b.ownerId));
matching.series.sort((a, b) => compareText(a.instrumentId, b.instrumentId));
matching.risk.ledger.ownerIds.sort(compareText);
strategies.sort((a, b) => compareText(a.ownerId, b.ownerId));
policy.observations.sort((a, b) => compareText(a.seriesId, b.seriesId));
policy.cadence.sort((a, b) => compareText(a.ownerId, b.ownerId));
policy.calendars.sort((a, b) => compareText(a.instrumentId, b.instrumentId));
return config;
}
export { validatePaperConfiguration } from '@stock-bot/trading-runtime/paper-configuration';
export function validatePaperFrame(
config: PaperConfiguration,

View file

@ -1,190 +1,2 @@
/** Read-only promotion custody. This module cannot import or execute strategy code. */
import { createHash } from 'node:crypto';
import type { QueryResultRow } from 'pg';
import {
paperDeploymentSchema,
type PaperDeployment,
type PaperPromotionPreview,
} from '@stock-bot/stock-config/paper-deployments';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
import { verifyRetainedProgramPackage } from '../strategies/retained-program';
export interface PaperDeploymentDatabase {
query(text: string, values?: unknown[]): Promise<{ rows: QueryResultRow[] }>;
}
export class PaperDeploymentError extends Error {
constructor(
readonly status: 400 | 403 | 404 | 409 | 422 | 503,
message: string
) {
super(message);
}
}
export const paperHash = (value: unknown) =>
createHash('sha256').update(canonicalStrategyJson(value)).digest('hex');
export function paperPreviewHash(
preview: Omit<PaperPromotionPreview, 'previewHash'> | PaperPromotionPreview
) {
const { previewHash: _ignored, ...body } = preview as PaperPromotionPreview;
return paperHash(body);
}
export function retainedPaperDeployment(raw: unknown): PaperDeployment {
const value = paperDeploymentSchema.parse(raw);
const { promotionHash, ...body } = value;
if (
paperHash(body) !== promotionHash ||
paperPreviewHash(value.preview) !== value.preview.previewHash
) {
throw new Error('Retained paper promotion identity mismatch');
}
return value;
}
export async function readPaperDeployment(
database: PaperDeploymentDatabase,
id: string
): Promise<PaperDeployment> {
const row = (await database.query('SELECT * FROM paper_deployments WHERE id=$1', [id])).rows[0];
if (!row) {
throw new PaperDeploymentError(404, 'Paper deployment not found');
}
const value = retainedPaperDeployment(row.document);
if (
value.id !== row.id ||
value.preview.configuration.matching.risk.ledger.accountId !== row.account_id ||
value.preview.strategy.versionId !== row.strategy_version_id ||
value.promotionHash !== row.promotion_hash
) {
throw new Error('Retained paper deployment row identity mismatch');
}
return value;
}
/** Admission and activation require a current operator approval. Historical GET stays available. */
export async function authorizedPaperPackage(
database: PaperDeploymentDatabase,
deployment: PaperDeployment | Pick<PaperPromotionPreview, 'strategy'>,
lock = false
) {
const preview = 'preview' in deployment ? deployment.preview : deployment;
const version = (
await database.query(
`SELECT v.envelope,v.origin,s.archived_at FROM strategy_versions v JOIN strategies s ON s.id=v.strategy_id WHERE v.id=$1 AND s.id=$2${lock ? ' FOR UPDATE OF s' : ''}`,
[preview.strategy.versionId, preview.strategy.familyId]
)
).rows[0];
const review = (
await database.query(
'SELECT id,decision FROM strategy_review_events WHERE version_id=$1 ORDER BY ordinal DESC LIMIT 1',
[preview.strategy.versionId]
)
).rows[0];
if (!version || version.archived_at !== null || review?.decision !== 'approve') {
throw new PaperDeploymentError(
409,
'Paper deployment requires an active family and current operator approval'
);
}
const pkg = verifyRetainedProgramPackage(version.envelope);
if (
version.origin !== preview.strategy.origin ||
pkg.artifact.sha256 !== preview.strategy.artifactSha256 ||
pkg.dependencyLock.sha256 !== preview.strategy.dependencyLockSha256
) {
throw new Error('Paper promotion artifact no longer matches retained bytes');
}
return { pkg, reviewId: String(review.id) };
}
/** Host-side retained identity check, independent of the web API's full financial source reader. */
export async function verifyPaperEvidenceCustody(
database: PaperDeploymentDatabase,
deployment: PaperDeployment
) {
const { input, evidence } = deployment.preview,
source = input.outOfSample;
let report: Record<string, unknown> | undefined;
if (source.kind === 'chronological-report/v1') {
const row = (
await database.query('SELECT validation_report FROM research_experiments WHERE id=$1', [
source.validationId,
])
).rows[0];
report = row?.validation_report;
if ((report?.test as { runId?: string } | undefined)?.runId !== input.testRunId) {
throw new Error('Paper test membership changed');
}
} else if (source.kind === 'walk-forward-report/v1') {
const row = (
await database.query('SELECT report FROM research_walk_forwards WHERE id=$1', [
source.walkForwardId,
])
).rows[0];
report = row?.report;
if (
!(report?.segments as Array<{ test: { runId: string } }> | undefined)?.some(
segment => segment.test.runId === input.testRunId
)
) {
throw new Error('Paper walk-forward test membership changed');
}
} else {
throw new Error('Paper promotion requires sealed out-of-sample evidence');
}
if (!report) {
throw new Error('Paper source report is missing');
}
const { _receipt, reportHash, ...body } = report;
if (
!_receipt ||
paperHash(body) !== reportHash ||
reportHash !== source.reportHash ||
report.id !== source.reportId ||
report.previewHash !== source.previewHash
) {
throw new Error('Paper source report changed');
}
const cost = (
await database.query(
'SELECT preview,preview_hash,validation_phase FROM research_experiments WHERE id=$1',
[input.costExperimentId]
)
).rows[0];
if (
!cost ||
cost.validation_phase !== null ||
cost.preview?.version !== 'cost-sensitivity-preview/v1' ||
cost.preview_hash !== input.costPreviewHash ||
cost.preview?.previewHash !== input.costPreviewHash ||
cost.preview.candidates.length !== evidence.costs.length
) {
throw new Error('Paper cost source changed');
}
const rows = (
await database.query('SELECT id FROM runs WHERE experiment_id=$1 ORDER BY trial_index', [
input.costExperimentId,
])
).rows;
if (
canonicalStrategyJson(rows.map(row => row.id)) !==
canonicalStrategyJson(evidence.costs.map(item => item.runId))
) {
throw new Error('Paper cost membership changed');
}
for (const item of [evidence.test, ...evidence.costs]) {
const row = (
await database.query(
'SELECT r.status,r.request_snapshot,r.dataset_hash,br.canonical_result FROM runs r JOIN backtest_results br ON br.run_id=r.id WHERE r.id=$1',
[item.runId]
)
).rows[0];
if (
!row ||
row.status !== 'completed' ||
row.dataset_hash !== item.datasetHash ||
paperHash(row.canonical_result) !== item.resultHash ||
canonicalStrategyJson(row.canonical_result.request) !==
canonicalStrategyJson(row.request_snapshot)
) {
throw new Error('Paper retained result identity changed');
}
}
}
/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */
export * from '@stock-bot/trading-runtime/paper-deployment-custody';

View file

@ -1,76 +1,2 @@
/** Read-only build identity. This module never imports the native addon or strategy code. */
import { createHash } from 'node:crypto';
import { realpathSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { dirname, isAbsolute, relative, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import {
paperHostIdentitySchema,
type PaperHostIdentity,
} from '@stock-bot/stock-config/paper-deployments';
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
const engineWrapper = realpathSync(fileURLToPath(import.meta.resolve('@stock-bot/engine')));
const repositoryRoot = resolve(dirname(engineWrapper), '../../..');
const ownPath = relative(repositoryRoot, realpathSync(fileURLToPath(import.meta.url)));
if (isAbsolute(ownPath) || ownPath === '..' || ownPath.startsWith('../')) {
throw new Error('Paper engine resolves outside this checkout');
}
if (engineWrapper !== resolve(repositoryRoot, 'apps/stock/engine/index.mjs')) {
throw new Error('Unsupported canonical engine wrapper location');
}
export const paperHostUrl = pathToFileURL(
resolve(repositoryRoot, 'apps/stock/orchestrator/dist/paper-host.js')
);
async function hashLocalFile(path: string): Promise<string> {
if (realpathSync(path) !== path) {
throw new Error('Paper build artifacts must belong to this checkout');
}
return createHash('sha256')
.update(await readFile(path))
.digest('hex');
}
/** Capture all executable worker/native bytes and the runtime that interprets them. */
export async function readPaperHostIdentity(): Promise<PaperHostIdentity> {
if (typeof Bun === 'undefined') {
throw new Error('Paper deployment requires the Bun runtime');
}
const [hostSha256, engineWrapperSha256, engineBinarySha256, dependencyLockSha256] =
await Promise.all([
hashLocalFile(fileURLToPath(paperHostUrl)),
hashLocalFile(engineWrapper),
hashLocalFile(resolve(repositoryRoot, 'apps/stock/engine/dist/engine.node')),
hashLocalFile(resolve(repositoryRoot, 'bun.lock')),
]);
return paperHostIdentitySchema.parse({
version: 'paper-host/v1',
hostSha256,
engineWrapperSha256,
engineBinarySha256,
dependencyLockSha256,
runtime: 'bun',
runtimeVersion: Bun.version,
platform: process.platform,
arch: process.arch,
});
}
/** The running child supplies its own module URL, never a URL from the request. */
export async function verifyPaperHostBuild(
expected: PaperHostIdentity,
actualHostUrl: string
): Promise<PaperHostIdentity> {
if (realpathSync(fileURLToPath(actualHostUrl)) !== realpathSync(fileURLToPath(paperHostUrl))) {
throw new Error('Paper deployment requires the bundled paper host from this checkout');
}
const actual = await readPaperHostIdentity();
if (
canonicalStrategyJson(actual) !== canonicalStrategyJson(paperHostIdentitySchema.parse(expected))
) {
throw new Error('Paper host/native/runtime build identity mismatch');
}
return actual;
}
/** Shared read-only artifact inspection. */
export * from '@stock-bot/trading-runtime/paper-host-identity';

View file

@ -1,23 +1,2 @@
import { getCredentialHttpPrincipal } from '@stock-bot/di';
import { PaperDeploymentError } from './paper-deployment-custody';
/** Defense in depth for both public services, including bearer requests carrying browser Origin. */
export function requirePaperOperator(request: Request, origins: readonly string[]) {
if (getCredentialHttpPrincipal(request) !== 'operator') {
throw new PaperDeploymentError(
403,
'Credential-backed human operator required for paper commands'
);
}
const origin = request.headers.get('origin');
if (origin && (!origins.length || !origins.includes(origin))) {
throw new PaperDeploymentError(
403,
'Paper commands require an explicitly configured trusted Origin'
);
}
}
export const paperAllowedOrigins = () =>
process.env.STOCK_BOT_ALLOWED_ORIGINS?.split(',')
.map(v => v.trim())
.filter(Boolean) ?? [];
/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */
export * from '@stock-bot/trading-runtime/paper-operator';

View file

@ -1,490 +1,2 @@
import type { Logger, MongoDBClient, QuestDBClient } from '@stock-bot/services';
import { parseInstrumentId, type HistoricalDataPolicy } from '@stock-bot/types';
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from '../data/preparation';
export interface HistoricalBar {
symbol: string;
timestamp: Date;
open: number;
high: number;
low: number;
close: number;
volume: number;
vwap?: number;
interpolated?: boolean;
source?: 'eod' | 'questdb' | 'synthetic';
adjustedClose?: number;
}
export type HistoricalStorageProvider = 'questdb' | 'eod';
export type HistoricalStorageErrorCode =
| 'unsupported-provider'
| 'unsupported-interval'
| 'provider-unavailable'
| 'missing-range';
/** Storage routing failures are distinct from invalid records and transport failures. */
export class HistoricalStorageError extends Error {
constructor(
readonly code: HistoricalStorageErrorCode,
message: string,
readonly provider?: HistoricalStorageProvider | 'synthetic'
) {
super(message);
this.name = 'HistoricalStorageError';
}
}
const historicalIntervals = ['1m', '5m', '15m', '1h', '1d'] as const;
const eodIntradayCollections: Readonly<Record<string, string | undefined>> = {
'1m': 'eodIntraday1M',
'5m': 'eodIntraday5M',
'1h': 'eodIntraday1H',
};
/** Historical reads over borrowed adapters; ingestion and migrations own all writes. */
export class StorageService {
private readonly questdb: QuestDBClient | null;
private readonly mongodb: MongoDBClient | null;
constructor(
private readonly logger: Pick<Logger, 'info'>,
mongoClient: MongoDBClient | null | undefined,
questdbClient: QuestDBClient | null,
private readonly options: { allowSyntheticData?: boolean; syntheticSeed?: number } = {}
) {
this.mongodb = mongoClient ?? null;
this.questdb = questdbClient;
}
/** Adapter support and current connectivity, not evidence of stored range coverage. */
getHistoricalCapabilities() {
return [
{
provider: 'questdb' as const,
configured: this.questdb !== null,
connected: this.questdb?.connected ?? false,
intervals: [...historicalIntervals],
},
{
provider: 'eod' as const,
configured: this.mongodb !== null,
connected: this.mongodb?.connected ?? false,
intervals: ['1m', '5m', '1h', '1d'] as const,
},
];
}
private selectHistoricalProvider(
requested: HistoricalStorageProvider | 'auto'
): HistoricalStorageProvider | 'synthetic' {
if (!['auto', 'questdb', 'eod'].includes(requested)) {
throw new HistoricalStorageError('unsupported-provider', 'Unsupported historical provider');
}
if (requested === 'questdb' || (requested === 'auto' && this.questdb)) {
if (!this.questdb) {
throw new HistoricalStorageError(
'provider-unavailable',
'QuestDB historical storage is unavailable',
'questdb'
);
}
return 'questdb';
}
if (requested === 'eod' || (requested === 'auto' && this.mongodb)) {
if (!this.mongodb) {
throw new HistoricalStorageError(
'provider-unavailable',
'EOD historical storage is unavailable',
'eod'
);
}
return 'eod';
}
if (this.options.allowSyntheticData) {
return 'synthetic';
}
throw new HistoricalStorageError(
'provider-unavailable',
'No historical data store configured; synthetic data requires explicit opt-in'
);
}
/** One historical-data policy for native and TypeScript execution. */
async getHistoricalBars(
symbol: string,
startTime: Date,
endTime: Date,
interval = '1m',
policy: HistoricalDataPolicy = {
adjustment: 'raw',
timestamp: interval === '1d' ? 'utc-session-date' : 'utc-instant',
},
signal?: AbortSignal,
provider: HistoricalStorageProvider | 'auto' = 'auto'
): Promise<HistoricalBar[]> {
signal?.throwIfAborted();
parseInstrumentId(symbol);
if (
!Number.isFinite(startTime.getTime()) ||
!Number.isFinite(endTime.getTime()) ||
endTime <= startTime
) {
throw new Error('Invalid historical date range');
}
if (!(historicalIntervals as readonly string[]).includes(interval)) {
throw new HistoricalStorageError('unsupported-interval', 'Unsupported historical interval');
}
if (
(interval === '1d') !== (policy.timestamp === 'utc-session-date') ||
(interval === '1d' &&
(startTime.getTime() % 86400000 !== 0 || endTime.getTime() % 86400000 !== 0))
) {
throw new Error(
'Daily ranges must use UTC midnight session dates; intraday ranges use UTC instants'
);
}
const selectedProvider = this.selectHistoricalProvider(provider);
const rows = await this.readHistoricalBars(
symbol,
startTime,
endTime,
interval,
selectedProvider,
signal
);
signal?.throwIfAborted();
const bars: HistoricalBar[] = [];
let processed = 0;
for (const row of rows) {
if (row.symbol !== symbol) {
throw new Error(`Historical instrument identity mismatch for ${symbol}`);
}
if (typeof row.timestamp === 'string' && !/(Z|[+-]\d{2}:\d{2})$/.test(row.timestamp)) {
throw new Error('Historical instants require an explicit UTC offset');
}
const timestamp = new Date(row.timestamp);
const numeric = (value: unknown) =>
typeof value === 'number'
? value
: typeof value === 'string' && value.trim()
? Number(value)
: NaN;
let open = numeric(row.open),
high = numeric(row.high),
low = numeric(row.low),
close = numeric(row.close);
const volume = numeric(row.volume);
if (
!Number.isFinite(timestamp.getTime()) ||
![open, high, low, close, volume].every(Number.isFinite) ||
low <= 0 ||
high < Math.max(open, close) ||
low > Math.min(open, close) ||
volume < 0 ||
(interval === '1d' && timestamp.getTime() % 86400000 !== 0)
) {
throw new Error(`Invalid historical OHLCV data for ${symbol}`);
}
let vwap = row.vwap === null || row.vwap === undefined ? undefined : numeric(row.vwap);
if (policy.adjustment === 'provider-adjusted') {
const adjustedClose = numeric(row.adjustedClose);
if (!(adjustedClose > 0) || !Number.isFinite(adjustedClose)) {
throw new Error(`Provider-adjusted prices unavailable for ${symbol}`);
}
const factor = adjustedClose / close;
open *= factor;
high *= factor;
low *= factor;
close = adjustedClose;
if (vwap !== undefined) {
vwap *= factor;
}
}
if (
![open, high, low, close].every(value => Number.isFinite(value) && value > 0) ||
(vwap !== undefined && (!Number.isFinite(vwap) || vwap <= 0))
) {
throw new Error(`Invalid adjusted historical data for ${symbol}`);
}
if (timestamp >= startTime && timestamp < endTime) {
bars.push({ ...row, symbol, timestamp, open, high, low, close, volume, vwap });
}
if (++processed % PREPARATION_BATCH_SIZE === 0) {
await preparationCheckpoint(signal);
}
}
signal?.throwIfAborted();
bars.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
if (!bars.length) {
throw new HistoricalStorageError(
'missing-range',
`No historical data for ${symbol} in the requested range`,
selectedProvider
);
}
if (
bars.some(
(bar, index) =>
index > 0 && bars[index - 1]?.timestamp.getTime() === bar.timestamp.getTime()
)
) {
throw new Error(`Duplicate historical timestamps for ${symbol}`);
}
return bars;
}
private async readHistoricalBars(
symbol: string,
startTime: Date,
endTime: Date,
interval: string,
provider: HistoricalStorageProvider | 'synthetic',
signal?: AbortSignal
): Promise<HistoricalBar[]> {
// Select once, before reading: empty ranges/errors never switch providers.
if (provider === 'questdb' && this.questdb) {
const result = await this.questdb.query<HistoricalBar>(
`SELECT * FROM bars_${interval} WHERE symbol = $1 AND timestamp >= $2 AND timestamp < $3 ORDER BY timestamp`,
[symbol, startTime, endTime]
);
return result.rows.map(row => ({ ...row, source: 'questdb' }));
}
if (provider === 'eod' && this.mongodb) {
const identity = parseInstrumentId(symbol);
if (interval !== '1d') {
const collection = eodIntradayCollections[interval];
if (!collection) {
throw new HistoricalStorageError(
'unsupported-interval',
`EOD historical storage does not support ${interval}`,
'eod'
);
}
// fetchIntraday writes raw bar-start UTC Unix seconds, not local datetime labels.
// https://eodhd.com/financial-apis/intraday-historical-data-api
// This instant is not publication time; availability/calendar policy belongs to datasets.
const records = await this.mongodb.find<{
symbol: string;
exchange: string;
eodSearchCode: string;
timestamp: number;
open: number;
high: number;
low: number;
close: number;
volume: number;
}>(
collection,
{
eodSearchCode: identity.id,
timestamp: { $gte: startTime.getTime() / 1000, $lt: endTime.getTime() / 1000 },
},
{
sort: { timestamp: 1 },
projection: {
symbol: 1,
exchange: 1,
eodSearchCode: 1,
timestamp: 1,
open: 1,
high: 1,
low: 1,
close: 1,
volume: 1,
},
}
);
signal?.throwIfAborted();
const bars: HistoricalBar[] = [];
for (const record of records) {
if (
record.eodSearchCode !== identity.id ||
record.symbol !== identity.symbol ||
record.exchange !== identity.exchange
) {
throw new Error(`Historical instrument identity mismatch for ${symbol}`);
}
const milliseconds = record.timestamp * 1000;
if (
!Number.isSafeInteger(record.timestamp) ||
!Number.isSafeInteger(milliseconds) ||
!Number.isFinite(new Date(milliseconds).getTime())
) {
throw new Error(`Invalid historical Unix-seconds timestamp for ${symbol}`);
}
bars.push({
symbol,
timestamp: new Date(milliseconds),
open: record.open,
high: record.high,
low: record.low,
close: record.close,
volume: record.volume,
source: 'eod',
});
if (bars.length % PREPARATION_BATCH_SIZE === 0) {
await preparationCheckpoint(signal);
}
}
return bars;
}
const prices = await this.mongodb.find<{
symbol: string;
exchange: string;
eodSearchCode: string;
providerExchange?: string;
date: string;
open: number;
high: number;
low: number;
close: number;
volume: number;
adjustedClose?: number;
}>(
'eodPrices',
{
eodSearchCode: identity.id,
date: {
$gte: startTime.toISOString().slice(0, 10),
$lt: endTime.toISOString().slice(0, 10),
},
},
{
sort: { date: 1 },
projection: {
symbol: 1,
exchange: 1,
eodSearchCode: 1,
providerExchange: 1,
date: 1,
open: 1,
high: 1,
low: 1,
close: 1,
volume: 1,
adjustedClose: 1,
},
}
);
return prices.map(price => {
if (
price.eodSearchCode !== identity.id ||
price.symbol !== identity.symbol ||
(price.providerExchange !== undefined && price.providerExchange !== identity.exchange)
) {
throw new Error(`Historical instrument identity mismatch for ${symbol}`);
}
if (
!/^\d{4}-\d{2}-\d{2}$/.test(price.date) ||
!Number.isFinite(Date.parse(price.date)) ||
new Date(price.date).toISOString().slice(0, 10) !== price.date
) {
throw new Error(`Invalid historical session date for ${symbol}`);
}
return {
symbol,
timestamp: new Date(price.date),
open: price.open,
high: price.high,
low: price.low,
close: price.close,
volume: price.volume,
adjustedClose: price.adjustedClose,
source: 'eod' as const,
};
});
}
return this.generateMockBars(symbol, startTime, endTime, interval).map(bar => ({
...bar,
source: 'synthetic',
}));
}
private generateMockBars(
symbol: string,
startTime: Date,
endTime: Date,
interval: string
): HistoricalBar[] {
const bars = [];
const msPerInterval = this.getIntervalMilliseconds(interval);
let currentTime = new Date(startTime);
// Synthetic data is only generated with explicit opt-in and a stable seed.
const seed = this.options.syntheticSeed ?? 42;
const seedMultiplier = (seed % 1000) / 1000; // 0-1 based on milliseconds
// Starting price based on symbol with some randomness
let basePrice =
symbol === 'AAPL'
? 150 + (seedMultiplier * 20 - 10)
: symbol === 'MSFT'
? 300 + (seedMultiplier * 30 - 15)
: symbol === 'GOOGL'
? 120 + (seedMultiplier * 15 - 7.5)
: 100 + (seedMultiplier * 10 - 5);
// Random walk seed to make each run different
let walkSeed = seedMultiplier;
while (currentTime < endTime) {
// Use a pseudo-random based on walkSeed for deterministic but different results
walkSeed = (walkSeed * 9.73 + 0.27) % 1;
// Random walk with trend - increased volatility for testing
const trend = 0.0002; // Slight upward trend
const volatility = 0.01; // 1% volatility
const change = (walkSeed - 0.5 + trend) * volatility;
basePrice *= 1 + change;
// Generate OHLC data with more realistic volatility
const openSeed = (walkSeed * 7.13 + 0.31) % 1;
const highSeed = (walkSeed * 5.17 + 0.41) % 1;
const lowSeed = (walkSeed * 3.19 + 0.59) % 1;
const volumeSeed = (walkSeed * 11.23 + 0.67) % 1;
const open = basePrice * (1 + (openSeed - 0.5) * 0.005);
const close = basePrice;
const high = Math.max(open, close) * (1 + highSeed * 0.008);
const low = Math.min(open, close) * (1 - lowSeed * 0.008);
const volume = 1000000 + volumeSeed * 500000;
bars.push({
symbol,
timestamp: new Date(currentTime),
open,
high,
low,
close,
volume,
vwap: (high + low + close) / 3,
});
currentTime = new Date(currentTime.getTime() + msPerInterval);
}
this.logger.info(`Generated ${bars.length} mock bars for ${symbol} with seed ${seed}`);
return bars;
}
private getIntervalMilliseconds(interval: string): number {
switch (interval) {
case '1m':
return 60 * 1000;
case '5m':
return 5 * 60 * 1000;
case '15m':
return 15 * 60 * 1000;
case '1h':
return 60 * 60 * 1000;
case '1d':
return 24 * 60 * 60 * 1000;
default:
return 60 * 1000; // Default to 1 minute
}
}
}
/** Compatibility entrypoint; implementation is shared by the API and orchestrator. */
export * from '@stock-bot/trading-runtime/historical-storage';

View file

@ -1,32 +1,17 @@
/** Executable loader: call only in an OS-isolated candidate host or after a server-owned
* trusted builtin/paper-promotion authorization. Metadata never grants that authority. */
import { createHash } from 'node:crypto';
import {
retainedProgramSelectionSchema,
type RetainedProgramSelection,
} from '@stock-bot/stock-config/candidate-execution';
import { parseStrategyVersionPackage } from '@stock-bot/stock-config/strategy';
import { verifyRetainedProgramPackage } from '@stock-bot/trading-runtime/retained-package';
import type { StrategyVersionPackage } from '@stock-bot/types';
import type { StrategyProgram } from '../contracts/canonical-strategy';
import { freeze } from './strategy-decision';
export type { RetainedProgramSelection } from '@stock-bot/stock-config/candidate-execution';
/** Validates bytes and metadata only; never imports, compiles or calls candidate code. */
export function verifyRetainedProgramPackage(input: unknown): StrategyVersionPackage {
const pkg = parseStrategyVersionPackage(input);
const hash = (content: string) => createHash('sha256').update(content, 'utf8').digest('hex');
if (
hash(pkg.artifact.content) !== pkg.artifact.sha256 ||
hash(pkg.dependencyLock.content) !== pkg.dependencyLock.sha256
) {
throw new Error('Retained strategy artifact or dependency lock hash mismatch');
}
if (pkg.program.apiVersion !== 'canonical-ts/v1') {
throw new Error('Unsupported retained strategy API version');
}
return pkg;
}
export { verifyRetainedProgramPackage } from '@stock-bot/trading-runtime/retained-package';
export async function importRetainedProgram(
input: StrategyVersionPackage,