feat(research): prepare stored data by declared sessions (RP03)
This commit is contained in:
parent
302ba60e53
commit
d2b78eacdf
10 changed files with 805 additions and 72 deletions
|
|
@ -1,6 +1,9 @@
|
|||
import { z } from 'zod';
|
||||
import { parseHistoricalDatasetMetadataV2 } from '@stock-bot/research/datasets';
|
||||
import type { CanonicalStoredSourcePreparation } from '@stock-bot/stock-config/canonical-research';
|
||||
import {
|
||||
declaredStoredSourceWindows,
|
||||
type CanonicalStoredSourcePreparation,
|
||||
} from '@stock-bot/stock-config/canonical-research';
|
||||
import type { HistoricalDatasetInputV2, HistoricalDatasetMetadataV2 } from '@stock-bot/types';
|
||||
import {
|
||||
HistoricalStorageError,
|
||||
|
|
@ -16,7 +19,9 @@ export class StoredDatasetPreparationError extends Error {
|
|||
super(message);
|
||||
}
|
||||
}
|
||||
const bodySchema = z.object({ metadata: z.unknown() }).strict();
|
||||
const bodySchema = z
|
||||
.object({ metadata: z.unknown(), selection: z.literal('declared-sessions').optional() })
|
||||
.strict();
|
||||
function freeze<T>(value: T): T {
|
||||
if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
|
||||
Object.values(value).forEach(freeze);
|
||||
|
|
@ -24,10 +29,16 @@ function freeze<T>(value: T): T {
|
|||
}
|
||||
return value;
|
||||
}
|
||||
function metadataFromBody(body: unknown): HistoricalDatasetMetadataV2 {
|
||||
function metadataFromBody(body: unknown): {
|
||||
metadata: HistoricalDatasetMetadataV2;
|
||||
selection?: 'declared-sessions';
|
||||
} {
|
||||
try {
|
||||
const parsed = bodySchema.parse(body);
|
||||
return freeze(parseHistoricalDatasetMetadataV2(parsed.metadata));
|
||||
return {
|
||||
metadata: freeze(parseHistoricalDatasetMetadataV2(parsed.metadata)),
|
||||
...(parsed.selection ? { selection: parsed.selection } : {}),
|
||||
};
|
||||
} catch (error) {
|
||||
const path = error instanceof z.ZodError ? error.issues[0]?.path.join('.') : undefined;
|
||||
throw new StoredDatasetPreparationError(
|
||||
|
|
@ -39,14 +50,14 @@ function metadataFromBody(body: unknown): HistoricalDatasetMetadataV2 {
|
|||
}
|
||||
}
|
||||
|
||||
/** Materialize one explicit stored EOD query. Captured bytes, not this mutable query, are retained. */
|
||||
/** Capture the explicit range or declared session windows. Retention never repeats these reads. */
|
||||
export async function prepareStoredDataset(
|
||||
body: unknown,
|
||||
storage: Pick<StorageService, 'getHistoricalBars'>,
|
||||
signal: AbortSignal
|
||||
): Promise<CanonicalStoredSourcePreparation> {
|
||||
signal.throwIfAborted();
|
||||
const metadata = metadataFromBody(body);
|
||||
const { metadata, selection } = metadataFromBody(body);
|
||||
const series = metadata.series[0];
|
||||
if (
|
||||
!series ||
|
||||
|
|
@ -64,60 +75,79 @@ export async function prepareStoredDataset(
|
|||
'Stored source supports one EOD raw 1m/5m/1h series with interval-start timestamps and declared interval-end-assumption availability'
|
||||
);
|
||||
}
|
||||
let rows;
|
||||
try {
|
||||
rows = await storage.getHistoricalBars(
|
||||
series.instrumentId,
|
||||
new Date(metadata.bounds.warmupStart),
|
||||
new Date(metadata.bounds.tradeEnd),
|
||||
series.interval,
|
||||
{ adjustment: 'raw', timestamp: 'utc-instant' },
|
||||
signal,
|
||||
'eod'
|
||||
const windows =
|
||||
selection === 'declared-sessions'
|
||||
? declaredStoredSourceWindows(metadata)
|
||||
: [{ start: metadata.bounds.warmupStart, end: metadata.bounds.tradeEnd }];
|
||||
if (!windows.length) {
|
||||
throw new StoredDatasetPreparationError(
|
||||
422,
|
||||
'No declared sessions intersect the requested bounds'
|
||||
);
|
||||
} catch (error) {
|
||||
}
|
||||
const captured: Array<
|
||||
Omit<HistoricalDatasetInputV2['bars'][number], 'timestamp' | 'sourceSequence'> & {
|
||||
timestamp: number;
|
||||
}
|
||||
> = [];
|
||||
for (const window of windows) {
|
||||
signal.throwIfAborted();
|
||||
if (error instanceof HistoricalStorageError && error.code === 'missing-range') {
|
||||
let rows;
|
||||
try {
|
||||
rows = await storage.getHistoricalBars(
|
||||
series.instrumentId,
|
||||
new Date(window.start),
|
||||
new Date(window.end),
|
||||
series.interval,
|
||||
{ adjustment: 'raw', timestamp: 'utc-instant' },
|
||||
signal,
|
||||
'eod'
|
||||
);
|
||||
} catch (error) {
|
||||
signal.throwIfAborted();
|
||||
if (error instanceof HistoricalStorageError && error.code === 'missing-range') {
|
||||
throw new StoredDatasetPreparationError(404, 'No stored EOD bars in the requested range');
|
||||
}
|
||||
if (error instanceof HistoricalStorageError && error.code === 'provider-unavailable') {
|
||||
throw new StoredDatasetPreparationError(503, 'EOD historical storage is unavailable');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
if (!rows.length) {
|
||||
throw new StoredDatasetPreparationError(404, 'No stored EOD bars in the requested range');
|
||||
}
|
||||
if (error instanceof HistoricalStorageError && error.code === 'provider-unavailable') {
|
||||
throw new StoredDatasetPreparationError(503, 'EOD historical storage is unavailable');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
if (!rows.length) {
|
||||
throw new StoredDatasetPreparationError(404, 'No stored EOD bars in the requested range');
|
||||
}
|
||||
for (const row of rows) {
|
||||
if (
|
||||
row.symbol !== series.instrumentId ||
|
||||
row.source !== 'eod' ||
|
||||
row.interpolated === true ||
|
||||
!(row.timestamp instanceof Date) ||
|
||||
!Number.isSafeInteger(row.timestamp.getTime()) ||
|
||||
row.timestamp.getTime() < metadata.bounds.warmupStart ||
|
||||
row.timestamp.getTime() >= metadata.bounds.tradeEnd
|
||||
) {
|
||||
throw new Error('Stored source returned inconsistent bar identity or range');
|
||||
}
|
||||
}
|
||||
const input: HistoricalDatasetInputV2 = freeze({
|
||||
metadata,
|
||||
// Ordinal is deterministic adapter ordering, not a vendor publication sequence.
|
||||
bars: [...rows]
|
||||
.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime())
|
||||
.map((row, sourceSequence) => ({
|
||||
for (const row of rows) {
|
||||
if (
|
||||
row.symbol !== series.instrumentId ||
|
||||
row.source !== 'eod' ||
|
||||
row.interpolated === true ||
|
||||
!(row.timestamp instanceof Date) ||
|
||||
!Number.isSafeInteger(row.timestamp.getTime()) ||
|
||||
row.timestamp.getTime() < window.start ||
|
||||
row.timestamp.getTime() >= window.end
|
||||
) {
|
||||
throw new Error('Stored source returned inconsistent bar identity or range');
|
||||
}
|
||||
// Snapshot scalars now: a subsequent asynchronous read may reuse mutable adapter rows.
|
||||
captured.push({
|
||||
seriesId: series.id,
|
||||
timestamp: row.timestamp.getTime(),
|
||||
sourceSequence,
|
||||
open: row.open,
|
||||
high: row.high,
|
||||
low: row.low,
|
||||
close: row.close,
|
||||
volume: row.volume,
|
||||
...(row.vwap === undefined ? {} : { vwap: row.vwap }),
|
||||
})),
|
||||
});
|
||||
}
|
||||
}
|
||||
const input: HistoricalDatasetInputV2 = freeze({
|
||||
metadata,
|
||||
// Ordinal is deterministic adapter ordering, not a vendor publication sequence.
|
||||
bars: captured
|
||||
.sort((a, b) => a.timestamp - b.timestamp)
|
||||
.map((row, sourceSequence) => ({ ...row, sourceSequence })),
|
||||
});
|
||||
let preparation;
|
||||
try {
|
||||
|
|
@ -132,5 +162,5 @@ export async function prepareStoredDataset(
|
|||
throw error;
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
return freeze({ input, preparation });
|
||||
return freeze({ input, preparation, ...(selection ? { selection } : {}) });
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue