feat(paper): gate canonical execution on durable feed readiness
This commit is contained in:
parent
c01e96e4dd
commit
75abae2cfc
24 changed files with 3720 additions and 66 deletions
|
|
@ -87,6 +87,8 @@ export const stockAppSchema = baseAppSchema.extend({
|
|||
port: z.number().default(3002),
|
||||
defaultMode: z.enum(['backtest', 'paper', 'live']).default('paper'),
|
||||
paperTradingCapital: z.number().default(100000),
|
||||
// Validated by the orchestrator's canonical contract before opening resources.
|
||||
canonicalPaper: z.record(z.unknown()).optional(),
|
||||
enableWebSocket: z.boolean().default(true),
|
||||
backtesting: z
|
||||
.object({
|
||||
|
|
|
|||
104
apps/stock/orchestrator/src/api/rest/paper.ts
Normal file
104
apps/stock/orchestrator/src/api/rest/paper.ts
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
import { Hono } from 'hono';
|
||||
import { z } from 'zod';
|
||||
import { getVerifiedHttpPrincipal } from '@stock-bot/di';
|
||||
import {
|
||||
paperActivationSchema,
|
||||
paperConnectionSchema,
|
||||
paperFrameSchema,
|
||||
paperHaltSchema,
|
||||
PaperRuntimeError,
|
||||
type PaperReadiness,
|
||||
} from '../../contracts/paper-runtime';
|
||||
import { ExecutionConflictError } from '../../execution/repository';
|
||||
import type { OrchestratorServices } from '../../types';
|
||||
|
||||
export function createPaperRoutes(services: OrchestratorServices): Hono {
|
||||
const app = new Hono();
|
||||
const runtime = () => {
|
||||
const value = services.custom?.CanonicalPaperRuntime;
|
||||
if (!value) {
|
||||
throw new PaperRuntimeError('not-ready', 'Canonical paper execution is not configured');
|
||||
}
|
||||
return value;
|
||||
};
|
||||
app.use('*', async (c, next) => {
|
||||
c.header('Cache-Control', 'no-store');
|
||||
if (c.req.method !== 'GET') {
|
||||
const principal = getVerifiedHttpPrincipal(c.req.raw);
|
||||
const feed = c.req.path.includes('/feed/');
|
||||
if (principal !== 'operator' && !(feed && principal === 'service')) {
|
||||
return c.json(
|
||||
{ error: feed ? 'Verified feed producer required' : 'Human operator required' },
|
||||
403
|
||||
);
|
||||
}
|
||||
}
|
||||
await next();
|
||||
return undefined;
|
||||
});
|
||||
app.onError((error, c) => {
|
||||
if (error instanceof z.ZodError || error instanceof SyntaxError) {
|
||||
return c.json({ error: 'Invalid paper request' }, 400);
|
||||
}
|
||||
if (error instanceof PaperRuntimeError) {
|
||||
return c.json(
|
||||
{ error: error.message, code: error.kind },
|
||||
error.kind === 'invalid-input' ? 400 : 409
|
||||
);
|
||||
}
|
||||
if (error instanceof ExecutionConflictError) {
|
||||
return c.json({ error: error.message, code: 'conflict' }, 409);
|
||||
}
|
||||
services.logger.error('Canonical paper request failed', { error });
|
||||
return c.json({ error: 'Canonical paper runtime unavailable' }, 503);
|
||||
});
|
||||
app.get('/readiness', async c => {
|
||||
if (!services.custom?.CanonicalPaperRuntime) {
|
||||
const unavailable: PaperReadiness = {
|
||||
configured: false,
|
||||
accountId: null,
|
||||
sourceId: null,
|
||||
active: false,
|
||||
ready: false,
|
||||
operatorHalted: true,
|
||||
connected: false,
|
||||
reasons: ['not-configured'],
|
||||
lastReceivedAt: null,
|
||||
lastAvailableAt: null,
|
||||
requiresHistoricalRecovery: false,
|
||||
pendingInput: null,
|
||||
pendingBatch: null,
|
||||
pendingDecisionSequence: null,
|
||||
nativeStatus: null,
|
||||
risk: null,
|
||||
};
|
||||
return c.json(unavailable);
|
||||
}
|
||||
return c.json(await runtime().status());
|
||||
});
|
||||
app.post('/activate', async c =>
|
||||
c.json(await runtime().activate(paperActivationSchema.parse(await c.req.json())))
|
||||
);
|
||||
app.post('/halt', async c =>
|
||||
c.json(await runtime().halt(paperHaltSchema.parse(await c.req.json()).reason))
|
||||
);
|
||||
app.post('/feed/connect', async c =>
|
||||
c.json(await runtime().connect(paperConnectionSchema.parse(await c.req.json())))
|
||||
);
|
||||
app.post('/feed/disconnect', async c =>
|
||||
c.json(await runtime().disconnect(paperConnectionSchema.parse(await c.req.json())))
|
||||
);
|
||||
app.post('/feed/frames', async c => {
|
||||
const input: unknown = await c.req.json();
|
||||
let frame;
|
||||
try {
|
||||
frame = paperFrameSchema.parse(input);
|
||||
} catch {
|
||||
// Decimal transforms can throw ordinary errors. Classify only input
|
||||
// parsing here; storage/native failures must still surface as unavailable.
|
||||
throw new PaperRuntimeError('invalid-input', 'Invalid paper frame');
|
||||
}
|
||||
return c.json(await runtime().ingest(frame));
|
||||
});
|
||||
return app;
|
||||
}
|
||||
|
|
@ -6,14 +6,19 @@ import type { BacktestExecutionEngine } from './backtest/execution-engine';
|
|||
import { PostgresBacktestRunRepository } from './backtest/PostgresBacktestRunRepository';
|
||||
import { UnavailableBacktestRunRepository } from './backtest/run-repository';
|
||||
import { RustBacktestAdapter } from './backtest/RustBacktestAdapter';
|
||||
import type { PaperConfigurationInput, PaperRuntime } from './contracts/paper-runtime';
|
||||
import { ModeManager } from './core/ModeManager';
|
||||
import { PostgresCanonicalExecutionRepository } from './execution/PostgresCanonicalExecutionRepository';
|
||||
import { BacktestHandler } from './handlers/backtest/backtest.handler';
|
||||
import { CanonicalPaperRuntime } from './paper/CanonicalPaperRuntime';
|
||||
import { validatePaperConfiguration } from './paper/feed';
|
||||
import { PaperTradingManager } from './paper/PaperTradingManager';
|
||||
import { AnalyticsService } from './services/AnalyticsService';
|
||||
import { ExecutionService } from './services/ExecutionService';
|
||||
import { MarketDataService } from './services/MarketDataService';
|
||||
import { StorageService } from './services/StorageService';
|
||||
import { createBuiltinStrategyRegistry } from './strategies/builtin-strategies';
|
||||
import { createBuiltinStrategy } from './strategies/canonical-sma';
|
||||
import { StrategyManager } from './strategies/StrategyManager';
|
||||
import type { StrategyRegistry } from './strategies/StrategyRegistry';
|
||||
import type { OrchestratorServices as IServiceContainer } from './types';
|
||||
|
|
@ -47,11 +52,20 @@ export async function registerOrchestratorServices(
|
|||
syntheticSeed?: number;
|
||||
nativeExecutionTimeoutMs?: number;
|
||||
strategyRegistry?: StrategyRegistry;
|
||||
canonicalPaper?: PaperConfigurationInput;
|
||||
paperTradingCapital?: number;
|
||||
} = {}
|
||||
): Promise<void> {
|
||||
const role = options.role === undefined ? 'paper' : options.role;
|
||||
const useRustEngine = options.useRustEngine === undefined ? true : options.useRustEngine;
|
||||
assertSupportedComposition(role, useRustEngine);
|
||||
if (options.canonicalPaper !== undefined && role !== 'paper') {
|
||||
throw new Error('Canonical paper configuration requires a paper composition');
|
||||
}
|
||||
const canonicalPaper =
|
||||
options.canonicalPaper === undefined
|
||||
? undefined
|
||||
: validatePaperConfiguration(options.canonicalPaper);
|
||||
const allowedMode = role === 'research-only' ? 'backtest' : 'paper';
|
||||
|
||||
// Create a service adapter that provides the expected interface
|
||||
|
|
@ -60,6 +74,24 @@ export async function registerOrchestratorServices(
|
|||
if (!services.custom) {
|
||||
Object.defineProperty(services, 'custom', { value: custom, enumerable: true });
|
||||
}
|
||||
if (
|
||||
custom.CanonicalPaperRuntime ||
|
||||
container.hasRegistration('CanonicalPaperRuntime') ||
|
||||
(canonicalPaper &&
|
||||
(
|
||||
[
|
||||
'ModeManager',
|
||||
'ExecutionService',
|
||||
'MarketDataService',
|
||||
'StrategyManager',
|
||||
'PaperTradingManager',
|
||||
'BacktestEngine',
|
||||
'BacktestRunner',
|
||||
] as const
|
||||
).some(key => custom[key] || container.hasRegistration(key)))
|
||||
) {
|
||||
throw new Error('Canonical paper requires a fresh runtime composition');
|
||||
}
|
||||
|
||||
// Create storage service first as it's needed by other services
|
||||
const storageService = new StorageService(
|
||||
|
|
@ -70,6 +102,67 @@ export async function registerOrchestratorServices(
|
|||
options
|
||||
);
|
||||
|
||||
if (canonicalPaper) {
|
||||
if (!services.postgres) {
|
||||
throw new Error('Canonical paper requires durable PostgreSQL custody');
|
||||
}
|
||||
const paper = new CanonicalPaperRuntime({
|
||||
repository: new PostgresCanonicalExecutionRepository(services.postgres),
|
||||
programs: canonicalPaper.strategies.map(createBuiltinStrategy),
|
||||
});
|
||||
const engine = new RustBacktestAdapter(
|
||||
{ logger: services.logger, storage: storageService },
|
||||
{ timeoutMs: options.nativeExecutionTimeoutMs }
|
||||
);
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
engineName: 'native',
|
||||
repository: new PostgresBacktestRunRepository(services.postgres),
|
||||
logger: services.logger,
|
||||
});
|
||||
const analytics = new AnalyticsService(services);
|
||||
// No legacy order gateway, feed listener or mode initializer is exposed in
|
||||
// this composition. Research still runs in the existing isolated worker.
|
||||
Object.assign(custom, {
|
||||
StorageService: storageService,
|
||||
AnalyticsService: analytics,
|
||||
CanonicalPaperRuntime: paper,
|
||||
BacktestEngine: engine,
|
||||
BacktestRunner: runner,
|
||||
});
|
||||
const canonicalContainer = container as AwilixContainer<
|
||||
ServiceDefinitions & {
|
||||
StorageService: StorageService;
|
||||
AnalyticsService: AnalyticsService;
|
||||
CanonicalPaperRuntime: PaperRuntime;
|
||||
BacktestEngine: BacktestExecutionEngine;
|
||||
BacktestRunner: BacktestRunner;
|
||||
orchestratorServices: IServiceContainer;
|
||||
}
|
||||
>;
|
||||
canonicalContainer.register({
|
||||
StorageService: asValue(storageService),
|
||||
AnalyticsService: asValue(analytics),
|
||||
CanonicalPaperRuntime: asValue(paper),
|
||||
BacktestEngine: asValue(engine),
|
||||
BacktestRunner: asValue(runner),
|
||||
orchestratorServices: asValue(services),
|
||||
});
|
||||
container
|
||||
.resolve('handlerScanner')
|
||||
.registerHandlerClass(BacktestHandler, { serviceName: 'orchestrator' });
|
||||
try {
|
||||
if (options.initializeMode !== false) {
|
||||
await paper.initialize(canonicalPaper);
|
||||
}
|
||||
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 });
|
||||
} catch (error) {
|
||||
await paper.shutdown().catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Callbacks are invoked after composition: the feed drains the manager, and
|
||||
// factories receive the current mode without either service locating its peers.
|
||||
const marketDataService: MarketDataService = new MarketDataService({
|
||||
|
|
@ -174,7 +267,10 @@ export async function registerOrchestratorServices(
|
|||
|
||||
// Initialize mode manager with default paper trading mode
|
||||
if (role === 'paper' && options.initializeMode !== false) {
|
||||
await modeManager.initializeMode({ mode: 'paper', startingCapital: 100000 });
|
||||
await modeManager.initializeMode({
|
||||
mode: 'paper',
|
||||
startingCapital: options.paperTradingCapital ?? 100000,
|
||||
});
|
||||
}
|
||||
// Start job consumption only after the shared graph and initial mode are ready.
|
||||
services.queueManager?.getQueue('orchestrator', { workers: 1, concurrency: 1 });
|
||||
|
|
|
|||
146
apps/stock/orchestrator/src/contracts/paper-runtime.ts
Normal file
146
apps/stock/orchestrator/src/contracts/paper-runtime.ts
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
/** Explicit trusted producer boundary. No legacy timestamp repair or broker capabilities. */
|
||||
import { z } from 'zod';
|
||||
import { parseFinancialDecimal } from '@stock-bot/types';
|
||||
import { builtinStrategySelectionSchema } from './builtin-strategy';
|
||||
import { canonicalMatchingConfigSchema, matchingCommandSchema } from './canonical-execution';
|
||||
import { replayConfigSchema, 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 duration = counter.refine(value => value > 0, 'Duration must be positive');
|
||||
const decimal = z.string().transform(value => parseFinancialDecimal(value));
|
||||
|
||||
export const paperPolicySchema = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
sourceId: id,
|
||||
priceBasis: z.literal('raw'),
|
||||
maxFeedAgeMs: duration,
|
||||
observations: z.array(
|
||||
z
|
||||
.object({
|
||||
seriesId: id,
|
||||
instrumentId: id,
|
||||
intervalMs: duration,
|
||||
staleAfterMs: counter,
|
||||
})
|
||||
.strict()
|
||||
),
|
||||
cadence: z.array(z.object({ ownerId: id, seriesIds: z.array(id).min(1) }).strict()),
|
||||
calendars: z
|
||||
.array(
|
||||
z
|
||||
.object({
|
||||
instrumentId: id,
|
||||
calendarId: id,
|
||||
revision: id,
|
||||
sessions: z
|
||||
.array(z.object({ sessionId: id, opensAt: time, closesAt: time }).strict())
|
||||
.min(1),
|
||||
})
|
||||
.strict()
|
||||
)
|
||||
.min(1),
|
||||
riskBoundaries: z.array(
|
||||
replayConfigSchema.shape.matching.shape.risk.shape.ledger.shape.riskSession
|
||||
),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const paperConfigurationSchema = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
matching: canonicalMatchingConfigSchema,
|
||||
strategies: z.array(builtinStrategySelectionSchema).min(1),
|
||||
policy: paperPolicySchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** 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>;
|
||||
}
|
||||
|
|
@ -27,6 +27,7 @@ import {
|
|||
type CanonicalExecutionRepository,
|
||||
type CanonicalJournalEntry,
|
||||
type CanonicalOwner,
|
||||
type CanonicalPaperHost,
|
||||
type CanonicalPaperInput,
|
||||
type CanonicalTransaction,
|
||||
} from './canonical-paper';
|
||||
|
|
@ -65,6 +66,8 @@ export class CanonicalPaperExecution {
|
|||
programs: readonly StrategyProgram[];
|
||||
/** Best effort after SQL commit. Recover missed notifications using journal(sequence). */
|
||||
publish?: (entries: readonly CanonicalJournalEntry[]) => void | Promise<void>;
|
||||
/** Only the trusted paper runtime owns this generation and operational gate. */
|
||||
control?: { generation: string; guard(account: CanonicalAccount): boolean };
|
||||
}
|
||||
) {
|
||||
this.programs = new Map();
|
||||
|
|
@ -95,12 +98,14 @@ export class CanonicalPaperExecution {
|
|||
pendingObservations: [],
|
||||
};
|
||||
})
|
||||
.sort((a, b) => (a.definition.ownerId < b.definition.ownerId ? -1 : 1));
|
||||
.sort((a, b) =>
|
||||
Buffer.compare(Buffer.from(a.definition.ownerId), Buffer.from(b.definition.ownerId))
|
||||
);
|
||||
// Program closures are trusted code. Metadata and state are detached now, before any await.
|
||||
freeze(this.initialOwners);
|
||||
}
|
||||
|
||||
initialize(configuration: CanonicalMatchingConfig): Promise<void> {
|
||||
initialize(configuration: CanonicalMatchingConfig, host?: CanonicalPaperHost): Promise<void> {
|
||||
outsideCallback();
|
||||
const config = canonicalMatchingConfigSchema.parse(configuration);
|
||||
const identity = {
|
||||
|
|
@ -131,6 +136,7 @@ export class CanonicalPaperExecution {
|
|||
observed: 0,
|
||||
pendingDecisionSequence: null,
|
||||
latestObservations: [],
|
||||
...(host ? { host } : {}),
|
||||
};
|
||||
return this.options.repository.initialize(initial, this.initialOwners).then(() => {
|
||||
this.identity = identity;
|
||||
|
|
@ -149,6 +155,49 @@ export class CanonicalPaperExecution {
|
|||
enqueue(value: CanonicalPaperInput): Promise<boolean> {
|
||||
outsideCallback();
|
||||
const id = this.accountId();
|
||||
return this.options.repository.transact(id, async tx => {
|
||||
if (tx.account.host) {
|
||||
throw new ExecutionConflictError(
|
||||
'Controlled paper accounts accept only atomic producer frames'
|
||||
);
|
||||
}
|
||||
return this.enqueueInput(tx, value);
|
||||
});
|
||||
}
|
||||
|
||||
/** The runtime calls this while holding the account lock for the whole frame. */
|
||||
async enqueueFrame(
|
||||
tx: CanonicalTransaction,
|
||||
inputs: readonly CanonicalPaperInput[]
|
||||
): Promise<void> {
|
||||
outsideCallback();
|
||||
if (
|
||||
tx.account.identity.accountId !== this.accountId() ||
|
||||
!tx.account.host ||
|
||||
!this.allowed(tx.account)
|
||||
) {
|
||||
throw new ExecutionConflictError('Paper frame admission requires an active owned runtime');
|
||||
}
|
||||
for (const input of inputs) {
|
||||
await this.enqueueInput(tx, input);
|
||||
}
|
||||
}
|
||||
|
||||
private allowed(account: CanonicalAccount): boolean {
|
||||
if (!account.host) {
|
||||
return true;
|
||||
}
|
||||
const control = this.options.control;
|
||||
if (!control || account.host.generation !== control.generation) {
|
||||
throw new ExecutionConflictError('Canonical paper runtime generation is obsolete');
|
||||
}
|
||||
return control.guard(account) && account.host.active && !account.host.operatorHalted;
|
||||
}
|
||||
|
||||
private async enqueueInput(
|
||||
tx: CanonicalTransaction,
|
||||
value: CanonicalPaperInput
|
||||
): Promise<boolean> {
|
||||
const input = canonicalPaperInputSchema.parse(value);
|
||||
if (input.command.body.kind === 'submit') {
|
||||
throw new Error('Strategy submissions require a durable all-owner decision batch');
|
||||
|
|
@ -182,30 +231,28 @@ export class CanonicalPaperExecution {
|
|||
throw new Error('Observation is unavailable at its admitted input time');
|
||||
}
|
||||
const fingerprint = createHash('sha256').update(canonicalJson(input)).digest('hex');
|
||||
return this.options.repository.transact(id, async tx => {
|
||||
const old = await tx.getInput(input.command.commandId);
|
||||
if (old) {
|
||||
if (old.fingerprint !== fingerprint) {
|
||||
throw new ExecutionConflictError('Conflicting canonical market input identity');
|
||||
}
|
||||
return false;
|
||||
const old = await tx.getInput(input.command.commandId);
|
||||
if (old) {
|
||||
if (old.fingerprint !== fingerprint) {
|
||||
throw new ExecutionConflictError('Conflicting canonical market input identity');
|
||||
}
|
||||
if (tx.account.checkpoint.status !== 'Running') {
|
||||
throw new Error(
|
||||
`Canonical account is terminal: ${diagnosticFailure(tx.account) ?? tx.account.checkpoint.status}`
|
||||
);
|
||||
}
|
||||
tx.account.inputSequence = increment(tx.account.inputSequence);
|
||||
await tx.putInput({
|
||||
version: 1,
|
||||
id: input.command.commandId,
|
||||
sequence: tx.account.inputSequence,
|
||||
fingerprint,
|
||||
status: 'pending',
|
||||
input,
|
||||
});
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
if (tx.account.checkpoint.status !== 'Running') {
|
||||
throw new Error(
|
||||
`Canonical account is terminal: ${diagnosticFailure(tx.account) ?? tx.account.checkpoint.status}`
|
||||
);
|
||||
}
|
||||
tx.account.inputSequence = increment(tx.account.inputSequence);
|
||||
await tx.putInput({
|
||||
version: 1,
|
||||
id: input.command.commandId,
|
||||
sequence: tx.account.inputSequence,
|
||||
fingerprint,
|
||||
status: 'pending',
|
||||
input,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
private async persist(
|
||||
|
|
@ -357,7 +404,8 @@ export class CanonicalPaperExecution {
|
|||
tx: CanonicalTransaction,
|
||||
input: NonNullable<CanonicalPaperInput['decision']>
|
||||
): DecisionContext {
|
||||
const series = tx.account.checkpoint.config.series;
|
||||
const series =
|
||||
tx.account.host?.configuration.policy.observations ?? tx.account.checkpoint.config.series;
|
||||
if (
|
||||
input.inputs.length !== series.length ||
|
||||
new Set(input.inputs.map(item => item.series_id)).size !== series.length ||
|
||||
|
|
@ -372,7 +420,10 @@ export class CanonicalPaperExecution {
|
|||
const expected = !latest
|
||||
? 'Missing'
|
||||
: {
|
||||
[input.key.at - latest.event_time > tx.account.checkpoint.config.risk.maxMarkAgeMs
|
||||
[input.key.at - latest.event_time >
|
||||
(tx.account.host?.configuration.policy.observations.find(
|
||||
series => series.seriesId === item.series_id
|
||||
)?.staleAfterMs ?? tx.account.checkpoint.config.risk.maxMarkAgeMs)
|
||||
? 'Stale'
|
||||
: 'Fresh']: { event_time: latest.event_time, available_at: latest.available_at },
|
||||
};
|
||||
|
|
@ -389,7 +440,9 @@ export class CanonicalPaperExecution {
|
|||
barrier_id: input.barrierId,
|
||||
at: input.key.at,
|
||||
revision: tx.account.view.admissionRevision,
|
||||
owner_ids: [...input.ownerIds].sort(),
|
||||
owner_ids: [...input.ownerIds].sort((a, b) =>
|
||||
Buffer.compare(Buffer.from(a), Buffer.from(b))
|
||||
),
|
||||
observation_count: tx.account.observed,
|
||||
inputs: input.inputs,
|
||||
},
|
||||
|
|
@ -410,7 +463,10 @@ export class CanonicalPaperExecution {
|
|||
const observations = input.input.observations;
|
||||
for (const observation of observations) {
|
||||
if (
|
||||
!tx.account.checkpoint.config.series.some(
|
||||
!(
|
||||
tx.account.host?.configuration.policy.observations ??
|
||||
tx.account.checkpoint.config.series
|
||||
).some(
|
||||
series =>
|
||||
series.seriesId === observation.series_id &&
|
||||
series.instrumentId === observation.instrument_id
|
||||
|
|
@ -461,6 +517,9 @@ export class CanonicalPaperExecution {
|
|||
return (async () => {
|
||||
for (;;) {
|
||||
const step = await this.options.repository.transact(id, async tx => {
|
||||
if (!this.allowed(tx.account)) {
|
||||
return { worked: false, entries: [], failure: undefined };
|
||||
}
|
||||
const failure = diagnosticFailure(tx.account);
|
||||
if (failure) {
|
||||
return { worked: false, entries: [], failure };
|
||||
|
|
|
|||
|
|
@ -35,6 +35,44 @@ function accountState(raw: unknown): CanonicalAccount {
|
|||
) {
|
||||
throw new ExecutionConflictError('Canonical envelope identity or revision mismatch');
|
||||
}
|
||||
if (
|
||||
account.host &&
|
||||
canonicalJson(account.host.configuration.matching) !== canonicalJson(account.checkpoint.config)
|
||||
) {
|
||||
throw new ExecutionConflictError(
|
||||
'Canonical host configuration differs from financial configuration'
|
||||
);
|
||||
}
|
||||
if (account.host) {
|
||||
const { configuration, connection, quotes, quoteHighWater } = account.host;
|
||||
if (
|
||||
configuration.strategies.length !== account.definitions.length ||
|
||||
configuration.strategies.some(
|
||||
selection =>
|
||||
!account.definitions.some(
|
||||
definition =>
|
||||
definition.ownerId === selection.ownerId &&
|
||||
definition.strategyId === selection.strategyId &&
|
||||
definition.strategyVersion === selection.strategyVersion &&
|
||||
definition.seed === selection.seed &&
|
||||
definition.mode === 'target'
|
||||
)
|
||||
) ||
|
||||
(connection && connection.sourceId !== configuration.policy.sourceId) ||
|
||||
[quotes, quoteHighWater].some(
|
||||
clocks =>
|
||||
new Set(clocks.map(quote => quote.instrumentId)).size !== clocks.length ||
|
||||
clocks.some(
|
||||
quote =>
|
||||
!configuration.matching.series.some(
|
||||
series => series.instrumentId === quote.instrumentId
|
||||
)
|
||||
)
|
||||
)
|
||||
) {
|
||||
throw new ExecutionConflictError('Canonical host strategy or feed binding mismatch');
|
||||
}
|
||||
}
|
||||
return account;
|
||||
}
|
||||
|
||||
|
|
@ -59,11 +97,13 @@ export class PostgresCanonicalExecutionRepository implements CanonicalExecutionR
|
|||
identity: account.identity,
|
||||
config: account.checkpoint.config,
|
||||
definitions: account.definitions,
|
||||
hostConfiguration: account.host?.configuration ?? null,
|
||||
}) !==
|
||||
canonicalJson({
|
||||
identity: expected.identity,
|
||||
config: expected.checkpoint.config,
|
||||
definitions: expected.definitions,
|
||||
hostConfiguration: expected.host?.configuration ?? null,
|
||||
})
|
||||
) {
|
||||
throw new ExecutionConflictError(
|
||||
|
|
|
|||
|
|
@ -12,13 +12,44 @@ import {
|
|||
nativeManagedOrderSchema,
|
||||
stepSchema,
|
||||
} from '../contracts/native-replay';
|
||||
import { paperConfigurationSchema, paperConnectionSchema } from '../contracts/paper-runtime';
|
||||
import { metadataSchema, stateCopy } from '../strategies/strategy-decision';
|
||||
|
||||
const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
||||
const time = matchingCommandSchema.shape.key.shape.at;
|
||||
const json = z.unknown().transform(value => stateCopy(value));
|
||||
const observation = stepSchema.shape.observations.element;
|
||||
const barrier = stepSchema.shape.step.options[1].shape.barrier;
|
||||
const definition = metadataSchema.extend({ initialState: json }).strict();
|
||||
const quoteClock = z
|
||||
.object({ instrumentId: z.string(), observedAt: time, sourceSequence: counter })
|
||||
.strict();
|
||||
/** Host controls are deliberately outside the native financial checkpoint. */
|
||||
export const canonicalPaperHostSchema = z
|
||||
.object({
|
||||
version: z.literal(1),
|
||||
configuration: paperConfigurationSchema,
|
||||
generation: z.string().min(1),
|
||||
active: z.boolean(),
|
||||
operatorHalted: z.boolean(),
|
||||
haltReason: z.string().nullable(),
|
||||
diagnostic: z.string().nullable(),
|
||||
connection: paperConnectionSchema.nullable(),
|
||||
lastReceivedAt: time.nullable(),
|
||||
lastAvailableAt: time.nullable(),
|
||||
lastSequence: counter.nullable(),
|
||||
quotes: z.array(quoteClock),
|
||||
quoteHighWater: z.array(quoteClock),
|
||||
frames: z.record(
|
||||
z
|
||||
.object({ fingerprint: z.string(), disposition: z.enum(['health-only', 'admitted']) })
|
||||
.strict()
|
||||
),
|
||||
observations: z.record(z.string()),
|
||||
physicalQuotes: z.record(z.string()),
|
||||
})
|
||||
.strict();
|
||||
export type CanonicalPaperHost = z.infer<typeof canonicalPaperHostSchema>;
|
||||
const feedback = z
|
||||
.object({
|
||||
decision: nativeManagedOrderSchema.shape.order.shape.decision,
|
||||
|
|
@ -76,6 +107,7 @@ export const canonicalAccountSchema = z
|
|||
observed: counter,
|
||||
pendingDecisionSequence: counter.nullable(),
|
||||
latestObservations: z.array(observation),
|
||||
host: canonicalPaperHostSchema.optional(),
|
||||
})
|
||||
.strict();
|
||||
export const canonicalPaperInputSchema = z
|
||||
|
|
@ -170,7 +202,7 @@ export function compareEventKeys(
|
|||
return (
|
||||
a.at - b.at ||
|
||||
phases[a.phase] - phases[b.phase] ||
|
||||
(a.instrumentId < b.instrumentId ? -1 : a.instrumentId > b.instrumentId ? 1 : 0) ||
|
||||
Buffer.compare(Buffer.from(a.instrumentId), Buffer.from(b.instrumentId)) ||
|
||||
a.sourceSequence - b.sourceSequence
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -151,10 +151,23 @@ async function main() {
|
|||
const stopped = server?.stop();
|
||||
let exitCode = 0;
|
||||
try {
|
||||
await services.custom?.BacktestRunner?.shutdown();
|
||||
await services.queueManager?.shutdown();
|
||||
await services.custom?.ModeManager?.shutdown();
|
||||
await stopped;
|
||||
const failures: unknown[] = [];
|
||||
for (const close of [
|
||||
() => services.custom?.CanonicalPaperRuntime?.shutdown(),
|
||||
() => services.custom?.BacktestRunner?.shutdown(),
|
||||
() => services.queueManager?.shutdown(),
|
||||
() => services.custom?.ModeManager?.shutdown(),
|
||||
() => stopped,
|
||||
]) {
|
||||
try {
|
||||
await close();
|
||||
} catch (error) {
|
||||
failures.push(error);
|
||||
}
|
||||
}
|
||||
if (failures.length) {
|
||||
throw new AggregateError(failures, 'Orchestrator shutdown failed');
|
||||
}
|
||||
} catch (error) {
|
||||
exitCode = 1;
|
||||
services.logger.error('Orchestrator shutdown failed', { error });
|
||||
|
|
|
|||
498
apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts
Normal file
498
apps/stock/orchestrator/src/paper/CanonicalPaperRuntime.ts
Normal file
|
|
@ -0,0 +1,498 @@
|
|||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import type { StrategyProgram } from '../contracts/canonical-strategy';
|
||||
import {
|
||||
paperActivationSchema,
|
||||
paperConnectionSchema,
|
||||
paperHaltSchema,
|
||||
PaperRuntimeError,
|
||||
type PaperConfiguration,
|
||||
type PaperConfigurationInput,
|
||||
type PaperConnection,
|
||||
type PaperFrameInput,
|
||||
type PaperReadiness,
|
||||
type PaperRuntime,
|
||||
} from '../contracts/paper-runtime';
|
||||
import type {
|
||||
CanonicalAccount,
|
||||
CanonicalExecutionRepository,
|
||||
CanonicalJournalEntry,
|
||||
CanonicalPaperHost,
|
||||
CanonicalTransaction,
|
||||
} from '../execution/canonical-paper';
|
||||
import { CanonicalPaperExecution } from '../execution/CanonicalPaperExecution';
|
||||
import { canonicalJson } from '../execution/strategy-recovery';
|
||||
import { planPaperFrame, validatePaperConfiguration, validatePaperFrame } from './feed';
|
||||
|
||||
const fingerprint = (value: unknown) =>
|
||||
createHash('sha256').update(canonicalJson(value)).digest('hex');
|
||||
function hostState(account: CanonicalAccount): CanonicalPaperHost {
|
||||
if (!account.host) {
|
||||
throw new PaperRuntimeError('conflict', 'Paper account has no host policy');
|
||||
}
|
||||
return account.host;
|
||||
}
|
||||
|
||||
/** An operational gate around durable custody, never a second financial simulator.
|
||||
* Each transaction releases the account lock so a halt can stop the next step. */
|
||||
export class CanonicalPaperRuntime implements PaperRuntime {
|
||||
private readonly generation = randomUUID();
|
||||
private readonly execution: CanonicalPaperExecution;
|
||||
private configuration?: PaperConfiguration;
|
||||
private readonly now: () => number;
|
||||
|
||||
constructor(
|
||||
private readonly options: {
|
||||
repository: CanonicalExecutionRepository;
|
||||
programs: readonly StrategyProgram[];
|
||||
now?: () => number;
|
||||
publish?: (entries: readonly CanonicalJournalEntry[]) => void | Promise<void>;
|
||||
}
|
||||
) {
|
||||
this.now = options.now ?? Date.now;
|
||||
this.execution = new CanonicalPaperExecution({
|
||||
repository: options.repository,
|
||||
programs: options.programs,
|
||||
publish: options.publish,
|
||||
control: { generation: this.generation, guard: account => this.guard(account) },
|
||||
});
|
||||
}
|
||||
|
||||
async initialize(input: PaperConfigurationInput): Promise<void> {
|
||||
if (this.configuration) {
|
||||
throw new PaperRuntimeError('conflict', 'Paper runtime is already initialized');
|
||||
}
|
||||
const configuration = validatePaperConfiguration(input);
|
||||
if (
|
||||
configuration.strategies.length !== this.options.programs.length ||
|
||||
configuration.strategies.some(
|
||||
selection =>
|
||||
!this.options.programs.some(
|
||||
program =>
|
||||
program.ownerId === selection.ownerId &&
|
||||
program.strategyId === selection.strategyId &&
|
||||
program.strategyVersion === selection.strategyVersion &&
|
||||
program.seed === selection.seed &&
|
||||
program.mode === 'target'
|
||||
)
|
||||
)
|
||||
) {
|
||||
throw new PaperRuntimeError(
|
||||
'conflict',
|
||||
'Paper programs must match immutable configured strategy selections'
|
||||
);
|
||||
}
|
||||
const host: CanonicalPaperHost = {
|
||||
version: 1,
|
||||
configuration,
|
||||
generation: this.generation,
|
||||
active: false,
|
||||
operatorHalted: true,
|
||||
haltReason: 'Initial operator activation required',
|
||||
diagnostic: null,
|
||||
connection: null,
|
||||
lastReceivedAt: null,
|
||||
lastAvailableAt: null,
|
||||
lastSequence: null,
|
||||
quotes: [],
|
||||
quoteHighWater: [],
|
||||
frames: {},
|
||||
observations: {},
|
||||
physicalQuotes: {},
|
||||
};
|
||||
await this.execution.initialize(configuration.matching, host);
|
||||
await this.options.repository.transact(
|
||||
configuration.matching.risk.ledger.accountId,
|
||||
async tx => {
|
||||
if (!tx.account.host) {
|
||||
throw new PaperRuntimeError('conflict', 'Paper account has no host policy');
|
||||
}
|
||||
tx.account.host.generation = this.generation;
|
||||
tx.account.host.active = false;
|
||||
tx.account.host.connection = null;
|
||||
tx.account.host.lastReceivedAt = null;
|
||||
tx.account.host.lastSequence = null;
|
||||
tx.account.host.quotes = [];
|
||||
}
|
||||
);
|
||||
this.configuration = configuration;
|
||||
}
|
||||
|
||||
private transaction<T>(
|
||||
work: (tx: CanonicalTransaction, host: CanonicalPaperHost) => Promise<T>
|
||||
): Promise<T> {
|
||||
if (!this.configuration) {
|
||||
throw new PaperRuntimeError('not-ready', 'Paper runtime is not initialized');
|
||||
}
|
||||
return this.options.repository.transact(
|
||||
this.configuration.matching.risk.ledger.accountId,
|
||||
async tx => {
|
||||
const host = tx.account.host;
|
||||
if (!host || host.generation !== this.generation) {
|
||||
throw new PaperRuntimeError('conflict', 'Paper runtime generation is obsolete');
|
||||
}
|
||||
return work(tx, host);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private health(account: CanonicalAccount, now: number): string[] {
|
||||
const host = hostState(account);
|
||||
const { policy, matching } = host.configuration;
|
||||
const reasons: string[] = [];
|
||||
if (!host.connection) {
|
||||
reasons.push('feed-disconnected');
|
||||
}
|
||||
if (
|
||||
host.lastReceivedAt === null ||
|
||||
host.lastAvailableAt === null ||
|
||||
now < host.lastReceivedAt ||
|
||||
now < host.lastAvailableAt ||
|
||||
now - host.lastReceivedAt > policy.maxFeedAgeMs ||
|
||||
now - host.lastAvailableAt > policy.maxFeedAgeMs
|
||||
) {
|
||||
reasons.push('feed-stale');
|
||||
}
|
||||
for (const series of matching.series) {
|
||||
const quote = host.quotes.find(item => item.instrumentId === series.instrumentId);
|
||||
if (!quote || now < quote.observedAt || now - quote.observedAt > matching.risk.maxMarkAgeMs) {
|
||||
reasons.push(`quote-stale:${series.instrumentId}`);
|
||||
}
|
||||
const calendar = policy.calendars.find(item => item.instrumentId === series.instrumentId);
|
||||
if (!calendar?.sessions.some(session => session.opensAt <= now && now < session.closesAt)) {
|
||||
reasons.push(`calendar-uncovered:${series.instrumentId}`);
|
||||
}
|
||||
}
|
||||
if (account.checkpoint.status !== 'Running') {
|
||||
reasons.push('native-not-running');
|
||||
}
|
||||
return reasons;
|
||||
}
|
||||
|
||||
private guard(account: CanonicalAccount): boolean {
|
||||
const host = hostState(account);
|
||||
if (this.health(account, this.now()).length && host.active) {
|
||||
host.active = false;
|
||||
host.diagnostic =
|
||||
'Operational readiness expired; fresh feed and operator activation required';
|
||||
}
|
||||
return host.active && !host.operatorHalted;
|
||||
}
|
||||
|
||||
private async readiness(tx: CanonicalTransaction): Promise<PaperReadiness> {
|
||||
this.guard(tx.account);
|
||||
const host = hostState(tx.account);
|
||||
const reasons = this.health(tx.account, this.now());
|
||||
if (host.operatorHalted) {
|
||||
reasons.push('operator-halted');
|
||||
}
|
||||
if (host.diagnostic) {
|
||||
reasons.push(host.diagnostic);
|
||||
}
|
||||
const pendingInput = (await tx.nextInput())?.id ?? null;
|
||||
const pendingBatch = (await tx.nextBatch())?.id ?? null;
|
||||
const pendingDecisionSequence = tx.account.pendingDecisionSequence;
|
||||
const requiresHistoricalRecovery =
|
||||
pendingInput !== null || pendingBatch !== null || pendingDecisionSequence !== null;
|
||||
if (requiresHistoricalRecovery) {
|
||||
reasons.push('historical-recovery-required');
|
||||
}
|
||||
return {
|
||||
configured: true,
|
||||
accountId: tx.account.identity.accountId,
|
||||
sourceId: host.configuration.policy.sourceId,
|
||||
active: host.active,
|
||||
ready: reasons.length === 0,
|
||||
operatorHalted: host.operatorHalted,
|
||||
connected: host.connection !== null,
|
||||
reasons,
|
||||
lastReceivedAt: host.lastReceivedAt,
|
||||
lastAvailableAt: host.lastAvailableAt,
|
||||
requiresHistoricalRecovery,
|
||||
pendingInput,
|
||||
pendingBatch,
|
||||
pendingDecisionSequence,
|
||||
nativeStatus: tx.account.checkpoint.status,
|
||||
risk: {
|
||||
dailyHalted: tx.account.view.risk.dailyHalted,
|
||||
drawdownHalted: tx.account.view.risk.drawdownHalted,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A rejected request rolls back its admission transaction. Persist ONLY the
|
||||
* freshness latch separately, preserving the original failure if storage is down. */
|
||||
private async withFreshnessLatch<T>(work: () => Promise<T>): Promise<T> {
|
||||
try {
|
||||
return await work();
|
||||
} catch (error) {
|
||||
try {
|
||||
await this.transaction(async tx => {
|
||||
this.guard(tx.account);
|
||||
});
|
||||
} catch {
|
||||
// A replacement generation or unavailable repository must not mask the original error.
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
connect(input: PaperConnection): Promise<PaperReadiness> {
|
||||
const connection = paperConnectionSchema.parse(input);
|
||||
return this.transaction(async (tx, host) => {
|
||||
if (connection.sourceId !== host.configuration.policy.sourceId) {
|
||||
throw new PaperRuntimeError(
|
||||
'invalid-input',
|
||||
'Paper source does not match its configured provider'
|
||||
);
|
||||
}
|
||||
this.guard(tx.account);
|
||||
if (canonicalJson(connection) !== canonicalJson(host.connection)) {
|
||||
host.connection = connection;
|
||||
host.active = false;
|
||||
host.lastReceivedAt = null;
|
||||
host.lastSequence = null;
|
||||
host.quotes = [];
|
||||
}
|
||||
return this.readiness(tx);
|
||||
});
|
||||
}
|
||||
|
||||
disconnect(input: PaperConnection): Promise<PaperReadiness> {
|
||||
const connection = paperConnectionSchema.parse(input);
|
||||
return this.transaction(async (tx, host) => {
|
||||
if (canonicalJson(connection) === canonicalJson(host.connection)) {
|
||||
host.active = false;
|
||||
host.connection = null;
|
||||
}
|
||||
return this.readiness(tx);
|
||||
});
|
||||
}
|
||||
|
||||
async ingest(input: PaperFrameInput): ReturnType<PaperRuntime['ingest']> {
|
||||
return this.withFreshnessLatch(async () => {
|
||||
if (!this.configuration) {
|
||||
throw new PaperRuntimeError('not-ready', 'Paper runtime is not initialized');
|
||||
}
|
||||
const frame = validatePaperFrame(this.configuration, input, this.now());
|
||||
const digest = fingerprint(frame);
|
||||
const frameIdentity = fingerprint(frame.id);
|
||||
const receipt = await this.transaction(async (tx, host) => {
|
||||
const old = host.frames[frameIdentity];
|
||||
if (old) {
|
||||
if (old.fingerprint !== digest) {
|
||||
throw new PaperRuntimeError('conflict', 'Paper frame ID has conflicting content');
|
||||
}
|
||||
this.guard(tx.account);
|
||||
return { duplicate: true, disposition: old.disposition };
|
||||
}
|
||||
if (
|
||||
!host.connection ||
|
||||
host.connection.sourceId !== frame.sourceId ||
|
||||
host.connection.connectionId !== frame.connectionId
|
||||
) {
|
||||
throw new PaperRuntimeError('conflict', 'Paper frame belongs to an inactive connection');
|
||||
}
|
||||
if (
|
||||
(host.lastSequence !== null && frame.sequence <= host.lastSequence) ||
|
||||
(host.lastAvailableAt !== null && frame.availableAt <= host.lastAvailableAt)
|
||||
) {
|
||||
throw new PaperRuntimeError(
|
||||
'conflict',
|
||||
'Distinct paper frames require increasing sequence and availability time'
|
||||
);
|
||||
}
|
||||
// Compare the OLD health deadline before this fresh frame can change it.
|
||||
this.guard(tx.account);
|
||||
if (
|
||||
host.active &&
|
||||
((await tx.nextInput()) ||
|
||||
(await tx.nextBatch()) ||
|
||||
tx.account.pendingDecisionSequence !== null)
|
||||
) {
|
||||
throw new PaperRuntimeError(
|
||||
'not-ready',
|
||||
'Previously admitted paper work requires completion before another frame'
|
||||
);
|
||||
}
|
||||
const observations = frame.observations.filter(observation => {
|
||||
const identity = fingerprint([
|
||||
observation.series_id,
|
||||
observation.event_time,
|
||||
observation.source_sequence,
|
||||
]);
|
||||
const value = fingerprint(observation);
|
||||
const known = host.observations[identity];
|
||||
if (known && known !== value) {
|
||||
throw new PaperRuntimeError(
|
||||
'conflict',
|
||||
'Physical observation identity has conflicting content'
|
||||
);
|
||||
}
|
||||
return !known;
|
||||
});
|
||||
for (const quote of frame.quotes) {
|
||||
const latest = host.quoteHighWater.find(item => item.instrumentId === quote.instrumentId);
|
||||
if (
|
||||
latest &&
|
||||
(quote.observedAt < latest.observedAt ||
|
||||
(quote.observedAt === latest.observedAt &&
|
||||
quote.sourceSequence < latest.sourceSequence))
|
||||
) {
|
||||
throw new PaperRuntimeError(
|
||||
'invalid-input',
|
||||
'Paper quote regresses the retained physical event time'
|
||||
);
|
||||
}
|
||||
if (
|
||||
host.active &&
|
||||
this.now() - quote.observedAt > host.configuration.matching.risk.maxMarkAgeMs
|
||||
) {
|
||||
throw new PaperRuntimeError('invalid-input', 'Admitted paper quote is stale');
|
||||
}
|
||||
const known =
|
||||
host.physicalQuotes[
|
||||
fingerprint([quote.instrumentId, quote.observedAt, quote.sourceSequence])
|
||||
];
|
||||
if (known) {
|
||||
throw new PaperRuntimeError(
|
||||
'conflict',
|
||||
known === fingerprint(quote)
|
||||
? 'New paper frame reuses known physical quote liquidity'
|
||||
: 'Physical quote identity has conflicting content'
|
||||
);
|
||||
}
|
||||
}
|
||||
const disposition = host.active ? ('admitted' as const) : ('health-only' as const);
|
||||
host.lastReceivedAt = this.now();
|
||||
host.lastAvailableAt = frame.availableAt;
|
||||
host.lastSequence = frame.sequence;
|
||||
for (const quote of frame.quotes) {
|
||||
for (const clocks of [host.quotes, host.quoteHighWater]) {
|
||||
const oldQuote = clocks.find(item => item.instrumentId === quote.instrumentId);
|
||||
if (!oldQuote) {
|
||||
clocks.push({
|
||||
instrumentId: quote.instrumentId,
|
||||
observedAt: quote.observedAt,
|
||||
sourceSequence: quote.sourceSequence,
|
||||
});
|
||||
} else if (
|
||||
quote.observedAt > oldQuote.observedAt ||
|
||||
(quote.observedAt === oldQuote.observedAt &&
|
||||
quote.sourceSequence > oldQuote.sourceSequence)
|
||||
) {
|
||||
Object.assign(oldQuote, {
|
||||
observedAt: quote.observedAt,
|
||||
sourceSequence: quote.sourceSequence,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (disposition === 'admitted') {
|
||||
await this.execution.enqueueFrame(
|
||||
tx,
|
||||
planPaperFrame(host.configuration, { ...frame, observations }, tx.account)
|
||||
);
|
||||
}
|
||||
for (const observation of frame.observations) {
|
||||
host.observations[
|
||||
fingerprint([
|
||||
observation.series_id,
|
||||
observation.event_time,
|
||||
observation.source_sequence,
|
||||
])
|
||||
] = fingerprint(observation);
|
||||
}
|
||||
for (const quote of frame.quotes) {
|
||||
host.physicalQuotes[
|
||||
fingerprint([quote.instrumentId, quote.observedAt, quote.sourceSequence])
|
||||
] = fingerprint(quote);
|
||||
}
|
||||
host.frames[frameIdentity] = { fingerprint: digest, disposition };
|
||||
return { duplicate: false, disposition };
|
||||
});
|
||||
// A retry retains its first disposition and never replays an inactive probe.
|
||||
if (!receipt.duplicate && receipt.disposition === 'admitted') {
|
||||
await this.drain();
|
||||
}
|
||||
return { ...receipt, readiness: await this.status() };
|
||||
});
|
||||
}
|
||||
|
||||
private async drain(): Promise<void> {
|
||||
try {
|
||||
await this.execution.drain();
|
||||
} catch (error) {
|
||||
await this.transaction(async (_tx, host) => {
|
||||
host.active = false;
|
||||
host.diagnostic = error instanceof Error ? error.message : String(error);
|
||||
}).catch(() => {
|
||||
/* A replacement generation alone controls its account. */
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async activate(input: { recoverPending: boolean }): Promise<PaperReadiness> {
|
||||
return this.withFreshnessLatch(async () => {
|
||||
const { recoverPending } = paperActivationSchema.parse(input);
|
||||
await this.transaction(async (tx, host) => {
|
||||
this.guard(tx.account);
|
||||
const reasons = this.health(tx.account, this.now());
|
||||
if (reasons.length) {
|
||||
throw new PaperRuntimeError(
|
||||
'not-ready',
|
||||
`Paper activation unavailable: ${reasons.join(', ')}`
|
||||
);
|
||||
}
|
||||
if (
|
||||
!recoverPending &&
|
||||
((await tx.nextInput()) ||
|
||||
(await tx.nextBatch()) ||
|
||||
tx.account.pendingDecisionSequence !== null)
|
||||
) {
|
||||
throw new PaperRuntimeError(
|
||||
'not-ready',
|
||||
'Historical admitted work requires explicit recoverPending: true'
|
||||
);
|
||||
}
|
||||
host.active = true;
|
||||
host.operatorHalted = false;
|
||||
host.haltReason = null;
|
||||
host.diagnostic = null;
|
||||
});
|
||||
await this.drain();
|
||||
const result = await this.status();
|
||||
if (!result.active || !result.ready || result.requiresHistoricalRecovery) {
|
||||
await this.transaction(async (_tx, host) => {
|
||||
host.active = false;
|
||||
});
|
||||
throw new PaperRuntimeError(
|
||||
'not-ready',
|
||||
'Paper activation stopped before recovery and fresh readiness completed'
|
||||
);
|
||||
}
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
halt(reason: string): Promise<PaperReadiness> {
|
||||
const parsed = paperHaltSchema.parse({ reason });
|
||||
return this.transaction(async (tx, host) => {
|
||||
host.active = false;
|
||||
host.operatorHalted = true;
|
||||
host.haltReason = parsed.reason;
|
||||
return this.readiness(tx);
|
||||
});
|
||||
}
|
||||
|
||||
status(): Promise<PaperReadiness> {
|
||||
return this.transaction(tx => this.readiness(tx));
|
||||
}
|
||||
|
||||
async shutdown(): Promise<void> {
|
||||
await this.transaction(async (_tx, host) => {
|
||||
host.active = false;
|
||||
host.connection = null;
|
||||
});
|
||||
}
|
||||
}
|
||||
520
apps/stock/orchestrator/src/paper/feed.ts
Normal file
520
apps/stock/orchestrator/src/paper/feed.ts
Normal file
|
|
@ -0,0 +1,520 @@
|
|||
/** Pure trusted-feed validation and deterministic command planning. Rust alone
|
||||
* matches orders and accounts for money; no feed clock or price is repaired here. */
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { ZodError } from 'zod';
|
||||
import {
|
||||
matchingCommandSchema,
|
||||
type CanonicalMatchingCommand,
|
||||
} from '../contracts/canonical-execution';
|
||||
import {
|
||||
paperConfigurationSchema,
|
||||
paperFrameSchema,
|
||||
PaperRuntimeError,
|
||||
type PaperConfiguration,
|
||||
type PaperConfigurationInput,
|
||||
type PaperFrame,
|
||||
type PaperFrameInput,
|
||||
} from '../contracts/paper-runtime';
|
||||
import type { CanonicalAccount, CanonicalPaperInput } from '../execution/canonical-paper';
|
||||
|
||||
type Observation = PaperFrame['observations'][number];
|
||||
type Quote = PaperFrame['quotes'][number];
|
||||
type Session = PaperConfiguration['policy']['calendars'][number]['sessions'][number];
|
||||
type Key = CanonicalMatchingCommand['key'];
|
||||
|
||||
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));
|
||||
const units = (value: string) => BigInt(value.replace('.', ''));
|
||||
function unique(values: readonly string[], label: string): void {
|
||||
if (new Set(values).size !== values.length) {
|
||||
invalid(`Duplicate paper ${label}`);
|
||||
}
|
||||
}
|
||||
function keyCompare(a: Key, b: Key): number {
|
||||
const phase = { Observation: 0, Decision: 1, Execution: 2, SessionClose: 3 };
|
||||
return (
|
||||
a.at - b.at ||
|
||||
phase[a.phase] - phase[b.phase] ||
|
||||
compareText(a.instrumentId, b.instrumentId) ||
|
||||
a.sourceSequence - b.sourceSequence
|
||||
);
|
||||
}
|
||||
const observationId = (row: Observation) =>
|
||||
JSON.stringify([row.series_id, row.event_time, row.source_sequence]);
|
||||
const physicalQuote = (instrumentId: string, observedAt: number, sourceSequence: number) =>
|
||||
JSON.stringify([instrumentId, observedAt, sourceSequence]);
|
||||
const quoteId = (quote: Quote) =>
|
||||
physicalQuote(quote.instrumentId, quote.observedAt, quote.sourceSequence);
|
||||
const quoteKey = (frame: PaperFrame, quote: Quote): Key => ({
|
||||
at: frame.availableAt,
|
||||
phase: 'Execution',
|
||||
instrumentId: quote.instrumentId,
|
||||
sourceSequence: quote.sourceSequence,
|
||||
});
|
||||
function sessions(config: PaperConfiguration, instrumentId: string): Session[] {
|
||||
const calendar = config.policy.calendars.find(item => item.instrumentId === instrumentId);
|
||||
if (!calendar) {
|
||||
invalid('Paper instrument has no declared calendar');
|
||||
}
|
||||
return calendar.sessions;
|
||||
}
|
||||
function activeSession(config: PaperConfiguration, instrumentId: string, at: number): Session {
|
||||
const session = sessions(config, instrumentId).find(
|
||||
item => item.opensAt <= at && at < item.closesAt
|
||||
);
|
||||
if (!session) {
|
||||
invalid('Paper quote is outside declared session coverage');
|
||||
}
|
||||
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 function validatePaperFrame(
|
||||
config: PaperConfiguration,
|
||||
input: PaperFrameInput,
|
||||
now: number
|
||||
): PaperFrame {
|
||||
const frame = parseInput(paperFrameSchema, input);
|
||||
if (
|
||||
!Number.isSafeInteger(now) ||
|
||||
frame.sourceId !== config.policy.sourceId ||
|
||||
frame.availableAt > now
|
||||
) {
|
||||
invalid('Paper frame source or availability time is invalid');
|
||||
}
|
||||
unique(frame.quotes.map(quoteId), 'physical quote');
|
||||
unique(
|
||||
frame.quotes.map(quote => JSON.stringify([quote.instrumentId, quote.sourceSequence])),
|
||||
'quote event key'
|
||||
);
|
||||
for (const quote of frame.quotes) {
|
||||
const series = config.matching.series.find(item => item.instrumentId === quote.instrumentId);
|
||||
const session = activeSession(config, quote.instrumentId, frame.availableAt);
|
||||
if (
|
||||
series?.seriesId !== quote.seriesId ||
|
||||
quote.observedAt > frame.availableAt ||
|
||||
quote.observedAt < session.opensAt ||
|
||||
units(quote.bid) <= 0n ||
|
||||
units(quote.ask) <= 0n ||
|
||||
units(quote.bid) > units(quote.ask) ||
|
||||
units(quote.bidSize) < 0n ||
|
||||
units(quote.askSize) < 0n
|
||||
) {
|
||||
invalid('Paper quote identity, time, price or size is invalid');
|
||||
}
|
||||
}
|
||||
frame.quotes.sort((a, b) => keyCompare(quoteKey(frame, a), quoteKey(frame, b)));
|
||||
for (let index = 1; index < frame.quotes.length; index++) {
|
||||
const prior = frame.quotes[index - 1];
|
||||
const current = frame.quotes[index];
|
||||
if (
|
||||
prior &&
|
||||
current &&
|
||||
prior.instrumentId === current.instrumentId &&
|
||||
prior.observedAt > current.observedAt
|
||||
) {
|
||||
invalid('Paper quote sequence reverses physical event time within a frame');
|
||||
}
|
||||
}
|
||||
const observations = new Map<string, Observation>();
|
||||
for (const row of frame.observations) {
|
||||
const series = config.policy.observations.find(item => item.seriesId === row.series_id);
|
||||
if (!series || series.instrumentId !== row.instrument_id) {
|
||||
invalid('Paper observation is outside the declared series manifest');
|
||||
}
|
||||
const session = sessions(config, row.instrument_id).find(
|
||||
item => item.opensAt <= row.interval_start && row.interval_start < item.closesAt
|
||||
);
|
||||
const intervalEnd = BigInt(row.interval_start) + BigInt(series.intervalMs);
|
||||
// Intervals start on a session-open grid and the final complete bar may be
|
||||
// clipped at a half-day/session close. No synthetic partial prices or volume.
|
||||
if (
|
||||
!session ||
|
||||
row.interval_end <= row.interval_start ||
|
||||
(BigInt(row.interval_start) - BigInt(session.opensAt)) % BigInt(series.intervalMs) !== 0n ||
|
||||
BigInt(row.interval_end) !==
|
||||
(intervalEnd < BigInt(session.closesAt) ? intervalEnd : BigInt(session.closesAt)) ||
|
||||
row.event_time !== row.interval_end ||
|
||||
row.interval_end > row.available_at ||
|
||||
row.available_at > frame.availableAt ||
|
||||
units(row.open) <= 0n ||
|
||||
units(row.close) <= 0n ||
|
||||
units(row.low) <= 0n ||
|
||||
units(row.high) < units(row.low) ||
|
||||
units(row.high) < units(row.open) ||
|
||||
units(row.high) < units(row.close) ||
|
||||
units(row.low) > units(row.open) ||
|
||||
units(row.low) > units(row.close) ||
|
||||
units(row.volume) < 0n
|
||||
) {
|
||||
invalid('Paper observation is incomplete, unaligned, unavailable or has invalid OHLCV');
|
||||
}
|
||||
const prior = observations.get(observationId(row));
|
||||
if (prior && !isDeepStrictEqual(prior, row)) {
|
||||
invalid('Conflicting physical paper observation');
|
||||
}
|
||||
observations.set(observationId(row), row);
|
||||
}
|
||||
frame.observations = [...observations.values()];
|
||||
return frame;
|
||||
}
|
||||
|
||||
/** Caller atomically enqueues this complete plan under the same account lock.
|
||||
* The runtime owns cross-frame observation fingerprints; this pure helper also
|
||||
* deduplicates against the known latest observation while retaining delayed older bars. */
|
||||
export function planPaperFrame(
|
||||
config: PaperConfiguration,
|
||||
frame: PaperFrame,
|
||||
account: Pick<CanonicalAccount, 'checkpoint' | 'latestObservations' | 'observed'>
|
||||
): CanonicalPaperInput[] {
|
||||
const { checkpoint } = account;
|
||||
if (checkpoint.status !== 'Running' || !isDeepStrictEqual(checkpoint.config, config.matching)) {
|
||||
throw new PaperRuntimeError(
|
||||
'not-ready',
|
||||
'Paper financial snapshot is incompatible or terminal'
|
||||
);
|
||||
}
|
||||
const retained = new Set<string>();
|
||||
const physicalTime = new Map<string, number>();
|
||||
for (const receipt of checkpoint.receipts) {
|
||||
const input = receipt.input;
|
||||
if (!input || typeof input !== 'object' || !('source' in input) || input.source !== 'Engine') {
|
||||
continue;
|
||||
}
|
||||
const parsed = matchingCommandSchema.safeParse('command' in input ? input.command : undefined);
|
||||
if (!parsed.success) {
|
||||
invalid('Malformed retained paper execution receipt');
|
||||
}
|
||||
const command = parsed.data;
|
||||
const observedAt =
|
||||
command.body.kind === 'mark'
|
||||
? command.body.observedAt
|
||||
: command.body.kind === 'execute' && command.body.observation.kind === 'quote'
|
||||
? command.body.observation.observedAt
|
||||
: undefined;
|
||||
if (observedAt !== undefined) {
|
||||
physicalTime.set(
|
||||
command.key.instrumentId,
|
||||
Math.max(physicalTime.get(command.key.instrumentId) ?? observedAt, observedAt)
|
||||
);
|
||||
}
|
||||
if (command.body.kind === 'execute' && command.body.observation.kind === 'quote') {
|
||||
retained.add(
|
||||
physicalQuote(
|
||||
command.key.instrumentId,
|
||||
command.body.observation.observedAt,
|
||||
command.key.sourceSequence
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
if (frame.quotes.some(quote => retained.has(quoteId(quote)))) {
|
||||
throw new PaperRuntimeError('conflict', 'Paper frame reuses retained physical quote liquidity');
|
||||
}
|
||||
if (
|
||||
frame.quotes.some(
|
||||
quote => quote.observedAt < (physicalTime.get(quote.instrumentId) ?? quote.observedAt)
|
||||
)
|
||||
) {
|
||||
invalid('Paper quote regresses the retained physical event time');
|
||||
}
|
||||
const commands: CanonicalMatchingCommand[] = [];
|
||||
const add = (command: CanonicalMatchingCommand) => {
|
||||
if (
|
||||
command.key.at <= frame.availableAt &&
|
||||
(!checkpoint.cursor || keyCompare(command.key, checkpoint.cursor) > 0)
|
||||
) {
|
||||
commands.push(command);
|
||||
}
|
||||
};
|
||||
for (const calendar of config.policy.calendars) {
|
||||
for (const session of calendar.sessions) {
|
||||
const identity = [
|
||||
frame.sourceId,
|
||||
calendar.instrumentId,
|
||||
calendar.calendarId,
|
||||
calendar.revision,
|
||||
session.sessionId,
|
||||
];
|
||||
add({
|
||||
commandId: JSON.stringify(['paper-session-open', ...identity]),
|
||||
key: {
|
||||
at: session.opensAt,
|
||||
phase: 'Observation',
|
||||
instrumentId: calendar.instrumentId,
|
||||
sourceSequence: 2,
|
||||
},
|
||||
body: { kind: 'openSession', session },
|
||||
});
|
||||
add({
|
||||
commandId: JSON.stringify(['paper-session-close', ...identity]),
|
||||
key: {
|
||||
at: session.closesAt,
|
||||
phase: 'Observation',
|
||||
instrumentId: calendar.instrumentId,
|
||||
sourceSequence: 0,
|
||||
},
|
||||
body: { kind: 'closeSession', sessionId: session.sessionId },
|
||||
});
|
||||
}
|
||||
}
|
||||
const firstSeries = config.matching.series[0];
|
||||
if (!firstSeries) {
|
||||
invalid('Paper configuration has no execution series');
|
||||
}
|
||||
for (const boundary of config.policy.riskBoundaries) {
|
||||
add({
|
||||
commandId: JSON.stringify([
|
||||
'paper-risk-boundary',
|
||||
frame.sourceId,
|
||||
boundary.calendarId,
|
||||
boundary.calendarRevision,
|
||||
boundary.sessionId,
|
||||
]),
|
||||
key: {
|
||||
at: boundary.startsAt,
|
||||
phase: 'Observation',
|
||||
instrumentId: firstSeries.instrumentId,
|
||||
sourceSequence: 1,
|
||||
},
|
||||
body: { kind: 'riskSessionBoundary', riskSession: boundary },
|
||||
});
|
||||
}
|
||||
const active = new Map(checkpoint.sessions);
|
||||
commands.sort((a, b) => keyCompare(a.key, b.key));
|
||||
for (const command of commands) {
|
||||
if (command.body.kind === 'openSession') {
|
||||
if (active.has(command.key.instrumentId)) {
|
||||
invalid('Paper venue session is already open at its declared boundary');
|
||||
}
|
||||
active.set(command.key.instrumentId, command.body.session);
|
||||
} else if (command.body.kind === 'closeSession') {
|
||||
if (active.get(command.key.instrumentId)?.sessionId !== command.body.sessionId) {
|
||||
invalid('Paper venue close does not match the retained open session');
|
||||
}
|
||||
active.delete(command.key.instrumentId);
|
||||
}
|
||||
}
|
||||
const quotes = [...frame.quotes].sort((a, b) =>
|
||||
keyCompare(quoteKey(frame, a), quoteKey(frame, b))
|
||||
);
|
||||
for (const quote of quotes) {
|
||||
const key = quoteKey(frame, quote);
|
||||
if (
|
||||
(checkpoint.cursor && keyCompare(key, checkpoint.cursor) <= 0) ||
|
||||
!isDeepStrictEqual(
|
||||
active.get(quote.instrumentId),
|
||||
activeSession(config, quote.instrumentId, frame.availableAt)
|
||||
)
|
||||
) {
|
||||
invalid('Paper quote cannot advance the retained event cursor/session');
|
||||
}
|
||||
commands.push({
|
||||
commandId: JSON.stringify([
|
||||
'paper-quote',
|
||||
frame.sourceId,
|
||||
quote.instrumentId,
|
||||
quote.seriesId,
|
||||
quote.observedAt,
|
||||
quote.sourceSequence,
|
||||
]),
|
||||
key,
|
||||
body: {
|
||||
kind: 'execute',
|
||||
seriesId: quote.seriesId,
|
||||
observation: {
|
||||
kind: 'quote',
|
||||
observedAt: quote.observedAt,
|
||||
bid: quote.bid,
|
||||
ask: quote.ask,
|
||||
bidSize: quote.bidSize,
|
||||
askSize: quote.askSize,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
const observations = frame.observations.filter(row => {
|
||||
const latest = account.latestObservations.find(
|
||||
item => observationId(item) === observationId(row)
|
||||
);
|
||||
if (latest && !isDeepStrictEqual(latest, row)) {
|
||||
throw new PaperRuntimeError(
|
||||
'conflict',
|
||||
'Paper observation conflicts with its retained identity'
|
||||
);
|
||||
}
|
||||
return !latest;
|
||||
});
|
||||
const latest = new Map(account.latestObservations.map(row => [row.series_id, row]));
|
||||
for (const row of observations) {
|
||||
const old = latest.get(row.series_id);
|
||||
if (
|
||||
!old ||
|
||||
row.event_time > old.event_time ||
|
||||
(row.event_time === old.event_time && row.source_sequence > old.source_sequence)
|
||||
) {
|
||||
latest.set(row.series_id, row);
|
||||
}
|
||||
}
|
||||
const ownerIds = config.policy.cadence
|
||||
.filter(cadence => observations.some(row => cadence.seriesIds.includes(row.series_id)))
|
||||
.map(cadence => cadence.ownerId)
|
||||
.sort(compareText);
|
||||
const result: CanonicalPaperInput[] = commands.map(command => ({ command, observations: [] }));
|
||||
const final = result.at(-1);
|
||||
if (!final || final.command.body.kind !== 'execute') {
|
||||
invalid('Paper frame requires a final execution quote');
|
||||
}
|
||||
final.observations = observations;
|
||||
if (ownerIds.length) {
|
||||
const identity = [frame.sourceId, frame.id, frame.sequence];
|
||||
final.decision = {
|
||||
commandId: JSON.stringify(['paper-decision', ...identity]),
|
||||
key: { ...final.command.key },
|
||||
barrierId: JSON.stringify(['paper-barrier', ...identity]),
|
||||
ownerIds,
|
||||
inputs: config.policy.observations.map(series => {
|
||||
const row = latest.get(series.seriesId);
|
||||
const timing = row && { event_time: row.event_time, available_at: row.available_at };
|
||||
return {
|
||||
series_id: series.seriesId,
|
||||
availability:
|
||||
!row || !timing
|
||||
? 'Missing'
|
||||
: frame.availableAt - row.event_time > series.staleAfterMs
|
||||
? { Stale: timing }
|
||||
: { Fresh: timing },
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ import { Server as SocketIOServer } from 'socket.io';
|
|||
import { createAnalyticsRoutes } from '../api/rest/analytics';
|
||||
import { createBacktestRoutes } from '../api/rest/backtest';
|
||||
import { createOrderRoutes } from '../api/rest/orders';
|
||||
import { createPaperRoutes } from '../api/rest/paper';
|
||||
import { createPositionRoutes } from '../api/rest/positions';
|
||||
import { setupWebSocketHandlers } from '../api/websocket';
|
||||
import type { OrchestratorServices as IServiceContainer } from '../types';
|
||||
|
|
@ -20,7 +21,10 @@ export function createRoutes(services: IServiceContainer, io?: SocketIOServer):
|
|||
return c.json({
|
||||
status: 'healthy',
|
||||
service: 'orchestrator',
|
||||
mode: modeManager?.getCurrentMode() || 'unknown',
|
||||
mode: services.custom?.CanonicalPaperRuntime
|
||||
? 'paper'
|
||||
: modeManager?.getCurrentMode() || 'unknown',
|
||||
execution: services.custom?.CanonicalPaperRuntime ? 'canonical-paper' : 'legacy',
|
||||
timestamp: new Date().toISOString(),
|
||||
});
|
||||
});
|
||||
|
|
@ -28,6 +32,12 @@ export function createRoutes(services: IServiceContainer, io?: SocketIOServer):
|
|||
// Mount REST API routes
|
||||
app.get('/api/recovery', async c => {
|
||||
try {
|
||||
if (services.custom?.CanonicalPaperRuntime) {
|
||||
return c.json({
|
||||
engine: 'canonical-paper',
|
||||
...(await services.custom.CanonicalPaperRuntime.status()),
|
||||
});
|
||||
}
|
||||
const execution = services.custom?.ExecutionService;
|
||||
if (!execution) {
|
||||
return c.json({ error: 'Execution gateway unavailable' }, 503);
|
||||
|
|
@ -38,13 +48,23 @@ export function createRoutes(services: IServiceContainer, io?: SocketIOServer):
|
|||
return c.json({ error: 'Strategy recovery status unavailable' }, 503);
|
||||
}
|
||||
});
|
||||
app.route('/api/orders', createOrderRoutes(services));
|
||||
app.route('/api/positions', createPositionRoutes(services));
|
||||
app.route('/api/paper', createPaperRoutes(services));
|
||||
if (services.custom?.CanonicalPaperRuntime) {
|
||||
// Legacy numeric gateways cannot operate on a controlled canonical account.
|
||||
const unavailable = new Hono().all('*', c =>
|
||||
c.json({ error: 'Legacy account gateway unavailable in canonical paper mode' }, 409)
|
||||
);
|
||||
app.route('/api/orders', unavailable);
|
||||
app.route('/api/positions', unavailable);
|
||||
} else {
|
||||
app.route('/api/orders', createOrderRoutes(services));
|
||||
app.route('/api/positions', createPositionRoutes(services));
|
||||
}
|
||||
app.route('/api/analytics', createAnalyticsRoutes(services));
|
||||
app.route('/api/backtest', createBacktestRoutes(services));
|
||||
|
||||
// Setup WebSocket handlers if Socket.IO is provided
|
||||
if (io) {
|
||||
if (io && !services.custom?.CanonicalPaperRuntime) {
|
||||
setupWebSocketHandlers(io, services);
|
||||
services.logger.info('WebSocket handlers configured');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import { ServiceContainerBuilder } from '@stock-bot/di';
|
||||
import type { StockAppConfig } from '@stock-bot/stock-config';
|
||||
import { paperConfigurationSchema } from './contracts/paper-runtime';
|
||||
import { validatePaperConfiguration } from './paper/feed';
|
||||
import {
|
||||
assertSupportedComposition,
|
||||
registerOrchestratorServices,
|
||||
|
|
@ -12,11 +14,30 @@ export async function createContainer(
|
|||
config: StockAppConfig,
|
||||
options: { role?: OrchestratorRole } = {}
|
||||
) {
|
||||
const role = options.role === undefined ? 'paper' : options.role;
|
||||
const settings = config.services?.orchestrator;
|
||||
if (settings?.defaultMode === 'live') {
|
||||
throw new Error('Live trading is disabled: no real broker adapter exists');
|
||||
}
|
||||
const role =
|
||||
options.role === undefined
|
||||
? settings?.defaultMode === 'backtest'
|
||||
? 'research-only'
|
||||
: 'paper'
|
||||
: options.role;
|
||||
const configuredEngine = config.services?.orchestrator?.backtesting?.useRustEngine;
|
||||
const useRustEngine = configuredEngine === undefined ? true : configuredEngine;
|
||||
// Fail before opening connections as well as before registering runtime services.
|
||||
assertSupportedComposition(role, useRustEngine);
|
||||
if (settings?.canonicalPaper !== undefined && role !== 'paper') {
|
||||
throw new Error('Canonical paper configuration requires a paper composition');
|
||||
}
|
||||
const canonicalPaper =
|
||||
settings?.canonicalPaper === undefined
|
||||
? undefined
|
||||
: validatePaperConfiguration(paperConfigurationSchema.parse(settings.canonicalPaper));
|
||||
if (canonicalPaper && !config.database?.postgres?.enabled) {
|
||||
throw new Error('Canonical paper requires durable PostgreSQL custody');
|
||||
}
|
||||
const container = await new ServiceContainerBuilder()
|
||||
.withConfig(config)
|
||||
.withOptions({
|
||||
|
|
@ -35,6 +56,8 @@ export async function createContainer(
|
|||
allowSyntheticData: config.services?.orchestrator?.backtesting?.allowSyntheticData ?? false,
|
||||
syntheticSeed: config.services?.orchestrator?.backtesting?.syntheticSeed ?? 42,
|
||||
nativeExecutionTimeoutMs: config.services?.orchestrator?.backtesting?.executionTimeoutMs,
|
||||
canonicalPaper,
|
||||
paperTradingCapital: settings?.paperTradingCapital,
|
||||
});
|
||||
return container.resolve('serviceContainer') as OrchestratorServices;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -56,6 +56,7 @@ export type OrchestratorServices = import('@stock-bot/services').IServiceContain
|
|||
BacktestEngine: import('./backtest/execution-engine').BacktestExecutionEngine;
|
||||
PaperTradingManager: import('./paper/PaperTradingManager').PaperTradingManager;
|
||||
ModeManager: import('./core/ModeManager').ModeManager;
|
||||
CanonicalPaperRuntime: import('./contracts/paper-runtime').PaperRuntime;
|
||||
}>;
|
||||
};
|
||||
export type { BacktestResult } from './backtest/RustBacktestAdapter';
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue