import "server-only"; import { and, eq, gte, inArray, isNotNull, isNull, ne, sql } from "drizzle-orm"; import { aiEnabled, AiUnavailableError, dailyCommittee, type Analysis, type HoldingContext } from "./ai"; import { getDb, schema } from "./db"; import { aiSimStuck, checkBuy, clampStopPct, 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, purgeOldNews, recentNews, triagePending } from "./news"; import { addCash, getOpenSymbols, getPortfolioState, placeOrder, processAll, snapshotEquity, type PortfolioState, type PositionView } from "./portfolio"; import { sendPush } from "./push"; 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, dueDeposits, isTradeRepublicOpen, isTradingDay, parisDate, parisMinutes } from "./time"; import { findStock, UNIVERSE } from "./universe"; const UNIVERSE_COLLECT_EVERY_MS = 3 * 3_600_000; const AUTO_TICK_EVERY_MS = 20 * 60_000; /** * Mise à jour automatique quand tu ouvres l'app : si la dernière mise à jour date de plus de * 20 minutes, on la relance en arrière-plan (après l'affichage de la page, sans la ralentir). * 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 { // 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[] = []; try { await setKv("lastTickAt", Date.now()); const settings = await getSettings(); const today = parisDate(now); const minutes = parisMinutes(now); 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(() => {}); } } export type RunLog = { at: string; log: string[] }; /** * 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 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 amount = settings.realMonthlyDeposit; 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 90 € 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: 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. */ 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( 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 (!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)); log.push(`Alerte envoyée : ${name}`); } return log; } type Candidate = { symbol: string; score: number; newsIds: string[]; technical?: string }; /** Nombre d'actions étudiées chaque jour par le comité de l'IA. */ const MAX_CANDIDATES = 6; /** Au plus 4 viennent de l'actualité : on garde de la place pour les replis du filtre technique. */ const MAX_FROM_NEWS = 4; /** * Les candidates du jour : d'abord les actions portées par une actu positive (pertinence ≥ 5/10), * puis les meilleures idées du filtre technique (repli dans une tendance haussière). * Il y a donc presque toujours de quoi comparer, même un jour sans grande nouvelle. */ function pickCandidates(rows: Awaited>, exclude: string[], ideas: Idea[]): Candidate[] { const bySymbol = new Map(); for (const n of rows) { const t = n.triage; if (!t || t.direction !== "positive" || t.relevance < 5 || exclude.includes(n.symbol) || !findStock(n.symbol)) continue; const c = bySymbol.get(n.symbol) ?? { symbol: n.symbol, score: 0, newsIds: [] }; c.score = Math.max(c.score, t.relevance) + 0.5 * c.newsIds.length; c.newsIds.push(n.id); bySymbol.set(n.symbol, c); } const out = [...bySymbol.values()].sort((a, b) => b.score - a.score).slice(0, MAX_FROM_NEWS); for (const idea of ideas) { if (out.length >= MAX_CANDIDATES) break; const already = out.find((c) => c.symbol === idea.symbol); if (already) already.technical = idea.reason; else if (!exclude.includes(idea.symbol)) out.push({ symbol: idea.symbol, score: idea.score, newsIds: [], technical: idea.reason }); } return out; } const MANUAL_RUNS_PER_DAY = 3; /** Lancement à la demande (« Chercher des idées maintenant ») : limité pour garder le budget IA. */ export async function runEveningNow(): Promise { const today = parisDate(); const key = `manualRuns:${today}`; const used = (await getKv(key)) ?? 0; if (used >= MANUAL_RUNS_PER_DAY) { return [`Déjà ${MANUAL_RUNS_PER_DAY} recherches aujourd'hui : reviens demain (ça protège ton budget IA).`]; } await setKv(key, used + 1); await refreshIdeas().catch(() => null); return runEvening({ manual: true }); } /** Le rendez-vous du soir : analyse, décisions, fiches et notification. */ 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.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) .values({ date: today, summary: "" }) .onConflictDoUpdate({ target: schema.rendezvous.date, set: { createdAt: new Date() } }) .returning(); // Relancé le même jour : on remplace les fiches encore sans réponse au lieu de les dupliquer. // (sauf le virement mensuel vers le PEA, qui n'est créé qu'une fois par mois). await db .delete(schema.actions) .where(and(eq(schema.actions.rendezvousId, rdv.id), eq(schema.actions.status, "pending"), ne(schema.actions.kind, "to_pea"))); // Les fiches des jours précédents restées sans réponse ne sont plus valables (prix périmés) : // elles passent « expirées » au lieu de traîner. Le virement vers le PEA, lui, reste à faire. await db .update(schema.actions) .set({ status: "expired" }) .where( and( eq(schema.actions.status, "pending"), ne(schema.actions.rendezvousId, rdv.id), ne(schema.actions.rendezvousId, 0), ne(schema.actions.kind, "to_pea"), ), ); let settings = await getSettings(); const ai = await getPortfolioState("ai_sim"); const real = await getPortfolioState("real"); let gate = await getGateStatus(settings, ai); if (!settings.realUnlockedAt && gate.unlocked) { settings = await updateSettings({ realUnlockedAt: today, realLockedReason: null }); gate = { ...gate, realActive: true }; summary.push("🎉 Tous les critères sont remplis : le mode réel est débloqué."); } // Coupe-circuit du réel. if (gate.realActive && circuitBreakerTripped(real.equity, await totalDeposited())) { settings = await updateSettings({ realLockedReason: `Cagnotte réelle sous 50 % des versements le ${today}` }); gate = { ...gate, realActive: false }; summary.push("🛑 Coupe-circuit : ta cagnotte réelle a perdu plus de 50 %. Retour en simulation, plus aucune proposition réelle."); } // 1. Le comité du jour : l'IA compare les candidates et passe en revue les positions détenues. const ideas = (await getIdeas())?.items ?? []; const sandbox = await getPortfolioState("sandbox"); let committee: Awaited> = null; if (aiEnabled()) { try { committee = await runCommittee(ai, sandbox, ideas, today, log); } catch (e) { if (!(e instanceof AiUnavailableError)) console.error("[comité]", e); log.push(`Analyse de l'IA impossible : ${e instanceof Error ? e.message : String(e)}`); } } else { summary.push("L'IA n'est pas encore branchée (clé Anthropic manquante)."); } const buys = (committee?.decided ?? []) .filter((d) => d.analysis.decision === "buy" && d.analysis.confidence >= MIN_CONFIDENCE) .sort((a, b) => b.analysis.confidence - a.analysis.confidence); const best = buys[0] ?? null; // 2. La cagnotte de l'IA agit seule : elle vend ce qu'elle ne veut plus garder, puis achète // ses meilleures idées tant que le contrôle des risques lui laisse de la place. if (committee) { for (const h of committee.holdings.filter((x) => x.action === "sell")) { const pos = ai.positions.find((p) => p.id === h.positionId); if (!pos) continue; await placeOrder({ portfolioId: "ai_sim", symbol: pos.symbol, name: pos.name, currency: pos.currency, side: "sell", type: "market", shares: pos.shares, positionId: pos.id }); summary.push(`L'IA vend ${pos.name} (${pos.pnlOpenPct >= 0 ? "+" : ""}${pos.pnlOpenPct.toFixed(1)} %) : ${h.reason}`); } for (const d of buys) { const r = await sizeFor(await getPortfolioState("ai_sim"), d, today); await db.update(schema.signals).set({ riskVerdict: r.ok ? "accepté" : r.reason }).where(eq(schema.signals.id, d.signalId)); if (!r.ok) { if (d === best) summary.push(`L'IA aimait ${d.name}, mais le contrôle des risques a dit non : ${r.reason}`); continue; } await placeOrder({ portfolioId: "ai_sim", symbol: d.symbol, name: d.name, currency: d.currency, side: "buy", type: "limit", shares: r.shares, limitPrice: r.limitPrice, stopPrice: r.stopPrice, targetPrice: r.targetPrice, maxExitDate: r.maxExitDate, signalId: d.signalId, validUntil: addTradingDays(today, 1), }); summary.push(`L'IA achète ${d.name} pour ${r.amountEur} € dans sa cagnotte (confiance ${d.analysis.confidence} %).`); } if (!buys.length) summary.push(`L'IA a comparé ${committee.decided.length} actions et préfère attendre : ${committee.marketView}`); } // 3. Son conseil pour ton bac à sable (affiché dans l'onglet Bac à sable). // Sans réponse de l'IA ce soir (panne, budget), on garde son dernier conseil plutôt que de l'effacer. const advice = await sandboxAdvice(committee, sandbox, today); if (advice) await setKv("aiAdvice", advice); // 4. La fiche du rendez-vous : la meilleure idée, pour ton bac à sable ou pour de vrai. if (best) { const fx = (await getFxToEur(best.currency, { fresh: true })) ?? 1; const forCard = gate.realActive ? await sizeFor(real, best, today) : await trainingSize(sandbox, best, today); if (forCard.ok) { const training = !gate.realActive; await db.insert(schema.actions).values({ rendezvousId: rdv.id, kind: "buy", training, symbol: best.symbol, payload: buyPayload(best, forCard, fx, training), }); } else if (gate.realActive) { summary.push(`Pas de proposition réelle sur ${best.name} : ${forCard.reason}`); } } else { // Sans conviction de l'IA (ou sans IA), on te propose la meilleure idée du filtre, pour t'entraîner. const held = sandbox.positions.map((p) => p.symbol); const idea = ideas.find((i) => !held.includes(i.symbol)); if (idea) { await db.insert(schema.actions).values({ rendezvousId: rdv.id, kind: "buy", training: true, symbol: idea.symbol, payload: ideaPayload(idea), }); summary.push(`Idée du filtre (sans IA) à tester dans ton bac à sable : ${idea.name}.`); } } // 5. Revue des positions réelles : vendre, ou remonter le stop pour protéger un gain. if (real.positions.length) await reviewRealPositions(real, rdv.id, today); // 6. Le cliquet, une fois par mois. const month = today.slice(0, 7); if (gate.realActive && (await getKv("lastRatchet")) !== month) { const r = computeRatchet(real.equity, real.highWaterMark, real.cash); if (r.transfer > 0) { await db.insert(schema.actions).values({ rendezvousId: rdv.id, kind: "to_pea", training: false, payload: { title: `Vire ${r.transfer} € de gains vers ton PEA`, why: "Ta cagnotte a dépassé son plus haut : la moitié du gain part à l'abri sur le PEA (règle du cliquet).", steps: [ "Dans Trade Republic, ouvre ton compte-titres.", `Retire ${r.transfer} € vers ton compte bancaire, puis verse-les sur ton PEA.`, "Ajoute-les à ton plan d'épargne ETF S&P 500 (ou achète des parts).", ], amountEur: r.transfer, }, }); } await setKv("lastRatchet", month); } // 7. Résumé de la simulation. const aiAfter = await getPortfolioState("ai_sim"); for (const p of aiAfter.positions) { summary.push(`Cagnotte IA : ${p.name} ${p.pnlOpenPct >= 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"))); await db.update(schema.rendezvous).set({ summary: summary.join("\n") }).where(eq(schema.rendezvous.id, rdv.id)); const body = cards.length ? cards.map((c) => (c.training ? "Entraînement : " : "") + c.payload.title).join(" · ") : summary[0] ?? "Rien à faire ce soir."; const sent = await sendPush("Ton rendez-vous du soir", body, "/"); await db.update(schema.rendezvous).set({ notifiedAt: sent ? new Date() : null }).where(eq(schema.rendezvous.id, rdv.id)); log.push(`Rendez-vous créé (${cards.length} fiche(s), ${sent} notification(s))`); await setKv("lastEveningLog", { at: new Date().toISOString(), log: [...log, ...summary] }); return log; } /** Une action jugée par le comité, avec son analyse enregistrée (table signals). */ type Decided = { analysis: Analysis; signalId: number; symbol: string; name: string; price: number; currency: string }; /** Les données d'une candidate pour l'IA : cours frais, 30 derniers jours, résultats, actus triées. */ async function candidateContext(c: Candidate, news: Awaited>, today: string) { const stock = findStock(c.symbol)!; const [quote, bars, earnings] = await Promise.all([ getQuote(c.symbol, { fresh: true }), getBars(c.symbol, addDays(today, -45)).catch(() => []), getNextEarningsDate(c.symbol), ]); if (!quote) return null; const items = news.filter((n) => n.symbol === c.symbol).slice(0, 6); return { newsIds: items.map((n) => n.id), ctx: { symbol: c.symbol, company: stock.name, currency: quote.currency, price: quote.price, changeTodayPct: quote.changePct, closes30d: bars.slice(-30).map((b) => ({ date: b.date, close: Math.round(b.close * 100) / 100 })), nextEarningsDate: earnings, news: items.map((n) => ({ title: n.title, publisher: n.publisher, publishedAt: n.publishedAt.toISOString(), triage: n.triage ? `${n.triage.eventType}, pertinence ${n.triage.relevance}/10 : ${n.triage.reason}` : "", })), technicalSignal: c.technical ?? null, today, }, }; } /** * Le comité du jour : un seul appel à l'IA qui compare jusqu'à 6 actions et revoit les positions * de sa cagnotte et de ton bac à sable. Chaque analyse est enregistrée (onglet IA, fiche action). */ async function runCommittee(ai: PortfolioState, sandbox: PortfolioState, ideas: Idea[], today: string, log: string[]) { const news = await recentNews(30); // Ni les actions déjà détenues par l'IA ou toi en réel, ni celles qu'elle a déjà en commande. const exclude = [...new Set([...(await getOpenSymbols(["ai_sim", "real"])), ...ai.pendingOrders.filter((o) => o.side === "buy").map((o) => o.symbol)])]; const picked = pickCandidates(news, exclude, ideas); const contexts = (await Promise.all(picked.map((c) => candidateContext(c, news, today)))).filter((x) => x !== null); const holding = (p: PositionView, portfolio: HoldingContext["portfolio"]): HoldingContext => ({ positionId: p.id, portfolio, symbol: p.symbol, company: p.name, entryPrice: Math.round(p.entryPrice * 100) / 100, price: p.price, pnlPct: Math.round(p.pnlOpenPct * 10) / 10, openedOn: parisDate(p.openedAt), stopPrice: p.stopPrice, targetPrice: p.targetPrice, recentNews: news .filter((n) => n.symbol === p.symbol) .slice(0, 3) .map((n) => (n.triage ? `${n.title} (${n.triage.direction}, ${n.triage.relevance}/10)` : n.title)), }); const holdings = [...ai.positions.map((p) => holding(p, "cagnotte_ia")), ...sandbox.positions.map((p) => holding(p, "bac_a_sable"))]; const res = await dailyCommittee({ today, candidates: contexts.map((c) => c.ctx), holdings }); if (!res) return null; const db = await getDb(); const decided: Decided[] = []; for (const a of res.candidates) { const c = contexts.find((x) => x.ctx.symbol === a.symbol); if (!c) continue; const [signal] = await db .insert(schema.signals) .values({ date: today, symbol: a.symbol, name: c.ctx.company, decision: a.decision, confidence: Math.round(a.confidence), thesis: a.thesis, risks: a.risks, expectedMovePct: a.expectedMovePct, stopPct: a.stopPct, targetPct: a.targetPct, horizonDays: Math.round(a.horizonDays), priceAtSignal: c.ctx.price, currency: c.ctx.currency, newsIds: c.newsIds, }) .returning(); decided.push({ analysis: a, signalId: signal.id, symbol: a.symbol, name: c.ctx.company, price: c.ctx.price, currency: c.ctx.currency }); } log.push(`Comité : ${contexts.length} actions comparées, ${decided.filter((d) => d.analysis.decision === "buy").length} jugées intéressantes, ${holdings.length} positions revues`); await setKv("aiCommittee", { date: today, at: new Date().toISOString(), marketView: res.marketView }); return { marketView: res.marketView, decided, holdings: res.holdings }; } /** Passe une idée de l'IA au contrôle des risques, pour un portefeuille donné. */ async function sizeFor(s: PortfolioState, d: Decided, today: string) { const [fx, earnings] = await Promise.all([getFxToEur(d.currency, { fresh: true }), getNextEarningsDate(d.symbol)]); const pendingBuys = s.pendingOrders.filter((o) => o.side === "buy"); return checkBuy({ equity: s.equity, cash: s.cash, openPositions: s.positions.length + pendingBuys.length, heldSymbols: [...s.positions.map((p) => p.symbol), ...pendingBuys.map((o) => o.symbol)], symbol: d.symbol, priceLocal: d.price, fxToEur: fx ?? 1, stopPct: d.analysis.stopPct, targetPct: d.analysis.targetPct, horizonDays: d.analysis.horizonDays, nextEarningsDate: earnings, today, }); } /** Dimensionne une fiche d'entraînement sur ton bac à sable, ou sur 200 € neufs s'il n'a plus de place. */ async function trainingSize(sandbox: PortfolioState, d: Decided, today: string) { const r = await sizeFor(sandbox, d, today); if (r.ok) return r; return sizeFor({ ...sandbox, equity: SIM_INITIAL_CASH, cash: SIM_INITIAL_CASH, positions: [], pendingOrders: [] }, d, today); } /** Le conseil de l'IA pour ton bac à sable, montré dans l'onglet Bac à sable jusqu'au prochain comité. */ export type AiAdvice = { date: string; at: string; marketView: string | null; pick: { symbol: string; name: string; currency: string; price: number; confidence: number; thesis: string; risks: string; stopPct: number; targetPct: number; horizonDays: number; /** Montant conseillé pour ton bac à sable, ou null s'il n'a plus de place. */ amountEur: number | null; blockedReason: string | null; } | null; sells: { positionId: number; symbol: string; name: string; reason: string }[]; keeps: { positionId: number; name: string; reason: string }[]; }; async function sandboxAdvice(committee: Awaited>, sandbox: PortfolioState, today: string): Promise { if (!committee) return null; const held = sandbox.positions.map((p) => p.symbol); const best = committee.decided .filter((d) => d.analysis.decision === "buy" && d.analysis.confidence >= MIN_CONFIDENCE && !held.includes(d.symbol)) .sort((a, b) => b.analysis.confidence - a.analysis.confidence)[0]; let pick: AiAdvice["pick"] = null; if (best) { const r = await sizeFor(sandbox, best, today); pick = { symbol: best.symbol, name: best.name, currency: best.currency, price: best.price, confidence: Math.round(best.analysis.confidence), thesis: best.analysis.thesis, risks: best.analysis.risks, stopPct: Math.round(clampStopPct(best.analysis.stopPct) * 10) / 10, targetPct: Math.round(Math.max(best.analysis.targetPct, best.analysis.stopPct * 1.5) * 10) / 10, horizonDays: Math.round(best.analysis.horizonDays), amountEur: r.ok ? r.amountEur : null, blockedReason: r.ok ? null : r.reason, }; } const byId = new Map(sandbox.positions.map((p) => [p.id, p])); const mine = committee.holdings.filter((h) => byId.has(h.positionId)); return { date: today, at: new Date().toISOString(), marketView: committee.marketView, pick, sells: mine.filter((h) => h.action === "sell").map((h) => ({ positionId: h.positionId, symbol: byId.get(h.positionId)!.symbol, name: byId.get(h.positionId)!.name, reason: h.reason })), keeps: mine.filter((h) => h.action === "keep").map((h) => ({ positionId: h.positionId, name: byId.get(h.positionId)!.name, reason: h.reason })), }; } export async function getAiAdvice(): Promise { return getKv("aiAdvice"); } function money(n: number, currency: string) { return `${n.toFixed(2)} ${currency === "EUR" ? "€" : "$"}`; } type RiskOk = Extract, { ok: true }>; /** En euros, comme dans Trade Republic (les actions américaines y sont cotées en euros). */ function inEur(n: number, currency: string, fx: number) { return currency === "EUR" ? `${n.toFixed(2)} €` : `${n.toFixed(2)} $ (≈ ${(n * fx).toFixed(2)} €)`; } function buyPayload( best: { analysis: Analysis; signalId: number; symbol: string; name: string; currency: string }, r: RiskOk, fx: number, training: boolean, ): ActionPayload { return { title: `Acheter ${best.name} pour ${r.amountEur} €`, why: `${best.analysis.thesis}\n\nRisques : ${best.analysis.risks}`, steps: [ training ? "Entraînement : le mode réel n'est pas encore débloqué. Essaie ce trade dans ton bac à sable, ou dis simplement si tu l'aurais pris." : `Dans Trade Republic (compte-titres), cherche « ${best.name} » et touche Acheter.`, `Choisis « Montant » et saisis ${r.amountEur} € (≈ ${fmtShares(r.shares)} action). N'achète pas si le cours dépasse ${inEur(r.limitPrice, best.currency, fx)}.`, `Une fois acheté : ordre Stop (vente) à ${inEur(r.stopPrice, best.currency, fx)}. Perte maximale ≈ ${r.maxLossEur.toFixed(0)} €.`, `L'app te dira quand vendre : objectif ${inEur(r.targetPrice, best.currency, fx)}, au plus tard le ${r.maxExitDate}.`, ], name: best.name, currency: best.currency, shares: r.shares, amountEur: r.amountEur, limitPrice: r.limitPrice, stopPrice: r.stopPrice, targetPrice: r.targetPrice, maxExitDate: r.maxExitDate, signalId: best.signalId, stopPct: Math.round((1 - r.stopPrice / r.limitPrice) * 1000) / 10, targetPct: Math.round((r.targetPrice / r.limitPrice - 1) * 1000) / 10, }; } /** Fiche d'entraînement issue du filtre technique (sans IA). */ function ideaPayload(idea: Idea): ActionPayload { return { title: `Idée à tester : ${idea.name}`, why: `${idea.reason}\n\nCette idée vient d'une règle simple, pas de l'IA. Teste-la dans ton bac à sable pour voir si elle marche.`, steps: [ "Entraînement uniquement : essaie-la dans ton bac à sable avec un stop à 7 %.", "Le bac à sable vendra tout seul si le stop ou l'objectif (+12 %) est touché.", ], name: idea.name, currency: idea.currency, stopPct: 7, targetPct: 12, amountEur: 100, source: "screen", }; } export function fmtShares(n: number): string { return n.toLocaleString("fr-FR", { maximumFractionDigits: 4 }); } async function reviewRealPositions(real: PortfolioState, rdvId: number, today: string) { const db = await getDb(); 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; const sellReason = p.targetPrice && price >= p.targetPrice ? "L'objectif est atteint : on encaisse le gain." : p.maxExitDate && today >= p.maxExitDate ? "La durée maximale de 3 semaines est atteinte : l'effet de l'actu est épuisé." : null; if (sellReason) { await db.insert(schema.actions).values({ rendezvousId: rdvId, kind: "sell", training: false, symbol: p.symbol, payload: { title: `Vendre tes ${p.shares} ${p.name}`, why: `${sellReason} Gain actuel : ${p.pnlOpenEur >= 0 ? "+" : ""}${p.pnlOpenEur.toFixed(2)} €.`, steps: [ "Dans Trade Republic, annule d'abord ton ordre Stop sur cette action.", `Puis Vendre → ${p.shares} action(s) au marché${isTradeRepublicOpen() ? "" : " (demain dès 7h30)"}.`, ], name: p.name, currency: p.currency, shares: p.shares, positionId: p.id, }, }); } else if (p.pnlOpenPct >= 5 && p.stopPrice !== null && p.stopPrice < p.entryPrice) { const newStop = Math.round(p.entryPrice * 100) / 100; await db.insert(schema.actions).values({ rendezvousId: rdvId, kind: "move_stop", training: false, symbol: p.symbol, payload: { title: `Remonter le stop de ${p.name} à ${money(newStop, p.currency)}`, why: `Tu gagnes déjà ${p.pnlOpenPct.toFixed(1)} %. En plaçant le stop à ton prix d'achat, ce trade ne peut plus te faire perdre d'argent.`, steps: ["Dans Trade Republic, modifie ton ordre Stop sur cette action.", `Nouveau prix de stop : ${money(newStop, p.currency)}.`], name: p.name, currency: p.currency, stopPrice: newStop, positionId: p.id, }, }); } } }