AI daily committee, sandbox advice, 100 EUR budget, evening wake-ups
Some checks failed
Tick / tick (push) Failing after 1s

- Risk rules: up to 2 positions of ~100 EUR under 400 EUR (3 up to 1000,
  4 above), so the AI pot can buy several times a week
- One Sonnet call per day compares up to 6 candidates (news + screener)
  and reviews AI pot and sandbox holdings; the AI pot sells and buys on
  its own, through the deterministic risk engine
- Sandbox: "Le conseil de l'IA" card (what to buy, sell, keep) with
  one-tap follow
- Monthly budget of 100 EUR (half PEA S&P 500, half CTO) enforced when
  saving the account and the PEA plan, shown on Mon compte
- Vercel cron backup (weekday evenings) next to GitHub Actions; the tick
  endpoint records who woke the app, shown in Reglages

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
David 2026-11-18 15:30:57 +01:00
parent dba64728d6
commit 8a0c73901e
18 changed files with 778 additions and 177 deletions

View File

@ -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 ;

View File

@ -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 <AiAdviceCard advice={advice} aiOn={aiEnabled()} today={parisDate()} />;
}
export default function SandboxPage() {
return (
<Page title="Bac à sable" subtitle="Argent fictif, vrais cours et vrais frais Trade Republic (1 € par ordre). Entraîne-toi sans risque.">
<Suspense fallback={<CardSkeleton title="Le conseil de l'IA" height="h-40" />}>
<Advice />
</Suspense>
<Suspense fallback={<CardSkeleton height="h-48" />}>
<SandboxContent />
</Suspense>

View File

@ -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 (
<Card title="Ses dernières analyses">
{!signals.length && <Empty>Aucune analyse pour l&apos;instant. Elles arrivent chaque soir de semaine, 30 minutes avant ton rendez-vous.</Empty>}
{committee && (
<div className="mb-4 rounded-2xl bg-surface-2 p-4">
<p className="text-[13px] text-muted">Son avis sur le marché, {formatDateFr(committee.date)}</p>
<p className="mt-1 text-[15px] leading-relaxed">{committee.marketView}</p>
</div>
)}
{!signals.length && (
<Empty>
Chaque soir de semaine, 30 minutes avant ton rendez-vous, l&apos;IA compare jusqu&apos;à 6 actions, achète les meilleures pour sa cagnotte et te conseille pour ton bac à
sable.
</Empty>
)}
<div className="mb-2 mt-1">
<FindIdeas label="Lancer son analyse maintenant" />
</div>
<ul className="-my-1 divide-y divide-line">
{signals.map((s) => (
<li key={s.id} className="py-4">

View File

@ -156,7 +156,7 @@ async function Todo() {
<ul className="-my-1 divide-y divide-line">
{ideas.items.slice(0, 3).map((i) => (
<li key={i.symbol}>
<Link href={`/actions/${encodeURIComponent(i.symbol)}?montant=150&stop=7&objectif=12`} className="flex items-center justify-between gap-3 py-3">
<Link href={`/actions/${encodeURIComponent(i.symbol)}?montant=100&stop=7&objectif=12`} className="flex items-center justify-between gap-3 py-3">
<span className="font-semibold">{i.name}</span>
<span className="num shrink-0 text-[14px] text-danger">{pct(i.pullbackPct)} cette semaine</span>
</Link>

View File

@ -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 (
<>
<Card title={`Mes ${settings.monthlyBudget} € par mois`}>
<div className="flex h-3 gap-1 overflow-hidden rounded-full" aria-hidden>
<div className="shrink-0 rounded-full bg-accent" style={{ width: `${(peaMonthly / settings.monthlyBudget) * 100}%` }} />
<div className="shrink-0 rounded-full bg-pot" style={{ width: `${(ctoMonthly / settings.monthlyBudget) * 100}%` }} />
{left > 0 && <div className="flex-1 rounded-full bg-surface-2" />}
</div>
<div className="mt-4 grid grid-cols-2 gap-4 text-[14px]">
<div>
<p className="flex items-center gap-2 font-semibold">
<span className="h-2.5 w-2.5 rounded-full bg-accent" aria-hidden />
PEA, S&amp;P 500
</p>
<p className="amount mt-1 text-[1.4rem] font-semibold">{eur(peaMonthly, 0)}</p>
<p className="text-[13px] text-muted">à l&apos;abri, plan d&apos;épargne automatique</p>
</div>
<div>
<p className="flex items-center gap-2 font-semibold">
<span className="h-2.5 w-2.5 rounded-full bg-pot" aria-hidden />
Compte-titres
</p>
<p className="amount mt-1 text-[1.4rem] font-semibold">{eur(ctoMonthly, 0)}</p>
<p className="text-[13px] text-muted">la cagnotte que l&apos;IA fait travailler</p>
</div>
</div>
{left > 0 && <p className="mt-3 text-[13px] text-muted">Il reste {eur(left, 0)} non attribués chaque mois.</p>}
</Card>
<Card
title="Mon compte-titres"
tone={configured ? undefined : "pot"}

View File

@ -52,22 +52,59 @@ function ago(iso: string | undefined) {
return new Date(iso).toLocaleString("fr-FR", { timeZone: "Europe/Paris", dateStyle: "short", timeStyle: "short" });
}
/** 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) => (
function Row({ ok, label, hint, value }: { ok: boolean | null; label: string; hint?: string; value: React.ReactNode }) {
return (
<li className="flex items-center justify-between gap-3 py-2.5">
<span className="flex items-center gap-2">
<span className={`h-2 w-2 shrink-0 rounded-full ${ok ? "bg-gain" : "bg-pot"}`} aria-hidden />
<span className={`h-2 w-2 shrink-0 rounded-full ${ok === null ? "bg-line" : ok ? "bg-gain" : "bg-pot"}`} aria-hidden />
<span>
{label}
{!ok && <span className="sr-only"> (à vérifier)</span>}
{ok === false && <span className="sr-only"> (à vérifier)</span>}
{hint && <span className="block text-[13px] text-muted">{hint}</span>}
</span>
</span>
<span className="num shrink-0 text-right text-muted">{value}</span>
</li>
);
}
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 (
<Card title="Réveils automatiques">
<p className="mb-3 text-[14px] leading-relaxed text-muted">
Sur Vercel, l&apos;app dort tant que personne ne l&apos;appelle. Ces réveils lui permettent de préparer ton rendez-vous du soir et de t&apos;envoyer la notification.
</p>
<ul className="-my-1 divide-y divide-line text-[15px]">
<Row ok={hoursSince(github) < 72} label="GitHub" hint="toutes les 30 minutes en semaine" value={ago(github ?? undefined)} />
<Row ok={hoursSince(vercel) < 96} label="Vercel (secours)" hint="vers 18h et 19h en semaine" value={ago(vercel ?? undefined)} />
<Row ok={shortcut ? hoursSince(shortcut) < 96 : null} label="Raccourci iPhone" hint="facultatif" value={ago(shortcut ?? undefined)} />
</ul>
{none && (
<p className="mt-3 text-[14px] leading-relaxed text-danger">
Aucun réveil automatique n&apos;a encore eu lieu : le rendez-vous ne se prépare que quand tu ouvres l&apos;app après 18h30. Vérifie les secrets APP_URL et CRON_SECRET (voir le
README).
</p>
)}
{!d.cronConfigured && <p className="mt-3 text-[14px] text-danger">CRON_SECRET n&apos;est pas réglé sur le serveur : aucun réveil ne peut fonctionner.</p>}
</Card>
);
}
/** 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) => <Row ok={ok} label={label} value={value} />;
return (
<Card title="Diagnostic de l'IA">
<ul className="-my-1 divide-y divide-line text-[15px]">
@ -129,6 +166,10 @@ export default function SettingsPage() {
</Link>
</Card>
<Suspense fallback={<CardSkeleton title="Réveils automatiques" height="h-32" />}>
<Wakes />
</Suspense>
<Suspense fallback={<CardSkeleton title="Diagnostic de l'IA" height="h-40" />}>
<Diagnostics />
</Suspense>

View File

@ -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<Fo
const quote = await getQuote(symbol);
if (!quote) return { ok: false, message: `ETF « ${symbol} » introuvable. Garde ESE.PA si tu as un doute.` };
const calShares = parseNum(formData.get("calibrationShares"));
const peaAmount = parseNum(formData.get("peaAmount")) ?? base.monthlyAmount;
const overBudget = budgetError(s.monthlyBudget, s.realMonthlyDeposit, peaAmount);
if (overBudget) return { ok: false, message: overBudget };
await updateSettings({
peaPlan: {
etfSymbol: symbol,
etfName: quote.name,
monthlyAmount: parseNum(formData.get("peaAmount")) ?? base.monthlyAmount,
monthlyAmount: peaAmount,
dayOfMonth: clampDay(parseNum(formData.get("peaDay")), base.dayOfMonth),
startDate: String(formData.get("peaStart") ?? "").trim() || base.startDate,
calibration: calShares !== null ? { date: parisDate(), shares: calShares } : (base.calibration ?? null),

View File

@ -1,18 +1,36 @@
import { NextResponse, type NextRequest } from "next/server";
import { safeEqual } from "@/lib/auth";
import { tick } from "@/lib/jobs";
import { setKv } from "@/lib/settings";
export const maxDuration = 300;
/** Appelé toutes les 30 minutes par GitHub Actions avec l'en-tête « Authorization: Bearer CRON_SECRET ». */
/** Qui a réveillé l'app : sert à vérifier dans Réglages que chaque réveil automatique fonctionne. */
type WakeSource = "github" | "vercel" | "raccourci";
function sourceOf(request: NextRequest): WakeSource {
const ua = request.headers.get("user-agent") ?? "";
if (ua.startsWith("vercel-cron")) return "vercel";
if (ua.startsWith("curl")) return "github";
return "raccourci";
}
/**
* Réveil de l'app, avec l'en-tête « Authorization: Bearer CRON_SECRET ». Trois réveils possibles :
* - GitHub Actions, toutes les 30 minutes en semaine (.github/workflows/tick.yml) ;
* - Vercel, 2 fois par soir en semaine, en secours (vercel.json, gratuit : une fois par jour par tâche) ;
* - un raccourci iPhone, si tu en programmes un.
*/
async function handle(request: NextRequest) {
const expected = process.env.CRON_SECRET;
const given = request.headers.get("authorization")?.replace(/^Bearer /, "") ?? "";
if (!expected || !safeEqual(given, expected)) {
return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
}
const source = sourceOf(request);
await setKv(`lastWake:${source}`, new Date().toISOString());
const log = await tick();
return NextResponse.json({ ok: true, log });
return NextResponse.json({ ok: true, source, log });
}
export const GET = handle;

View File

@ -0,0 +1,140 @@
"use client";
import Link from "next/link";
import { useState, useTransition } from "react";
import { followAiAdvice, sandboxSell } from "@/app/actions";
import type { AiAdvice } from "@/lib/jobs";
import { eur, price } from "@/lib/format";
import { FindIdeas } from "./find-ideas";
import { Badge, Card, Empty, primaryBtn, secondaryBtn } from "./ui";
function when(advice: AiAdvice, today: string) {
if (advice.date === today) return "aujourd'hui";
return `le ${advice.date.split("-").reverse().slice(0, 2).join("/")}`;
}
/** Le conseil de l'IA pour ton bac à sable : quoi acheter, quoi vendre, quoi garder. Un toucher pour le suivre. */
export function AiAdviceCard({ advice, aiOn, today }: { advice: AiAdvice | null; aiOn: boolean; today: string }) {
const [pending, start] = useTransition();
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
const [why, setWhy] = useState(false);
if (!aiOn) {
return (
<Card title="Le conseil de l'IA">
<Empty>L&apos;IA n&apos;est pas branchée (clé Anthropic manquante). En attendant, les idées sans IA de l&apos;onglet Actions sont là pour t&apos;entraîner.</Empty>
</Card>
);
}
if (!advice) {
return (
<Card title="Le conseil de l'IA">
<Empty>Chaque soir de semaine, l&apos;IA compare plusieurs actions et te dit laquelle essayer ici. Tu peux lui demander maintenant.</Empty>
<div className="mt-4">
<FindIdeas label="Demander son conseil maintenant" />
</div>
</Card>
);
}
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 (
<Card title="Le conseil de l'IA" tone={pick || advice.sells.length ? "accent" : undefined} action={<span className="text-[13px] text-muted">{when(advice, today)}</span>}>
{pick ? (
<>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<p className="text-[14px] text-muted">Elle te conseille d&apos;essayer</p>
<Link href={`/actions/${encodeURIComponent(pick.symbol)}`} className="display mt-0.5 block text-[1.7rem] font-bold">
{pick.name}
</Link>
</div>
<Badge tone="gain">confiance {pick.confidence} %</Badge>
</div>
<p className="mt-3 text-[15px] leading-relaxed">{pick.thesis}</p>
<dl className="mt-4 grid grid-cols-3 gap-3 rounded-2xl bg-surface-2 p-4 text-[13px]">
<div>
<dt className="text-muted">Montant</dt>
<dd className="amount mt-1 text-[1.2rem] font-semibold">{pick.amountEur ? eur(pick.amountEur, 0) : "–"}</dd>
</div>
<div>
<dt className="text-muted">Stop</dt>
<dd className="amount mt-1 text-[1.2rem] font-semibold text-danger">−{String(pick.stopPct).replace(".", ",")} %</dd>
</div>
<div>
<dt className="text-muted">Objectif</dt>
<dd className="amount mt-1 text-[1.2rem] font-semibold text-gain">+{String(pick.targetPct).replace(".", ",")} %</dd>
</div>
</dl>
<p className="mt-2 text-[13px] text-muted">
Cours à l&apos;analyse : {price(pick.price, pick.currency)}. Durée prévue : environ {pick.horizonDays} jours de bourse.
</p>
<button type="button" onClick={() => setWhy(!why)} aria-expanded={why} className="mt-3 text-[14px] font-semibold text-accent">
{why ? "Masquer les risques" : "Ce qui peut mal tourner"}
</button>
{why && <p className="mt-2 text-[15px] leading-relaxed text-muted">{pick.risks}</p>}
{pick.amountEur ? (
<button className={`${primaryBtn} mt-4 w-full`} disabled={pending} onClick={buy}>
{pending ? "Achat en cours…" : `Suivre son conseil : acheter pour ${eur(pick.amountEur, 0)}`}
</button>
) : (
<p className="mt-4 rounded-2xl bg-pot-soft p-4 text-[14px] leading-relaxed">{pick.blockedReason} Vends une position ou attends qu&apos;un stop ou un objectif se déclenche.</p>
)}
</>
) : (
<>
<p className="display text-[1.4rem] font-bold">Elle te conseille d&apos;attendre</p>
<p className="mt-2 text-[15px] leading-relaxed text-muted">{advice.marketView}</p>
</>
)}
{advice.sells.length > 0 && (
<div className="mt-5 border-t border-line pt-4">
<p className="mb-1 text-[15px] font-semibold">À vendre dans ton bac à sable</p>
<ul className="-my-1 divide-y divide-line">
{advice.sells.map((s) => (
<li key={s.positionId} className="py-3">
<p className="font-semibold">{s.name}</p>
<p className="mt-0.5 text-[14px] leading-relaxed text-muted">{s.reason}</p>
<button className={`${secondaryBtn} mt-2 h-10 w-full`} disabled={pending} onClick={() => sell(s.positionId, s.name)}>
Vendre {s.name}
</button>
</li>
))}
</ul>
</div>
)}
{advice.keeps.length > 0 && (
<div className="mt-4 border-t border-line pt-4">
<p className="mb-1 text-[15px] font-semibold">À garder</p>
<ul className="flex flex-col gap-2 text-[14px] leading-relaxed">
{advice.keeps.map((k) => (
<li key={k.positionId}>
<span className="font-semibold">{k.name}</span> <span className="text-muted">{k.reason}</span>
</li>
))}
</ul>
</div>
)}
{msg && <p className={`mt-3 text-[14px] font-semibold ${msg.ok ? "text-gain" : "text-danger"}`}>{msg.text}</p>}
</Card>
);
}

View File

@ -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));

View File

@ -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<Analysis | null> {
// ---------------------------------------------------------------------------
// 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<typeof CommitteeSchema>;
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<CommitteeResult | null> {
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;
}

View File

@ -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<typeof import("./ai")>();
return {
...real,
aiEnabled: () => true,
triageNews: async () => [],
dailyCommittee: async (input: Parameters<typeof real.dailyCommittee>[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);
});
});

View File

@ -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<string>("lastWake:github"),
getKv<string>("lastWake:vercel"),
getKv<string>("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,

View File

@ -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);
});
});

View File

@ -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;
}

View File

@ -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<string[]> {
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<ReturnType<typeof recentNews>>, exclude: string[], ideas: Idea[]): Candidate[] {
const bySymbol = new Map<string, Candidate>();
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<ReturnType<typeof runCommittee>> = 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<string>("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<ReturnType<typeof recentNews>>, 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<ReturnType<typeof recentNews>>, 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<ReturnType<typeof runCommittee>>, sandbox: PortfolioState, today: string): Promise<AiAdvice | null> {
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<AiAdvice | null> {
return getKv<AiAdvice>("aiAdvice");
}
function money(n: number, currency: string) {
@ -517,14 +648,6 @@ function money(n: number, currency: string) {
type RiskOk = Extract<ReturnType<typeof checkBuy>, { 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<typeof checkBuy>[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",
};
}

View File

@ -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<T>(key: string): Promise<T | null> {
const db = await getDb();
const rows = await db.select().from(schema.kv).where(eq(schema.kv.key, key));

View File

@ -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" }
]
}