refactor(runtime): expose shared admission and artifact boundaries (CL26)
This commit is contained in:
parent
2165a2efa8
commit
b4589d5af1
49 changed files with 1790 additions and 1565 deletions
66
libs/trading-runtime/src/artifacts.ts
Normal file
66
libs/trading-runtime/src/artifacts.ts
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
/** Shared server-only artifact custody. Resolve paths on demand, never while importing APIs. */
|
||||
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';
|
||||
|
||||
export function localBuildArtifacts() {
|
||||
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');
|
||||
}
|
||||
return { repositoryRoot, engineWrapper };
|
||||
}
|
||||
export function bundledHostUrl(name: 'native-worker' | 'paper-host'): URL {
|
||||
return pathToFileURL(
|
||||
resolve(localBuildArtifacts().repositoryRoot, `apps/stock/orchestrator/dist/${name}.js`)
|
||||
);
|
||||
}
|
||||
export async function hashLocalArtifact(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');
|
||||
}
|
||||
export async function readBuildArtifacts(name: 'native-worker' | 'paper-host') {
|
||||
if (typeof Bun === 'undefined') {
|
||||
throw new Error('Canonical execution requires the Bun runtime');
|
||||
}
|
||||
const { repositoryRoot, engineWrapper } = localBuildArtifacts();
|
||||
const [executableSha256, engineWrapperSha256, engineBinarySha256, dependencyLockSha256] =
|
||||
await Promise.all([
|
||||
hashLocalArtifact(fileURLToPath(bundledHostUrl(name))),
|
||||
hashLocalArtifact(engineWrapper),
|
||||
hashLocalArtifact(resolve(repositoryRoot, 'apps/stock/engine/dist/engine.node')),
|
||||
hashLocalArtifact(resolve(repositoryRoot, 'bun.lock')),
|
||||
]);
|
||||
return {
|
||||
executableSha256,
|
||||
engineWrapperSha256,
|
||||
engineBinarySha256,
|
||||
dependencyLockSha256,
|
||||
runtime: 'bun' as const,
|
||||
runtimeVersion: Bun.version,
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
};
|
||||
}
|
||||
export function verifyBundledHost(name: 'native-worker' | 'paper-host', actualUrl: string): void {
|
||||
if (
|
||||
realpathSync(fileURLToPath(actualUrl)) !== realpathSync(fileURLToPath(bundledHostUrl(name)))
|
||||
) {
|
||||
throw new Error(
|
||||
name === 'native-worker'
|
||||
? 'Canonical research requires the bundled worker from this checkout'
|
||||
: 'Paper deployment requires the bundled paper host from this checkout'
|
||||
);
|
||||
}
|
||||
}
|
||||
109
libs/trading-runtime/src/candidate-environment.ts
Normal file
109
libs/trading-runtime/src/candidate-environment.ts
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
/** Installed candidate metadata and isolation inspection. Never launches or imports a strategy. */
|
||||
import { execFile } from 'node:child_process';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdtemp, readFile, realpath, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import {
|
||||
candidateExecutionSchema,
|
||||
type CandidateExecution,
|
||||
} from '@stock-bot/stock-config/candidate-execution';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { localBuildArtifacts } from './artifacts';
|
||||
|
||||
const runFile = promisify(execFile);
|
||||
export const docker = '/usr/bin/docker';
|
||||
export const daemon = ['--host', 'unix:///var/run/docker.sock'];
|
||||
export const environment = (config: string) => ({ PATH: '/usr/bin:/bin', DOCKER_CONFIG: config });
|
||||
export const candidateDescriptorPath = () =>
|
||||
resolve(
|
||||
localBuildArtifacts().repositoryRoot,
|
||||
'apps/stock/orchestrator/dist/candidate-sandbox.json'
|
||||
);
|
||||
export class CandidateSandboxUnavailable extends Error {
|
||||
readonly code = 'candidate_sandbox_unavailable';
|
||||
}
|
||||
|
||||
export 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 root = localBuildArtifacts().repositoryRoot;
|
||||
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'
|
||||
);
|
||||
}
|
||||
}
|
||||
31
libs/trading-runtime/src/canonical-build.ts
Normal file
31
libs/trading-runtime/src/canonical-build.ts
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
/** Read-only identity; importing this module neither resolves nor loads executable artifacts. */
|
||||
import {
|
||||
canonicalBuildIdentitySchema,
|
||||
type CanonicalBuildIdentity,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { bundledHostUrl, readBuildArtifacts, verifyBundledHost } from './artifacts';
|
||||
|
||||
export const canonicalWorkerUrl = () => bundledHostUrl('native-worker');
|
||||
export async function readCanonicalBuildIdentity(): Promise<CanonicalBuildIdentity> {
|
||||
const { executableSha256, ...common } = await readBuildArtifacts('native-worker');
|
||||
return canonicalBuildIdentitySchema.parse({
|
||||
version: 1,
|
||||
workerSha256: executableSha256,
|
||||
...common,
|
||||
});
|
||||
}
|
||||
export async function verifyCanonicalWorkerBuild(
|
||||
expected: CanonicalBuildIdentity,
|
||||
actualUrl: string
|
||||
): Promise<CanonicalBuildIdentity> {
|
||||
verifyBundledHost('native-worker', actualUrl);
|
||||
const actual = await readCanonicalBuildIdentity();
|
||||
if (
|
||||
canonicalStrategyJson(actual) !==
|
||||
canonicalStrategyJson(canonicalBuildIdentitySchema.parse(expected))
|
||||
) {
|
||||
throw new Error('Canonical worker/native/runtime build identity mismatch');
|
||||
}
|
||||
return actual;
|
||||
}
|
||||
490
libs/trading-runtime/src/historical-storage.ts
Normal file
490
libs/trading-runtime/src/historical-storage.ts
Normal file
|
|
@ -0,0 +1,490 @@
|
|||
import type { Logger, MongoDBClient, QuestDBClient } from '@stock-bot/services';
|
||||
import { parseInstrumentId, type HistoricalDataPolicy } from '@stock-bot/types';
|
||||
import { PREPARATION_BATCH_SIZE, preparationCheckpoint } from './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
|
||||
}
|
||||
}
|
||||
}
|
||||
145
libs/trading-runtime/src/paper-configuration.ts
Normal file
145
libs/trading-runtime/src/paper-configuration.ts
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { ZodError } from 'zod';
|
||||
import {
|
||||
paperConfigurationSchema,
|
||||
PaperRuntimeError,
|
||||
type PaperConfiguration,
|
||||
type PaperConfigurationInput,
|
||||
} from '@stock-bot/stock-config/paper-runtime';
|
||||
|
||||
function invalid(message: string): never {
|
||||
throw new PaperRuntimeError('invalid-input', message);
|
||||
}
|
||||
// Decimal wire transforms throw ordinary Errors. Classify only this synchronous
|
||||
// input parsing boundary, never arbitrary storage/native errors, as bad input.
|
||||
function parseInput<T>(schema: { parse(input: unknown): T }, input: unknown): T {
|
||||
try {
|
||||
return schema.parse(input);
|
||||
} catch (error) {
|
||||
if (error instanceof ZodError) {
|
||||
throw error;
|
||||
}
|
||||
invalid(error instanceof Error ? error.message : 'Malformed paper input');
|
||||
}
|
||||
}
|
||||
// UTF-8 ordering agrees with Rust Id/String ordering, including supplementary characters.
|
||||
const compareText = (a: string, b: string) => Buffer.compare(Buffer.from(a), Buffer.from(b));
|
||||
function unique(values: readonly string[], label: string): void {
|
||||
if (new Set(values).size !== values.length) {
|
||||
invalid(`Duplicate paper ${label}`);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
190
libs/trading-runtime/src/paper-deployment-custody.ts
Normal file
190
libs/trading-runtime/src/paper-deployment-custody.ts
Normal file
|
|
@ -0,0 +1,190 @@
|
|||
/** 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 './retained-package';
|
||||
|
||||
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');
|
||||
}
|
||||
}
|
||||
}
|
||||
30
libs/trading-runtime/src/paper-host-identity.ts
Normal file
30
libs/trading-runtime/src/paper-host-identity.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
/** Read-only identity; importing this module neither resolves nor loads executable artifacts. */
|
||||
import {
|
||||
paperHostIdentitySchema,
|
||||
type PaperHostIdentity,
|
||||
} from '@stock-bot/stock-config/paper-deployments';
|
||||
import { canonicalStrategyJson } from '@stock-bot/stock-config/strategy';
|
||||
import { bundledHostUrl, readBuildArtifacts, verifyBundledHost } from './artifacts';
|
||||
|
||||
export const paperHostUrl = () => bundledHostUrl('paper-host');
|
||||
export async function readPaperHostIdentity(): Promise<PaperHostIdentity> {
|
||||
const { executableSha256, ...common } = await readBuildArtifacts('paper-host');
|
||||
return paperHostIdentitySchema.parse({
|
||||
version: 'paper-host/v1',
|
||||
hostSha256: executableSha256,
|
||||
...common,
|
||||
});
|
||||
}
|
||||
export async function verifyPaperHostBuild(
|
||||
expected: PaperHostIdentity,
|
||||
actualUrl: string
|
||||
): Promise<PaperHostIdentity> {
|
||||
verifyBundledHost('paper-host', actualUrl);
|
||||
const actual = await readPaperHostIdentity();
|
||||
if (
|
||||
canonicalStrategyJson(actual) !== canonicalStrategyJson(paperHostIdentitySchema.parse(expected))
|
||||
) {
|
||||
throw new Error('Paper host/native/runtime build identity mismatch');
|
||||
}
|
||||
return actual;
|
||||
}
|
||||
23
libs/trading-runtime/src/paper-operator.ts
Normal file
23
libs/trading-runtime/src/paper-operator.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
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) ?? [];
|
||||
10
libs/trading-runtime/src/preparation.ts
Normal file
10
libs/trading-runtime/src/preparation.ts
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
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();
|
||||
}
|
||||
23
libs/trading-runtime/src/retained-dataset.ts
Normal file
23
libs/trading-runtime/src/retained-dataset.ts
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import { validateDatasetV2 } from '@stock-bot/research/datasets';
|
||||
|
||||
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;
|
||||
}
|
||||
19
libs/trading-runtime/src/retained-package.ts
Normal file
19
libs/trading-runtime/src/retained-package.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { parseStrategyVersionPackage } from '@stock-bot/stock-config/strategy';
|
||||
import type { StrategyVersionPackage } from '@stock-bot/types';
|
||||
|
||||
/** 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;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue