stock-bot/apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts

1756 lines
52 KiB
TypeScript

import type { MongoDBClient } from '@stock-bot/mongodb';
import {
normalizeBarDate,
type BarSpanIndex,
type SpanDateRange,
} from '../normalization/bar-spans';
import { isValidCusip, isValidIsin } from '../normalization/identifiers';
import { normalizeProviderSymbol } from '../normalization/provider-symbol';
import { parseTickerDetailed } from '../normalization/ticker';
import {
compareAscii,
EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS,
ISO_EXCHANGE_SEEDS,
type ExchangeRole,
type ExchangeSeedRow,
type ExchangeSource,
type ExchangeSourceMapRow,
} from './exchange-pass1';
import type { StageASourceRecord } from './instrument-stage-a';
import {
MAX_TICKER_ROOT_LENGTH,
type StageBEodListingInput,
type StageBIbContractInput,
type StageBInput,
type StageBSymbolChangeInput,
type StageBTickerSourceInput,
} from './listing-stage-b';
export const SOURCE_SYMBOL_COLLECTIONS = Object.freeze({
eod: 'eodSymbols',
ib: 'ibSymbols',
qm: 'qmSymbols',
ceo: 'ceoSymbols',
eodSymbolChange: 'eodSymbolChange',
} as const);
export type SourceSymbolCollectionKey = keyof typeof SOURCE_SYMBOL_COLLECTIONS;
export type SourceSymbolCollectionName =
(typeof SOURCE_SYMBOL_COLLECTIONS)[SourceSymbolCollectionKey];
export const DEFAULT_SOURCE_COUNTRIES: readonly string[] = Object.freeze(['US', 'CA']);
export interface SourceSymbolFindOptions {
projection?: Record<string, 0 | 1>;
batchSize?: number;
}
/**
* Narrow read-only MongoDB reader interface for source-symbol collections.
* Exposes strictly `isReadOnly()` and `find()` — no write, index, drop, or
* collection-mutation methods are reachable through this contract.
*/
export interface ReadOnlySourceSymbolReader {
isReadOnly(): boolean;
find<T extends Record<string, unknown> = Record<string, unknown>>(
collectionName: string,
filter?: Record<string, unknown>,
options?: SourceSymbolFindOptions
): Promise<Iterable<T> | AsyncIterable<T>> | Iterable<T> | AsyncIterable<T>;
}
// Compile-time structural compatibility check (type-only, erased at runtime):
// ensures MongoDBClient satisfies ReadOnlySourceSymbolReader under `bun run typecheck`.
type AssertAssignable<Target, _Candidate extends Target> = true;
export type MongoDBClientSourceSymbolReaderCheck = AssertAssignable<
ReadOnlySourceSymbolReader,
MongoDBClient
>;
export interface ExchangeSourceLookupEntry {
readonly source: ExchangeSource;
readonly sourceCode: string;
readonly role: ExchangeRole;
readonly mic: string | null;
readonly countryIso: string | null;
}
export interface ExchangeSourceLookup {
get(source: ExchangeSource, sourceCode: string): ExchangeSourceLookupEntry | undefined;
getCodesForCountries?(source: ExchangeSource, countries: readonly string[]): string[];
}
export interface CreateExchangeSourceLookupOptions {
readonly includeExplicitRules?: boolean;
}
export type SourceSymbolSkipReason =
| 'missingId'
| 'invalidFieldType'
| 'invalidIdentifier'
| 'excludedMutualFund'
| 'unmappedExchange'
| 'outOfScopeCountry';
export interface SourceSymbolSkipCounts {
missingId: number;
invalidFieldType: number;
invalidIdentifier: number;
excludedMutualFund: number;
unmappedExchange: number;
outOfScopeCountry: number;
}
export interface SourceCollectionReadStats {
collection: SourceSymbolCollectionName;
docsRead: number;
emitted: number;
invalidIdentifiersNulled: number;
skips: SourceSymbolSkipCounts;
}
export interface ReadSourceCollectionOptions {
readonly exchangeLookup: ExchangeSourceLookup;
readonly barSpans?: Pick<BarSpanIndex, 'get'> | null;
readonly ceoSpans?: ReadonlyMap<string, SpanDateRange> | null;
readonly countries?: readonly string[] | null;
readonly knownExchanges?: readonly ExchangeSeedRow[];
readonly batchSize?: number;
}
export type ReadSecurityMasterSourcesOptions = ReadSourceCollectionOptions;
export interface AdaptEodSymbolContext {
readonly exchangeLookup: ExchangeSourceLookup;
readonly barSpans?: Pick<BarSpanIndex, 'get'> | null;
readonly allowedCountries: ReadonlySet<string> | null;
readonly micCurrencyMap: ReadonlyMap<string, string>;
}
export interface AdaptIbSymbolContext {
readonly exchangeLookup: ExchangeSourceLookup;
readonly allowedCountries: ReadonlySet<string> | null;
}
export interface AdaptQmSymbolContext {
readonly exchangeLookup: ExchangeSourceLookup;
readonly barSpans?: Pick<BarSpanIndex, 'get'> | null;
readonly allowedCountries: ReadonlySet<string> | null;
readonly micCurrencyMap: ReadonlyMap<string, string>;
}
export interface AdaptCeoSymbolContext {
readonly exchangeLookup: ExchangeSourceLookup;
readonly ceoSpans?: ReadonlyMap<string, SpanDateRange> | null;
readonly allowedCountries: ReadonlySet<string> | null;
readonly micCurrencyMap: ReadonlyMap<string, string>;
}
export interface AdaptEodSymbolChangeContext {
readonly exchangeLookup: ExchangeSourceLookup;
readonly allowedCountries: ReadonlySet<string> | null;
}
export type AdaptEodSymbolResult =
| {
readonly ok: true;
readonly stageARecord: StageASourceRecord;
readonly eodListing: StageBEodListingInput;
readonly invalidIdentifiersNulled: number;
}
| { readonly ok: false; readonly skipReason: SourceSymbolSkipReason };
export type AdaptIbSymbolResult =
| {
readonly ok: true;
readonly stageARecord: StageASourceRecord;
readonly ibContract: StageBIbContractInput;
readonly invalidIdentifiersNulled: number;
}
| { readonly ok: false; readonly skipReason: SourceSymbolSkipReason };
export type AdaptTickerSourceResult =
| {
readonly ok: true;
readonly tickerSource: StageBTickerSourceInput;
}
| { readonly ok: false; readonly skipReason: SourceSymbolSkipReason };
export type AdaptEodSymbolChangeResult =
| {
readonly ok: true;
readonly symbolChange: StageBSymbolChangeInput;
}
| { readonly ok: false; readonly skipReason: SourceSymbolSkipReason };
export interface ReadEodSymbolsResult {
stageARecords: StageASourceRecord[];
eodListings: StageBEodListingInput[];
stats: SourceCollectionReadStats;
}
export interface ReadIbSymbolsResult {
stageARecords: StageASourceRecord[];
ibContracts: StageBIbContractInput[];
stats: SourceCollectionReadStats;
}
export interface ReadTickerSourcesResult {
tickerSources: StageBTickerSourceInput[];
stats: SourceCollectionReadStats;
}
export interface ReadEodSymbolChangesResult {
symbolChanges: StageBSymbolChangeInput[];
stats: SourceCollectionReadStats;
}
export interface SecurityMasterStageBSourceInput
extends Omit<StageBInput, 'instruments' | 'eodListings' | 'ibContracts' | 'tickerSources' | 'symbolChanges'> {
eodListings: StageBEodListingInput[];
ibContracts: StageBIbContractInput[];
tickerSources: StageBTickerSourceInput[];
symbolChanges: StageBSymbolChangeInput[];
}
export interface SecurityMasterSourcesStats {
eodSymbols: SourceCollectionReadStats;
ibSymbols: SourceCollectionReadStats;
qmSymbols: SourceCollectionReadStats;
ceoSymbols: SourceCollectionReadStats;
eodSymbolChange: SourceCollectionReadStats;
}
export interface SecurityMasterSourcesResult {
stageARecords: StageASourceRecord[];
stageBInput: SecurityMasterStageBSourceInput;
stats: SecurityMasterSourcesStats;
}
const ISO2_PATTERN = /^[A-Z]{2}$/;
const DEFAULT_CEO_CA_CODES: readonly string[] = Object.freeze(['AQL', 'CDX', 'CNQ', 'TSX']);
const COUNTRY_NAME_TO_ISO2: ReadonlyMap<string, string> = new Map<string, string>([
['US', 'US'],
['USA', 'US'],
['U.S.', 'US'],
['U.S.A.', 'US'],
['UNITED STATES', 'US'],
['UNITED STATES OF AMERICA', 'US'],
['CA', 'CA'],
['CAN', 'CA'],
['CANADA', 'CA'],
['GB', 'GB'],
['GBR', 'GB'],
['UK', 'GB'],
['UNITED KINGDOM', 'GB'],
['GREAT BRITAIN', 'GB'],
['DE', 'DE'],
['DEU', 'DE'],
['GERMANY', 'DE'],
['FR', 'FR'],
['FRA', 'FR'],
['FRANCE', 'FR'],
['AU', 'AU'],
['AUS', 'AU'],
['AUSTRALIA', 'AU'],
['JP', 'JP'],
['JPN', 'JP'],
['JAPAN', 'JP'],
['CN', 'CN'],
['CHN', 'CN'],
['CHINA', 'CN'],
['HK', 'HK'],
['HKG', 'HK'],
['HONG KONG', 'HK'],
['CH', 'CH'],
['CHE', 'CH'],
['SWITZERLAND', 'CH'],
['NL', 'NL'],
['NLD', 'NL'],
['NETHERLANDS', 'NL'],
['IT', 'IT'],
['ITA', 'IT'],
['ITALY', 'IT'],
['ES', 'ES'],
['ESP', 'ES'],
['SPAIN', 'ES'],
['SE', 'SE'],
['SWE', 'SE'],
['SWEDEN', 'SE'],
['NO', 'NO'],
['NOR', 'NO'],
['NORWAY', 'NO'],
['DK', 'DK'],
['DNK', 'DK'],
['DENMARK', 'DK'],
['FI', 'FI'],
['FIN', 'FI'],
['FINLAND', 'FI'],
['BE', 'BE'],
['BEL', 'BE'],
['BELGIUM', 'BE'],
['AT', 'AT'],
['AUT', 'AT'],
['AUSTRIA', 'AT'],
['IE', 'IE'],
['IRL', 'IE'],
['IRELAND', 'IE'],
['IN', 'IN'],
['IND', 'IN'],
['INDIA', 'IN'],
['BR', 'BR'],
['BRA', 'BR'],
['BRAZIL', 'BR'],
['MX', 'MX'],
['MEX', 'MX'],
['MEXICO', 'MX'],
['KR', 'KR'],
['KOR', 'KR'],
['SOUTH KOREA', 'KR'],
['KOREA', 'KR'],
['TW', 'TW'],
['TWN', 'TW'],
['TAIWAN', 'TW'],
['SG', 'SG'],
['SGP', 'SG'],
['SINGAPORE', 'SG'],
['NZ', 'NZ'],
['NZL', 'NZ'],
['NEW ZEALAND', 'NZ'],
['IL', 'IL'],
['ISR', 'IL'],
['ISRAEL', 'IL'],
['ZA', 'ZA'],
['ZAF', 'ZA'],
['SOUTH AFRICA', 'ZA'],
['PL', 'PL'],
['POL', 'PL'],
['POLAND', 'PL'],
['PT', 'PT'],
['PRT', 'PT'],
['PORTUGAL', 'PT'],
['GR', 'GR'],
['GRC', 'GR'],
['GREECE', 'GR'],
['TR', 'TR'],
['TUR', 'TR'],
['TURKEY', 'TR'],
['AR', 'AR'],
['ARG', 'AR'],
['ARGENTINA', 'AR'],
['CL', 'CL'],
['CHL', 'CL'],
['CHILE', 'CL'],
['ID', 'ID'],
['IDN', 'ID'],
['INDONESIA', 'ID'],
['MY', 'MY'],
['MYS', 'MY'],
['MALAYSIA', 'MY'],
['TH', 'TH'],
['THA', 'TH'],
['THAILAND', 'TH'],
['VN', 'VN'],
['VNM', 'VN'],
['VIETNAM', 'VN'],
['PH', 'PH'],
['PHL', 'PH'],
['PHILIPPINES', 'PH'],
['SA', 'SA'],
['SAU', 'SA'],
['SAUDI ARABIA', 'SA'],
['AE', 'AE'],
['ARE', 'AE'],
['UAE', 'AE'],
['UNITED ARAB EMIRATES', 'AE'],
]);
const EOD_COUNTRY_FILTER_SPELLINGS: Readonly<Record<string, readonly string[]>> = Object.freeze({
US: Object.freeze(['US', 'USA', 'United States', 'United States of America']),
CA: Object.freeze(['CA', 'CAN', 'Canada']),
});
export const EOD_SYMBOLS_PROJECTION: Readonly<Record<string, 0 | 1>> = Object.freeze({
_id: 0,
eodSearchCode: 1,
Code: 1,
code: 1,
symbol: 1,
Exchange: 1,
eodExchange: 1,
exchange: 1,
exchangeCode: 1,
Country: 1,
countryCode: 1,
Currency: 1,
currency: 1,
Isin: 1,
isin: 1,
Cusip: 1,
cusip: 1,
Name: 1,
name: 1,
companyName: 1,
delisted: 1,
});
export const IB_SYMBOLS_PROJECTION: Readonly<Record<string, 0 | 1>> = Object.freeze({
_id: 0,
conid: 1,
symbol: 1,
localSymbol: 1,
exchangeId: 1,
exchange: 1,
exchangeCode: 1,
primaryExchange: 1,
listingExchange: 1,
country: 1,
countryCode: 1,
currency: 1,
isin: 1,
cusip: 1,
description: 1,
name: 1,
companyName: 1,
});
export const QM_SYMBOLS_PROJECTION: Readonly<Record<string, 0 | 1>> = Object.freeze({
_id: 0,
qmSearchCode: 1,
symbol: 1,
code: 1,
exchange: 1,
exchangeCode: 1,
countryCode: 1,
country: 1,
currency: 1,
name: 1,
companyName: 1,
active: 1,
});
export const CEO_SYMBOLS_PROJECTION: Readonly<Record<string, 0 | 1>> = Object.freeze({
_id: 0,
ceoId: 1,
symbol: 1,
exchange: 1,
exchangeCode: 1,
countryCode: 1,
country: 1,
currency: 1,
name: 1,
lastSeen: 1,
});
export const EOD_SYMBOL_CHANGE_PROJECTION: Readonly<Record<string, 0 | 1>> = Object.freeze({
_id: 0,
oldSymbol: 1,
newSymbol: 1,
exchange: 1,
eodExchange: 1,
eodSearchCode: 1,
date: 1,
effectiveDate: 1,
validFrom: 1,
country: 1,
Country: 1,
});
/**
* Normalizes ISO-2 country codes and common provider country name spellings
* (e.g. EODHD `'USA'`, `'United States'`, `'Canada'`) to uppercase ISO-2.
*/
export function normalizeCountryIso2(value: string | null | undefined): string | null {
if (typeof value !== 'string') {
return null;
}
const trimmed = value.trim();
if (trimmed.length === 0) {
return null;
}
const upper = trimmed.toUpperCase();
const mapped = COUNTRY_NAME_TO_ISO2.get(upper);
if (mapped !== undefined) {
return mapped;
}
return ISO2_PATTERN.test(upper) ? upper : null;
}
/**
* Builds an in-memory per-source lookup map from Pass 1 `exchange_source_map` rows.
* Seeds `EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS` by default with caller rows taking precedence.
*/
export function createExchangeSourceLookup(
rows: readonly ExchangeSourceMapRow[],
options: CreateExchangeSourceLookupOptions = {}
): ExchangeSourceLookup {
const bySource: Readonly<Record<ExchangeSource, Map<string, ExchangeSourceLookupEntry>>> = {
eod: new Map<string, ExchangeSourceLookupEntry>(),
ib: new Map<string, ExchangeSourceLookupEntry>(),
qm: new Map<string, ExchangeSourceLookupEntry>(),
ceo: new Map<string, ExchangeSourceLookupEntry>(),
};
const insertRow = (row: ExchangeSourceMapRow): void => {
const code = row.sourceCode.trim().toUpperCase();
if (code.length === 0) {
return;
}
const mic = row.mic === null ? null : row.mic.trim().toUpperCase() || null;
const countryIso =
row.countryIso === null
? null
: (normalizeCountryIso2(row.countryIso) ?? (row.countryIso.trim().toUpperCase() || null));
bySource[row.source].set(code, {
source: row.source,
sourceCode: code,
role: row.role,
mic,
countryIso,
});
};
if (options.includeExplicitRules !== false) {
for (let i = 0; i < EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS.length; i++) {
const row = EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS[i];
if (row !== undefined) {
insertRow(row);
}
}
}
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
if (row !== undefined) {
insertRow(row);
}
}
return {
get(source: ExchangeSource, sourceCode: string): ExchangeSourceLookupEntry | undefined {
const code = sourceCode.trim().toUpperCase();
if (code.length === 0) {
return undefined;
}
return bySource[source].get(code);
},
getCodesForCountries(source: ExchangeSource, countries: readonly string[]): string[] {
const allowed = new Set<string>();
for (let i = 0; i < countries.length; i++) {
const iso = normalizeCountryIso2(countries[i]);
if (iso !== null) {
allowed.add(iso);
}
}
if (allowed.size === 0) {
return [];
}
const codes: string[] = [];
for (const entry of bySource[source].values()) {
if (entry.countryIso !== null && allowed.has(entry.countryIso)) {
codes.push(entry.sourceCode);
}
}
codes.sort(compareAscii);
return codes;
},
};
}
function buildMicCurrencyMap(
knownExchanges: readonly ExchangeSeedRow[] = ISO_EXCHANGE_SEEDS
): ReadonlyMap<string, string> {
const map = new Map<string, string>();
for (let i = 0; i < knownExchanges.length; i++) {
const row = knownExchanges[i];
if (row === undefined) {
continue;
}
const mic = row.mic.trim().toUpperCase();
const currency = row.currency.trim().toUpperCase();
if (mic.length > 0 && currency.length > 0) {
map.set(mic, currency);
}
}
return map;
}
function resolveAllowedCountries(countries?: readonly string[] | null): {
set: ReadonlySet<string> | null;
list: string[] | null;
} {
if (countries === null) {
return { set: null, list: null };
}
const source = countries === undefined ? DEFAULT_SOURCE_COUNTRIES : countries;
const set = new Set<string>();
for (let i = 0; i < source.length; i++) {
const raw = source[i];
const normalized = normalizeCountryIso2(raw);
if (normalized !== null) {
set.add(normalized);
} else if (typeof raw === 'string' && raw.trim().length > 0) {
set.add(raw.trim().toUpperCase());
}
}
const list = [...set].sort(compareAscii);
return { set, list };
}
function createEmptySkipCounts(): SourceSymbolSkipCounts {
return {
missingId: 0,
invalidFieldType: 0,
invalidIdentifier: 0,
excludedMutualFund: 0,
unmappedExchange: 0,
outOfScopeCountry: 0,
};
}
function createCollectionStats(
collection: SourceSymbolCollectionName
): SourceCollectionReadStats {
return {
collection,
docsRead: 0,
emitted: 0,
invalidIdentifiersNulled: 0,
skips: createEmptySkipCounts(),
};
}
function assertReadOnlyReader(reader: ReadOnlySourceSymbolReader): void {
if (
reader === null ||
reader === undefined ||
typeof reader !== 'object' ||
typeof reader.isReadOnly !== 'function' ||
!reader.isReadOnly()
) {
throw new Error(
'Source symbol reader requires a read-only MongoDB client (isReadOnly() must be true)'
);
}
}
function isSyncIterable<T>(value: unknown): value is Iterable<T> {
return (
value !== null &&
(typeof value === 'object' || typeof value === 'function') &&
typeof (value as Record<symbol, unknown>)[Symbol.iterator] === 'function'
);
}
function isAsyncIterable<T>(value: unknown): value is AsyncIterable<T> {
return (
value !== null &&
(typeof value === 'object' || typeof value === 'function') &&
typeof (value as Record<symbol, unknown>)[Symbol.asyncIterator] === 'function'
);
}
async function streamCollection<T extends Record<string, unknown>>(
reader: ReadOnlySourceSymbolReader,
collectionName: SourceSymbolCollectionName,
filter: Record<string, unknown>,
options: SourceSymbolFindOptions,
onDoc: (doc: unknown) => void
): Promise<void> {
assertReadOnlyReader(reader);
try {
const cursor = await reader.find<T>(collectionName, filter, options);
if (isAsyncIterable<T>(cursor)) {
for await (const doc of cursor) {
onDoc(doc);
}
return;
}
if (isSyncIterable<T>(cursor)) {
for (const doc of cursor) {
onDoc(doc);
}
return;
}
throw new TypeError(
`Reader returned a non-iterable result for collection "${collectionName}"`
);
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
const message = detail.includes(collectionName)
? detail
: `Failed reading collection "${collectionName}": ${detail}`;
throw new Error(message, { cause: error });
}
}
type StringFieldResult = { readonly ok: true; readonly value: string | null } | { readonly ok: false };
function readOptionalString(doc: Record<string, unknown>, key: string): StringFieldResult {
const raw = doc[key];
if (raw === undefined || raw === null) {
return { ok: true, value: null };
}
if (typeof raw !== 'string') {
return { ok: false };
}
const trimmed = raw.trim();
return { ok: true, value: trimmed.length > 0 ? trimmed : null };
}
function readFirstOptionalString(
doc: Record<string, unknown>,
keys: readonly string[]
): StringFieldResult {
let found: string | null = null;
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if (key === undefined) {
continue;
}
const res = readOptionalString(doc, key);
if (!res.ok) {
return res;
}
if (found === null && res.value !== null) {
found = res.value;
}
}
return { ok: true, value: found };
}
function isPlainRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object' && !Array.isArray(value);
}
function isNorthAmericaIso(code: string | null): code is 'US' | 'CA' {
return code === 'US' || code === 'CA';
}
function countryFallbackCurrency(countryIso: string | null): string | null {
if (countryIso === 'US') {
return 'USD';
}
if (countryIso === 'CA') {
return 'CAD';
}
return null;
}
function formatCanonicalTicker(tickerRoot: string, classSuffix: string): string {
return classSuffix.length > 0 ? `${tickerRoot}.${classSuffix}` : tickerRoot;
}
/**
* Formats a parsed CEO ticker so Stage B's `parseTickerDetailed(ticker, 'ceo')`
* recovers the exact `(tickerRoot, classSuffix)` without double-stripping a
* share-class suffix that happens to be `TO` or `V`.
*/
function formatStageBSafeCeoTicker(tickerRoot: string, classSuffix: string): string {
if (classSuffix.length === 0) {
return tickerRoot;
}
if (classSuffix === 'TO' || classSuffix === 'V') {
return `${tickerRoot}-${classSuffix}`;
}
if (classSuffix.endsWith('.TO')) {
return `${tickerRoot}.${classSuffix.slice(0, -3)}-TO`;
}
if (classSuffix.endsWith('.V')) {
return `${tickerRoot}.${classSuffix.slice(0, -2)}-V`;
}
return `${tickerRoot}.${classSuffix}`;
}
function toSpanDateRange(span: SpanDateRange | undefined | null): SpanDateRange | null {
if (span === undefined || span === null) {
return null;
}
return {
firstBarDate: span.firstBarDate,
lastBarDate: span.lastBarDate,
};
}
function buildEodCountryFilter(countries: readonly string[] | null): Record<string, unknown> {
if (countries === null) {
return {};
}
const expanded = new Set<string>();
for (let i = 0; i < countries.length; i++) {
const iso = countries[i];
if (iso === undefined) {
continue;
}
const spellings = EOD_COUNTRY_FILTER_SPELLINGS[iso];
if (spellings !== undefined) {
for (let j = 0; j < spellings.length; j++) {
const spelling = spellings[j];
if (spelling !== undefined) {
expanded.add(spelling);
}
}
} else {
expanded.add(iso);
}
}
return { Country: { $in: [...expanded].sort(compareAscii) } };
}
function buildIbCountryFilter(countries: readonly string[] | null): Record<string, unknown> {
if (countries === null) {
return {};
}
return { country: { $in: [...countries] } };
}
function buildQmCountryFilter(countries: readonly string[] | null): Record<string, unknown> {
if (countries === null) {
return {};
}
return { countryCode: { $in: [...countries] } };
}
function buildCeoCountryFilter(
exchangeLookup: ExchangeSourceLookup,
countries: readonly string[] | null
): Record<string, unknown> {
if (countries === null) {
return {};
}
if (typeof exchangeLookup.getCodesForCountries === 'function') {
return { exchange: { $in: exchangeLookup.getCodesForCountries('ceo', countries) } };
}
const codes = countries.includes('CA') ? [...DEFAULT_CEO_CA_CODES] : [];
return { exchange: { $in: codes } };
}
function buildEodSymbolChangeFilter(
exchangeLookup: ExchangeSourceLookup,
countries: readonly string[] | null
): Record<string, unknown> {
if (countries === null) {
return {};
}
if (typeof exchangeLookup.getCodesForCountries === 'function') {
return { exchange: { $in: exchangeLookup.getCodesForCountries('eod', countries) } };
}
return {};
}
function compareStageARecords(a: StageASourceRecord, b: StageASourceRecord): number {
return (
compareAscii(a.source, b.source) ||
compareAscii(a.sourceId, b.sourceId) ||
compareAscii(a.isin ?? '', b.isin ?? '') ||
compareAscii(a.cusip ?? '', b.cusip ?? '') ||
compareAscii(a.country ?? '', b.country ?? '') ||
compareAscii(a.currency ?? '', b.currency ?? '') ||
compareAscii(a.name ?? '', b.name ?? '')
);
}
function compareEodListings(a: StageBEodListingInput, b: StageBEodListingInput): number {
return (
compareAscii(a.sourceId, b.sourceId) ||
compareAscii(a.mic ?? '', b.mic ?? '') ||
compareAscii(a.role ?? '', b.role ?? '') ||
compareAscii(a.ticker ?? '', b.ticker ?? '') ||
compareAscii(a.currency ?? '', b.currency ?? '') ||
compareAscii(a.span?.firstBarDate ?? '', b.span?.firstBarDate ?? '') ||
compareAscii(a.span?.lastBarDate ?? '', b.span?.lastBarDate ?? '')
);
}
function compareIbContracts(a: StageBIbContractInput, b: StageBIbContractInput): number {
return (
compareAscii(a.sourceId, b.sourceId) ||
(a.conid === b.conid ? 0 : a.conid < b.conid ? -1 : 1) ||
compareAscii(a.currency ?? '', b.currency ?? '') ||
compareAscii(a.primaryExchange ?? '', b.primaryExchange ?? '')
);
}
function compareTickerSources(a: StageBTickerSourceInput, b: StageBTickerSourceInput): number {
return (
compareAscii(a.source, b.source) ||
compareAscii(a.sourceId, b.sourceId) ||
compareAscii(a.mic ?? '', b.mic ?? '') ||
compareAscii(a.role ?? '', b.role ?? '') ||
compareAscii(a.ticker ?? '', b.ticker ?? '') ||
compareAscii(a.currency ?? '', b.currency ?? '') ||
compareAscii(a.span?.firstBarDate ?? '', b.span?.firstBarDate ?? '') ||
compareAscii(a.span?.lastBarDate ?? '', b.span?.lastBarDate ?? '')
);
}
function compareSymbolChanges(a: StageBSymbolChangeInput, b: StageBSymbolChangeInput): number {
return (
compareAscii(a.eodSourceId, b.eodSourceId) ||
compareAscii(a.effectiveDate, b.effectiveDate) ||
compareAscii(a.oldTicker, b.oldTicker) ||
compareAscii(a.validFrom ?? '', b.validFrom ?? '')
);
}
/**
* Pure adapter converting a raw `eodSymbols` document into a Stage A source record
* and Stage B EOD listing input.
*/
export function adaptEodSymbolDoc(
doc: unknown,
context: AdaptEodSymbolContext
): AdaptEodSymbolResult {
if (!isPlainRecord(doc)) {
return { ok: false, skipReason: 'invalidFieldType' };
}
const sourceIdField = readOptionalString(doc, 'eodSearchCode');
const tickerField = readFirstOptionalString(doc, ['Code', 'code', 'symbol']);
// Resolve listing venue from Exchange/exchange/exchangeCode — never from composite eodExchange="US".
const exchangeField = readFirstOptionalString(doc, ['Exchange', 'exchange', 'exchangeCode']);
const countryField = readFirstOptionalString(doc, ['Country', 'countryCode']);
const currencyField = readFirstOptionalString(doc, ['Currency', 'currency']);
const isinField = readFirstOptionalString(doc, ['Isin', 'isin']);
const cusipField = readFirstOptionalString(doc, ['Cusip', 'cusip']);
const nameField = readFirstOptionalString(doc, ['Name', 'name', 'companyName']);
if (
!sourceIdField.ok ||
!tickerField.ok ||
!exchangeField.ok ||
!countryField.ok ||
!currencyField.ok ||
!isinField.ok ||
!cusipField.ok ||
!nameField.ok
) {
return { ok: false, skipReason: 'invalidFieldType' };
}
if (sourceIdField.value === null) {
return { ok: false, skipReason: 'missingId' };
}
const sourceId = sourceIdField.value;
const rawExchange = exchangeField.value;
const exchangeEntry =
rawExchange !== null ? context.exchangeLookup.get('eod', rawExchange) : undefined;
if (context.allowedCountries !== null) {
if (countryField.value !== null) {
const normalizedCountry = normalizeCountryIso2(countryField.value);
if (normalizedCountry === null || !context.allowedCountries.has(normalizedCountry)) {
return { ok: false, skipReason: 'outOfScopeCountry' };
}
} else if (exchangeEntry?.countryIso !== undefined && exchangeEntry.countryIso !== null) {
if (!context.allowedCountries.has(exchangeEntry.countryIso)) {
return { ok: false, skipReason: 'outOfScopeCountry' };
}
}
}
if (rawExchange !== null && rawExchange.toUpperCase() === 'NMFQS') {
return { ok: false, skipReason: 'excludedMutualFund' };
}
if (exchangeEntry?.role === 'excluded_fund') {
return { ok: false, skipReason: 'excludedMutualFund' };
}
if (rawExchange === null || exchangeEntry === undefined) {
return { ok: false, skipReason: 'unmappedExchange' };
}
const normalized = normalizeProviderSymbol({
Code: tickerField.value,
Exchange: rawExchange,
Name: nameField.value,
Country: countryField.value,
Currency: currencyField.value,
eodSearchCode: sourceId,
});
let invalidIdentifiersNulled = 0;
let validIsin: string | null = null;
if (isinField.value !== null) {
const candidate = isinField.value.toUpperCase();
if (isValidIsin(candidate)) {
validIsin = candidate;
} else {
invalidIdentifiersNulled += 1;
}
}
let validCusip: string | null = null;
if (cusipField.value !== null) {
const candidate = cusipField.value.toUpperCase();
if (isValidCusip(candidate)) {
validCusip = candidate;
} else {
invalidIdentifiersNulled += 1;
}
}
// Per T-55: Stage A country must be issuer country (from ISIN prefix), never listing Country.
let issuerCountry: string | null = null;
if (validIsin !== null) {
issuerCountry = validIsin.slice(0, 2);
} else if (validCusip !== null && isinField.value !== null && isinField.value.length >= 2) {
const rawPrefix = isinField.value.slice(0, 2).toUpperCase();
if (isNorthAmericaIso(rawPrefix)) {
issuerCountry = rawPrefix;
}
}
const rawCurrency = normalized?.currency ?? currencyField.value;
const currency =
rawCurrency !== null
? rawCurrency.toUpperCase()
: exchangeEntry.mic !== null
? context.micCurrencyMap.get(exchangeEntry.mic) ?? null
: null;
const name = normalized?.companyName ?? nameField.value;
const ticker = normalized?.symbol ?? tickerField.value;
const span = toSpanDateRange(context.barSpans?.get('eod', sourceId));
return {
ok: true,
stageARecord: {
source: 'eod',
sourceId,
isin: validIsin,
cusip: validCusip,
country: issuerCountry,
currency,
name,
},
eodListing: {
sourceId,
ticker,
mic: exchangeEntry.mic,
role: exchangeEntry.role,
currency,
span,
},
invalidIdentifiersNulled,
};
}
/**
* Pure adapter converting a raw `ibSymbols` document into a Stage A source record
* and Stage B IB contract input. Never blocks on `exchangeId` or treats ATS venues
* (e.g. `AEQLIT`, `OTCLNKECN`) as listing MICs or primary exchanges.
*/
export function adaptIbSymbolDoc(
doc: unknown,
context: AdaptIbSymbolContext
): AdaptIbSymbolResult {
if (!isPlainRecord(doc)) {
return { ok: false, skipReason: 'invalidFieldType' };
}
const rawConid = doc.conid;
if (rawConid === undefined || rawConid === null) {
return { ok: false, skipReason: 'missingId' };
}
if (typeof rawConid !== 'number') {
return { ok: false, skipReason: 'invalidFieldType' };
}
if (!Number.isSafeInteger(rawConid) || rawConid <= 0) {
return { ok: false, skipReason: 'invalidIdentifier' };
}
const symbolField = readFirstOptionalString(doc, ['symbol', 'localSymbol']);
const exchangeIdField = readFirstOptionalString(doc, ['exchangeId', 'exchange', 'exchangeCode']);
const explicitPrimaryExchangeField = readFirstOptionalString(doc, [
'primaryExchange',
'listingExchange',
]);
const countryField = readFirstOptionalString(doc, ['country', 'countryCode']);
const currencyField = readOptionalString(doc, 'currency');
const isinField = readOptionalString(doc, 'isin');
const cusipField = readOptionalString(doc, 'cusip');
const nameField = readFirstOptionalString(doc, ['companyName', 'name', 'description']);
if (
!symbolField.ok ||
!exchangeIdField.ok ||
!explicitPrimaryExchangeField.ok ||
!countryField.ok ||
!currencyField.ok ||
!isinField.ok ||
!cusipField.ok ||
!nameField.ok
) {
return { ok: false, skipReason: 'invalidFieldType' };
}
const normalizedDocCountry =
countryField.value !== null ? normalizeCountryIso2(countryField.value) : null;
if (context.allowedCountries !== null) {
if (normalizedDocCountry === null || !context.allowedCountries.has(normalizedDocCountry)) {
return { ok: false, skipReason: 'outOfScopeCountry' };
}
}
const normalized = normalizeProviderSymbol({
symbol: symbolField.value,
exchangeId: exchangeIdField.value,
description: nameField.value,
countryCode: countryField.value,
currency: currencyField.value,
});
let invalidIdentifiersNulled = 0;
let validIsin: string | null = null;
if (isinField.value !== null) {
const candidate = isinField.value.toUpperCase();
if (isValidIsin(candidate)) {
validIsin = candidate;
} else {
invalidIdentifiersNulled += 1;
}
}
let validCusip: string | null = null;
if (cusipField.value !== null) {
const candidate = cusipField.value.toUpperCase();
if (isValidCusip(candidate)) {
validCusip = candidate;
} else {
invalidIdentifiersNulled += 1;
}
}
// Derive Stage A issuer country without leaking listing country when valid ISIN is present.
let issuerCountry: string | null = null;
if (validIsin !== null) {
issuerCountry = validIsin.slice(0, 2);
} else if (validCusip !== null) {
const rawPrefix =
isinField.value !== null && isinField.value.length >= 2
? isinField.value.slice(0, 2).toUpperCase()
: null;
if (isNorthAmericaIso(rawPrefix)) {
issuerCountry = rawPrefix;
} else if (isNorthAmericaIso(normalizedDocCountry)) {
issuerCountry = normalizedDocCountry;
}
}
let primaryExchange: string | null = null;
if (explicitPrimaryExchangeField.value !== null) {
primaryExchange = explicitPrimaryExchangeField.value.toUpperCase();
} else if (exchangeIdField.value !== null) {
const entry = context.exchangeLookup.get('ib', exchangeIdField.value);
if (entry?.role === 'primary_venue') {
primaryExchange = exchangeIdField.value.toUpperCase();
}
}
const sourceId = String(rawConid);
const currency = currencyField.value !== null ? currencyField.value.toUpperCase() : null;
const name = normalized?.companyName ?? nameField.value;
return {
ok: true,
stageARecord: {
source: 'ib',
sourceId,
isin: validIsin,
cusip: validCusip,
country: issuerCountry,
currency,
name,
},
ibContract: {
sourceId,
conid: rawConid,
currency,
primaryExchange,
},
invalidIdentifiersNulled,
};
}
/**
* Pure adapter converting a raw `qmSymbols` document into a Stage B ticker-source input.
* Preserves inactive (`active: false`) records and duplicate `(symbol, exchange)` pairs
* (such as `VOY:CNX` and `VOY:CC`) as distinct `qmSearchCode` `sourceId`s.
*/
export function adaptQmSymbolDoc(
doc: unknown,
context: AdaptQmSymbolContext
): AdaptTickerSourceResult {
if (!isPlainRecord(doc)) {
return { ok: false, skipReason: 'invalidFieldType' };
}
const sourceIdField = readOptionalString(doc, 'qmSearchCode');
const symbolField = readFirstOptionalString(doc, ['symbol', 'code']);
const exchangeField = readFirstOptionalString(doc, ['exchange', 'exchangeCode']);
const countryField = readFirstOptionalString(doc, ['countryCode', 'country']);
const currencyField = readOptionalString(doc, 'currency');
if (
!sourceIdField.ok ||
!symbolField.ok ||
!exchangeField.ok ||
!countryField.ok ||
!currencyField.ok
) {
return { ok: false, skipReason: 'invalidFieldType' };
}
if (sourceIdField.value === null) {
return { ok: false, skipReason: 'missingId' };
}
const sourceId = sourceIdField.value;
const rawExchange = exchangeField.value;
const exchangeEntry =
rawExchange !== null ? context.exchangeLookup.get('qm', rawExchange) : undefined;
const normalizedCountry =
countryField.value !== null ? normalizeCountryIso2(countryField.value) : null;
if (context.allowedCountries !== null) {
if (countryField.value !== null) {
if (normalizedCountry === null || !context.allowedCountries.has(normalizedCountry)) {
return { ok: false, skipReason: 'outOfScopeCountry' };
}
} else if (exchangeEntry?.countryIso !== undefined && exchangeEntry.countryIso !== null) {
if (!context.allowedCountries.has(exchangeEntry.countryIso)) {
return { ok: false, skipReason: 'outOfScopeCountry' };
}
}
}
if (exchangeEntry?.role === 'excluded_fund') {
return { ok: false, skipReason: 'excludedMutualFund' };
}
if (rawExchange === null || exchangeEntry === undefined) {
return { ok: false, skipReason: 'unmappedExchange' };
}
const parsedTicker = parseTickerDetailed(symbolField.value, 'qm');
const ticker = parsedTicker.ok
? formatCanonicalTicker(parsedTicker.tickerRoot, parsedTicker.classSuffix)
: symbolField.value;
const effectiveCountry = normalizedCountry ?? exchangeEntry.countryIso;
const currency =
currencyField.value !== null
? currencyField.value.toUpperCase()
: exchangeEntry.mic !== null
? context.micCurrencyMap.get(exchangeEntry.mic) ?? countryFallbackCurrency(effectiveCountry)
: countryFallbackCurrency(effectiveCountry);
const span = toSpanDateRange(context.barSpans?.get('qm', sourceId));
return {
ok: true,
tickerSource: {
source: 'qm',
sourceId,
ticker,
mic: exchangeEntry.mic,
role: exchangeEntry.role,
currency,
span,
},
};
}
/**
* Pure adapter converting a raw `ceoSymbols` document into a Stage B ticker-source input.
* Maps `TSX`/`CDX`/`CNQ`/`AQL` through `exchangeLookup` and parses embedded `.TO`/`.V` suffixes.
*/
export function adaptCeoSymbolDoc(
doc: unknown,
context: AdaptCeoSymbolContext
): AdaptTickerSourceResult {
if (!isPlainRecord(doc)) {
return { ok: false, skipReason: 'invalidFieldType' };
}
const sourceIdField = readOptionalString(doc, 'ceoId');
const symbolField = readOptionalString(doc, 'symbol');
const exchangeField = readFirstOptionalString(doc, ['exchange', 'exchangeCode']);
const countryField = readFirstOptionalString(doc, ['countryCode', 'country']);
const currencyField = readOptionalString(doc, 'currency');
const rawLastSeen = doc.lastSeen;
const lastSeenTypeValid =
rawLastSeen === undefined ||
rawLastSeen === null ||
typeof rawLastSeen === 'string' ||
rawLastSeen instanceof Date;
if (
!sourceIdField.ok ||
!symbolField.ok ||
!exchangeField.ok ||
!countryField.ok ||
!currencyField.ok ||
!lastSeenTypeValid
) {
return { ok: false, skipReason: 'invalidFieldType' };
}
if (sourceIdField.value === null) {
return { ok: false, skipReason: 'missingId' };
}
const sourceId = sourceIdField.value;
const rawExchange = exchangeField.value;
const exchangeEntry =
rawExchange !== null ? context.exchangeLookup.get('ceo', rawExchange) : undefined;
const normalizedCountry =
countryField.value !== null ? normalizeCountryIso2(countryField.value) : null;
if (context.allowedCountries !== null) {
if (countryField.value !== null) {
if (normalizedCountry === null || !context.allowedCountries.has(normalizedCountry)) {
return { ok: false, skipReason: 'outOfScopeCountry' };
}
} else if (exchangeEntry?.countryIso !== undefined && exchangeEntry.countryIso !== null) {
if (!context.allowedCountries.has(exchangeEntry.countryIso)) {
return { ok: false, skipReason: 'outOfScopeCountry' };
}
}
}
if (exchangeEntry?.role === 'excluded_fund') {
return { ok: false, skipReason: 'excludedMutualFund' };
}
if (rawExchange === null || exchangeEntry === undefined) {
return { ok: false, skipReason: 'unmappedExchange' };
}
const parsedTicker = parseTickerDetailed(symbolField.value, 'ceo');
const ticker = parsedTicker.ok
? formatStageBSafeCeoTicker(parsedTicker.tickerRoot, parsedTicker.classSuffix)
: symbolField.value;
const currency =
currencyField.value !== null
? currencyField.value.toUpperCase()
: exchangeEntry.mic !== null
? context.micCurrencyMap.get(exchangeEntry.mic) ?? 'CAD'
: 'CAD';
let span = toSpanDateRange(context.ceoSpans?.get(sourceId));
if (span === null && rawLastSeen !== undefined && rawLastSeen !== null) {
const lastSeenDate = normalizeBarDate(rawLastSeen);
if (lastSeenDate !== null) {
span = { firstBarDate: lastSeenDate, lastBarDate: lastSeenDate };
}
}
return {
ok: true,
tickerSource: {
source: 'ceo',
sourceId,
ticker,
mic: exchangeEntry.mic,
role: exchangeEntry.role,
currency,
span,
},
};
}
/**
* Pure adapter converting a raw `eodSymbolChange` document into a validated
* Stage B symbol-change input that will never throw in `matchListingsStageB`.
*/
export function adaptEodSymbolChangeDoc(
doc: unknown,
context: AdaptEodSymbolChangeContext
): AdaptEodSymbolChangeResult {
if (!isPlainRecord(doc)) {
return { ok: false, skipReason: 'invalidFieldType' };
}
const oldSymbolField = readOptionalString(doc, 'oldSymbol');
const newSymbolField = readOptionalString(doc, 'newSymbol');
const exchangeField = readOptionalString(doc, 'exchange');
const eodExchangeField = readOptionalString(doc, 'eodExchange');
const eodSearchCodeField = readOptionalString(doc, 'eodSearchCode');
const countryField = readFirstOptionalString(doc, ['country', 'Country']);
const rawDate = doc.effectiveDate !== undefined ? doc.effectiveDate : doc.date;
const dateTypeValid =
rawDate === undefined ||
rawDate === null ||
typeof rawDate === 'string' ||
rawDate instanceof Date;
const rawValidFrom = doc.validFrom;
const validFromTypeValid =
rawValidFrom === undefined ||
rawValidFrom === null ||
typeof rawValidFrom === 'string' ||
rawValidFrom instanceof Date;
if (
!oldSymbolField.ok ||
!newSymbolField.ok ||
!exchangeField.ok ||
!eodExchangeField.ok ||
!eodSearchCodeField.ok ||
!countryField.ok ||
!dateTypeValid ||
!validFromTypeValid
) {
return { ok: false, skipReason: 'invalidFieldType' };
}
if (
oldSymbolField.value === null ||
newSymbolField.value === null ||
exchangeField.value === null
) {
return { ok: false, skipReason: 'missingId' };
}
const exchange = exchangeField.value;
const exchangeEntry = context.exchangeLookup.get('eod', exchange);
if (context.allowedCountries !== null) {
if (countryField.value !== null) {
const normalizedCountry = normalizeCountryIso2(countryField.value);
if (normalizedCountry === null || !context.allowedCountries.has(normalizedCountry)) {
return { ok: false, skipReason: 'outOfScopeCountry' };
}
} else if (exchangeEntry?.countryIso !== undefined && exchangeEntry.countryIso !== null) {
if (!context.allowedCountries.has(exchangeEntry.countryIso)) {
return { ok: false, skipReason: 'outOfScopeCountry' };
}
}
}
if (exchange.toUpperCase() === 'NMFQS' || exchangeEntry?.role === 'excluded_fund') {
return { ok: false, skipReason: 'excludedMutualFund' };
}
if (exchangeEntry === undefined) {
return { ok: false, skipReason: 'unmappedExchange' };
}
const parsedOld = parseTickerDetailed(oldSymbolField.value, 'eod');
if (!parsedOld.ok || parsedOld.tickerRoot.length > MAX_TICKER_ROOT_LENGTH) {
return { ok: false, skipReason: 'invalidIdentifier' };
}
const effectiveDate = normalizeBarDate(rawDate);
if (effectiveDate === null || effectiveDate <= '0001-01-01') {
return { ok: false, skipReason: 'invalidIdentifier' };
}
let validFrom: string | null = null;
if (rawValidFrom !== undefined && rawValidFrom !== null) {
const normalizedValidFrom = normalizeBarDate(rawValidFrom);
if (normalizedValidFrom === null || normalizedValidFrom >= effectiveDate) {
return { ok: false, skipReason: 'invalidIdentifier' };
}
validFrom = normalizedValidFrom;
}
const eodSourceId =
eodSearchCodeField.value ??
`${newSymbolField.value}.${
eodExchangeField.value ?? (exchangeEntry.countryIso === 'US' ? 'US' : exchange)
}`;
const symbolChange: StageBSymbolChangeInput =
validFrom !== null
? {
eodSourceId,
oldTicker: formatCanonicalTicker(parsedOld.tickerRoot, parsedOld.classSuffix),
effectiveDate,
validFrom,
}
: {
eodSourceId,
oldTicker: formatCanonicalTicker(parsedOld.tickerRoot, parsedOld.classSuffix),
effectiveDate,
};
return { ok: true, symbolChange };
}
/** Streams and adapts `eodSymbols` from a read-only MongoDB reader. */
export async function readEodSymbols(
reader: ReadOnlySourceSymbolReader,
options: ReadSourceCollectionOptions
): Promise<ReadEodSymbolsResult> {
const { set: allowedCountries, list: countryList } = resolveAllowedCountries(options.countries);
const micCurrencyMap = buildMicCurrencyMap(options.knownExchanges);
const context: AdaptEodSymbolContext = {
exchangeLookup: options.exchangeLookup,
barSpans: options.barSpans,
allowedCountries,
micCurrencyMap,
};
const stageARecords: StageASourceRecord[] = [];
const eodListings: StageBEodListingInput[] = [];
const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.eod);
const findOptions: SourceSymbolFindOptions = {
projection: { ...EOD_SYMBOLS_PROJECTION },
...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}),
};
await streamCollection(
reader,
SOURCE_SYMBOL_COLLECTIONS.eod,
buildEodCountryFilter(countryList),
findOptions,
doc => {
stats.docsRead += 1;
const adapted = adaptEodSymbolDoc(doc, context);
if (!adapted.ok) {
stats.skips[adapted.skipReason] += 1;
return;
}
stageARecords.push(adapted.stageARecord);
eodListings.push(adapted.eodListing);
stats.emitted += 1;
stats.invalidIdentifiersNulled += adapted.invalidIdentifiersNulled;
}
);
stageARecords.sort(compareStageARecords);
eodListings.sort(compareEodListings);
return { stageARecords, eodListings, stats };
}
/** Streams and adapts `ibSymbols` from a read-only MongoDB reader. */
export async function readIbSymbols(
reader: ReadOnlySourceSymbolReader,
options: ReadSourceCollectionOptions
): Promise<ReadIbSymbolsResult> {
const { set: allowedCountries, list: countryList } = resolveAllowedCountries(options.countries);
const context: AdaptIbSymbolContext = {
exchangeLookup: options.exchangeLookup,
allowedCountries,
};
const stageARecords: StageASourceRecord[] = [];
const ibContracts: StageBIbContractInput[] = [];
const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.ib);
const findOptions: SourceSymbolFindOptions = {
projection: { ...IB_SYMBOLS_PROJECTION },
...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}),
};
await streamCollection(
reader,
SOURCE_SYMBOL_COLLECTIONS.ib,
buildIbCountryFilter(countryList),
findOptions,
doc => {
stats.docsRead += 1;
const adapted = adaptIbSymbolDoc(doc, context);
if (!adapted.ok) {
stats.skips[adapted.skipReason] += 1;
return;
}
stageARecords.push(adapted.stageARecord);
ibContracts.push(adapted.ibContract);
stats.emitted += 1;
stats.invalidIdentifiersNulled += adapted.invalidIdentifiersNulled;
}
);
stageARecords.sort(compareStageARecords);
ibContracts.sort(compareIbContracts);
return { stageARecords, ibContracts, stats };
}
/** Streams and adapts `qmSymbols` from a read-only MongoDB reader. */
export async function readQmSymbols(
reader: ReadOnlySourceSymbolReader,
options: ReadSourceCollectionOptions
): Promise<ReadTickerSourcesResult> {
const { set: allowedCountries, list: countryList } = resolveAllowedCountries(options.countries);
const micCurrencyMap = buildMicCurrencyMap(options.knownExchanges);
const context: AdaptQmSymbolContext = {
exchangeLookup: options.exchangeLookup,
barSpans: options.barSpans,
allowedCountries,
micCurrencyMap,
};
const tickerSources: StageBTickerSourceInput[] = [];
const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.qm);
const findOptions: SourceSymbolFindOptions = {
projection: { ...QM_SYMBOLS_PROJECTION },
...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}),
};
await streamCollection(
reader,
SOURCE_SYMBOL_COLLECTIONS.qm,
buildQmCountryFilter(countryList),
findOptions,
doc => {
stats.docsRead += 1;
const adapted = adaptQmSymbolDoc(doc, context);
if (!adapted.ok) {
stats.skips[adapted.skipReason] += 1;
return;
}
tickerSources.push(adapted.tickerSource);
stats.emitted += 1;
}
);
tickerSources.sort(compareTickerSources);
return { tickerSources, stats };
}
/** Streams and adapts `ceoSymbols` from a read-only MongoDB reader. */
export async function readCeoSymbols(
reader: ReadOnlySourceSymbolReader,
options: ReadSourceCollectionOptions
): Promise<ReadTickerSourcesResult> {
const { set: allowedCountries, list: countryList } = resolveAllowedCountries(options.countries);
const micCurrencyMap = buildMicCurrencyMap(options.knownExchanges);
const context: AdaptCeoSymbolContext = {
exchangeLookup: options.exchangeLookup,
ceoSpans: options.ceoSpans,
allowedCountries,
micCurrencyMap,
};
const tickerSources: StageBTickerSourceInput[] = [];
const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.ceo);
const findOptions: SourceSymbolFindOptions = {
projection: { ...CEO_SYMBOLS_PROJECTION },
...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}),
};
await streamCollection(
reader,
SOURCE_SYMBOL_COLLECTIONS.ceo,
buildCeoCountryFilter(options.exchangeLookup, countryList),
findOptions,
doc => {
stats.docsRead += 1;
const adapted = adaptCeoSymbolDoc(doc, context);
if (!adapted.ok) {
stats.skips[adapted.skipReason] += 1;
return;
}
tickerSources.push(adapted.tickerSource);
stats.emitted += 1;
}
);
tickerSources.sort(compareTickerSources);
return { tickerSources, stats };
}
/** Streams and adapts `eodSymbolChange` from a read-only MongoDB reader. */
export async function readEodSymbolChanges(
reader: ReadOnlySourceSymbolReader,
options: ReadSourceCollectionOptions
): Promise<ReadEodSymbolChangesResult> {
const { set: allowedCountries, list: countryList } = resolveAllowedCountries(options.countries);
const context: AdaptEodSymbolChangeContext = {
exchangeLookup: options.exchangeLookup,
allowedCountries,
};
const symbolChanges: StageBSymbolChangeInput[] = [];
const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.eodSymbolChange);
const findOptions: SourceSymbolFindOptions = {
projection: { ...EOD_SYMBOL_CHANGE_PROJECTION },
...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}),
};
await streamCollection(
reader,
SOURCE_SYMBOL_COLLECTIONS.eodSymbolChange,
buildEodSymbolChangeFilter(options.exchangeLookup, countryList),
findOptions,
doc => {
stats.docsRead += 1;
const adapted = adaptEodSymbolChangeDoc(doc, context);
if (!adapted.ok) {
stats.skips[adapted.skipReason] += 1;
return;
}
symbolChanges.push(adapted.symbolChange);
stats.emitted += 1;
}
);
symbolChanges.sort(compareSymbolChanges);
return { symbolChanges, stats };
}
/**
* Aggregate read-only entry point reading `eodSymbols`, `ibSymbols`, `qmSymbols`,
* `ceoSymbols`, and `eodSymbolChange` into deterministic Stage A and Stage B inputs.
*/
export async function readSecurityMasterSources(
reader: ReadOnlySourceSymbolReader,
options: ReadSecurityMasterSourcesOptions
): Promise<SecurityMasterSourcesResult> {
assertReadOnlyReader(reader);
const eodResult = await readEodSymbols(reader, options);
const ibResult = await readIbSymbols(reader, options);
const qmResult = await readQmSymbols(reader, options);
const ceoResult = await readCeoSymbols(reader, options);
const symbolChangeResult = await readEodSymbolChanges(reader, options);
const stageARecords: StageASourceRecord[] = [
...eodResult.stageARecords,
...ibResult.stageARecords,
];
stageARecords.sort(compareStageARecords);
const tickerSources: StageBTickerSourceInput[] = [
...qmResult.tickerSources,
...ceoResult.tickerSources,
];
tickerSources.sort(compareTickerSources);
return {
stageARecords,
stageBInput: {
eodListings: eodResult.eodListings,
ibContracts: ibResult.ibContracts,
tickerSources,
symbolChanges: symbolChangeResult.symbolChanges,
},
stats: {
eodSymbols: eodResult.stats,
ibSymbols: ibResult.stats,
qmSymbols: qmResult.stats,
ceoSymbols: ceoResult.stats,
eodSymbolChange: symbolChangeResult.stats,
},
};
}