diff --git a/apps/stock/data-pipeline/src/security-master/index.ts b/apps/stock/data-pipeline/src/security-master/index.ts index 1b1b9d26..116056b2 100644 --- a/apps/stock/data-pipeline/src/security-master/index.ts +++ b/apps/stock/data-pipeline/src/security-master/index.ts @@ -58,3 +58,29 @@ export { type StageAStats, type StageAUnresolvedRecord, } from './instrument-stage-a'; + +export { + isStageBSource, + matchListingsStageB, + MAX_TICKER_ROOT_LENGTH, + STAGE_B_SOURCES, + type ListingNaturalKey, + type MatchListingsStageBOptions, + type StageBConflictDetail, + type StageBConflictKind, + type StageBConflictRecord, + type StageBEodListingInput, + type StageBIbContractInput, + type StageBInput, + type StageBListingCandidate, + type StageBMatchMethod, + type StageBMatchResult, + type StageBProviderMappingCandidate, + type StageBSource, + type StageBSourceStats, + type StageBStats, + type StageBTickerSource, + type StageBTickerSourceInput, + type StageBUnresolvedReason, + type StageBUnresolvedRecord, +} from './listing-stage-b'; diff --git a/apps/stock/data-pipeline/src/security-master/listing-stage-b.ts b/apps/stock/data-pipeline/src/security-master/listing-stage-b.ts new file mode 100644 index 00000000..7b38fbc9 --- /dev/null +++ b/apps/stock/data-pipeline/src/security-master/listing-stage-b.ts @@ -0,0 +1,1320 @@ +import { + normalizeBarDate, + spansOverlap, + type SpanDateRange, + type SpansOverlapOptions, +} from '../normalization/bar-spans'; +import { MAX_CLASS_SUFFIX_LENGTH, parseTicker } from '../normalization/ticker'; +import { compareAscii, type ExchangeRole } from './exchange-pass1'; +import type { + StageAInstrumentCandidate, + StageAMatchMethod, + StageASource, +} from './instrument-stage-a'; + +export const MAX_TICKER_ROOT_LENGTH = 24; + +export const STAGE_B_SOURCES = ['eod', 'ib', 'qm', 'ceo'] as const; + +export type StageBSource = (typeof STAGE_B_SOURCES)[number]; + +export type StageBTickerSource = 'qm' | 'ceo'; + +export type StageBMatchMethod = StageAMatchMethod | 'tier3_ticker_span'; + +export interface ListingNaturalKey { + primaryIsin: string; + mic: string; + tickerRoot: string; + classSuffix: string; + currency: string; +} + +export interface StageBEodListingInput { + sourceId: string; + ticker: string | null | undefined; + mic: string | null; + role: ExchangeRole | null; + currency?: string | null; + span: SpanDateRange | null; +} + +export interface StageBIbContractInput { + sourceId: string; + conid: number; + currency?: string | null; + primaryExchange: string | null; +} + +export interface StageBTickerSourceInput { + source: StageBTickerSource; + sourceId: string; + ticker: string | null | undefined; + mic: string | null; + role: ExchangeRole | null; + currency?: string | null; + span: SpanDateRange | null; +} + +export interface StageBInput { + readonly instruments: readonly StageAInstrumentCandidate[]; + readonly eodListings: + | readonly StageBEodListingInput[] + | ReadonlyMap>; + readonly ibContracts: + | readonly StageBIbContractInput[] + | ReadonlyMap>; + readonly tickerSources: readonly StageBTickerSourceInput[]; +} + +export interface MatchListingsStageBOptions { + readonly spanOverlapToleranceDays?: number; +} + +export interface StageBListingCandidate extends ListingNaturalKey { + ibConid: number | null; + ibPrimaryExchange: string | null; + listedFrom: string | null; + listedTo: string | null; +} + +export interface StageBProviderMappingCandidate { + source: StageBSource; + sourceId: string; + listingKey: ListingNaturalKey; + method: StageBMatchMethod; + validFrom: string | null; + validTo: string | null; +} + +export type StageBUnresolvedReason = + | 'excluded_fund' + | 'composite_venue' + | 'ats_routing_venue' + | 'forex_venue' + | 'missing_mic' + | 'invalid_mic' + | 'invalid_ticker' + | 'ticker_root_too_long' + | 'class_suffix_too_long' + | 'invalid_currency' + | 'missing_span' + | 'invalid_span' + | 'no_span_overlap' + | 'missing_eod_listing' + | 'missing_ib_contract' + | 'invalid_ib_conid' + | 'no_listing_for_currency' + | 'no_matching_listing'; + +export interface StageBUnresolvedRecord { + source: StageBSource; + sourceId: string; + reason: StageBUnresolvedReason; + primaryIsin: string | null; +} + +export type StageBConflictKind = + | 'duplicate_source_id' + | 'ambiguous_ib_listing' + | 'competing_ib_conid' + | 'ambiguous_ticker_span'; + +export interface StageBConflictDetail { + primaryIsin: string | null; + currency: string | null; + ibConid: number | null; + competingConids: number[]; + candidateListingKeys: ListingNaturalKey[]; +} + +export interface StageBConflictRecord { + source: StageBSource; + sourceId: string; + conflictKind: StageBConflictKind; + detail: StageBConflictDetail; +} + +export interface StageBSourceStats { + total: number; + matched: number; + unresolved: number; + conflict: number; +} + +export interface StageBStats { + totalListings: number; + totalProviderMappings: number; + listingsWithIbConid: number; + excludedFunds: number; + bySource: Record; +} + +export interface StageBMatchResult { + listings: StageBListingCandidate[]; + providerMappings: StageBProviderMappingCandidate[]; + unresolved: StageBUnresolvedRecord[]; + conflicts: StageBConflictRecord[]; + stats: StageBStats; +} + +type EodMetadata = Omit; +type IbMetadata = Omit; + +interface ListingAccumulator { + readonly key: ListingNaturalKey; + listedFrom: string | null; + listedTo: string | null; + ibConid: number | null; + ibPrimaryExchange: string | null; +} + +interface StagedIbCandidate { + sourceId: string; + primaryIsin: string; + currency: string; + conid: number; + primaryExchange: string | null; + method: StageAMatchMethod; +} + +const ISO_MIC_PATTERN = /^[A-Z0-9]{4}$/; +const ISO_CURRENCY_PATTERN = /^[A-Z]{3}$/; + +const CODE_TAB = 9; +const CODE_SPACE = 32; +const CODE_DASH = 45; +const CODE_DOT = 46; +const CODE_SLASH = 47; + +export function isStageBSource(value: unknown): value is StageBSource { + return value === 'eod' || value === 'ib' || value === 'qm' || value === 'ceo'; +} + +function isStageASourceValue(value: unknown): value is StageASource { + return value === 'ib' || value === 'eod'; +} + +function isStageAMatchMethodValue(value: unknown): value is StageAMatchMethod { + return value === 'tier1_isin' || value === 'tier2_cusip'; +} + +function isStageBTickerSourceValue(value: unknown): value is StageBTickerSource { + return value === 'qm' || value === 'ceo'; +} + +function isExchangeRoleValue(value: unknown): value is ExchangeRole { + return ( + value === 'primary_venue' || + value === 'composite' || + value === 'ats_routing' || + value === 'forex' || + value === 'excluded_fund' + ); +} + +function createEmptySourceStats(): StageBSourceStats { + return { + total: 0, + matched: 0, + unresolved: 0, + conflict: 0, + }; +} + +function isTickerWhitespace(code: number): boolean { + return code === CODE_SPACE || code === CODE_TAB; +} + +function isTickerSeparator(code: number): boolean { + return ( + code === CODE_DOT || + code === CODE_DASH || + code === CODE_SPACE || + code === CODE_TAB || + code === CODE_SLASH + ); +} + +function findNextTickerSeparator(str: string, start: number): number { + for (let i = start; i < str.length; i++) { + if (isTickerSeparator(str.charCodeAt(i))) { + return i; + } + } + return -1; +} + +/** + * Called only when `parseTicker` returned `null` so the hot path remains single-pass. + * Distinguishes structurally valid tickers whose `classSuffix` exceeded `MAX_CLASS_SUFFIX_LENGTH` + * (or whose `tickerRoot` exceeded `MAX_TICKER_ROOT_LENGTH`) from malformed tickers. + */ +function classifyNullTickerReason( + raw: string | null | undefined, + source: StageBSource +): 'ticker_root_too_long' | 'class_suffix_too_long' | 'invalid_ticker' { + if (typeof raw !== 'string') { + return 'invalid_ticker'; + } + let s = raw.trim().toUpperCase(); + if (s.length === 0) { + return 'invalid_ticker'; + } + if (source === 'ceo') { + if (s.length > 3 && s.endsWith('.TO')) { + s = s.slice(0, -3).trimEnd(); + } else if (s.length > 2 && s.endsWith('.V')) { + s = s.slice(0, -2).trimEnd(); + } + if (s.length === 0) { + return 'invalid_ticker'; + } + } + + const firstSep = findNextTickerSeparator(s, 0); + if (firstSep <= 0) { + return 'invalid_ticker'; + } + + const tickerRoot = s.slice(0, firstSep); + let pos = firstSep + 1; + while (pos < s.length && isTickerWhitespace(s.charCodeAt(pos))) { + pos++; + } + if (pos >= s.length || isTickerSeparator(s.charCodeAt(pos))) { + return 'invalid_ticker'; + } + + const secondSep = findNextTickerSeparator(s, pos); + let classSuffix: string; + if (secondSep === -1) { + classSuffix = s.slice(pos); + } else { + classSuffix = s.slice(pos, secondSep); + pos = secondSep; + while (pos < s.length) { + pos++; + while (pos < s.length && isTickerWhitespace(s.charCodeAt(pos))) { + pos++; + } + if (pos >= s.length || isTickerSeparator(s.charCodeAt(pos))) { + return 'invalid_ticker'; + } + const nextSep = findNextTickerSeparator(s, pos); + if (nextSep === -1) { + classSuffix += '.' + s.slice(pos); + break; + } + classSuffix += '.' + s.slice(pos, nextSep); + pos = nextSep; + } + } + + if (tickerRoot.length > MAX_TICKER_ROOT_LENGTH) { + return 'ticker_root_too_long'; + } + if (classSuffix.length > MAX_CLASS_SUFFIX_LENGTH) { + return 'class_suffix_too_long'; + } + return 'invalid_ticker'; +} + +function classifyTicker( + raw: string | null | undefined, + source: StageBSource +): + | { ok: true; tickerRoot: string; classSuffix: string } + | { ok: false; reason: 'ticker_root_too_long' | 'class_suffix_too_long' | 'invalid_ticker' } { + const parsed = parseTicker(raw, source); + if (parsed === null) { + return { ok: false, reason: classifyNullTickerReason(raw, source) }; + } + if (parsed.tickerRoot.length > MAX_TICKER_ROOT_LENGTH) { + return { ok: false, reason: 'ticker_root_too_long' }; + } + return { ok: true, tickerRoot: parsed.tickerRoot, classSuffix: parsed.classSuffix }; +} + +function classifyVenueRoleAndMic( + role: ExchangeRole | null | undefined, + mic: string | null | undefined +): + | { ok: true; mic: string } + | { + ok: false; + reason: + | 'excluded_fund' + | 'composite_venue' + | 'ats_routing_venue' + | 'forex_venue' + | 'missing_mic' + | 'invalid_mic'; + } { + if (role === 'excluded_fund') { + return { ok: false, reason: 'excluded_fund' }; + } + if (role === 'composite') { + return { ok: false, reason: 'composite_venue' }; + } + if (role === 'ats_routing') { + return { ok: false, reason: 'ats_routing_venue' }; + } + if (role === 'forex') { + return { ok: false, reason: 'forex_venue' }; + } + if (role === null || role === undefined) { + return { ok: false, reason: 'missing_mic' }; + } + if (typeof mic !== 'string') { + return { ok: false, reason: 'missing_mic' }; + } + const normalizedMic = mic.trim().toUpperCase(); + if (normalizedMic.length === 0) { + return { ok: false, reason: 'missing_mic' }; + } + if (!ISO_MIC_PATTERN.test(normalizedMic)) { + return { ok: false, reason: 'invalid_mic' }; + } + return { ok: true, mic: normalizedMic }; +} + +function normalizeCurrency(value: string | null | undefined): string | null { + if (typeof value !== 'string') { + return null; + } + const normalized = value.trim().toUpperCase(); + return ISO_CURRENCY_PATTERN.test(normalized) ? normalized : null; +} + +function normalizeOptionalExchangeLabel(value: string | null | undefined): string | null { + if (typeof value !== 'string') { + return null; + } + const normalized = value.trim().toUpperCase(); + return normalized.length > 0 ? normalized : null; +} + +function validateSpan( + span: SpanDateRange | null | undefined +): + | { status: 'missing' } + | { status: 'invalid' } + | { status: 'valid'; span: SpanDateRange } { + if (span === null || span === undefined) { + return { status: 'missing' }; + } + if (typeof span !== 'object') { + return { status: 'invalid' }; + } + if (typeof span.firstBarDate !== 'string' || typeof span.lastBarDate !== 'string') { + return { status: 'invalid' }; + } + const firstBarDate = normalizeBarDate(span.firstBarDate); + const lastBarDate = normalizeBarDate(span.lastBarDate); + if (firstBarDate === null || lastBarDate === null || firstBarDate > lastBarDate) { + return { status: 'invalid' }; + } + return { status: 'valid', span: { firstBarDate, lastBarDate } }; +} + +function makeListingNaturalKeyId(key: ListingNaturalKey): string { + return `${key.primaryIsin}\u0000${key.mic}\u0000${key.tickerRoot}\u0000${key.classSuffix}\u0000${key.currency}`; +} + +function makeTickerLookupKey( + mic: string, + currency: string, + tickerRoot: string, + classSuffix: string +): string { + return `${mic}\u0000${currency}\u0000${tickerRoot}\u0000${classSuffix}`; +} + +function compareListingNaturalKey(a: ListingNaturalKey, b: ListingNaturalKey): number { + return ( + compareAscii(a.primaryIsin, b.primaryIsin) || + compareAscii(a.mic, b.mic) || + compareAscii(a.tickerRoot, b.tickerRoot) || + compareAscii(a.classSuffix, b.classSuffix) || + compareAscii(a.currency, b.currency) + ); +} + +function compareNullableNumber(a: number | null, b: number | null): number { + if (a === b) { + return 0; + } + if (a === null) { + return -1; + } + if (b === null) { + return 1; + } + return a < b ? -1 : 1; +} + +function compareNumberArrays(a: readonly number[], b: readonly number[]): number { + const len = a.length < b.length ? a.length : b.length; + for (let i = 0; i < len; i++) { + const av = a[i] ?? 0; + const bv = b[i] ?? 0; + if (av !== bv) { + return av < bv ? -1 : 1; + } + } + return a.length - b.length; +} + +function compareListingKeyArrays( + a: readonly ListingNaturalKey[], + b: readonly ListingNaturalKey[] +): number { + const len = a.length < b.length ? a.length : b.length; + for (let i = 0; i < len; i++) { + const ak = a[i]; + const bk = b[i]; + if (ak !== undefined && bk !== undefined) { + const cmp = compareListingNaturalKey(ak, bk); + if (cmp !== 0) { + return cmp; + } + } + } + return a.length - b.length; +} + +function compareProviderMappings( + a: StageBProviderMappingCandidate, + b: StageBProviderMappingCandidate +): number { + return ( + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareListingNaturalKey(a.listingKey, b.listingKey) || + compareAscii(a.method, b.method) || + compareAscii(a.validFrom ?? '', b.validFrom ?? '') || + compareAscii(a.validTo ?? '', b.validTo ?? '') + ); +} + +function compareUnresolved(a: StageBUnresolvedRecord, b: StageBUnresolvedRecord): number { + return ( + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.reason, b.reason) || + compareAscii(a.primaryIsin ?? '', b.primaryIsin ?? '') + ); +} + +function compareConflicts(a: StageBConflictRecord, b: StageBConflictRecord): number { + return ( + compareAscii(a.source, b.source) || + compareAscii(a.sourceId, b.sourceId) || + compareAscii(a.conflictKind, b.conflictKind) || + compareAscii(a.detail.primaryIsin ?? '', b.detail.primaryIsin ?? '') || + compareAscii(a.detail.currency ?? '', b.detail.currency ?? '') || + compareNullableNumber(a.detail.ibConid, b.detail.ibConid) || + compareNumberArrays(a.detail.competingConids, b.detail.competingConids) || + compareListingKeyArrays(a.detail.candidateListingKeys, b.detail.candidateListingKeys) + ); +} + +function assertIsArray(value: unknown, label: string): void { + if (!Array.isArray(value)) { + throw new TypeError(`Stage B ${label} must be an array`); + } +} + +function emptyConflictDetail( + primaryIsin: string | null = null, + currency: string | null = null +): StageBConflictDetail { + return { + primaryIsin, + currency, + ibConid: null, + competingConids: [], + candidateListingKeys: [], + }; +} + +/** + * Pass 3 Stage B pure in-memory listing matcher. + * + * 1. Builds primary-venue EOD listings keyed by `(primaryIsin, mic, tickerRoot, classSuffix, currency)`. + * 2. Attaches IB `conid`s strictly at `(instrument, currency)` with conflict quarantine; never uses + * IB `exchangeId` as a listing MIC. + * 3. Matches QM and CEO records via Tier 3 `(tickerRoot, classSuffix, mic, currency)` + `spansOverlap`. + */ +export function matchListingsStageB( + input: StageBInput, + options: MatchListingsStageBOptions = {} +): StageBMatchResult { + if (options === null || typeof options !== 'object') { + throw new TypeError('options must be an object'); + } + const toleranceDays = options.spanOverlapToleranceDays ?? 0; + if ( + typeof toleranceDays !== 'number' || + !Number.isSafeInteger(toleranceDays) || + toleranceDays < 0 + ) { + throw new RangeError( + `options.spanOverlapToleranceDays must be a non-negative safe integer, received ${String(toleranceDays)}` + ); + } + const overlapOptions: SpansOverlapOptions = { toleranceDays }; + + if (input === null || input === undefined || typeof input !== 'object') { + throw new TypeError('Stage B input must be an object'); + } + assertIsArray(input.instruments, 'input.instruments'); + assertIsArray(input.tickerSources, 'input.tickerSources'); + + // Validate instruments and count member `(source, sourceId)` occurrences in a single pass. + const memberCountsBySource: Record> = { + eod: new Map(), + ib: new Map(), + }; + const seenPrimaryIsins = new Set(); + + for (let i = 0; i < input.instruments.length; i++) { + if (!(i in input.instruments)) { + throw new TypeError(`Invalid sparse slot at instruments[${i}]: expected an instrument object`); + } + const inst = input.instruments[i]; + if (inst === undefined || inst === null || typeof inst !== 'object') { + throw new TypeError(`Invalid Stage B instrument at instruments[${i}]: expected an object`); + } + if (typeof inst.primaryIsin !== 'string' || inst.primaryIsin.trim().length === 0) { + throw new Error(`Invalid empty or non-string primaryIsin at instruments[${i}]`); + } + if (seenPrimaryIsins.has(inst.primaryIsin)) { + throw new Error(`Duplicate primaryIsin "${inst.primaryIsin}" at instruments[${i}]`); + } + seenPrimaryIsins.add(inst.primaryIsin); + + assertIsArray(inst.members, `instruments[${i}].members`); + for (let j = 0; j < inst.members.length; j++) { + if (!(j in inst.members)) { + throw new TypeError( + `Invalid sparse slot at instruments[${i}].members[${j}]: expected a member object` + ); + } + const member = inst.members[j]; + if (member === undefined || member === null || typeof member !== 'object') { + throw new TypeError( + `Invalid Stage B instrument member at instruments[${i}].members[${j}]: expected an object` + ); + } + if (!isStageASourceValue(member.source)) { + throw new Error( + `Unknown Stage A member source "${String(member.source)}" at instruments[${i}].members[${j}]` + ); + } + if (typeof member.sourceId !== 'string' || member.sourceId.length === 0) { + throw new Error( + `Invalid empty or non-string sourceId at instruments[${i}].members[${j}]` + ); + } + if (!isStageAMatchMethodValue(member.method)) { + throw new Error( + `Unknown Stage A member method "${String(member.method)}" at instruments[${i}].members[${j}]` + ); + } + const counts = memberCountsBySource[member.source]; + counts.set(member.sourceId, (counts.get(member.sourceId) ?? 0) + 1); + } + } + + // Validate and index eodListings. + const eodBySourceId = new Map(); + const eodMetadataCounts = new Map(); + + if (input.eodListings instanceof Map) { + let idx = 0; + for (const [sourceId, entry] of input.eodListings.entries()) { + if (typeof sourceId !== 'string' || sourceId.length === 0) { + throw new Error(`Invalid empty or non-string sourceId in eodListings map at entry ${idx}`); + } + if (entry === undefined || entry === null || typeof entry !== 'object') { + throw new TypeError( + `Invalid eodListings map value for sourceId "${sourceId}" at entry ${idx}: expected an object` + ); + } + if (entry.role !== null && entry.role !== undefined && !isExchangeRoleValue(entry.role)) { + throw new Error( + `Unknown exchange role "${String(entry.role)}" in eodListings map for sourceId "${sourceId}"` + ); + } + eodMetadataCounts.set(sourceId, 1); + eodBySourceId.set(sourceId, entry); + idx++; + } + } else { + if (!Array.isArray(input.eodListings)) { + throw new TypeError('Stage B input.eodListings must be an array or Map'); + } + const eodList: readonly StageBEodListingInput[] = input.eodListings; + for (let i = 0; i < eodList.length; i++) { + if (!(i in eodList)) { + throw new TypeError(`Invalid sparse slot at eodListings[${i}]: expected an object`); + } + const entry = eodList[i]; + if (entry === undefined || entry === null || typeof entry !== 'object') { + throw new TypeError(`Invalid eodListings entry at index ${i}: expected an object`); + } + if (typeof entry.sourceId !== 'string' || entry.sourceId.length === 0) { + throw new Error(`Invalid empty or non-string sourceId at eodListings[${i}]`); + } + if (entry.role !== null && entry.role !== undefined && !isExchangeRoleValue(entry.role)) { + throw new Error(`Unknown exchange role "${String(entry.role)}" at eodListings[${i}]`); + } + const nextCount = (eodMetadataCounts.get(entry.sourceId) ?? 0) + 1; + eodMetadataCounts.set(entry.sourceId, nextCount); + if (nextCount === 1) { + eodBySourceId.set(entry.sourceId, entry); + } + } + } + + // Validate and index ibContracts. + const ibBySourceId = new Map(); + const ibMetadataCounts = new Map(); + + if (input.ibContracts instanceof Map) { + let idx = 0; + for (const [sourceId, entry] of input.ibContracts.entries()) { + if (typeof sourceId !== 'string' || sourceId.length === 0) { + throw new Error(`Invalid empty or non-string sourceId in ibContracts map at entry ${idx}`); + } + if (entry === undefined || entry === null || typeof entry !== 'object') { + throw new TypeError( + `Invalid ibContracts map value for sourceId "${sourceId}" at entry ${idx}: expected an object` + ); + } + ibMetadataCounts.set(sourceId, 1); + ibBySourceId.set(sourceId, entry); + idx++; + } + } else { + if (!Array.isArray(input.ibContracts)) { + throw new TypeError('Stage B input.ibContracts must be an array or Map'); + } + const ibList: readonly StageBIbContractInput[] = input.ibContracts; + for (let i = 0; i < ibList.length; i++) { + if (!(i in ibList)) { + throw new TypeError(`Invalid sparse slot at ibContracts[${i}]: expected an object`); + } + const entry = ibList[i]; + if (entry === undefined || entry === null || typeof entry !== 'object') { + throw new TypeError(`Invalid ibContracts entry at index ${i}: expected an object`); + } + if (typeof entry.sourceId !== 'string' || entry.sourceId.length === 0) { + throw new Error(`Invalid empty or non-string sourceId at ibContracts[${i}]`); + } + const nextCount = (ibMetadataCounts.get(entry.sourceId) ?? 0) + 1; + ibMetadataCounts.set(entry.sourceId, nextCount); + if (nextCount === 1) { + ibBySourceId.set(entry.sourceId, entry); + } + } + } + + // Validate and count tickerSources (qm / ceo). + const tickerCountsBySource: Record> = { + qm: new Map(), + ceo: new Map(), + }; + + for (let i = 0; i < input.tickerSources.length; i++) { + if (!(i in input.tickerSources)) { + throw new TypeError(`Invalid sparse slot at tickerSources[${i}]: expected an object`); + } + const entry = input.tickerSources[i]; + if (entry === undefined || entry === null || typeof entry !== 'object') { + throw new TypeError(`Invalid tickerSources entry at index ${i}: expected an object`); + } + if (!isStageBTickerSourceValue(entry.source)) { + throw new Error( + `Unknown Stage B ticker source "${String(entry.source)}" at tickerSources[${i}]` + ); + } + if (typeof entry.sourceId !== 'string' || entry.sourceId.length === 0) { + throw new Error(`Invalid empty or non-string sourceId at tickerSources[${i}]`); + } + if (entry.role !== null && entry.role !== undefined && !isExchangeRoleValue(entry.role)) { + throw new Error(`Unknown exchange role "${String(entry.role)}" at tickerSources[${i}]`); + } + const counts = tickerCountsBySource[entry.source]; + counts.set(entry.sourceId, (counts.get(entry.sourceId) ?? 0) + 1); + } + + const statsBySource: Record = { + eod: createEmptySourceStats(), + ib: createEmptySourceStats(), + qm: createEmptySourceStats(), + ceo: createEmptySourceStats(), + }; + let excludedFunds = 0; + + const listingsByNaturalKey = new Map(); + const listingsByInstrumentCurrency = new Map>(); + const listingsByTickerKey = new Map(); + + const providerMappings: StageBProviderMappingCandidate[] = []; + const unresolved: StageBUnresolvedRecord[] = []; + const conflicts: StageBConflictRecord[] = []; + + // Step 1: EOD members -> primary-venue listing candidates + EOD provider mappings. + for (let i = 0; i < input.instruments.length; i++) { + const inst = input.instruments[i]; + if (inst === undefined) { + continue; + } + for (let j = 0; j < inst.members.length; j++) { + const member = inst.members[j]; + if (member === undefined || member.source !== 'eod') { + continue; + } + + statsBySource.eod.total += 1; + + if ( + (memberCountsBySource.eod.get(member.sourceId) ?? 0) > 1 || + (eodMetadataCounts.get(member.sourceId) ?? 0) > 1 + ) { + conflicts.push({ + source: 'eod', + sourceId: member.sourceId, + conflictKind: 'duplicate_source_id', + detail: emptyConflictDetail(inst.primaryIsin, member.currency), + }); + statsBySource.eod.conflict += 1; + continue; + } + + const eod = eodBySourceId.get(member.sourceId); + if (eod === undefined) { + unresolved.push({ + source: 'eod', + sourceId: member.sourceId, + reason: 'missing_eod_listing', + primaryIsin: inst.primaryIsin, + }); + statsBySource.eod.unresolved += 1; + continue; + } + + const venue = classifyVenueRoleAndMic(eod.role, eod.mic); + if (!venue.ok) { + if (venue.reason === 'excluded_fund') { + excludedFunds += 1; + } + unresolved.push({ + source: 'eod', + sourceId: member.sourceId, + reason: venue.reason, + primaryIsin: inst.primaryIsin, + }); + statsBySource.eod.unresolved += 1; + continue; + } + + const ticker = classifyTicker(eod.ticker, 'eod'); + if (!ticker.ok) { + unresolved.push({ + source: 'eod', + sourceId: member.sourceId, + reason: ticker.reason, + primaryIsin: inst.primaryIsin, + }); + statsBySource.eod.unresolved += 1; + continue; + } + + const currency = normalizeCurrency(eod.currency ?? member.currency); + if (currency === null) { + unresolved.push({ + source: 'eod', + sourceId: member.sourceId, + reason: 'invalid_currency', + primaryIsin: inst.primaryIsin, + }); + statsBySource.eod.unresolved += 1; + continue; + } + + const spanCheck = validateSpan(eod.span); + if (spanCheck.status === 'invalid') { + unresolved.push({ + source: 'eod', + sourceId: member.sourceId, + reason: 'invalid_span', + primaryIsin: inst.primaryIsin, + }); + statsBySource.eod.unresolved += 1; + continue; + } + const validSpan = spanCheck.status === 'valid' ? spanCheck.span : null; + + const key: ListingNaturalKey = { + primaryIsin: inst.primaryIsin, + mic: venue.mic, + tickerRoot: ticker.tickerRoot, + classSuffix: ticker.classSuffix, + currency, + }; + const keyId = makeListingNaturalKeyId(key); + let acc = listingsByNaturalKey.get(keyId); + if (acc === undefined) { + acc = { + key, + listedFrom: validSpan?.firstBarDate ?? null, + listedTo: validSpan?.lastBarDate ?? null, + ibConid: null, + ibPrimaryExchange: null, + }; + listingsByNaturalKey.set(keyId, acc); + + let byCurrency = listingsByInstrumentCurrency.get(inst.primaryIsin); + if (byCurrency === undefined) { + byCurrency = new Map(); + listingsByInstrumentCurrency.set(inst.primaryIsin, byCurrency); + } + let currencyList = byCurrency.get(currency); + if (currencyList === undefined) { + currencyList = []; + byCurrency.set(currency, currencyList); + } + currencyList.push(acc); + + const tickerKey = makeTickerLookupKey( + venue.mic, + currency, + ticker.tickerRoot, + ticker.classSuffix + ); + let tickerList = listingsByTickerKey.get(tickerKey); + if (tickerList === undefined) { + tickerList = []; + listingsByTickerKey.set(tickerKey, tickerList); + } + tickerList.push(acc); + } else if (validSpan !== null) { + // Associative & commutative min/max widening ensures shuffle invariance. + if (acc.listedFrom === null || validSpan.firstBarDate < acc.listedFrom) { + acc.listedFrom = validSpan.firstBarDate; + } + if (acc.listedTo === null || validSpan.lastBarDate > acc.listedTo) { + acc.listedTo = validSpan.lastBarDate; + } + } + + providerMappings.push({ + source: 'eod', + sourceId: member.sourceId, + listingKey: acc.key, + method: member.method, + validFrom: validSpan?.firstBarDate ?? null, + validTo: validSpan?.lastBarDate ?? null, + }); + statsBySource.eod.matched += 1; + } + } + + for (const [sourceId, count] of eodMetadataCounts.entries()) { + if (count > 1 && (memberCountsBySource.eod.get(sourceId) ?? 0) === 0) { + conflicts.push({ + source: 'eod', + sourceId, + conflictKind: 'duplicate_source_id', + detail: emptyConflictDetail(), + }); + statsBySource.eod.total += 1; + statsBySource.eod.conflict += 1; + } + } + + // Step 2: IB members -> attach conid strictly at (instrument, currency). + const ibCandidatesByListing = new Map(); + + for (let i = 0; i < input.instruments.length; i++) { + const inst = input.instruments[i]; + if (inst === undefined) { + continue; + } + for (let j = 0; j < inst.members.length; j++) { + const member = inst.members[j]; + if (member === undefined || member.source !== 'ib') { + continue; + } + + statsBySource.ib.total += 1; + + if ( + (memberCountsBySource.ib.get(member.sourceId) ?? 0) > 1 || + (ibMetadataCounts.get(member.sourceId) ?? 0) > 1 + ) { + conflicts.push({ + source: 'ib', + sourceId: member.sourceId, + conflictKind: 'duplicate_source_id', + detail: emptyConflictDetail(inst.primaryIsin, member.currency), + }); + statsBySource.ib.conflict += 1; + continue; + } + + const contract = ibBySourceId.get(member.sourceId); + if (contract === undefined) { + unresolved.push({ + source: 'ib', + sourceId: member.sourceId, + reason: 'missing_ib_contract', + primaryIsin: inst.primaryIsin, + }); + statsBySource.ib.unresolved += 1; + continue; + } + + if ( + typeof contract.conid !== 'number' || + !Number.isSafeInteger(contract.conid) || + contract.conid <= 0 + ) { + unresolved.push({ + source: 'ib', + sourceId: member.sourceId, + reason: 'invalid_ib_conid', + primaryIsin: inst.primaryIsin, + }); + statsBySource.ib.unresolved += 1; + continue; + } + + const currency = normalizeCurrency(contract.currency ?? member.currency); + if (currency === null) { + unresolved.push({ + source: 'ib', + sourceId: member.sourceId, + reason: 'invalid_currency', + primaryIsin: inst.primaryIsin, + }); + statsBySource.ib.unresolved += 1; + continue; + } + + const primaryExchange = normalizeOptionalExchangeLabel(contract.primaryExchange); + const candidates = listingsByInstrumentCurrency.get(inst.primaryIsin)?.get(currency); + + if (candidates === undefined || candidates.length === 0) { + unresolved.push({ + source: 'ib', + sourceId: member.sourceId, + reason: 'no_listing_for_currency', + primaryIsin: inst.primaryIsin, + }); + statsBySource.ib.unresolved += 1; + continue; + } + + if (candidates.length > 1) { + const candidateListingKeys = candidates.map(c => c.key).sort(compareListingNaturalKey); + conflicts.push({ + source: 'ib', + sourceId: member.sourceId, + conflictKind: 'ambiguous_ib_listing', + detail: { + primaryIsin: inst.primaryIsin, + currency, + ibConid: contract.conid, + competingConids: [], + candidateListingKeys, + }, + }); + statsBySource.ib.conflict += 1; + continue; + } + + const targetListing = candidates[0]; + if (targetListing === undefined) { + continue; + } + + let staged = ibCandidatesByListing.get(targetListing); + if (staged === undefined) { + staged = []; + ibCandidatesByListing.set(targetListing, staged); + } + staged.push({ + sourceId: member.sourceId, + primaryIsin: inst.primaryIsin, + currency, + conid: contract.conid, + primaryExchange, + method: member.method, + }); + } + } + + for (const [listingAcc, staged] of ibCandidatesByListing.entries()) { + if (staged.length === 1) { + const winner = staged[0]; + if (winner === undefined) { + continue; + } + listingAcc.ibConid = winner.conid; + listingAcc.ibPrimaryExchange = winner.primaryExchange; + providerMappings.push({ + source: 'ib', + sourceId: winner.sourceId, + listingKey: listingAcc.key, + method: winner.method, + validFrom: null, + validTo: null, + }); + statsBySource.ib.matched += 1; + } else if (staged.length > 1) { + const competingConids = Array.from(new Set(staged.map(s => s.conid))).sort((a, b) => a - b); + for (const item of staged) { + conflicts.push({ + source: 'ib', + sourceId: item.sourceId, + conflictKind: 'competing_ib_conid', + detail: { + primaryIsin: item.primaryIsin, + currency: item.currency, + ibConid: item.conid, + competingConids: [...competingConids], + candidateListingKeys: [listingAcc.key], + }, + }); + statsBySource.ib.conflict += 1; + } + } + } + + for (const [sourceId, count] of ibMetadataCounts.entries()) { + if (count > 1 && (memberCountsBySource.ib.get(sourceId) ?? 0) === 0) { + conflicts.push({ + source: 'ib', + sourceId, + conflictKind: 'duplicate_source_id', + detail: emptyConflictDetail(), + }); + statsBySource.ib.total += 1; + statsBySource.ib.conflict += 1; + } + } + + // Step 3: QM / CEO Tier 3 ticker + inclusive spansOverlap matching. + for (let i = 0; i < input.tickerSources.length; i++) { + const record = input.tickerSources[i]; + if (record === undefined) { + continue; + } + const source = record.source; + const sourceStats = statsBySource[source]; + sourceStats.total += 1; + + if ((tickerCountsBySource[source].get(record.sourceId) ?? 0) > 1) { + conflicts.push({ + source, + sourceId: record.sourceId, + conflictKind: 'duplicate_source_id', + detail: emptyConflictDetail(), + }); + sourceStats.conflict += 1; + continue; + } + + const venue = classifyVenueRoleAndMic(record.role, record.mic); + if (!venue.ok) { + if (venue.reason === 'excluded_fund') { + excludedFunds += 1; + } + unresolved.push({ + source, + sourceId: record.sourceId, + reason: venue.reason, + primaryIsin: null, + }); + sourceStats.unresolved += 1; + continue; + } + + const ticker = classifyTicker(record.ticker, source); + if (!ticker.ok) { + unresolved.push({ + source, + sourceId: record.sourceId, + reason: ticker.reason, + primaryIsin: null, + }); + sourceStats.unresolved += 1; + continue; + } + + const currency = normalizeCurrency(record.currency); + if (currency === null) { + unresolved.push({ + source, + sourceId: record.sourceId, + reason: 'invalid_currency', + primaryIsin: null, + }); + sourceStats.unresolved += 1; + continue; + } + + const spanCheck = validateSpan(record.span); + if (spanCheck.status === 'missing') { + unresolved.push({ + source, + sourceId: record.sourceId, + reason: 'missing_span', + primaryIsin: null, + }); + sourceStats.unresolved += 1; + continue; + } + if (spanCheck.status === 'invalid') { + unresolved.push({ + source, + sourceId: record.sourceId, + reason: 'invalid_span', + primaryIsin: null, + }); + sourceStats.unresolved += 1; + continue; + } + + const tickerKey = makeTickerLookupKey( + venue.mic, + currency, + ticker.tickerRoot, + ticker.classSuffix + ); + const candidates = listingsByTickerKey.get(tickerKey); + if (candidates === undefined || candidates.length === 0) { + unresolved.push({ + source, + sourceId: record.sourceId, + reason: 'no_matching_listing', + primaryIsin: null, + }); + sourceStats.unresolved += 1; + continue; + } + + const overlapping: ListingAccumulator[] = []; + let missingSpanCount = 0; + + for (let k = 0; k < candidates.length; k++) { + const cand = candidates[k]; + if (cand === undefined) { + continue; + } + if (cand.listedFrom === null || cand.listedTo === null) { + missingSpanCount += 1; + } else if ( + spansOverlap( + spanCheck.span, + { firstBarDate: cand.listedFrom, lastBarDate: cand.listedTo }, + overlapOptions + ) + ) { + overlapping.push(cand); + } + } + + if (overlapping.length > 1) { + const candidateListingKeys = overlapping.map(c => c.key).sort(compareListingNaturalKey); + conflicts.push({ + source, + sourceId: record.sourceId, + conflictKind: 'ambiguous_ticker_span', + detail: { + primaryIsin: null, + currency, + ibConid: null, + competingConids: [], + candidateListingKeys, + }, + }); + sourceStats.conflict += 1; + } else if (missingSpanCount > 0) { + // Never match when a same-key listing has an unknown span (could hide a reused-ticker collision). + unresolved.push({ + source, + sourceId: record.sourceId, + reason: 'missing_span', + primaryIsin: null, + }); + sourceStats.unresolved += 1; + } else if (overlapping.length === 1) { + const matchedListing = overlapping[0]; + if (matchedListing !== undefined) { + providerMappings.push({ + source, + sourceId: record.sourceId, + listingKey: matchedListing.key, + method: 'tier3_ticker_span', + validFrom: spanCheck.span.firstBarDate, + validTo: spanCheck.span.lastBarDate, + }); + sourceStats.matched += 1; + } + } else { + unresolved.push({ + source, + sourceId: record.sourceId, + reason: 'no_span_overlap', + primaryIsin: null, + }); + sourceStats.unresolved += 1; + } + } + + // Finalize deterministically sorted outputs and stats. + const listings: StageBListingCandidate[] = []; + let listingsWithIbConid = 0; + + for (const acc of listingsByNaturalKey.values()) { + if (acc.ibConid !== null) { + listingsWithIbConid += 1; + } + listings.push({ + primaryIsin: acc.key.primaryIsin, + mic: acc.key.mic, + tickerRoot: acc.key.tickerRoot, + classSuffix: acc.key.classSuffix, + currency: acc.key.currency, + ibConid: acc.ibConid, + ibPrimaryExchange: acc.ibPrimaryExchange, + listedFrom: acc.listedFrom, + listedTo: acc.listedTo, + }); + } + + listings.sort(compareListingNaturalKey); + providerMappings.sort(compareProviderMappings); + unresolved.sort(compareUnresolved); + conflicts.sort(compareConflicts); + + return { + listings, + providerMappings, + unresolved, + conflicts, + stats: { + totalListings: listings.length, + totalProviderMappings: providerMappings.length, + listingsWithIbConid, + excludedFunds, + bySource: statsBySource, + }, + }; +} diff --git a/test/unit/security-master-listing-stage-b.test.ts b/test/unit/security-master-listing-stage-b.test.ts new file mode 100644 index 00000000..9f9255ce --- /dev/null +++ b/test/unit/security-master-listing-stage-b.test.ts @@ -0,0 +1,1395 @@ +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, test } from 'bun:test'; +import { + isStageBSource, + matchListingsStageB, + MAX_TICKER_ROOT_LENGTH, + STAGE_B_SOURCES, + type StageAInstrumentCandidate, + type StageBEodListingInput, + type StageBIbContractInput, + type StageBInput, + type StageBMatchResult, + type StageBTickerSourceInput, +} from '../../apps/stock/data-pipeline/src/security-master'; +import { MAX_CLASS_SUFFIX_LENGTH } from '../../apps/stock/data-pipeline/src/normalization/ticker'; + +const stageBSourcePath = fileURLToPath( + new URL( + '../../apps/stock/data-pipeline/src/security-master/listing-stage-b.ts', + import.meta.url + ) +); + +const ALLOWED_METHODS = new Set(['tier1_isin', 'tier2_cusip', 'tier3_ticker_span']); +const ISO_MIC_PATTERN = /^[A-Z0-9]{4}$/; +const ISO_CURRENCY_PATTERN = /^[A-Z]{3}$/; + +function assertReconciliationAndContracts(result: StageBMatchResult): void { + expect(result.stats.totalListings).toBe(result.listings.length); + expect(result.stats.totalProviderMappings).toBe(result.providerMappings.length); + + let listingsWithConid = 0; + for (const listing of result.listings) { + expect(ISO_MIC_PATTERN.test(listing.mic)).toBe(true); + expect(ISO_CURRENCY_PATTERN.test(listing.currency)).toBe(true); + expect(listing.tickerRoot.length).toBeGreaterThan(0); + expect(listing.tickerRoot.length).toBeLessThanOrEqual(MAX_TICKER_ROOT_LENGTH); + expect(listing.classSuffix.length).toBeLessThanOrEqual(MAX_CLASS_SUFFIX_LENGTH); + if (listing.ibConid !== null) { + expect(Number.isSafeInteger(listing.ibConid)).toBe(true); + expect(listing.ibConid).toBeGreaterThan(0); + listingsWithConid += 1; + } + } + expect(result.stats.listingsWithIbConid).toBe(listingsWithConid); + + const matchedBySource = { eod: 0, ib: 0, qm: 0, ceo: 0 }; + for (const mapping of result.providerMappings) { + expect(ALLOWED_METHODS.has(mapping.method)).toBe(true); + matchedBySource[mapping.source] += 1; + } + + const unresolvedBySource = { eod: 0, ib: 0, qm: 0, ceo: 0 }; + let excludedFundCount = 0; + for (const row of result.unresolved) { + unresolvedBySource[row.source] += 1; + if (row.reason === 'excluded_fund') { + excludedFundCount += 1; + } + } + expect(result.stats.excludedFunds).toBe(excludedFundCount); + + const conflictBySource = { eod: 0, ib: 0, qm: 0, ceo: 0 }; + for (const row of result.conflicts) { + conflictBySource[row.source] += 1; + } + + for (const source of STAGE_B_SOURCES) { + const s = result.stats.bySource[source]; + expect(s.matched).toBe(matchedBySource[source]); + expect(s.unresolved).toBe(unresolvedBySource[source]); + expect(s.conflict).toBe(conflictBySource[source]); + expect(s.matched + s.unresolved + s.conflict).toBe(s.total); + } +} + +function makeRng(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = state; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function shuffleWithSeed(items: readonly T[], seed: number): T[] { + const copy = [...items]; + const rng = makeRng(seed); + for (let i = copy.length - 1; i > 0; i--) { + const j = Math.floor(rng() * (i + 1)); + const tmp = copy[i]; + const swap = copy[j]; + if (tmp !== undefined && swap !== undefined) { + copy[i] = swap; + copy[j] = tmp; + } + } + return copy; +} + +describe('security master Pass 3 Stage B listing matcher', () => { + test('is exported from security-master barrel and performs zero I/O imports', () => { + expect(typeof matchListingsStageB).toBe('function'); + expect(STAGE_B_SOURCES).toEqual(['eod', 'ib', 'qm', 'ceo']); + expect(MAX_TICKER_ROOT_LENGTH).toBe(24); + expect(isStageBSource('eod')).toBe(true); + expect(isStageBSource('ib')).toBe(true); + expect(isStageBSource('qm')).toBe(true); + expect(isStageBSource('ceo')).toBe(true); + expect(isStageBSource('yahoo')).toBe(false); + + const sourceText = readFileSync(stageBSourcePath, 'utf8'); + const forbiddenImports = [ + '@stock-bot/mongodb', + '@stock-bot/postgres', + 'node:fs', + 'node:http', + 'node:https', + 'node:net', + 'bun:sqlite', + "'fs'", + '"fs"', + "'http'", + '"http"', + "'https'", + '"https"', + "'net'", + '"net"', + ]; + for (const forbidden of forbiddenImports) { + expect(sourceText).not.toContain(forbidden); + } + }); + + test('produces 2 listings with matching IB conids for interlisted US+CA instrument and never uses ATS exchangeId as MIC', () => { + const instruments: StageAInstrumentCandidate[] = [ + { + primaryIsin: 'CA82509L1076', + primaryCusip: '82509L107', + issuerCountry: 'CA', + canonicalName: 'Shopify Inc.', + members: [ + { source: 'eod', sourceId: 'SHOP.TO', currency: 'CAD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'SHOP.US', currency: 'USD', method: 'tier2_cusip' }, + { source: 'ib', sourceId: 'ib-shop-cad', currency: 'CAD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-shop-usd', currency: 'USD', method: 'tier2_cusip' }, + ], + }, + ]; + + const eodListings: StageBEodListingInput[] = [ + { + sourceId: 'SHOP.TO', + ticker: 'SHOP', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2015-05-21', lastBarDate: '2025-11-26' }, + }, + { + sourceId: 'SHOP.US', + ticker: 'SHOP', + mic: 'XNYS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2015-05-21', lastBarDate: '2025-11-26' }, + }, + ]; + + // Extra ATS exchangeId fields on raw IB objects must never leak into listing MICs. + const ibContracts: StageBIbContractInput[] = [ + { + sourceId: 'ib-shop-cad', + conid: 194041555, + currency: 'CAD', + primaryExchange: 'tse', + ...({ exchangeId: 'AEQLIT' } as Record), + }, + { + sourceId: 'ib-shop-usd', + conid: 194041552, + currency: 'USD', + primaryExchange: 'nyse', + ...({ exchangeId: 'DRCTEDGE' } as Record), + }, + ]; + + const result = matchListingsStageB({ + instruments, + eodListings, + ibContracts, + tickerSources: [], + }); + + expect(result.unresolved).toEqual([]); + expect(result.conflicts).toEqual([]); + expect(result.listings).toEqual([ + { + primaryIsin: 'CA82509L1076', + mic: 'XNYS', + tickerRoot: 'SHOP', + classSuffix: '', + currency: 'USD', + ibConid: 194041552, + ibPrimaryExchange: 'NYSE', + listedFrom: '2015-05-21', + listedTo: '2025-11-26', + }, + { + primaryIsin: 'CA82509L1076', + mic: 'XTSE', + tickerRoot: 'SHOP', + classSuffix: '', + currency: 'CAD', + ibConid: 194041555, + ibPrimaryExchange: 'TSE', + listedFrom: '2015-05-21', + listedTo: '2025-11-26', + }, + ]); + + const mics = new Set(result.listings.map(l => l.mic)); + expect(mics.has('AEQLIT')).toBe(false); + expect(mics.has('DRCTEDGE')).toBe(false); + + expect(result.providerMappings).toEqual([ + { + source: 'eod', + sourceId: 'SHOP.TO', + listingKey: { + primaryIsin: 'CA82509L1076', + mic: 'XTSE', + tickerRoot: 'SHOP', + classSuffix: '', + currency: 'CAD', + }, + method: 'tier1_isin', + validFrom: '2015-05-21', + validTo: '2025-11-26', + }, + { + source: 'eod', + sourceId: 'SHOP.US', + listingKey: { + primaryIsin: 'CA82509L1076', + mic: 'XNYS', + tickerRoot: 'SHOP', + classSuffix: '', + currency: 'USD', + }, + method: 'tier2_cusip', + validFrom: '2015-05-21', + validTo: '2025-11-26', + }, + { + source: 'ib', + sourceId: 'ib-shop-cad', + listingKey: { + primaryIsin: 'CA82509L1076', + mic: 'XTSE', + tickerRoot: 'SHOP', + classSuffix: '', + currency: 'CAD', + }, + method: 'tier1_isin', + validFrom: null, + validTo: null, + }, + { + source: 'ib', + sourceId: 'ib-shop-usd', + listingKey: { + primaryIsin: 'CA82509L1076', + mic: 'XNYS', + tickerRoot: 'SHOP', + classSuffix: '', + currency: 'USD', + }, + method: 'tier2_cusip', + validFrom: null, + validTo: null, + }, + ]); + assertReconciliationAndContracts(result); + }); + + test('disambiguates reused ticker FB on XNAS USD by span overlap and quarantines cross-span overlap', () => { + const instruments: StageAInstrumentCandidate[] = [ + { + primaryIsin: 'US30303M1027', + primaryCusip: '30303M102', + issuerCountry: 'US', + canonicalName: 'Facebook Inc.', + members: [{ source: 'eod', sourceId: 'FB_META.US', currency: 'USD', method: 'tier1_isin' }], + }, + { + primaryIsin: 'US0000000026', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'FB Financial Reused Ticker', + members: [{ source: 'eod', sourceId: 'FB_NEW.US', currency: 'USD', method: 'tier1_isin' }], + }, + ]; + + const eodListings: StageBEodListingInput[] = [ + { + sourceId: 'FB_META.US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2012-05-18', lastBarDate: '2022-06-08' }, + }, + { + sourceId: 'FB_NEW.US', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2025-01-02', lastBarDate: '2025-11-26' }, + }, + ]; + + const tickerSources: StageBTickerSourceInput[] = [ + { + source: 'qm', + sourceId: 'QM_FB_2015', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2015-01-02', lastBarDate: '2015-12-31' }, + }, + { + source: 'qm', + sourceId: 'QM_FB_2025', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2025-02-03', lastBarDate: '2025-10-31' }, + }, + { + source: 'qm', + sourceId: 'QM_FB_2023', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2023-01-03', lastBarDate: '2023-12-29' }, + }, + { + source: 'qm', + sourceId: 'QM_FB_BOTH', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2025-06-01' }, + }, + ]; + + const result = matchListingsStageB({ + instruments, + eodListings, + ibContracts: [], + tickerSources, + }); + + expect(result.listings).toHaveLength(2); + const qmMappings = result.providerMappings.filter(m => m.source === 'qm'); + expect(qmMappings).toEqual([ + { + source: 'qm', + sourceId: 'QM_FB_2015', + listingKey: { + primaryIsin: 'US30303M1027', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }, + method: 'tier3_ticker_span', + validFrom: '2015-01-02', + validTo: '2015-12-31', + }, + { + source: 'qm', + sourceId: 'QM_FB_2025', + listingKey: { + primaryIsin: 'US0000000026', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }, + method: 'tier3_ticker_span', + validFrom: '2025-02-03', + validTo: '2025-10-31', + }, + ]); + + expect(result.unresolved).toEqual([ + { + source: 'qm', + sourceId: 'QM_FB_2023', + reason: 'no_span_overlap', + primaryIsin: null, + }, + ]); + + expect(result.conflicts).toEqual([ + { + source: 'qm', + sourceId: 'QM_FB_BOTH', + conflictKind: 'ambiguous_ticker_span', + detail: { + primaryIsin: null, + currency: 'USD', + ibConid: null, + competingConids: [], + candidateListingKeys: [ + { + primaryIsin: 'US0000000026', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }, + { + primaryIsin: 'US30303M1027', + mic: 'XNAS', + tickerRoot: 'FB', + classSuffix: '', + currency: 'USD', + }, + ], + }, + }, + ]); + assertReconciliationAndContracts(result); + }); + + test('normalizes CEO .TO/.V suffixes and QM/EOD class-share separators identically', () => { + const result = matchListingsStageB({ + instruments: [ + { + primaryIsin: 'CA0977512007', + primaryCusip: '097751200', + issuerCountry: 'CA', + canonicalName: 'Bombardier Inc. Class B', + members: [{ source: 'eod', sourceId: 'BBD-B.TO', currency: 'CAD', method: 'tier1_isin' }], + }, + { + primaryIsin: 'US0846707026', + primaryCusip: '084670702', + issuerCountry: 'US', + canonicalName: 'Berkshire Hathaway Class B', + members: [{ source: 'eod', sourceId: 'BRK-B.US', currency: 'USD', method: 'tier1_isin' }], + }, + ], + eodListings: [ + { + sourceId: 'BBD-B.TO', + ticker: 'BBD-B', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2010-01-04', lastBarDate: '2025-11-26' }, + }, + { + sourceId: 'BRK-B.US', + ticker: 'BRK-B', + mic: 'XNYS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2010-01-04', lastBarDate: '2025-11-26' }, + }, + ], + ibContracts: [], + tickerSources: [ + { + source: 'ceo', + sourceId: 'ceo-bbd-b', + ticker: 'BBD.B.TO', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2024-12-31' }, + }, + { + source: 'qm', + sourceId: 'qm-brk-b', + ticker: 'BRK.B', + mic: 'XNYS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2021-01-04', lastBarDate: '2024-12-31' }, + }, + ], + }); + + expect(result.unresolved).toEqual([]); + expect(result.conflicts).toEqual([]); + expect(result.providerMappings.filter(m => m.method === 'tier3_ticker_span')).toEqual([ + { + source: 'ceo', + sourceId: 'ceo-bbd-b', + listingKey: { + primaryIsin: 'CA0977512007', + mic: 'XTSE', + tickerRoot: 'BBD', + classSuffix: 'B', + currency: 'CAD', + }, + method: 'tier3_ticker_span', + validFrom: '2020-01-02', + validTo: '2024-12-31', + }, + { + source: 'qm', + sourceId: 'qm-brk-b', + listingKey: { + primaryIsin: 'US0846707026', + mic: 'XNYS', + tickerRoot: 'BRK', + classSuffix: 'B', + currency: 'USD', + }, + method: 'tier3_ticker_span', + validFrom: '2021-01-04', + validTo: '2024-12-31', + }, + ]); + assertReconciliationAndContracts(result); + }); + + test('routes non-primary, excluded-fund, null/invalid MIC venues to distinct unresolved reasons', () => { + const result = matchListingsStageB({ + instruments: [ + { + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Venue Test Corp', + members: [ + { source: 'eod', sourceId: 'EOD_COMP', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'EOD_ATS', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'EOD_FX', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'EOD_FUND', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'EOD_NULL_MIC', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'EOD_NULL_ROLE', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'EOD_BAD_MIC', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'EOD_MISSING_META', currency: 'USD', method: 'tier1_isin' }, + ], + }, + ], + eodListings: [ + { sourceId: 'EOD_COMP', ticker: 'AAPL', mic: null, role: 'composite', currency: 'USD', span: null }, + { sourceId: 'EOD_ATS', ticker: 'AAPL', mic: null, role: 'ats_routing', currency: 'USD', span: null }, + { sourceId: 'EOD_FX', ticker: 'USDCAD', mic: null, role: 'forex', currency: 'USD', span: null }, + { sourceId: 'EOD_FUND', ticker: 'VFIAX', mic: null, role: 'excluded_fund', currency: 'USD', span: null }, + { sourceId: 'EOD_NULL_MIC', ticker: 'AAPL', mic: null, role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'EOD_NULL_ROLE', ticker: 'AAPL', mic: 'XNAS', role: null, currency: 'USD', span: null }, + { sourceId: 'EOD_BAD_MIC', ticker: 'AAPL', mic: 'NASDAQ', role: 'primary_venue', currency: 'USD', span: null }, + ], + ibContracts: [], + tickerSources: [ + { + source: 'qm', + sourceId: 'QM_FUND', + ticker: 'VFIAX', + mic: null, + role: 'excluded_fund', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2024-12-31' }, + }, + { + source: 'ceo', + sourceId: 'CEO_ATS', + ticker: 'SHOP.TO', + mic: null, + role: 'ats_routing', + currency: 'CAD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2024-12-31' }, + }, + ], + }); + + expect(result.listings).toEqual([]); + expect(result.providerMappings).toEqual([]); + expect(result.conflicts).toEqual([]); + expect(result.stats.excludedFunds).toBe(2); + expect(result.unresolved).toEqual([ + { source: 'ceo', sourceId: 'CEO_ATS', reason: 'ats_routing_venue', primaryIsin: null }, + { source: 'eod', sourceId: 'EOD_ATS', reason: 'ats_routing_venue', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'EOD_BAD_MIC', reason: 'invalid_mic', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'EOD_COMP', reason: 'composite_venue', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'EOD_FUND', reason: 'excluded_fund', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'EOD_FX', reason: 'forex_venue', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'EOD_MISSING_META', reason: 'missing_eod_listing', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'EOD_NULL_MIC', reason: 'missing_mic', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'EOD_NULL_ROLE', reason: 'missing_mic', primaryIsin: 'US0378331005' }, + { source: 'qm', sourceId: 'QM_FUND', reason: 'excluded_fund', primaryIsin: null }, + ]); + assertReconciliationAndContracts(result); + }); + + test('handles IB failure modes and quarantines ambiguous_ib_listing and competing_ib_conid without attaching', () => { + const result = matchListingsStageB({ + instruments: [ + // Instrument 1: single USD listing, 2 competing IB conids -> neither attached + { + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Competing Conid Corp', + members: [ + { source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-aapl-1', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-aapl-2', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-aapl-eur', currency: 'EUR', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-aapl-missing', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-aapl-badconid', currency: 'USD', method: 'tier1_isin' }, + ], + }, + // Instrument 2: 2 USD listings -> ambiguous_ib_listing, nothing attached + { + primaryIsin: 'US5949181045', + primaryCusip: '594918104', + issuerCountry: 'US', + canonicalName: 'Ambiguous USD Listings Corp', + members: [ + { source: 'eod', sourceId: 'MSFT_XNAS', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'MSFT_XNYS', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-msft', currency: 'USD', method: 'tier1_isin' }, + ], + }, + ], + eodListings: [ + { sourceId: 'AAPL.US', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'MSFT_XNAS', ticker: 'MSFT', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'MSFT_XNYS', ticker: 'MSFT', mic: 'XNYS', role: 'primary_venue', currency: 'USD', span: null }, + ], + ibContracts: [ + { sourceId: 'ib-aapl-1', conid: 265598, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'ib-aapl-2', conid: 999999, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'ib-aapl-eur', conid: 38708077, currency: 'EUR', primaryExchange: 'IBIS' }, + { sourceId: 'ib-aapl-badconid', conid: 0, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'ib-msft', conid: 272093, currency: 'USD', primaryExchange: 'NASDAQ' }, + ], + tickerSources: [], + }); + + // No listing should have an ibConid attached. + for (const listing of result.listings) { + expect(listing.ibConid).toBeNull(); + expect(listing.ibPrimaryExchange).toBeNull(); + } + expect(result.stats.listingsWithIbConid).toBe(0); + + expect(result.unresolved).toEqual([ + { source: 'ib', sourceId: 'ib-aapl-badconid', reason: 'invalid_ib_conid', primaryIsin: 'US0378331005' }, + { source: 'ib', sourceId: 'ib-aapl-eur', reason: 'no_listing_for_currency', primaryIsin: 'US0378331005' }, + { source: 'ib', sourceId: 'ib-aapl-missing', reason: 'missing_ib_contract', primaryIsin: 'US0378331005' }, + ]); + + expect(result.conflicts).toEqual([ + { + source: 'ib', + sourceId: 'ib-aapl-1', + conflictKind: 'competing_ib_conid', + detail: { + primaryIsin: 'US0378331005', + currency: 'USD', + ibConid: 265598, + competingConids: [265598, 999999], + candidateListingKeys: [ + { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }, + ], + }, + }, + { + source: 'ib', + sourceId: 'ib-aapl-2', + conflictKind: 'competing_ib_conid', + detail: { + primaryIsin: 'US0378331005', + currency: 'USD', + ibConid: 999999, + competingConids: [265598, 999999], + candidateListingKeys: [ + { + primaryIsin: 'US0378331005', + mic: 'XNAS', + tickerRoot: 'AAPL', + classSuffix: '', + currency: 'USD', + }, + ], + }, + }, + { + source: 'ib', + sourceId: 'ib-msft', + conflictKind: 'ambiguous_ib_listing', + detail: { + primaryIsin: 'US5949181045', + currency: 'USD', + ibConid: 272093, + competingConids: [], + candidateListingKeys: [ + { + primaryIsin: 'US5949181045', + mic: 'XNAS', + tickerRoot: 'MSFT', + classSuffix: '', + currency: 'USD', + }, + { + primaryIsin: 'US5949181045', + mic: 'XNYS', + tickerRoot: 'MSFT', + classSuffix: '', + currency: 'USD', + }, + ], + }, + }, + ]); + assertReconciliationAndContracts(result); + }); + + test('enforces span edge cases (missing span on either side, invalid span, and toleranceDays)', () => { + const baseInput: StageBInput = { + instruments: [ + { + primaryIsin: 'US1111111111', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'Null Span Listing', + members: [{ source: 'eod', sourceId: 'NULLSPAN.US', currency: 'USD', method: 'tier1_isin' }], + }, + { + primaryIsin: 'US2222222222', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'Overlap Plus Null Span Partner', + members: [{ source: 'eod', sourceId: 'MIXED_KNOWN.US', currency: 'USD', method: 'tier1_isin' }], + }, + { + primaryIsin: 'US3333333333', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'Mixed Null Span Partner', + members: [{ source: 'eod', sourceId: 'MIXED_NULL.US', currency: 'USD', method: 'tier1_isin' }], + }, + { + primaryIsin: 'US4444444444', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'Adjacent Tolerance Listing', + members: [ + { source: 'eod', sourceId: 'ADJ.US', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'BADSPAN.US', currency: 'USD', method: 'tier1_isin' }, + ], + }, + ], + eodListings: [ + { sourceId: 'NULLSPAN.US', ticker: 'NSPN', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { + sourceId: 'MIXED_KNOWN.US', + ticker: 'MIXD', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2024-12-31' }, + }, + { sourceId: 'MIXED_NULL.US', ticker: 'MIXD', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { + sourceId: 'ADJ.US', + ticker: 'ADJC', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2020-06-30' }, + }, + { + sourceId: 'BADSPAN.US', + ticker: 'BDSP', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2024-06-01', lastBarDate: '2024-01-01' }, + }, + ], + ibContracts: [], + tickerSources: [ + { source: 'qm', sourceId: 'QM_NULL_REC_SPAN', ticker: 'ADJC', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { + source: 'qm', + sourceId: 'QM_NULL_LISTING_SPAN', + ticker: 'NSPN', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2020-12-31' }, + }, + { + source: 'qm', + sourceId: 'QM_MIXED_NULL_PARTNER', + ticker: 'MIXD', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2021-01-04', lastBarDate: '2022-12-30' }, + }, + { + source: 'qm', + sourceId: 'QM_INVALID_DATE', + ticker: 'ADJC', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2023-02-29', lastBarDate: '2023-03-05' }, + }, + { + source: 'qm', + sourceId: 'QM_ADJACENT', + ticker: 'ADJC', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-07-02', lastBarDate: '2020-12-31' }, + }, + ], + }; + + const strict = matchListingsStageB(baseInput); + expect(strict.unresolved).toEqual([ + { source: 'eod', sourceId: 'BADSPAN.US', reason: 'invalid_span', primaryIsin: 'US4444444444' }, + { source: 'qm', sourceId: 'QM_ADJACENT', reason: 'no_span_overlap', primaryIsin: null }, + { source: 'qm', sourceId: 'QM_INVALID_DATE', reason: 'invalid_span', primaryIsin: null }, + { source: 'qm', sourceId: 'QM_MIXED_NULL_PARTNER', reason: 'missing_span', primaryIsin: null }, + { source: 'qm', sourceId: 'QM_NULL_LISTING_SPAN', reason: 'missing_span', primaryIsin: null }, + { source: 'qm', sourceId: 'QM_NULL_REC_SPAN', reason: 'missing_span', primaryIsin: null }, + ]); + assertReconciliationAndContracts(strict); + + const tolerant = matchListingsStageB(baseInput, { spanOverlapToleranceDays: 2 }); + expect(tolerant.providerMappings.filter(m => m.sourceId === 'QM_ADJACENT')).toHaveLength(1); + assertReconciliationAndContracts(tolerant); + + expect(() => matchListingsStageB(baseInput, { spanOverlapToleranceDays: -1 })).toThrow(RangeError); + expect(() => matchListingsStageB(baseInput, { spanOverlapToleranceDays: 1.5 })).toThrow(RangeError); + }); + + test('enforces ticker/classSuffix/currency bounds and does not mask explicitly invalid eod.currency', () => { + const root25 = 'A'.repeat(MAX_TICKER_ROOT_LENGTH + 1); + const suffix13 = 'B'.repeat(MAX_CLASS_SUFFIX_LENGTH + 1); + + const result = matchListingsStageB({ + instruments: [ + { + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Bounds Corp', + members: [ + { source: 'eod', sourceId: 'LONG_ROOT', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'LONG_SUFFIX', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'BAD_TICKER', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'EMPTY_CCY_MASK', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'BAD_CCY_DIGITS', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'BAD_CCY_LEN', currency: 'USD', method: 'tier1_isin' }, + ], + }, + ], + eodListings: [ + { sourceId: 'LONG_ROOT', ticker: root25, mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'LONG_SUFFIX', ticker: `AAPL.${suffix13}`, mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'BAD_TICKER', ticker: 'BRK..B', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'EMPTY_CCY_MASK', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: '', span: null }, + { sourceId: 'BAD_CCY_DIGITS', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: '123', span: null }, + { sourceId: 'BAD_CCY_LEN', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USDD', span: null }, + ], + ibContracts: [], + tickerSources: [ + { + source: 'qm', + sourceId: 'QM_LONG_SUFFIX', + ticker: `BRK-${suffix13}`, + mic: 'XNYS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2024-12-31' }, + }, + { + source: 'ceo', + sourceId: 'CEO_LONG_ROOT', + ticker: `${root25}.TO`, + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2024-12-31' }, + }, + { + source: 'qm', + sourceId: 'QM_SHORT_CCY', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'US', + span: { firstBarDate: '2020-01-02', lastBarDate: '2024-12-31' }, + }, + ], + }); + + expect(result.listings).toEqual([]); + expect(result.unresolved).toEqual([ + { source: 'ceo', sourceId: 'CEO_LONG_ROOT', reason: 'ticker_root_too_long', primaryIsin: null }, + { source: 'eod', sourceId: 'BAD_CCY_DIGITS', reason: 'invalid_currency', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'BAD_CCY_LEN', reason: 'invalid_currency', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'BAD_TICKER', reason: 'invalid_ticker', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'EMPTY_CCY_MASK', reason: 'invalid_currency', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'LONG_ROOT', reason: 'ticker_root_too_long', primaryIsin: 'US0378331005' }, + { source: 'eod', sourceId: 'LONG_SUFFIX', reason: 'class_suffix_too_long', primaryIsin: 'US0378331005' }, + { source: 'qm', sourceId: 'QM_LONG_SUFFIX', reason: 'class_suffix_too_long', primaryIsin: null }, + { source: 'qm', sourceId: 'QM_SHORT_CCY', reason: 'invalid_currency', primaryIsin: null }, + ]); + assertReconciliationAndContracts(result); + }); + + test('quarantines duplicate (source, sourceId) across all inputs and throws on sparse slots or invalid IDs', () => { + const dupResult = matchListingsStageB({ + instruments: [ + { + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: 'Dup Corp', + members: [ + { source: 'eod', sourceId: 'DUP_EOD_MEM', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'DUP_EOD_MEM', currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'DUP_EOD_META', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'DUP_IB_MEM', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'DUP_IB_MEM', currency: 'USD', method: 'tier1_isin' }, + ], + }, + ], + eodListings: [ + { sourceId: 'DUP_EOD_MEM', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'DUP_EOD_META', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'DUP_EOD_META', ticker: 'AAPL', mic: 'XNYS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'ORPHAN_EOD_DUP', ticker: 'ORPH', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + { sourceId: 'ORPHAN_EOD_DUP', ticker: 'ORPH', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + ], + ibContracts: [ + { sourceId: 'DUP_IB_MEM', conid: 100, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'ORPHAN_IB_DUP', conid: 200, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'ORPHAN_IB_DUP', conid: 201, currency: 'USD', primaryExchange: 'NASDAQ' }, + ], + tickerSources: [ + { + source: 'qm', + sourceId: 'DUP_QM', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2024-12-31' }, + }, + { + source: 'qm', + sourceId: 'DUP_QM', + ticker: 'AAPL', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2021-01-02', lastBarDate: '2024-12-31' }, + }, + ], + }); + + expect(dupResult.listings).toEqual([]); + expect(dupResult.providerMappings).toEqual([]); + expect(dupResult.conflicts.every(c => c.conflictKind === 'duplicate_source_id')).toBe(true); + expect(dupResult.conflicts).toHaveLength(9); + assertReconciliationAndContracts(dupResult); + + // Sparse array slots throw naming the index. + const sparseInstruments = new Array(2) as unknown as StageAInstrumentCandidate[]; + sparseInstruments[1] = { + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: null, + members: [], + }; + expect(() => + matchListingsStageB({ + instruments: sparseInstruments, + eodListings: [], + ibContracts: [], + tickerSources: [], + }) + ).toThrow(/instruments\[0\]/); + + const sparseMembers = new Array(2) as unknown as StageAInstrumentCandidate['members']; + sparseMembers[1] = { source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }; + expect(() => + matchListingsStageB({ + instruments: [ + { + primaryIsin: 'US0378331005', + primaryCusip: '037833100', + issuerCountry: 'US', + canonicalName: null, + members: sparseMembers, + }, + ], + eodListings: [], + ibContracts: [], + tickerSources: [], + }) + ).toThrow(/instruments\[0\]\.members\[0\]/); + + const sparseEod = new Array(2) as unknown as StageBEodListingInput[]; + sparseEod[0] = { sourceId: 'A', ticker: 'A', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }; + expect(() => + matchListingsStageB({ + instruments: [], + eodListings: sparseEod, + ibContracts: [], + tickerSources: [], + }) + ).toThrow(/eodListings\[1\]/); + + const sparseIb = new Array(2) as unknown as StageBIbContractInput[]; + sparseIb[0] = { sourceId: '1', conid: 1, currency: 'USD', primaryExchange: null }; + expect(() => + matchListingsStageB({ + instruments: [], + eodListings: [], + ibContracts: sparseIb, + tickerSources: [], + }) + ).toThrow(/ibContracts\[1\]/); + + const sparseTickers = new Array(2) as unknown as StageBTickerSourceInput[]; + sparseTickers[0] = { + source: 'qm', + sourceId: 'Q1', + ticker: 'A', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: null, + }; + expect(() => + matchListingsStageB({ + instruments: [], + eodListings: [], + ibContracts: [], + tickerSources: sparseTickers, + }) + ).toThrow(/tickerSources\[1\]/); + + // Non-string / empty IDs throw naming the index. + expect(() => + matchListingsStageB({ + instruments: [ + { + primaryIsin: '', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: null, + members: [], + }, + ], + eodListings: [], + ibContracts: [], + tickerSources: [], + }) + ).toThrow(/instruments\[0\]/); + + expect(() => + matchListingsStageB({ + instruments: [], + eodListings: [ + { sourceId: '', ticker: 'AAPL', mic: 'XNAS', role: 'primary_venue', currency: 'USD', span: null }, + ], + ibContracts: [], + tickerSources: [], + }) + ).toThrow(/eodListings\[0\]/); + }); + + test('is invariant to shuffling every input array and matches ReadonlyMap inputs identically', () => { + const instruments: StageAInstrumentCandidate[] = [ + { + primaryIsin: 'CA82509L1076', + primaryCusip: '82509L107', + issuerCountry: 'CA', + canonicalName: 'Shopify Inc.', + members: [ + { source: 'eod', sourceId: 'SHOP.TO', currency: 'CAD', method: 'tier1_isin' }, + { source: 'eod', sourceId: 'SHOP.TO.ALT', currency: 'CAD', method: 'tier2_cusip' }, + { source: 'eod', sourceId: 'SHOP.US', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-shop-cad', currency: 'CAD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-shop-usd', currency: 'USD', method: 'tier1_isin' }, + ], + }, + { + primaryIsin: 'US30303M1027', + primaryCusip: '30303M102', + issuerCountry: 'US', + canonicalName: 'Facebook Inc.', + members: [ + { source: 'eod', sourceId: 'FB_OLD', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-fb-1', currency: 'USD', method: 'tier1_isin' }, + { source: 'ib', sourceId: 'ib-fb-2', currency: 'USD', method: 'tier1_isin' }, + ], + }, + { + primaryIsin: 'US0000000026', + primaryCusip: null, + issuerCountry: 'US', + canonicalName: 'FB New', + members: [{ source: 'eod', sourceId: 'FB_NEW', currency: 'USD', method: 'tier1_isin' }], + }, + ]; + + const eodListings: StageBEodListingInput[] = [ + { + sourceId: 'SHOP.TO', + ticker: 'SHOP', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2015-05-21', lastBarDate: '2022-12-31' }, + }, + { + sourceId: 'SHOP.TO.ALT', + ticker: 'SHOP', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2025-11-26' }, + }, + { + sourceId: 'SHOP.US', + ticker: 'SHOP', + mic: 'XNYS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2015-05-21', lastBarDate: '2025-11-26' }, + }, + { + sourceId: 'FB_OLD', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2012-05-18', lastBarDate: '2022-06-08' }, + }, + { + sourceId: 'FB_NEW', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2025-01-02', lastBarDate: '2025-11-26' }, + }, + ]; + + const ibContracts: StageBIbContractInput[] = [ + { sourceId: 'ib-shop-cad', conid: 194041555, currency: 'CAD', primaryExchange: 'TSE' }, + { sourceId: 'ib-shop-usd', conid: 194041552, currency: 'USD', primaryExchange: 'NYSE' }, + { sourceId: 'ib-fb-1', conid: 107113386, currency: 'USD', primaryExchange: 'NASDAQ' }, + { sourceId: 'ib-fb-2', conid: 999113386, currency: 'USD', primaryExchange: 'NASDAQ' }, + ]; + + const tickerSources: StageBTickerSourceInput[] = [ + { + source: 'ceo', + sourceId: 'ceo-shop', + ticker: 'SHOP.TO', + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2018-01-02', lastBarDate: '2024-12-31' }, + }, + { + source: 'qm', + sourceId: 'qm-fb-old', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2016-01-04', lastBarDate: '2017-12-29' }, + }, + { + source: 'qm', + sourceId: 'qm-fb-both', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2020-01-02', lastBarDate: '2025-06-01' }, + }, + { + source: 'qm', + sourceId: 'qm-fb-gap', + ticker: 'FB', + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2023-01-03', lastBarDate: '2023-12-29' }, + }, + ]; + + const baseline = matchListingsStageB({ + instruments, + eodListings, + ibContracts, + tickerSources, + }); + const baselineJson = JSON.stringify(baseline); + assertReconciliationAndContracts(baseline); + + // Same-natural-key EOD members widened listedFrom/listedTo to [2015-05-21, 2025-11-26]. + const shopCad = baseline.listings.find(l => l.mic === 'XTSE' && l.tickerRoot === 'SHOP'); + expect(shopCad?.listedFrom).toBe('2015-05-21'); + expect(shopCad?.listedTo).toBe('2025-11-26'); + + // ReadonlyMap inputs match array inputs byte-for-byte. + const eodMap = new Map(eodListings.map(({ sourceId, ...rest }) => [sourceId, rest])); + const ibMap = new Map(ibContracts.map(({ sourceId, ...rest }) => [sourceId, rest])); + const mapResult = matchListingsStageB({ + instruments, + eodListings: eodMap, + ibContracts: ibMap, + tickerSources, + }); + expect(JSON.stringify(mapResult)).toBe(baselineJson); + + // Shuffling every input array (including inner members) yields byte-identical output. + for (const seed of [7, 42, 1337, 202611]) { + const shuffledInstruments = shuffleWithSeed(instruments, seed).map((inst, idx) => ({ + ...inst, + members: shuffleWithSeed(inst.members, seed + idx + 100), + })); + const shuffledResult = matchListingsStageB({ + instruments: shuffledInstruments, + eodListings: shuffleWithSeed(eodListings, seed + 1), + ibContracts: shuffleWithSeed(ibContracts, seed + 2), + tickerSources: shuffleWithSeed(tickerSources, seed + 3), + }); + expect(JSON.stringify(shuffledResult)).toBe(baselineJson); + assertReconciliationAndContracts(shuffledResult); + } + }); + + test('local scale benchmark: ~20k instruments, ~60k EOD, ~18k IB, ~40k QM/CEO complete under 5000 ms', () => { + const NUM_INSTRUMENTS = 20_000; + const instruments: StageAInstrumentCandidate[] = new Array( + NUM_INSTRUMENTS + ); + const eodListings: StageBEodListingInput[] = []; + const ibContracts: StageBIbContractInput[] = []; + const tickerSources: StageBTickerSourceInput[] = []; + + for (let i = 0; i < NUM_INSTRUMENTS; i++) { + const isCa = (i & 1) === 1; + const isin = `${isCa ? 'CA' : 'US'}${String(1000000000 + i)}`; + const ticker = `T${i}`; + const members: StageAInstrumentCandidate['members'] = []; + + // 3 EOD members per instrument = 60,000 EOD records (2 primary venues + 1 composite/fund). + const eodPrimary1 = `EOD1_${i}`; + const eodPrimary2 = `EOD2_${i}`; + const eodNonPrimary = `EOD3_${i}`; + members.push( + { source: 'eod', sourceId: eodPrimary1, currency: 'USD', method: 'tier1_isin' }, + { source: 'eod', sourceId: eodPrimary2, currency: 'CAD', method: 'tier2_cusip' }, + { source: 'eod', sourceId: eodNonPrimary, currency: 'USD', method: 'tier1_isin' } + ); + eodListings.push( + { + sourceId: eodPrimary1, + ticker, + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2015-01-02', lastBarDate: '2025-11-26' }, + }, + { + sourceId: eodPrimary2, + ticker, + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2015-01-02', lastBarDate: '2025-11-26' }, + }, + { + sourceId: eodNonPrimary, + ticker, + mic: null, + role: i % 10 === 0 ? 'excluded_fund' : 'composite', + currency: 'USD', + span: null, + } + ); + + // 18,000 IB members (90% of instruments). + if (i < 18_000) { + const ibId = `IB_${i}`; + const ibCcy = isCa ? 'CAD' : 'USD'; + members.push({ source: 'ib', sourceId: ibId, currency: ibCcy, method: 'tier1_isin' }); + ibContracts.push({ + sourceId: ibId, + conid: 100_000 + i, + currency: ibCcy, + primaryExchange: isCa ? 'TSE' : 'NASDAQ', + }); + } + + instruments[i] = { + primaryIsin: isin, + primaryCusip: null, + issuerCountry: isCa ? 'CA' : 'US', + canonicalName: `Issuer ${i}`, + members, + }; + + // 40,000 QM + CEO records (20k QM USD + 20k CEO CAD). + tickerSources.push( + { + source: 'qm', + sourceId: `QM_${i}`, + ticker, + mic: 'XNAS', + role: 'primary_venue', + currency: 'USD', + span: { firstBarDate: '2018-01-02', lastBarDate: '2024-12-31' }, + }, + { + source: 'ceo', + sourceId: `CEO_${i}`, + ticker: `${ticker}.TO`, + mic: 'XTSE', + role: 'primary_venue', + currency: 'CAD', + span: { firstBarDate: '2019-01-02', lastBarDate: '2025-06-30' }, + } + ); + } + + const startMs = performance.now(); + const result = matchListingsStageB({ + instruments, + eodListings, + ibContracts, + tickerSources, + }); + const elapsedMs = performance.now() - startMs; + + process.stdout.write( + `[benchmark] matchListingsStageB(${NUM_INSTRUMENTS} instruments, ${eodListings.length} EOD, ${ibContracts.length} IB, ${tickerSources.length} QM+CEO): ${elapsedMs.toFixed(1)} ms (${result.stats.totalListings} listings, ${result.stats.totalProviderMappings} mappings)\n` + ); + + expect(elapsedMs).toBeLessThan(5000); + expect(result.stats.totalListings).toBe(40_000); + expect(result.stats.listingsWithIbConid).toBe(18_000); + expect(result.stats.excludedFunds).toBe(2_000); + expect(result.stats.bySource.eod.total).toBe(60_000); + expect(result.stats.bySource.eod.matched).toBe(40_000); + expect(result.stats.bySource.eod.unresolved).toBe(20_000); + expect(result.stats.bySource.ib.total).toBe(18_000); + expect(result.stats.bySource.ib.matched).toBe(18_000); + expect(result.stats.bySource.qm.matched).toBe(20_000); + expect(result.stats.bySource.ceo.matched).toBe(20_000); + assertReconciliationAndContracts(result); + }); +});