527 lines
16 KiB
TypeScript
527 lines
16 KiB
TypeScript
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]);
|
|
});
|
|
});
|