T-40: M1.1c — Pass 1 exchanges: ISO MIC seed, source-code role classifier and reviewable seed-SQL generator

This commit is contained in:
Studio 2026-11-27 14:56:52 -05:00
parent 2dbfb7e5bc
commit c36f89352c
12 changed files with 1848 additions and 20 deletions

View file

@ -41,3 +41,16 @@ bun run build
# Run PostgreSQL environment & read-only MongoDB safety tests
bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/pipeline-safety.test.ts
```
## Pass 1 Exchange Seed Generator
The committed baseline seed in `database/postgres/init/35-security-master-exchange-seed.sql` covers the 11 US+CA ISO 10383 MICs and the 17 documented explicit provider mappings. To regenerate a full reviewable candidate seed and unresolved-codes report from the read-only QA MongoDB collections (`eodExchanges`, `ibExchanges`, `qmExchanges`, `ceoExchanges`) on the host:
```bash
MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@localhost:27017/stock?authSource=stock" \
bun run apps/stock/data-pipeline/src/security-master/generate-exchange-seed.ts \
--sql-out ./tmp/35-security-master-exchange-seed.generated.sql \
--report-out ./tmp/pass1-unresolved-exchanges.md
```
- **Read-only guarantee:** The CLI initializes config with `mongoReadOnly: true`, connects via `MONGODB_READ_URI` with `readOnly: true`, performs zero MongoDB writes, and performs zero PostgreSQL writes.
- **Review workflow:** Inspect `./tmp/pass1-unresolved-exchanges.md` for unresolved codes (unknown MICs, multi-valued `OperatingMIC`, missing MICs), add approved mappings to `EXPLICIT_EXCHANGE_SOURCE_RULES` (or `database/postgres/init/35-security-master-exchange-seed.sql` with `reviewed_by` set as appropriate), and commit the reviewed SQL. Re-applying the migration never overwrites rows where `reviewed_by IS NOT NULL`.

View file

@ -0,0 +1,564 @@
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 type UnresolvedExchangeReason =
| 'empty_code'
| '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[];
}
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 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,
}))
);
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 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;
}
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;
}
// 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(
(a, b) =>
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 ?? '')
);
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),
};
}

View file

@ -0,0 +1,143 @@
import {
compareAscii,
type ExchangeClassificationResult,
type ExchangeSeedRow,
type ExchangeSourceMapRow,
type UnresolvedExchangeRecord,
} from './exchange-pass1';
export interface GenerateExchangeSeedSqlInput {
exchanges?: readonly ExchangeSeedRow[];
mappings: readonly ExchangeSourceMapRow[];
}
export function escapeSqlLiteral(value: string | null | undefined): string {
if (value === null || value === undefined) {
return 'NULL';
}
if (value.includes('\0')) {
throw new Error('SQL literal value must not contain NUL bytes');
}
return `'${value.replaceAll("'", "''")}'`;
}
export function generateExchangeSeedSql(input: GenerateExchangeSeedSqlInput): string {
const exchanges = [...(input.exchanges ?? [])].sort((a, b) => compareAscii(a.mic, b.mic));
const mappings = [...input.mappings].sort(
(a, b) => compareAscii(a.source, b.source) || compareAscii(a.sourceCode, b.sourceCode)
);
const sections: string[] = [
[
'-- Security master Pass 1 exchange seed (M1.1c)',
'-- Generated deterministically by apps/stock/data-pipeline/src/security-master/exchange-seed-sql.ts.',
'-- Runs in the active search_path; idempotent and never overwrites rows with reviewed_by IS NOT NULL.',
].join('\n'),
];
if (exchanges.length > 0) {
const exchangeValues = exchanges.map(row =>
` (${[
escapeSqlLiteral(row.mic),
escapeSqlLiteral(row.operatingMic),
escapeSqlLiteral(row.name),
escapeSqlLiteral(row.countryIso),
escapeSqlLiteral(row.currency),
escapeSqlLiteral(row.timezone),
escapeSqlLiteral(row.calendarCode),
escapeSqlLiteral(row.boardLotPolicy),
].join(', ')})`
);
sections.push(
[
'INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy)',
'VALUES',
`${exchangeValues.join(',\n')}`,
'ON CONFLICT (mic) DO NOTHING;',
].join('\n')
);
}
if (mappings.length > 0) {
const mappingValues = mappings.map(row =>
` (${[
escapeSqlLiteral(row.source),
escapeSqlLiteral(row.sourceCode),
escapeSqlLiteral(row.role),
escapeSqlLiteral(row.mic),
escapeSqlLiteral(row.countryIso),
escapeSqlLiteral(row.method),
escapeSqlLiteral(row.reviewedBy ?? null),
].join(', ')})`
);
sections.push(
[
'INSERT INTO exchange_source_map (source, source_code, role, mic, country_iso, method, reviewed_by)',
'VALUES',
`${mappingValues.join(',\n')}`,
'ON CONFLICT (source, source_code) DO UPDATE SET',
' role = EXCLUDED.role,',
' mic = EXCLUDED.mic,',
' country_iso = EXCLUDED.country_iso,',
' method = EXCLUDED.method',
'WHERE exchange_source_map.reviewed_by IS NULL;',
].join('\n')
);
}
return `${sections.join('\n\n')}\n`;
}
function escapeMarkdownCell(value: string | null | undefined): string {
if (value === null || value === undefined || value.length === 0) {
return '';
}
return value.replaceAll('\\', '\\\\').replaceAll('|', '\\|').replaceAll(/\r?\n/g, ' ');
}
function sortUnresolvedForReport(
records: readonly UnresolvedExchangeRecord[]
): UnresolvedExchangeRecord[] {
return [...records].sort(
(a, b) =>
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 ?? '')
);
}
export function generateUnresolvedExchangesMarkdown(result: ExchangeClassificationResult): string {
const unresolved = sortUnresolvedForReport(result.unresolved);
const lines: string[] = [
'# Security Master Pass 1 — Unresolved Exchange Codes',
'',
`- Mapped: ${result.mapped.length}`,
`- Unresolved: ${unresolved.length}`,
'',
];
if (unresolved.length === 0) {
lines.push('All source exchange records resolved cleanly.', '');
return lines.join('\n');
}
lines.push(
'| Source | Code | Raw Code | Operating MIC | Country | Currency | Name | Reason |',
'| --- | --- | --- | --- | --- | --- | --- | --- |'
);
for (const row of unresolved) {
lines.push(
`| ${escapeMarkdownCell(row.source)} | ${escapeMarkdownCell(row.sourceCode)} | ${escapeMarkdownCell(row.rawCode)} | ${escapeMarkdownCell(row.operatingMic)} | ${escapeMarkdownCell(row.country)} | ${escapeMarkdownCell(row.currency)} | ${escapeMarkdownCell(row.name)} | ${escapeMarkdownCell(row.reason)} |`
);
}
lines.push('');
return lines.join('\n');
}

View file

@ -0,0 +1,247 @@
import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname } from 'node:path';
import { getLogger } from '@stock-bot/logger';
import { MongoDBClient, type MongoDBClientConfig } from '@stock-bot/mongodb';
import { initializeStockConfig, type StockAppConfig } from '@stock-bot/stock-config';
import {
classifySourceExchanges,
ISO_EXCHANGE_SEEDS,
normalizeRawExchangeDoc,
type ExchangeClassificationResult,
type ExchangeSeedRow,
type ExchangeSource,
type SourceExchangeRecord,
} from './exchange-pass1';
import {
generateExchangeSeedSql,
generateUnresolvedExchangesMarkdown,
} from './exchange-seed-sql';
export const SOURCE_EXCHANGE_COLLECTIONS: Readonly<Record<ExchangeSource, string>> = Object.freeze({
eod: 'eodExchanges',
ib: 'ibExchanges',
qm: 'qmExchanges',
ceo: 'ceoExchanges',
});
export interface ReadOnlyExchangeMongoClient {
isReadOnly(): boolean;
find<T extends Record<string, unknown> = Record<string, unknown>>(
collectionName: string,
filter?: Record<string, unknown>
): Promise<T[]>;
}
export interface GenerateExchangeSeedOptions {
sqlOutPath: string;
reportOutPath: string;
knownExchanges?: readonly ExchangeSeedRow[];
}
export interface GenerateExchangeSeedOutput {
sqlPath: string;
reportPath: string;
sql: string;
reportMarkdown: string;
classification: ExchangeClassificationResult;
countsByCollection: Record<ExchangeSource, number>;
}
export interface ParsedGenerateExchangeSeedArgs {
sqlOutPath: string;
reportOutPath: string;
}
const DEFAULT_SQL_OUT_PATH = './tmp/35-security-master-exchange-seed.generated.sql';
const DEFAULT_REPORT_OUT_PATH = './tmp/pass1-unresolved-exchanges.md';
function extractMongoDatabaseFromUri(uri?: string): string | undefined {
const trimmed = uri?.trim();
if (!trimmed) {
return undefined;
}
const schemeMatch = /^mongodb(?:\+srv)?:\/\/(.*)$/i.exec(trimmed);
const rest = schemeMatch?.[1];
if (!rest) {
return undefined;
}
const delimiterMatch = /[/?#]/.exec(rest);
if (!delimiterMatch || delimiterMatch[0] !== '/') {
return undefined;
}
const pathPart = rest.slice(delimiterMatch.index).split(/[?#]/, 1)[0] ?? '';
const rawDb = pathPart.replace(/^\/+/, '').split('/')[0];
if (!rawDb) {
return undefined;
}
try {
return decodeURIComponent(rawDb);
} catch {
return rawDb;
}
}
export function resolveReadOnlyMongoClientConfig(
config: Pick<StockAppConfig, 'database'>
): MongoDBClientConfig {
const mongo = config.database.mongodb;
const resolvedUri = mongo.readUri?.trim() || mongo.uri;
const resolvedDatabase =
extractMongoDatabaseFromUri(mongo.readUri) ??
extractMongoDatabaseFromUri(resolvedUri) ??
mongo.database;
return {
host: mongo.host ?? 'localhost',
port: mongo.port ?? 27017,
database: resolvedDatabase,
username: mongo.user,
password: mongo.password,
authSource: mongo.authSource,
uri: resolvedUri,
readOnly: true,
poolSettings: {
maxPoolSize: mongo.poolSize,
minPoolSize: 1,
maxIdleTime: 30_000,
},
};
}
export function parseGenerateExchangeSeedArgs(
argv: readonly string[]
): ParsedGenerateExchangeSeedArgs {
let sqlOutPath = DEFAULT_SQL_OUT_PATH;
let reportOutPath = DEFAULT_REPORT_OUT_PATH;
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--sql-out') {
const value = argv[i + 1];
if (!value || value.startsWith('--')) {
throw new Error('Missing value for --sql-out');
}
sqlOutPath = value;
i += 1;
continue;
}
if (arg?.startsWith('--sql-out=')) {
const value = arg.slice('--sql-out='.length);
if (!value) {
throw new Error('Missing value for --sql-out');
}
sqlOutPath = value;
continue;
}
if (arg === '--report-out') {
const value = argv[i + 1];
if (!value || value.startsWith('--')) {
throw new Error('Missing value for --report-out');
}
reportOutPath = value;
i += 1;
continue;
}
if (arg?.startsWith('--report-out=')) {
const value = arg.slice('--report-out='.length);
if (!value) {
throw new Error('Missing value for --report-out');
}
reportOutPath = value;
continue;
}
throw new Error(`Unknown argument: ${String(arg)}`);
}
return { sqlOutPath, reportOutPath };
}
export async function generateExchangeSeedFromMongo(
mongo: ReadOnlyExchangeMongoClient,
options: GenerateExchangeSeedOptions
): Promise<GenerateExchangeSeedOutput> {
if (!mongo.isReadOnly()) {
throw new Error(
'generateExchangeSeedFromMongo requires a read-only MongoDB client (isReadOnly() must be true)'
);
}
const orderedSources: readonly ExchangeSource[] = ['eod', 'ib', 'qm', 'ceo'];
const normalizedRecords: SourceExchangeRecord[] = [];
const countsByCollection: Record<ExchangeSource, number> = {
eod: 0,
ib: 0,
qm: 0,
ceo: 0,
};
for (const source of orderedSources) {
const collectionName = SOURCE_EXCHANGE_COLLECTIONS[source];
const docs = await mongo.find<Record<string, unknown>>(collectionName, {});
countsByCollection[source] = docs.length;
for (const doc of docs) {
normalizedRecords.push(normalizeRawExchangeDoc(source, doc));
}
}
const knownExchanges = options.knownExchanges ?? ISO_EXCHANGE_SEEDS;
const classification = classifySourceExchanges(normalizedRecords, { knownExchanges });
const sql = generateExchangeSeedSql({
exchanges: knownExchanges,
mappings: classification.mapped,
});
const reportMarkdown = generateUnresolvedExchangesMarkdown(classification);
mkdirSync(dirname(options.sqlOutPath), { recursive: true });
writeFileSync(options.sqlOutPath, sql, 'utf8');
mkdirSync(dirname(options.reportOutPath), { recursive: true });
writeFileSync(options.reportOutPath, reportMarkdown, 'utf8');
return {
sqlPath: options.sqlOutPath,
reportPath: options.reportOutPath,
sql,
reportMarkdown,
classification,
countsByCollection,
};
}
async function runCli(): Promise<void> {
const logger = getLogger('security-master-pass1-seed');
const args = parseGenerateExchangeSeedArgs(process.argv.slice(2));
const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true });
const mongoConfig = resolveReadOnlyMongoClientConfig(config);
const mongo = new MongoDBClient(mongoConfig, logger);
await mongo.connect();
try {
const result = await generateExchangeSeedFromMongo(mongo, {
sqlOutPath: args.sqlOutPath,
reportOutPath: args.reportOutPath,
});
logger.info('Generated Pass 1 security master exchange seed files', {
sqlPath: result.sqlPath,
reportPath: result.reportPath,
mappedCount: result.classification.mapped.length,
unresolvedCount: result.classification.unresolved.length,
countsByCollection: result.countsByCollection,
});
} finally {
await mongo.disconnect();
}
}
if (import.meta.main) {
runCli().catch(error => {
const logger = getLogger('security-master-pass1-seed');
logger.fatal('Failed to generate Pass 1 exchange seed SQL', { error });
process.exit(1);
});
}

View file

@ -0,0 +1,40 @@
export {
classifySourceExchanges,
compareAscii,
EXCHANGE_SOURCES,
EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS,
EXPLICIT_EXCHANGE_SOURCE_RULES,
isExchangeSource,
ISO_EXCHANGE_SEEDS,
normalizeRawExchangeDoc,
type BoardLotPolicy,
type ClassificationMethod,
type ClassifySourceExchangesOptions,
type ExchangeClassificationResult,
type ExchangeRole,
type ExchangeSeedRow,
type ExchangeSource,
type ExchangeSourceMapRow,
type ExplicitExchangeSourceRule,
type SourceExchangeRecord,
type UnresolvedExchangeReason,
type UnresolvedExchangeRecord,
} from './exchange-pass1';
export {
escapeSqlLiteral,
generateExchangeSeedSql,
generateUnresolvedExchangesMarkdown,
type GenerateExchangeSeedSqlInput,
} from './exchange-seed-sql';
export {
generateExchangeSeedFromMongo,
parseGenerateExchangeSeedArgs,
resolveReadOnlyMongoClientConfig,
SOURCE_EXCHANGE_COLLECTIONS,
type GenerateExchangeSeedOptions,
type GenerateExchangeSeedOutput,
type ParsedGenerateExchangeSeedArgs,
type ReadOnlyExchangeMongoClient,
} from './generate-exchange-seed';

View file

@ -0,0 +1,44 @@
-- Security master Pass 1 exchange seed (M1.1c)
-- Generated deterministically by apps/stock/data-pipeline/src/security-master/exchange-seed-sql.ts.
-- Runs in the active search_path; idempotent and never overwrites rows with reviewed_by IS NOT NULL.
INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy)
VALUES
('ARCX', 'XNYS', 'NYSE Arca', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
('BATS', 'BATS', 'Cboe BZX Exchange', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
('IEXG', 'IEXG', 'Investors Exchange', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
('NEOE', 'NEOE', 'Cboe Canada (NEO Exchange)', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered'),
('OTCM', 'OTCM', 'OTC Markets', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
('XASE', 'XNYS', 'NYSE American', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
('XCNQ', 'XCNQ', 'Canadian Securities Exchange', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered'),
('XNAS', 'XNAS', 'NASDAQ Stock Market', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
('XNYS', 'XNYS', 'New York Stock Exchange', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
('XTSE', 'XTSE', 'Toronto Stock Exchange', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered'),
('XTSX', 'XTSX', 'TSX Venture Exchange', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered')
ON CONFLICT (mic) DO NOTHING;
INSERT INTO exchange_source_map (source, source_code, role, mic, country_iso, method, reviewed_by)
VALUES
('ceo', 'AQL', 'primary_venue', 'NEOE', 'CA', 'explicit_rule', NULL),
('ceo', 'CDX', 'primary_venue', 'XTSX', 'CA', 'explicit_rule', NULL),
('ceo', 'CNQ', 'primary_venue', 'XCNQ', 'CA', 'explicit_rule', NULL),
('ceo', 'TSX', 'primary_venue', 'XTSE', 'CA', 'explicit_rule', NULL),
('eod', 'FOREX', 'forex', NULL, NULL, 'explicit_rule', NULL),
('eod', 'NMFQS', 'excluded_fund', NULL, 'US', 'explicit_rule', NULL),
('eod', 'US', 'composite', NULL, 'US', 'explicit_rule', NULL),
('ib', 'AEQLIT', 'ats_routing', NULL, 'CA', 'explicit_rule', NULL),
('ib', 'ARCAEDGE', 'ats_routing', NULL, 'US', 'explicit_rule', NULL),
('ib', 'BEX', 'ats_routing', NULL, 'US', 'explicit_rule', NULL),
('ib', 'DRCTEDGE', 'ats_routing', NULL, 'US', 'explicit_rule', NULL),
('ib', 'EDGEA', 'ats_routing', NULL, 'US', 'explicit_rule', NULL),
('ib', 'IBEOS', 'ats_routing', NULL, 'US', 'explicit_rule', NULL),
('ib', 'IEX', 'ats_routing', NULL, 'US', 'explicit_rule', NULL),
('ib', 'MEMX', 'ats_routing', NULL, 'US', 'explicit_rule', NULL),
('ib', 'OTCLNKECN', 'ats_routing', NULL, 'US', 'explicit_rule', NULL),
('ib', 'PSX', 'ats_routing', NULL, 'US', 'explicit_rule', NULL)
ON CONFLICT (source, source_code) DO UPDATE SET
role = EXCLUDED.role,
mic = EXCLUDED.mic,
country_iso = EXCLUDED.country_iso,
method = EXCLUDED.method
WHERE exchange_source_map.reviewed_by IS NULL;

View file

@ -15,6 +15,7 @@ const MASTER_FILES = new Set([
'04-provider-exchange-mapping-schema.sql',
'05-add-visible-column.sql',
'34-security-master.sql',
'35-security-master-exchange-seed.sql',
]);
const RESEARCH_FILES = new Set([

View file

@ -20,6 +20,7 @@ const MASTER_FILES = [
'04-provider-exchange-mapping-schema.sql',
'05-add-visible-column.sql',
'34-security-master.sql',
'35-security-master-exchange-seed.sql',
];
const LEGACY_MASTER_TABLES = [
@ -136,13 +137,13 @@ async function createIsolatedFixture() {
}
describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
test('Case A: init SQL 01-34 contain no CREATE DATABASE/\\c and create all master and research tables', async () => {
test('Case A: init SQL 01-35 contain no CREATE DATABASE/\\c and create all master and research tables', async () => {
const f = await createIsolatedFixture();
const sqlFiles = readdirSync(initDir)
.filter(file => file.endsWith('.sql'))
.sort();
expect(sqlFiles.length).toBeGreaterThanOrEqual(34);
expect(sqlFiles.length).toBeGreaterThanOrEqual(35);
for (const file of sqlFiles) {
const sql = readFileSync(join(initDir, file), 'utf8');
@ -176,7 +177,7 @@ describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
expect(await f.hasColumn('backtest_results', 'canonical_result')).toBe(true);
});
test('Case B: master track creates master tables, records exact 6 files, and is idempotent', async () => {
test('Case B: master track creates master tables, records exact 7 files, and is idempotent', async () => {
const f = await createIsolatedFixture();
const first = await runPostgresMigrations(f.postgres, { track: 'master' });

View file

@ -367,7 +367,7 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
).toBe(1);
});
test('34-security-master.sql is applied on master and all tracks, excluded from research, and idempotent', async () => {
test('34-security-master.sql and 35-security-master-exchange-seed.sql are applied on master and all tracks, excluded from research, and idempotent', async () => {
const securityMasterTables = [
'exchange',
'exchange_source_map',
@ -382,13 +382,16 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
'golden_field_audit',
];
// 1. research track must NOT apply 34-security-master.sql or create any of its 11 tables;
// master track applies it and is idempotent on re-run.
// 1. research track must NOT apply 34-security-master.sql or 35-security-master-exchange-seed.sql;
// master track applies both in order and is idempotent on re-run.
const f1 = await fixture();
const runner1 = f1.startup();
const researchApplied = await runner1.runTrack('research');
expect(researchApplied).not.toContain('34-security-master.sql');
expect(await f1.recorded()).not.toContain('34-security-master.sql');
expect(researchApplied).not.toContain('35-security-master-exchange-seed.sql');
const recordedAfterResearch = await f1.recorded();
expect(recordedAfterResearch).not.toContain('34-security-master.sql');
expect(recordedAfterResearch).not.toContain('35-security-master-exchange-seed.sql');
const tablesAfterResearch = new Set(await f1.relations());
for (const table of securityMasterTables) {
@ -397,7 +400,13 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
const masterApplied = await runner1.runTrack('master');
expect(masterApplied).toContain('34-security-master.sql');
expect(await f1.recorded()).toContain('34-security-master.sql');
expect(masterApplied).toContain('35-security-master-exchange-seed.sql');
expect(masterApplied.indexOf('35-security-master-exchange-seed.sql')).toBe(
masterApplied.indexOf('34-security-master.sql') + 1
);
const recordedAfterMaster = await f1.recorded();
expect(recordedAfterMaster).toContain('34-security-master.sql');
expect(recordedAfterMaster).toContain('35-security-master-exchange-seed.sql');
const tablesAfterMaster = new Set(await f1.relations());
for (const table of securityMasterTables) {
@ -406,7 +415,7 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
expect(await runner1.runTrack('master')).toEqual([]);
// 2. all track applies 34-security-master.sql alongside 01-05 and 09-33 and is idempotent.
// 2. all track applies 34 and 35 alongside 01-05 and 09-33 and is idempotent.
const f2 = await fixture();
const runner2 = f2.startup();
const allApplied = await runner2.runTrack('all');
@ -415,7 +424,10 @@ describe.skipIf(!url)('startup migrations on real PostgreSQL', () => {
expect(allApplied).toContain('09-backtest-run-contract.sql');
expect(allApplied).toContain('33-candidate-decimal-normalization.sql');
expect(allApplied).toContain('34-security-master.sql');
expect(await f2.recorded()).toContain('34-security-master.sql');
expect(allApplied).toContain('35-security-master-exchange-seed.sql');
const recordedAfterAll = await f2.recorded();
expect(recordedAfterAll).toContain('34-security-master.sql');
expect(recordedAfterAll).toContain('35-security-master-exchange-seed.sql');
const tablesAfterAll = new Set(await f2.relations());
for (const table of securityMasterTables) {

View file

@ -0,0 +1,227 @@
import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, test } from 'bun:test';
import { Pool } from 'pg';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('security-master-exchange-seed-test');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const exchangeSeedSqlPath = fileURLToPath(
new URL('../../database/postgres/init/35-security-master-exchange-seed.sql', import.meta.url)
);
const REQUIRED_US_MICS = ['ARCX', 'BATS', 'IEXG', 'OTCM', 'XASE', 'XNAS', 'XNYS'] as const;
const REQUIRED_CA_MICS = ['NEOE', 'XCNQ', 'XTSE', 'XTSX'] as const;
const REQUIRED_MICS = [...REQUIRED_US_MICS, ...REQUIRED_CA_MICS] as const;
const IB_ATS_ROUTING_CODES = [
'AEQLIT',
'ARCAEDGE',
'BEX',
'DRCTEDGE',
'EDGEA',
'IBEOS',
'IEX',
'MEMX',
'OTCLNKECN',
'PSX',
] as const;
const cleanup: (() => Promise<void> | void)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
async function createIsolatedFixture() {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Dedicated stock_bot_safety database required');
}
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({
connectionString: url,
options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`,
});
cleanup.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', {
get: () => ({
connect: () => pool.connect(),
}),
});
await runPostgresMigrations(postgres, { track: 'master' });
return { pool, schema, postgres };
}
describe.skipIf(!url)('security master Pass 1 exchange seed migration', () => {
test('seeds all 11 required US+CA ISO MICs and explicit source mappings with referential integrity', async () => {
const f = await createIsolatedFixture();
const exchanges = (
await f.pool.query(
`SELECT mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy
FROM exchange
ORDER BY mic`
)
).rows as Array<{
mic: string;
operating_mic: string;
name: string;
country_iso: string;
currency: string;
timezone: string;
calendar_code: string;
board_lot_policy: string;
}>;
const exchangeByMic = new Map(exchanges.map(row => [row.mic, row]));
for (const mic of REQUIRED_MICS) {
const row = exchangeByMic.get(mic);
expect(row).toBeDefined();
expect(row?.timezone.trim().length).toBeGreaterThan(0);
expect(row?.calendar_code.trim().length).toBeGreaterThan(0);
}
for (const caMic of REQUIRED_CA_MICS) {
const row = exchangeByMic.get(caMic);
expect(row?.board_lot_policy).toBe('tsx_tiered');
expect(row?.country_iso).toBe('CA');
expect(row?.currency).toBe('CAD');
}
for (const usMic of REQUIRED_US_MICS) {
const row = exchangeByMic.get(usMic);
expect(row?.board_lot_policy).toBe('us_100');
expect(row?.country_iso).toBe('US');
expect(row?.currency).toBe('USD');
}
const mappings = (
await f.pool.query(
`SELECT source, source_code, role, mic, country_iso, method, reviewed_by
FROM exchange_source_map
ORDER BY source, source_code`
)
).rows as Array<{
source: string;
source_code: string;
role: string;
mic: string | null;
country_iso: string | null;
method: string;
reviewed_by: string | null;
}>;
const mappingByKey = new Map(mappings.map(row => [`${row.source}:${row.source_code}`, row]));
// CEO primary venues
expect(mappingByKey.get('ceo:TSX')).toMatchObject({ role: 'primary_venue', mic: 'XTSE' });
expect(mappingByKey.get('ceo:CDX')).toMatchObject({ role: 'primary_venue', mic: 'XTSX' });
expect(mappingByKey.get('ceo:CNQ')).toMatchObject({ role: 'primary_venue', mic: 'XCNQ' });
expect(mappingByKey.get('ceo:AQL')).toMatchObject({ role: 'primary_venue', mic: 'NEOE' });
// EOD non-venue / composite / forex codes
expect(mappingByKey.get('eod:US')).toMatchObject({ role: 'composite', mic: null });
expect(mappingByKey.get('eod:NMFQS')).toMatchObject({ role: 'excluded_fund', mic: null });
expect(mappingByKey.get('eod:FOREX')).toMatchObject({ role: 'forex', mic: null });
// IB ATS routing codes
for (const code of IB_ATS_ROUTING_CODES) {
expect(mappingByKey.get(`ib:${code}`)).toMatchObject({ role: 'ats_routing', mic: null });
}
// Every non-null exchange_source_map.mic resolves to an exchange row
const orphanCount = (
await f.pool.query(
`SELECT count(*)::int AS count
FROM exchange_source_map m
LEFT JOIN exchange e ON e.mic = m.mic
WHERE m.mic IS NOT NULL AND e.mic IS NULL`
)
).rows[0].count as number;
expect(orphanCount).toBe(0);
});
test('is idempotent on raw SQL re-apply, preserves reviewed rows, and refreshes unreviewed rows', async () => {
const f = await createIsolatedFixture();
const rawSql = readFileSync(exchangeSeedSqlPath, 'utf8');
const countRows = async () => ({
exchanges: (await f.pool.query('SELECT count(*)::int AS count FROM exchange')).rows[0]
.count as number,
mappings: (await f.pool.query('SELECT count(*)::int AS count FROM exchange_source_map'))
.rows[0].count as number,
});
const initialCounts = await countRows();
expect(initialCounts.exchanges).toBe(11);
expect(initialCounts.mappings).toBe(17);
// Re-apply twice: row counts stay identical
await f.pool.query(rawSql);
await f.pool.query(rawSql);
expect(await countRows()).toEqual(initialCounts);
// Director-reviewed override must NOT be overwritten by re-apply
await f.pool.query(
`UPDATE exchange_source_map
SET role = 'primary_venue', mic = 'XNYS', method = 'director_override', reviewed_by = 'director'
WHERE source = 'eod' AND source_code = 'US'`
);
// Unreviewed row modification SHOULD be refreshed back to seed values on re-apply
await f.pool.query(
`UPDATE exchange_source_map
SET role = 'composite', mic = NULL, method = 'stale_value'
WHERE source = 'ceo' AND source_code = 'TSX' AND reviewed_by IS NULL`
);
await f.pool.query(rawSql);
const reviewedRow = (
await f.pool.query(
`SELECT role, mic, method, reviewed_by
FROM exchange_source_map
WHERE source = 'eod' AND source_code = 'US'`
)
).rows[0];
expect(reviewedRow).toEqual({
role: 'primary_venue',
mic: 'XNYS',
method: 'director_override',
reviewed_by: 'director',
});
const refreshedRow = (
await f.pool.query(
`SELECT role, mic, method, reviewed_by
FROM exchange_source_map
WHERE source = 'ceo' AND source_code = 'TSX'`
)
).rows[0];
expect(refreshedRow).toEqual({
role: 'primary_venue',
mic: 'XTSE',
method: 'explicit_rule',
reviewed_by: null,
});
expect(await countRows()).toEqual(initialCounts);
});
});

View file

@ -85,6 +85,37 @@ async function expectPgErrorCode(operation: Promise<unknown>, expectedCode: stri
throw new Error(`Expected PostgreSQL error code ${expectedCode}, but query succeeded`);
}
async function ensureExchange(
pool: Pool,
mic: string,
overrides: {
operatingMic?: string;
name?: string;
countryIso?: string;
currency?: string;
timezone?: string;
calendarCode?: string;
boardLotPolicy?: string;
} = {}
): Promise<void> {
await pool.query(
`INSERT INTO exchange (
mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (mic) DO NOTHING`,
[
mic,
overrides.operatingMic ?? mic,
overrides.name ?? `${mic} Exchange`,
overrides.countryIso ?? 'US',
overrides.currency ?? 'USD',
overrides.timezone ?? 'America/New_York',
overrides.calendarCode ?? mic,
overrides.boardLotPolicy ?? 'us_100',
]
);
}
async function seedExchange(
pool: Pool,
mic: string,
@ -144,24 +175,25 @@ describe.skipIf(!url)('security master PostgreSQL schema', () => {
test('accepts valid insert chain across all 11 tables and populates defaults', async () => {
const f = await createIsolatedFixture();
// 1. exchange (omitting board_lot_policy to verify default 'us_100')
// 1. exchange (omitting board_lot_policy on an unseeded synthetic MIC to verify default 'us_100')
const exchangeRow = (
await f.pool.query(
`INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code)
VALUES ('XNYS', 'XNYS', 'New York Stock Exchange', 'US', 'USD', 'America/New_York', 'XNYS')
VALUES ('XTST', 'XTST', 'Synthetic Test Exchange', 'US', 'USD', 'America/New_York', 'XNYS')
RETURNING board_lot_policy`
)
).rows[0];
expect(exchangeRow.board_lot_policy).toBe('us_100');
await seedExchange(f.pool, 'OTCM', { name: 'OTC Markets' });
await ensureExchange(f.pool, 'XNYS', { name: 'New York Stock Exchange' });
await ensureExchange(f.pool, 'OTCM', { name: 'OTC Markets' });
// 2. exchange_source_map (primary_venue with mic, and composite with NULL mic)
await f.pool.query(
`INSERT INTO exchange_source_map (source, source_code, role, mic, country_iso, method)
VALUES
('eod', 'NYSE', 'primary_venue', 'XNYS', 'US', 'manual_seed'),
('eod', 'US', 'composite', NULL, 'US', 'manual_seed')`
('eod', 'TEST_COMP', 'composite', NULL, 'US', 'manual_seed')`
);
// 3. instrument
@ -269,7 +301,7 @@ describe.skipIf(!url)('security master PostgreSQL schema', () => {
test('rejects foreign key violations (23503)', async () => {
const f = await createIsolatedFixture();
await seedExchange(f.pool, 'XNYS');
await ensureExchange(f.pool, 'XNYS');
const instrumentId = (
await f.pool.query(
`INSERT INTO instrument (canonical_name, security_type)
@ -330,7 +362,7 @@ describe.skipIf(!url)('security master PostgreSQL schema', () => {
test('rejects unique and primary key violations (23505) while allowing distinct dates and NULL ISINs', async () => {
const f = await createIsolatedFixture();
await seedExchange(f.pool, 'XNYS');
await ensureExchange(f.pool, 'XNYS');
const instrumentId = (
await f.pool.query(
@ -409,7 +441,7 @@ describe.skipIf(!url)('security master PostgreSQL schema', () => {
test('rejects CHECK constraint violations (23514) and accepts valid boundary values', async () => {
const f = await createIsolatedFixture();
await seedExchange(f.pool, 'XNYS');
await ensureExchange(f.pool, 'XNYS');
const instrumentId = (
await f.pool.query(
`INSERT INTO instrument (canonical_name, security_type)
@ -531,15 +563,15 @@ describe.skipIf(!url)('security master PostgreSQL schema', () => {
test('allows interlisted listings on different mics and ticker reuse across distinct instruments', async () => {
const f = await createIsolatedFixture();
await seedExchange(f.pool, 'XTSE', {
await ensureExchange(f.pool, 'XTSE', {
name: 'Toronto Stock Exchange',
countryIso: 'CA',
currency: 'CAD',
timezone: 'America/Toronto',
boardLotPolicy: 'tsx_tiered',
});
await seedExchange(f.pool, 'XNYS');
await seedExchange(f.pool, 'XNAS', { name: 'NASDAQ' });
await ensureExchange(f.pool, 'XNYS');
await ensureExchange(f.pool, 'XNAS', { name: 'NASDAQ' });
// Interlisted Shopify: one instrument, two listings on XTSE (CAD) and XNYS (USD)
const shopInstrumentId = (

View file

@ -0,0 +1,504 @@
import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, test } from 'bun:test';
import {
classifySourceExchanges,
escapeSqlLiteral,
EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS,
generateExchangeSeedFromMongo,
generateExchangeSeedSql,
generateUnresolvedExchangesMarkdown,
ISO_EXCHANGE_SEEDS,
normalizeRawExchangeDoc,
parseGenerateExchangeSeedArgs,
resolveReadOnlyMongoClientConfig,
SOURCE_EXCHANGE_COLLECTIONS,
type ExchangeSource,
type ReadOnlyExchangeMongoClient,
type SourceExchangeRecord,
} from '../../apps/stock/data-pipeline/src/security-master';
const committedSeedPath = fileURLToPath(
new URL('../../database/postgres/init/35-security-master-exchange-seed.sql', import.meta.url)
);
const tempDirs: string[] = [];
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe('security master Pass 1 exchange classifier', () => {
test('explicit rules take precedence over OperatingMIC', () => {
const result = classifySourceExchanges([
{ source: 'eod', code: 'US', operatingMic: 'XNYS', country: 'US' },
{ source: 'eod', code: 'NMFQS', operatingMic: 'XNAS', country: 'US' },
{ source: 'eod', code: 'FOREX', operatingMic: 'XNYS' },
{ source: 'ib', code: 'IEX', operatingMic: 'IEXG', country: 'US' },
{ source: 'ceo', code: 'TSX', operatingMic: 'XNYS', country: 'CA' },
]);
expect(result.unresolved).toEqual([]);
expect(result.mapped).toEqual([
{
source: 'ceo',
sourceCode: 'TSX',
role: 'primary_venue',
mic: 'XTSE',
countryIso: 'CA',
method: 'explicit_rule',
reviewedBy: null,
},
{
source: 'eod',
sourceCode: 'FOREX',
role: 'forex',
mic: null,
countryIso: null,
method: 'explicit_rule',
reviewedBy: null,
},
{
source: 'eod',
sourceCode: 'NMFQS',
role: 'excluded_fund',
mic: null,
countryIso: 'US',
method: 'explicit_rule',
reviewedBy: null,
},
{
source: 'eod',
sourceCode: 'US',
role: 'composite',
mic: null,
countryIso: 'US',
method: 'explicit_rule',
reviewedBy: null,
},
{
source: 'ib',
sourceCode: 'IEX',
role: 'ats_routing',
mic: null,
countryIso: 'US',
method: 'explicit_rule',
reviewedBy: null,
},
]);
});
test('trims, uppercases, and collapses duplicate source codes deterministically', () => {
const result = classifySourceExchanges([
{ source: 'ceo', code: ' tsx ' },
{ source: 'ceo', code: 'TSX' },
{ source: 'eod', code: ' to ', operatingMic: ' xtse ' },
{ source: 'eod', code: 'TO', operatingMic: 'XTSE' },
{ source: 'eod', code: 'to', operatingMic: null },
]);
expect(result.unresolved).toEqual([]);
expect(result.mapped).toEqual([
{
source: 'ceo',
sourceCode: 'TSX',
role: 'primary_venue',
mic: 'XTSE',
countryIso: 'CA',
method: 'explicit_rule',
reviewedBy: null,
},
{
source: 'eod',
sourceCode: 'TO',
role: 'primary_venue',
mic: 'XTSE',
countryIso: 'CA',
method: 'operating_mic',
reviewedBy: null,
},
]);
});
test('resolves valid single OperatingMIC to primary_venue with exchange countryIso', () => {
const result = classifySourceExchanges([
{ source: 'eod', code: 'NASDAQ', operatingMic: 'xnas', country: 'USA' },
{ source: 'qm', code: 'TSV', operatingMic: 'XTSX', country: 'Canada' },
]);
expect(result.unresolved).toEqual([]);
expect(result.mapped).toEqual([
{
source: 'eod',
sourceCode: 'NASDAQ',
role: 'primary_venue',
mic: 'XNAS',
countryIso: 'US',
method: 'operating_mic',
reviewedBy: null,
},
{
source: 'qm',
sourceCode: 'TSV',
role: 'primary_venue',
mic: 'XTSX',
countryIso: 'CA',
method: 'operating_mic',
reviewedBy: null,
},
]);
});
test('routes empty codes, missing/unknown/malformed/multi-valued/conflicting MICs to unresolved without guessing', () => {
const result = classifySourceExchanges([
{ source: 'eod', code: ' ', name: 'Blank' },
{ source: 'qm', code: 'MYSTERY', name: 'No MIC' },
{ source: 'eod', code: 'LSE', operatingMic: 'XLON', country: 'GB' },
{ source: 'eod', code: 'BADFMT', operatingMic: 'XN-Y' },
{ source: 'eod', code: 'MULTI_COMMA', operatingMic: 'XNAS, XNYS' },
{ source: 'eod', code: 'MULTI_SEMI', operatingMic: 'XNYS;XNAS' },
{ source: 'eod', code: 'MULTI_SPACE', operatingMic: 'XNAS XNYS' },
{ source: 'eod', code: 'MULTI_SLASH', operatingMic: 'XNAS/XNYS' },
{ source: 'eod', code: 'MULTI_PIPE', operatingMic: 'XNAS|XNYS' },
{ source: 'ib', code: 'CONFLICT', operatingMic: 'XNYS' },
{ source: 'ib', code: 'conflict', operatingMic: 'XNAS' },
]);
expect(result.mapped).toEqual([]);
expect(result.unresolved.map(row => [row.source, row.sourceCode, row.reason])).toEqual([
['eod', '', 'empty_code'],
['eod', 'BADFMT', 'invalid_operating_mic_format'],
['eod', 'LSE', 'unknown_operating_mic'],
['eod', 'MULTI_COMMA', 'multi_valued_operating_mic'],
['eod', 'MULTI_PIPE', 'multi_valued_operating_mic'],
['eod', 'MULTI_SEMI', 'multi_valued_operating_mic'],
['eod', 'MULTI_SLASH', 'multi_valued_operating_mic'],
['eod', 'MULTI_SPACE', 'multi_valued_operating_mic'],
['ib', 'CONFLICT', 'multi_valued_operating_mic'],
['qm', 'MYSTERY', 'missing_operating_mic'],
]);
});
test('throws an error naming both source and code on unknown source', () => {
expect(() =>
classifySourceExchanges([
{ source: 'yahoo' as unknown as ExchangeSource, code: 'NYSE', operatingMic: 'XNYS' },
])
).toThrow(/yahoo.*NYSE/);
});
test('normalizes observed raw MongoDB field spellings across all four provider collections', () => {
expect(
normalizeRawExchangeDoc('eod', {
Code: 'TO',
Name: 'Toronto Exchange',
CountryISO2: 'CA',
OperatingMIC: 'XTSE',
Currency: 'CAD',
})
).toEqual({
source: 'eod',
code: 'TO',
name: 'Toronto Exchange',
country: 'CA',
operatingMic: 'XTSE',
currency: 'CAD',
});
expect(
normalizeRawExchangeDoc('ib', {
id: 'DRCTEDGE',
description: 'Direct Edge',
country_code: 'US',
})
).toEqual({
source: 'ib',
code: 'DRCTEDGE',
name: 'Direct Edge',
country: 'US',
operatingMic: null,
currency: null,
});
expect(
normalizeRawExchangeDoc('ib', {
exchange_id: 'AEQLIT',
name: 'Aequitas NEO',
countryCode: 'CA',
})
).toEqual({
source: 'ib',
code: 'AEQLIT',
name: 'Aequitas NEO',
country: 'CA',
operatingMic: null,
currency: null,
});
expect(
normalizeRawExchangeDoc('qm', {
exchange: 'TSX',
exchangeName: 'Toronto Stock Exchange',
countryCode: 'CA',
OperatingMIC: 'XTSE',
})
).toEqual({
source: 'qm',
code: 'TSX',
name: 'Toronto Stock Exchange',
country: 'CA',
operatingMic: 'XTSE',
currency: null,
});
expect(
normalizeRawExchangeDoc('qm', {
exchangeCode: 'NGS',
exchangeShortName: 'NASDAQ',
country_code: 'US',
})
).toEqual({
source: 'qm',
code: 'NGS',
name: 'NASDAQ',
country: 'US',
operatingMic: null,
currency: null,
});
expect(
normalizeRawExchangeDoc('ceo', {
exchange: 'CDX',
name: 'TSX Venture',
country: 'CA',
})
).toEqual({
source: 'ceo',
code: 'CDX',
name: 'TSX Venture',
country: 'CA',
operatingMic: null,
currency: null,
});
});
});
describe('security master Pass 1 SQL and Markdown generator', () => {
test('escapes single quotes and rejects NUL bytes in SQL literals', () => {
expect(escapeSqlLiteral(null)).toBe('NULL');
expect(escapeSqlLiteral(undefined)).toBe('NULL');
expect(escapeSqlLiteral("O'Hare's Exchange")).toBe("'O''Hare''s Exchange'");
expect(() => escapeSqlLiteral('BAD\0VALUE')).toThrow(/NUL/);
});
test('produces byte-identical SQL and Markdown for shuffled inputs sorted by mic and (source, source_code)', () => {
const recordsA: SourceExchangeRecord[] = [
{ source: 'ib', code: 'PSX' },
{ source: 'ceo', code: 'TSX' },
{ source: 'eod', code: 'TO', operatingMic: 'XTSE' },
{ source: 'eod', code: 'US' },
{ source: 'qm', code: 'UNK_B', name: 'Pipe | Name\nLine2' },
{ source: 'eod', code: 'UNK_A', operatingMic: 'XLON' },
];
const recordsB: SourceExchangeRecord[] = [
recordsA[5]!,
recordsA[2]!,
recordsA[0]!,
recordsA[4]!,
recordsA[3]!,
recordsA[1]!,
];
const resA = classifySourceExchanges(recordsA);
const resB = classifySourceExchanges(recordsB);
const sqlA = generateExchangeSeedSql({
exchanges: ISO_EXCHANGE_SEEDS,
mappings: resA.mapped,
});
const sqlB = generateExchangeSeedSql({
exchanges: [...ISO_EXCHANGE_SEEDS].reverse(),
mappings: [...resB.mapped].reverse(),
});
expect(sqlA).toBe(sqlB);
expect(sqlA.indexOf("('ceo', 'TSX'")).toBeLessThan(sqlA.indexOf("('eod', 'TO'"));
expect(sqlA.indexOf("('eod', 'TO'")).toBeLessThan(sqlA.indexOf("('eod', 'US'"));
expect(sqlA.indexOf("('eod', 'US'")).toBeLessThan(sqlA.indexOf("('ib', 'PSX'"));
const mdA = generateUnresolvedExchangesMarkdown(resA);
const mdB = generateUnresolvedExchangesMarkdown(resB);
expect(mdA).toBe(mdB);
expect(mdA).toContain('Pipe \\| Name Line2');
});
test('escapes single quotes in generated SQL values', () => {
const sql = generateExchangeSeedSql({
exchanges: [
{
mic: 'XTST',
operatingMic: 'XTST',
name: "O'Connor's Venue",
countryIso: 'US',
currency: 'USD',
timezone: 'America/New_York',
calendarCode: 'XNYS',
boardLotPolicy: 'us_100',
},
],
mappings: [],
});
expect(sql).toContain("'O''Connor''s Venue'");
});
test('generated SQL for baseline seeds matches committed 35-security-master-exchange-seed.sql byte-for-byte', () => {
const generated = generateExchangeSeedSql({
exchanges: ISO_EXCHANGE_SEEDS,
mappings: EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS,
});
const committed = readFileSync(committedSeedPath, 'utf8');
expect(generated).toBe(committed);
});
});
describe('security master Pass 1 read-only MongoDB generator wrapper', () => {
test('only calls isReadOnly and find on the four exchange collections and fails loudly on write methods', async () => {
const dir = mkdtempSync(join(tmpdir(), 'pass1-seed-gen-'));
tempDirs.push(dir);
const sqlOutPath = join(dir, 'out', 'seed.sql');
const reportOutPath = join(dir, 'out', 'unresolved.md');
const fixtures: Record<string, Record<string, unknown>[]> = {
[SOURCE_EXCHANGE_COLLECTIONS.eod]: [
{ Code: 'US', Name: 'USA Stocks', CountryISO2: 'US', OperatingMIC: 'XNAS, XNYS' },
{ Code: 'TO', Name: 'Toronto', CountryISO2: 'CA', OperatingMIC: 'XTSE' },
{ Code: 'LSE', Name: 'London', CountryISO2: 'GB', OperatingMIC: 'XLON' },
],
[SOURCE_EXCHANGE_COLLECTIONS.ib]: [
{ id: 'IEX', name: 'IEX Routing', country_code: 'US' },
],
[SOURCE_EXCHANGE_COLLECTIONS.qm]: [
{ exchange: 'NGS', exchangeName: 'NASDAQ Global Select', OperatingMIC: 'XNAS' },
],
[SOURCE_EXCHANGE_COLLECTIONS.ceo]: [
{ exchange: 'TSX', name: 'Toronto Stock Exchange', country: 'CA' },
],
};
const calls: Array<{ method: string; collection?: string }> = [];
const readOnlyFake = new Proxy(
{},
{
get(_target, prop) {
if (prop === 'isReadOnly') {
return () => {
calls.push({ method: 'isReadOnly' });
return true;
};
}
if (prop === 'find') {
return async (collectionName: string, filter?: Record<string, unknown>) => {
expect(filter).toEqual({});
calls.push({ method: 'find', collection: collectionName });
return fixtures[collectionName] ?? [];
};
}
return () => {
throw new Error(`Forbidden MongoDB method invoked: ${String(prop)}`);
};
},
}
) as ReadOnlyExchangeMongoClient & { insertOne: () => void };
expect(() => readOnlyFake.insertOne()).toThrow(/Forbidden MongoDB method invoked: insertOne/);
const output = await generateExchangeSeedFromMongo(readOnlyFake, {
sqlOutPath,
reportOutPath,
});
expect(calls).toEqual([
{ method: 'isReadOnly' },
{ method: 'find', collection: 'eodExchanges' },
{ method: 'find', collection: 'ibExchanges' },
{ method: 'find', collection: 'qmExchanges' },
{ method: 'find', collection: 'ceoExchanges' },
]);
expect(output.countsByCollection).toEqual({ eod: 3, ib: 1, qm: 1, ceo: 1 });
expect(output.classification.mapped).toHaveLength(5);
expect(output.classification.unresolved).toHaveLength(1);
expect(output.classification.unresolved[0]?.sourceCode).toBe('LSE');
expect(readFileSync(sqlOutPath, 'utf8')).toBe(output.sql);
expect(readFileSync(reportOutPath, 'utf8')).toBe(output.reportMarkdown);
});
test('rejects a non-read-only MongoDB client before calling find', async () => {
const dir = mkdtempSync(join(tmpdir(), 'pass1-seed-nonro-'));
tempDirs.push(dir);
let findCalled = false;
const nonReadOnlyFake: ReadOnlyExchangeMongoClient = {
isReadOnly: () => false,
find: async () => {
findCalled = true;
return [];
},
};
await expect(
generateExchangeSeedFromMongo(nonReadOnlyFake, {
sqlOutPath: join(dir, 'seed.sql'),
reportOutPath: join(dir, 'report.md'),
})
).rejects.toThrow(/read-only/i);
expect(findCalled).toBe(false);
});
test('parses CLI arguments and resolves read-only MongoDB config from readUri', () => {
expect(parseGenerateExchangeSeedArgs([])).toEqual({
sqlOutPath: './tmp/35-security-master-exchange-seed.generated.sql',
reportOutPath: './tmp/pass1-unresolved-exchanges.md',
});
expect(
parseGenerateExchangeSeedArgs(['--sql-out', '/tmp/a.sql', '--report-out=/tmp/b.md'])
).toEqual({
sqlOutPath: '/tmp/a.sql',
reportOutPath: '/tmp/b.md',
});
expect(() => parseGenerateExchangeSeedArgs(['--unknown'])).toThrow(/Unknown argument/);
expect(() => parseGenerateExchangeSeedArgs(['--sql-out'])).toThrow(/Missing value/);
const resolved = resolveReadOnlyMongoClientConfig({
database: {
mongodb: {
enabled: true,
host: 'localhost',
port: 27018,
database: 'stock_dev',
uri: 'mongodb://localhost:27018/stock_dev',
readUri: 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock',
readOnly: false,
poolSize: 10,
},
postgres: {} as never,
questdb: {} as never,
dragonfly: {} as never,
},
});
expect(resolved.readOnly).toBe(true);
expect(resolved.uri).toBe(
'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock'
);
expect(resolved.database).toBe('stock');
});
});