T-181: M2.1q — Bar-derived session-date adapter for the MCP copilot event_study calendars: SessionDatesPort over the Vault-fenced MarketDataStore.bars (timeframe: '1d', caller-configured reference listings per calendar code) in libs/research/src/mcp/adapters/bar-session-dates.ts (no new deps, no live DuckDB/Postgres, no entrypoint/bin)
This commit is contained in:
parent
e7c0089d1f
commit
fbc0aa0725
4 changed files with 807 additions and 0 deletions
|
|
@ -276,6 +276,7 @@ Server-only, dependency-free JSON-RPC 2.0 / Model Context Protocol core exported
|
|||
- **`createPostgresListingCalendarPort({ executor, schema? })`** and **`createExchangeCalendarResolver({ listingCalendars, sessionDates, earlyCloses? })`** (exported from `@stock-bot/research/mcp` alongside `ListingCalendarPort`, `SessionDatesPort`, `EarlyCloseOverrides`, `PostgresListingCalendarError`, and `ExchangeCalendarResolverError`) implement `EventStudyExchangeCalendarResolver` for `createEventStudyTool` with zero `node:*` imports and zero runtime `pg` dependency.
|
||||
- **Injected ports & fail-closed validation:** `createPostgresListingCalendarPort` issues one read-only parameterized `SELECT` joining `listing.mic` to `exchange.mic` (`WHERE l.listing_id = ANY($1::integer[])`), validating `executor.query` (`INVALID_EXECUTOR`), optional `schema` (`^[a-z_][a-z0-9_]*$`, `INVALID_SCHEMA`), and returned rows (`INVALID_ROW`). `SessionDatesPort.listSessionDates({ calendarCode, fromDate, toDate })` is called once per distinct calendar code in sorted order; the resolver fails closed with no partial result on missing, unrequested, or conflicting listing mappings or on malformed, duplicate, unsorted, or out-of-window session dates. Empty `listingIds` returns empty `{ calendars, listingCalendarId }` with zero port calls.
|
||||
- **Supported DST range & default half-day close:** Session close timestamps convert Eastern Time (`America/New_York` / `America/Toronto`) to UTC epoch milliseconds across `1976-01-01` through `2030-12-31` inclusive (matching `tools/curate-etl/src/session_close.rs` across the `1976–1986`, `1987–2006`, and `2007–2030` DST eras) and throw `ExchangeCalendarResolverError('UNSUPPORTED_DATE')` outside that range. Optional `earlyCloses` (`{ [calendarCode]: { [YYYY-MM-DD]: minuteOfDayEastern } }`, integer minutes in `1..=960`, e.g. `780` for `13:00 ET`) overrides the close on listed dates; when `earlyCloses` is omitted, every session closes at `16:00 ET` and exchange half-days are treated as full `16:00 ET` trading days.
|
||||
- **Bar-derived `SessionDatesPort` (`createBarSessionDatesPort({ store, referenceListingIds })`):** Exported from `@stock-bot/research/mcp` alongside `BarSessionDatesPortOptions` and `BarSessionDatesError`. Keys in `referenceListingIds` are exact `exchange.calendar_code` strings (e.g. `XNYS`, `XTSE`) mapped to non-empty, duplicate-free arrays of positive INT32 reference listing IDs whose daily bars define that exchange's session dates; the caller owns reference-listing coverage so gaps do not omit real sessions. Each `listSessionDates` call queries `store.bars({ listingIds, timeframe: '1d', from, to, adjustment: 'raw' })` once with `scope` and `asOf` omitted so the store's default `'vault_fenced'` scope applies (`'vault_evaluation_only'` is never passed), propagates store errors (including `VaultHoldoutFenceError`) unchanged, derives UTC session dates from `BarRecord.ts` (`Math.floor(ts / MS_PER_DAY)`), and fails closed on unknown calendars, malformed queries, or invalid bars.
|
||||
|
||||
### Copilot Server
|
||||
|
||||
|
|
|
|||
278
libs/research/src/mcp/adapters/bar-session-dates.ts
Normal file
278
libs/research/src/mcp/adapters/bar-session-dates.ts
Normal file
|
|
@ -0,0 +1,278 @@
|
|||
/**
|
||||
* Bar-derived {@link SessionDatesPort} adapter for the MCP copilot `event_study`
|
||||
* exchange-calendar resolver (`createExchangeCalendarResolver`).
|
||||
*
|
||||
* Pure, dependency-free, and browser-safe: zero `node:*` imports, zero bare
|
||||
* `process` access, no `pg` dependency, and no DuckDB driver import.
|
||||
*
|
||||
* Daily bar timestamp convention:
|
||||
* - In `libs/research/src/market-data-store-duckdb.ts`, `planBars1dQuery`
|
||||
* projects `epoch_ms(b.ts) AS ts` and `mapBarRows` validates it as an integer
|
||||
* UTC epoch millisecond value on `BarRecord.ts`.
|
||||
* - In `tools/curate-etl/src/curate_bars.rs`, curated daily bars are stamped at
|
||||
* `16:00:00 America/New_York` (`16:00 ET`), which converts to `20:00:00Z`
|
||||
* (EDT) or `21:00:00Z` (EST) on the same UTC calendar date.
|
||||
* - Therefore, `Math.floor(bar.ts / MS_PER_DAY)` yields the session's integer
|
||||
* UTC day key (`formatDayKeyUtc`). Close timestamps and optional early-close
|
||||
* overrides remain owned by `createExchangeCalendarResolver`.
|
||||
*
|
||||
* Vault fence behavior:
|
||||
* - Queries `store.bars` with `timeframe: '1d'` and `adjustment: 'raw'`,
|
||||
* omitting `scope` and `asOf` so the injected store applies its default
|
||||
* `'vault_fenced'` scope. Never passes `'vault_evaluation_only'`.
|
||||
* - Errors thrown by the store (including `VaultHoldoutFenceError`) propagate
|
||||
* unchanged.
|
||||
*/
|
||||
|
||||
import type { MarketDataStore } from '../../market-data-store';
|
||||
import {
|
||||
MS_PER_DAY,
|
||||
formatDayKeyUtc,
|
||||
isPlainRecord,
|
||||
isValidEpochMs,
|
||||
isValidInt32,
|
||||
parseCalendarDayKey,
|
||||
} from '../../panel-shared';
|
||||
import type { SessionDatesPort, SessionDatesQuery } from './exchange-calendars';
|
||||
|
||||
/** Error codes thrown by {@link BarSessionDatesError}. */
|
||||
export type BarSessionDatesErrorCode =
|
||||
| 'invalid_options'
|
||||
| 'unknown_calendar'
|
||||
| 'invalid_query'
|
||||
| 'invalid_bar';
|
||||
|
||||
/** Optional error constructor metadata for {@link BarSessionDatesError}. */
|
||||
export interface BarSessionDatesErrorOptions {
|
||||
readonly cause?: unknown;
|
||||
}
|
||||
|
||||
/** Typed fail-closed error thrown by {@link createBarSessionDatesPort}. */
|
||||
export class BarSessionDatesError extends RangeError {
|
||||
readonly code: BarSessionDatesErrorCode;
|
||||
override readonly cause?: unknown;
|
||||
|
||||
constructor(
|
||||
code: BarSessionDatesErrorCode,
|
||||
message: string,
|
||||
options?: BarSessionDatesErrorOptions
|
||||
) {
|
||||
super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);
|
||||
this.name = 'BarSessionDatesError';
|
||||
this.code = code;
|
||||
if (options?.cause !== undefined) {
|
||||
this.cause = options.cause;
|
||||
}
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
/** Factory options for {@link createBarSessionDatesPort}. */
|
||||
export interface BarSessionDatesPortOptions {
|
||||
readonly store: Pick<MarketDataStore, 'bars'>;
|
||||
/**
|
||||
* Caller-configured reference listing IDs per `exchange.calendar_code`
|
||||
* (e.g. `XNYS`, `XTSE`). The union of their daily bars defines the exchange's
|
||||
* session dates.
|
||||
*/
|
||||
readonly referenceListingIds: Readonly<Record<string, readonly number[]>>;
|
||||
}
|
||||
|
||||
interface CalendarReferenceConfig {
|
||||
readonly listingIds: readonly number[];
|
||||
readonly listingIdSet: ReadonlySet<number>;
|
||||
}
|
||||
|
||||
function isPlainObjectRecord(value: unknown): value is Record<string, unknown> {
|
||||
if (typeof value !== 'object' || value === null) {
|
||||
return false;
|
||||
}
|
||||
const proto: unknown = Object.getPrototypeOf(value);
|
||||
return proto === Object.prototype || proto === null;
|
||||
}
|
||||
|
||||
function parseQueryDayKey(value: unknown, field: string): number {
|
||||
return parseCalendarDayKey(value, field, (message, cause) =>
|
||||
new BarSessionDatesError(
|
||||
'invalid_query',
|
||||
message,
|
||||
cause !== undefined ? { cause } : undefined
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function validateOptions(options: BarSessionDatesPortOptions): {
|
||||
readonly store: Pick<MarketDataStore, 'bars'>;
|
||||
readonly calendars: ReadonlyMap<string, CalendarReferenceConfig>;
|
||||
} {
|
||||
if (!isPlainRecord(options)) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_options',
|
||||
'Invalid options: expected an object with store and referenceListingIds.'
|
||||
);
|
||||
}
|
||||
|
||||
const { store, referenceListingIds } = options;
|
||||
if (typeof store !== 'object' || store === null || typeof store.bars !== 'function') {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_options',
|
||||
'Invalid "store": expected an object with a callable bars(query) method.'
|
||||
);
|
||||
}
|
||||
|
||||
if (!isPlainObjectRecord(referenceListingIds)) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_options',
|
||||
'Invalid "referenceListingIds": expected a plain object mapping calendar codes to positive INT32 listing ID arrays.'
|
||||
);
|
||||
}
|
||||
|
||||
const calendars = new Map<string, CalendarReferenceConfig>();
|
||||
const entries = Object.entries(referenceListingIds);
|
||||
|
||||
for (let i = 0; i < entries.length; i += 1) {
|
||||
const [calendarCode, rawIds] = entries[i] as [string, unknown];
|
||||
if (calendarCode.trim().length === 0 || calendarCode !== calendarCode.trim()) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_options',
|
||||
`Invalid "referenceListingIds" calendar code "${calendarCode}": expected a non-empty trimmed string.`
|
||||
);
|
||||
}
|
||||
|
||||
if (!Array.isArray(rawIds) || rawIds.length === 0) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_options',
|
||||
`Invalid "referenceListingIds.${calendarCode}": expected a non-empty array of positive 32-bit integer listing IDs.`
|
||||
);
|
||||
}
|
||||
|
||||
const copiedIds: number[] = [];
|
||||
const idSet = new Set<number>();
|
||||
|
||||
for (let j = 0; j < rawIds.length; j += 1) {
|
||||
const id: unknown = rawIds[j];
|
||||
if (!isValidInt32(id) || id <= 0) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_options',
|
||||
`Invalid "referenceListingIds.${calendarCode}[${j}]": expected a positive 32-bit integer, got ${String(id)}.`
|
||||
);
|
||||
}
|
||||
if (idSet.has(id)) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_options',
|
||||
`Duplicate listing ID ${id} in "referenceListingIds.${calendarCode}".`
|
||||
);
|
||||
}
|
||||
idSet.add(id);
|
||||
copiedIds.push(id);
|
||||
}
|
||||
|
||||
calendars.set(calendarCode, {
|
||||
listingIds: copiedIds,
|
||||
listingIdSet: idSet,
|
||||
});
|
||||
}
|
||||
|
||||
return { store, calendars };
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a {@link SessionDatesPort} backed by Vault-fenced daily bars
|
||||
* (`timeframe: '1d'`, `adjustment: 'raw'`) for caller-configured reference
|
||||
* listings per `exchange.calendar_code`.
|
||||
*/
|
||||
export function createBarSessionDatesPort(
|
||||
options: BarSessionDatesPortOptions
|
||||
): SessionDatesPort {
|
||||
const { store, calendars } = validateOptions(options);
|
||||
|
||||
return {
|
||||
async listSessionDates(query: SessionDatesQuery): Promise<readonly string[]> {
|
||||
if (!isPlainRecord(query)) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_query',
|
||||
'Invalid query: expected an object with calendarCode, fromDate, and toDate.'
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof query.calendarCode !== 'string') {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_query',
|
||||
'Invalid "calendarCode": expected a string.'
|
||||
);
|
||||
}
|
||||
|
||||
const config = calendars.get(query.calendarCode);
|
||||
if (config === undefined) {
|
||||
throw new BarSessionDatesError(
|
||||
'unknown_calendar',
|
||||
`No reference listings configured for calendarCode "${query.calendarCode}".`
|
||||
);
|
||||
}
|
||||
|
||||
const fromDayKey = parseQueryDayKey(query.fromDate, 'fromDate');
|
||||
const toDayKey = parseQueryDayKey(query.toDate, 'toDate');
|
||||
if (fromDayKey > toDayKey) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_query',
|
||||
`Invalid date window: fromDate "${query.fromDate}" is after toDate "${query.toDate}".`
|
||||
);
|
||||
}
|
||||
|
||||
const dayKeys = new Set<number>();
|
||||
const stream = store.bars({
|
||||
listingIds: config.listingIds.slice(),
|
||||
timeframe: '1d',
|
||||
from: query.fromDate,
|
||||
to: query.toDate,
|
||||
adjustment: 'raw',
|
||||
});
|
||||
|
||||
for await (const batch of stream) {
|
||||
if (!isPlainRecord(batch) || !Array.isArray(batch.rows)) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_bar',
|
||||
'Invalid bar batch: expected an object with a rows array.'
|
||||
);
|
||||
}
|
||||
|
||||
const rows = batch.rows;
|
||||
for (let i = 0; i < rows.length; i += 1) {
|
||||
const bar: unknown = rows[i];
|
||||
if (!isPlainRecord(bar)) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_bar',
|
||||
`Invalid bar row at index ${i}: expected a plain object.`
|
||||
);
|
||||
}
|
||||
|
||||
if (!isValidEpochMs(bar.ts)) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_bar',
|
||||
`Invalid bar timestamp at index ${i}: expected a finite integer epoch ms, got ${String(bar.ts)}.`
|
||||
);
|
||||
}
|
||||
|
||||
if (!isValidInt32(bar.listingId) || !config.listingIdSet.has(bar.listingId)) {
|
||||
throw new BarSessionDatesError(
|
||||
'invalid_bar',
|
||||
`Unexpected bar listingId ${String(bar.listingId)} for calendarCode "${query.calendarCode}".`
|
||||
);
|
||||
}
|
||||
|
||||
const dayKey = Math.floor(bar.ts / MS_PER_DAY);
|
||||
if (dayKey >= fromDayKey && dayKey <= toDayKey) {
|
||||
dayKeys.add(dayKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (dayKeys.size === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const sortedDayKeys = Array.from(dayKeys).sort((a, b) => a - b);
|
||||
return sortedDayKeys.map(formatDayKeyUtc);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -13,3 +13,4 @@ export * from './tools/query-data';
|
|||
export * from './tools/read-knowledge';
|
||||
export * from './tools/search-symbols';
|
||||
export * from './adapters/postgres-copilot';
|
||||
export * from './adapters/bar-session-dates';
|
||||
|
|
|
|||
527
libs/research/test/mcp-bar-session-dates.test.ts
Normal file
527
libs/research/test/mcp-bar-session-dates.test.ts
Normal file
|
|
@ -0,0 +1,527 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
type BarBatch,
|
||||
type BarRecord,
|
||||
type MarketDataStore,
|
||||
VaultHoldoutFenceError,
|
||||
} from '../src/market-data-store';
|
||||
import {
|
||||
BarSessionDatesError,
|
||||
type BarSessionDatesPortOptions,
|
||||
type ListingCalendarPort,
|
||||
type PostgresResearchCopilotServerOptions,
|
||||
type SessionDatesPort,
|
||||
createBarSessionDatesPort,
|
||||
createExchangeCalendarResolver,
|
||||
} from '@stock-bot/research/mcp';
|
||||
|
||||
type BarsQueryArg = Parameters<MarketDataStore['bars']>[0];
|
||||
|
||||
function utcMs(
|
||||
year: number,
|
||||
month: number,
|
||||
day: number,
|
||||
hour = 0,
|
||||
minute = 0,
|
||||
second = 0
|
||||
): number {
|
||||
return Date.UTC(year, month - 1, day, hour, minute, second, 0);
|
||||
}
|
||||
|
||||
function makeBar(listingId: number, dateStr: string, closeHourUtc = 21): BarRecord {
|
||||
const [y, m, d] = dateStr.split('-').map(Number) as [number, number, number];
|
||||
const ts = utcMs(y, m, d, closeHourUtc, 0, 0);
|
||||
return {
|
||||
listingId,
|
||||
ts,
|
||||
open: 100,
|
||||
high: 101,
|
||||
low: 99,
|
||||
close: 100.5,
|
||||
volume: 100_000,
|
||||
knownAt: ts,
|
||||
};
|
||||
}
|
||||
|
||||
function makeRecordingStore(
|
||||
handler: (q: BarsQueryArg) => AsyncIterable<BarBatch>
|
||||
): {
|
||||
readonly store: Pick<MarketDataStore, 'bars'>;
|
||||
readonly calls: BarsQueryArg[];
|
||||
} {
|
||||
const calls: BarsQueryArg[] = [];
|
||||
const store: Pick<MarketDataStore, 'bars'> = {
|
||||
bars(q: BarsQueryArg): AsyncIterable<BarBatch> {
|
||||
calls.push(q);
|
||||
return handler(q);
|
||||
},
|
||||
};
|
||||
return { store, calls };
|
||||
}
|
||||
|
||||
async function* yieldBatches(batches: readonly BarBatch[]): AsyncGenerator<BarBatch> {
|
||||
for (const batch of batches) {
|
||||
yield batch;
|
||||
}
|
||||
}
|
||||
|
||||
describe('createBarSessionDatesPort — exports, types, and query contract', () => {
|
||||
test('returned port is assignable to SessionDatesPort and PostgresResearchCopilotServerOptions["sessionDates"] without casts', async () => {
|
||||
const { store } = makeRecordingStore(() => yieldBatches([]));
|
||||
const options: BarSessionDatesPortOptions = {
|
||||
store,
|
||||
referenceListingIds: {
|
||||
XNYS: [101],
|
||||
},
|
||||
};
|
||||
|
||||
const port = createBarSessionDatesPort(options);
|
||||
const asSessionDatesPort: SessionDatesPort = port;
|
||||
const asCopilotSessionDates: PostgresResearchCopilotServerOptions['sessionDates'] = port;
|
||||
|
||||
expect(asSessionDatesPort).toBe(port);
|
||||
expect(asCopilotSessionDates).toBe(port);
|
||||
expect(
|
||||
await asCopilotSessionDates.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-11-25',
|
||||
toDate: '2024-11-29',
|
||||
})
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
test('calls store.bars once per query with exact Vault-default keys and configured ID order', async () => {
|
||||
const { store, calls } = makeRecordingStore(() =>
|
||||
yieldBatches([{ rows: [makeBar(202, '2024-11-26', 21)] }])
|
||||
);
|
||||
|
||||
const port = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: {
|
||||
XNYS: [202, 101],
|
||||
XTSE: [303],
|
||||
},
|
||||
});
|
||||
|
||||
const dates = await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-11-25',
|
||||
toDate: '2024-11-29',
|
||||
});
|
||||
|
||||
expect(dates).toEqual(['2024-11-26']);
|
||||
expect(calls).toHaveLength(1);
|
||||
|
||||
const req = calls[0] as BarsQueryArg;
|
||||
expect(req.listingIds).toEqual([202, 101]);
|
||||
expect(req.timeframe).toBe('1d');
|
||||
expect(req.adjustment).toBe('raw');
|
||||
expect(req.from).toBe('2024-11-25');
|
||||
expect(req.to).toBe('2024-11-29');
|
||||
expect(Object.keys(req).sort()).toEqual(['adjustment', 'from', 'listingIds', 'timeframe', 'to']);
|
||||
expect('scope' in req).toBe(false);
|
||||
expect('asOf' in req).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createBarSessionDatesPort — union, bounds, determinism, and empty streams', () => {
|
||||
test('returns strictly ascending de-duplicated union across multiple out-of-order batches inside [fromDate, toDate]', async () => {
|
||||
const batches: readonly BarBatch[] = [
|
||||
{
|
||||
rows: [
|
||||
// Valid bars outside the requested window must be excluded.
|
||||
makeBar(101, '2024-11-22', 21),
|
||||
makeBar(102, '2024-12-02', 21),
|
||||
// Out-of-order bars inside window, including upper inclusive bound.
|
||||
makeBar(102, '2024-11-29', 21),
|
||||
makeBar(101, '2024-11-27', 21),
|
||||
],
|
||||
},
|
||||
{
|
||||
rows: [
|
||||
// Overlapping date (2024-11-27), single-listing date (2024-11-26), lower inclusive bound (2024-11-25).
|
||||
makeBar(102, '2024-11-27', 21),
|
||||
makeBar(101, '2024-11-25', 21),
|
||||
makeBar(102, '2024-11-26', 21),
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const { store, calls } = makeRecordingStore(() => yieldBatches(batches));
|
||||
const port = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: {
|
||||
XNYS: [101, 102],
|
||||
},
|
||||
});
|
||||
|
||||
const first = await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-11-25',
|
||||
toDate: '2024-11-29',
|
||||
});
|
||||
const second = await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-11-25',
|
||||
toDate: '2024-11-29',
|
||||
});
|
||||
|
||||
const expected = ['2024-11-25', '2024-11-26', '2024-11-27', '2024-11-29'];
|
||||
expect(first).toEqual(expected);
|
||||
expect(second).toEqual(expected);
|
||||
expect(calls).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('supports single-day inclusive window and returns [] for empty streams or empty batches', async () => {
|
||||
const { store: singleDayStore } = makeRecordingStore(() =>
|
||||
yieldBatches([
|
||||
{
|
||||
rows: [
|
||||
makeBar(101, '2024-07-01', 20),
|
||||
makeBar(101, '2024-07-02', 20),
|
||||
makeBar(101, '2024-07-03', 20),
|
||||
],
|
||||
},
|
||||
])
|
||||
);
|
||||
|
||||
const singleDayPort = createBarSessionDatesPort({
|
||||
store: singleDayStore,
|
||||
referenceListingIds: { XNYS: [101] },
|
||||
});
|
||||
|
||||
expect(
|
||||
await singleDayPort.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-07-02',
|
||||
toDate: '2024-07-02',
|
||||
})
|
||||
).toEqual(['2024-07-02']);
|
||||
|
||||
const { store: emptyBatchStore } = makeRecordingStore(() =>
|
||||
yieldBatches([{ rows: [] }, { rows: [] }])
|
||||
);
|
||||
const emptyPort = createBarSessionDatesPort({
|
||||
store: emptyBatchStore,
|
||||
referenceListingIds: { XNYS: [101] },
|
||||
});
|
||||
|
||||
expect(
|
||||
await emptyPort.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-07-02',
|
||||
toDate: '2024-07-02',
|
||||
})
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createBarSessionDatesPort — fail-closed query, store error, and bar validation', () => {
|
||||
test('throws unknown_calendar and invalid_query with zero store calls', async () => {
|
||||
const { store, calls } = makeRecordingStore(() => yieldBatches([]));
|
||||
const port = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: {
|
||||
XNYS: [101],
|
||||
},
|
||||
});
|
||||
|
||||
const expectError = async (
|
||||
query: unknown,
|
||||
expectedCode: BarSessionDatesError['code']
|
||||
): Promise<void> => {
|
||||
let caught: unknown;
|
||||
try {
|
||||
await port.listSessionDates(query as never);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(BarSessionDatesError);
|
||||
expect((caught as BarSessionDatesError).code).toBe(expectedCode);
|
||||
};
|
||||
|
||||
await expectError(
|
||||
{ calendarCode: 'XTSE', fromDate: '2024-11-25', toDate: '2024-11-29' },
|
||||
'unknown_calendar'
|
||||
);
|
||||
await expectError(
|
||||
{ calendarCode: '', fromDate: '2024-11-25', toDate: '2024-11-29' },
|
||||
'unknown_calendar'
|
||||
);
|
||||
await expectError(
|
||||
{ calendarCode: 'XNYS', fromDate: '2024/11/25', toDate: '2024-11-29' },
|
||||
'invalid_query'
|
||||
);
|
||||
await expectError(
|
||||
{ calendarCode: 'XNYS', fromDate: '2024-11-25T00:00:00Z', toDate: '2024-11-29' },
|
||||
'invalid_query'
|
||||
);
|
||||
await expectError(
|
||||
{ calendarCode: 'XNYS', fromDate: '2024-02-30', toDate: '2024-03-01' },
|
||||
'invalid_query'
|
||||
);
|
||||
await expectError(
|
||||
{ calendarCode: 'XNYS', fromDate: '2024-11-25', toDate: '2023-02-29' },
|
||||
'invalid_query'
|
||||
);
|
||||
await expectError(
|
||||
{ calendarCode: 'XNYS', fromDate: '2024-11-29', toDate: '2024-11-25' },
|
||||
'invalid_query'
|
||||
);
|
||||
await expectError(null, 'invalid_query');
|
||||
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('propagates VaultHoldoutFenceError from the async iterator unchanged with no partial result', async () => {
|
||||
const vaultError = new VaultHoldoutFenceError(
|
||||
'2025-01-02',
|
||||
utcMs(2025, 1, 2, 0, 0, 0),
|
||||
utcMs(2025, 1, 1, 0, 0, 0)
|
||||
);
|
||||
|
||||
const { store } = makeRecordingStore(() =>
|
||||
(async function* (): AsyncGenerator<BarBatch> {
|
||||
yield { rows: [makeBar(101, '2024-12-31', 21)] };
|
||||
throw vaultError;
|
||||
})()
|
||||
);
|
||||
|
||||
const port = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: { XNYS: [101] },
|
||||
});
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-12-30',
|
||||
toDate: '2025-01-02',
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
expect(caught).toBe(vaultError);
|
||||
});
|
||||
|
||||
test('throws invalid_bar for NaN, Infinity, fractional ts, or unconfigured listingId', async () => {
|
||||
const badBars: readonly BarRecord[] = [
|
||||
{ ...makeBar(101, '2024-11-25', 21), ts: Number.NaN },
|
||||
{ ...makeBar(101, '2024-11-25', 21), ts: Number.POSITIVE_INFINITY },
|
||||
{ ...makeBar(101, '2024-11-25', 21), ts: Number.NEGATIVE_INFINITY },
|
||||
{ ...makeBar(101, '2024-11-25', 21), ts: utcMs(2024, 11, 25, 21, 0, 0) + 0.5 },
|
||||
// Listing ID configured only on XTSE, not XNYS.
|
||||
makeBar(202, '2024-11-25', 21),
|
||||
// Listing ID not configured on any calendar, even when outside the date window.
|
||||
makeBar(999, '2024-01-02', 21),
|
||||
];
|
||||
|
||||
for (const badBar of badBars) {
|
||||
const { store } = makeRecordingStore(() => yieldBatches([{ rows: [badBar] }]));
|
||||
const port = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: {
|
||||
XNYS: [101],
|
||||
XTSE: [202],
|
||||
},
|
||||
});
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-11-25',
|
||||
toDate: '2024-11-29',
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
expect(caught).toBeInstanceOf(BarSessionDatesError);
|
||||
expect((caught as BarSessionDatesError).code).toBe('invalid_bar');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('createBarSessionDatesPort — options validation and defensive copy', () => {
|
||||
test('rejects malformed options, empty keys, non-positive/non-INT32 IDs, and duplicates with invalid_options', () => {
|
||||
const { store } = makeRecordingStore(() => yieldBatches([]));
|
||||
|
||||
const invalidInputs: readonly unknown[] = [
|
||||
null,
|
||||
undefined,
|
||||
{},
|
||||
{ store: null, referenceListingIds: { XNYS: [1] } },
|
||||
{ store: {}, referenceListingIds: { XNYS: [1] } },
|
||||
{ store: { bars: 'nope' }, referenceListingIds: { XNYS: [1] } },
|
||||
{ store, referenceListingIds: null },
|
||||
{ store, referenceListingIds: [] },
|
||||
{ store, referenceListingIds: { '': [1] } },
|
||||
{ store, referenceListingIds: { ' ': [1] } },
|
||||
{ store, referenceListingIds: { ' XNYS': [1] } },
|
||||
{ store, referenceListingIds: { XNYS: null } },
|
||||
{ store, referenceListingIds: { XNYS: [] } },
|
||||
{ store, referenceListingIds: { XNYS: [0] } },
|
||||
{ store, referenceListingIds: { XNYS: [-5] } },
|
||||
{ store, referenceListingIds: { XNYS: [1.5] } },
|
||||
{ store, referenceListingIds: { XNYS: [2_147_483_648] } },
|
||||
{ store, referenceListingIds: { XNYS: [Number.NaN] } },
|
||||
{ store, referenceListingIds: { XNYS: [101, 202, 101] } },
|
||||
];
|
||||
|
||||
for (const input of invalidInputs) {
|
||||
let caught: unknown;
|
||||
try {
|
||||
createBarSessionDatesPort(input as never);
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(BarSessionDatesError);
|
||||
expect((caught as BarSessionDatesError).code).toBe('invalid_options');
|
||||
}
|
||||
});
|
||||
|
||||
test('defensively copies caller config and isolates per-call listingIds arrays', async () => {
|
||||
const xnysIds = [101, 102];
|
||||
const referenceListingIds: Record<string, number[]> = {
|
||||
XNYS: xnysIds,
|
||||
};
|
||||
|
||||
const observedIds: number[][] = [];
|
||||
const store: Pick<MarketDataStore, 'bars'> = {
|
||||
bars(q: BarsQueryArg): AsyncIterable<BarBatch> {
|
||||
observedIds.push([...q.listingIds]);
|
||||
// Mutate caller-passed query array to confirm port passes a fresh copy each time.
|
||||
q.listingIds.push(999);
|
||||
return yieldBatches([{ rows: [makeBar(101, '2024-11-25', 21)] }]);
|
||||
},
|
||||
};
|
||||
|
||||
const port = createBarSessionDatesPort({ store, referenceListingIds });
|
||||
|
||||
// Mutate caller config after construction.
|
||||
xnysIds.push(303);
|
||||
xnysIds[0] = 404;
|
||||
referenceListingIds.XNYS = [505];
|
||||
referenceListingIds.XTSE = [606];
|
||||
|
||||
expect(
|
||||
await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-11-25',
|
||||
toDate: '2024-11-25',
|
||||
})
|
||||
).toEqual(['2024-11-25']);
|
||||
expect(
|
||||
await port.listSessionDates({
|
||||
calendarCode: 'XNYS',
|
||||
fromDate: '2024-11-25',
|
||||
toDate: '2024-11-25',
|
||||
})
|
||||
).toEqual(['2024-11-25']);
|
||||
|
||||
expect(observedIds).toEqual([
|
||||
[101, 102],
|
||||
[101, 102],
|
||||
]);
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await port.listSessionDates({
|
||||
calendarCode: 'XTSE',
|
||||
fromDate: '2024-11-25',
|
||||
toDate: '2024-11-25',
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(BarSessionDatesError);
|
||||
expect((caught as BarSessionDatesError).code).toBe('unknown_calendar');
|
||||
});
|
||||
});
|
||||
|
||||
describe('createBarSessionDatesPort — composition with createExchangeCalendarResolver', () => {
|
||||
test('resolves XNYS and XTSE session closes including summer EDT, Thanksgiving divergence, and early-close override', async () => {
|
||||
const xnysBars: readonly BarRecord[] = [
|
||||
// Summer EDT session (16:00 ET = 20:00Z)
|
||||
makeBar(1001, '2024-07-02', 20),
|
||||
// Winter EST sessions (US closed 2024-11-28 Thanksgiving; open 2024-11-29)
|
||||
makeBar(1001, '2024-11-27', 21),
|
||||
makeBar(1002, '2024-11-29', 21),
|
||||
];
|
||||
|
||||
const xtseBars: readonly BarRecord[] = [
|
||||
// Summer EDT session (16:00 ET = 20:00Z)
|
||||
makeBar(2001, '2024-07-02', 20),
|
||||
// Winter EST sessions (TSX open on US Thanksgiving 2024-11-28 and regular close on 2024-11-29)
|
||||
makeBar(2001, '2024-11-27', 21),
|
||||
makeBar(2001, '2024-11-28', 21),
|
||||
makeBar(2002, '2024-11-29', 21),
|
||||
];
|
||||
|
||||
const { store, calls } = makeRecordingStore((q) => {
|
||||
const requested = new Set(q.listingIds);
|
||||
const rows = [...xnysBars, ...xtseBars].filter((bar) => requested.has(bar.listingId));
|
||||
return yieldBatches([{ rows }]);
|
||||
});
|
||||
|
||||
const sessionDates = createBarSessionDatesPort({
|
||||
store,
|
||||
referenceListingIds: {
|
||||
XNYS: [1001, 1002],
|
||||
XTSE: [2001, 2002],
|
||||
},
|
||||
});
|
||||
|
||||
const listingCalendars: ListingCalendarPort = {
|
||||
getListingCalendars(listingIds) {
|
||||
return listingIds.map((listingId) => ({
|
||||
listingId,
|
||||
calendarCode: listingId === 501 ? 'XNYS' : 'XTSE',
|
||||
}));
|
||||
},
|
||||
};
|
||||
|
||||
const resolveExchangeCalendars = createExchangeCalendarResolver({
|
||||
listingCalendars,
|
||||
sessionDates,
|
||||
earlyCloses: {
|
||||
XNYS: {
|
||||
'2024-11-29': 13 * 60, // 13:00 ET -> 18:00Z (EST)
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const resolved = await resolveExchangeCalendars({
|
||||
listingIds: [501, 602],
|
||||
fromDate: '2024-07-02',
|
||||
toDate: '2024-11-29',
|
||||
});
|
||||
|
||||
expect(resolved.listingCalendarId).toEqual({
|
||||
501: 'XNYS',
|
||||
602: 'XTSE',
|
||||
});
|
||||
|
||||
expect(resolved.calendars).toEqual({
|
||||
XNYS: [
|
||||
{ date: '2024-07-02', closeTs: utcMs(2024, 7, 2, 20, 0, 0) },
|
||||
{ date: '2024-11-27', closeTs: utcMs(2024, 11, 27, 21, 0, 0) },
|
||||
{ date: '2024-11-29', closeTs: utcMs(2024, 11, 29, 18, 0, 0) },
|
||||
],
|
||||
XTSE: [
|
||||
{ date: '2024-07-02', closeTs: utcMs(2024, 7, 2, 20, 0, 0) },
|
||||
{ date: '2024-11-27', closeTs: utcMs(2024, 11, 27, 21, 0, 0) },
|
||||
{ date: '2024-11-28', closeTs: utcMs(2024, 11, 28, 21, 0, 0) },
|
||||
{ date: '2024-11-29', closeTs: utcMs(2024, 11, 29, 21, 0, 0) },
|
||||
],
|
||||
});
|
||||
|
||||
// One store.bars call per distinct calendar code (XNYS, XTSE).
|
||||
expect(calls).toHaveLength(2);
|
||||
expect(calls[0]?.listingIds).toEqual([1001, 1002]);
|
||||
expect(calls[1]?.listingIds).toEqual([2001, 2002]);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue