trading-app/src/lib/market.ts
David 234efda586 Fix trade proposals, speed, Trade Republic setup and stock UI
- Buy by EUR amount (fractional shares, like Trade Republic): 200 EUR can
  now reach every large cap; risk engine sizes in whole euros
- No-AI screener (pullback in uptrend) feeds training cards and AI candidates
- Auto-update on app open via after(); "find ideas now" button (3/day)
- New Actions tab: stock list, stock page with chart, news, AI opinion,
  sandbox buy by amount or shares
- "Mon compte" tab: declare deposits, cash, holdings and PEA plan
  (no broker credentials, no PEA invented by default)
- Yahoo data cached and deduplicated, pages stream per section
- Tests: fractional sizing, screener, no-AI idea flow

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 19:05:20 +01:00

192 lines
7.1 KiB
TypeScript

import "server-only";
import YahooFinance from "yahoo-finance2";
import type { Bar } from "./engine/fills";
import { addDays, parisDate } from "./time";
import { findStock } from "./universe";
/** Cours, historiques, actus et dates de résultats, via Yahoo Finance (gratuit, US + Europe). */
const yf = new YahooFinance({ suppressNotices: ["yahooSurvey"] });
export type Quote = {
symbol: string;
name: string;
price: number;
currency: string;
changePct: number | null;
};
const SUPPORTED_CURRENCIES = new Set(["EUR", "USD"]);
// ---------------------------------------------------------------------------
// Cache mémoire partagé par toutes les requêtes du serveur.
// Yahoo est lent (0,3 à 2 s par appel) : sans cache, chaque page en enchaînait une dizaine.
// Les appels identiques en cours sont aussi mutualisés (une seule requête pour 3 demandes simultanées).
// ---------------------------------------------------------------------------
type Entry = { at: number; value: Promise<unknown> };
const g = globalThis as unknown as { __marketCache?: Map<string, Entry> };
const cache = (g.__marketCache ??= new Map());
function memo<T>(key: string, ttlMs: number, fn: () => Promise<T>): Promise<T> {
const hit = cache.get(key);
if (hit && Date.now() - hit.at < ttlMs) return hit.value as Promise<T>;
const value = fn().catch((err) => {
cache.delete(key); // une erreur n'est jamais gardée en cache
throw err;
});
cache.set(key, { at: Date.now(), value });
return value;
}
const QUOTE_TTL_MS = 60_000;
const quoteCache = new Map<string, { at: number; quote: Quote }>();
const inflightQuotes = new Map<string, Promise<void>>();
async function fetchQuotes(symbols: string[]): Promise<void> {
// Yahoo accepte de gros paquets ; on découpe par 50 par prudence.
for (let i = 0; i < symbols.length; i += 50) {
const chunk = symbols.slice(i, i + 50);
let rows: Awaited<ReturnType<typeof yf.quote>> = [];
try {
rows = await yf.quote(chunk);
} catch (err) {
console.error("[market] cours indisponibles :", chunk.join(","), err);
continue;
}
for (const r of rows) {
if (r.regularMarketPrice == null || !r.currency) continue;
quoteCache.set(r.symbol, {
at: Date.now(),
quote: {
symbol: r.symbol,
name: findStock(r.symbol)?.name ?? r.longName ?? r.shortName ?? r.symbol,
price: r.regularMarketPrice,
currency: r.currency,
changePct: r.regularMarketChangePercent ?? null,
},
});
}
}
}
export async function getQuotes(symbols: string[]): Promise<Map<string, Quote>> {
const unique = [...new Set(symbols)];
const fresh = (s: string) => {
const hit = quoteCache.get(s);
return hit && Date.now() - hit.at < QUOTE_TTL_MS;
};
const missing = unique.filter((s) => !fresh(s) && !inflightQuotes.has(s));
if (missing.length) {
const p = fetchQuotes(missing).finally(() => missing.forEach((s) => inflightQuotes.delete(s)));
missing.forEach((s) => inflightQuotes.set(s, p));
}
await Promise.all(unique.map((s) => inflightQuotes.get(s)).filter(Boolean));
const out = new Map<string, Quote>();
for (const s of unique) {
const hit = quoteCache.get(s);
if (hit) out.set(s, hit.quote);
}
return out;
}
export async function getQuote(symbol: string): Promise<Quote | null> {
return (await getQuotes([symbol])).get(symbol) ?? null;
}
/** Taux de conversion vers l'euro : 1 unité de `currency` = n €. Null si devise non gérée. */
export async function getFxToEur(currency: string): Promise<number | null> {
if (currency === "EUR") return 1;
if (currency !== "USD") return null;
const q = await getQuote("EURUSD=X");
return q ? 1 / q.price : null;
}
export function isSupportedCurrency(currency: string): boolean {
return SUPPORTED_CURRENCIES.has(currency);
}
/**
* Barres journalières depuis une date (incluse), datées à l'heure de Paris.
* On télécharge au moins 9 mois d'historique une seule fois par action (cache 15 min),
* puis on découpe : une seule requête sert le graphique, le PEA, l'indice et le moteur.
*/
const BARS_TTL_MS = 15 * 60_000;
const barsFrom = new Map<string, string>();
export async function getBars(symbol: string, fromDate: string): Promise<Bar[]> {
const minFrom = addDays(parisDate(), -270);
const known = barsFrom.get(symbol);
const from = known && known <= fromDate ? known : fromDate < minFrom ? fromDate : minFrom;
barsFrom.set(symbol, from);
const all = await memo(`bars:${symbol}:${from}`, BARS_TTL_MS, async () => {
const chart = await yf.chart(symbol, { period1: from, interval: "1d" });
return chart.quotes
.filter((q) => q.open != null && q.high != null && q.low != null && q.close != null)
.map((q) => ({
date: parisDate(q.date),
open: q.open!,
high: q.high!,
low: q.low!,
close: q.close!,
}));
});
return all.filter((b) => b.date >= fromDate);
}
/** Prochaine date de résultats trimestriels (AAAA-MM-JJ), ou null si inconnue. */
export async function getNextEarningsDate(symbol: string): Promise<string | null> {
return memo(`earnings:${symbol}`, 12 * 3_600_000, async () => {
try {
const s = await yf.quoteSummary(symbol, { modules: ["calendarEvents"] });
const dates = s.calendarEvents?.earnings?.earningsDate ?? [];
const today = parisDate();
const next = dates.map((d) => parisDate(d)).filter((d) => d >= today).sort()[0];
return next ?? null;
} catch {
return null;
}
});
}
export type RawNews = { id: string; symbol: string; title: string; publisher: string; url: string; publishedAt: Date };
/** Actus récentes d'une action. Recherche par symbole (US) ou par nom (Europe), puis filtre sur la société. */
export async function getNews(symbol: string): Promise<RawNews[]> {
return memo(`news:${symbol}`, 10 * 60_000, async () => {
const stock = findStock(symbol);
const query = stock?.market === "EU" ? stock.name : symbol;
const res = await yf.search(query, { newsCount: 8, quotesCount: 0 });
return res.news
.filter((n) => n.relatedTickers?.includes(symbol))
.map((n) => ({
id: n.uuid,
symbol,
title: n.title,
publisher: n.publisher,
url: n.link,
publishedAt: n.providerPublishTime,
}));
});
}
export type SearchHit = { symbol: string; name: string; exchange: string; type: string };
/** Recherche d'actions ou d'ETF (en euros ou en dollars, les seules devises gérées). */
export async function searchInstruments(query: string): Promise<SearchHit[]> {
return memo(`search:${query.toLowerCase()}`, 10 * 60_000, async () => {
const res = await yf.search(query, { quotesCount: 10, newsCount: 0 });
const hits: SearchHit[] = [];
for (const q of res.quotes) {
if (!("symbol" in q) || !q.isYahooFinance) continue;
if (q.quoteType !== "EQUITY" && q.quoteType !== "ETF") continue;
hits.push({
symbol: q.symbol,
name: findStock(q.symbol)?.name || ("longname" in q && q.longname) || ("shortname" in q && q.shortname) || q.symbol,
exchange: ("exchDisp" in q && q.exchDisp) || "",
type: q.quoteType,
});
}
return hits;
});
}