stock-bot/apps/stock/data-pipeline/src/security-master/exchange-pass1.ts

771 lines
34 KiB
TypeScript

export const EXCHANGE_SOURCES = ['eod', 'qm', 'ib', 'ceo'] as const;
export type ExchangeSource = (typeof EXCHANGE_SOURCES)[number];
export type ExchangeRole =
| 'primary_venue'
| 'composite'
| 'ats_routing'
| 'forex'
| 'excluded_fund';
export type BoardLotPolicy = 'us_100' | 'tsx_tiered' | 'fx';
export type ClassificationMethod = 'explicit_rule' | 'operating_mic';
export const MAX_EXCHANGE_SOURCE_CODE_LENGTH = 32;
export type UnresolvedExchangeReason =
| 'empty_code'
| 'source_code_too_long'
| 'multi_valued_operating_mic'
| 'invalid_operating_mic_format'
| 'unknown_operating_mic'
| 'missing_operating_mic';
export interface SourceExchangeRecord {
source: ExchangeSource;
code: string;
name?: string | null;
country?: string | null;
operatingMic?: string | null;
currency?: string | null;
}
export interface ExchangeSeedRow {
mic: string;
operatingMic: string;
name: string;
countryIso: string;
currency: string;
timezone: string;
calendarCode: string;
boardLotPolicy: BoardLotPolicy;
}
export interface ExchangeSourceMapRow {
source: ExchangeSource;
sourceCode: string;
role: ExchangeRole;
mic: string | null;
countryIso: string | null;
method: ClassificationMethod;
reviewedBy?: string | null;
}
export interface UnresolvedExchangeRecord {
source: ExchangeSource;
sourceCode: string;
rawCode: string;
name: string | null;
country: string | null;
operatingMic: string | null;
currency: string | null;
reason: UnresolvedExchangeReason;
}
export interface ExchangeClassificationResult {
mapped: ExchangeSourceMapRow[];
unresolved: UnresolvedExchangeRecord[];
}
export interface ClassifySourceExchangesOptions {
knownExchanges?: readonly ExchangeSeedRow[];
reviewedRows?: readonly ExchangeSourceMapRow[];
}
const VALID_EXCHANGE_SOURCE_SET: ReadonlySet<string> = new Set(EXCHANGE_SOURCES);
const ISO_MIC_PATTERN = /^[A-Z0-9]{4}$/;
const MULTI_VALUE_MIC_SEPARATOR = /[,;/|\s]+/;
/**
* Locale-independent ASCII comparison so sort order never varies across hosts.
*/
export function compareAscii(a: string, b: string): number {
if (a < b) {
return -1;
}
if (a > b) {
return 1;
}
return 0;
}
export function compareUnresolvedExchangeRecords(
a: UnresolvedExchangeRecord,
b: UnresolvedExchangeRecord
): number {
return (
compareAscii(a.source, b.source) ||
compareAscii(a.sourceCode, b.sourceCode) ||
compareAscii(a.reason, b.reason) ||
compareAscii(a.rawCode, b.rawCode) ||
compareAscii(a.operatingMic ?? '', b.operatingMic ?? '') ||
compareAscii(a.name ?? '', b.name ?? '') ||
compareAscii(a.country ?? '', b.country ?? '') ||
compareAscii(a.currency ?? '', b.currency ?? '')
);
}
export function isExchangeSource(value: unknown): value is ExchangeSource {
return typeof value === 'string' && VALID_EXCHANGE_SOURCE_SET.has(value);
}
/**
* Baseline ISO 10383 MIC seeds for the US + Canada security-master scope,
* sorted ascending by MIC.
*/
export const ISO_EXCHANGE_SEEDS: readonly ExchangeSeedRow[] = Object.freeze([
{
mic: 'ARCX',
operatingMic: 'XNYS',
name: 'NYSE Arca',
countryIso: 'US',
currency: 'USD',
timezone: 'America/New_York',
calendarCode: 'XNYS',
boardLotPolicy: 'us_100',
},
{
mic: 'BATS',
operatingMic: 'BATS',
name: 'Cboe BZX Exchange',
countryIso: 'US',
currency: 'USD',
timezone: 'America/New_York',
calendarCode: 'XNYS',
boardLotPolicy: 'us_100',
},
{
mic: 'IEXG',
operatingMic: 'IEXG',
name: 'Investors Exchange',
countryIso: 'US',
currency: 'USD',
timezone: 'America/New_York',
calendarCode: 'XNYS',
boardLotPolicy: 'us_100',
},
{
mic: 'NEOE',
operatingMic: 'NEOE',
name: 'Cboe Canada (NEO Exchange)',
countryIso: 'CA',
currency: 'CAD',
timezone: 'America/Toronto',
calendarCode: 'XTSE',
boardLotPolicy: 'tsx_tiered',
},
{
mic: 'OTCM',
operatingMic: 'OTCM',
name: 'OTC Markets',
countryIso: 'US',
currency: 'USD',
timezone: 'America/New_York',
calendarCode: 'XNYS',
boardLotPolicy: 'us_100',
},
{
mic: 'XASE',
operatingMic: 'XNYS',
name: 'NYSE American',
countryIso: 'US',
currency: 'USD',
timezone: 'America/New_York',
calendarCode: 'XNYS',
boardLotPolicy: 'us_100',
},
{
mic: 'XCNQ',
operatingMic: 'XCNQ',
name: 'Canadian Securities Exchange',
countryIso: 'CA',
currency: 'CAD',
timezone: 'America/Toronto',
calendarCode: 'XTSE',
boardLotPolicy: 'tsx_tiered',
},
{
mic: 'XNAS',
operatingMic: 'XNAS',
name: 'NASDAQ Stock Market',
countryIso: 'US',
currency: 'USD',
timezone: 'America/New_York',
calendarCode: 'XNYS',
boardLotPolicy: 'us_100',
},
{
mic: 'XNYS',
operatingMic: 'XNYS',
name: 'New York Stock Exchange',
countryIso: 'US',
currency: 'USD',
timezone: 'America/New_York',
calendarCode: 'XNYS',
boardLotPolicy: 'us_100',
},
{
mic: 'XTSE',
operatingMic: 'XTSE',
name: 'Toronto Stock Exchange',
countryIso: 'CA',
currency: 'CAD',
timezone: 'America/Toronto',
calendarCode: 'XTSE',
boardLotPolicy: 'tsx_tiered',
},
{
mic: 'XTSX',
operatingMic: 'XTSX',
name: 'TSX Venture Exchange',
countryIso: 'CA',
currency: 'CAD',
timezone: 'America/Toronto',
calendarCode: 'XTSE',
boardLotPolicy: 'tsx_tiered',
},
]);
export interface ExplicitExchangeSourceRule {
source: ExchangeSource;
sourceCode: string;
role: ExchangeRole;
mic: string | null;
countryIso: string | null;
}
/**
* Documented explicit exchange-code mappings from design/PLATFORM-PLAN.md and
* design/DATA-CONTRACTS.md, sorted by (source, sourceCode).
*/
export const EXPLICIT_EXCHANGE_SOURCE_RULES: readonly ExplicitExchangeSourceRule[] = Object.freeze([
{ source: 'ceo', sourceCode: 'AQL', role: 'primary_venue', mic: 'NEOE', countryIso: 'CA' },
{ source: 'ceo', sourceCode: 'CDX', role: 'primary_venue', mic: 'XTSX', countryIso: 'CA' },
{ source: 'ceo', sourceCode: 'CNQ', role: 'primary_venue', mic: 'XCNQ', countryIso: 'CA' },
{ source: 'ceo', sourceCode: 'TSX', role: 'primary_venue', mic: 'XTSE', countryIso: 'CA' },
{ source: 'eod', sourceCode: 'FOREX', role: 'forex', mic: null, countryIso: null },
{ source: 'eod', sourceCode: 'NMFQS', role: 'excluded_fund', mic: null, countryIso: 'US' },
{ source: 'eod', sourceCode: 'US', role: 'composite', mic: null, countryIso: 'US' },
{ source: 'ib', sourceCode: 'AEQLIT', role: 'ats_routing', mic: null, countryIso: 'CA' },
{ source: 'ib', sourceCode: 'ARCAEDGE', role: 'ats_routing', mic: null, countryIso: 'US' },
{ source: 'ib', sourceCode: 'BEX', role: 'ats_routing', mic: null, countryIso: 'US' },
{ source: 'ib', sourceCode: 'DRCTEDGE', role: 'ats_routing', mic: null, countryIso: 'US' },
{ source: 'ib', sourceCode: 'EDGEA', role: 'ats_routing', mic: null, countryIso: 'US' },
{ source: 'ib', sourceCode: 'IBEOS', role: 'ats_routing', mic: null, countryIso: 'US' },
{ source: 'ib', sourceCode: 'IEX', role: 'ats_routing', mic: null, countryIso: 'US' },
{ source: 'ib', sourceCode: 'MEMX', role: 'ats_routing', mic: null, countryIso: 'US' },
{ source: 'ib', sourceCode: 'OTCLNKECN', role: 'ats_routing', mic: null, countryIso: 'US' },
{ source: 'ib', sourceCode: 'PSX', role: 'ats_routing', mic: null, countryIso: 'US' },
]);
export const EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMapRow[] = Object.freeze(
EXPLICIT_EXCHANGE_SOURCE_RULES.map(rule => ({
source: rule.source,
sourceCode: rule.sourceCode,
role: rule.role,
mic: rule.mic,
countryIso: rule.countryIso,
method: 'explicit_rule' as const,
reviewedBy: null,
}))
);
/**
* Reviewed US + Canada provider venue mappings supplementing the immutable
* 17-row Pass 1 baseline seed (`35-security-master-exchange-seed.sql`).
* Covers EOD US sub-exchanges under composite `eodExchange="US"` (`NASDAQ`,
* `NYSE`, `PINK`, etc.), EOD CA venues, IB primary venues, and QuoteMedia
* US/CA venue codes (whose `qmExchanges` collection carries no OperatingMICs),
* sorted by `(source, sourceCode)`.
*/
export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMapRow[] =
Object.freeze(
[
// EOD US + CA primary venues
{ source: 'eod' as const, sourceCode: 'AMEX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'BATS', role: 'primary_venue' as const, mic: 'BATS', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'CN', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' },
{ source: 'eod' as const, sourceCode: 'IEX', role: 'primary_venue' as const, mic: 'IEXG', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'NASDAQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'NEO', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
{ source: 'eod' as const, sourceCode: 'NYSE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'NYSE ARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'NYSE MKT', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'NYSE NAT', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'NYSEARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'NYSEMKT', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTC', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCBB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCCE', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCGREY', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCMKTS', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCMTKS', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCQB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'OTCQX', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'eod' as const, sourceCode: 'TO', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' },
{ source: 'eod' as const, sourceCode: 'V', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
// IB US + CA venues (additional ATS/routing venues live in EXPLICIT_EXCHANGE_SOURCE_RULES)
{ source: 'ib' as const, sourceCode: 'AMEX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'ARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'BATS', role: 'primary_venue' as const, mic: 'BATS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'BOX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'BYX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CBOE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CBOE2', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CBOT', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CDE', role: 'ats_routing' as const, mic: null, countryIso: 'CA' },
{ source: 'ib' as const, sourceCode: 'CFE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CFETAS', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CHX', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'CME', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'COMEX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'EDGX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'EMERALD', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'FORECASTX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'FUNDSERV', role: 'excluded_fund' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'GEMINI', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IBCMDTY', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IBDESK', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IBFX', role: 'forex' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IBKRAM', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IBKRATS', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IBUSCFD', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'ICEUS', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'IDEALPRO', role: 'forex' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'ISE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'ISLAND', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'LTSE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'MERCURY', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'MIAX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NASDAQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NASDAQBX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NASDAQOM', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NEO', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
{ source: 'ib' as const, sourceCode: 'NYBOT', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NYMEX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NYSE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NYSEFLOOR', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NYSELIFFE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'NYSENAT', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'OVERNIGHT', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'PEARL', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'PHLX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'PSE', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'PURE', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' },
{ source: 'ib' as const, sourceCode: 'SGXCME', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'SMFE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'TRADEWEB', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'TSE', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' },
{ source: 'ib' as const, sourceCode: 'VALUE', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'ib' as const, sourceCode: 'VENTURE', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
{ source: 'ib' as const, sourceCode: 'ZEROHASH', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
// QuoteMedia US + CA venues (qmExchanges has 0% OperatingMIC)
{ source: 'qm' as const, sourceCode: 'AMEX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'AMX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'AQL', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'AQLL', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'ARC', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'ARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'ASE', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'BATS', role: 'primary_venue' as const, mic: 'BATS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'BTS', role: 'primary_venue' as const, mic: 'BATS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'BZX', role: 'primary_venue' as const, mic: 'BATS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'CC', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'CCQ TSX', role: 'composite' as const, mic: null, countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'CCQ TSXV', role: 'composite' as const, mic: null, countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'CDX', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'CNQ', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'CNX', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'CSE', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'CVE', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'CVEM', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'EDGA', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'EDGX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'EGX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'EXPM', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'GREY', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'IEX', role: 'primary_venue' as const, mic: 'IEXG', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'MOE', role: 'ats_routing' as const, mic: null, countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'NASDAQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NCM', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NDD', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NEO', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'NEOE', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'NGM', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NGS', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NMF', role: 'excluded_fund' as const, mic: null, countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NSC', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NSD', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NSQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NYE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NYS', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NYSE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NYSE AMERICAN', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'NYSEMKT', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'OBB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'OTC', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'OTCBB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'OTCMKTS', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'OTCQB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'OTCQX', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'PCX', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'PINL', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'PNK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'QB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'QX', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
{ source: 'qm' as const, sourceCode: 'TOR', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'TSE', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'TSV', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'TSX', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'TSXC', role: 'composite' as const, mic: null, countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'TSXV', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'TSXVC', role: 'composite' as const, mic: null, countryIso: 'CA' },
{ source: 'qm' as const, sourceCode: 'VNX', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
].map(rule => ({
...rule,
method: 'explicit_rule' as const,
reviewedBy: 'reviewed_us_ca_venues',
}))
);
function makeRuleKey(source: ExchangeSource, sourceCode: string): string {
return `${source}\u0000${sourceCode}`;
}
const EXPLICIT_RULES_BY_KEY = new Map<string, ExplicitExchangeSourceRule>(
EXPLICIT_EXCHANGE_SOURCE_RULES.map(rule => [makeRuleKey(rule.source, rule.sourceCode), rule])
);
function normalizeOptionalString(value: string | null | undefined): string | null {
if (value === null || value === undefined) {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
function compareSourceRecordsDeterministically(
a: SourceExchangeRecord,
b: SourceExchangeRecord
): number {
return (
compareAscii(a.code, b.code) ||
compareAscii(normalizeOptionalString(a.operatingMic) ?? '', normalizeOptionalString(b.operatingMic) ?? '') ||
compareAscii(normalizeOptionalString(a.name) ?? '', normalizeOptionalString(b.name) ?? '') ||
compareAscii(normalizeOptionalString(a.country) ?? '', normalizeOptionalString(b.country) ?? '') ||
compareAscii(normalizeOptionalString(a.currency) ?? '', normalizeOptionalString(b.currency) ?? '')
);
}
function pickFirstNonNull(
records: readonly SourceExchangeRecord[],
selector: (record: SourceExchangeRecord) => string | null | undefined
): string | null {
for (const record of records) {
const value = normalizeOptionalString(selector(record));
if (value !== null) {
return value;
}
}
return null;
}
export function classifySourceExchanges(
records: readonly SourceExchangeRecord[],
options: ClassifySourceExchangesOptions = {}
): ExchangeClassificationResult {
const knownExchanges = options.knownExchanges ?? ISO_EXCHANGE_SEEDS;
const knownByMic = new Map<string, ExchangeSeedRow>(
knownExchanges.map(exchange => [exchange.mic.trim().toUpperCase(), exchange])
);
const reviewedByKey = new Map<string, ExchangeSourceMapRow>();
if (options.reviewedRows) {
for (const row of options.reviewedRows) {
reviewedByKey.set(makeRuleKey(row.source, row.sourceCode.trim().toUpperCase()), row);
}
}
const grouped = new Map<string, { source: ExchangeSource; sourceCode: string; records: SourceExchangeRecord[] }>();
const unresolved: UnresolvedExchangeRecord[] = [];
for (const record of records) {
if (!isExchangeSource(record.source)) {
throw new Error(
`Unknown exchange source "${String(record.source)}" for exchange code "${String(record.code)}"`
);
}
const rawCode = typeof record.code === 'string' ? record.code : String(record.code ?? '');
const normalizedCode = rawCode.trim().toUpperCase();
if (normalizedCode.length === 0) {
unresolved.push({
source: record.source,
sourceCode: '',
rawCode,
name: normalizeOptionalString(record.name),
country: normalizeOptionalString(record.country),
operatingMic: normalizeOptionalString(record.operatingMic),
currency: normalizeOptionalString(record.currency),
reason: 'empty_code',
});
continue;
}
if (normalizedCode.length > MAX_EXCHANGE_SOURCE_CODE_LENGTH) {
unresolved.push({
source: record.source,
sourceCode: normalizedCode,
rawCode,
name: normalizeOptionalString(record.name),
country: normalizeOptionalString(record.country),
operatingMic: normalizeOptionalString(record.operatingMic),
currency: normalizeOptionalString(record.currency),
reason: 'source_code_too_long',
});
continue;
}
const key = makeRuleKey(record.source, normalizedCode);
const existing = grouped.get(key);
if (existing) {
existing.records.push(record);
} else {
grouped.set(key, {
source: record.source,
sourceCode: normalizedCode,
records: [record],
});
}
}
const mapped: ExchangeSourceMapRow[] = [];
for (const group of grouped.values()) {
const explicitRule = EXPLICIT_RULES_BY_KEY.get(makeRuleKey(group.source, group.sourceCode));
if (explicitRule) {
mapped.push({
source: explicitRule.source,
sourceCode: explicitRule.sourceCode,
role: explicitRule.role,
mic: explicitRule.mic,
countryIso: explicitRule.countryIso,
method: 'explicit_rule',
reviewedBy: null,
});
continue;
}
const reviewedRow = reviewedByKey.get(makeRuleKey(group.source, group.sourceCode));
if (reviewedRow) {
mapped.push({
source: reviewedRow.source,
sourceCode: reviewedRow.sourceCode.trim().toUpperCase(),
role: reviewedRow.role,
mic: reviewedRow.mic,
countryIso: reviewedRow.countryIso,
method: reviewedRow.method,
reviewedBy: reviewedRow.reviewedBy ?? null,
});
continue;
}
// Sort group deterministically so duplicate collapse is independent of input order.
const sortedRecords = [...group.records].sort(compareSourceRecordsDeterministically);
const representative = sortedRecords[0];
const name = pickFirstNonNull(sortedRecords, r => r.name);
const country = pickFirstNonNull(sortedRecords, r => r.country);
const currency = pickFirstNonNull(sortedRecords, r => r.currency);
const rawMics: string[] = [];
for (const record of sortedRecords) {
const micValue = normalizeOptionalString(record.operatingMic);
if (micValue !== null) {
rawMics.push(micValue);
}
}
if (rawMics.length === 0) {
unresolved.push({
source: group.source,
sourceCode: group.sourceCode,
rawCode: representative?.code ?? group.sourceCode,
name,
country,
operatingMic: null,
currency,
reason: 'missing_operating_mic',
});
continue;
}
const hasMultiValuedEntry = rawMics.some(mic => MULTI_VALUE_MIC_SEPARATOR.test(mic));
if (hasMultiValuedEntry) {
const distinctRaw = Array.from(new Set(rawMics)).sort(compareAscii);
unresolved.push({
source: group.source,
sourceCode: group.sourceCode,
rawCode: representative?.code ?? group.sourceCode,
name,
country,
operatingMic: distinctRaw.join('; '),
currency,
reason: 'multi_valued_operating_mic',
});
continue;
}
const distinctNormalizedMics = Array.from(
new Set(rawMics.map(mic => mic.toUpperCase()))
).sort(compareAscii);
if (distinctNormalizedMics.length > 1) {
unresolved.push({
source: group.source,
sourceCode: group.sourceCode,
rawCode: representative?.code ?? group.sourceCode,
name,
country,
operatingMic: distinctNormalizedMics.join(', '),
currency,
reason: 'multi_valued_operating_mic',
});
continue;
}
const candidateMic = distinctNormalizedMics[0] ?? '';
if (!ISO_MIC_PATTERN.test(candidateMic)) {
unresolved.push({
source: group.source,
sourceCode: group.sourceCode,
rawCode: representative?.code ?? group.sourceCode,
name,
country,
operatingMic: candidateMic,
currency,
reason: 'invalid_operating_mic_format',
});
continue;
}
const matchedExchange = knownByMic.get(candidateMic);
if (!matchedExchange) {
unresolved.push({
source: group.source,
sourceCode: group.sourceCode,
rawCode: representative?.code ?? group.sourceCode,
name,
country,
operatingMic: candidateMic,
currency,
reason: 'unknown_operating_mic',
});
continue;
}
mapped.push({
source: group.source,
sourceCode: group.sourceCode,
role: 'primary_venue',
mic: matchedExchange.mic,
countryIso: matchedExchange.countryIso,
method: 'operating_mic',
reviewedBy: null,
});
}
mapped.sort(
(a, b) => compareAscii(a.source, b.source) || compareAscii(a.sourceCode, b.sourceCode)
);
unresolved.sort(compareUnresolvedExchangeRecords);
return { mapped, unresolved };
}
function readFirstStringField(
doc: Readonly<Record<string, unknown>>,
keys: readonly string[]
): string | null {
for (const key of keys) {
const value = doc[key];
if (typeof value === 'string') {
const trimmed = value.trim();
if (trimmed.length > 0) {
return value;
}
}
}
return null;
}
const RAW_FIELD_MAPPINGS: Record<
ExchangeSource,
{
code: readonly string[];
name: readonly string[];
country: readonly string[];
operatingMic: readonly string[];
currency: readonly string[];
}
> = {
eod: {
code: ['Code', 'code'],
name: ['Name', 'name'],
country: ['CountryISO2', 'Country', 'country'],
operatingMic: ['OperatingMIC', 'operatingMic', 'mic'],
currency: ['Currency', 'currency'],
},
ib: {
code: ['id', 'exchange_id', 'exchangeId', 'code'],
name: ['name', 'description'],
country: ['country_code', 'countryCode', 'country'],
operatingMic: ['operatingMic', 'OperatingMIC', 'mic'],
currency: ['currency'],
},
qm: {
code: ['exchange', 'exchangeCode', 'code'],
name: ['exchangeName', 'exchangeShortName', 'name'],
country: ['countryCode', 'country_code', 'country'],
operatingMic: ['operatingMic', 'OperatingMIC', 'mic'],
currency: ['currency'],
},
ceo: {
code: ['exchange', 'code'],
name: ['name'],
country: ['countryCode', 'country'],
operatingMic: ['operatingMic', 'OperatingMIC', 'mic'],
currency: ['currency'],
},
};
export function normalizeRawExchangeDoc(
source: ExchangeSource,
doc: Readonly<Record<string, unknown>>
): SourceExchangeRecord {
if (!isExchangeSource(source)) {
const fallbackCode =
readFirstStringField(doc, ['Code', 'code', 'id', 'exchange_id', 'exchange']) ?? '';
throw new Error(
`Unknown exchange source "${String(source)}" for exchange code "${fallbackCode}"`
);
}
const fields = RAW_FIELD_MAPPINGS[source];
const code = readFirstStringField(doc, fields.code) ?? '';
return {
source,
code,
name: readFirstStringField(doc, fields.name),
country: readFirstStringField(doc, fields.country),
operatingMic: readFirstStringField(doc, fields.operatingMic),
currency: readFirstStringField(doc, fields.currency),
};
}