T-146: M2.3f — QuestDB bars_1m intraday reader for MarketDataStore.bars (timeframe: '1m'): Vault-fenced, parameterized planBars1mQuery + batch iterator over an injected PGWire query port in libs/research/src/market-data-store-questdb.ts (pure, no new deps, no live QuestDB)
This commit is contained in:
parent
8f1bfbe9f1
commit
cfbcb51bd3
3 changed files with 1152 additions and 0 deletions
|
|
@ -4,6 +4,7 @@ export * from './event-panel';
|
|||
export * from './feature-library';
|
||||
export * from './market-data-store';
|
||||
export * from './market-data-store-duckdb';
|
||||
export * from './market-data-store-questdb';
|
||||
export * from './signal-panel';
|
||||
export * from './signal-study';
|
||||
export * from './trial-ledger';
|
||||
|
|
|
|||
448
libs/research/src/market-data-store-questdb.ts
Normal file
448
libs/research/src/market-data-store-questdb.ts
Normal file
|
|
@ -0,0 +1,448 @@
|
|||
/**
|
||||
* Pure, dependency-free QuestDB `bars_1m` query planner and injected-executor
|
||||
* intraday reader for `MarketDataStore.bars` (`timeframe: '1m'`,
|
||||
* `design/DATA-CONTRACTS.md` §3.B & §4).
|
||||
*
|
||||
* Browser-safe and dependency-free: zero `node:*` imports, zero `pg` or
|
||||
* `@stock-bot/questdb` dependency, zero bare `process` access. SQL execution
|
||||
* is injected via {@link QuestDbQueryExecutor}, which is structurally
|
||||
* compatible with `QuestDBClient.query(sql, params)`.
|
||||
*
|
||||
* Storage and point-in-time semantics:
|
||||
* - `bars_1m` stores split-unadjusted raw 1-minute OHLCV, nullable `vwap`,
|
||||
* `listing_id` (`SYMBOL`, canonical positive decimal string), `known_at`
|
||||
* (`TIMESTAMP`), and designated timestamp `ts` (`TIMESTAMP`,
|
||||
* `PARTITION BY MONTH`).
|
||||
* - Only `adjustment: 'raw'` is supported; `'split'` and `'total'` throw
|
||||
* {@link MarketDataStoreNotImplementedError}.
|
||||
* - Query bounds are Vault-fenced via {@link applyVaultFence} before SQL
|
||||
* planning. Every user-supplied value is bound via `$1..$n` placeholders;
|
||||
* only ordinal placeholder tokens are generated in SQL text.
|
||||
* - `ts` and `known_at` are projected as `CAST(... AS LONG)` (UTC epoch
|
||||
* microseconds) and verified in exact microseconds against the fenced bounds
|
||||
* before converting to epoch milliseconds or yielding any batch.
|
||||
*/
|
||||
|
||||
import {
|
||||
type BarBatch,
|
||||
type BarRecord,
|
||||
type FencedTimeRange,
|
||||
type MarketDataStore,
|
||||
MarketDataStoreValidationError,
|
||||
type VaultFenceContext,
|
||||
applyVaultFence,
|
||||
} from './market-data-store';
|
||||
import { MarketDataStoreNotImplementedError } from './market-data-store-duckdb';
|
||||
|
||||
const INT32_MAX = 2_147_483_647;
|
||||
const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000;
|
||||
const CANONICAL_POSITIVE_INT_RE = /^[1-9]\d*$/;
|
||||
const CANONICAL_SIGNED_INT_RE = /^-?(?:0|[1-9]\d*)$/;
|
||||
|
||||
/** Default maximum number of `BarRecord` rows yielded per `BarBatch`. */
|
||||
export const DEFAULT_QUESTDB_BARS_BATCH_SIZE = 50_000;
|
||||
|
||||
/** Input query type derived from `MarketDataStore['bars']`. */
|
||||
export type QuestDbBars1mQuery = Parameters<MarketDataStore['bars']>[0];
|
||||
|
||||
/**
|
||||
* Injected PGWire SQL executor port, structurally compatible with
|
||||
* `QuestDBClient.query(sql, params)` in `libs/data/questdb/src/client.ts`.
|
||||
*/
|
||||
export interface QuestDbQueryExecutor {
|
||||
query(
|
||||
sql: string,
|
||||
params: readonly unknown[]
|
||||
): Promise<{ readonly rows: readonly Record<string, unknown>[] }>;
|
||||
}
|
||||
|
||||
/** Pure output of {@link planBars1mQuery}. */
|
||||
export interface PlannedQuestDbBars1mQuery {
|
||||
readonly sql: string;
|
||||
readonly params: readonly string[];
|
||||
readonly fence: FencedTimeRange;
|
||||
}
|
||||
|
||||
/** Configuration for {@link createQuestDbIntradayBarsReader}. */
|
||||
export interface QuestDbIntradayBarsReaderOptions extends VaultFenceContext {
|
||||
readonly executor: QuestDbQueryExecutor;
|
||||
/** Maximum number of bars per yielded `BarBatch`. Defaults to `50_000`. */
|
||||
readonly batchSize?: number;
|
||||
}
|
||||
|
||||
interface InternalPlannedBars1mQuery {
|
||||
readonly planned: PlannedQuestDbBars1mQuery;
|
||||
readonly requestedListingIds: ReadonlySet<number>;
|
||||
}
|
||||
|
||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function validateVaultCutoffTs(vaultCutoffTs: unknown): number {
|
||||
if (
|
||||
typeof vaultCutoffTs !== 'number' ||
|
||||
!Number.isSafeInteger(vaultCutoffTs) ||
|
||||
Math.abs(vaultCutoffTs) > MAX_ECMASCRIPT_EPOCH_MS ||
|
||||
vaultCutoffTs <= -MAX_ECMASCRIPT_EPOCH_MS
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid epoch millisecond timestamp for "vaultCutoffTs": ${String(vaultCutoffTs)}.`,
|
||||
'vaultCutoffTs'
|
||||
);
|
||||
}
|
||||
return vaultCutoffTs === 0 ? 0 : vaultCutoffTs;
|
||||
}
|
||||
|
||||
function validatePositiveInt32ListingIds(raw: unknown): number[] {
|
||||
if (!Array.isArray(raw) || raw.length === 0) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Expected a non-empty array of positive INT32 listing IDs for "listingIds".',
|
||||
'listingIds'
|
||||
);
|
||||
}
|
||||
|
||||
const seen = new Set<number>();
|
||||
const normalized: number[] = [];
|
||||
for (let i = 0; i < raw.length; i += 1) {
|
||||
const id: unknown = raw[i];
|
||||
if (
|
||||
typeof id !== 'number' ||
|
||||
!Number.isSafeInteger(id) ||
|
||||
id < 1 ||
|
||||
id > INT32_MAX
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid positive INT32 listing ID at listingIds[${i}]: ${String(id)}.`,
|
||||
'listingIds'
|
||||
);
|
||||
}
|
||||
if (!seen.has(id)) {
|
||||
seen.add(id);
|
||||
normalized.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
normalized.sort((a, b) => a - b);
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function formatUtcIsoMs(epochMs: number): string {
|
||||
return new Date(epochMs).toISOString();
|
||||
}
|
||||
|
||||
function planBars1mQueryInternal(
|
||||
q: QuestDbBars1mQuery,
|
||||
ctx: VaultFenceContext
|
||||
): InternalPlannedBars1mQuery {
|
||||
if (!isPlainRecord(ctx)) {
|
||||
throw new MarketDataStoreValidationError('Expected a VaultFenceContext object.', 'ctx');
|
||||
}
|
||||
if (!isPlainRecord(q)) {
|
||||
throw new MarketDataStoreValidationError('Expected a bars query object.', 'query');
|
||||
}
|
||||
|
||||
const timeframe: unknown = q.timeframe;
|
||||
if (timeframe !== '1m') {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid bars timeframe "${String(timeframe)}". Expected '1m'.`,
|
||||
'timeframe'
|
||||
);
|
||||
}
|
||||
|
||||
const adjustment: unknown = q.adjustment;
|
||||
if (adjustment === 'split' || adjustment === 'total') {
|
||||
throw new MarketDataStoreNotImplementedError(
|
||||
'bars',
|
||||
`Adjustment '${adjustment}' is not supported for intraday '1m' bars; bars_1m stores raw split-unadjusted values.`
|
||||
);
|
||||
}
|
||||
if (adjustment !== 'raw') {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid bars adjustment "${String(adjustment)}". Expected 'raw'.`,
|
||||
'adjustment'
|
||||
);
|
||||
}
|
||||
|
||||
const sortedListingIds = validatePositiveInt32ListingIds(q.listingIds);
|
||||
|
||||
const fence = applyVaultFence(
|
||||
{
|
||||
from: q.from,
|
||||
to: q.to,
|
||||
asOf: q.asOf,
|
||||
scope: q.scope,
|
||||
},
|
||||
{
|
||||
vaultCutoffTs: ctx.vaultCutoffTs,
|
||||
vaultOperatorAuthorized: ctx.vaultOperatorAuthorized === true,
|
||||
}
|
||||
);
|
||||
|
||||
const listingPlaceholders = sortedListingIds.map((_, index) => `$${index + 3}`).join(', ');
|
||||
const asOfPlaceholder = `$${sortedListingIds.length + 3}`;
|
||||
|
||||
const sql =
|
||||
'SELECT listing_id, CAST(ts AS LONG) AS ts_us, open, high, low, close, volume, vwap, CAST(known_at AS LONG) AS known_at_us ' +
|
||||
'FROM bars_1m ' +
|
||||
`WHERE ts >= $1 AND ts <= $2 AND listing_id IN (${listingPlaceholders}) AND known_at <= ${asOfPlaceholder} ` +
|
||||
'ORDER BY ts, listing_id';
|
||||
|
||||
const params: string[] = [
|
||||
formatUtcIsoMs(fence.fromMs),
|
||||
formatUtcIsoMs(fence.toMs),
|
||||
...sortedListingIds.map(id => String(id)),
|
||||
formatUtcIsoMs(fence.asOfMs),
|
||||
];
|
||||
|
||||
return {
|
||||
planned: { sql, params, fence },
|
||||
requestedListingIds: new Set(sortedListingIds),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure, Vault-fenced, parameterized SQL planner for QuestDB `bars_1m`.
|
||||
*
|
||||
* Binds `from`, `to`, and `asOf` as exact millisecond UTC ISO-8601 strings and
|
||||
* deduplicated, numerically sorted positive INT32 `listingIds` as canonical
|
||||
* decimal `SYMBOL` strings.
|
||||
*/
|
||||
export function planBars1mQuery(
|
||||
q: QuestDbBars1mQuery,
|
||||
ctx: VaultFenceContext
|
||||
): PlannedQuestDbBars1mQuery {
|
||||
return planBars1mQueryInternal(q, ctx).planned;
|
||||
}
|
||||
|
||||
function parseListingIdSymbol(
|
||||
row: Record<string, unknown>,
|
||||
rowIndex: number,
|
||||
requestedListingIds: ReadonlySet<number>
|
||||
): number {
|
||||
const raw = row.listing_id;
|
||||
if (typeof raw !== 'string' || !CANONICAL_POSITIVE_INT_RE.test(raw)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid bars_1m listing_id SYMBOL in result row ${rowIndex}: ${String(raw)}.`,
|
||||
'listing_id'
|
||||
);
|
||||
}
|
||||
const parsed = Number(raw);
|
||||
if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > INT32_MAX) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Out-of-range bars_1m listing_id SYMBOL in result row ${rowIndex}: "${raw}".`,
|
||||
'listing_id'
|
||||
);
|
||||
}
|
||||
if (!requestedListingIds.has(parsed)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Unexpected unrequested listing_id ${parsed} in bars_1m result row ${rowIndex}.`,
|
||||
'listing_id'
|
||||
);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function parseTimestampMicros(
|
||||
row: Record<string, unknown>,
|
||||
column: 'ts_us' | 'known_at_us',
|
||||
field: 'ts' | 'known_at',
|
||||
rowIndex: number
|
||||
): bigint {
|
||||
const raw = row[column];
|
||||
if (typeof raw === 'bigint') {
|
||||
return raw;
|
||||
}
|
||||
if (typeof raw === 'string' && CANONICAL_SIGNED_INT_RE.test(raw)) {
|
||||
return BigInt(raw);
|
||||
}
|
||||
if (typeof raw === 'number' && Number.isSafeInteger(raw)) {
|
||||
return BigInt(raw);
|
||||
}
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid bars_1m timestamp column "${column}" in result row ${rowIndex}: ${String(raw)}.`,
|
||||
field
|
||||
);
|
||||
}
|
||||
|
||||
function microsToEpochMs(us: bigint, field: 'ts' | 'known_at', rowIndex: number): number {
|
||||
const quotient = us / 1000n;
|
||||
const remainder = us % 1000n;
|
||||
const msBigInt = remainder < 0n ? quotient - 1n : quotient;
|
||||
const ms = Number(msBigInt);
|
||||
if (!Number.isSafeInteger(ms) || Math.abs(ms) > MAX_ECMASCRIPT_EPOCH_MS) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Out-of-range bars_1m timestamp "${field}" (${us.toString()} us) in result row ${rowIndex}.`,
|
||||
field
|
||||
);
|
||||
}
|
||||
return ms === 0 ? 0 : ms;
|
||||
}
|
||||
|
||||
function readRequiredFiniteNumber(
|
||||
row: Record<string, unknown>,
|
||||
key: 'open' | 'high' | 'low' | 'close' | 'volume',
|
||||
rowIndex: number
|
||||
): number {
|
||||
const val = row[key];
|
||||
if (typeof val !== 'number' || !Number.isFinite(val)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid numeric column "${key}" in bars_1m result row ${rowIndex}: ${String(val)}.`,
|
||||
key
|
||||
);
|
||||
}
|
||||
return val === 0 ? 0 : val;
|
||||
}
|
||||
|
||||
function readNullableFiniteNumber(
|
||||
row: Record<string, unknown>,
|
||||
key: 'vwap',
|
||||
rowIndex: number
|
||||
): number | null {
|
||||
const val = row[key];
|
||||
if (val === null || val === undefined) {
|
||||
return null;
|
||||
}
|
||||
if (typeof val !== 'number' || !Number.isFinite(val)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid nullable numeric column "${key}" in bars_1m result row ${rowIndex}: ${String(val)}.`,
|
||||
key
|
||||
);
|
||||
}
|
||||
return val === 0 ? 0 : val;
|
||||
}
|
||||
|
||||
function mapBars1mRows(
|
||||
rows: readonly Record<string, unknown>[],
|
||||
fence: FencedTimeRange,
|
||||
requestedListingIds: ReadonlySet<number>
|
||||
): BarRecord[] {
|
||||
const fromUs = BigInt(fence.fromMs) * 1000n;
|
||||
const toUs = BigInt(fence.toMs) * 1000n;
|
||||
const asOfUs = BigInt(fence.asOfMs) * 1000n;
|
||||
|
||||
const out: BarRecord[] = new Array(rows.length);
|
||||
for (let i = 0; i < rows.length; i += 1) {
|
||||
const raw = rows[i];
|
||||
if (!isPlainRecord(raw)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Executor returned a non-object bar row at index ${i}.`,
|
||||
'rows'
|
||||
);
|
||||
}
|
||||
|
||||
const listingId = parseListingIdSymbol(raw, i, requestedListingIds);
|
||||
const tsUs = parseTimestampMicros(raw, 'ts_us', 'ts', i);
|
||||
if (tsUs < fromUs || tsUs > toUs) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Row ${i} timestamp ts (${tsUs.toString()} us) is outside fenced range [${fromUs.toString()}, ${toUs.toString()}] us.`,
|
||||
'ts'
|
||||
);
|
||||
}
|
||||
|
||||
const knownAtUs = parseTimestampMicros(raw, 'known_at_us', 'known_at', i);
|
||||
if (knownAtUs > asOfUs) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Row ${i} availability timestamp known_at (${knownAtUs.toString()} us) exceeds fenced asOf (${asOfUs.toString()} us).`,
|
||||
'known_at'
|
||||
);
|
||||
}
|
||||
|
||||
out[i] = {
|
||||
listingId,
|
||||
ts: microsToEpochMs(tsUs, 'ts', i),
|
||||
open: readRequiredFiniteNumber(raw, 'open', i),
|
||||
high: readRequiredFiniteNumber(raw, 'high', i),
|
||||
low: readRequiredFiniteNumber(raw, 'low', i),
|
||||
close: readRequiredFiniteNumber(raw, 'close', i),
|
||||
volume: readRequiredFiniteNumber(raw, 'volume', i),
|
||||
vwap: readNullableFiniteNumber(raw, 'vwap', i),
|
||||
knownAt: microsToEpochMs(knownAtUs, 'known_at', i),
|
||||
};
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a read-only intraday `bars` reader backed by an injected
|
||||
* {@link QuestDbQueryExecutor} over QuestDB `bars_1m`.
|
||||
*
|
||||
* Validates all inputs and applies the Vault fence before invoking
|
||||
* `executor.query(...)`. Validates and maps all returned rows (including
|
||||
* exact-microsecond defence-in-depth checks against `fence`) before yielding
|
||||
* batches of at most `batchSize` rows (default `50_000`).
|
||||
*/
|
||||
export function createQuestDbIntradayBarsReader(
|
||||
options: QuestDbIntradayBarsReaderOptions
|
||||
): Pick<MarketDataStore, 'bars'> {
|
||||
if (!isPlainRecord(options)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Expected a QuestDbIntradayBarsReaderOptions object.',
|
||||
'options'
|
||||
);
|
||||
}
|
||||
|
||||
const executor: unknown = options.executor;
|
||||
if (!isPlainRecord(executor) || typeof executor.query !== 'function') {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Expected `executor` with a `query(sql, params)` method.',
|
||||
'executor'
|
||||
);
|
||||
}
|
||||
const typedExecutor = executor as unknown as QuestDbQueryExecutor;
|
||||
|
||||
const vaultCutoffTs = validateVaultCutoffTs(options.vaultCutoffTs);
|
||||
|
||||
if (
|
||||
options.vaultOperatorAuthorized !== undefined &&
|
||||
typeof options.vaultOperatorAuthorized !== 'boolean'
|
||||
) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid vaultOperatorAuthorized "${String(options.vaultOperatorAuthorized)}". Expected a boolean.`,
|
||||
'vaultOperatorAuthorized'
|
||||
);
|
||||
}
|
||||
|
||||
const batchSize = options.batchSize ?? DEFAULT_QUESTDB_BARS_BATCH_SIZE;
|
||||
if (typeof batchSize !== 'number' || !Number.isSafeInteger(batchSize) || batchSize < 1) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
`Invalid batchSize "${String(options.batchSize)}". Expected a positive safe integer.`,
|
||||
'batchSize'
|
||||
);
|
||||
}
|
||||
|
||||
const planCtx: VaultFenceContext = {
|
||||
vaultCutoffTs,
|
||||
vaultOperatorAuthorized: options.vaultOperatorAuthorized === true,
|
||||
};
|
||||
|
||||
return {
|
||||
async *bars(q: QuestDbBars1mQuery): AsyncIterable<BarBatch> {
|
||||
const { planned, requestedListingIds } = planBars1mQueryInternal(q, planCtx);
|
||||
const result: unknown = await typedExecutor.query(planned.sql, [...planned.params]);
|
||||
if (!isPlainRecord(result) || !Array.isArray(result.rows)) {
|
||||
throw new MarketDataStoreValidationError(
|
||||
'Executor returned a malformed result; expected `{ rows: Record<string, unknown>[] }`.',
|
||||
'rows'
|
||||
);
|
||||
}
|
||||
|
||||
const mapped = mapBars1mRows(
|
||||
result.rows as readonly Record<string, unknown>[],
|
||||
planned.fence,
|
||||
requestedListingIds
|
||||
);
|
||||
if (mapped.length === 0) {
|
||||
return;
|
||||
}
|
||||
if (mapped.length <= batchSize) {
|
||||
yield { rows: mapped };
|
||||
return;
|
||||
}
|
||||
for (let offset = 0; offset < mapped.length; offset += batchSize) {
|
||||
yield { rows: mapped.slice(offset, offset + batchSize) };
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue