Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : server/next/dataLayer.ts9 * Module : server10 * Repository : https://git.spboucher.ai/vquant11 * Project Website : https://vquant.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier : MIT34 * License : MIT License35 * License File : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Data layer of VQuant Next (contract: docs/next/CONTRACT.md §3) — price bars and quotes with provenance.47 *48 * GET /api/v2/data/bars/:symbol?interval=1d&from=&to=&adjust=split_div|split|none&limit=49 * GET /api/v2/data/quotes?symbols=A,B50 *51 * Owner rules built in here:52 * - FMP first (it is faster); FinData only when FMP fails or has nothing. A series comes from ONE provider:53 * when FMP cannot serve it the whole series is asked again from FinData (`fallbackFrom: "fmp"`), never patched.54 * - Nothing is called "live": a quote fetched on request is `polled` and carries the provider's own timestamp.55 * - FMP answers at most 5 000 rows per request: long histories are paged backwards.56 * - FinData names crypto by base asset (BTC, not BTCUSD) and its catalogue covers US stocks and ETFs.57 *58 * This file also holds what the sibling modules (statements, market, health) share: the instrumented provider59 * client (timeouts, sanitized errors, per-provider counters), the TTL/LRU cache and the single-flight helper.60 */61import type { Express, Request, Response } from "express";62import { redactSecrets } from "../services/python/lab";63import { logger } from "../utils/logger";6465// ═══ Providers ═══════════════════════════════════════════════════════════════6667export type ProviderId = "fmp" | "findata" | "eodhd";68export type ProviderErrorKind = "not_configured" | "plan" | "not_found" | "rate_limit" | "timeout" | "network" | "upstream" | "bad_response";6970export class ProviderError extends Error {71 constructor(72 public provider: ProviderId,73 public kind: ProviderErrorKind,74 message: string,75 public status?: number,76 ) {77 super(message);78 }79}8081const PROVIDER_NAMES: Record<ProviderId, string> = { fmp: "FMP", findata: "FinData", eodhd: "EODHD" };8283const env = (name: string): string => (process.env[name] ?? "").trim();84const findataBase = () => (env("FINDATA_URL") || "https://findata.spboucher.ai").replace(/\/+$/, "") + "/api/v1";8586export function providerConfigured(p: ProviderId): boolean {87 return p === "fmp" ? env("FMP_API_KEY") !== "" : p === "findata" ? env("FINDATA_API_KEY") !== "" : env("EODHD_API_KEY") !== "";88}8990interface ProviderCounters {91 calls: number;92 errors: number;93 lastError: string | null;94 lastErrorAt: number | null;95 lastOkAt: number | null;96 lastLatencyMs: number | null;97}98const counters: Record<ProviderId, ProviderCounters> = {99 fmp: { calls: 0, errors: 0, lastError: null, lastErrorAt: null, lastOkAt: null, lastLatencyMs: null },100 findata: { calls: 0, errors: 0, lastError: null, lastErrorAt: null, lastOkAt: null, lastLatencyMs: null },101 eodhd: { calls: 0, errors: 0, lastError: null, lastErrorAt: null, lastOkAt: null, lastLatencyMs: null },102};103104/** Calls and errors of this layer since the process started (health route). */105export function providerStats(): Record<ProviderId, ProviderCounters> {106 return { fmp: { ...counters.fmp }, findata: { ...counters.findata }, eodhd: { ...counters.eodhd } };107}108109/** A provider message that can be shown: no key, no URL with a key, bounded. */110export function sanitizeProviderMessage(text: unknown): string {111 return redactSecrets(String(text ?? ""))112 .replace(/https?:\/\/\S+/g, "[url]")113 .replace(/\s+/g, " ")114 .trim()115 .slice(0, 240);116}117118export interface ProviderRequest {119 params?: Record<string, string | number | boolean | undefined | null>;120 method?: "GET" | "POST";121 body?: unknown;122 timeoutMs?: number;123 /** false for health probes: they must not move the call/error counters they report. */124 track?: boolean;125}126127const DEFAULT_TIMEOUT_MS: Record<ProviderId, number> = { fmp: 15_000, findata: 25_000, eodhd: 15_000 };128129/** What a provider says in an error body, whatever shape it uses. */130function bodyMessage(body: unknown): string {131 if (typeof body === "string") return body;132 if (!body || typeof body !== "object") return "";133 const b = body as Record<string, unknown>;134 const nested = b.error && typeof b.error === "object" ? (b.error as Record<string, unknown>) : null;135 for (const v of [b["Error Message"], nested?.message, b.error, b.message]) if (typeof v === "string" && v.trim() !== "") return v;136 return "";137}138139/**140 * One JSON request to a provider: key added here and nowhere else, timeout enforced, failures classified141 * (plan refusal, not found, rate limit, timeout…) with a message that never contains the key or the URL.142 */143export async function providerJson<T = unknown>(provider: ProviderId, path: string, req: ProviderRequest = {}): Promise<T> {144 const name = PROVIDER_NAMES[provider];145 if (!providerConfigured(provider)) throw new ProviderError(provider, "not_configured", `${name} is not configured on this server.`);146 const base = provider === "fmp" ? "https://financialmodelingprep.com/stable" : provider === "findata" ? findataBase() : "https://eodhd.com/api";147 const url = new URL(base + path);148 for (const [k, v] of Object.entries(req.params ?? {})) if (v !== undefined && v !== null && v !== "") url.searchParams.set(k, String(v));149 const headers: Record<string, string> = { Accept: "application/json" };150 if (provider === "fmp") url.searchParams.set("apikey", env("FMP_API_KEY"));151 else if (provider === "eodhd") {152 url.searchParams.set("api_token", env("EODHD_API_KEY"));153 url.searchParams.set("fmt", "json");154 } else headers.Authorization = `Bearer ${env("FINDATA_API_KEY")}`;155 if (req.body !== undefined) headers["Content-Type"] = "application/json";156157 const c = req.track === false ? { calls: 0, errors: 0, lastError: null as string | null, lastErrorAt: null as number | null, lastOkAt: null as number | null, lastLatencyMs: null as number | null } : counters[provider];158 c.calls++;159 const started = Date.now();160 const fail = (kind: ProviderErrorKind, message: string, status?: number): ProviderError => {161 c.errors++;162 c.lastError = sanitizeProviderMessage(message);163 c.lastErrorAt = Date.now();164 c.lastLatencyMs = Date.now() - started;165 return new ProviderError(provider, kind, c.lastError, status);166 };167168 const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS[provider];169 let res: globalThis.Response;170 let text: string;171 try {172 res = await fetch(url, { method: req.method ?? "GET", headers, body: req.body === undefined ? undefined : JSON.stringify(req.body), signal: AbortSignal.timeout(timeoutMs) });173 text = await res.text();174 } catch (e) {175 const err = e as Error & { cause?: { code?: string } };176 if (err.name === "TimeoutError" || err.name === "AbortError") throw fail("timeout", `${name} did not answer within ${Math.round(timeoutMs / 100) / 10} s (${path}).`);177 throw fail("network", `${name} is unreachable (${err.cause?.code ?? err.name ?? "network error"}).`);178 }179 let body: unknown = text;180 try {181 body = JSON.parse(text);182 } catch {183 /* some refusals are plain text ("Forbidden") */184 }185 const said = bodyMessage(body).slice(0, 200);186 if (!res.ok) {187 const s = res.status;188 if (s === 402 || s === 403 || (s === 401 && /plan|subscri|premium|upgrade/i.test(said))) throw fail("plan", `${name}: not included in the current plan (${s}) for ${path}${said ? ` — ${said}` : ""}`, s);189 if (s === 401) throw fail("not_configured", `${name} refused the key (401).`, s);190 if (s === 404) throw fail("not_found", `${name} has nothing at ${path} for these parameters (404).`, s);191 if (s === 429) throw fail("rate_limit", `${name} rate limit reached (429).`, s);192 throw fail("upstream", `${name} ${path} failed (${s})${said ? `: ${said}` : ""}`, s);193 }194 if (typeof body === "string") throw fail("bad_response", `${name} ${path} did not answer with JSON.`);195 // FMP reports some refusals with a 200 and an "Error Message".196 if (provider === "fmp" && body && typeof body === "object" && !Array.isArray(body) && typeof (body as Record<string, unknown>)["Error Message"] === "string") {197 const msg = String((body as Record<string, unknown>)["Error Message"]);198 throw fail(/plan|subscri|premium|upgrade|exclusive|special endpoint/i.test(msg) ? "plan" : "upstream", `${name} ${path}: ${msg}`);199 }200 c.lastOkAt = Date.now();201 c.lastLatencyMs = Date.now() - started;202 return body as T;203}204205// ═══ Cache and single-flight ═════════════════════════════════════════════════206207/** Small in-memory cache: entries expire after their own TTL and the least recently used is evicted when full. */208export class TtlCache<V> {209 private map = new Map<string, { value: V; expires: number }>();210 constructor(211 private maxEntries: number,212 private now: () => number = () => Date.now(),213 ) {}214215 get(key: string): V | undefined {216 const e = this.map.get(key);217 if (!e) return undefined;218 if (e.expires <= this.now()) {219 this.map.delete(key);220 return undefined;221 }222 // Re-inserted: a Map iterates in insertion order, so the first key is always the least recently used.223 this.map.delete(key);224 this.map.set(key, e);225 return e.value;226 }227228 set(key: string, value: V, ttlMs: number): void {229 this.map.delete(key);230 this.map.set(key, { value, expires: this.now() + ttlMs });231 while (this.map.size > this.maxEntries) this.map.delete(this.map.keys().next().value as string);232 }233234 delete(key: string): void {235 this.map.delete(key);236 }237 clear(): void {238 this.map.clear();239 }240 get size(): number {241 return this.map.size;242 }243}244245/** Concurrent callers of the same key share one execution; nothing is remembered once it has settled. */246export class SingleFlight<V> {247 private flights = new Map<string, Promise<V>>();248 run(key: string, fn: () => Promise<V>): Promise<V> {249 const existing = this.flights.get(key);250 if (existing) return existing;251 const p = Promise.resolve()252 .then(fn)253 .finally(() => this.flights.delete(key));254 this.flights.set(key, p);255 return p;256 }257 get inFlight(): number {258 return this.flights.size;259 }260}261262/** Cached value, or one shared fetch for everybody who asks while it is being loaded. Failures are not cached. */263export function cachedFlight<V>(cache: TtlCache<V>, flights: SingleFlight<V>, key: string, ttlMs: number | ((v: V) => number), fn: () => Promise<V>): Promise<V> {264 const hit = cache.get(key);265 if (hit !== undefined) return Promise.resolve(hit);266 return flights.run(key, async () => {267 const v = await fn();268 cache.set(key, v, typeof ttlMs === "function" ? ttlMs(v) : ttlMs);269 return v;270 });271}272273// ═══ Time ════════════════════════════════════════════════════════════════════274275const DAY_MS = 86_400_000;276export const isoDay = (ms: number): string => new Date(ms).toISOString().slice(0, 10);277const dayMs = (iso: string): number => Date.parse(`${iso}T00:00:00Z`);278const addDays = (iso: string, n: number): string => isoDay(dayMs(iso) + n * DAY_MS);279280const zoneFormats = new Map<string, Intl.DateTimeFormat>();281function zoneParts(ms: number, timeZone: string): { y: number; mo: number; d: number; h: number; mi: number; s: number; weekday: number } {282 let f = zoneFormats.get(timeZone);283 if (!f) {284 f = new Intl.DateTimeFormat("en-US", { timeZone, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", weekday: "short" });285 zoneFormats.set(timeZone, f);286 }287 const p: Record<string, string> = {};288 for (const part of f.formatToParts(new Date(ms))) p[part.type] = part.value;289 return { y: +p.year, mo: +p.month, d: +p.day, h: +p.hour % 24, mi: +p.minute, s: +p.second, weekday: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].indexOf(p.weekday) };290}291292/** Calendar date (YYYY-MM-DD) at `ms` in a time zone. */293export function dateInZone(ms: number, timeZone: string): string {294 const p = zoneParts(ms, timeZone);295 return `${p.y}-${String(p.mo).padStart(2, "0")}-${String(p.d).padStart(2, "0")}`;296}297298/** Minutes after local midnight, and the weekday (0 = Sunday), at `ms` in a time zone. */299export function clockInZone(ms: number, timeZone: string): { minutes: number; weekday: number; date: string } {300 const p = zoneParts(ms, timeZone);301 return { minutes: p.h * 60 + p.mi, weekday: p.weekday, date: `${p.y}-${String(p.mo).padStart(2, "0")}-${String(p.d).padStart(2, "0")}` };302}303304const offsetCache = new Map<string, number>();305/**306 * Epoch seconds of a wall-clock time ("YYYY-MM-DD HH:MM:SS") in a time zone. The UTC offset is looked up once per307 * local date and half-day (daylight saving switches at night), so converting a long intraday series stays cheap.308 */309export function zonedToEpochSec(local: string, timeZone: string): number {310 const m = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?/.exec(local);311 if (!m) return NaN;312 const asUtc = Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +(m[6] ?? 0));313 const key = `${timeZone}|${m[1]}${m[2]}${m[3]}|${+m[4] < 4 ? "n" : "d"}`;314 let offset = offsetCache.get(key);315 if (offset === undefined) {316 const at = (guess: number) => {317 const p = zoneParts(guess, timeZone);318 return Date.UTC(p.y, p.mo - 1, p.d, p.h, p.mi, p.s) - guess;319 };320 offset = at(asUtc - at(asUtc)); // second pass: the first guess can sit on the other side of a switch321 if (offsetCache.size > 20_000) offsetCache.clear();322 offsetCache.set(key, offset);323 }324 return Math.round((asUtc - offset) / 1000);325}326327// ═══ Freshness ═══════════════════════════════════════════════════════════════328329export type FreshnessKind = "polled" | "delayed" | "eod" | "historical" | "estimated";330export interface Freshness {331 kind: FreshnessKind;332 asOf: number | null;333 provider: string;334 retrievedAt: number;335 note: string | null;336}337338/**339 * Freshness of a quote. `polled` means: fetched from the provider on this request and stamped with the provider's340 * own time — it says nothing about how old that time is, so an old stamp gets a note (market closed, illiquid…).341 * EODHD's "real-time" endpoint is a delayed feed (15–20 min) and is labelled `delayed`. Nothing is ever "live".342 */343export function classifyQuoteFreshness(provider: ProviderId, providerTimestampMs: number | null, nowMs: number): Freshness {344 const kind: FreshnessKind = provider === "eodhd" ? "delayed" : provider === "findata" ? "eod" : "polled";345 let note: string | null = provider === "eodhd" ? "Delayed quote (about 15–20 minutes)." : null;346 if (providerTimestampMs === null) note = "The provider gave no timestamp for this quote.";347 else {348 const ageMin = (nowMs - providerTimestampMs) / 60_000;349 if (ageMin > 20) {350 const age = ageMin < 120 ? `${Math.round(ageMin)} min` : ageMin < 48 * 60 ? `${Math.round(ageMin / 60)} h` : `${Math.round(ageMin / 1440)} days`;351 note = `Last trade reported ${age} ago (market closed or no recent trade).`;352 }353 }354 return { kind, asOf: providerTimestampMs, provider, retrievedAt: nowMs, note };355}356357export const INTERVALS = ["1m", "5m", "15m", "30m", "1h", "4h", "1d"] as const;358export type Interval = (typeof INTERVALS)[number];359export const INTERVAL_SECONDS: Record<Interval, number> = { "1m": 60, "5m": 300, "15m": 900, "30m": 1800, "1h": 3600, "4h": 14_400, "1d": 86_400 };360361/**362 * Freshness of a series from its last bar.363 * daily — last bar is today's session and the market is open → `polled` (the bar is still forming);364 * last bar within 4 days → `eod`; older → `historical`.365 * intraday — last bar ended less than max(2 bars, 20 min) ago → `polled`; within 4 days → `eod`; older → `historical`.366 * FinData is loaded after each session: its series are never `polled`.367 */368export function classifyBarsFreshness(a: { interval: Interval; lastBarSec: number | null; nowMs: number; provider: ProviderId; sessionOpen: boolean | null; todayInZone: string }): Freshness {369 const base = { provider: a.provider, retrievedAt: a.nowMs };370 if (a.lastBarSec === null) return { ...base, kind: "historical", asOf: null, note: "No bar in the requested range." };371 const lastMs = a.lastBarSec * 1000;372 if (a.interval === "1d") {373 const lastDate = isoDay(lastMs);374 if (lastDate >= a.todayInZone && a.provider !== "findata") {375 if (a.sessionOpen === true) return { ...base, kind: "polled", asOf: lastMs, note: "Today's bar is still forming: its values are the session so far." };376 return { ...base, kind: "eod", asOf: lastMs, note: null };377 }378 const ageDays = (dayMs(a.todayInZone) - dayMs(lastDate)) / DAY_MS;379 return { ...base, kind: ageDays <= 4 ? "eod" : "historical", asOf: lastMs, note: a.provider === "findata" && ageDays <= 4 ? "FinData is loaded after each session: today's bar is not there yet." : null };380 }381 const endMs = lastMs + INTERVAL_SECONDS[a.interval] * 1000;382 const ageMs = a.nowMs - endMs;383 if (a.provider !== "findata" && ageMs < Math.max(2 * INTERVAL_SECONDS[a.interval] * 1000, 20 * 60_000)) return { ...base, kind: "polled", asOf: endMs, note: "The last bar may still be forming." };384 return { ...base, kind: ageMs <= 4 * DAY_MS ? "eod" : "historical", asOf: endMs, note: null };385}386387// ═══ Symbols ═════════════════════════════════════════════════════════════════388389export class DataParamError extends Error {}390391const SYMBOL_RE = /^[A-Z0-9^][A-Z0-9.\-=^]{0,19}$/;392export function parseSymbol(v: unknown): string {393 const s = String(v ?? "").trim().toUpperCase();394 if (!SYMBOL_RE.test(s)) throw new DataParamError(`"${String(v ?? "").slice(0, 24)}" is not a ticker symbol.`);395 return s;396}397398export type AssetClass = "equity" | "etf" | "index" | "fx" | "crypto" | "commodity";399400const CURRENCIES = new Set("USD EUR JPY GBP CHF CAD AUD NZD SEK NOK DKK MXN ZAR SGD HKD CNY CNH INR BRL TRY PLN CZK HUF ILS KRW THB RUB ARS".split(" "));401const COMMODITY_ROOTS = new Set("GC SI CL BZ NG HG PL PA HO RB ZC ZS ZW KC SB CC CT LE HE OJ DX ES NQ YM RTY ZB ZN ZF ZT ZO ZL ZM ZR LB ALI MGC SIL".split(" "));402403/** Asset class from the shape of the symbol alone — used only when FMP's quote cannot tell. */404export function guessAssetClass(symbol: string): AssetClass {405 if (symbol.startsWith("^")) return "index";406 if (/^[A-Z]{6}$/.test(symbol) && CURRENCIES.has(symbol.slice(0, 3)) && CURRENCIES.has(symbol.slice(3))) return "fx";407 if (/^[A-Z0-9]{1,8}USD$/.test(symbol)) return COMMODITY_ROOTS.has(symbol.slice(0, -3)) ? "commodity" : "crypto";408 return "equity";409}410411export interface SymbolMeta {412 symbol: string;413 name: string | null;414 assetClass: AssetClass;415 exchange: string | null;416 currency: string | null;417 timezone: string | null;418 /** "fmp" when the provider described the instrument, "symbol" when only its shape was used. */419 source: "fmp" | "symbol";420}421422interface FmpQuote {423 symbol: string;424 name?: string;425 price?: number;426 change?: number;427 changePercentage?: number;428 volume?: number;429 dayLow?: number;430 dayHigh?: number;431 yearLow?: number;432 yearHigh?: number;433 marketCap?: number | null;434 exchange?: string;435 open?: number;436 previousClose?: number;437 timestamp?: number;438}439interface FmpProfile {440 symbol: string;441 currency?: string;442 exchange?: string;443 companyName?: string;444 isEtf?: boolean;445 isFund?: boolean;446}447448const classFromExchange = (exchange: string | undefined, symbol: string): AssetClass => {449 const x = (exchange ?? "").toUpperCase();450 if (x === "INDEX") return "index";451 if (x === "FOREX") return "fx";452 if (x === "CRYPTO") return "crypto";453 if (x === "COMMODITY") return "commodity";454 return x ? "equity" : guessAssetClass(symbol);455};456457/** Currency a price is quoted in when the symbol itself says it (pairs); null when only a profile can tell. */458function impliedCurrency(symbol: string, cls: AssetClass): string | null {459 if (cls === "fx" && symbol.length === 6) return symbol.slice(3);460 if ((cls === "crypto" || cls === "commodity") && /USD$/.test(symbol)) return "USD";461 return null;462}463464const hoursCache = new TtlCache<Map<string, { timezone: string; isOpen: boolean }>>(1);465const hoursFlight = new SingleFlight<Map<string, { timezone: string; isOpen: boolean }>>();466/** Exchange code → time zone and whether it is open now (FMP market hours; cached one minute). */467export function exchangeHours(): Promise<Map<string, { timezone: string; isOpen: boolean }>> {468 return cachedFlight(hoursCache, hoursFlight, "all", 60_000, async () => {469 const rows = await providerJson<{ exchange?: string; timezone?: string; isMarketOpen?: boolean }[]>("fmp", "/all-exchange-market-hours", { timeoutMs: 8_000 });470 const map = new Map<string, { timezone: string; isOpen: boolean }>();471 for (const r of Array.isArray(rows) ? rows : []) if (r.exchange && r.timezone) map.set(r.exchange.toUpperCase(), { timezone: r.timezone, isOpen: r.isMarketOpen === true });472 return map;473 });474}475476const profileCache = new TtlCache<FmpProfile | null>(2_000);477const profileFlight = new SingleFlight<FmpProfile | null>();478/** FMP profile of a listed security (currency, exchange), cached a day. null = FMP has none (index, pair…). */479function fmpProfile(symbol: string): Promise<FmpProfile | null> {480 return cachedFlight(profileCache, profileFlight, symbol, DAY_MS, async () => {481 const rows = await providerJson<FmpProfile[]>("fmp", "/profile", { params: { symbol }, timeoutMs: 8_000 });482 return Array.isArray(rows) && rows[0] ? rows[0] : null;483 });484}485486const metaCache = new TtlCache<SymbolMeta>(2_000);487const metaFlight = new SingleFlight<SymbolMeta>();488489/**490 * What the instrument is, where it trades and in which currency — from FMP's quote and profile when they answer,491 * from the shape of the symbol otherwise (then currency and time zone stay null unless the symbol implies them).492 */493export function resolveMeta(symbol: string, knownQuote?: FmpQuote): Promise<SymbolMeta> {494 return cachedFlight(495 metaCache,496 metaFlight,497 symbol,498 (m) => (m.source === "fmp" ? 6 * 3_600_000 : 120_000),499 async () => {500 let quote = knownQuote;501 if (!quote && providerConfigured("fmp")) {502 try {503 const rows = await providerJson<FmpQuote[]>("fmp", "/quote", { params: { symbol }, timeoutMs: 8_000 });504 quote = Array.isArray(rows) ? rows[0] : undefined;505 } catch {506 /* the shape of the symbol is used instead */507 }508 }509 const cls0 = classFromExchange(quote?.exchange, symbol);510 const meta: SymbolMeta = { symbol, name: quote?.name ?? null, assetClass: cls0, exchange: quote?.exchange ?? null, currency: impliedCurrency(symbol, cls0), timezone: cls0 === "fx" || cls0 === "crypto" ? "UTC" : null, source: quote ? "fmp" : "symbol" };511 if (cls0 === "equity" && providerConfigured("fmp")) {512 try {513 const p = await fmpProfile(symbol);514 if (p) {515 meta.currency = p.currency ?? null;516 meta.exchange = p.exchange ?? meta.exchange;517 meta.name = meta.name ?? p.companyName ?? null;518 if (p.isEtf || p.isFund) meta.assetClass = "etf";519 meta.source = "fmp";520 }521 } catch {522 /* currency stays unknown */523 }524 }525 if ((meta.assetClass === "equity" || meta.assetClass === "etf") && meta.exchange && providerConfigured("fmp")) {526 try {527 meta.timezone = (await exchangeHours()).get(meta.exchange.toUpperCase())?.timezone ?? null;528 } catch {529 /* unknown */530 }531 }532 // US indices have no profile; their sessions are New York's.533 if (meta.assetClass === "index" && US_INDICES.has(symbol)) meta.timezone = "America/New_York";534 return meta;535 },536 );537}538539const US_INDICES = new Set(["^GSPC", "^SPX", "^DJI", "^IXIC", "^NDX", "^RUT", "^VIX", "^NYA", "^W5000", "^OEX", "^MID", "^SP600", "^VXN", "^VVIX"]);540const US_EXCHANGES = new Set(["NASDAQ", "NYSE", "AMEX", "CBOE", "BATS", "ARCA", "OTC", "PNK"]);541542// ═══ Gap diagnostics ═════════════════════════════════════════════════════════543544export interface GapReport {545 missingSessions: number;546 /** First missing dates (at most 25), oldest first. */547 missingDates: string[];548 /** Bars dated on a day the calendar says is closed (weekend or holiday). */549 unexpectedSessions: number;550 /** First such dates (at most 25), oldest first. */551 unexpectedDates: string[];552 calendar: "exchange" | "weekdays" | "every_day" | "none";553 checkedFrom: string | null;554 checkedTo: string | null;555 note: string;556}557558export interface SessionCalendar {559 mode: "exchange" | "weekdays" | "every_day";560 /** Dates the exchange is closed (exchange mode). */561 holidays?: Set<string>;562 /** Years the holiday list covers; other years are checked against weekdays only. */563 coveredYears?: Set<number>;564 label?: string;565 /** Currency pairs open on Sunday evening: a bar dated on a weekend is then normal, not an anomaly. */566 weekendBarsExpected?: boolean;567}568569/**570 * Sessions missing from a daily series, between its first and its last bar (what lies before the first bar is571 * "not listed yet", not a gap). Expected sessions: every weekday that the exchange calendar does not close; when572 * no holiday list is available, every weekday — and the note says that holidays are then counted as missing.573 */574export function detectGaps(dates: string[], cal: SessionCalendar): GapReport {575 if (dates.length === 0) return { missingSessions: 0, missingDates: [], unexpectedSessions: 0, unexpectedDates: [], calendar: cal.mode, checkedFrom: null, checkedTo: null, note: "No bar to check." };576 const have = new Set(dates);577 const first = dates[0];578 const last = dates[dates.length - 1];579 const missing: string[] = [];580 const unexpected: string[] = [];581 const uncovered = new Set<number>();582 for (let t = dayMs(first); t <= dayMs(last); t += DAY_MS) {583 const d = isoDay(t);584 const dow = new Date(t).getUTCDay();585 let open = cal.mode === "every_day" || (dow !== 0 && dow !== 6);586 if (open && cal.mode === "exchange") {587 const year = +d.slice(0, 4);588 if (cal.coveredYears && !cal.coveredYears.has(year)) uncovered.add(year);589 else if (cal.holidays?.has(d)) open = false;590 }591 if (open && !have.has(d)) missing.push(d);592 else if (!open && have.has(d) && !(cal.weekendBarsExpected && (dow === 0 || dow === 6))) unexpected.push(d);593 }594 const label = cal.label ?? "exchange";595 let note: string;596 if (cal.mode === "exchange") {597 note = `Checked against the ${label} trading calendar (FMP holidays).`;598 if (uncovered.size > 0) {599 const years = [...uncovered].sort();600 note += ` No holiday list for ${years[0]}${years.length > 1 ? `–${years[years.length - 1]}` : ""}: those years are checked against weekdays, so their market holidays count as missing.`;601 }602 } else if (cal.mode === "weekdays") note = `Checked against weekdays only (${label}): market holidays count as missing sessions.`;603 else note = "Checked against every calendar day (this market trades continuously).";604 if (unexpected.length > 0) note += ` ${unexpected.length} bar(s) are dated on a day this calendar marks closed.`;605 if (missing.length === 0 && unexpected.length === 0) note += " No gap.";606 return { missingSessions: missing.length, missingDates: missing.slice(0, 25), unexpectedSessions: unexpected.length, unexpectedDates: unexpected.slice(0, 25), calendar: cal.mode, checkedFrom: first, checkedTo: last, note };607}608609const holidayCache = new TtlCache<{ holidays: Set<string>; coveredYears: Set<number> }>(200);610const holidayFlight = new SingleFlight<{ holidays: Set<string>; coveredYears: Set<number> }>();611612/** Closed days of an exchange between two years (FMP holidays-by-exchange), cached a day. */613export function exchangeHolidays(exchange: string, fromYear: number, toYear: number): Promise<{ holidays: Set<string>; coveredYears: Set<number> }> {614 return cachedFlight(holidayCache, holidayFlight, `${exchange}|${fromYear}|${toYear}`, DAY_MS, async () => {615 const rows = await providerJson<{ date?: string; isClosed?: boolean | null }[]>("fmp", "/holidays-by-exchange", { params: { exchange, from: `${fromYear}-01-01`, to: `${toYear}-12-31` }, timeoutMs: 8_000 });616 const holidays = new Set<string>();617 const coveredYears = new Set<number>();618 for (const r of Array.isArray(rows) ? rows : []) {619 if (!r.date || !/^\d{4}-\d{2}-\d{2}$/.test(r.date)) continue;620 coveredYears.add(+r.date.slice(0, 4));621 if (r.isClosed === true) holidays.add(r.date); // early closes come with isClosed null: they are sessions622 }623 return { holidays, coveredYears };624 });625}626627/** The calendar a daily series is checked against, with the reason when it is only weekdays. */628async function calendarFor(meta: SymbolMeta, firstDate: string, lastDate: string): Promise<SessionCalendar> {629 if (meta.assetClass === "crypto") return { mode: "every_day" };630 if (meta.assetClass === "fx") return { mode: "weekdays", label: "currency pairs have no exchange calendar", weekendBarsExpected: true };631 if (meta.assetClass === "commodity") return { mode: "weekdays", label: "no exchange calendar for this future" };632 let exchange: string | null = null;633 if (meta.assetClass === "index") exchange = US_INDICES.has(meta.symbol) ? "NYSE" : null;634 else if (meta.exchange) exchange = US_EXCHANGES.has(meta.exchange.toUpperCase()) ? "NYSE" : meta.exchange.toUpperCase();635 if (!exchange) return { mode: "weekdays", label: "the exchange of this instrument is not known" };636 try {637 const h = await exchangeHolidays(exchange, +firstDate.slice(0, 4), +lastDate.slice(0, 4));638 if (h.coveredYears.size === 0) return { mode: "weekdays", label: `FMP has no holiday list for ${exchange}` };639 return { mode: "exchange", holidays: h.holidays, coveredYears: h.coveredYears, label: exchange };640 } catch (e) {641 return { mode: "weekdays", label: `the ${exchange} holiday calendar could not be fetched: ${e instanceof ProviderError ? e.kind : "error"}` };642 }643}644645// ═══ Bars ════════════════════════════════════════════════════════════════════646647export const ADJUST_MODES = ["split_div", "split", "none"] as const;648export type AdjustMode = (typeof ADJUST_MODES)[number];649650export interface BarsQuery {651 symbol: string;652 interval: Interval;653 from: string;654 to: string;655 /** false when the caller gave no `from`: the default window of the interval is used. */656 explicitFrom: boolean;657 adjust: AdjustMode;658 limit: number;659}660661/** Bar: [epoch seconds of the bar's start, open, high, low, close, volume|null]. A daily bar is stamped 00:00 UTC of its session date. */662export type Bar = [number, number, number, number, number, number | null];663664const DEFAULT_WINDOW_DAYS: Record<Interval, number> = { "1m": 5, "5m": 10, "15m": 30, "30m": 60, "1h": 120, "4h": 365, "1d": 365 };665export const MAX_BARS = 50_000;666const DEFAULT_LIMIT = 5_000;667const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;668669function parseDate(v: unknown, name: string): string | undefined {670 if (v === undefined || v === null || v === "") return undefined;671 const s = String(v).trim();672 if (!ISO_DATE.test(s) || Number.isNaN(dayMs(s)) || isoDay(dayMs(s)) !== s) throw new DataParamError(`${name} must be a date YYYY-MM-DD.`);673 return s;674}675676/** Validated bars request (throws DataParamError with a sentence for a 400). */677export function parseBarsQuery(symbol: unknown, q: Record<string, unknown>, nowMs = Date.now()): BarsQuery {678 const sym = parseSymbol(symbol);679 const interval = String(q.interval ?? "1d").trim() as Interval;680 if (!INTERVALS.includes(interval)) throw new DataParamError(`interval must be one of ${INTERVALS.join(", ")}.`);681 const adjust = String(q.adjust ?? "split_div").trim() as AdjustMode;682 if (!ADJUST_MODES.includes(adjust)) throw new DataParamError(`adjust must be one of ${ADJUST_MODES.join(", ")}.`);683 const today = isoDay(nowMs);684 let to = parseDate(q.to, "to") ?? today;685 // "Tomorrow" is tolerated (a client east of UTC); anything later is today's data anyway.686 if (to > addDays(today, 1)) to = addDays(today, 1);687 const givenFrom = parseDate(q.from, "from");688 const from = givenFrom ?? addDays(to, -DEFAULT_WINDOW_DAYS[interval]);689 if (from > to) throw new DataParamError("from is after to.");690 if (from < "1900-01-01") throw new DataParamError("from is too far in the past.");691 let limit = DEFAULT_LIMIT;692 if (q.limit !== undefined && q.limit !== null && q.limit !== "") {693 const n = Number(q.limit);694 if (!Number.isInteger(n) || n < 1 || n > MAX_BARS) throw new DataParamError(`limit must be an integer between 1 and ${MAX_BARS}.`);695 limit = n;696 }697 return { symbol: sym, interval, from, to, explicitFrom: givenFrom !== undefined, adjust, limit };698}699700interface RawSeries {701 provider: ProviderId;702 bars: Bar[];703 /** The adjustment the series really has (intraday bars are never dividend-adjusted, pairs are never adjusted…). */704 adjust: AdjustMode;705 notes: string[];706 currency?: string | null;707}708709const finiteNum = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);710function toBar(t: number, o: unknown, h: unknown, l: unknown, c: unknown, v: unknown): Bar | null {711 if (!Number.isFinite(t) || !finiteNum(o) || !finiteNum(h) || !finiteNum(l) || !finiteNum(c)) return null;712 return [t, o, h, l, c, finiteNum(v) ? v : null];713}714715// ─── FMP ─────────────────────────────────────────────────────────────────────716717const FMP_PAGE_ROWS = 5_000;718const FMP_MAX_PAGES = 12;719const FMP_DAILY_PATH: Record<AdjustMode, string> = {720 split: "/historical-price-eod/full", // split-adjusted, dividends not reinvested721 split_div: "/historical-price-eod/dividend-adjusted",722 none: "/historical-price-eod/non-split-adjusted",723};724const FMP_INTRADAY: Record<Exclude<Interval, "1d">, string> = { "1m": "1min", "5m": "5min", "15m": "15min", "30m": "30min", "1h": "1hour", "4h": "4hour" };725/** FMP stamps intraday bars in New York time for every asset class (observed for US and Toronto stocks, indices, FX, crypto). */726const FMP_INTRADAY_ZONE = "America/New_York";727728type FmpRow = Record<string, unknown>;729730async function fmpDaily(q: BarsQuery, cls: AssetClass): Promise<RawSeries> {731 // Pairs, indices and futures have no corporate actions: one endpoint serves them, whatever was asked.732 const adjustable = cls === "equity" || cls === "etf";733 const path = adjustable ? FMP_DAILY_PATH[q.adjust] : FMP_DAILY_PATH.split;734 const notes: string[] = [];735 const byDate = new Map<string, Bar>();736 let to = q.to;737 for (let page = 0; page < FMP_MAX_PAGES; page++) {738 const rows = await providerJson<FmpRow[]>("fmp", path, { params: { symbol: q.symbol, from: q.from, to } });739 if (!Array.isArray(rows) || rows.length === 0) break;740 let oldest = to;741 for (const r of rows) {742 const d = String(r.date ?? "").slice(0, 10);743 if (!ISO_DATE.test(d)) continue;744 const b = "adjClose" in r ? toBar(dayMs(d) / 1000, r.adjOpen, r.adjHigh, r.adjLow, r.adjClose, r.volume) : toBar(dayMs(d) / 1000, r.open, r.high, r.low, r.close, r.volume);745 if (b) byDate.set(d, b);746 if (d < oldest) oldest = d;747 }748 // A full page means the range was cut at the provider's cap: continue from the day before the oldest row.749 if (rows.length < FMP_PAGE_ROWS || oldest <= q.from || byDate.size >= q.limit) break;750 to = addDays(oldest, -1);751 if (page === FMP_MAX_PAGES - 1) notes.push("The history was cut at the paging limit of this route.");752 }753 if (!adjustable && q.adjust !== "none") notes.push("This instrument has no splits or dividends: prices are as quoted.");754 return { provider: "fmp", bars: [...byDate.values()], adjust: adjustable ? q.adjust : "none", notes };755}756757async function fmpIntraday(q: BarsQuery, cls: AssetClass): Promise<RawSeries> {758 const tf = FMP_INTRADAY[q.interval as Exclude<Interval, "1d">];759 const adjustable = cls === "equity" || cls === "etf";760 const notes: string[] = [];761 const byTime = new Map<number, Bar>();762 let to = q.to;763 for (let page = 0; page < FMP_MAX_PAGES; page++) {764 const rows = await providerJson<FmpRow[]>("fmp", `/historical-chart/${tf}`, { params: { symbol: q.symbol, from: q.from, to, nonadjusted: adjustable && q.adjust === "none" ? "true" : undefined } });765 if (!Array.isArray(rows) || rows.length === 0) break;766 const before = byTime.size;767 let oldest = to;768 for (const r of rows) {769 const stamp = String(r.date ?? "");770 const b = toBar(zonedToEpochSec(stamp, FMP_INTRADAY_ZONE), r.open, r.high, r.low, r.close, r.volume);771 if (!b) continue;772 byTime.set(b[0], b);773 if (stamp.slice(0, 10) < oldest) oldest = stamp.slice(0, 10);774 }775 // FMP returns the most recent bars of the window, up to its own cap: ask again ending on the oldest day776 // received until the start is reached, enough bars are held, or a page brings nothing new.777 if (oldest <= q.from || byTime.size >= q.limit) break;778 if (byTime.size === before) {779 notes.push("The provider returned no earlier bars: the series starts later than requested.");780 break;781 }782 to = oldest;783 if (page === FMP_MAX_PAGES - 1) notes.push("The series was cut at the paging limit of this route: narrow the range or use a coarser interval.");784 }785 let adjust: AdjustMode = "none";786 if (adjustable) {787 adjust = q.adjust === "none" ? "none" : "split";788 if (q.adjust === "split_div") notes.push("Intraday bars are split-adjusted only: FMP does not reinvest dividends intraday.");789 }790 notes.push("Regular trading session only for stocks and ETFs.");791 return { provider: "fmp", bars: [...byTime.values()], adjust, notes };792}793794// ─── FinData ─────────────────────────────────────────────────────────────────795796/** FMP index symbols FinData knows under another name. */797const FINDATA_INDEX: Record<string, string> = { "^GSPC": "SPX", "^SPX": "SPX", "^NDX": "NDX", "^DJI": "DJI", "^RUT": "RUT", "^VIX": "VIX" };798const FINDATA_REST_MAX_DAYS: Record<"1m" | "5m" | "1d", number> = { "1m": 31, "5m": 186, "1d": 3660 };799const FINDATA_MAX_CHUNKS = 8;800const FINDATA_SQL_SAFE = /^[A-Z0-9._-]{1,20}$/;801802interface FindataRow {803 timestamp_utc?: string;804 t?: string;805 session_date?: string;806 open?: number;807 high?: number;808 low?: number;809 close?: number;810 volume?: number | null;811 currency?: string;812}813814/** FinData's name and dataset family for a symbol, or the reason it has none. */815async function findataTarget(meta: SymbolMeta): Promise<{ symbol: string; cls: "stock" | "etf" | "index" | "fx" | "crypto"; currency: string | null }> {816 const s = meta.symbol;817 const none = (why: string) => new ProviderError("findata", "not_found", `FinData: ${why}`);818 if (meta.assetClass === "index") {819 const mapped = FINDATA_INDEX[s] ?? s.replace(/^\^/, "");820 if (!FINDATA_SQL_SAFE.test(mapped)) throw none(`no index series for ${s}.`);821 return { symbol: mapped, cls: "index", currency: null };822 }823 if (meta.assetClass === "crypto") {824 // FinData names crypto by its base asset: BTCUSD → BTC.825 const base = s.replace(/USDT?$/, "");826 if (!base || !FINDATA_SQL_SAFE.test(base)) throw none(`no crypto series for ${s}.`);827 return { symbol: base, cls: "crypto", currency: "USD" };828 }829 if (meta.assetClass === "fx") return { symbol: s, cls: "fx", currency: s.slice(3) };830 if (meta.assetClass === "commodity") throw none("futures are not served through this route (continuous contracts need a roll convention).");831 // Stocks and ETFs: the catalogue covers US listings only (a suffix like .TO is another market).832 if (/\.[A-Z]{1,3}$/.test(s) && !/\.[AB]$/.test(s)) throw none(`its catalogue covers US stocks and ETFs; ${s} is listed elsewhere.`);833 const info = await providerJson<{ instrument: { asset_class?: string; currency?: string } | null }>("findata", `/instruments/${encodeURIComponent(s)}`);834 const cls = info?.instrument?.asset_class;835 if (cls !== "stock" && cls !== "etf") throw none(`${s} is not in its catalogue of US stocks and ETFs.`);836 return { symbol: s, cls, currency: info.instrument?.currency ?? "USD" };837}838839async function findataRest(symbol: string, interval: "1m" | "5m" | "1d", from: string, to: string, adjustment: string, want: number): Promise<{ rows: FindataRow[]; clamped: boolean }> {840 // The endpoint accepts a bounded span per call: walk the range backwards in chunks, most recent first.841 const span = FINDATA_REST_MAX_DAYS[interval];842 const rows: FindataRow[] = [];843 let end = to;844 let clamped = false;845 for (let chunk = 0; chunk < FINDATA_MAX_CHUNKS && end >= from; chunk++) {846 const start = addDays(end, -(span - 1)) < from ? from : addDays(end, -(span - 1));847 let cursor: string | undefined;848 for (let page = 0; page < 30; page++) {849 const res = await providerJson<{ data: FindataRow[]; next_cursor: string | null }>("findata", "/market/bars", { params: { symbol, interval, start, end, adjustment, limit: 10_000, cursor } });850 rows.push(...(res.data ?? []));851 if (!res.next_cursor) break;852 cursor = res.next_cursor;853 }854 if (start <= from || rows.length >= want) break;855 end = addDays(start, -1);856 if (chunk === FINDATA_MAX_CHUNKS - 1) clamped = true;857 }858 return { rows, clamped };859}860861/** Bars of a coarser interval from finer ones. `bucket(t)` gives the start (epoch s) of the bar a fine bar belongs to, or null to drop it. */862export function aggregateBars(bars: Bar[], bucket: (tSec: number) => number | null): Bar[] {863 const out: Bar[] = [];864 let cur: Bar | null = null;865 for (const b of bars) {866 const k = bucket(b[0]);867 if (k === null) continue;868 if (!cur || cur[0] !== k) {869 cur = [k, b[1], b[2], b[3], b[4], b[5]];870 out.push(cur);871 } else {872 cur[2] = Math.max(cur[2], b[2]);873 cur[3] = Math.min(cur[3], b[3]);874 cur[4] = b[4];875 cur[5] = cur[5] === null && b[5] === null ? null : (cur[5] ?? 0) + (b[5] ?? 0);876 }877 }878 return out;879}880881const NY = "America/New_York";882const SESSION_OPEN_MIN = 9 * 60 + 30;883const SESSION_CLOSE_MIN = 16 * 60;884885/** Bucket of a US regular-session bar, anchored on the 09:30 open like FMP's own bars (1h: 09:30, 10:30…; 4h: 09:30, 13:30). */886export function usSessionBucket(intervalSec: number): (tSec: number) => number | null {887 return (tSec) => {888 const { minutes } = clockInZone(tSec * 1000, NY);889 if (minutes < SESSION_OPEN_MIN || minutes >= SESSION_CLOSE_MIN) return null; // extended hours are left out890 const into = (minutes - SESSION_OPEN_MIN) * 60;891 return tSec - (into % intervalSec) - (tSec % 60);892 };893}894895async function findataSeries(q: BarsQuery, meta: SymbolMeta): Promise<RawSeries> {896 const target = await findataTarget(meta);897 const notes: string[] = [];898 const sec = INTERVAL_SECONDS[q.interval];899 const fromRow = (r: FindataRow, daily: boolean): Bar | null => {900 const t = daily ? dayMs(String(r.session_date ?? String(r.timestamp_utc ?? r.t ?? "").slice(0, 10))) / 1000 : Date.parse(String(r.timestamp_utc ?? r.t ?? "")) / 1000;901 return toBar(t, r.open, r.high, r.low, r.close, r.volume ?? null);902 };903904 if (target.cls === "stock" || target.cls === "etf") {905 const adjustment = q.adjust === "none" ? "raw" : q.adjust;906 if (q.interval === "1d") {907 const { rows, clamped } = await findataRest(target.symbol, "1d", q.from, q.to, adjustment, q.limit);908 if (clamped) notes.push("The history was cut at the paging limit of this route.");909 return { provider: "findata", bars: rows.map((r) => fromRow(r, true)).filter((b): b is Bar => b !== null), adjust: q.adjust, notes, currency: target.currency };910 }911 // Intraday: stored 1m and (for stocks) 5m series; the other intervals are built from them.912 let source: "1m" | "5m" = q.interval === "1m" ? "1m" : "5m";913 const finePerBar = Math.ceil(sec / (source === "1m" ? 60 : 300));914 let got = await findataRest(target.symbol, source, q.from, q.to, adjustment, q.limit * finePerBar * 3);915 if (got.rows.length === 0 && source === "5m") {916 // ETFs have no stored 5-minute series: build from 1-minute bars.917 source = "1m";918 got = await findataRest(target.symbol, "1m", q.from, q.to, adjustment, q.limit * Math.ceil(sec / 60) * 3);919 }920 if (got.clamped) notes.push("The series was cut at the paging limit of this route: narrow the range.");921 const fine = got.rows.map((r) => fromRow(r, false)).filter((b): b is Bar => b !== null).sort((a, b) => a[0] - b[0]);922 const bars = aggregateBars(fine, usSessionBucket(sec));923 notes.push(`Regular session (09:30–16:00 New York) built from FinData ${source} bars; extended hours left out.`);924 return { provider: "findata", bars, adjust: q.adjust, notes, currency: target.currency };925 }926927 // Indices, pairs, crypto: SQL views market_bars_<class>_<interval>_raw (1m, 5m, 30m, 1h, and 1d except for pairs).928 const stored: Record<Interval, string> = { "1m": "1m", "5m": "5m", "15m": "5m", "30m": "30m", "1h": "1h", "4h": "1h", "1d": "1d" };929 const view = `market_bars_${target.cls}_${stored[q.interval]}_raw`;930 const volume = target.cls === "index" ? "" : ", volume";931 const sql =932 `SELECT timestamp_utc AS t, session_date, open, high, low, close${volume} FROM ${view} ` +933 `WHERE symbol = '${target.symbol}' AND year BETWEEN ${q.from.slice(0, 4)} AND ${q.to.slice(0, 4)} AND session_date BETWEEN DATE '${q.from}' AND DATE '${q.to}' ORDER BY timestamp_utc DESC`;934 let res: { rows: FindataRow[]; meta?: { truncated?: boolean } };935 try {936 res = await providerJson("findata", "/query", { method: "POST", body: { sql, max_rows: 100_000 }, timeoutMs: 40_000 });937 } catch (e) {938 // A view that does not exist, or a filter that matches no file, is "no data", not a failure.939 if (e instanceof ProviderError && /does not exist|Binder Error[\s\S]*empty/i.test(e.message)) throw new ProviderError("findata", "not_found", `FinData has no ${q.interval} series for ${target.cls} ${target.symbol}.`);940 throw e;941 }942 if (res.meta?.truncated) notes.push("FinData returned the most recent 100 000 rows of the range.");943 let bars = (res.rows ?? []).map((r) => fromRow(r, q.interval === "1d")).filter((b): b is Bar => b !== null).sort((a, b) => a[0] - b[0]);944 if (stored[q.interval] !== q.interval) {945 bars = aggregateBars(bars, (t) => t - (t % sec));946 notes.push(`Built from FinData ${stored[q.interval]} bars in clock-aligned UTC buckets.`);947 }948 if (q.adjust !== "none") notes.push("This instrument has no splits or dividends: prices are as quoted.");949 return { provider: "findata", bars, adjust: "none", notes, currency: target.currency };950}951952// ─── Assembly ────────────────────────────────────────────────────────────────953954export interface BarsProvenance {955 provider: ProviderId;956 fallbackFrom?: ProviderId;957 /** Why the first provider was not used (present with fallbackFrom). */958 fallbackReason?: string;959 retrievedAt: number;960 adjust: AdjustMode;961 adjustRequested: AdjustMode;962 assetClass: AssetClass;963 exchange: string | null;964 timezone: string | null;965 currency: string | null;966 freshness: Freshness;967 observations: number;968 firstDate: string | null;969 lastDate: string | null;970 /** true when more bars matched than `limit`: the most recent ones were kept. */971 truncated: boolean;972 gaps: GapReport;973 notes: string[];974}975976export interface BarsResult {977 symbol: string;978 interval: Interval;979 bars: Bar[];980 provenance: BarsProvenance;981}982983export class NoDataError extends Error {984 constructor(985 message: string,986 public attempts: { provider: ProviderId; kind: string; reason: string }[],987 /** true when at least one provider failed for a reason other than "nothing for this symbol". */988 public upstream: boolean,989 ) {990 super(message);991 }992}993994const barsCache = new TtlCache<BarsResult>(150);995const barsFlight = new SingleFlight<BarsResult>();996997function barsTtl(q: BarsQuery, nowMs: number): number {998 const touchesToday = q.to >= addDays(isoDay(nowMs), -1);999 if (q.interval === "1d") return touchesToday ? 60_000 : 6 * 3_600_000;1000 return touchesToday ? 20_000 : 10 * 60_000;1001}10021003/** One series from one provider, FMP first. */1004async function fetchSeries(q: BarsQuery, meta: SymbolMeta): Promise<{ series: RawSeries; fallbackFrom?: ProviderId; fallbackReason?: string }> {1005 const attempts: { provider: ProviderId; kind: string; reason: string }[] = [];1006 const attempt = async (provider: ProviderId, fn: () => Promise<RawSeries>): Promise<RawSeries | null> => {1007 if (!providerConfigured(provider)) {1008 attempts.push({ provider, kind: "not_configured", reason: `${PROVIDER_NAMES[provider]} is not configured on this server.` });1009 return null;1010 }1011 try {1012 const s = await fn();1013 if (s.bars.length > 0) return s;1014 attempts.push({ provider, kind: "empty", reason: `${PROVIDER_NAMES[provider]} has no ${q.interval} bars for ${q.symbol} between ${q.from} and ${q.to}.` });1015 } catch (e) {1016 if (!(e instanceof ProviderError)) throw e;1017 attempts.push({ provider, kind: e.kind, reason: e.message });1018 }1019 return null;1020 };1021 const fmp = await attempt("fmp", () => (q.interval === "1d" ? fmpDaily(q, meta.assetClass) : fmpIntraday(q, meta.assetClass)));1022 if (fmp) return { series: fmp };1023 const fd = await attempt("findata", () => findataSeries(q, meta));1024 if (fd) return { series: fd, fallbackFrom: "fmp", fallbackReason: attempts[0]?.reason };1025 const upstream = attempts.some((a) => !["empty", "not_found", "not_configured"].includes(a.kind));1026 throw new NoDataError(`No ${q.interval} bars for ${q.symbol} between ${q.from} and ${q.to}.`, attempts, upstream);1027}10281029/** Bars with provenance (contract §3). Cached by request: seconds for a series that is still moving, hours for history. */1030export function getBars(q: BarsQuery, nowMs = Date.now()): Promise<BarsResult> {1031 const key = [q.symbol, q.interval, q.from, q.to, q.adjust, q.limit].join("|");1032 return cachedFlight(barsCache, barsFlight, key, barsTtl(q, nowMs), async () => {1033 const meta = await resolveMeta(q.symbol);1034 const { series, fallbackFrom, fallbackReason } = await fetchSeries(q, meta);1035 const retrievedAt = Date.now();10361037 // One clean ascending series inside the requested dates; when it is longer than `limit` the most recent bars stay.1038 const lo = dayMs(q.from) / 1000;1039 const hi = dayMs(q.to) / 1000 + 86_400 + (q.interval === "1d" ? 0 : 5 * 3_600); // intraday: the day `to` ends in New York, not in UTC1040 const seen = new Set<number>();1041 let bars = series.bars1042 .filter((b) => b[0] >= lo && b[0] < hi && !seen.has(b[0]) && seen.add(b[0]))1043 .sort((a, b) => a[0] - b[0]);1044 if (bars.length === 0) throw new NoDataError(`No ${q.interval} bars for ${q.symbol} between ${q.from} and ${q.to}.`, [{ provider: series.provider, kind: "empty", reason: `${PROVIDER_NAMES[series.provider]} returned bars outside the requested dates only.` }], false);1045 const truncated = bars.length > q.limit;1046 if (truncated) bars = bars.slice(-q.limit);10471048 const firstDate = bars.length ? isoDay(bars[0][0] * 1000) : null;1049 const lastDate = bars.length ? isoDay(bars[bars.length - 1][0] * 1000) : null;1050 let sessionOpen: boolean | null = null;1051 if (meta.assetClass === "crypto") sessionOpen = true;1052 else if (meta.exchange && series.provider === "fmp") {1053 try {1054 // Indices have no exchange of their own in FMP ("INDEX"): the US ones follow New York's session.1055 const venue = meta.assetClass === "index" ? (US_INDICES.has(q.symbol) ? "NYSE" : "") : meta.exchange.toUpperCase();1056 sessionOpen = (await exchangeHours()).get(venue)?.isOpen ?? null;1057 } catch {1058 /* unknown */1059 }1060 }1061 const freshness = classifyBarsFreshness({1062 interval: q.interval,1063 lastBarSec: bars.length ? bars[bars.length - 1][0] : null,1064 nowMs: retrievedAt,1065 provider: series.provider,1066 sessionOpen,1067 todayInZone: dateInZone(retrievedAt, meta.timezone ?? "UTC"),1068 });10691070 let gaps: GapReport;1071 if (q.interval !== "1d") gaps = { missingSessions: 0, missingDates: [], unexpectedSessions: 0, unexpectedDates: [], calendar: "none", checkedFrom: null, checkedTo: null, note: "Gap diagnostics are computed for daily series only." };1072 else if (!firstDate || !lastDate) gaps = detectGaps([], { mode: "weekdays" });1073 else gaps = detectGaps(bars.map((b) => isoDay(b[0] * 1000)), await calendarFor(meta, firstDate, lastDate));10741075 const notes = [...series.notes];1076 if (truncated) notes.push(`More than ${q.limit} bars matched: the most recent ${q.limit} are returned.`);1077 if (q.interval === "1d") notes.push("A daily bar is stamped 00:00 UTC of its session date.");10781079 return {1080 symbol: q.symbol,1081 interval: q.interval,1082 bars,1083 provenance: {1084 provider: series.provider,1085 ...(fallbackFrom ? { fallbackFrom, fallbackReason } : {}),1086 retrievedAt,1087 adjust: series.adjust,1088 adjustRequested: q.adjust,1089 assetClass: meta.assetClass,1090 exchange: meta.exchange,1091 timezone: meta.timezone,1092 currency: meta.currency ?? series.currency ?? null,1093 freshness,1094 observations: bars.length,1095 firstDate,1096 lastDate,1097 truncated,1098 gaps,1099 notes,1100 },1101 };1102 });1103}11041105// ═══ Quotes ══════════════════════════════════════════════════════════════════11061107export const MAX_QUOTE_SYMBOLS = 60;11081109export interface Quote {1110 symbol: string;1111 name: string | null;1112 price: number | null;1113 change: number | null;1114 changePct: number | null;1115 currency: string | null;1116 dayLow: number | null;1117 dayHigh: number | null;1118 yearLow: number | null;1119 yearHigh: number | null;1120 volume: number | null;1121 marketCap: number | null;1122 open: number | null;1123 previousClose: number | null;1124 exchange: string | null;1125 assetClass: AssetClass;1126 /** The provider's own time for this quote (ms), null when it gave none. */1127 providerTimestamp: number | null;1128 provider: ProviderId;1129 freshness: FreshnessKind;1130}11311132export interface QuotesResult {1133 quotes: Quote[];1134 /** Symbols no provider had a quote for. */1135 missing: string[];1136 freshness: Freshness;1137}11381139/** Symbols of a `symbols=A,B` query: validated, upper-cased, de-duplicated, order kept. */1140export function parseSymbolList(v: unknown, max = MAX_QUOTE_SYMBOLS): string[] {1141 const parts = (Array.isArray(v) ? v.join(",") : String(v ?? "")).split(/[\s,;]+/).filter((s) => s !== "");1142 if (parts.length === 0) throw new DataParamError("symbols is required (comma-separated tickers).");1143 const out = [...new Set(parts.map(parseSymbol))];1144 if (out.length > max) throw new DataParamError(`At most ${max} symbols per request.`);1145 return out;1146}11471148const n = (v: unknown): number | null => (finiteNum(v) ? v : null);11491150/** FMP quote → contract quote. A market cap of 0 (indices) or null (pairs) is "not applicable", never a value. */1151export function quoteFromFmp(q: FmpQuote, meta: Pick<SymbolMeta, "assetClass" | "currency">, nowMs: number): Quote {1152 const ts = finiteNum(q.timestamp) && q.timestamp > 0 ? q.timestamp * 1000 : null;1153 return {1154 symbol: q.symbol,1155 name: q.name ?? null,1156 price: n(q.price),1157 change: n(q.change),1158 changePct: n(q.changePercentage),1159 currency: meta.currency,1160 dayLow: n(q.dayLow),1161 dayHigh: n(q.dayHigh),1162 yearLow: n(q.yearLow),1163 yearHigh: n(q.yearHigh),1164 volume: meta.assetClass === "index" && q.volume === 0 ? null : n(q.volume),1165 marketCap: finiteNum(q.marketCap) && q.marketCap > 0 ? q.marketCap : null,1166 open: n(q.open),1167 previousClose: n(q.previousClose),1168 exchange: q.exchange ?? null,1169 assetClass: meta.assetClass,1170 providerTimestamp: ts,1171 provider: "fmp",1172 freshness: classifyQuoteFreshness("fmp", ts, nowMs).kind,1173 };1174}11751176interface EodhdQuote {1177 code?: string;1178 timestamp?: number | string;1179 open?: number | string;1180 high?: number | string;1181 low?: number | string;1182 close?: number | string;1183 volume?: number | string;1184 previousClose?: number | string;1185 change?: number | string;1186 change_p?: number | string;1187}11881189/** EODHD's delayed quote for a listed security FMP did not return (US ticker, or TICKER.EXCHANGE). */1190async function eodhdQuote(symbol: string, nowMs: number): Promise<Quote | null> {1191 if (guessAssetClass(symbol) !== "equity") return null;1192 const code = /\.[A-Z]{1,6}$/.test(symbol) ? symbol : `${symbol}.US`;1193 const q = await providerJson<EodhdQuote>("eodhd", `/real-time/${encodeURIComponent(code)}`, { timeoutMs: 8_000 });1194 const num = (v: unknown) => (v === "NA" || v === null || v === undefined || v === "" ? null : n(Number(v)));1195 const price = num(q.close);1196 if (price === null) return null;1197 const ts = num(q.timestamp);1198 return {1199 symbol,1200 name: null,1201 price,1202 change: num(q.change),1203 changePct: num(q.change_p),1204 currency: null,1205 dayLow: num(q.low),1206 dayHigh: num(q.high),1207 yearLow: null,1208 yearHigh: null,1209 volume: num(q.volume),1210 marketCap: null,1211 open: num(q.open),1212 previousClose: num(q.previousClose),1213 exchange: null,1214 assetClass: "equity",1215 providerTimestamp: ts === null ? null : ts * 1000,1216 provider: "eodhd",1217 freshness: "delayed",1218 };1219}12201221/** Runs `fn` over `items` with at most `width` in flight. */1222export async function mapLimit<T, R>(items: T[], width: number, fn: (item: T) => Promise<R>): Promise<R[]> {1223 const out = new Array<R>(items.length);1224 let next = 0;1225 await Promise.all(1226 Array.from({ length: Math.min(width, items.length) }, async () => {1227 while (next < items.length) {1228 const i = next++;1229 out[i] = await fn(items[i]);1230 }1231 }),1232 );1233 return out;1234}12351236const quotesCache = new TtlCache<QuotesResult>(300);1237const quotesFlight = new SingleFlight<QuotesResult>();1238const QUOTES_TTL_MS = 10_000;12391240/** Raw FMP quotes of a list (one upstream call). Shared with the market overview. */1241export async function fmpBatchQuotes(symbols: string[]): Promise<FmpQuote[]> {1242 const rows = await providerJson<FmpQuote[]>("fmp", "/batch-quote", { params: { symbols: symbols.join(",") } });1243 return Array.isArray(rows) ? rows.filter((r) => r && typeof r.symbol === "string") : [];1244}12451246/**1247 * Quotes of a list of symbols: one FMP batch call; listed securities FMP does not know are asked from EODHD1248 * (delayed). Each quote says which provider it came from; the response's `freshness` describes the batch.1249 */1250export function getQuotes(symbols: string[]): Promise<QuotesResult> {1251 return cachedFlight(quotesCache, quotesFlight, symbols.join(","), QUOTES_TTL_MS, async () => {1252 const retrievedAt = Date.now();1253 let rows: FmpQuote[] = [];1254 let fmpError: ProviderError | null = null;1255 try {1256 rows = await fmpBatchQuotes(symbols);1257 } catch (e) {1258 if (!(e instanceof ProviderError)) throw e;1259 fmpError = e;1260 }1261 const bySymbol = new Map(rows.map((r) => [r.symbol.toUpperCase(), r]));1262 const quotes = await mapLimit(symbols, 6, async (symbol): Promise<Quote | null> => {1263 const row = bySymbol.get(symbol);1264 if (row) return quoteFromFmp(row, await resolveMeta(symbol, row), retrievedAt);1265 if (!providerConfigured("eodhd")) return null;1266 try {1267 return await eodhdQuote(symbol, retrievedAt);1268 } catch {1269 return null;1270 }1271 });1272 const found = quotes.filter((q): q is Quote => q !== null);1273 if (found.length === 0 && fmpError) throw fmpError;1274 const providers = [...new Set(found.map((q) => q.provider))];1275 const stamps = found.map((q) => q.providerTimestamp).filter((t): t is number => t !== null);1276 const newest = stamps.length ? Math.max(...stamps) : null;1277 const main: ProviderId = providers.includes("fmp") || providers.length === 0 ? "fmp" : providers[0];1278 const freshness = classifyQuoteFreshness(main, newest, retrievedAt);1279 freshness.provider = providers.length > 1 ? providers.join("+") : main;1280 const notes = [freshness.note, "Quotes are fetched on request, not streamed.", providers.length > 1 ? "Some quotes come from EODHD (delayed): see each quote's provider." : null, fmpError ? `FMP: ${fmpError.message}` : null];1281 freshness.note = notes.filter(Boolean).join(" ");1282 return { quotes: found, missing: symbols.filter((s, i) => quotes[i] === null), freshness };1283 });1284}12851286// ═══ Batch of daily series (sparklines) ══════════════════════════════════════12871288export const MAX_BATCH_SYMBOLS = 30;1289export const MAX_BATCH_LIMIT = 260;1290const BATCH_PARALLEL = 6;12911292export interface BarsBatchQuery { symbols: string[]; interval: "1d"; limit: number }1293export interface BarsBatchResult {1294 interval: "1d";1295 limit: number;1296 /** one entry per symbol that has bars, in the order asked; each with its own provenance (provider, fallback, gaps…) */1297 series: BarsResult[];1298 /** symbols without a series: the same error a single request would have answered */1299 failed: { symbol: string; status: number; error: string }[];1300}13011302/**1303 * Validated batch request: `symbols=A,B,C` (≤ 30), daily bars only, the most recent `limit` (≤ 260, default 30) of1304 * the last year. Small on purpose: it exists for tables of sparklines, not for downloads.1305 */1306export function parseBarsBatchQuery(q: Record<string, unknown>): BarsBatchQuery {1307 const symbols = parseSymbolList(q.symbols, MAX_BATCH_SYMBOLS);1308 const interval = String(q.interval ?? "1d").trim();1309 if (interval !== "1d") throw new DataParamError("The batch route serves daily bars only (interval=1d).");1310 for (const k of ["from", "to", "adjust"]) if (q[k] !== undefined && q[k] !== "") throw new DataParamError(`${k} is not accepted by the batch route.`);1311 let limit = 30;1312 if (q.limit !== undefined && q.limit !== null && q.limit !== "") {1313 const n = Number(q.limit);1314 if (!Number.isInteger(n) || n < 1 || n > MAX_BATCH_LIMIT) throw new DataParamError(`limit must be an integer between 1 and ${MAX_BATCH_LIMIT}.`);1315 limit = n;1316 }1317 return { symbols, interval: "1d", limit };1318}13191320/**1321 * Several daily series in one answer. Every symbol goes through `getBars` with the request a single call1322 * `GET /bars/:symbol?interval=1d&limit=n` would make, so both routes share one cache entry per symbol and a series is1323 * never mixed between providers. A symbol that fails does not fail the batch: it is listed in `failed`.1324 */1325export async function getBarsBatch(q: BarsBatchQuery, nowMs = Date.now()): Promise<BarsBatchResult> {1326 const out: (BarsResult | { symbol: string; status: number; error: string })[] = new Array(q.symbols.length);1327 let next = 0;1328 const worker = async () => {1329 for (;;) {1330 const i = next++;1331 if (i >= q.symbols.length) return;1332 const symbol = q.symbols[i];1333 try {1334 out[i] = await getBars(parseBarsQuery(symbol, { interval: "1d", limit: q.limit }, nowMs), nowMs);1335 } catch (e) {1336 const r = dataErrorResponse(e, "bars batch");1337 out[i] = { symbol, status: r.status, error: String(r.body.error ?? "Data error.") };1338 }1339 }1340 };1341 await Promise.all(Array.from({ length: Math.min(BATCH_PARALLEL, q.symbols.length) }, worker));1342 return {1343 interval: "1d",1344 limit: q.limit,1345 series: out.filter((x): x is BarsResult => "bars" in x),1346 failed: out.filter((x): x is { symbol: string; status: number; error: string } => !("bars" in x)),1347 };1348}13491350// ═══ Routes ══════════════════════════════════════════════════════════════════13511352/** HTTP status and body for a failure of this layer. Unknown errors are logged and answered without detail. */1353export function dataErrorResponse(e: unknown, where: string): { status: number; body: Record<string, unknown> } {1354 if (e instanceof DataParamError) return { status: 400, body: { error: e.message } };1355 if (e instanceof NoDataError) return { status: e.upstream ? 502 : 404, body: { error: e.message, providers: e.attempts.map((a) => ({ provider: a.provider, reason: a.reason })) } };1356 if (e instanceof ProviderError) {1357 const status = e.kind === "not_configured" ? 503 : e.kind === "not_found" ? 404 : e.kind === "rate_limit" ? 429 : 502;1358 return { status, body: { error: e.message, provider: e.provider } };1359 }1360 logger.error(`[data] ${where}: ${sanitizeProviderMessage((e as Error)?.message)}`);1361 return { status: 500, body: { error: "Data error." } };1362}13631364export function registerDataRoutes(app: Express): void {1365 app.get("/api/v2/data/bars", async (req: Request, res: Response) => {1366 res.set("Cache-Control", "private, no-store");1367 try {1368 res.json(await getBarsBatch(parseBarsBatchQuery(req.query as Record<string, unknown>)));1369 } catch (e) {1370 const r = dataErrorResponse(e, "bars batch");1371 res.status(r.status).json(r.body);1372 }1373 });13741375 app.get("/api/v2/data/bars/:symbol", async (req: Request, res: Response) => {1376 res.set("Cache-Control", "private, no-store");1377 try {1378 res.json(await getBars(parseBarsQuery(req.params.symbol, req.query as Record<string, unknown>)));1379 } catch (e) {1380 const r = dataErrorResponse(e, "bars");1381 res.status(r.status).json(r.body);1382 }1383 });13841385 app.get("/api/v2/data/quotes", async (req: Request, res: Response) => {1386 res.set("Cache-Control", "private, no-store");1387 try {1388 res.json(await getQuotes(parseSymbolList(req.query.symbols)));1389 } catch (e) {1390 const r = dataErrorResponse(e, "quotes");1391 res.status(r.status).json(r.body);1392 }1393 });1394}13951396/** Test hook: forgets everything cached by this module. */1397export function resetDataLayer(): void {1398 for (const c of [barsCache, quotesCache, metaCache, profileCache, holidayCache, hoursCache] as TtlCache<unknown>[]) c.clear();1399 offsetCache.clear();1400 for (const p of Object.keys(counters) as ProviderId[]) counters[p] = { calls: 0, errors: 0, lastError: null, lastErrorAt: null, lastOkAt: null, lastLatencyMs: null };1401}1402