feat(research): add financial contracts and availability-aware datasets

Implement reviewed F01/D01 foundations without changing active trading runtimes. Validate strict Rust/TypeScript financial wire contracts, decimal postings, versioned datasets, explicit calendars, provenance, and v1 compatibility.
This commit is contained in:
Boki 2026-10-22 20:51:25 -04:00
parent 243e9ab43f
commit b4af840d4e
25 changed files with 4071 additions and 43 deletions

View file

@ -0,0 +1,493 @@
/**
* F01 wire shapes only. Rust owns all financial arithmetic and transitions.
* These validators never calculate fills, fees, basis, reservations or equity.
* Market/feature arrays stay numeric; this string boundary is for postings.
*/
export const FINANCIAL_PROTOCOL_VERSION = 1 as const;
export const MAX_FINANCIAL_POSTING = '792281625142643375935.43950335';
declare const financialDecimal: unique symbol;
export type FinancialDecimal = string & { readonly [financialDecimal]: true };
export interface DecisionIdentity {
ownerId: string;
decisionId: string;
sequence: number;
}
export interface RiskSessionIdentity {
calendarId: string;
calendarRevision: string;
sessionId: string;
/** Unix milliseconds, not an inferred processing-time date. */
startsAt: number;
}
type Side = 'buy' | 'sell';
type TimeInForce = 'GTC' | 'DAY' | 'IOC' | 'FOK';
type EngineCommandBody =
| {
kind: 'applyFill';
decision: DecisionIdentity;
orderId: string;
fillId: string;
instrumentId: string;
side: Side;
quantity: FinancialDecimal;
price: FinancialDecimal;
fee: { feeId: string; amount: FinancialDecimal };
}
| { kind: 'mark'; instrumentId: string; price: FinancialDecimal }
| { kind: 'riskSessionBoundary'; riskSession: RiskSessionIdentity };
/** Engine internal only. NEVER accept this as the strategy submission API. */
export interface EngineFinancialCommand {
version: 1;
sessionId: string;
accountId: string;
/** Scoped to (sessionId, accountId); F02 implements retry/conflict enforcement. */
commandId: string;
eventTime: number;
body: EngineCommandBody;
}
export type FinancialOrderIntent =
| {
kind: 'market';
orderId: string;
instrumentId: string;
side: Side;
quantity: FinancialDecimal;
timeInForce: TimeInForce;
}
| {
kind: 'limit';
orderId: string;
instrumentId: string;
side: Side;
quantity: FinancialDecimal;
price: FinancialDecimal;
timeInForce: TimeInForce;
}
| { kind: 'cancel'; orderId: string };
export type FinancialStrategyIntent =
| { mode: 'target'; targets: { instrumentId: string; quantity: FinancialDecimal }[] }
| { mode: 'orders'; orders: FinancialOrderIntent[] };
/** A member of a shared barrier, never a direct financial mutation. */
export interface FinancialStrategyDecision {
version: 1;
sessionId: string;
barrierId: string;
revision: number;
decision: DecisionIdentity;
intent: FinancialStrategyIntent;
}
/**
* Economic projection ONLY, not a complete restorable session snapshot.
* F02/F04/F07 own receipts, reservations, open orders, risk/replay/strategy/RNG
* state. Remaining cost is authoritative; rounded average cost is absent.
*/
export interface FinancialSnapshot {
version: 1;
sessionId: string;
accountId: string;
revision: number;
baseCurrency: string;
reserveOwnerId: string;
cash: FinancialDecimal;
positions: {
ownerId: string;
instrumentId: string;
quantity: FinancialDecimal;
remainingCost: FinancialDecimal;
realizedGrossPnl: FinancialDecimal;
}[];
fees: { ownerId: string; amount: FinancialDecimal }[];
riskSession: RiskSessionIdentity;
}
export type FinancialEffect =
| {
kind: 'fillApplied';
ownerId: string;
orderId: string;
fillId: string;
instrumentId: string;
price: FinancialDecimal;
cashDelta: FinancialDecimal;
quantityDelta: FinancialDecimal;
releasedBasis: FinancialDecimal;
realizedGrossPnl: FinancialDecimal;
}
| { kind: 'feeApplied'; ownerId: string; fillId: string; feeId: string; amount: FinancialDecimal }
| { kind: 'markUpdated'; instrumentId: string; price: FinancialDecimal }
| { kind: 'riskSessionChanged'; riskSession: RiskSessionIdentity }
| { kind: 'rejected'; code: string };
export interface FinancialEffects {
version: 1;
sessionId: string;
accountId: string;
commandId: string;
eventTime: number;
revision: number;
/** Transition order is authoritative. Do not sort. */
effects: FinancialEffect[];
}
function invalid(message: string): never {
throw new Error(`Invalid financial contract: ${message}`);
}
function object(value: unknown, keys: readonly string[]): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return invalid('expected object');
}
const record = value as Record<string, unknown>;
if (Object.keys(record).length !== keys.length || keys.some(key => !Object.hasOwn(record, key))) {
return invalid(`expected exactly ${keys.join(', ')}`);
}
return record;
}
function tag(value: unknown, key: string): unknown {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return invalid('expected tagged object');
}
return (value as Record<string, unknown>)[key];
}
function id(value: unknown): string {
// Preserve provider/instrument IDs; dataset membership is checked at admission.
if (
typeof value !== 'string' ||
value.length === 0 ||
Array.from(value).some(character => {
const code = character.charCodeAt(0);
// Array.from keeps valid surrogate pairs together. Lone surrogates cannot
// round-trip through Rust's UTF-8 String.
return (
code < 32 || code === 127 || (character.length === 1 && code >= 0xd800 && code <= 0xdfff)
);
})
) {
return invalid('expected nonempty well-formed identity without control characters');
}
return value;
}
function integer(value: unknown, signed = false): number {
if (typeof value !== 'number' || !Number.isSafeInteger(value) || (!signed && value < 0)) {
return invalid('expected a safe integer');
}
return value === 0 ? 0 : value;
}
function version(value: unknown): 1 {
if (integer(value) !== FINANCIAL_PROTOCOL_VERSION) {
return invalid('unsupported financial protocol version');
}
return FINANCIAL_PROTOCOL_VERSION;
}
function array<T>(value: unknown, parse: (item: unknown) => T): T[] {
if (!Array.isArray(value)) {
return invalid('expected array');
}
return Array.from(value, parse);
}
function choice<T extends string>(value: unknown, choices: readonly T[]): T {
if (typeof value !== 'string' || !choices.includes(value as T)) {
return invalid(`expected ${choices.join(' | ')}`);
}
return value as T;
}
/** Lexical precision/range validation and padding only: no financial arithmetic. */
export function parseFinancialDecimal(value: unknown): FinancialDecimal {
if (
typeof value !== 'string' ||
value.match(/^-?(0|[1-9][0-9]*)(\.[0-9]{1,8})?$/)?.[0] !== value
) {
return invalid('expected plain decimal string with at most 8 fractional digits');
}
const negative = value.startsWith('-');
const [whole = '', fraction = ''] = (negative ? value.slice(1) : value).split('.');
const magnitude = `${whole}.${fraction.padEnd(8, '0')}`;
const maxWhole = MAX_FINANCIAL_POSTING.slice(0, MAX_FINANCIAL_POSTING.indexOf('.'));
if (
whole.length > maxWhole.length ||
(whole.length === maxWhole.length && magnitude > MAX_FINANCIAL_POSTING)
) {
return invalid('financial posting exceeds the fixed-8 decimal range');
}
return `${negative && magnitude !== '0.00000000' ? '-' : ''}${magnitude}` as FinancialDecimal;
}
function decimal(
value: unknown,
sign: 'any' | 'nonnegative' | 'positive' = 'any'
): FinancialDecimal {
const parsed = parseFinancialDecimal(value);
if (
(sign !== 'any' && parsed.startsWith('-')) ||
(sign === 'positive' && parsed === '0.00000000')
) {
return invalid(`expected ${sign} posting`);
}
return parsed;
}
function decisionIdentity(value: unknown): DecisionIdentity {
const row = object(value, ['ownerId', 'decisionId', 'sequence']);
return {
ownerId: id(row.ownerId),
decisionId: id(row.decisionId),
sequence: integer(row.sequence),
};
}
function riskSession(value: unknown): RiskSessionIdentity {
const row = object(value, ['calendarId', 'calendarRevision', 'sessionId', 'startsAt']);
return {
calendarId: id(row.calendarId),
calendarRevision: id(row.calendarRevision),
sessionId: id(row.sessionId),
startsAt: integer(row.startsAt, true),
};
}
function commandBody(value: unknown): EngineCommandBody {
switch (tag(value, 'kind')) {
case 'applyFill': {
const row = object(value, [
'kind',
'decision',
'orderId',
'fillId',
'instrumentId',
'side',
'quantity',
'price',
'fee',
]);
const fee = object(row.fee, ['feeId', 'amount']);
return {
kind: 'applyFill',
decision: decisionIdentity(row.decision),
orderId: id(row.orderId),
fillId: id(row.fillId),
instrumentId: id(row.instrumentId),
side: choice(row.side, ['buy', 'sell']),
quantity: decimal(row.quantity, 'positive'),
price: decimal(row.price, 'positive'),
fee: { feeId: id(fee.feeId), amount: decimal(fee.amount, 'nonnegative') },
};
}
case 'mark': {
const row = object(value, ['kind', 'instrumentId', 'price']);
return {
kind: 'mark',
instrumentId: id(row.instrumentId),
price: decimal(row.price, 'positive'),
};
}
case 'riskSessionBoundary': {
const row = object(value, ['kind', 'riskSession']);
return { kind: 'riskSessionBoundary', riskSession: riskSession(row.riskSession) };
}
default:
return invalid('unsupported engine command');
}
}
export function parseEngineFinancialCommand(value: unknown): EngineFinancialCommand {
const row = object(value, [
'version',
'sessionId',
'accountId',
'commandId',
'eventTime',
'body',
]);
return {
version: version(row.version),
sessionId: id(row.sessionId),
accountId: id(row.accountId),
commandId: id(row.commandId),
eventTime: integer(row.eventTime, true),
body: commandBody(row.body),
};
}
function orderIntent(value: unknown): FinancialOrderIntent {
const kind = choice(tag(value, 'kind'), ['market', 'limit', 'cancel']);
if (kind === 'cancel') {
const row = object(value, ['kind', 'orderId']);
return { kind, orderId: id(row.orderId) };
}
const row = object(value, [
'kind',
'orderId',
'instrumentId',
'side',
'quantity',
'timeInForce',
...(kind === 'limit' ? ['price'] : []),
]);
const common = {
orderId: id(row.orderId),
instrumentId: id(row.instrumentId),
side: choice(row.side, ['buy', 'sell']),
quantity: decimal(row.quantity, 'positive'),
timeInForce: choice(row.timeInForce, ['GTC', 'DAY', 'IOC', 'FOK']),
};
return kind === 'limit'
? { kind, ...common, price: decimal(row.price, 'positive') }
: { kind, ...common };
}
function strategyIntent(value: unknown): FinancialStrategyIntent {
switch (tag(value, 'mode')) {
case 'target': {
const row = object(value, ['mode', 'targets']);
return {
mode: 'target',
targets: array(row.targets, item => {
const target = object(item, ['instrumentId', 'quantity']);
return {
instrumentId: id(target.instrumentId),
quantity: decimal(target.quantity, 'nonnegative'),
};
}),
};
}
case 'orders': {
const row = object(value, ['mode', 'orders']);
return { mode: 'orders', orders: array(row.orders, orderIntent) };
}
default:
return invalid('unsupported strategy mode');
}
}
export function parseFinancialStrategyDecision(value: unknown): FinancialStrategyDecision {
const row = object(value, [
'version',
'sessionId',
'barrierId',
'revision',
'decision',
'intent',
]);
return {
version: version(row.version),
sessionId: id(row.sessionId),
barrierId: id(row.barrierId),
revision: integer(row.revision),
decision: decisionIdentity(row.decision),
intent: strategyIntent(row.intent),
};
}
export function parseFinancialSnapshot(value: unknown): FinancialSnapshot {
const row = object(value, [
'version',
'sessionId',
'accountId',
'revision',
'baseCurrency',
'reserveOwnerId',
'cash',
'positions',
'fees',
'riskSession',
]);
return {
version: version(row.version),
sessionId: id(row.sessionId),
accountId: id(row.accountId),
revision: integer(row.revision),
baseCurrency: id(row.baseCurrency),
reserveOwnerId: id(row.reserveOwnerId),
cash: decimal(row.cash, 'nonnegative'),
positions: array(row.positions, item => {
const position = object(item, [
'ownerId',
'instrumentId',
'quantity',
'remainingCost',
'realizedGrossPnl',
]);
return {
ownerId: id(position.ownerId),
instrumentId: id(position.instrumentId),
quantity: decimal(position.quantity, 'nonnegative'),
remainingCost: decimal(position.remainingCost, 'nonnegative'),
realizedGrossPnl: decimal(position.realizedGrossPnl),
};
}),
fees: array(row.fees, item => {
const fee = object(item, ['ownerId', 'amount']);
return { ownerId: id(fee.ownerId), amount: decimal(fee.amount, 'nonnegative') };
}),
riskSession: riskSession(row.riskSession),
};
}
function effect(value: unknown): FinancialEffect {
switch (tag(value, 'kind')) {
case 'fillApplied': {
const row = object(value, [
'kind',
'ownerId',
'orderId',
'fillId',
'instrumentId',
'price',
'cashDelta',
'quantityDelta',
'releasedBasis',
'realizedGrossPnl',
]);
return {
kind: 'fillApplied',
ownerId: id(row.ownerId),
orderId: id(row.orderId),
fillId: id(row.fillId),
instrumentId: id(row.instrumentId),
price: decimal(row.price, 'positive'),
cashDelta: decimal(row.cashDelta),
quantityDelta: decimal(row.quantityDelta),
releasedBasis: decimal(row.releasedBasis, 'nonnegative'),
realizedGrossPnl: decimal(row.realizedGrossPnl),
};
}
case 'feeApplied': {
const row = object(value, ['kind', 'ownerId', 'fillId', 'feeId', 'amount']);
return {
kind: 'feeApplied',
ownerId: id(row.ownerId),
fillId: id(row.fillId),
feeId: id(row.feeId),
amount: decimal(row.amount, 'nonnegative'),
};
}
case 'markUpdated': {
const row = object(value, ['kind', 'instrumentId', 'price']);
return {
kind: 'markUpdated',
instrumentId: id(row.instrumentId),
price: decimal(row.price, 'positive'),
};
}
case 'riskSessionChanged': {
const row = object(value, ['kind', 'riskSession']);
return { kind: 'riskSessionChanged', riskSession: riskSession(row.riskSession) };
}
case 'rejected': {
const row = object(value, ['kind', 'code']);
return { kind: 'rejected', code: id(row.code) };
}
default:
return invalid('unsupported financial effect');
}
}
export function parseFinancialEffects(value: unknown): FinancialEffects {
const row = object(value, [
'version',
'sessionId',
'accountId',
'commandId',
'eventTime',
'revision',
'effects',
]);
return {
version: version(row.version),
sessionId: id(row.sessionId),
accountId: id(row.accountId),
commandId: id(row.commandId),
eventTime: integer(row.eventTime, true),
revision: integer(row.revision),
effects: array(row.effects, effect),
};
}

View file

@ -115,3 +115,117 @@ export interface HistoricalDataset {
vwap: number;
}[];
}
/** V2 is additive: legacy snapshots and their hashes retain the v1 contract above. */
export interface HistoricalCalendarV2 {
readonly id: string;
readonly venue: string;
readonly timeZone: string;
readonly revision: string;
readonly source: string;
/** Session-label coverage [startDate, endDate); no inferred holiday/session rules. */
readonly startDate: string;
readonly endDate: string;
readonly sessions: readonly {
readonly date: string;
readonly open: number;
readonly close: number;
}[];
}
export interface HistoricalSeriesV2 {
readonly id: string;
readonly instrumentId: string;
readonly interval: '1m' | '5m' | '15m' | '1h' | '1d';
readonly calendarId: string;
readonly venue: string;
readonly source: { readonly provider: string; readonly revision: string };
readonly timestamp: 'session-date' | 'interval-start' | 'interval-end';
readonly availability: 'explicit' | 'interval-end-assumption';
readonly adjustment: 'raw' | 'provider-adjusted';
}
export interface HistoricalDatasetMetadataV2 {
readonly calendars: readonly HistoricalCalendarV2[];
readonly series: readonly HistoricalSeriesV2[];
/** Exactly one execution feed per included instrument; other series are feature inputs. */
readonly executionSeries: readonly { readonly instrumentId: string; readonly seriesId: string }[];
/** Interval coverage [warmupStart, tradeEnd], with starts strictly before tradeEnd.
* Replay must restrict decisions/fills to [tradeStart, tradeEnd); an observation
* available exactly at tradeEnd may provide a terminal mark, not a new decision.
*/
readonly bounds: {
readonly warmupStart: number;
readonly tradeStart: number;
readonly tradeEnd: number;
};
readonly universe: {
readonly selection: 'point-in-time' | 'current-constituents' | 'unknown';
readonly asOf: number | null;
readonly revision: string;
readonly instrumentIds: readonly string[];
};
readonly corporateActions: readonly {
readonly instrumentId: string;
readonly status: 'unknown' | 'action-free' | 'known-actions';
readonly start: number;
readonly end: number;
readonly revision: string;
readonly actions: readonly {
readonly effectiveAt: number;
readonly kind: 'split' | 'dividend' | 'other';
readonly reference: string;
}[];
}[];
}
export interface HistoricalBarV2 {
readonly seriesId: string;
readonly instrumentId: string;
readonly intervalStart: number;
readonly intervalEnd: number;
readonly eventTime: number;
readonly availableAt: number;
readonly sourceSequence: number;
readonly open: number;
readonly high: number;
readonly low: number;
readonly close: number;
readonly volume: number;
readonly vwap: number | null;
}
export interface HistoricalDatasetManifestV2 extends HistoricalDatasetMetadataV2 {
readonly version: 2;
readonly hash: string;
readonly normalizationRevision: 'historical-normalization-v2';
readonly parentDatasetHash: string | null;
readonly volumePolicy: 'reported';
readonly qualityPolicy: 'reject-invalid-no-interpolation';
readonly intradayPolicy: 'full-duration-session-contained';
readonly eligibility: 'eligible' | 'exploratory' | 'ineligible';
readonly limitations: readonly string[];
readonly barCount: number;
}
export interface HistoricalDatasetV2 {
readonly manifest: HistoricalDatasetManifestV2;
readonly bars: readonly HistoricalBarV2[];
}
export interface HistoricalDatasetInputV2 {
readonly metadata: HistoricalDatasetMetadataV2;
readonly bars: readonly {
readonly seriesId: string;
/** Daily YYYY-MM-DD label, otherwise explicit epoch milliseconds per series policy. */
readonly timestamp: string | number;
readonly availableAt?: number;
readonly sourceSequence: number;
readonly open: number;
readonly high: number;
readonly low: number;
readonly close: number;
readonly volume: number;
readonly vwap?: number | null;
}[];
}

View file

@ -94,6 +94,27 @@ export {
parseReferenceDataResetRequest,
} from './reference-data';
export type { ReferenceDataResetRequest, ReferenceDataResetScope } from './reference-data';
export {
FINANCIAL_PROTOCOL_VERSION,
MAX_FINANCIAL_POSTING,
parseFinancialDecimal,
parseEngineFinancialCommand,
parseFinancialStrategyDecision,
parseFinancialSnapshot,
parseFinancialEffects,
} from './financial-engine';
export type {
FinancialDecimal,
DecisionIdentity,
RiskSessionIdentity,
EngineFinancialCommand,
FinancialOrderIntent,
FinancialStrategyIntent,
FinancialStrategyDecision,
FinancialSnapshot,
FinancialEffect,
FinancialEffects,
} from './financial-engine';
export {
parseInstrumentId,
HistoricalDataRequestError,
@ -105,3 +126,12 @@ export type {
HistoricalDataset,
HistoricalDatasetManifest,
} from './historical-data';
export type {
HistoricalCalendarV2,
HistoricalSeriesV2,
HistoricalDatasetMetadataV2,
HistoricalBarV2,
HistoricalDatasetManifestV2,
HistoricalDatasetV2,
HistoricalDatasetInputV2,
} from './historical-data';