diff --git a/README.md b/README.md index 804988d..c03b054 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,12 @@ Dans le dépôt GitHub → **Settings → Secrets and variables → Actions** Puis onglet **Actions** → *Tick* → *Run workflow* pour tester. Ensuite, il tourne seul toutes les 30 minutes en semaine. +**Réveil de secours par Vercel** (déjà configuré dans `vercel.json`, rien à faire) : Vercel appelle l'app deux fois chaque soir de semaine, vers 18h et 19h (heure de Paris en hiver, une heure plus tard en été). L'offre gratuite de Vercel déclenche ces tâches à un moment quelconque dans l'heure prévue, d'où les deux passages. Il suffit que `CRON_SECRET` soit réglé dans Vercel. + +**Raccourci iPhone (facultatif)** : app **Raccourcis** → *Automatisation* → *Nouvelle automatisation* → *Heure de la journée* 18:30, jours de semaine, *Exécuter immédiatement*. Action : **Obtenir le contenu de l'URL**, adresse `https://TON-APP.vercel.app/api/cron/tick`, méthode GET, en-tête `Authorization` = `Bearer ` suivi de ton `CRON_SECRET`. + +Pour vérifier que chaque réveil marche : **Réglages → Réveils automatiques** dans l'app montre la date du dernier passage de GitHub, de Vercel et du raccourci. + ### 6. Sur ton iPhone 1. Ouvre l'adresse Vercel dans **Safari** et connecte-toi. 2. **Partager** → **Sur l'écran d'accueil** → *Ajouter*. @@ -103,16 +109,19 @@ GitHub Actions (toutes les 30 min, en semaine) ├─ actus de 92 grandes actions US + Europe → tri par Claude Haiku (quelques centimes) ├─ alerte immédiate seulement si un événement grave touche une position réelle └─ à 18h30 : rendez-vous du soir - ├─ analyse approfondie des 3 meilleures candidates par Claude Sonnet (débat haussier/baissier) - ├─ contrôle des risques (code fixe, jamais l'IA) → l'IA achète dans sa cagnotte simulée + ├─ comité du jour : Claude Sonnet compare jusqu'à 6 actions (actus + filtre technique) + │ en un seul appel, et passe en revue les positions de sa cagnotte et de ton bac à sable + ├─ contrôle des risques (code fixe, jamais l'IA) → l'IA vend ce qu'elle ne veut plus garder + │ et achète ses meilleures idées tant qu'elle a de la place + ├─ conseil pour ton bac à sable (quoi acheter, vendre, garder), suivi en un toucher ├─ fiche « recette » pour toi (entraînement tant que le réel n'est pas débloqué) ├─ revue des positions réelles, cliquet vers le PEA, coupe-circuit └─ notification sur l'iPhone ``` **Règles du contrôle des risques** (`src/lib/engine/risk.ts`) : -- 1 position à la fois sous 400 €, 2 entre 400 et 1 000 €, 4 au-delà ; -- au moins 150 € par position, sinon les frais mangent le gain ; +- 2 positions à la fois sous 400 €, 3 entre 400 et 1 000 €, 4 au-delà ; +- environ 100 € par position (90 € minimum) : avec 2 € de frais aller-retour, il faut plus de 2 % de gain pour être à l'équilibre ; - stop obligatoire, entre 4 et 10 % ; - sortie au plus tard après 15 jours de bourse ; - pas d'achat dans les 4 jours avant des résultats trimestriels ; diff --git a/src/app/(app)/bac-a-sable/page.tsx b/src/app/(app)/bac-a-sable/page.tsx index d9b79ff..757d3ed 100644 --- a/src/app/(app)/bac-a-sable/page.tsx +++ b/src/app/(app)/bac-a-sable/page.tsx @@ -6,7 +6,10 @@ import { ResetSandbox } from "@/components/reset-sandbox"; import { Card, CardSkeleton, Delta, Page, primaryBtn, Stat } from "@/components/ui"; import { eur, pct, signedEur } from "@/lib/format"; import { getClosedPositions, getPortfolioState } from "@/lib/portfolio"; -import { isTradeRepublicOpen } from "@/lib/time"; +import { isTradeRepublicOpen, parisDate } from "@/lib/time"; +import { AiAdviceCard } from "@/components/ai-advice"; +import { aiEnabled } from "@/lib/ai"; +import { getAiAdvice } from "@/lib/jobs"; async function SandboxContent() { await connection(); @@ -58,9 +61,18 @@ async function SandboxContent() { ); } +async function Advice() { + await connection(); + const advice = await getAiAdvice(); + return ; +} + export default function SandboxPage() { return ( + }> + + }> diff --git a/src/app/(app)/ia/page.tsx b/src/app/(app)/ia/page.tsx index 551bd28..c2bbdcc 100644 --- a/src/app/(app)/ia/page.tsx +++ b/src/app/(app)/ia/page.tsx @@ -9,7 +9,8 @@ import { aiSimStuck, MIN_POSITION_EUR } from "@/lib/engine/risk"; import { eur, pct } from "@/lib/format"; import { getClosedPositions, getPortfolioState } from "@/lib/portfolio"; -import { getSettings } from "@/lib/settings"; +import { getKv, getSettings } from "@/lib/settings"; +import { FindIdeas } from "@/components/find-ideas"; import { aiDeposits, aiPerformance } from "@/lib/stats"; import { formatDateFr } from "@/lib/time"; @@ -84,10 +85,27 @@ async function Pot() { async function Signals() { await connection(); const db = await getDb(); - const signals = await db.select().from(schema.signals).orderBy(desc(schema.signals.createdAt)).limit(20); + const [signals, committee] = await Promise.all([ + db.select().from(schema.signals).orderBy(desc(schema.signals.createdAt)).limit(24), + getKv<{ date: string; at: string; marketView: string }>("aiCommittee"), + ]); return ( - {!signals.length && Aucune analyse pour l'instant. Elles arrivent chaque soir de semaine, 30 minutes avant ton rendez-vous.} + {committee && ( +
+

Son avis sur le marché, {formatDateFr(committee.date)}

+

{committee.marketView}

+
+ )} + {!signals.length && ( + + Chaque soir de semaine, 30 minutes avant ton rendez-vous, l'IA compare jusqu'à 6 actions, achète les meilleures pour sa cagnotte et te conseille pour ton bac à + sable. + + )} +
+ +
    {signals.map((s) => (
  • diff --git a/src/app/(app)/page.tsx b/src/app/(app)/page.tsx index df6f662..7fa1158 100644 --- a/src/app/(app)/page.tsx +++ b/src/app/(app)/page.tsx @@ -156,7 +156,7 @@ async function Todo() {
      {ideas.items.slice(0, 3).map((i) => (
    • - + {i.name} {pct(i.pullbackPct)} cette semaine diff --git a/src/app/(app)/reel/page.tsx b/src/app/(app)/reel/page.tsx index 6e2feba..a12cd0c 100644 --- a/src/app/(app)/reel/page.tsx +++ b/src/app/(app)/reel/page.tsx @@ -27,8 +27,39 @@ async function AccountContent() { const configured = Boolean(settings.trAccountOpenedAt); const gain = state.equity + toPea - deposited; + const peaMonthly = settings.peaPlan?.monthlyAmount ?? settings.monthlyBudget / 2; + const ctoMonthly = settings.realMonthlyDeposit; + const left = settings.monthlyBudget - peaMonthly - ctoMonthly; + return ( <> + +
      +
      +
      + {left > 0 &&
      } +
      +
      +
      +

      + + PEA, S&P 500 +

      +

      {eur(peaMonthly, 0)}

      +

      à l'abri, plan d'épargne automatique

      +
      +
      +

      + + Compte-titres +

      +

      {eur(ctoMonthly, 0)}

      +

      la cagnotte que l'IA fait travailler

      +
      +
      + {left > 0 &&

      Il reste {eur(left, 0)} non attribués chaque mois.

      } + + ( +function Row({ ok, label, hint, value }: { ok: boolean | null; label: string; hint?: string; value: React.ReactNode }) { + return (
    • - + {label} - {!ok && (à vérifier)} + {ok === false && (à vérifier)} + {hint && {hint}} {value}
    • ); +} + +const hoursSince = (iso: string | null) => (iso ? (Date.now() - new Date(iso).getTime()) / 3_600_000 : Infinity); + +/** + * Qui réveille l'app pour le rendez-vous du soir. Le week-end, aucun réveil n'est prévu : + * on tolère donc jusqu'à 3 jours sans nouvelles avant d'afficher une alerte. + */ +async function Wakes() { + await connection(); + const d = await getDiagnostics(); + const { github, vercel, shortcut } = d.wakes; + const none = !github && !vercel && !shortcut; + return ( + +

      + Sur Vercel, l'app dort tant que personne ne l'appelle. Ces réveils lui permettent de préparer ton rendez-vous du soir et de t'envoyer la notification. +

      +
        + + + +
      + {none && ( +

      + Aucun réveil automatique n'a encore eu lieu : le rendez-vous ne se prépare que quand tu ouvres l'app après 18h30. Vérifie les secrets APP_URL et CRON_SECRET (voir le + README). +

      + )} + {!d.cronConfigured &&

      CRON_SECRET n'est pas réglé sur le serveur : aucun réveil ne peut fonctionner.

      } +
      + ); +} + +/** Pourquoi l'IA trade ou non : tout ce qui s'est passé lors des dernières mises à jour. */ +async function Diagnostics() { + await connection(); + const d = await getDiagnostics(); + const row = (ok: boolean, label: string, value: React.ReactNode) => ; return (
        @@ -129,6 +166,10 @@ export default function SettingsPage() { + }> + + + }> diff --git a/src/app/actions.ts b/src/app/actions.ts index 872d665..23b2900 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 { resetAiSim, runEvening, runEveningNow, tick } from "@/lib/jobs"; +import { getAiAdvice, resetAiSim, runEvening, runEveningNow, tick } from "@/lib/jobs"; import { FEE_EUR } from "@/lib/engine/fills"; import { roundShares } from "@/lib/engine/risk"; import { @@ -23,7 +23,7 @@ import { import { cancelOrder, getPortfolioState, placeOrder } from "@/lib/portfolio"; import { removeSubscription, saveSubscription, sendPush } from "@/lib/push"; import { addHolding, deleteHolding, recordDeposit, recordSale, setCash } from "@/lib/real"; -import { defaultPeaPlan, getSettings, updateSettings } from "@/lib/settings"; +import { budgetError, defaultPeaPlan, getSettings, updateSettings } from "@/lib/settings"; import { addDays, parisDate } from "@/lib/time"; import { getDb, schema } from "@/lib/db"; import { and, eq } from "drizzle-orm"; @@ -169,6 +169,28 @@ export async function resetSandbox() { revalidatePath("/", "layout"); } +/** + * « Suivre le conseil de l'IA » dans le bac à sable : achète l'action qu'elle recommande, + * pour le montant conseillé, avec son stop et son objectif. Le prix est revérifié à l'instant. + */ +export async function followAiAdvice(): Promise<{ ok: boolean; message: string }> { + await requireAuth(); + const advice = await getAiAdvice(); + const pick = advice?.pick; + if (!pick) return { ok: false, message: "Pas de conseil d'achat en ce moment." }; + if (!pick.amountEur) return { ok: false, message: pick.blockedReason ?? "Ton bac à sable n'a plus de place pour une nouvelle position." }; + const state = await getPortfolioState("sandbox"); + if (state.positions.some((p) => p.symbol === pick.symbol)) return { ok: false, message: `Tu détiens déjà ${pick.name}.` }; + const r = await sandboxBuy({ + symbol: pick.symbol, + amountEur: Math.min(pick.amountEur, Math.floor(state.cash - FEE_EUR)), + type: "market", + stopPct: pick.stopPct, + targetPct: pick.targetPct, + }); + return r.ok ? { ok: true, message: `${pick.name} : ${r.message}` } : r; +} + /** Remet la cagnotte de l'IA à 200 € et relance la simulation à partir d'aujourd'hui. */ export async function resetAiPot() { await requireAuth(); @@ -263,6 +285,9 @@ export async function saveAccount(_prev: FormResult, formData: FormData): Promis const monthly = parseNum(formData.get("monthlyDeposit")); const day = clampDay(parseNum(formData.get("depositDay")), s.realDepositDay); const auto = formData.get("autoDeposit") === "on"; + // Le PEA garde sa part du budget, même s'il n'est pas encore déclaré. + const overBudget = budgetError(s.monthlyBudget, monthly ?? s.realMonthlyDeposit, s.peaPlan?.monthlyAmount ?? s.monthlyBudget / 2); + if (overBudget) return { ok: false, message: overBudget }; const today = parisDate(); // Le prochain virement automatique compté par l'app : ce mois-ci si le jour n'est pas passé, sinon le mois prochain. const nextDeposit = (() => { @@ -296,11 +321,14 @@ export async function savePea(_prev: FormResult, formData: FormData): Promise(null); + const [why, setWhy] = useState(false); + + if (!aiOn) { + return ( + + L'IA n'est pas branchée (clé Anthropic manquante). En attendant, les idées sans IA de l'onglet Actions sont là pour t'entraîner. + + ); + } + if (!advice) { + return ( + + Chaque soir de semaine, l'IA compare plusieurs actions et te dit laquelle essayer ici. Tu peux lui demander maintenant. +
        + +
        +
        + ); + } + + const pick = advice.pick; + const buy = () => + start(async () => { + setMsg(null); + const r = await followAiAdvice(); + setMsg({ ok: r.ok, text: r.message }); + }); + const sell = (id: number, name: string) => + start(async () => { + setMsg(null); + const r = await sandboxSell(id); + setMsg({ ok: r.ok, text: r.ok ? `${name} : ${r.message}` : r.message }); + }); + + return ( + {when(advice, today)}}> + {pick ? ( + <> +
        +
        +

        Elle te conseille d'essayer

        + + {pick.name} + +
        + confiance {pick.confidence} % +
        +

        {pick.thesis}

        + +
        +
        +
        Montant
        +
        {pick.amountEur ? eur(pick.amountEur, 0) : "–"}
        +
        +
        +
        Stop
        +
        −{String(pick.stopPct).replace(".", ",")} %
        +
        +
        +
        Objectif
        +
        +{String(pick.targetPct).replace(".", ",")} %
        +
        +
        +

        + Cours à l'analyse : {price(pick.price, pick.currency)}. Durée prévue : environ {pick.horizonDays} jours de bourse. +

        + + + {why &&

        {pick.risks}

        } + + {pick.amountEur ? ( + + ) : ( +

        {pick.blockedReason} Vends une position ou attends qu'un stop ou un objectif se déclenche.

        + )} + + ) : ( + <> +

        Elle te conseille d'attendre

        +

        {advice.marketView}

        + + )} + + {advice.sells.length > 0 && ( +
        +

        À vendre dans ton bac à sable

        +
          + {advice.sells.map((s) => ( +
        • +

          {s.name}

          +

          {s.reason}

          + +
        • + ))} +
        +
        + )} + + {advice.keeps.length > 0 && ( +
        +

        À garder

        +
          + {advice.keeps.map((k) => ( +
        • + {k.name} {k.reason} +
        • + ))} +
        +
        + )} + + {msg &&

        {msg.text}

        } +
        + ); +} diff --git a/src/components/trade-panel.tsx b/src/components/trade-panel.tsx index ba164eb..08b8bd5 100644 --- a/src/components/trade-panel.tsx +++ b/src/components/trade-panel.tsx @@ -23,7 +23,7 @@ const num = (s: string) => Number(s.replace(",", ".")) || 0; export function TradePanel({ symbol, currency, lastPrice, fxToEur, cash, askLeft, aiOn, realActive, defaults }: Props) { const [mode, setMode] = useState<"amount" | "shares">("amount"); - const [amount, setAmount] = useState(String(defaults.amount ?? Math.min(150, Math.floor(Math.max(cash - 1, 0))))); + const [amount, setAmount] = useState(String(defaults.amount ?? Math.min(100, Math.floor(Math.max(cash - 1, 0))))); const [shares, setShares] = useState("1"); const [type, setType] = useState<"market" | "limit">("market"); const [limit, setLimit] = useState(lastPrice.toFixed(2)); diff --git a/src/lib/ai.ts b/src/lib/ai.ts index f63e5e4..610b34f 100644 --- a/src/lib/ai.ts +++ b/src/lib/ai.ts @@ -198,19 +198,76 @@ Méthode : Écris thesis et risks en français simple, sans jargon, comme pour un ami qui débute.`; -export async function analyzeCandidate(ctx: AnalysisContext): Promise { +// --------------------------------------------------------------------------- +// 2 bis. Le comité du jour (Sonnet) : toutes les candidates comparées d'un coup, +// plus la revue des positions détenues (cagnotte IA et bac à sable). +// Un seul appel par jour au lieu d'un par action : moins cher, et l'IA choisit +// vraiment la meilleure idée du jour au lieu de juger chaque action isolément. +// --------------------------------------------------------------------------- + +const CommitteeSchema = z.object({ + marketView: z.string().describe("1-2 phrases en français simple : l'ambiance du marché aujourd'hui et ce que tu en retiens"), + candidates: z.array(AnalysisSchema.extend({ symbol: z.string() })).describe("une entrée par candidate, avec le même symbole"), + holdings: z + .array( + z.object({ + positionId: z.number(), + action: z.enum(["keep", "sell"]), + reason: z.string().describe("une phrase en français simple"), + }), + ) + .describe("une entrée par position détenue, avec le même positionId"), +}); + +export type CommitteeResult = z.infer; +export type CommitteeCandidate = CommitteeResult["candidates"][number]; + +export type HoldingContext = { + positionId: number; + portfolio: "cagnotte_ia" | "bac_a_sable"; + symbol: string; + company: string; + entryPrice: number; + price: number | null; + pnlPct: number; + openedOn: string; + stopPrice: number | null; + targetPrice: number | null; + recentNews: string[]; +}; + +const COMMITTEE_SYSTEM = `${ANALYSIS_SYSTEM} + +Aujourd'hui tu travailles en comité : on te donne plusieurs candidates d'un coup et les positions déjà détenues. + +Candidates : +- Analyse chacune avec la même méthode, puis compare-les entre elles. Ta confiance doit refléter ce classement : la meilleure idée du jour a la confiance la plus haute. +- Le système veut se positionner presque chaque jour de bourse : réponds "buy" pour chaque candidate qui a un avantage réel. Une position fait environ 100 € et coûte 2 € de frais aller-retour : le gain attendu doit dépasser nettement 2 %. +- Ne force pas : si toutes les candidates sont faibles, réponds "pass" partout et explique pourquoi dans marketView. + +Positions détenues ("cagnotte_ia" = ta propre cagnotte, "bac_a_sable" = celle de l'utilisateur qui s'entraîne) : +- "sell" si la raison de l'achat ne tient plus (mauvaise nouvelle, tendance cassée), ou si l'objectif est presque atteint et que l'élan retombe. +- Sinon "keep" : le stop et l'objectif automatiques font déjà leur travail, ne vends pas pour un petit mouvement normal.`; + +export async function dailyCommittee(input: { + today: string; + candidates: AnalysisContext[]; + holdings: HoldingContext[]; +}): Promise { + if (!input.candidates.length && !input.holdings.length) return null; await assertBudget("analysis"); const response = await getClient().beta.messages.parse({ model: ANALYSIS_MODEL, - max_tokens: 16000, + max_tokens: 32000, betas: ["server-side-fallback-2026-07-01"], fallbacks: "default", - output_config: { effort: "medium", format: betaZodOutputFormat(AnalysisSchema) }, - system: ANALYSIS_SYSTEM, - messages: [{ role: "user", content: `Données (JSON) :\n${JSON.stringify(ctx, null, 1)}` }], + output_config: { effort: "medium", format: betaZodOutputFormat(CommitteeSchema) }, + system: COMMITTEE_SYSTEM, + messages: [{ role: "user", content: `Données du ${input.today} (JSON) :\n${JSON.stringify({ candidates: input.candidates, holdings: input.holdings })}` }], }); await recordUsage(response.model, "analysis", response.usage); if (response.stop_reason === "refusal") return null; + if (response.stop_reason === "max_tokens") throw new Error("Analyse du comité coupée (réponse trop longue)."); return response.parsed_output ?? null; } diff --git a/src/lib/committee.integration.test.ts b/src/lib/committee.integration.test.ts new file mode 100644 index 0000000..1c141c5 --- /dev/null +++ b/src/lib/committee.integration.test.ts @@ -0,0 +1,88 @@ +/** + * Le comité du jour de bout en bout, avec une vraie base (PGlite) et de vrais cours Yahoo, + * mais une réponse de l'IA simulée (aucun appel payant à Claude). + */ +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { eq } from "drizzle-orm"; +import { beforeAll, describe, expect, it, vi } from "vitest"; + +process.env.PGLITE_DIR = mkdtempSync(path.join(tmpdir(), "cagnotte-comite-")); +delete process.env.DATABASE_URL; + +// L'IA répond « acheter » pour toutes les candidates, avec une confiance décroissante, +// et conseille de vendre toute position du bac à sable. +vi.mock("./ai", async (orig) => { + const real = await orig(); + return { + ...real, + aiEnabled: () => true, + triageNews: async () => [], + dailyCommittee: async (input: Parameters[0]) => ({ + marketView: "Marché calme, quelques replis intéressants.", + candidates: input.candidates.map((c, i) => ({ + symbol: c.symbol, + bullCase: "Tendance solide.", + bearCase: "Le marché peut se retourner.", + pricedIn: false, + decision: "buy" as const, + confidence: 80 - i * 3, + expectedMovePct: 6, + horizonDays: 8, + stopPct: 6, + targetPct: 10, + thesis: `Bonne idée sur ${c.company}.`, + risks: "Un repli du marché.", + })), + holdings: input.holdings.map((h) => ({ positionId: h.positionId, action: h.portfolio === "bac_a_sable" ? ("sell" as const) : ("keep" as const), reason: "Test." })), + }), + }; +}); + +const { getDb, schema } = await import("./db"); +const { ensureSetup, setKv } = await import("./settings"); +const { getPortfolioState, placeOrder } = await import("./portfolio"); +const { getQuote } = await import("./market"); +const { runEvening, getAiAdvice } = await import("./jobs"); +const { parisDate } = await import("./time"); + +describe("comité de l'IA", () => { + beforeAll(async () => { + await ensureSetup(); + // Des idées du filtre garanties, pour ne pas dépendre de l'humeur du marché. + const items = await Promise.all( + ["KO", "PEP", "MC.PA"].map(async (symbol) => { + const q = (await getQuote(symbol))!; + return { symbol, name: q.name, currency: q.currency, price: q.price, changePct: q.changePct, score: 5, trendPct: 2, pullbackPct: -3, reason: "Repli dans une tendance haussière." }; + }), + ); + await setKv("ideas", { at: new Date().toISOString(), date: parisDate(), items }); + }); + + it("achète jusqu'à 2 positions pour l'IA et conseille le bac à sable", async () => { + // Une position dans le bac à sable, que l'IA conseillera de vendre. + const q = (await getQuote("AAPL"))!; + await placeOrder({ portfolioId: "sandbox", symbol: "AAPL", name: "Apple", currency: q.currency, side: "buy", type: "limit", shares: 0.2, limitPrice: q.price * 2 }); + + const log = await runEvening({ force: true }); + expect(log.join(" ")).toContain("Comité"); + + const ai = await getPortfolioState("ai_sim"); + const aiBuys = [...ai.positions.map((p) => p.symbol), ...ai.pendingOrders.filter((o) => o.side === "buy").map((o) => o.symbol)]; + expect(aiBuys).toHaveLength(2); // 200 € : 2 positions d'environ 100 € + expect(aiBuys).toEqual(["KO", "PEP"]); // les deux meilleures, dans l'ordre de confiance + + const advice = (await getAiAdvice())!; + expect(advice.marketView).toContain("calme"); + expect(advice.pick?.symbol).toBe("KO"); + expect(advice.pick?.amountEur).toBeGreaterThanOrEqual(90); + const sandbox = await getPortfolioState("sandbox"); + if (sandbox.positions.length) expect(advice.sells.map((s) => s.symbol)).toContain("AAPL"); + + const db = await getDb(); + const signals = await db.select().from(schema.signals).where(eq(schema.signals.date, parisDate())); + expect(signals.length).toBe(3); + expect(signals.filter((s) => s.riskVerdict === "accepté")).toHaveLength(2); + }); +}); diff --git a/src/lib/diagnostics.ts b/src/lib/diagnostics.ts index 09942c6..a8ebdc0 100644 --- a/src/lib/diagnostics.ts +++ b/src/lib/diagnostics.ts @@ -10,6 +10,11 @@ export async function getDiagnostics() { const db = await getDb(); const since48h = new Date(Date.now() - 48 * 3_600_000); const since7d = new Date(Date.now() - 7 * 86_400_000); + const [wakeGithub, wakeVercel, wakeShortcut] = await Promise.all([ + getKv("lastWake:github"), + getKv("lastWake:vercel"), + getKv("lastWake:raccourci"), + ]); const [news, triaged, signals, spend, lastTick, lastEvening] = await Promise.all([ db.select({ id: schema.news.id }).from(schema.news).where(gte(schema.news.publishedAt, since48h)), db @@ -25,6 +30,7 @@ export async function getDiagnostics() { return { aiOn: aiEnabled(), cronConfigured: Boolean(process.env.CRON_SECRET), + wakes: { github: wakeGithub, vercel: wakeVercel, shortcut: wakeShortcut }, news48h: news.length, triagedTotal: triaged.length, positiveStrong: scored.filter((t) => t.triage!.direction === "positive" && t.triage!.relevance >= 6).length, diff --git a/src/lib/engine/engine.test.ts b/src/lib/engine/engine.test.ts index 75cdc5f..b9d427a 100644 --- a/src/lib/engine/engine.test.ts +++ b/src/lib/engine/engine.test.ts @@ -95,26 +95,27 @@ describe("contrôle des risques", () => { }; it("paliers de positions selon la cagnotte", () => { - expect(tierFor(200).maxPositions).toBe(1); - expect(tierFor(600).maxPositions).toBe(2); + expect(tierFor(200).maxPositions).toBe(2); + expect(tierFor(600).maxPositions).toBe(3); expect(tierFor(2000).maxPositions).toBe(4); }); - it("dimensionne une position avec stop et objectif", () => { + it("dimensionne une position d'environ 100 € avec stop et objectif", () => { const r = checkBuy(base); expect(r.ok).toBe(true); if (!r.ok) return; - expect(r.amountEur).toBe(198); - expect(r.shares).toBeCloseTo(198 / (60.3 / 1.12), 3); - expect(r.costEur).toBeLessThanOrEqual(198); - expect(r.costEur).toBeGreaterThanOrEqual(150); + expect(r.amountEur).toBe(99); + expect(r.shares).toBeCloseTo(99 / (60.3 / 1.12), 3); + expect(r.costEur).toBeLessThanOrEqual(99); + expect(r.costEur).toBeGreaterThanOrEqual(90); expect(r.stopPrice).toBeCloseTo(60.3 * 0.93, 1); expect(r.maxExitDate).toBe(addTradingDays("2026-10-12", 10)); }); - it("refuse une 2e position sous 400 €", () => { - const r = checkBuy({ ...base, openPositions: 1 }); - expect(r.ok).toBe(false); + it("accepte une 2e position sous 400 €, refuse la 3e", () => { + // Après un premier achat de 99 € + 1 € de frais, il reste 100 € de liquidités. + expect(checkBuy({ ...base, openPositions: 1, heldSymbols: ["AAPL"], cash: 100, equity: 199 }).ok).toBe(true); + expect(checkBuy({ ...base, openPositions: 2 }).ok).toBe(false); }); it("achète une fraction d'une action chère (achat par montant)", () => { @@ -122,7 +123,7 @@ describe("contrôle des risques", () => { expect(r.ok).toBe(true); if (!r.ok) return; expect(r.shares).toBeLessThan(1); - expect(r.amountEur).toBe(198); + expect(r.amountEur).toBe(99); }); it("refuse quand il reste trop peu de liquidités", () => { @@ -232,8 +233,8 @@ describe("cagnotte de l'IA avec versements mensuels", () => { 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: 80, positions: [], pendingOrders: [] })).toBe(true); + expect(aiSimStuck({ cash: 80, positions: [{}], pendingOrders: [] })).toBe(false); expect(aiSimStuck({ cash: 190, positions: [], pendingOrders: [] })).toBe(false); }); }); diff --git a/src/lib/engine/risk.ts b/src/lib/engine/risk.ts index 782737e..0cd4ec6 100644 --- a/src/lib/engine/risk.ts +++ b/src/lib/engine/risk.ts @@ -6,16 +6,23 @@ import { addTradingDays, daysBetween } from "../time"; import { FEE_EUR } from "./fills"; export const MIN_CONFIDENCE = 60; -export const MIN_POSITION_EUR = 150; +/** + * Minimum par position : environ 100 € (90 € pour laisser la place aux frais). Avec 1 € à l'achat + * et 1 € à la vente, il faut gagner un peu plus de 2 % pour être à l'équilibre. + */ +export const MIN_POSITION_EUR = 90; export const MAX_HOLD_TRADING_DAYS = 15; // 3 semaines export const EARNINGS_BLACKOUT_DAYS = 4; // pas d'achat si des résultats tombent dans les 4 jours export type Tier = { maxPositions: number; budgetShare: number; maxRiskPct: number | null }; -/** Règles validées : 1 position sous 400 €, 2 entre 400 et 1 000 €, 4 au-delà. */ +/** + * Règles choisies le 18/11/2026 : 2 positions (~100 €) sous 400 €, 3 entre 400 et 1 000 €, + * 4 au-delà. Assez de places pour que l'IA puisse se positionner plusieurs fois par semaine. + */ export function tierFor(equity: number): Tier { - if (equity < 400) return { maxPositions: 1, budgetShare: 1, maxRiskPct: null }; - if (equity <= 1000) return { maxPositions: 2, budgetShare: 0.5, maxRiskPct: 0.05 }; + if (equity < 400) return { maxPositions: 2, budgetShare: 0.5, maxRiskPct: null }; + if (equity <= 1000) return { maxPositions: 3, budgetShare: 1 / 3, maxRiskPct: 0.05 }; return { maxPositions: 4, budgetShare: 0.25, maxRiskPct: 0.03 }; } @@ -78,7 +85,8 @@ export function checkBuy(input: RiskInput): RiskResult { const limitPrice = round(priceLocal * 1.005); const priceEur = limitPrice * fxToEur; - let budget = Math.min(cash, equity * tier.budgetShare) - FEE_EUR * 2; + // La part de la cagnotte pour cette position, frais d'achat compris, sans dépasser les liquidités. + let budget = Math.min(cash, equity * tier.budgetShare) - FEE_EUR; if (tier.maxRiskPct !== null) { budget = Math.min(budget, (equity * tier.maxRiskPct) / (stopPct / 100)); } @@ -109,7 +117,7 @@ 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. */ +/** La cagnotte n'a plus de quoi ouvrir une position (minimum 90 € + 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; } diff --git a/src/lib/jobs.ts b/src/lib/jobs.ts index 6b94a96..438d423 100644 --- a/src/lib/jobs.ts +++ b/src/lib/jobs.ts @@ -1,13 +1,13 @@ import "server-only"; import { and, eq, gte, inArray, isNotNull, isNull, ne, sql } from "drizzle-orm"; -import { aiEnabled, analyzeCandidate, AiUnavailableError, type Analysis } from "./ai"; +import { aiEnabled, AiUnavailableError, dailyCommittee, type Analysis, type HoldingContext } from "./ai"; import { getDb, schema } from "./db"; -import { aiSimStuck, checkBuy, MIN_CONFIDENCE, MIN_POSITION_EUR } from "./engine/risk"; +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 } from "./portfolio"; +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"; @@ -138,7 +138,7 @@ async function monthlyDeposit(settings: Settings, today: string, log: string[]) /** * 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. + * 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[]) { @@ -203,29 +203,34 @@ async function urgentAlerts(): Promise { type Candidate = { symbol: string; score: number; newsIds: string[]; technical?: string }; -const MAX_CANDIDATES = 3; +/** 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 analysées par l'IA : d'abord les actions portées par une actu positive - * (pertinence ≥ 6/10), puis, s'il reste de la place, les meilleures idées du filtre technique. + * 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 < 6 || exclude.includes(n.symbol) || !findStock(n.symbol)) continue; + 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 fromNews = [...bySymbol.values()].sort((a, b) => b.score - a.score).slice(0, MAX_CANDIDATES); + const out = [...bySymbol.values()].sort((a, b) => b.score - a.score).slice(0, MAX_FROM_NEWS); for (const idea of ideas) { - if (fromNews.length >= MAX_CANDIDATES) break; - if (exclude.includes(idea.symbol) || fromNews.some((c) => c.symbol === idea.symbol)) continue; - fromNews.push({ symbol: idea.symbol, score: idea.score, newsIds: [], technical: idea.reason }); + 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 fromNews; + return out; } const MANUAL_RUNS_PER_DAY = 3; @@ -305,81 +310,70 @@ async function prepareEvening(opts: { manual?: boolean; force?: boolean }): Prom summary.push("🛑 Coupe-circuit : ta cagnotte réelle a perdu plus de 50 %. Retour en simulation, plus aucune proposition réelle."); } - // 1. Analyse des meilleures candidates. - let best: { analysis: Analysis; signalId: number; symbol: string; name: string; price: number; currency: string } | null = null; - let analyzed = 0; + // 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()) { - const news = await recentNews(30); - // Ni les actions déjà détenues, ni celles qui ont déjà un ordre d'achat en attente. - const exclude = [...new Set([...(await getOpenSymbols(["ai_sim", "real"])), ...ai.pendingOrders.filter((o) => 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) { - if (r.status === "rejected") { - log.push(`Analyse échouée : ${r.reason instanceof Error ? r.reason.message : r.reason}`); - continue; - } - if (!r.value) continue; - analyzed++; - const v = r.value; - if (v.analysis.decision === "buy" && v.analysis.confidence >= MIN_CONFIDENCE && (!best || v.analysis.confidence > best.analysis.confidence)) { - best = v; - } + 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)}`); } - log.push(`${candidates.length} candidates, ${analyzed} analysées`); } 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. Décision pour la cagnotte IA (simulation, exécutée automatiquement) et fiche pour toi. - if (best) { - const fx = (await getFxToEur(best.currency, { fresh: true })) ?? 1; - const earnings = await getNextEarningsDate(best.symbol); - const riskInput = (s: PortfolioState) => ({ - equity: s.equity, - cash: s.cash, - openPositions: s.positions.length + s.pendingOrders.filter((o) => o.side === "buy").length, - heldSymbols: s.positions.map((p) => p.symbol), - symbol: best.symbol, - priceLocal: best.price, - fxToEur: fx, - stopPct: best.analysis.stopPct, - targetPct: best.analysis.targetPct, - horizonDays: best.analysis.horizonDays, - nextEarningsDate: earnings, - today, - }); - - const aiRisk = checkBuy(riskInput(ai)); - await db - .update(schema.signals) - .set({ riskVerdict: aiRisk.ok ? "accepté" : aiRisk.reason }) - .where(eq(schema.signals.id, best.signalId)); - if (aiRisk.ok) { + // 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: best.symbol, - name: best.name, - currency: best.currency, + symbol: d.symbol, + name: d.name, + currency: d.currency, side: "buy", type: "limit", - shares: aiRisk.shares, - limitPrice: aiRisk.limitPrice, - stopPrice: aiRisk.stopPrice, - targetPrice: aiRisk.targetPrice, - maxExitDate: aiRisk.maxExitDate, - signalId: best.signalId, + 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 ${aiRisk.shares} ${best.name} dans sa cagnotte simulée (confiance ${best.analysis.confidence} %).`); - } else { - summary.push(`🤖 L'IA aimait ${best.name}, mais le contrôle des risques a dit non : ${aiRisk.reason}`); + 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}`); + } - // Fiche d'entraînement : dimensionnée sur ton bac à sable (ou sur 200 € neufs s'il est plein), - // pour que tu aies toujours quelque chose à essayer, même quand la cagnotte de l'IA est déjà investie. - const forCard = gate.realActive ? checkBuy(riskInput(real)) : trainingRisk(riskInput, await getPortfolioState("sandbox")); + // 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({ @@ -393,9 +387,8 @@ async function prepareEvening(opts: { manual?: boolean; force?: boolean }): Prom summary.push(`Pas de proposition réelle sur ${best.name} : ${forCard.reason}`); } } else { - if (aiEnabled()) summary.push(`😴 L'IA a étudié ${analyzed} candidate(s) et préfère attendre ce soir.`); // Sans conviction de l'IA (ou sans IA), on te propose la meilleure idée du filtre, pour t'entraîner. - const held = await getOpenSymbols(["sandbox"]); + 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({ @@ -405,14 +398,14 @@ async function prepareEvening(opts: { manual?: boolean; force?: boolean }): Prom symbol: idea.symbol, payload: ideaPayload(idea), }); - summary.push(`🔎 Idée du filtre (sans IA) à tester dans ton bac à sable : ${idea.name}.`); + summary.push(`Idée du filtre (sans IA) à tester dans ton bac à sable : ${idea.name}.`); } } - // 3. Revue des positions réelles : vendre, ou remonter le stop pour protéger un gain. + // 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); - // 4. Le cliquet, une fois par mois. + // 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); @@ -436,7 +429,7 @@ async function prepareEvening(opts: { manual?: boolean; force?: boolean }): Prom await setKv("lastRatchet", month); } - // 5. Résumé de la simulation. + // 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)} %`); @@ -461,54 +454,192 @@ async function prepareEvening(opts: { manual?: boolean; force?: boolean }): Prom return log; } -async function analyze(c: Candidate, news: Awaited>, today: string) { +/** 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)), + 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, 8); - const analysis = await analyzeCandidate({ - 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 })), + 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, - 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, }); - if (!analysis) return null; - const db = await getDb(); - const [signal] = await db - .insert(schema.signals) - .values({ - date: today, - symbol: c.symbol, - name: stock.name, - decision: analysis.decision, - confidence: Math.round(analysis.confidence), - thesis: analysis.thesis, - risks: analysis.risks, - expectedMovePct: analysis.expectedMovePct, - stopPct: analysis.stopPct, - targetPct: analysis.targetPct, - horizonDays: Math.round(analysis.horizonDays), - priceAtSignal: quote.price, - currency: quote.currency, - newsIds: items.map((n) => n.id), - }) - .returning(); - return { analysis, signalId: signal.id, symbol: c.symbol, name: stock.name, price: quote.price, currency: quote.currency }; +} + +/** 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) { @@ -517,14 +648,6 @@ function money(n: number, currency: string) { type RiskOk = Extract, { ok: true }>; -/** Dimensionne une fiche d'entraînement sur ton bac à sable, ou sur 200 € neufs s'il n'a plus de place. */ -function trainingRisk(riskInput: (s: PortfolioState) => Parameters[0], sandbox: PortfolioState) { - const r = checkBuy(riskInput(sandbox)); - if (r.ok) return r; - const fresh = { ...sandbox, equity: SIM_INITIAL_CASH, cash: SIM_INITIAL_CASH, positions: [], pendingOrders: [] }; - return checkBuy(riskInput(fresh)); -} - /** 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)} €)`; @@ -574,7 +697,7 @@ function ideaPayload(idea: Idea): ActionPayload { currency: idea.currency, stopPct: 7, targetPct: 12, - amountEur: 150, + amountEur: 100, source: "screen", }; } diff --git a/src/lib/settings.ts b/src/lib/settings.ts index ee7361d..fe8d798 100644 --- a/src/lib/settings.ts +++ b/src/lib/settings.ts @@ -19,16 +19,22 @@ export type Settings = { realLockedReason: string | null; /** Date à laquelle tu as déclaré ton compte Trade Republic ouvert (null = pas encore). */ trAccountOpenedAt: string | null; + /** + * Ce que tu peux investir au total chaque mois (100 €) : la moitié pour le S&P 500 sur le PEA, + * l'autre moitié sur le compte-titres pour la cagnotte. Les deux virements ne peuvent pas le dépasser. + */ + monthlyBudget: number; }; export const SIM_INITIAL_CASH = 200; +export const MONTHLY_BUDGET = 100; -/** Le plan PEA par défaut, proposé quand tu configures ton compte. */ +/** Le plan PEA par défaut, proposé quand tu configures ton compte : la moitié du budget mensuel. */ export function defaultPeaPlan(startDate: string): PeaPlan { return { etfSymbol: DEFAULT_PEA_ETF.symbol, etfName: DEFAULT_PEA_ETF.name, - monthlyAmount: 50, + monthlyAmount: MONTHLY_BUDGET / 2, dayOfMonth: 5, startDate, calibration: null, @@ -42,8 +48,9 @@ function defaults(): Settings { rendezvousMinutes: 19 * 60, // Pas de PEA tant que tu ne l'as pas déclaré : sinon l'app inventerait des versements. peaPlan: null, - realMonthlyDeposit: 50, + realMonthlyDeposit: MONTHLY_BUDGET / 2, realDepositDay: 5, + monthlyBudget: MONTHLY_BUDGET, realDepositsStart: null, aiMonthlyBudgetUsd: 8, askDailyLimit: 10, @@ -53,6 +60,16 @@ function defaults(): Settings { }; } +/** + * Vérifie que les deux virements mensuels (compte-titres + PEA) tiennent dans ton budget. + * Renvoie un message d'erreur, ou null si tout va bien. + */ +export function budgetError(budget: number, cto: number, pea: number): string | null { + if (cto < 0 || pea < 0) return "Les montants ne peuvent pas être négatifs."; + if (cto + pea <= budget + 0.001) return null; + return `Ton budget est de ${budget} € par mois : ${cto} € sur le compte-titres + ${pea} € sur le PEA font ${cto + pea} €. Baisse l'un des deux (conseil : ${budget / 2} € chacun).`; +} + export async function getKv(key: string): Promise { const db = await getDb(); const rows = await db.select().from(schema.kv).where(eq(schema.kv.key, key)); diff --git a/vercel.json b/vercel.json index c5652a4..608a520 100644 --- a/vercel.json +++ b/vercel.json @@ -1,4 +1,8 @@ { "$schema": "https://openapi.vercel.sh/vercel.json", - "regions": ["cdg1"] + "regions": ["cdg1"], + "crons": [ + { "path": "/api/cron/tick", "schedule": "0 17 * * 1-5" }, + { "path": "/api/cron/tick", "schedule": "0 18 * * 1-5" } + ] }