feat(research): add owner-aware ledger and intraday storage

Implement reviewed F02/D02: exact owner accounting, atomic funding checks, idempotent receipts and ledger checkpoints; connect existing EOD intraday storage through validated research admission without active financial-engine cutover.
This commit is contained in:
Boki 2026-10-22 21:16:53 -04:00
parent b4af840d4e
commit b65acccd91
15 changed files with 2704 additions and 104 deletions

View file

@ -21,6 +21,33 @@ export interface HistoricalBar {
source?: 'eod' | 'questdb' | 'synthetic';
adjustedClose?: number;
}
export type HistoricalStorageProvider = 'questdb' | 'eod';
export type HistoricalStorageErrorCode =
| 'unsupported-provider'
| 'unsupported-interval'
| 'provider-unavailable'
| 'missing-range';
/** Storage routing failures are distinct from invalid records and transport failures. */
export class HistoricalStorageError extends Error {
constructor(
readonly code: HistoricalStorageErrorCode,
message: string,
readonly provider?: HistoricalStorageProvider | 'synthetic'
) {
super(message);
this.name = 'HistoricalStorageError';
}
}
const historicalIntervals = ['1m', '5m', '15m', '1h', '1d'] as const;
const eodIntradayCollections: Readonly<Record<string, string | undefined>> = {
'1m': 'eodIntraday1M',
'5m': 'eodIntraday5M',
'1h': 'eodIntraday1H',
};
export class StorageService {
private questdb: QuestDBClient | null = null;
private postgres: PostgresClient | null = null;
@ -166,6 +193,59 @@ export class StorageService {
);
}
/** Adapter support and current connectivity, not evidence of stored range coverage. */
getHistoricalCapabilities() {
return [
{
provider: 'questdb' as const,
configured: this.questdb !== null,
connected: this.questdb?.connected ?? false,
intervals: [...historicalIntervals],
},
{
provider: 'eod' as const,
configured: this.mongodb !== null,
connected: this.mongodb?.connected ?? false,
intervals: ['1m', '5m', '1h', '1d'] as const,
},
];
}
private selectHistoricalProvider(
requested: HistoricalStorageProvider | 'auto'
): HistoricalStorageProvider | 'synthetic' {
if (!['auto', 'questdb', 'eod'].includes(requested)) {
throw new HistoricalStorageError('unsupported-provider', 'Unsupported historical provider');
}
if (requested === 'questdb' || (requested === 'auto' && this.questdb)) {
if (!this.questdb) {
throw new HistoricalStorageError(
'provider-unavailable',
'QuestDB historical storage is unavailable',
'questdb'
);
}
return 'questdb';
}
if (requested === 'eod' || (requested === 'auto' && this.mongodb)) {
if (!this.mongodb) {
throw new HistoricalStorageError(
'provider-unavailable',
'EOD historical storage is unavailable',
'eod'
);
}
return 'eod';
}
if (this.options.allowSyntheticData) {
return 'synthetic';
}
throw new HistoricalStorageError(
'provider-unavailable',
'No historical data store configured; synthetic data requires explicit opt-in'
);
}
/** One historical-data policy for native and TypeScript execution. */
async getHistoricalBars(
symbol: string,
@ -176,7 +256,8 @@ export class StorageService {
adjustment: 'raw',
timestamp: interval === '1d' ? 'utc-session-date' : 'utc-instant',
},
signal?: AbortSignal
signal?: AbortSignal,
provider: HistoricalStorageProvider | 'auto' = 'auto'
): Promise<HistoricalBar[]> {
signal?.throwIfAborted();
parseInstrumentId(symbol);
@ -187,8 +268,8 @@ export class StorageService {
) {
throw new Error('Invalid historical date range');
}
if (!['1m', '5m', '15m', '1h', '1d'].includes(interval)) {
throw new Error('Unsupported historical interval');
if (!(historicalIntervals as readonly string[]).includes(interval)) {
throw new HistoricalStorageError('unsupported-interval', 'Unsupported historical interval');
}
if (
(interval === '1d') !== (policy.timestamp === 'utc-session-date') ||
@ -199,7 +280,15 @@ export class StorageService {
'Daily ranges must use UTC midnight session dates; intraday ranges use UTC instants'
);
}
const rows = await this.readHistoricalBars(symbol, startTime, endTime, interval);
const selectedProvider = this.selectHistoricalProvider(provider);
const rows = await this.readHistoricalBars(
symbol,
startTime,
endTime,
interval,
selectedProvider,
signal
);
signal?.throwIfAborted();
const bars: HistoricalBar[] = [];
let processed = 0;
@ -264,7 +353,11 @@ export class StorageService {
signal?.throwIfAborted();
bars.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
if (!bars.length) {
throw new Error(`No historical data for ${symbol}`);
throw new HistoricalStorageError(
'missing-range',
`No historical data for ${symbol} in the requested range`,
selectedProvider
);
}
if (
bars.some(
@ -281,13 +374,12 @@ export class StorageService {
symbol: string,
startTime: Date,
endTime: Date,
interval: string
interval: string,
provider: HistoricalStorageProvider | 'synthetic',
signal?: AbortSignal
): Promise<HistoricalBar[]> {
// If QuestDB is available, use real data
if (this.questdb) {
if (!['1m', '5m', '15m', '1h', '1d'].includes(interval)) {
throw new Error('Unsupported historical interval');
}
// Select once, before reading: empty ranges/errors never switch providers.
if (provider === 'questdb' && this.questdb) {
const result = await this.questdb.query<HistoricalBar>(
`SELECT * FROM bars_${interval} WHERE symbol = $1 AND timestamp >= $2 AND timestamp < $3 ORDER BY timestamp`,
[symbol, startTime, endTime]
@ -295,11 +387,85 @@ export class StorageService {
return result.rows.map(row => ({ ...row, source: 'questdb' }));
}
if (this.mongodb) {
if (interval !== '1d') {
throw new Error('Daily provider storage cannot satisfy an intraday request');
}
if (provider === 'eod' && this.mongodb) {
const identity = parseInstrumentId(symbol);
if (interval !== '1d') {
const collection = eodIntradayCollections[interval];
if (!collection) {
throw new HistoricalStorageError(
'unsupported-interval',
`EOD historical storage does not support ${interval}`,
'eod'
);
}
// fetchIntraday writes raw bar-start UTC Unix seconds, not local datetime labels.
// https://eodhd.com/financial-apis/intraday-historical-data-api
// This instant is not publication time; availability/calendar policy belongs to datasets.
const records = await this.mongodb.find<{
symbol: string;
exchange: string;
eodSearchCode: string;
timestamp: number;
open: number;
high: number;
low: number;
close: number;
volume: number;
}>(
collection,
{
eodSearchCode: identity.id,
timestamp: { $gte: startTime.getTime() / 1000, $lt: endTime.getTime() / 1000 },
},
{
sort: { timestamp: 1 },
projection: {
symbol: 1,
exchange: 1,
eodSearchCode: 1,
timestamp: 1,
open: 1,
high: 1,
low: 1,
close: 1,
volume: 1,
},
}
);
signal?.throwIfAborted();
const bars: HistoricalBar[] = [];
for (const record of records) {
if (
record.eodSearchCode !== identity.id ||
record.symbol !== identity.symbol ||
record.exchange !== identity.exchange
) {
throw new Error(`Historical instrument identity mismatch for ${symbol}`);
}
const milliseconds = record.timestamp * 1000;
if (
!Number.isSafeInteger(record.timestamp) ||
!Number.isSafeInteger(milliseconds) ||
!Number.isFinite(new Date(milliseconds).getTime())
) {
throw new Error(`Invalid historical Unix-seconds timestamp for ${symbol}`);
}
bars.push({
symbol,
timestamp: new Date(milliseconds),
open: record.open,
high: record.high,
low: record.low,
close: record.close,
volume: record.volume,
source: 'eod',
});
if (bars.length % PREPARATION_BATCH_SIZE === 0) {
await preparationCheckpoint(signal);
}
}
return bars;
}
const prices = await this.mongodb.find<{
symbol: string;
exchange: string;
@ -366,11 +532,6 @@ export class StorageService {
};
});
}
if (!this.options.allowSyntheticData) {
throw new Error(
'No historical data store configured; synthetic data requires explicit opt-in'
);
}
return this.generateMockBars(symbol, startTime, endTime, interval).map(bar => ({
...bar,
source: 'synthetic',