diff --git a/README.md b/README.md index f61f51e..804988d 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,6 @@ GitHub Actions (toutes les 30 min, en semaine) **Le coupe-circuit** : si la cagnotte réelle tombe sous 50 % de ce que tu y as versé, retour en simulation. **Limites connues** : -- La simulation utilise des barres journalières. Si un stop et un objectif sont touchés le même jour, on suppose le stop. -- Les jours fériés ne sont pas gérés. +- La simulation utilise des barres journalières. Si le cours ouvre au-delà du stop ou de l'objectif, l'ordre part au prix d'ouverture. Si les deux sont touchés dans la même journée sans trou de cotation, on suppose le stop. +- Jours fériés gérés : ceux de Trade Republic (1er janvier, Vendredi saint, lundi de Pâques, 24, 25, 26 et 31 décembre). Les autres fermetures exceptionnelles ne le sont pas. - Les cours US viennent de la Bourse américaine, alors que Trade Republic cote sur LS Exchange avec un petit écart. On compte 0,1 % de glissement par ordre. diff --git a/next.config.ts b/next.config.ts index 54ce252..b5fcaa3 100644 --- a/next.config.ts +++ b/next.config.ts @@ -7,6 +7,11 @@ const nextConfig: NextConfig = { outputFileTracingIncludes: { "/**": ["./drizzle/**"] }, cacheComponents: true, partialPrefetching: true, + experimental: { + // Un onglet déjà ouvert se réaffiche instantanément pendant 1 minute (au lieu d'être rechargé à chaque toucher). + // Toute action (achat, réponse à une fiche...) vide ce cache : on ne voit jamais un état périmé après avoir agi. + staleTimes: { dynamic: 60 }, + }, turbopack: { rules: { "*.css": { diff --git a/src/app/actions.ts b/src/app/actions.ts index 91f4e3f..872d665 100644 --- a/src/app/actions.ts +++ b/src/app/actions.ts @@ -6,7 +6,7 @@ import { revalidatePath } from "next/cache"; import { askAboutStock, AiUnavailableError, type AskAnswer } from "@/lib/ai"; import { createSessionToken, isValidSession, safeEqual, SESSION_COOKIE, SESSION_DAYS } from "@/lib/auth"; import { proposeManualRealBuy, respondToCard } from "@/lib/cards"; -import { runEvening, runEveningNow, tick } from "@/lib/jobs"; +import { resetAiSim, runEvening, runEveningNow, tick } from "@/lib/jobs"; import { FEE_EUR } from "@/lib/engine/fills"; import { roundShares } from "@/lib/engine/risk"; import { @@ -26,7 +26,7 @@ import { addHolding, deleteHolding, recordDeposit, recordSale, setCash } from "@ import { defaultPeaPlan, getSettings, updateSettings } from "@/lib/settings"; import { addDays, parisDate } from "@/lib/time"; import { getDb, schema } from "@/lib/db"; -import { eq } from "drizzle-orm"; +import { and, eq } from "drizzle-orm"; /** Les actions serveur sont des points d'entrée publics : chacune vérifie la session. */ async function requireAuth() { @@ -95,11 +95,11 @@ export async function sandboxBuy(input: { targetPct?: number; }): Promise<{ ok: boolean; message: string }> { await requireAuth(); - const quote = await getQuote(input.symbol); + const quote = await getQuote(input.symbol, { fresh: true }); if (!quote) return { ok: false, message: "Cours introuvable." }; if (!isSupportedCurrency(quote.currency)) return { ok: false, message: "Seules les actions en euros ou en dollars sont gérées." }; const ref = input.type === "limit" && input.limitPrice ? input.limitPrice : quote.price; - const fx = (await getFxToEur(quote.currency)) ?? 1; + const fx = (await getFxToEur(quote.currency, { fresh: true })) ?? 1; const shares = input.amountEur ? roundShares(input.amountEur / (ref * fx)) : (input.shares ?? 0); if (!(shares > 0)) return { ok: false, message: "Indique un montant ou un nombre d'actions." }; const state = await getPortfolioState("sandbox"); @@ -131,6 +131,11 @@ export async function sandboxSell(positionId: number): Promise<{ ok: boolean; me const db = await getDb(); const [pos] = await db.select().from(schema.positions).where(eq(schema.positions.id, positionId)); if (!pos || pos.portfolioId !== "sandbox" || pos.status !== "open") return { ok: false, message: "Position introuvable." }; + const [already] = await db + .select({ id: schema.orders.id }) + .from(schema.orders) + .where(and(eq(schema.orders.positionId, pos.id), eq(schema.orders.side, "sell"), eq(schema.orders.status, "pending"))); + if (already) return { ok: false, message: "Une vente est déjà en attente pour cette position (elle partira à la réouverture)." }; const r = await placeOrder({ portfolioId: "sandbox", symbol: pos.symbol, @@ -164,6 +169,13 @@ export async function resetSandbox() { revalidatePath("/", "layout"); } +/** Remet la cagnotte de l'IA à 200 € et relance la simulation à partir d'aujourd'hui. */ +export async function resetAiPot() { + await requireAuth(); + await resetAiSim(); + revalidatePath("/", "layout"); +} + export async function askAi(symbol: string, question: string): Promise<{ ok: true; answer: AskAnswer } | { ok: false; message: string }> { await requireAuth(); try { @@ -333,7 +345,8 @@ export async function deleteHoldingAction(positionId: number) { export async function runNow(mode: "tick" | "evening"): Promise { await requireAuth(); - const log = mode === "evening" ? await runEvening() : await tick(); + // « Préparer le rendez-vous maintenant » : on le refait même s'il a déjà eu lieu aujourd'hui. + const log = mode === "evening" ? await runEvening({ force: true }) : await tick(); revalidatePath("/", "layout"); return log; } diff --git a/src/lib/app.integration.test.ts b/src/lib/app.integration.test.ts index 4745c9a..8a43659 100644 --- a/src/lib/app.integration.test.ts +++ b/src/lib/app.integration.test.ts @@ -118,7 +118,7 @@ describe("intégration", () => { }); it("prépare un rendez-vous même sans IA, et calcule PEA, classement et critères", async () => { - const log = await runEvening(); + const log = await runEvening({ force: true }); expect(log.join(" ")).toContain("Rendez-vous créé"); const db = await getDb(); const [rdv] = await db.select().from(schema.rendezvous); @@ -137,10 +137,88 @@ describe("intégration", () => { expect(board.map((b) => b.label).sort()).toEqual(["L'IA", "S&P 500", "Toi"]); }); + it("n'exécute un ordre qu'une fois même si deux mises à jour tournent en même temps", async () => { + const db = await getDb(); + await db.delete(schema.positions).where(eq(schema.positions.portfolioId, "sandbox")); + await db.delete(schema.orders).where(eq(schema.orders.portfolioId, "sandbox")); + await db.update(schema.portfolios).set({ cash: 200 }).where(eq(schema.portfolios.id, "sandbox")); + const quote = (await getQuote("KO"))!; + const [order] = await db + .insert(schema.orders) + .values({ + portfolioId: "sandbox", + symbol: "KO", + name: "Coca-Cola", + currency: quote.currency, + side: "buy", + type: "limit", + shares: 1, + limitPrice: quote.price * 1.2, + validUntil: addDays(parisDate(), 5), + createdAt: new Date(Date.now() - 5 * 86_400_000), + }) + .returning(); + await Promise.all([processAll(), processAll(), processAll()]); + const positions = await db.select().from(schema.positions).where(eq(schema.positions.portfolioId, "sandbox")); + expect(positions).toHaveLength(1); + const [o] = await db.select().from(schema.orders).where(eq(schema.orders.id, order.id)); + expect(o.status).toBe("filled"); + const s = await getPortfolioState("sandbox"); + expect(s.cash).toBeCloseTo(200 - positions[0].shares * positions[0].entryPrice * positions[0].entryFx - 1, 6); + + // Vente : la position ne peut être clôturée qu'une fois. + const { closePosition } = await import("./portfolio"); + const results = await Promise.all([closePosition(positions[0], 70, 1, "manual"), closePosition(positions[0], 70, 1, "manual")]); + expect(results.filter(Boolean)).toHaveLength(1); + }); + + it("un double appui sur « C'est fait » n'enregistre l'achat réel qu'une fois", async () => { + const db = await getDb(); + await db.delete(schema.positions).where(eq(schema.positions.portfolioId, "real")); + const [card] = await db + .insert(schema.actions) + .values({ + rendezvousId: 0, + kind: "buy", + training: false, + symbol: "KO", + payload: { title: "Acheter", why: "", steps: [], name: "Coca-Cola", currency: "USD", shares: 1, limitPrice: 60, stopPrice: 55 }, + }) + .returning(); + const r = await Promise.allSettled([respondToCard(card.id, "done"), respondToCard(card.id, "done")]); + expect(r.filter((x) => x.status === "fulfilled")).toHaveLength(1); + const real = await getPortfolioState("real"); + expect(real.positions).toHaveLength(1); + }); + + it("verrous : une seule mise à jour à la fois, une chose par jour", async () => { + const { claimKv, claimLock, releaseLock } = await import("./settings"); + expect(await claimLock("testLock", 60_000)).toBe(true); + expect(await claimLock("testLock", 60_000)).toBe(false); + await releaseLock("testLock"); + expect(await claimLock("testLock", 60_000)).toBe(true); + expect(await claimKv("testDay", "2026-11-18")).toBe(true); + expect(await claimKv("testDay", "2026-11-18")).toBe(false); + expect(await claimKv("testDay", "2026-11-19")).toBe(true); + }); + + it("remet la cagnotte de l'IA à zéro et relance la simulation", async () => { + const db = await getDb(); + const { resetAiSim } = await import("./jobs"); + await db.update(schema.portfolios).set({ cash: 120 }).where(eq(schema.portfolios.id, "ai_sim")); + await db.insert(schema.cashFlows).values({ portfolioId: "ai_sim", amount: 50, kind: "deposit", date: "2026-10-05" }); + await resetAiSim(); + const ai = await getPortfolioState("ai_sim"); + expect(ai.cash).toBe(200); + const flows = await db.select().from(schema.cashFlows).where(eq(schema.cashFlows.portfolioId, "ai_sim")); + expect(flows).toHaveLength(0); + expect((await ensureSetup()).simStartDate).toBe(parisDate()); + }); + it("sans IA, propose une idée du filtre et permet un achat fractionné", async () => { const { refreshIdeas } = await import("./ideas"); const ideas = await refreshIdeas(true); - await runEvening(); + await runEvening({ force: true }); const db = await getDb(); const cards = await db.select().from(schema.actions).where(eq(schema.actions.status, "pending")); // Le marché ne donne pas toujours d'idée : la fiche n'existe que s'il y en a une. diff --git a/src/lib/cards.ts b/src/lib/cards.ts index 33c083b..6db10f7 100644 --- a/src/lib/cards.ts +++ b/src/lib/cards.ts @@ -1,10 +1,10 @@ import "server-only"; -import { desc, eq } from "drizzle-orm"; +import { and, desc, eq, or } from "drizzle-orm"; import { getDb, schema } from "./db"; import { FEE_EUR } from "./engine/fills"; import { checkBuy } from "./engine/risk"; import { getFxToEur, getNextEarningsDate, getQuote, isSupportedCurrency } from "./market"; -import { closePosition, getPortfolioState } from "./portfolio"; +import { addCash, closePosition, getPortfolioState } from "./portfolio"; import { parisDate } from "./time"; export type Card = typeof schema.actions.$inferSelect; @@ -17,10 +17,16 @@ export async function getLatestRendezvous() { return { ...rdv, cards }; } +/** + * Fiches encore à traiter hors du dernier rendez-vous : tes trades proposés à la main, + * et les virements vers le PEA (qui ne doivent pas disparaître le lendemain). + */ export async function getPendingAdhocCards(): Promise { const db = await getDb(); - const rows = await db.select().from(schema.actions).where(eq(schema.actions.rendezvousId, 0)); - return rows.filter((r) => r.status === "pending"); + return db + .select() + .from(schema.actions) + .where(and(eq(schema.actions.status, "pending"), or(eq(schema.actions.rendezvousId, 0), eq(schema.actions.kind, "to_pea")))); } /** @@ -29,17 +35,31 @@ export async function getPendingAdhocCards(): Promise { */ export async function respondToCard(id: number, answer: "done" | "skipped", fill?: { price?: number; shares?: number }) { const db = await getDb(); - const [card] = await db.select().from(schema.actions).where(eq(schema.actions.id, id)); - if (!card || card.status !== "pending") throw new Error("Fiche introuvable ou déjà traitée."); + // Réservation atomique : un double appui sur « C'est fait » n'enregistre pas l'achat deux fois. + const [card] = await db + .update(schema.actions) + .set({ status: answer, respondedAt: new Date() }) + .where(and(eq(schema.actions.id, id), eq(schema.actions.status, "pending"))) + .returning(); + if (!card) throw new Error("Fiche introuvable ou déjà traitée."); + try { + if (answer === "done" && !card.training) await applyRealCard(card, fill); + } catch (e) { + await db.update(schema.actions).set({ status: "pending", respondedAt: null }).where(eq(schema.actions.id, id)); + throw e; + } +} - if (answer === "done" && !card.training) { +async function applyRealCard(card: Card, fill?: { price?: number; shares?: number }) { + const db = await getDb(); + { const p = card.payload; if (card.kind === "buy" && card.symbol) { const shares = fill?.shares ?? p.shares!; const price = fill?.price ?? p.limitPrice!; + if (!(shares > 0) || !(price > 0)) throw new Error("Indique le prix et le nombre d'actions réellement obtenus."); const fx = (await getFxToEur(p.currency!)) ?? 1; - const [pf] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, "real")); - await db.update(schema.portfolios).set({ cash: pf.cash - (shares * price * fx + FEE_EUR) }).where(eq(schema.portfolios.id, "real")); + await addCash("real", -(shares * price * fx + FEE_EUR)); await db.insert(schema.positions).values({ portfolioId: "real", symbol: card.symbol, @@ -65,20 +85,18 @@ export async function respondToCard(id: number, answer: "done" | "skipped", fill } else if (card.kind === "move_stop" && p.positionId) { await db.update(schema.positions).set({ stopPrice: p.stopPrice }).where(eq(schema.positions.id, p.positionId)); } else if (card.kind === "to_pea" && p.amountEur) { - const [pf] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, "real")); - await db.update(schema.portfolios).set({ cash: pf.cash - p.amountEur }).where(eq(schema.portfolios.id, "real")); + await addCash("real", -p.amountEur); await db.insert(schema.cashFlows).values({ portfolioId: "real", amount: -p.amountEur, kind: "to_pea", date: parisDate() }); // Nouveau plus haut de référence : la valeur de la cagnotte juste après le virement. const state = await getPortfolioState("real"); await db.update(schema.portfolios).set({ highWaterMark: state.equity }).where(eq(schema.portfolios.id, "real")); } } - await db.update(schema.actions).set({ status: answer, respondedAt: new Date() }).where(eq(schema.actions.id, id)); } /** Un trade réel que TU proposes : il passe par le même contrôle des risques que l'IA. */ export async function proposeManualRealBuy(symbol: string, stopPct: number) { - const quote = await getQuote(symbol); + const quote = await getQuote(symbol, { fresh: true }); if (!quote) throw new Error("Cours introuvable."); if (!isSupportedCurrency(quote.currency)) throw new Error("Seules les actions en euros ou en dollars sont gérées."); const fx = (await getFxToEur(quote.currency))!; diff --git a/src/lib/db/schema.ts b/src/lib/db/schema.ts index cbf8ca6..1812b7b 100644 --- a/src/lib/db/schema.ts +++ b/src/lib/db/schema.ts @@ -149,7 +149,7 @@ export const actions = pgTable("actions", { training: boolean("training").notNull(), // true = entraînement (réel pas encore débloqué) symbol: text("symbol"), payload: jsonb("payload").$type().notNull(), - status: text("status").notNull().default("pending"), // pending | done | skipped + status: text("status").notNull().default("pending"), // pending | done | skipped | expired respondedAt: timestamp("responded_at", { withTimezone: true }), }); diff --git a/src/lib/diagnostics.ts b/src/lib/diagnostics.ts index 7b840f6..09942c6 100644 --- a/src/lib/diagnostics.ts +++ b/src/lib/diagnostics.ts @@ -1,5 +1,5 @@ import "server-only"; -import { desc, gte, isNotNull } from "drizzle-orm"; +import { and, desc, gte, isNotNull } from "drizzle-orm"; import { aiEnabled, getAiSpend } from "./ai"; import { getDb, schema } from "./db"; import type { RunLog } from "./jobs"; @@ -15,7 +15,7 @@ export async function getDiagnostics() { db .select({ triage: schema.news.triage }) .from(schema.news) - .where(isNotNull(schema.news.triagedAt)), + .where(and(isNotNull(schema.news.triagedAt), gte(schema.news.publishedAt, since48h))), db.select().from(schema.signals).where(gte(schema.signals.createdAt, since7d)).orderBy(desc(schema.signals.createdAt)).limit(10), getAiSpend(), getKv("lastTickLog"), diff --git a/src/lib/engine/engine.test.ts b/src/lib/engine/engine.test.ts index 5f930a8..75cdc5f 100644 --- a/src/lib/engine/engine.test.ts +++ b/src/lib/engine/engine.test.ts @@ -1,11 +1,11 @@ import { describe, expect, it } from "vitest"; import { evaluateBuyLimit, evaluateExit, type Bar } from "./fills"; -import { checkBuy, tierFor } from "./risk"; +import { aiSimStuck, checkBuy, tierFor } from "./risk"; import { screenBars } from "./screen"; import { computePea } from "./pea"; -import { computeGate, maxDrawdownPct } from "./gate"; +import { benchmarkWithFlows, computeGate, equityWithoutDeposits, maxDrawdownPct } from "./gate"; import { circuitBreakerTripped, computeRatchet } from "./ratchet"; -import { addTradingDays } from "../time"; +import { addTradingDays, dueDeposits, easterSunday, isTradingDay } from "../time"; const bar = (date: string, open: number, high: number, low: number, close: number): Bar => ({ date, @@ -188,6 +188,72 @@ describe("cliquet et coupe-circuit", () => { }); }); +describe("calendrier Trade Republic", () => { + it("connaît Pâques et les jours fériés", () => { + expect(easterSunday(2026)).toBe("2026-04-05"); + expect(easterSunday(2027)).toBe("2027-03-28"); + expect(isTradingDay("2026-04-03")).toBe(false); // Vendredi saint + expect(isTradingDay("2026-04-06")).toBe(false); // lundi de Pâques + expect(isTradingDay("2026-12-24")).toBe(false); + expect(isTradingDay("2026-11-18")).toBe(true); + }); + it("saute les jours fériés en comptant les jours de bourse", () => { + expect(addTradingDays("2026-12-23", 1)).toBe("2026-12-28"); + expect(addTradingDays("2026-04-02", 1)).toBe("2026-04-07"); + }); + it("rattrape les virements mensuels manqués, sans doublon", () => { + expect(dueDeposits("2026-09-05", 5, null, "2026-11-18")).toEqual(["2026-09-05", "2026-10-05", "2026-11-05"]); + expect(dueDeposits("2026-09-05", 5, "2026-10", "2026-11-18")).toEqual(["2026-11-05"]); + expect(dueDeposits("2026-09-05", 5, "2026-11", "2026-11-18")).toEqual([]); + expect(dueDeposits("2026-11-20", 20, null, "2026-11-18")).toEqual([]); + }); +}); + +describe("cagnotte de l'IA avec versements mensuels", () => { + it("compare au S&P 500 avec les mêmes versements aux mêmes dates", () => { + const bars = [bar("2026-09-01", 100, 100, 100, 100), bar("2026-10-05", 50, 50, 50, 50)]; + // 200 € à 100 (2 parts) + 50 € à 50 (1 part) = 3 parts à 60 = 180 € pour 250 € versés. + const r = benchmarkWithFlows(bars, 60, [ + { date: "2026-09-01", amount: 200 }, + { date: "2026-10-05", amount: 50 }, + ]); + expect(r).toBeCloseTo(-28, 6); + }); + it("un versement ne masque pas une perte dans la pire baisse", () => { + const curve = equityWithoutDeposits( + [ + { date: "2026-09-01", equity: 200 }, + { date: "2026-10-01", equity: 150 }, + { date: "2026-10-06", equity: 200 }, + ], + [{ date: "2026-10-05", amount: 50 }], + ); + expect(curve).toEqual([200, 150, 150]); + expect(maxDrawdownPct(curve)).toBeCloseTo(25, 6); + }); + it("repère une cagnotte bloquée sous le minimum", () => { + expect(aiSimStuck({ cash: 140, positions: [], pendingOrders: [] })).toBe(true); + expect(aiSimStuck({ cash: 140, positions: [{}], pendingOrders: [] })).toBe(false); + expect(aiSimStuck({ cash: 190, positions: [], pendingOrders: [] })).toBe(false); + }); +}); + +describe("trous de cotation", () => { + it("vend à l'objectif à l'ouverture si le cours ouvre au-dessus, même si le stop est touché ensuite", () => { + const r = evaluateExit({ + entryDate: "2026-10-12", + today: "2026-10-13", + stop: 93, + target: 110, + maxExitDate: null, + bars: [bar("2026-10-13", 112, 113, 92, 95)], + currentPrice: 95, + brokerOpen: true, + }); + expect(r).toEqual({ price: 112, reason: "target", date: "2026-10-13" }); + }); +}); + describe("filtre d'idées sans IA", () => { const series = (closes: number[]): Bar[] => closes.map((c, i) => ({ date: `d${String(i).padStart(3, "0")}`, open: c, high: c, low: c, close: c })); diff --git a/src/lib/engine/fills.ts b/src/lib/engine/fills.ts index 9e3c5c1..d3c9b39 100644 --- a/src/lib/engine/fills.ts +++ b/src/lib/engine/fills.ts @@ -64,7 +64,10 @@ export function evaluateExit(input: ExitInput): ExitResult { for (const bar of bars) { if (bar.date <= entryDate || bar.date > today) continue; - // Si le stop et l'objectif sont touchés le même jour, on suppose le pire : le stop. + // Ouverture au-delà du stop ou de l'objectif (trou de cotation) : l'ordre part à l'ouverture. + if (stop !== null && bar.open <= stop) return { price: bar.open, reason: "stop", date: bar.date }; + if (target !== null && bar.open >= target) return { price: bar.open, reason: "target", date: bar.date }; + // Stop et objectif touchés dans la même journée sans trou : on ne sait pas lequel d'abord, on suppose le pire. if (stop !== null && bar.low <= stop) { return { price: Math.min(bar.open, stop), reason: "stop", date: bar.date }; } diff --git a/src/lib/engine/gate.ts b/src/lib/engine/gate.ts index abe6424..9223caa 100644 --- a/src/lib/engine/gate.ts +++ b/src/lib/engine/gate.ts @@ -3,13 +3,14 @@ * 3 mois de simulation, 20 trades clôturés, meilleur que le S&P 500 après frais et coût de l'IA, * pire baisse inférieure à 25 %, au moins 80 % des rendez-vous suivis. */ +import type { Bar } from "./fills"; export type GateInput = { simDays: number; closedTrades: number; - aiReturnPct: number; // rendement de la cagnotte IA, frais Trade Republic inclus + aiReturnPct: number; // rendement de la cagnotte IA sur l'argent versé, frais Trade Republic inclus aiCostEur: number; // coût cumulé de l'IA - initialCash: number; + initialCash: number; // argent versé au total (départ + versements mensuels) benchmarkReturnPct: number; maxDrawdownPct: number; actionsTotal: number; @@ -52,6 +53,38 @@ export function maxDrawdownPct(equities: number[]): number { return worst; } +export type Flow = { date: string; amount: number }; + +/** + * Ce qu'aurait rapporté le S&P 500 avec exactement les mêmes versements, aux mêmes dates + * (le capital de départ puis chaque versement mensuel achète des parts de l'ETF ce jour-là). + * Comparaison équitable avec une cagnotte qui reçoit de l'argent tous les mois. En %. + */ +export function benchmarkWithFlows(bars: Bar[], lastPrice: number | null, flows: Flow[]): number { + const sorted = [...bars].sort((a, b) => a.date.localeCompare(b.date)); + let units = 0; + let invested = 0; + for (const f of flows) { + const bar = sorted.find((b) => b.date >= f.date) ?? sorted.at(-1); + if (!bar) continue; + units += f.amount / bar.close; + invested += f.amount; + } + const price = lastPrice ?? sorted.at(-1)?.close; + if (!invested || !price) return 0; + return ((units * price) / invested - 1) * 100; +} + +/** + * Valeurs de la cagnotte sans l'effet des versements : on retire de chaque valeur l'argent versé + * après le départ. Un versement ne masque donc pas une perte dans le calcul de la pire baisse. + */ +export function equityWithoutDeposits(snaps: { date: string; equity: number }[], deposits: Flow[]): number[] { + return [...snaps] + .sort((a, b) => a.date.localeCompare(b.date)) + .map((s) => s.equity - deposits.filter((d) => d.date <= s.date).reduce((t, d) => t + d.amount, 0)); +} + function fmt(n: number): string { return `${n >= 0 ? "+" : ""}${n.toFixed(1)} %`; } diff --git a/src/lib/engine/risk.ts b/src/lib/engine/risk.ts index f79f413..782737e 100644 --- a/src/lib/engine/risk.ts +++ b/src/lib/engine/risk.ts @@ -109,6 +109,11 @@ export function checkBuy(input: RiskInput): RiskResult { }; } +/** La cagnotte n'a plus de quoi ouvrir une position (minimum 150 € + frais) et n'en détient aucune. */ +export function aiSimStuck(s: { cash: number; positions: unknown[]; pendingOrders: unknown[] }): boolean { + return s.positions.length === 0 && s.pendingOrders.length === 0 && s.cash < MIN_POSITION_EUR + 2 * FEE_EUR; +} + /** Fractions d'actions : 4 décimales, arrondi vers le bas pour ne jamais dépasser le budget. */ export function roundShares(n: number): number { return Math.floor(n * 10_000) / 10_000; diff --git a/src/lib/jobs.ts b/src/lib/jobs.ts index be4fbac..6b94a96 100644 --- a/src/lib/jobs.ts +++ b/src/lib/jobs.ts @@ -1,18 +1,18 @@ import "server-only"; -import { and, eq, isNull, ne } from "drizzle-orm"; +import { and, eq, gte, inArray, isNotNull, isNull, ne, sql } from "drizzle-orm"; import { aiEnabled, analyzeCandidate, AiUnavailableError, type Analysis } from "./ai"; import { getDb, schema } from "./db"; -import { checkBuy, MIN_CONFIDENCE } from "./engine/risk"; +import { aiSimStuck, checkBuy, MIN_CONFIDENCE, MIN_POSITION_EUR } from "./engine/risk"; import { circuitBreakerTripped, computeRatchet } from "./engine/ratchet"; import type { ActionPayload } from "./db/schema"; import { getBars, getFxToEur, getNextEarningsDate, getQuote, getQuotes } from "./market"; -import { collectNews, recentNews, triagePending } from "./news"; -import { getOpenSymbols, getPortfolioState, placeOrder, processAll, snapshotEquity, type PortfolioState } from "./portfolio"; +import { collectNews, purgeOldNews, recentNews, triagePending } from "./news"; +import { addCash, getOpenSymbols, getPortfolioState, placeOrder, processAll, snapshotEquity, type PortfolioState } from "./portfolio"; import { sendPush } from "./push"; -import { getKv, getSettings, setKv, SIM_INITIAL_CASH, updateSettings, type Settings } from "./settings"; +import { claimKv, claimLock, getKv, getSettings, releaseLock, setKv, SIM_INITIAL_CASH, updateSettings, type Settings } from "./settings"; import { getIdeas, refreshIdeas, type Idea } from "./ideas"; import { getGateStatus, totalDeposited } from "./stats"; -import { addDays, addTradingDays, isTradeRepublicOpen, isWeekend, parisDate, parisMinutes } from "./time"; +import { addDays, addTradingDays, dueDeposits, isTradeRepublicOpen, isTradingDay, parisDate, parisMinutes } from "./time"; import { findStock, UNIVERSE } from "./universe"; const UNIVERSE_COLLECT_EVERY_MS = 3 * 3_600_000; @@ -25,79 +25,152 @@ const AUTO_TICK_EVERY_MS = 20 * 60_000; * Ainsi l'app vit même sans la tâche planifiée GitHub (en local, ou si elle n'est pas branchée). */ export async function shouldAutoTick(): Promise { - const last = (await getKv("lastTickAt")) ?? 0; - if (Date.now() - last < AUTO_TICK_EVERY_MS) return false; - await setKv("lastTickAt", Date.now()); // réservé tout de suite : pas deux mises à jour en même temps - return true; + // Réservé de façon atomique : deux pages ouvertes en même temps ne lancent qu'une mise à jour. + return claimLock("autoTickAt", AUTO_TICK_EVERY_MS); +} + +/** Durée de vie du verrou de mise à jour : au-delà, on considère qu'elle a planté en route. */ +const TICK_LOCK_MS = 6 * 60_000; + +/** Lance une étape et note son échec dans le journal sans arrêter les suivantes. */ +async function step(log: string[], label: string, fn: () => Promise) { + try { + await fn(); + } catch (e) { + console.error(`[tick] ${label}`, e); + log.push(`⚠️ ${label} : ${e instanceof Error ? e.message : String(e)}`); + } } /** * Appelé toutes les 30 minutes par GitHub Actions, à l'ouverture de l'app, ou à la main. * Décide seul quoi faire selon l'heure de Paris. + * Une seule mise à jour à la fois (verrou en base), et une étape en panne n'empêche pas les autres. */ export async function tick(now = new Date()): Promise { + if (!(await claimLock("tickLock", TICK_LOCK_MS))) return ["Une mise à jour est déjà en cours : rien à faire."]; const log: string[] = []; - await setKv("lastTickAt", Date.now()); - const settings = await getSettings(); - const today = parisDate(now); - const minutes = parisMinutes(now); - - log.push(...(await processAll())); - await monthlyDeposit(settings, today, log); - - // Les actus et les idées se collectent tous les jours (week-end compris) pour que l'app ne soit jamais vide. - const held = await getOpenSymbols(["real", "ai_sim"]); - const last = (await getKv("lastUniverseCollect")) ?? 0; - const collectUniverse = Date.now() - last > UNIVERSE_COLLECT_EVERY_MS; - const symbols = collectUniverse ? UNIVERSE.map((s) => s.symbol) : held; - if (symbols.length) { - const n = await collectNews(symbols); - if (collectUniverse) await setKv("lastUniverseCollect", Date.now()); - log.push(`${n} nouvelles actus collectées`); - } try { - const t = await triagePending(log); - if (t) log.push(`${t} actus triées par l'IA`); - } catch (e) { - if (!(e instanceof AiUnavailableError)) throw e; - log.push(e.message); - } - log.push(...(await urgentAlerts())); - try { - const ideas = await refreshIdeas(); - log.push(`${ideas.items.length} idée(s) repérée(s) par le filtre`); - } catch (e) { - log.push(`Filtre d'idées indisponible : ${e instanceof Error ? e.message : e}`); - } + await setKv("lastTickAt", Date.now()); + const settings = await getSettings(); + const today = parisDate(now); + const minutes = parisMinutes(now); - if (!isWeekend(today)) { - const lastEvening = await getKv("lastEvening"); - if (lastEvening !== today && minutes >= settings.rendezvousMinutes - 30) { - log.push(...(await runEvening())); + await step(log, "Ordres et stops", async () => { + log.push(...(await processAll())); + }); + await step(log, "Virement mensuel", () => monthlyDeposit(settings, today, log)); + await step(log, "Versement simulé de l'IA", () => aiMonthlyDeposit(settings, today, log)); + + // Les actus et les idées se collectent tous les jours (week-end compris) pour que l'app ne soit jamais vide. + await step(log, "Collecte des actus", async () => { + const held = await getOpenSymbols(["real", "ai_sim"]); + const last = (await getKv("lastUniverseCollect")) ?? 0; + const collectUniverse = Date.now() - last > UNIVERSE_COLLECT_EVERY_MS; + const symbols = collectUniverse ? UNIVERSE.map((s) => s.symbol) : held; + if (!symbols.length) return; + const n = await collectNews(symbols); + if (collectUniverse) await setKv("lastUniverseCollect", Date.now()); + log.push(`${n} nouvelles actus collectées`); + }); + await step(log, "Tri des actus", async () => { + try { + const t = await triagePending(log); + if (t) log.push(`${t} actus triées par l'IA`); + } catch (e) { + if (!(e instanceof AiUnavailableError)) throw e; + log.push(e.message); + } + }); + await step(log, "Alertes urgentes", async () => { + log.push(...(await urgentAlerts())); + }); + await step(log, "Filtre d'idées", async () => { + const ideas = await refreshIdeas(); + log.push(`${ideas.items.length} idée(s) repérée(s) par le filtre`); + }); + await step(log, "Nettoyage", async () => { + if (!(await claimKv("lastPurge", today))) return; + const n = await purgeOldNews(); + if (n) log.push(`${n} vieilles actus supprimées`); + }); + + // Pas de rendez-vous le week-end ni les jours fériés de Trade Republic. + if (isTradingDay(today) && minutes >= settings.rendezvousMinutes - 30 && (await getKv("lastEvening")) !== today) { + await step(log, "Rendez-vous du soir", async () => { + log.push(...(await runEvening())); + }); } + await setKv("lastTickLog", { at: new Date().toISOString(), log }); + return log; + } finally { + await releaseLock("tickLock").catch(() => {}); } - await setKv("lastTickLog", { at: new Date().toISOString(), log }); - return log; } export type RunLog = { at: string; log: string[] }; -/** Virement mensuel vers le compte-titres (supposé programmé chez ta banque). */ +/** + * Virements mensuels vers le compte-titres (supposés programmés chez ta banque). + * Les mois manqués (app pas mise à jour pendant un moment) sont rattrapés, chacun à sa date. + */ async function monthlyDeposit(settings: Settings, today: string, log: string[]) { if (!settings.realDepositsStart || today < settings.realDepositsStart) return; - const month = today.slice(0, 7); - if (Number(today.slice(8, 10)) < settings.realDepositDay) return; - if ((await getKv("lastDeposit")) === month) return; + const dates = dueDeposits(settings.realDepositsStart, settings.realDepositDay, await getKv("lastDeposit"), today); + if (!dates.length) return; + // Réservé avant d'écrire : deux mises à jour simultanées ne comptent pas deux fois le même virement. + if (!(await claimKv("lastDeposit", dates.at(-1)!.slice(0, 7)))) return; const db = await getDb(); - const [p] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, "real")); const amount = settings.realMonthlyDeposit; - await db.insert(schema.cashFlows).values({ portfolioId: "real", amount, kind: "deposit", date: today }); + for (const date of dates) { + await db.insert(schema.cashFlows).values({ portfolioId: "real", amount, kind: "deposit", date }); + await db + .update(schema.portfolios) + .set({ + cash: sql`${schema.portfolios.cash} + ${amount}`, + highWaterMark: sql`${schema.portfolios.highWaterMark} + ${amount}`, + }) + .where(eq(schema.portfolios.id, "real")); + log.push(`Virement mensuel de ${amount} € du ${date} ajouté au compte-titres`); + } +} + +/** + * La cagnotte simulée de l'IA reçoit chaque mois le même versement que ton compte-titres + * (50 € par défaut), au même jour. Comme en vrai : après quelques pertes, elle n'est pas + * bloquée pour toujours sous le minimum de 150 € par position. + * Le premier versement tombe le mois qui suit le début de la simulation. + */ +async function aiMonthlyDeposit(settings: Settings, today: string, log: string[]) { + const amount = settings.realMonthlyDeposit; + if (!(amount > 0)) return; + const dates = dueDeposits(addDays(settings.simStartDate, 1), settings.realDepositDay, await getKv("lastAiDeposit"), today); + if (!dates.length) return; + if (!(await claimKv("lastAiDeposit", dates.at(-1)!.slice(0, 7)))) return; + const db = await getDb(); + for (const date of dates) { + await db.insert(schema.cashFlows).values({ portfolioId: "ai_sim", amount, kind: "deposit", date }); + await addCash("ai_sim", amount); + log.push(`Versement simulé de ${amount} € du ${date} ajouté à la cagnotte de l'IA`); + } +} + +/** + * Remet la cagnotte de l'IA à zéro (200 € neufs) et relance la simulation : les 3 mois + * et les 20 trades exigés repartent d'aujourd'hui. Les analyses passées restent visibles. + */ +export async function resetAiSim() { + const db = await getDb(); + await db.delete(schema.orders).where(eq(schema.orders.portfolioId, "ai_sim")); + await db.delete(schema.positions).where(eq(schema.positions.portfolioId, "ai_sim")); + await db.delete(schema.equitySnapshots).where(eq(schema.equitySnapshots.portfolioId, "ai_sim")); + await db.delete(schema.cashFlows).where(eq(schema.cashFlows.portfolioId, "ai_sim")); await db .update(schema.portfolios) - .set({ cash: p.cash + amount, highWaterMark: p.highWaterMark + amount }) - .where(eq(schema.portfolios.id, "real")); - await setKv("lastDeposit", month); - log.push(`Virement mensuel de ${amount} € ajouté au compte-titres`); + .set({ cash: SIM_INITIAL_CASH, initialCash: SIM_INITIAL_CASH, highWaterMark: SIM_INITIAL_CASH, createdAt: new Date() }) + .where(eq(schema.portfolios.id, "ai_sim")); + await db.delete(schema.kv).where(eq(schema.kv.key, "lastAiDeposit")); + await updateSettings({ simStartDate: parisDate() }); } /** Alerte immédiate seulement pour un événement grave et négatif sur une action que tu détiens vraiment. */ @@ -105,11 +178,21 @@ async function urgentAlerts(): Promise { const held = await getOpenSymbols(["real"]); if (!held.length) return []; const db = await getDb(); - const rows = await db.select().from(schema.news).where(isNull(schema.news.alertedAt)); + const rows = await db + .select() + .from(schema.news) + .where( + and( + isNull(schema.news.alertedAt), + isNotNull(schema.news.triagedAt), + inArray(schema.news.symbol, held), + gte(schema.news.publishedAt, new Date(Date.now() - 48 * 3_600_000)), + ), + ); const log: string[] = []; for (const n of rows) { const t = n.triage; - if (!held.includes(n.symbol) || !t || t.severity !== "high" || t.direction !== "negative") continue; + if (!t || t.severity !== "high" || t.direction !== "negative") continue; const name = findStock(n.symbol)?.name ?? n.symbol; await sendPush(`⚠️ Alerte sur ${name}`, `${t.reason} Ton stop te protège ; regarde l'app quand tu peux.`, "/actus"); await db.update(schema.news).set({ alertedAt: new Date() }).where(eq(schema.news.id, n.id)); @@ -161,13 +244,24 @@ export async function runEveningNow(): Promise { } /** Le rendez-vous du soir : analyse, décisions, fiches et notification. */ -export async function runEvening(opts: { manual?: boolean } = {}): Promise { +export async function runEvening(opts: { manual?: boolean; force?: boolean } = {}): Promise { + // Un seul rendez-vous en préparation à la fois (la tâche planifiée et un bouton peuvent tomber ensemble). + if (!(await claimLock("eveningLock", TICK_LOCK_MS))) return ["Un rendez-vous est déjà en préparation : patiente une minute."]; + try { + return await prepareEvening(opts); + } finally { + await releaseLock("eveningLock").catch(() => {}); + } +} + +async function prepareEvening(opts: { manual?: boolean; force?: boolean }): Promise { const log: string[] = []; const db = await getDb(); const today = parisDate(); const summary: string[] = []; // Une recherche à la demande ne remplace pas le vrai rendez-vous du soir (ni sa notification). - if (!opts.manual) await setKv("lastEvening", today); + if (opts.force) await setKv("lastEvening", today); + else if (!opts.manual && !(await claimKv("lastEvening", today))) return ["Le rendez-vous du jour est déjà prêt."]; const [rdv] = await db .insert(schema.rendezvous) @@ -179,6 +273,19 @@ export async function runEvening(opts: { manual?: boolean } = {}): Promise o.side === "buy").map((o) => o.symbol)])]; const candidates = pickCandidates(news, exclude, ideas); const results = await Promise.allSettled(candidates.map((c) => analyze(c, news, today))); for (const r of results) { @@ -226,7 +334,7 @@ export async function runEvening(opts: { manual?: boolean } = {}): Promise ({ equity: s.equity, @@ -333,6 +441,11 @@ export async function runEvening(opts: { manual?: boolean } = {}): Promise= 0 ? "+" : ""}${p.pnlOpenPct.toFixed(1)} %`); } + if (aiSimStuck(aiAfter)) { + summary.push( + `La cagnotte de l'IA n'a plus que ${aiAfter.cash.toFixed(0)} €, sous le minimum de ${MIN_POSITION_EUR} € par position. Elle reprendra après le prochain versement de ${settings.realMonthlyDeposit} €, ou tu peux la remettre à zéro dans l'onglet IA.`, + ); + } await snapshotEquity(); const cards = await db.select().from(schema.actions).where(and(eq(schema.actions.rendezvousId, rdv.id), eq(schema.actions.status, "pending"))); @@ -351,7 +464,7 @@ export async function runEvening(opts: { manual?: boolean } = {}): Promise>, today: string) { const stock = findStock(c.symbol)!; const [quote, bars, earnings] = await Promise.all([ - getQuote(c.symbol), + getQuote(c.symbol, { fresh: true }), getBars(c.symbol, addDays(today, -45)), getNextEarningsDate(c.symbol), ]); @@ -472,7 +585,7 @@ export function fmtShares(n: number): string { async function reviewRealPositions(real: PortfolioState, rdvId: number, today: string) { const db = await getDb(); - const quotes = await getQuotes(real.positions.map((p) => p.symbol)); + const quotes = await getQuotes(real.positions.map((p) => p.symbol), { fresh: true }); for (const p of real.positions) { const price = quotes.get(p.symbol)?.price; if (!price) continue; diff --git a/src/lib/market-cache.ts b/src/lib/market-cache.ts new file mode 100644 index 0000000..37f7a5c --- /dev/null +++ b/src/lib/market-cache.ts @@ -0,0 +1,160 @@ +import "server-only"; +import { inArray, sql } from "drizzle-orm"; +import { after } from "next/server"; +import { getDb, schema } from "./db"; + +/** + * Cache des données de marché (cours, historiques, actus Yahoo) à deux étages : + * 1. la mémoire du serveur (instantané, mais perdue à chaque nouveau serveur sur Vercel), + * 2. la base de données (partagée par tous les serveurs, ~10 ms). + * + * Yahoo met 0,3 à 2 s par appel : c'est ce qui rendait chaque onglet lent à s'ouvrir. + * Désormais une page affiche tout de suite la dernière valeur connue (« stale ») et la + * rafraîchit en arrière-plan, après l'envoi de la page. Seul le moteur d'ordres exige un + * cours frais (`requireFresh`), car il décide d'exécuter ou non un ordre. + */ + +export type Ttl = { freshMs: number; staleMs: number }; +type Stored = { at: number; v: unknown }; + +const g = globalThis as unknown as { __mktMem?: Map; __mktInflight?: Map> }; +const mem = (g.__mktMem ??= new Map()); +const inflight = (g.__mktInflight ??= new Map()); + +const dbKey = (key: string) => `m:${key}`; + +/** Lance un travail après l'envoi de la page (ou tout de suite hors d'une requête : tâche planifiée, tests). */ +function inBackground(fn: () => Promise) { + const run = () => fn().catch((e) => console.error("[market] rafraîchissement en arrière-plan", e)); + try { + after(run); + } catch { + void run(); + } +} + +async function readDb(keys: string[]): Promise> { + const out = new Map(); + if (!keys.length) return out; + try { + const db = await getDb(); + const rows = await db + .select({ key: schema.kv.key, value: schema.kv.value }) + .from(schema.kv) + .where(inArray(schema.kv.key, keys.map(dbKey))); + for (const r of rows) out.set(r.key.slice(2), r.value as Stored); + } catch (e) { + console.error("[market] lecture du cache impossible", e); + } + return out; +} + +async function writeDb(entries: [string, Stored][]) { + if (!entries.length) return; + try { + const db = await getDb(); + await db + .insert(schema.kv) + .values(entries.map(([key, value]) => ({ key: dbKey(key), value }))) + .onConflictDoUpdate({ target: schema.kv.key, set: { value: sql`excluded.value`, updatedAt: new Date() } }); + } catch (e) { + console.error("[market] écriture du cache impossible", e); + } +} + +function remember(key: string, v: unknown) { + const s = { at: Date.now(), v }; + mem.set(key, s); + return s; +} + +/** Va chercher la valeur à la source (une seule fois même si plusieurs pages la demandent en même temps). */ +function refresh(key: string, fetcher: () => Promise): Promise { + const running = inflight.get(key); + if (running) return running as Promise; + const p = (async () => { + const v = await fetcher(); + await writeDb([[key, remember(key, v)]]); + return v; + })().finally(() => inflight.delete(key)); + inflight.set(key, p); + return p; +} + +/** Une valeur, avec la logique « frais / encore utilisable / à recharger ». */ +export async function cached(key: string, ttl: Ttl, fetcher: () => Promise, opts: { requireFresh?: boolean } = {}): Promise { + const now = Date.now(); + let hit = mem.get(key); + if (!hit || now - hit.at >= ttl.freshMs) { + const fromDb = (await readDb([key])).get(key); + if (fromDb && (!hit || fromDb.at > hit.at)) { + hit = fromDb; + mem.set(key, fromDb); + } + } + if (hit && now - hit.at < ttl.freshMs) return hit.v as T; + if (hit && !opts.requireFresh && now - hit.at < ttl.staleMs) { + inBackground(() => refresh(key, fetcher)); + return hit.v as T; + } + return refresh(key, fetcher); +} + +/** + * Plusieurs valeurs d'un coup (les cours de 92 actions) : une seule lecture en base, + * puis un seul appel à la source pour toutes celles qui manquent ou sont trop vieilles. + */ +export async function cachedMany( + keys: string[], + ttl: Ttl, + fetchMany: (missing: string[]) => Promise>, + opts: { requireFresh?: boolean } = {}, +): Promise> { + const now = Date.now(); + const hits = new Map(); + const toRead: string[] = []; + for (const k of keys) { + const h = mem.get(k); + if (h) hits.set(k, h); + if (!h || now - h.at >= ttl.freshMs) toRead.push(k); + } + for (const [k, s] of await readDb(toRead)) { + const h = hits.get(k); + if (!h || s.at > h.at) { + hits.set(k, s); + mem.set(k, s); + } + } + + const mustFetch: string[] = []; + const canRefreshLater: string[] = []; + for (const k of keys) { + const h = hits.get(k); + if (h && now - h.at < ttl.freshMs) continue; + if (h && !opts.requireFresh && now - h.at < ttl.staleMs) canRefreshLater.push(k); + else mustFetch.push(k); + } + + const load = async (list: string[]) => { + const pending = list.filter((k) => !inflight.has(k)); + if (pending.length) { + const p = (async () => { + const got = await fetchMany(pending); + await writeDb([...got].map(([k, v]) => [k, remember(k, v)] as [string, Stored])); + return got; + })().finally(() => pending.forEach((k) => inflight.delete(k))); + pending.forEach((k) => inflight.set(k, p)); + } + await Promise.all(list.map((k) => inflight.get(k)).filter(Boolean)).catch(() => {}); + }; + + if (canRefreshLater.length) inBackground(() => load(canRefreshLater)); + if (mustFetch.length) await load(mustFetch); + + const out = new Map(); + for (const k of keys) { + const h = mem.get(k) ?? hits.get(k); + if (h) out.set(k, h.v as T); + } + return out; +} diff --git a/src/lib/market.ts b/src/lib/market.ts index c619aed..acfb01e 100644 --- a/src/lib/market.ts +++ b/src/lib/market.ts @@ -1,6 +1,7 @@ import "server-only"; import YahooFinance from "yahoo-finance2"; import type { Bar } from "./engine/fills"; +import { cached, cachedMany, type Ttl } from "./market-cache"; import { addDays, parisDate } from "./time"; import { findStock } from "./universe"; @@ -15,34 +16,23 @@ export type Quote = { changePct: number | null; }; +/** + * `fresh` : exiger un cours de moins d'une minute (exécution d'ordres, stops, achat). + * Sans `fresh`, une page peut afficher un cours de moins de 6 h, rafraîchi en arrière-plan. + */ +export type MarketOpts = { fresh?: boolean }; + 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). -// --------------------------------------------------------------------------- +// Durées de vie : « frais » = servi tel quel ; « encore utilisable » = affiché puis rafraîchi en arrière-plan. +const QUOTE_TTL: Ttl = { freshMs: 60_000, staleMs: 6 * 3_600_000 }; +const BARS_TTL: Ttl = { freshMs: 15 * 60_000, staleMs: 3 * 86_400_000 }; +const EARNINGS_TTL: Ttl = { freshMs: 12 * 3_600_000, staleMs: 7 * 86_400_000 }; +const NEWS_TTL: Ttl = { freshMs: 10 * 60_000, staleMs: 6 * 3_600_000 }; +const SEARCH_TTL: Ttl = { freshMs: 24 * 3_600_000, staleMs: 7 * 86_400_000 }; -type Entry = { at: number; value: Promise }; -const g = globalThis as unknown as { __marketCache?: Map }; -const cache = (g.__marketCache ??= new Map()); - -function memo(key: string, ttlMs: number, fn: () => Promise): Promise { - const hit = cache.get(key); - if (hit && Date.now() - hit.at < ttlMs) return hit.value as Promise; - 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(); -const inflightQuotes = new Map>(); - -async function fetchQuotes(symbols: string[]): Promise { +async function fetchQuotes(symbols: string[]): Promise> { + const out = new Map(); // 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); @@ -55,49 +45,43 @@ async function fetchQuotes(symbols: string[]): Promise { } 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, - }, + out.set(r.symbol, { + 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> { - 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(); - 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 { - return (await getQuotes([symbol])).get(symbol) ?? null; +export async function getQuotes(symbols: string[], opts: MarketOpts = {}): Promise> { + const unique = [...new Set(symbols)]; + const byKey = await cachedMany( + unique.map((s) => `q:${s}`), + QUOTE_TTL, + async (keys) => { + const got = await fetchQuotes(keys.map((k) => k.slice(2))); + return new Map([...got].map(([s, q]) => [`q:${s}`, q])); + }, + { requireFresh: opts.fresh }, + ); + const out = new Map(); + for (const [k, q] of byKey) out.set(k.slice(2), q as Quote); + return out; +} + +export async function getQuote(symbol: string, opts: MarketOpts = {}): Promise { + return (await getQuotes([symbol], opts)).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 { +export async function getFxToEur(currency: string, opts: MarketOpts = {}): Promise { if (currency === "EUR") return 1; if (currency !== "USD") return null; - const q = await getQuote("EURUSD=X"); + const q = await getQuote("EURUSD=X", opts); return q ? 1 / q.price : null; } @@ -105,75 +89,70 @@ export function isSupportedCurrency(currency: string): boolean { return SUPPORTED_CURRENCIES.has(currency); } +type StoredBars = { from: string; bars: Bar[] }; + /** * 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. + * On garde au moins 9 mois d'historique par action, puis on découpe : une seule requête + * sert le graphique, le PEA, l'indice et le moteur. Les jours passés ne changent plus, + * donc un historique de la veille reste utilisable (le cours du jour vient de getQuote). */ -const BARS_TTL_MS = 15 * 60_000; -const barsFrom = new Map(); - export async function getBars(symbol: string, fromDate: string): Promise { 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 from = fromDate < minFrom ? fromDate : minFrom; + const load = async (): Promise => { const chart = await yf.chart(symbol, { period1: from, interval: "1d" }); - return chart.quotes + const bars = 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); + .map((q) => ({ date: parisDate(q.date), open: q.open!, high: q.high!, low: q.low!, close: q.close! })); + return { from, bars }; + }; + let stored = await cached(`bars:${symbol}`, BARS_TTL, load); + // Historique en cache trop court (ex. PEA commencé il y a plus de 9 mois) : on recharge plus loin. + if (stored.from > fromDate) stored = await cached(`bars:${symbol}`, { freshMs: 0, staleMs: 0 }, load); + return stored.bars.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 { - return memo(`earnings:${symbol}`, 12 * 3_600_000, async () => { + const today = parisDate(); + const dates = await cached(`earnings:${symbol}`, EARNINGS_TTL, 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; + return (s.calendarEvents?.earnings?.earningsDate ?? []).map((d) => parisDate(d)); } catch { - return null; + return [] as string[]; } }); + return dates.filter((d) => d >= today).sort()[0] ?? 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 { - 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 async function getNews(symbol: string, opts: MarketOpts = {}): Promise { + const rows = await cached( + `news:${symbol}`, + NEWS_TTL, + 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 })); + }, + { requireFresh: opts.fresh }, + ); + // Les dates reviennent du cache en texte : on les retransforme en dates. + return rows.map((n) => ({ ...n, publishedAt: new Date(n.publishedAt) })); } 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 { - return memo(`search:${query.toLowerCase()}`, 10 * 60_000, async () => { + return cached(`search:${query.toLowerCase()}`, SEARCH_TTL, async () => { const res = await yf.search(query, { quotesCount: 10, newsCount: 0 }); const hits: SearchHit[] = []; for (const q of res.quotes) { diff --git a/src/lib/news.ts b/src/lib/news.ts index c9a8d6c..62299a1 100644 --- a/src/lib/news.ts +++ b/src/lib/news.ts @@ -1,5 +1,5 @@ import "server-only"; -import { desc, eq, gte, isNull } from "drizzle-orm"; +import { and, desc, eq, gte, isNull, lt } from "drizzle-orm"; import { aiEnabled, triageNews, TriageFailedError } from "./ai"; import { getDb, schema } from "./db"; import { getNews } from "./market"; @@ -36,7 +36,14 @@ export async function collectNews(symbols: string[]): Promise { export async function triagePending(log: string[] = []): Promise { if (!aiEnabled()) return 0; const db = await getDb(); - const pending = await db.select().from(schema.news).where(isNull(schema.news.triagedAt)); + // Seulement les actus récentes, et pas plus de 150 par passage : la mise à jour reste rapide + // et une panne passagère ne fait pas exploser la facture IA d'un coup au retour. + const pending = await db + .select() + .from(schema.news) + .where(and(isNull(schema.news.triagedAt), gte(schema.news.publishedAt, new Date(Date.now() - MAX_AGE_HOURS * 3_600_000)))) + .orderBy(desc(schema.news.publishedAt)) + .limit(150); let done = 0; for (let i = 0; i < pending.length; i += 25) { const batch = pending.slice(i, i + 25); @@ -75,6 +82,16 @@ export async function triagePending(log: string[] = []): Promise { return done; } +/** Supprime les actus de plus de 30 jours : la table ne grossit plus sans fin (et les pages restent rapides). */ +export async function purgeOldNews(days = 30): Promise { + const db = await getDb(); + const rows = await db + .delete(schema.news) + .where(lt(schema.news.publishedAt, new Date(Date.now() - days * 86_400_000))) + .returning({ id: schema.news.id }); + return rows.length; +} + export type NewsRow = typeof schema.news.$inferSelect; /** Nombre d'actus récentes par action (pour la liste des actions). */ diff --git a/src/lib/portfolio.ts b/src/lib/portfolio.ts index b44a73d..edbadd6 100644 --- a/src/lib/portfolio.ts +++ b/src/lib/portfolio.ts @@ -1,9 +1,9 @@ import "server-only"; -import { and, eq, inArray } from "drizzle-orm"; +import { and, eq, inArray, sql } from "drizzle-orm"; import { getDb, schema } from "./db"; import { evaluateBuyLimit, evaluateExit, FEE_EUR, withSlippage, type Bar } from "./engine/fills"; import { getBars, getFxToEur, getQuotes, type Quote } from "./market"; -import { addDays, isTradeRepublicOpen, parisDate } from "./time"; +import { addTradingDays, isTradeRepublicOpen, parisDate } from "./time"; export type PortfolioId = "ai_sim" | "sandbox" | "real"; export type Position = typeof schema.positions.$inferSelect; @@ -97,7 +97,7 @@ export async function placeOrder(o: NewOrder): Promise<{ order: Order; filled: b .values({ ...o, limitPrice: o.limitPrice ?? null, - validUntil: o.validUntil ?? (o.type === "limit" ? addDays(parisDate(), 1) : null), + validUntil: o.validUntil ?? (o.type === "limit" ? addTradingDays(parisDate(), 1) : null), }) .returning(); const filled = await tryFillOrder(order); @@ -116,14 +116,13 @@ async function tryFillOrder(order: Order, bars?: Bar[]): Promise { const now = new Date(); const today = parisDate(now); const open = isTradeRepublicOpen(now); - const quote = (await getQuotes([order.symbol])).get(order.symbol) ?? null; - const fx = await getFxToEur(order.currency); + const quote = (await getQuotes([order.symbol], { fresh: true })).get(order.symbol) ?? null; + const fx = await getFxToEur(order.currency, { fresh: true }); if (fx === null) return false; if (order.type === "market") { if (!open || !quote) return false; - await executeOrder(order, quote.price, fx); - return true; + return executeOrder(order, quote.price, fx); } if (order.side === "buy" && order.limitPrice !== null) { const createdDate = parisDate(order.createdAt); @@ -136,29 +135,54 @@ async function tryFillOrder(order: Order, bars?: Bar[]): Promise { currentPrice: quote?.price ?? null, brokerOpen: open, }); - if (res.status === "filled") { - await executeOrder(order, res.price, fx); - return true; - } + if (res.status === "filled") return executeOrder(order, res.price, fx); if (res.status === "expired") { const db = await getDb(); - await db.update(schema.orders).set({ status: "expired" }).where(eq(schema.orders.id, order.id)); + await db + .update(schema.orders) + .set({ status: "expired" }) + .where(and(eq(schema.orders.id, order.id), eq(schema.orders.status, "pending"))); } } return false; } -async function executeOrder(order: Order, rawPrice: number, fx: number) { +/** Change le statut d'un ordre encore en attente. Renvoie false si quelqu'un l'a déjà traité. */ +async function settleOrder(orderId: number, set: Partial): Promise { + const db = await getDb(); + const rows = await db + .update(schema.orders) + .set(set) + .where(and(eq(schema.orders.id, orderId), eq(schema.orders.status, "pending"))) + .returning({ id: schema.orders.id }); + return rows.length > 0; +} + +/** Ajoute (ou retire) des liquidités en une seule instruction : deux mises à jour simultanées ne s'écrasent pas. */ +export async function addCash(portfolioId: string, amount: number) { + const db = await getDb(); + await db + .update(schema.portfolios) + .set({ cash: sql`${schema.portfolios.cash} + ${amount}` }) + .where(eq(schema.portfolios.id, portfolioId)); +} + +/** + * Exécute un ordre. L'ordre est d'abord « réservé » (en attente → exécuté) de façon atomique : + * si deux mises à jour tournent en même temps, une seule l'exécute. + */ +async function executeOrder(order: Order, rawPrice: number, fx: number): Promise { const db = await getDb(); const price = withSlippage(rawPrice, order.side as "buy" | "sell"); if (order.side === "buy") { const [p] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, order.portfolioId)); const cost = order.shares * price * fx + FEE_EUR; if (cost > p.cash + 0.01) { - await db.update(schema.orders).set({ status: "cancelled", note: "Pas assez de liquidités." }).where(eq(schema.orders.id, order.id)); - return; + await settleOrder(order.id, { status: "cancelled", note: "Pas assez de liquidités." }); + return false; } - await db.update(schema.portfolios).set({ cash: p.cash - cost }).where(eq(schema.portfolios.id, p.id)); + if (!(await settleOrder(order.id, { status: "filled", filledAt: new Date(), fillPrice: price }))) return false; + await addCash(p.id, -cost); const [pos] = await db .insert(schema.positions) .values({ @@ -177,27 +201,30 @@ async function executeOrder(order: Order, rawPrice: number, fx: number) { signalId: order.signalId, }) .returning(); - await db - .update(schema.orders) - .set({ status: "filled", filledAt: new Date(), fillPrice: price, positionId: pos.id }) - .where(eq(schema.orders.id, order.id)); - } else if (order.positionId) { - const [pos] = await db.select().from(schema.positions).where(eq(schema.positions.id, order.positionId)); - if (!pos || pos.status !== "open") return; - await closePosition(pos, rawPrice, fx, "manual"); - await db.update(schema.orders).set({ status: "filled", filledAt: new Date(), fillPrice: price }).where(eq(schema.orders.id, order.id)); + await db.update(schema.orders).set({ positionId: pos.id }).where(eq(schema.orders.id, order.id)); + return true; } + if (!order.positionId) return false; + const [pos] = await db.select().from(schema.positions).where(eq(schema.positions.id, order.positionId)); + if (!pos || pos.status !== "open") { + // Position déjà vendue (stop, objectif...) : l'ordre de vente n'a plus d'objet, il ne doit pas rester en attente. + await settleOrder(order.id, { status: "cancelled", note: "Position déjà clôturée." }); + return false; + } + if (!(await settleOrder(order.id, { status: "filled", filledAt: new Date(), fillPrice: price }))) return false; + return closePosition(pos, rawPrice, fx, "manual"); } -/** Clôture une position (prix brut, glissement et frais appliqués ici). */ -export async function closePosition(pos: Position, rawPrice: number, fx: number, reason: string, applySlippage = true) { +/** + * Clôture une position (prix brut, glissement et frais appliqués ici). + * Atomique : une position ne peut être vendue qu'une fois. Renvoie false si elle l'était déjà. + */ +export async function closePosition(pos: Position, rawPrice: number, fx: number, reason: string, applySlippage = true): Promise { const db = await getDb(); const price = applySlippage ? withSlippage(rawPrice, "sell") : rawPrice; const proceeds = pos.shares * price * fx - FEE_EUR; const cost = pos.shares * pos.entryPrice * pos.entryFx + pos.feesEur; - const [p] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, pos.portfolioId)); - await db.update(schema.portfolios).set({ cash: p.cash + proceeds }).where(eq(schema.portfolios.id, p.id)); - await db + const closed = await db .update(schema.positions) .set({ status: "closed", @@ -208,7 +235,16 @@ export async function closePosition(pos: Position, rawPrice: number, fx: number, feesEur: pos.feesEur + FEE_EUR, pnlEur: proceeds - cost, }) - .where(eq(schema.positions.id, pos.id)); + .where(and(eq(schema.positions.id, pos.id), eq(schema.positions.status, "open"))) + .returning({ id: schema.positions.id }); + if (!closed.length) return false; + await addCash(pos.portfolioId, proceeds); + // Les ordres de vente encore en attente sur cette position n'ont plus d'objet. + await db + .update(schema.orders) + .set({ status: "cancelled", note: "Position déjà clôturée." }) + .where(and(eq(schema.orders.positionId, pos.id), eq(schema.orders.side, "sell"), eq(schema.orders.status, "pending"))); + return true; } export async function cancelOrder(orderId: number) { @@ -236,7 +272,7 @@ export async function processAll(): Promise { const now = new Date(); const today = parisDate(now); const brokerOpen = isTradeRepublicOpen(now); - const quotes = await getQuotes(symbols); + const quotes = await getQuotes(symbols, { fresh: true }); const barsCache = new Map(); const barsFor = async (symbol: string, from: string) => { const key = `${symbol}:${from}`; @@ -266,7 +302,7 @@ export async function processAll(): Promise { brokerOpen, }); if (!res) continue; - await closePosition(pos, res.price, fx, res.reason); + if (!(await closePosition(pos, res.price, fx, res.reason))) continue; const label = { stop: "stop déclenché", target: "objectif atteint", time: "durée maximale atteinte" }[res.reason]; log.push(`${pos.name} vendue (${label}) — ${pos.portfolioId}`); } diff --git a/src/lib/real.ts b/src/lib/real.ts index 8f05462..2aafc65 100644 --- a/src/lib/real.ts +++ b/src/lib/real.ts @@ -1,5 +1,5 @@ import "server-only"; -import { eq } from "drizzle-orm"; +import { eq, sql } from "drizzle-orm"; import { getDb, schema } from "./db"; import { FEE_EUR } from "./engine/fills"; import { getFxToEur, getQuote, isSupportedCurrency } from "./market"; @@ -21,11 +21,14 @@ async function realPortfolio() { /** Tu as versé de l'argent sur ton compte-titres (compte dans les versements : sert au coupe-circuit et au cliquet). */ export async function recordDeposit(amount: number, date = parisDate()) { if (!Number.isFinite(amount) || amount === 0) throw new Error("Montant invalide."); - const { db, p } = await realPortfolio(); + const db = await getDb(); await db.insert(schema.cashFlows).values({ portfolioId: "real", amount, kind: amount > 0 ? "deposit" : "withdrawal", date }); await db .update(schema.portfolios) - .set({ cash: p.cash + amount, highWaterMark: Math.max(0, p.highWaterMark + amount) }) + .set({ + cash: sql`${schema.portfolios.cash} + ${amount}`, + highWaterMark: sql`greatest(0, ${schema.portfolios.highWaterMark} + ${amount})`, + }) .where(eq(schema.portfolios.id, "real")); } @@ -55,10 +58,13 @@ export async function addHolding(input: { if (!quote) throw new Error("Action introuvable."); if (!isSupportedCurrency(quote.currency)) throw new Error("Seules les actions en euros ou en dollars sont gérées."); const fx = (await getFxToEur(quote.currency)) ?? 1; - const { db, p } = await realPortfolio(); + const db = await getDb(); if (input.paidFromCash) { const cost = input.shares * input.price * fx + FEE_EUR; - await db.update(schema.portfolios).set({ cash: Math.max(0, p.cash - cost) }).where(eq(schema.portfolios.id, "real")); + await db + .update(schema.portfolios) + .set({ cash: sql`greatest(0, ${schema.portfolios.cash} - ${cost})` }) + .where(eq(schema.portfolios.id, "real")); } await db.insert(schema.positions).values({ portfolioId: "real", diff --git a/src/lib/settings.ts b/src/lib/settings.ts index 8d1a604..ee7361d 100644 --- a/src/lib/settings.ts +++ b/src/lib/settings.ts @@ -1,6 +1,6 @@ import "server-only"; import { cache } from "react"; -import { eq } from "drizzle-orm"; +import { eq, sql } from "drizzle-orm"; import { getDb, schema } from "./db"; import type { PeaPlan } from "./engine/pea"; import { parisDate } from "./time"; @@ -67,6 +67,48 @@ export async function setKv(key: string, value: unknown): Promise { .onConflictDoUpdate({ target: schema.kv.key, set: { value, updatedAt: new Date() } }); } +/** + * Écrit `value` seulement si la clé n'a pas déjà cette valeur, de façon atomique. + * Renvoie true si c'est nous qui l'avons écrite : sert à faire une chose une seule fois + * (virement du mois, rendez-vous du jour) même si deux mises à jour tournent en même temps. + */ +export async function claimKv(key: string, value: unknown): Promise { + const db = await getDb(); + const rows = await db + .insert(schema.kv) + .values({ key, value }) + .onConflictDoUpdate({ + target: schema.kv.key, + set: { value, updatedAt: new Date() }, + setWhere: sql`${schema.kv.value} is distinct from ${JSON.stringify(value)}::jsonb`, + }) + .returning({ key: schema.kv.key }); + return rows.length > 0; +} + +/** + * Verrou atomique avec durée de vie : renvoie true si on l'a pris (personne ne l'a pris + * depuis `ttlMs`). Un verrou oublié (serveur coupé en route) expire tout seul. + */ +export async function claimLock(key: string, ttlMs: number): Promise { + const db = await getDb(); + const now = Date.now(); + const rows = await db + .insert(schema.kv) + .values({ key, value: now }) + .onConflictDoUpdate({ + target: schema.kv.key, + set: { value: now, updatedAt: new Date() }, + setWhere: sql`jsonb_typeof(${schema.kv.value}) <> 'number' or (${schema.kv.value})::text::numeric < ${now - ttlMs}`, + }) + .returning({ key: schema.kv.key }); + return rows.length > 0; +} + +export async function releaseLock(key: string): Promise { + await setKv(key, 0); +} + const g = globalThis as unknown as { __setupDone?: boolean }; /** Crée les réglages et les trois portefeuilles au premier lancement (une seule fois par serveur). */ diff --git a/src/lib/stats.ts b/src/lib/stats.ts index 01b5e99..6ec1a72 100644 --- a/src/lib/stats.ts +++ b/src/lib/stats.ts @@ -2,7 +2,7 @@ import "server-only"; import { and, eq, ne } from "drizzle-orm"; import { aiSpendSince } from "./ai"; import { getDb, schema } from "./db"; -import { computeGate, maxDrawdownPct, type Criterion } from "./engine/gate"; +import { benchmarkWithFlows, computeGate, equityWithoutDeposits, maxDrawdownPct, type Criterion, type Flow } from "./engine/gate"; import { computePea, type PeaResult } from "./engine/pea"; import { getBars, getFxToEur, getQuote } from "./market"; import { getPortfolioState, type PortfolioState } from "./portfolio"; @@ -33,11 +33,34 @@ export type GateStatus = { aiCostEur: number; }; +/** Versements mensuels simulés reçus par la cagnotte de l'IA (comme ton vrai virement). */ +export async function aiDeposits(): Promise { + const db = await getDb(); + const rows = await db + .select({ date: schema.cashFlows.date, amount: schema.cashFlows.amount }) + .from(schema.cashFlows) + .where(and(eq(schema.cashFlows.portfolioId, "ai_sim"), eq(schema.cashFlows.kind, "deposit"))); + return rows; +} + +/** Performance de la cagnotte IA sur tout l'argent qu'elle a reçu (départ + versements), en %. */ +export function aiPerformance(ai: PortfolioState, deposits: Flow[]) { + const contributed = ai.initialCash + deposits.reduce((s, d) => s + d.amount, 0); + return { contributed, pct: contributed > 0 ? (ai.equity / contributed - 1) * 100 : 0 }; +} + +/** Le S&P 500 avec les mêmes versements que la cagnotte de l'IA, aux mêmes dates. */ +async function benchmarkForAi(s: Settings, initialCash: number, deposits: Flow[]): Promise { + const symbol = benchmarkSymbol(s); + const [bars, quote] = await Promise.all([getBars(symbol, s.simStartDate).catch((e) => (console.error("[indice]", e), [])), getQuote(symbol)]); + return benchmarkWithFlows(bars, quote?.price ?? null, [{ date: s.simStartDate, amount: initialCash }, ...deposits]); +} + export async function getGateStatus(settings?: Settings, ai?: PortfolioState): Promise { const s = settings ?? (await getSettings()); const db = await getDb(); // Tout est lancé en parallèle : la page attend la requête la plus lente, pas leur somme. - const [aiState, closed, snaps, acts, usdToEur, spent, bench] = await Promise.all([ + const [aiState, closed, snaps, acts, usdToEur, spent, deposits] = await Promise.all([ ai ?? getPortfolioState("ai_sim"), db .select({ id: schema.positions.id }) @@ -47,20 +70,24 @@ export async function getGateStatus(settings?: Settings, ai?: PortfolioState): P db.select({ status: schema.actions.status }).from(schema.actions).where(ne(schema.actions.kind, "to_pea")), getFxToEur("USD").then((x) => x ?? 0.9), aiSpendSince(s.simStartDate), - benchmarkReturnPct(benchmarkSymbol(s), s.simStartDate), + aiDeposits(), ]); const aiCostEur = spent * usdToEur; + const perf = aiPerformance(aiState, deposits); + const bench = await benchmarkForAi(s, aiState.initialCash, deposits); + const curve = equityWithoutDeposits([...snaps, { date: parisDate(), equity: aiState.equity }], deposits); const gate = computeGate({ simDays: daysBetween(s.simStartDate, parisDate()), closedTrades: closed.length, - aiReturnPct: (aiState.equity / aiState.initialCash - 1) * 100, + aiReturnPct: perf.pct, aiCostEur, - initialCash: aiState.initialCash, + initialCash: perf.contributed, benchmarkReturnPct: bench, - maxDrawdownPct: maxDrawdownPct([...snaps.sort((a, b) => a.date.localeCompare(b.date)).map((x) => x.equity), aiState.equity]), + maxDrawdownPct: maxDrawdownPct(curve), actionsTotal: acts.length, - actionsAnswered: acts.filter((a) => a.status !== "pending").length, + // « Expirée » = fiche restée sans réponse : elle ne compte pas comme suivie. + actionsAnswered: acts.filter((a) => a.status === "done" || a.status === "skipped").length, }); return { unlocked: gate.unlocked, @@ -74,9 +101,10 @@ export async function getGateStatus(settings?: Settings, ai?: PortfolioState): P export type Leaderboard = { label: string; pct: number; detail: string }[]; export async function getLeaderboard(settings: Settings, ai: PortfolioState, sandbox: PortfolioState): Promise { - const bench = await benchmarkReturnPct(benchmarkSymbol(settings), settings.simStartDate); + const [bench, deposits] = await Promise.all([benchmarkReturnPct(benchmarkSymbol(settings), settings.simStartDate), aiDeposits()]); + const perf = aiPerformance(ai, deposits); const rows = [ - { label: "L'IA", pct: (ai.equity / ai.initialCash - 1) * 100, detail: eur(ai.equity) }, + { label: "L'IA", pct: perf.pct, detail: eur(ai.equity) }, { label: "Toi", pct: (sandbox.equity / sandbox.initialCash - 1) * 100, detail: eur(sandbox.equity) }, { label: "S&P 500", pct: bench, detail: "sans rien faire" }, ]; diff --git a/src/lib/time.ts b/src/lib/time.ts index e153f49..dfe43b8 100644 --- a/src/lib/time.ts +++ b/src/lib/time.ts @@ -40,26 +40,82 @@ export function addDays(date: string, n: number): string { return d.toISOString().slice(0, 10); } -/** Ajoute n jours de bourse (lundi-vendredi ; les jours fériés sont ignorés). */ +/** Dimanche de Pâques (algorithme grégorien anonyme), au format AAAA-MM-JJ. */ +export function easterSunday(year: number): string { + const a = year % 19; + const b = Math.floor(year / 100); + const c = year % 100; + const d = Math.floor(b / 4); + const e = b % 4; + const f = Math.floor((b + 8) / 25); + const g = Math.floor((b - f + 1) / 3); + const h = (19 * a + b - d - g + 15) % 30; + const i = Math.floor(c / 4); + const k = c % 4; + const l = (32 + 2 * e + 2 * i - h - k) % 7; + const m = Math.floor((a + 11 * h + 22 * l) / 451); + const month = Math.floor((h + l - 7 * m + 114) / 31); + const day = ((h + l - 7 * m + 114) % 31) + 1; + return `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`; +} + +/** + * Jours fériés où Trade Republic (LS Exchange) ne cote pas : 1er janvier, Vendredi saint, + * lundi de Pâques, 24, 25, 26 et 31 décembre. + */ +export function isTradeRepublicHoliday(date: string): boolean { + if (["01-01", "12-24", "12-25", "12-26", "12-31"].includes(date.slice(5))) return true; + const easter = easterSunday(Number(date.slice(0, 4))); + return date === addDays(easter, -2) || date === addDays(easter, 1); +} + +/** Jour où l'on peut passer des ordres chez Trade Republic. */ +export function isTradingDay(date: string): boolean { + return !isWeekend(date) && !isTradeRepublicHoliday(date); +} + +/** Ajoute n jours de bourse (hors week-ends et jours fériés de Trade Republic). */ export function addTradingDays(date: string, n: number): string { let d = date; let left = n; while (left > 0) { d = addDays(d, 1); - if (!isWeekend(d)) left--; + if (isTradingDay(d)) left--; } return d; } +/** + * Dates des virements mensuels dus et pas encore comptés : un par mois, à partir du mois qui + * suit `lastMonth` (AAAA-MM, ou null) jusqu'à aujourd'hui, jamais avant `start`. + * Rattrape les mois où l'app ne s'est pas mise à jour : aucun virement n'est oublié. + */ +export function dueDeposits(start: string, day: number, lastMonth: string | null, today: string): string[] { + const out: string[] = []; + let [y, m] = start.split("-").map(Number); + for (let guard = 0; guard < 600; guard++) { + const month = `${y}-${String(m).padStart(2, "0")}`; + const date = `${month}-${String(day).padStart(2, "0")}`; + if (date > today) break; + if (date >= start && (!lastMonth || month > lastMonth)) out.push(date); + m++; + if (m > 12) { + m = 1; + y++; + } + } + return out; +} + export function daysBetween(from: string, to: string): number { return Math.round( (new Date(`${to}T12:00:00Z`).getTime() - new Date(`${from}T12:00:00Z`).getTime()) / 86_400_000, ); } -/** Trade Republic (LS Exchange) : du lundi au vendredi, de 7h30 à 23h00, heure de Paris. */ +/** Trade Republic (LS Exchange) : du lundi au vendredi hors jours fériés, de 7h30 à 23h00, heure de Paris. */ export function isTradeRepublicOpen(d: Date = new Date()): boolean { - if (isWeekend(parisDate(d))) return false; + if (!isTradingDay(parisDate(d))) return false; const m = parisMinutes(d); return m >= 7 * 60 + 30 && m < 23 * 60; }