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';