682 lines
21 KiB
TypeScript
682 lines
21 KiB
TypeScript
/**
|
|
* 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 Table,
|
|
type TableRow,
|
|
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;
|
|
|
|
/** Output columns for QuestDB `fx_1m` queries. */
|
|
export const FX_1M_COLUMNS = ['pair', 'ts', 'open', 'high', 'low', 'close', 'source'] as const;
|
|
|
|
const FX_1M_ACCEPTED_PAIRS: ReadonlySet<string> = new Set(['USDCAD', 'USD.CAD']);
|
|
|
|
/** Input query type derived from `MarketDataStore['bars']`. */
|
|
export type QuestDbBars1mQuery = Parameters<MarketDataStore['bars']>[0];
|
|
|
|
/** Input query type derived from `MarketDataStore['fx']`. */
|
|
export type QuestDbFx1mQuery = Parameters<MarketDataStore['fx']>[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;
|
|
}
|
|
|
|
/** Pure output of {@link planFx1mQuery}. */
|
|
export interface PlannedQuestDbFx1mQuery {
|
|
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;
|
|
}
|
|
|
|
/** Configuration for {@link createQuestDbIntradayFxReader}. */
|
|
export interface QuestDbIntradayFxReaderOptions extends VaultFenceContext {
|
|
readonly executor: QuestDbQueryExecutor;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
/**
|
|
* Pure, Vault-fenced, parameterized SQL planner for QuestDB `fx_1m`.
|
|
*
|
|
* Always fences under `scope: 'vault_fenced'` with `vaultOperatorAuthorized: false`
|
|
* and binds both `'USDCAD'` and `'USD.CAD'` pair symbols via `$3, $4`.
|
|
*/
|
|
export function planFx1mQuery(
|
|
q: QuestDbFx1mQuery,
|
|
ctx: VaultFenceContext
|
|
): PlannedQuestDbFx1mQuery {
|
|
if (!isPlainRecord(ctx)) {
|
|
throw new MarketDataStoreValidationError('Expected a VaultFenceContext object.', 'ctx');
|
|
}
|
|
if (!isPlainRecord(q)) {
|
|
throw new MarketDataStoreValidationError('Expected an fx query object.', 'query');
|
|
}
|
|
|
|
const timeframe: unknown = q.timeframe;
|
|
if (timeframe !== '1m') {
|
|
throw new MarketDataStoreValidationError(
|
|
`Invalid fx timeframe "${String(timeframe)}". Expected '1m'.`,
|
|
'timeframe'
|
|
);
|
|
}
|
|
|
|
const pair: unknown = q.pair;
|
|
if (pair !== 'USD.CAD') {
|
|
throw new MarketDataStoreValidationError(
|
|
`Unsupported FX pair "${String(pair)}". Expected 'USD.CAD'.`,
|
|
'pair'
|
|
);
|
|
}
|
|
|
|
const fence = applyVaultFence(
|
|
{
|
|
from: q.from,
|
|
to: q.to,
|
|
scope: 'vault_fenced',
|
|
},
|
|
{
|
|
vaultCutoffTs: ctx.vaultCutoffTs,
|
|
vaultOperatorAuthorized: false,
|
|
}
|
|
);
|
|
|
|
const sql =
|
|
'SELECT pair, CAST(ts AS LONG) AS ts_us, open, high, low, close, source ' +
|
|
'FROM fx_1m ' +
|
|
'WHERE ts >= $1 AND ts <= $2 AND pair IN ($3, $4) ' +
|
|
'ORDER BY ts ASC';
|
|
|
|
const params: string[] = [
|
|
formatUtcIsoMs(fence.fromMs),
|
|
formatUtcIsoMs(fence.toMs),
|
|
'USDCAD',
|
|
'USD.CAD',
|
|
];
|
|
|
|
return { sql, params, fence };
|
|
}
|
|
|
|
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,
|
|
rounding: 'floor' | 'ceil'
|
|
): number {
|
|
const quotient = us / 1000n;
|
|
const remainder = us % 1000n;
|
|
const msBigInt =
|
|
rounding === 'ceil'
|
|
? remainder > 0n
|
|
? quotient + 1n
|
|
: quotient
|
|
: 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, 'floor'),
|
|
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),
|
|
// Round sub-millisecond availability up so replay never treats a bar as known before arrival.
|
|
knownAt: microsToEpochMs(knownAtUs, 'known_at', i, 'ceil'),
|
|
};
|
|
}
|
|
|
|
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 === undefined ? DEFAULT_QUESTDB_BARS_BATCH_SIZE : options.batchSize;
|
|
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) };
|
|
}
|
|
},
|
|
};
|
|
}
|
|
|
|
function mapFx1mRows(
|
|
rows: readonly Record<string, unknown>[],
|
|
fence: FencedTimeRange,
|
|
vaultCutoffTs: number
|
|
): Table {
|
|
const fromUs = BigInt(fence.fromMs) * 1000n;
|
|
const toUs = BigInt(fence.toMs) * 1000n;
|
|
const vaultCutoffUs = BigInt(vaultCutoffTs) * 1000n;
|
|
|
|
const out: TableRow[] = 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 fx_1m row at index ${i}.`,
|
|
'rows'
|
|
);
|
|
}
|
|
|
|
const pair = raw.pair;
|
|
if (typeof pair !== 'string' || !FX_1M_ACCEPTED_PAIRS.has(pair)) {
|
|
throw new MarketDataStoreValidationError(
|
|
`Invalid fx_1m pair in result row ${i}: ${String(pair)}.`,
|
|
'pair'
|
|
);
|
|
}
|
|
|
|
const tsUs = parseTimestampMicros(raw, 'ts_us', 'ts', i);
|
|
if (tsUs < fromUs || tsUs > toUs || tsUs >= vaultCutoffUs) {
|
|
throw new MarketDataStoreValidationError(
|
|
`Row ${i} timestamp ts (${tsUs.toString()} us) is outside fenced range [${fromUs.toString()}, ${toUs.toString()}] us (cutoff ${vaultCutoffUs.toString()} us).`,
|
|
'ts'
|
|
);
|
|
}
|
|
|
|
const source = raw.source;
|
|
if (typeof source !== 'string' || source.length === 0) {
|
|
throw new MarketDataStoreValidationError(
|
|
`Invalid fx_1m source in result row ${i}: ${String(source)}.`,
|
|
'source'
|
|
);
|
|
}
|
|
|
|
out[i] = {
|
|
pair,
|
|
ts: microsToEpochMs(tsUs, 'ts', i, 'floor'),
|
|
open: readRequiredFiniteNumber(raw, 'open', i),
|
|
high: readRequiredFiniteNumber(raw, 'high', i),
|
|
low: readRequiredFiniteNumber(raw, 'low', i),
|
|
close: readRequiredFiniteNumber(raw, 'close', i),
|
|
source,
|
|
};
|
|
}
|
|
|
|
return {
|
|
columns: [...FX_1M_COLUMNS],
|
|
rows: out,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Creates a read-only Vault-fenced intraday `fx` reader backed by an injected
|
|
* {@link QuestDbQueryExecutor} over QuestDB `fx_1m`.
|
|
*/
|
|
export function createQuestDbIntradayFxReader(
|
|
options: QuestDbIntradayFxReaderOptions
|
|
): Pick<MarketDataStore, 'fx'> {
|
|
if (!isPlainRecord(options)) {
|
|
throw new MarketDataStoreValidationError(
|
|
'Expected a QuestDbIntradayFxReaderOptions 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 planCtx: VaultFenceContext = {
|
|
vaultCutoffTs,
|
|
vaultOperatorAuthorized: false,
|
|
};
|
|
|
|
return {
|
|
async fx(q: QuestDbFx1mQuery): Promise<Table> {
|
|
const planned = planFx1mQuery(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'
|
|
);
|
|
}
|
|
return mapFx1mRows(
|
|
result.rows as readonly Record<string, unknown>[],
|
|
planned.fence,
|
|
vaultCutoffTs
|
|
);
|
|
},
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Creates a combined read-only intraday `bars` + `fx` reader backed by an
|
|
* injected {@link QuestDbQueryExecutor} over QuestDB `bars_1m` and `fx_1m`.
|
|
*/
|
|
export function createQuestDbIntradayReader(
|
|
options: QuestDbIntradayBarsReaderOptions
|
|
): Pick<MarketDataStore, 'bars' | 'fx'> {
|
|
const barsReader = createQuestDbIntradayBarsReader(options);
|
|
const fxReader = createQuestDbIntradayFxReader(options);
|
|
return {
|
|
bars(q) {
|
|
return barsReader.bars(q);
|
|
},
|
|
fx(q) {
|
|
return fxReader.fx(q);
|
|
},
|
|
};
|
|
}
|