Compare commits

..

No commits in common. "dba64728d6706a93c6726c9f4ad3f4d094ef719a" and "82093744f30c839a5508f1f6cc5f728ed5a3aa29" have entirely different histories.

45 changed files with 735 additions and 1697 deletions

View File

@ -122,6 +122,6 @@ GitHub Actions (toutes les 30 min, en semaine)
**Le coupe-circuit** : si la cagnotte réelle tombe sous 50 % de ce que tu y as versé, retour en simulation.
**Limites connues** :
- La simulation utilise des barres journalières. Si le cours ouvre au-delà du stop ou de l'objectif, l'ordre part au prix d'ouverture. Si les deux sont touchés dans la même journée sans trou de cotation, on suppose le stop.
- Jours fériés gérés : ceux de Trade Republic (1er janvier, Vendredi saint, lundi de Pâques, 24, 25, 26 et 31 décembre). Les autres fermetures exceptionnelles ne le sont pas.
- La simulation utilise des barres journalières. Si un stop et un objectif sont touchés le même jour, on suppose le stop.
- Les jours fériés ne sont pas gérés.
- Les cours US viennent de la Bourse américaine, alors que Trade Republic cote sur LS Exchange avec un petit écart. On compte 0,1 % de glissement par ordre.

View File

@ -7,11 +7,6 @@ const nextConfig: NextConfig = {
outputFileTracingIncludes: { "/**": ["./drizzle/**"] },
cacheComponents: true,
partialPrefetching: true,
experimental: {
// Un onglet déjà ouvert se réaffiche instantanément pendant 1 minute (au lieu d'être rechargé à chaque toucher).
// Toute action (achat, réponse à une fiche...) vide ce cache : on ne voit jamais un état périmé après avoir agi.
staleTimes: { dynamic: 60 },
},
turbopack: {
rules: {
"*.css": {

View File

@ -1,12 +1,12 @@
import { Suspense } from "react";
import Link from "next/link";
import { notFound } from "next/navigation";
import { connection } from "next/server";
import { and, desc, eq } from "drizzle-orm";
import { PositionList } from "@/components/positions";
import { StockChart } from "@/components/stock-chart";
import { TradePanel } from "@/components/trade-panel";
import { Badge, Card, CardSkeleton, Delta, Empty, Page } from "@/components/ui";
import { BackLink } from "@/components/nav";
import { Badge, Card, CardSkeleton, Empty, Page } from "@/components/ui";
import { aiEnabled, getAiSpend } from "@/lib/ai";
import { getDb, schema } from "@/lib/db";
import { pct, price, timeAgo } from "@/lib/format";
@ -52,32 +52,26 @@ async function StockContent({ params, searchParams }: Props) {
return (
<Page
title={stock?.name ?? quote.name}
subtitle={`${symbol}${stock ? `, ${stock.market === "US" ? "Bourse américaine" : "Bourse européenne"}` : ""}`}
action={<BackLink href="/actions" label="Actions" />}
subtitle={`${symbol}${stock ? ` · ${stock.market === "US" ? "Bourse américaine" : "Bourse européenne"}` : ""}`}
action={
<Link href="/actions" className="text-sm font-medium text-accent">
‹ Actions
</Link>
}
>
<Card>
<div className="flex items-end justify-between gap-3">
<div>
<p className="amount text-[2.8rem] font-bold">{price(quote.price, quote.currency)}</p>
{quote.currency === "USD" && fx && <p className="num mt-1.5 text-[14px] text-muted">soit {(quote.price * fx).toFixed(2).replace(".", ",")} € chez Trade Republic</p>}
</div>
<div className="pb-1 text-right text-[14px]">
{quote.changePct !== null && (
<p>
<Delta value={quote.changePct}>{pct(quote.changePct, 2)}</Delta> <span className="text-muted">aujourd&apos;hui</span>
</p>
)}
{change3m !== null && (
<p className="mt-0.5">
<Delta value={change3m}>{pct(change3m)}</Delta> <span className="text-muted">en 3 mois</span>
</p>
)}
<p className="num text-3xl font-semibold">{price(quote.price, quote.currency)}</p>
<div className="text-right text-sm">
{quote.changePct !== null && <p className={`num font-semibold ${quote.changePct >= 0 ? "text-accent" : "text-danger"}`}>{pct(quote.changePct, 2)} auj.</p>}
{change3m !== null && <p className={`num text-xs ${change3m >= 0 ? "text-accent" : "text-danger"}`}>{pct(change3m)} sur 3 mois</p>}
</div>
</div>
<div className="mt-4">
{quote.currency === "USD" && fx && <p className="num mt-1 text-xs text-muted">≈ {(quote.price * fx).toFixed(2)} € chez Trade Republic</p>}
<div className="mt-3">
<StockChart bars={bars} lastPrice={quote.price} stop={held[0]?.stopPrice} target={held[0]?.targetPrice} />
</div>
{earnings && <p className="mt-3 text-[13px] text-muted">Prochains résultats le {formatDateFr(earnings)}. L&apos;app n&apos;achète jamais dans les 4 jours qui précèdent.</p>}
{earnings && <p className="mt-2 text-xs text-muted">📅 Prochains résultats : {formatDateFr(earnings)}</p>}
</Card>
{held.length > 0 && (
@ -87,13 +81,13 @@ async function StockContent({ params, searchParams }: Props) {
)}
{signal && (
<Card title="Ce qu'en pense l'IA" action={<span className="text-[13px] text-muted">{formatDateFr(signal.date)}</span>}>
<p className="mb-2 flex items-center gap-2">
<Badge tone={signal.decision === "buy" ? "gain" : "neutral"}>{signal.decision === "buy" ? "Achète" : "Passe son tour"}</Badge>
<span className="text-[13px] text-muted">confiance {signal.confidence} %</span>
<Card title={`Dernière analyse de l'IA · ${formatDateFr(signal.date)}`}>
<p className="mb-2">
<Badge tone={signal.decision === "buy" ? "accent" : "neutral"}>{signal.decision === "buy" ? "Achat" : "On passe"}</Badge>{" "}
<span className="text-xs text-muted">confiance {signal.confidence} %</span>
</p>
<p className="text-[15px] leading-relaxed">{signal.thesis}</p>
<p className="mt-1.5 text-[14px] leading-relaxed text-muted">Risques : {signal.risks}</p>
<p className="text-sm leading-relaxed">{signal.thesis}</p>
<p className="mt-1 text-sm leading-relaxed text-muted">⚠️ {signal.risks}</p>
</Card>
)}
@ -117,22 +111,16 @@ async function StockContent({ params, searchParams }: Props) {
<Card title="Actus récentes">
{!news.length && <Empty>Pas d&apos;actu récente.</Empty>}
<ul className="-my-1 divide-y divide-line">
<ul className="divide-y divide-line">
{news.map((n) => (
<li key={n.id} className="py-3">
<a href={n.url ?? "#"} target="_blank" rel="noreferrer" className="text-[15px] font-semibold leading-snug">
<li key={n.id} className="py-2.5">
<a href={n.url ?? "#"} target="_blank" rel="noreferrer" className="text-sm font-medium leading-snug">
{n.title}
</a>
{n.triage?.reason && <p className="mt-1 text-[14px] leading-relaxed text-muted">{n.triage.reason}</p>}
<p className="mt-1 flex flex-wrap items-center gap-x-2 text-[13px] text-muted">
<span>
{n.publisher}, {timeAgo(n.publishedAt)}
</span>
{n.triage && (
<Badge tone={n.triage.direction === "positive" ? "gain" : n.triage.direction === "negative" ? "danger" : "neutral"}>
{n.triage.direction === "positive" ? "Bonne nouvelle" : n.triage.direction === "negative" ? "Mauvaise nouvelle" : "Neutre"}, {n.triage.relevance}/10
</Badge>
)}
{n.triage?.reason && <p className="mt-1 text-xs leading-relaxed text-muted">{n.triage.reason}</p>}
<p className="mt-1 text-xs text-muted">
{n.publisher} · {timeAgo(n.publishedAt)}
{n.triage && ` · ${n.triage.direction === "positive" ? "▲" : n.triage.direction === "negative" ? "▼" : "•"} ${n.triage.relevance}/10`}
</p>
</li>
))}
@ -146,7 +134,7 @@ export default function StockPage(props: Props) {
return (
<Suspense
fallback={
<Page title=" " action={<BackLink href="/actions" label="Actions" />}>
<Page title="Chargement…">
<CardSkeleton height="h-40" />
<CardSkeleton height="h-64" />
</Page>

View File

@ -2,7 +2,7 @@ import { Suspense } from "react";
import Link from "next/link";
import { connection } from "next/server";
import { StockBrowser, type StockRow } from "@/components/stock-browser";
import { Badge, Card, CardSkeleton, Empty, Page } from "@/components/ui";
import { Card, CardSkeleton, Empty, Page } from "@/components/ui";
import { pct } from "@/lib/format";
import { getIdeas } from "@/lib/ideas";
import { getQuotes } from "@/lib/market";
@ -15,17 +15,17 @@ async function Ideas() {
const ideas = await getIdeas();
const items = ideas?.items.slice(0, 4) ?? [];
return (
<Card title="Idées du moment" action={<Badge>Sans IA</Badge>}>
<Card title="Idées du moment" action={<span className="text-xs text-muted">filtre sans IA</span>}>
{!items.length && <Empty>Les idées se calculent à l&apos;ouverture de l&apos;app : reviens dans une minute.</Empty>}
<ul className="-my-1 divide-y divide-line">
<ul className="flex flex-col gap-2">
{items.map((i) => (
<li key={i.symbol}>
<Link href={`/actions/${encodeURIComponent(i.symbol)}`} className="block py-3">
<Link href={`/actions/${encodeURIComponent(i.symbol)}`} className="block rounded-xl bg-surface-2 p-3">
<span className="flex items-center justify-between gap-2">
<span className="font-semibold">{i.name}</span>
<span className="num shrink-0 text-[14px] font-semibold text-danger">{pct(i.pullbackPct)} en 5 jours</span>
<span className="num text-sm text-danger">{pct(i.pullbackPct)} sur 5 j</span>
</span>
<span className="mt-1 block text-[13px] leading-relaxed text-muted">{i.reason}</span>
<span className="mt-1 block text-xs leading-relaxed text-muted">{i.reason}</span>
</Link>
</li>
))}
@ -57,10 +57,10 @@ export default function ActionsPage() {
return (
<Page
title="Actions"
subtitle="Les grandes entreprises américaines et européennes suivies par l'app. Touche-en une pour la voir et l'essayer."
subtitle="Les grandes actions US et Europe suivies par l'app. Touche une action pour la voir et l'acheter dans ton bac à sable."
action={
<Link href="/actus" className="inline-flex h-10 items-center rounded-full bg-surface px-4 text-[14px] font-semibold text-ink dark:ring-1 dark:ring-line">
Actus
<Link href="/actus" className="text-sm font-medium text-accent">
📰 Actus
</Link>
}
>

View File

@ -1,7 +1,6 @@
import { Suspense } from "react";
import { connection } from "next/server";
import { PageSkeleton } from "@/components/page-skeleton";
import { BackLink } from "@/components/nav";
import { Badge, Card, Empty, Page } from "@/components/ui";
import { timeAgo } from "@/lib/format";
import { recentNews } from "@/lib/news";
@ -34,23 +33,23 @@ async function NewsPageContent() {
return (
<li key={n.id} className="py-3">
<div className="mb-1 flex flex-wrap items-center gap-1.5">
<span className="text-[13px] font-semibold">{findStock(n.symbol)?.name ?? n.symbol}</span>
<span className="text-xs font-semibold">{findStock(n.symbol)?.name ?? n.symbol}</span>
{t && (
<>
<Badge tone={t.direction === "positive" ? "gain" : t.direction === "negative" ? "danger" : "neutral"}>
{t.direction === "positive" ? "Bonne nouvelle" : t.direction === "negative" ? "Mauvaise nouvelle" : "Neutre"}
<Badge tone={t.direction === "positive" ? "accent" : t.direction === "negative" ? "danger" : "neutral"}>
{t.direction === "positive" ? "▲ positif" : t.direction === "negative" ? "▼ négatif" : "neutre"}
</Badge>
<Badge>{EVENT_LABELS[t.eventType] ?? t.eventType}</Badge>
<span className="num text-[13px] text-muted">{t.relevance}/10</span>
<span className="num text-xs text-muted">{t.relevance}/10</span>
</>
)}
{!t && <Badge>pas encore triée</Badge>}
</div>
<a href={n.url ?? "#"} target="_blank" rel="noreferrer" className="text-[15px] font-semibold leading-snug">
<a href={n.url ?? "#"} target="_blank" rel="noreferrer" className="text-sm font-medium leading-snug">
{n.title}
</a>
{t?.reason && <p className="mt-1 text-[13px] leading-relaxed text-muted">{t.reason}</p>}
<p className="mt-1 text-[13px] text-muted">
{t?.reason && <p className="mt-1 text-xs leading-relaxed text-muted">{t.reason}</p>}
<p className="mt-1 text-xs text-muted">
{n.publisher} · {timeAgo(n.publishedAt)}
</p>
</li>
@ -58,12 +57,12 @@ async function NewsPageContent() {
};
return (
<Page title="Actus" subtitle="Les actus des 48 dernières heures, notées par l'IA de 0 à 10." action={<BackLink href="/actions" label="Actions" />}>
<Card title="Ce qui compte" action={<Badge>7/10 et plus</Badge>}>
{important.length ? <ul className="-my-1 divide-y divide-line">{important.map(item)}</ul> : <Empty>Rien de marquant pour l&apos;instant.</Empty>}
<Page title="Actus" subtitle="Les actus des 48 dernières heures, notées par l'IA de 0 à 10.">
<Card title="Importantes (7/10 et plus)">
{important.length ? <ul className="divide-y divide-line">{important.map(item)}</ul> : <Empty>Rien de marquant pour l&apos;instant.</Empty>}
</Card>
<Card title="Les autres">
{others.length ? <ul className="-my-1 divide-y divide-line">{others.map(item)}</ul> : <Empty>Aucune actu collectée pour l&apos;instant.</Empty>}
{others.length ? <ul className="divide-y divide-line">{others.map(item)}</ul> : <Empty>Aucune actu collectée pour l&apos;instant.</Empty>}
</Card>
</Page>
);

View File

@ -17,26 +17,21 @@ async function SandboxContent() {
return (
<>
<Card>
<p className="text-[15px] text-muted">Mes 200 € virtuels valent</p>
<div className="mt-1 flex items-end justify-between gap-3">
<p className="amount text-[3rem] font-bold">{eur(state.equity)}</p>
<p className="amount pb-1 text-[1.4rem]">
<Card title="Ma cagnotte virtuelle">
<div className="flex items-end justify-between">
<p className="num text-3xl font-semibold">{eur(state.equity)}</p>
<Delta value={perf}>{pct(perf)}</Delta>
</p>
</div>
<div className="mt-5 grid grid-cols-3 gap-3">
<Stat label="à investir">{eur(state.cash, 0)}</Stat>
<div className="mt-3 grid grid-cols-3 gap-2 text-sm">
<Stat label="liquidités">{eur(state.cash, 0)}</Stat>
<Stat label="gains encaissés">{signedEur(realized)}</Stat>
<Stat label="trades gagnants">{closed.length ? `${wins} sur ${closed.length}` : "–"}</Stat>
<Stat label="trades gagnants">{closed.length ? `${wins}/${closed.length}` : "—"}</Stat>
</div>
<Link href="/actions" className={`${primaryBtn} mt-5 w-full`}>
Choisir une action à acheter
<Link href="/actions" className={`${primaryBtn} mt-4 w-full`}>
+ Acheter une action
</Link>
{!isTradeRepublicOpen() && (
<p className="mt-3 text-[13px] leading-relaxed text-muted">
Trade Republic est fermé (de 7h30 à 23h en semaine) : tes ordres partiront à la réouverture, comme en vrai.
</p>
<p className="mt-2 text-xs text-muted">Trade Republic est fermé (7h30-23h en semaine) : tes ordres s&apos;exécuteront à la réouverture, comme en vrai.</p>
)}
</Card>
@ -50,7 +45,7 @@ async function SandboxContent() {
<PositionList positions={state.positions} sellable />
</Card>
<Card title="Mes trades terminés">
<Card title="Historique">
<ClosedList positions={closed} />
</Card>
<ResetSandbox />
@ -60,8 +55,8 @@ async function SandboxContent() {
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 height="h-48" />}>
<Page title="Bac à sable" subtitle="Argent fictif, cours réels, frais Trade Republic (1 € par ordre). Entraîne-toi sans risque.">
<Suspense fallback={<CardSkeleton title="Ma cagnotte virtuelle" height="h-40" />}>
<SandboxContent />
</Suspense>
</Page>

View File

@ -1,122 +1,89 @@
import { Suspense } from "react";
import { connection } from "next/server";
import { PageSkeleton } from "@/components/page-skeleton";
import { desc } from "drizzle-orm";
import { ClosedList, PendingOrders, PositionList } from "@/components/positions";
import { ResetAi } from "@/components/reset-ai";
import { Badge, Card, CardSkeleton, Delta, Empty, Page, Stat } from "@/components/ui";
import { Badge, Card, Empty, Page } from "@/components/ui";
import { getDb, schema } from "@/lib/db";
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 { aiDeposits, aiPerformance } from "@/lib/stats";
import { formatDateFr } from "@/lib/time";
async function Pot() {
async function AiPageContent() {
await connection();
const [state, closed, deposits, settings] = await Promise.all([getPortfolioState("ai_sim"), getClosedPositions("ai_sim", 100), aiDeposits(), getSettings()]);
const perf = aiPerformance(state, deposits);
const db = await getDb();
const [state, closed, signals] = await Promise.all([
getPortfolioState("ai_sim"),
getClosedPositions("ai_sim", 100),
db.select().from(schema.signals).orderBy(desc(schema.signals.createdAt)).limit(20),
]);
const perf = (state.equity / state.initialCash - 1) * 100;
const wins = closed.filter((p) => (p.pnlEur ?? 0) > 0).length;
const fees = closed.reduce((s, p) => s + p.feesEur, 0);
const stuck = aiSimStuck(state);
return (
<>
<Card tone="pot">
<p className="text-[15px] text-muted">Sa cagnotte aujourd&apos;hui</p>
<div className="mt-1 flex items-end justify-between gap-3">
<p className="amount text-[3rem] font-bold">{eur(state.equity)}</p>
<p className="amount pb-1 text-[1.4rem]">
<Delta value={perf.pct}>{pct(perf.pct)}</Delta>
</p>
<Page title="La cagnotte de l'IA" subtitle="200 € virtuels, gérés seuls par l'IA avec exactement les règles du réel.">
<Card title="Résultat">
<div className="flex items-end justify-between">
<p className="num text-3xl font-semibold">{eur(state.equity)}</p>
<p className={`num text-lg font-semibold ${perf >= 0 ? "text-accent" : "text-danger"}`}>{pct(perf)}</p>
</div>
<div className="num mt-3 grid grid-cols-3 gap-2 text-center text-sm">
<div className="rounded-xl bg-surface-2 p-2">
<p className="text-lg font-semibold">{closed.length}</p>
<p className="text-xs text-muted">trades</p>
</div>
<div className="rounded-xl bg-surface-2 p-2">
<p className="text-lg font-semibold">{closed.length ? Math.round((wins / closed.length) * 100) : 0} %</p>
<p className="text-xs text-muted">gagnants</p>
</div>
<div className="rounded-xl bg-surface-2 p-2">
<p className="text-lg font-semibold">{eur(fees, 0)}</p>
<p className="text-xs text-muted">frais payés</p>
</div>
<p className="mt-2 text-[14px] text-muted">
Sur {eur(perf.contributed, 0)} reçus : 200 € au départ le {formatDateFr(settings.simStartDate)}
{deposits.length ? `, puis ${deposits.length} versement${deposits.length > 1 ? "s" : ""} de ${settings.realMonthlyDeposit} €` : ""}.
</p>
<div className="mt-5 grid grid-cols-3 gap-3">
<Stat label="trades finis">{closed.length}</Stat>
<Stat label="gagnants">{closed.length ? `${Math.round((wins / closed.length) * 100)} %` : "–"}</Stat>
<Stat label="frais payés">{eur(fees, 0)}</Stat>
</div>
</Card>
{stuck && (
<Card tone="danger" title="L'IA ne peut plus acheter">
<p className="text-[15px] leading-relaxed">
Il lui reste {eur(state.cash)}, sous le minimum de {MIN_POSITION_EUR} € par position. Elle reprendra après le prochain versement de {settings.realMonthlyDeposit} €, le{" "}
{settings.realDepositDay} du mois. Si tu estimes qu&apos;elle a échoué, remets-la à zéro.
</p>
<div className="mt-4">
<ResetAi stuck />
</div>
</Card>
)}
<Card title="Ce qu'elle détient">
<Card title="Position en cours">
<PositionList positions={state.positions} />
{state.pendingOrders.length > 0 && (
<div className="mt-4 border-t border-line pt-3">
<p className="mb-1 text-[14px] font-semibold text-muted">Ordres en attente</p>
<div className="mt-3">
<PendingOrders orders={state.pendingOrders} />
</div>
)}
</Card>
<Card title="Ses trades terminés">
<ClosedList positions={closed} />
</Card>
{!stuck && (
<Card title="Repartir de zéro">
<p className="mb-4 text-[15px] leading-relaxed text-muted">
Chaque mois, l&apos;IA reçoit le même versement que ton compte-titres ({settings.realMonthlyDeposit} €), comme en vrai. Tu peux aussi effacer sa simulation et lui redonner
200 €.
</p>
<ResetAi stuck={false} />
</Card>
)}
</>
);
}
async function Signals() {
await connection();
const db = await getDb();
const signals = await db.select().from(schema.signals).orderBy(desc(schema.signals.createdAt)).limit(20);
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>}
<ul className="-my-1 divide-y divide-line">
<Card title="Dernières analyses">
{!signals.length && <Empty>Aucune analyse pour l&apos;instant. Elles arrivent chaque soir.</Empty>}
<ul className="flex flex-col gap-3">
{signals.map((s) => (
<li key={s.id} className="py-4">
<li key={s.id} className="rounded-xl bg-surface-2 p-3 text-sm">
<div className="flex flex-wrap items-center gap-2">
<span className="font-semibold">{s.name}</span>
<Badge tone={s.decision === "buy" ? "gain" : "neutral"}>{s.decision === "buy" ? "Achète" : "Passe son tour"}</Badge>
<span className="text-[13px] text-muted">
{formatDateFr(s.date)}, confiance {s.confidence} %
<Badge tone={s.decision === "buy" ? "accent" : "neutral"}>{s.decision === "buy" ? "Achat" : "On passe"}</Badge>
<span className="text-xs text-muted">
{s.date} · confiance {s.confidence} %
</span>
</div>
<p className="mt-2 text-[15px] leading-relaxed">{s.thesis}</p>
<p className="mt-1.5 text-[14px] leading-relaxed text-muted">Risques : {s.risks}</p>
{s.riskVerdict && s.riskVerdict !== "accepté" && <p className="mt-1.5 text-[13px] text-warn">Refusé par le contrôle des risques : {s.riskVerdict}</p>}
<p className="mt-2 leading-relaxed">{s.thesis}</p>
<p className="mt-1 leading-relaxed text-muted">⚠️ {s.risks}</p>
{s.riskVerdict && s.riskVerdict !== "accepté" && <p className="mt-1 text-xs text-warn">Contrôle des risques : {s.riskVerdict}</p>}
</li>
))}
</ul>
</Card>
<Card title="Trades terminés">
<ClosedList positions={closed} />
</Card>
</Page>
);
}
export default function AiPage() {
return (
<Page title="La cagnotte de l'IA" subtitle="De l'argent virtuel que l'IA gère seule, avec exactement les règles du réel.">
<Suspense fallback={<CardSkeleton height="h-44" />}>
<Pot />
<Suspense fallback={<PageSkeleton title={"La cagnotte de l'IA"} />}>
<AiPageContent />
</Suspense>
<Suspense fallback={<CardSkeleton title="Ses dernières analyses" height="h-48" />}>
<Signals />
</Suspense>
</Page>
);
}

View File

@ -4,7 +4,7 @@ import { connection } from "next/server";
import { ActionCard } from "@/components/action-card";
import { FindIdeas } from "@/components/find-ideas";
import { SettingsLink } from "@/components/nav";
import { Badge, Card, CardSkeleton, Delta, Empty, primaryBtn } from "@/components/ui";
import { Badge, Card, CardSkeleton, Delta, Empty, Page, primaryBtn } from "@/components/ui";
import { aiEnabled, getAiSpend } from "@/lib/ai";
import { getLatestRendezvous, getPendingAdhocCards } from "@/lib/cards";
import { eur, pct, signedEur } from "@/lib/format";
@ -18,120 +18,37 @@ function hhmm(minutes: number) {
return `${String(Math.floor(minutes / 60)).padStart(2, "0")}h${String(minutes % 60).padStart(2, "0")}`;
}
/** En-tête : la date du jour, connue sans attendre aucune donnée. */
async function Today() {
await connection();
const d = formatDateFr(parisDate());
return <p className="text-[15px] font-semibold text-muted">{d.charAt(0).toUpperCase() + d.slice(1)}</p>;
}
/**
* Le patrimoine et sa répartition : à gauche ce qui est à l'abri (PEA), à droite la cagnotte
* que l'IA fait travailler (compte-titres). C'est toute l'idée de l'app en une barre.
*/
async function Wealth() {
await connection();
const settings = await getSettings();
const [real, pea] = await Promise.all([getPortfolioState("real"), getPea(settings)]);
const safe = pea?.value ?? 0;
const pot = real.equity;
const total = safe + pot;
const safeShare = total > 0 ? (safe / total) * 100 : 50;
return (
<section aria-label="Mon patrimoine" className="pb-2">
<p className="text-[15px] text-muted">Mon patrimoine</p>
<p className="amount mt-1 text-[3.4rem] font-bold">{eur(total)}</p>
<div className="mt-5 flex h-3.5 gap-1 overflow-hidden rounded-full" aria-hidden>
{total > 0 ? (
<>
<div className="bar-fill shrink-0 rounded-full bg-accent" style={{ width: `${safeShare}%` }} />
<div className="bar-fill flex-1 rounded-full bg-pot" style={{ animationDelay: "120ms" }} />
</>
) : (
<div className="flex-1 rounded-full bg-surface-2" />
)}
</div>
<div className="mt-4 grid grid-cols-2 gap-4">
<Link href="/reel#pea" className="block">
<p className="flex items-center gap-2 text-[14px] font-semibold">
<span className="h-2.5 w-2.5 rounded-full bg-accent" aria-hidden />À l&apos;abri
</p>
<p className="amount mt-1.5 text-[1.5rem] font-semibold">{eur(safe, 0)}</p>
<p className="mt-0.5 text-[13px] text-muted">
{pea && pea.invested > 0 ? (
<>
PEA S&amp;P 500, <Delta value={pea.gain}>{signedEur(pea.gain)}</Delta>
</>
) : settings.peaPlan ? (
"PEA, premier achat à venir"
) : (
"PEA à configurer"
)}
</p>
</Link>
<Link href="/reel" className="block">
<p className="flex items-center gap-2 text-[14px] font-semibold">
<span className="h-2.5 w-2.5 rounded-full bg-pot" aria-hidden />
Cagnotte qui travaille
</p>
<p className="amount mt-1.5 text-[1.5rem] font-semibold">{eur(pot, 0)}</p>
<p className="mt-0.5 text-[13px] text-muted">
Compte-titres, {real.positions.length ? `${real.positions.length} position${real.positions.length > 1 ? "s" : ""}` : `${eur(real.cash, 0)} en attente`}
</p>
</Link>
</div>
</section>
);
}
function WealthSkeleton() {
return (
<section aria-busy="true" className="pb-2">
<p className="text-[15px] text-muted">Mon patrimoine</p>
<div className="skeleton mt-2 h-12 w-56 rounded-xl" />
<div className="skeleton mt-5 h-3.5 rounded-full" />
<div className="mt-4 grid grid-cols-2 gap-4">
<div className="skeleton h-16 rounded-xl" />
<div className="skeleton h-16 rounded-xl" />
</div>
</section>
);
}
/** Ce que tu as à faire : seulement la base de données, donc rapide. */
/** Ce que tu as à faire : seulement la base de données, donc instantané. */
async function Todo() {
await connection();
const [settings, rdv, adhoc, ideas] = await Promise.all([getSettings(), getLatestRendezvous(), getPendingAdhocCards(), getIdeas()]);
const isToday = rdv?.date === parisDate();
const cards = [...(rdv?.cards ?? []), ...adhoc.filter((c) => c.rendezvousId !== rdv?.id)];
const cards = [...(rdv?.cards ?? []), ...adhoc];
const pending = cards.filter((c) => c.status === "pending");
const shown = isToday ? cards.filter((c) => c.status !== "expired") : pending;
const shown = isToday ? cards : pending;
return (
<>
{!settings.trAccountOpenedAt && (
<Card tone="pot" title="Dis à l'app où tu en es">
<p className="text-[15px] leading-relaxed">
Versements, PEA, actions déjà achetées : une minute suffit, et aucun identifiant Trade Republic n&apos;est demandé.
<Card tone="warn" title="À configurer">
<p className="text-sm leading-relaxed">
Indique à l&apos;app où en est ton compte Trade Republic (versements, PEA, actions déjà achetées). Ça prend 1 minute, et aucun identifiant n&apos;est demandé.
</p>
<Link href="/reel" className={`${primaryBtn} mt-4 w-full`}>
<Link href="/reel" className={`${primaryBtn} mt-3 w-full`}>
Configurer mon compte
</Link>
</Card>
)}
<Card
title={rdv && !isToday ? `Rendez-vous du ${formatDateFr(rdv.date)}` : "Ton rendez-vous du soir"}
title={rdv ? `Rendez-vous · ${isToday ? "aujourd'hui" : formatDateFr(rdv.date)}` : "Rendez-vous du soir"}
tone={pending.length ? "accent" : undefined}
action={pending.length ? <Badge tone="accent">{pending.length} à traiter</Badge> : undefined}
>
{rdv?.summary && isToday && <p className="mb-4 whitespace-pre-line text-[15px] leading-relaxed">{rdv.summary}</p>}
{rdv?.summary && isToday && <p className="mb-3 whitespace-pre-line text-sm leading-relaxed">{rdv.summary}</p>}
{!shown.length && (
<Empty>
Rien à faire pour l&apos;instant. L&apos;IA prépare ton prochain rendez-vous pour {hhmm(settings.rendezvousMinutes)}, en semaine. Tu peux aussi lancer une recherche maintenant.
Rien à faire pour l&apos;instant. Ton prochain rendez-vous arrive à {hhmm(settings.rendezvousMinutes)} (en semaine), ou lance une recherche tout de suite.
</Empty>
)}
<div className="flex flex-col gap-3">
@ -139,37 +56,63 @@ async function Todo() {
<ActionCard key={c.id} id={c.id} kind={c.kind} training={c.training} status={c.status} symbol={c.symbol} payload={c.payload} />
))}
</div>
<div className="mt-4">
<div className="mt-3">
<FindIdeas />
</div>
</Card>
{!pending.length && ideas && ideas.items.length > 0 && (
<Card
title="Idées à tester"
action={
<Link href="/actions" className="text-[14px] font-semibold text-accent">
Toutes les actions
</Link>
}
>
<ul className="-my-1 divide-y divide-line">
<Card title="Idées à tester" action={<Link href="/actions" className="text-sm font-medium text-accent">Toutes les actions</Link>}>
<ul className="flex flex-col gap-2">
{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">
<span className="font-semibold">{i.name}</span>
<span className="num shrink-0 text-[14px] text-danger">{pct(i.pullbackPct)} cette semaine</span>
<Link href={`/actions/${encodeURIComponent(i.symbol)}?montant=150&stop=7&objectif=12`} className="flex items-center justify-between gap-3 rounded-xl bg-surface-2 px-3 py-2.5">
<span className="font-medium">{i.name}</span>
<span className="num text-xs text-muted">
tendance +{i.trendPct} % · repli {i.pullbackPct} %
</span>
</Link>
</li>
))}
</ul>
<p className="mt-3 text-[13px] leading-relaxed text-muted">Des actions en hausse de fond qui viennent de reculer. Repérées par une règle simple, sans IA : essaie-les dans ton bac à sable.</p>
<p className="mt-2 text-xs text-muted">Repérées par une règle simple (sans IA). À essayer dans ton bac à sable.</p>
</Card>
)}
</>
);
}
/** Patrimoine : dépend des cours (PEA + compte-titres). */
async function Wealth() {
await connection();
const settings = await getSettings();
const [real, pea] = await Promise.all([getPortfolioState("real"), getPea(settings)]);
const total = (pea?.value ?? 0) + real.equity;
return (
<Card title="Mon patrimoine">
<p className="num text-3xl font-semibold tracking-tight">{eur(total)}</p>
<div className="mt-4 grid grid-cols-2 gap-3 text-sm">
<Link href="/reel#pea" className="rounded-xl bg-surface-2 p-3">
<p className="text-muted">PEA · cœur</p>
<p className="num mt-1 text-lg font-semibold">{eur(pea?.value ?? 0)}</p>
{pea && pea.invested > 0 ? (
<p className="text-xs">
<Delta value={pea.gain}>{signedEur(pea.gain)}</Delta> <span className="text-muted">sur {eur(pea.invested, 0)}</span>
</p>
) : (
<p className="text-xs text-muted">{settings.peaPlan ? "Premier achat à venir" : "Pas encore configuré ›"}</p>
)}
</Link>
<Link href="/reel" className="rounded-xl bg-surface-2 p-3">
<p className="text-muted">Compte-titres</p>
<p className="num mt-1 text-lg font-semibold">{eur(real.equity)}</p>
<p className="text-xs text-muted">{real.positions.length ? `${real.positions.length} position(s)` : `${eur(real.cash, 0)} en liquidités ›`}</p>
</Link>
</div>
</Card>
);
}
/** Classement et critères du mode réel : dépendent de l'indice S&P 500. */
async function Progress() {
await connection();
@ -180,69 +123,55 @@ async function Progress() {
return (
<>
<Card
title="Qui gagne ?"
action={
<Link href="/ia" className="text-[14px] font-semibold text-accent">
Voir l&apos;IA
</Link>
}
>
<ol className="-my-1 divide-y divide-line">
<Card title="Classement" action={<Link href="/ia" className="text-sm font-medium text-accent">Détails</Link>}>
<ol className="flex flex-col gap-2">
{board.map((row, i) => (
<li key={row.label} className="flex items-center gap-3 py-3">
<span className={`amount w-6 text-[1.4rem] font-bold ${i === 0 ? "text-accent" : "text-muted"}`}>{i + 1}</span>
<span className="min-w-0 flex-1">
<span className="block font-semibold">{row.label}</span>
<span className="block text-[13px] text-muted">{row.detail}</span>
<li key={row.label} className="flex items-center justify-between rounded-xl bg-surface-2 px-3 py-2.5">
<span className="font-medium">
{["🥇", "🥈", "🥉"][i]} {row.label}
<span className="ml-2 text-xs font-normal text-muted">{row.detail}</span>
</span>
<Delta value={row.pct}>{pct(row.pct)}</Delta>
</li>
))}
</ol>
<p className="mt-3 text-[13px] leading-relaxed text-muted">
L&apos;IA et toi partez de 200 € virtuels. Le S&amp;P 500 montre ce que tu aurais gagné sans rien faire.
</p>
<p className="mt-3 text-xs text-muted">L&apos;IA et toi partez chacun de 200 € virtuels. Le S&amp;P 500, c&apos;est ce que tu aurais gagné sans rien faire.</p>
</Card>
<Card title="Passer à l'argent réel" action={gate.realActive ? <Badge tone="gain">Débloqué</Badge> : <Badge tone="pot">{met} critères sur 5</Badge>}>
{settings.realLockedReason && <p className="mb-3 text-[15px] text-danger">Coupe-circuit : {settings.realLockedReason}</p>}
<div className="mb-4 grid grid-cols-5 gap-1.5" aria-hidden>
{gate.criteria.map((c) => (
<div key={c.label} className={`h-2 rounded-full ${c.ok ? "bg-gain" : "bg-surface-2"}`} />
))}
<Card title="Passage à l'argent réel" action={gate.realActive ? <Badge tone="accent">Débloqué</Badge> : <Badge tone="warn">{met}/5 critères</Badge>}>
{settings.realLockedReason && <p className="mb-3 text-sm text-danger">Coupe-circuit : {settings.realLockedReason}</p>}
<div className="mb-3 h-2 overflow-hidden rounded-full bg-surface-2">
<div className="h-full rounded-full bg-accent" style={{ width: `${(met / 5) * 100}%` }} />
</div>
<ul className="-my-1 divide-y divide-line text-[15px]">
<details>
<summary className="cursor-pointer text-sm font-medium text-accent">Voir les 5 critères</summary>
<ul className="mt-2 flex flex-col gap-2 text-sm">
{gate.criteria.map((c) => (
<li key={c.label} 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 ${c.ok ? "bg-gain" : "bg-line"}`} aria-hidden />
{c.label}
<li key={c.label} className="flex items-center justify-between gap-3">
<span>
{c.ok ? "✅" : "⏳"} {c.label}
</span>
<span className="num shrink-0 text-right text-[14px] text-muted">
<span className="block text-ink">{c.value}</span>
<span className="block text-[12px]">objectif {c.target}</span>
<span className="num shrink-0 text-muted">
{c.value} <span className="text-xs">/ {c.target}</span>
</span>
</li>
))}
</ul>
</details>
</Card>
<Card title="Budget IA du mois">
<Card title="Budget IA ce mois-ci">
{aiEnabled() ? (
<>
<p className="amount text-[1.6rem] font-semibold">
{spend.monthUsd.toFixed(2)} $ <span className="text-[1rem] font-normal text-muted">sur {settings.aiMonthlyBudgetUsd} $</span>
</p>
<div className="mt-3 h-2 overflow-hidden rounded-full bg-surface-2">
<div className="h-2 overflow-hidden rounded-full bg-surface-2">
<div className="h-full rounded-full bg-accent" style={{ width: `${Math.min(100, (spend.monthUsd / settings.aiMonthlyBudgetUsd) * 100)}%` }} />
</div>
<p className="mt-2 text-[13px] text-muted">Ce coût est déduit des résultats de l&apos;IA avant de la comparer au S&amp;P 500.</p>
<p className="num mt-2 text-sm text-muted">
{spend.monthUsd.toFixed(2)} $ sur {settings.aiMonthlyBudgetUsd} $ · coût déduit des résultats de l&apos;IA
</p>
</>
) : (
<Empty>
L&apos;IA n&apos;est pas encore branchée : ajoute ta clé Anthropic (ANTHROPIC_API_KEY, voir le README). En attendant, l&apos;app te propose des idées sans IA.
</Empty>
<Empty>IA pas encore branchée : ajoute ta clé Anthropic (ANTHROPIC_API_KEY, voir le README). En attendant, l&apos;app te propose des idées sans IA.</Empty>
)}
</Card>
</>
@ -251,22 +180,16 @@ async function Progress() {
export default function Home() {
return (
<main className="mx-auto flex w-full max-w-lg flex-col gap-4 px-4 pb-32 pt-[max(env(safe-area-inset-top),1.5rem)]">
<header className="flex items-center justify-between gap-3">
<Suspense fallback={<p className="text-[15px] font-semibold text-muted">Aujourd&apos;hui</p>}>
<Today />
</Suspense>
<SettingsLink />
</header>
<Suspense fallback={<WealthSkeleton />}>
<Wealth />
</Suspense>
<Suspense fallback={<CardSkeleton title="Ton rendez-vous du soir" height="h-32" />}>
<Page title="Cagnotte 🌱" subtitle="Ce qu'il y a à faire aujourd'hui." action={<SettingsLink />}>
<Suspense fallback={<CardSkeleton title="Rendez-vous du soir" height="h-32" />}>
<Todo />
</Suspense>
<Suspense fallback={<CardSkeleton title="Qui gagne ?" height="h-36" />}>
<Suspense fallback={<CardSkeleton title="Mon patrimoine" height="h-28" />}>
<Wealth />
</Suspense>
<Suspense fallback={<CardSkeleton title="Classement" height="h-36" />}>
<Progress />
</Suspense>
</main>
</Page>
);
}

View File

@ -29,12 +29,15 @@ async function AccountContent() {
return (
<>
<Card
title="Mon compte-titres"
tone={configured ? undefined : "pot"}
action={configured ? <Badge tone="gain">Configuré</Badge> : <Badge tone="pot">À faire</Badge>}
>
{configured && <p className="-mt-2 mb-4 text-[13px] text-muted">Ouvert le {formatDateFr(settings.trAccountOpenedAt!)}.</p>}
<Card>
<p className="text-sm leading-relaxed text-muted">
🔒 Trade Republic n&apos;offre pas de connexion pour les applications : l&apos;app ne se branche jamais à ton compte et ne te demandera jamais tes identifiants.
Tu lui indiques ce que tu as, elle fait les calculs et te dit quoi faire.
</p>
</Card>
<Card title="1 · Mon compte-titres" tone={configured ? undefined : "warn"} action={configured ? <Badge tone="accent">configuré</Badge> : <Badge tone="warn">à faire</Badge>}>
{configured && <p className="mb-3 text-xs text-muted">Ouvert le {formatDateFr(settings.trAccountOpenedAt!)}.</p>}
<AccountForm
openedAt={settings.trAccountOpenedAt}
monthly={settings.realMonthlyDeposit}
@ -44,59 +47,43 @@ async function AccountContent() {
/>
</Card>
<Card>
<div className="mb-1 flex items-center justify-between gap-3">
<p className="flex items-center gap-2 text-[15px] text-muted">
<span className="h-2.5 w-2.5 rounded-full bg-pot" aria-hidden />
Ma cagnotte réelle
</p>
{realActive ? <Badge tone="gain">Mode réel actif</Badge> : <Badge tone="pot">Simulation d&apos;abord</Badge>}
<Card title="Ma cagnotte réelle" action={realActive ? <Badge tone="accent">Mode réel actif</Badge> : <Badge tone="warn">Simulation d&apos;abord</Badge>}>
<div className="flex items-end justify-between">
<p className="num text-3xl font-semibold">{eur(state.equity)}</p>
{deposited > 0 && <Delta value={gain}>{signedEur(gain)}</Delta>}
</div>
<div className="flex items-end justify-between gap-3">
<p className="amount text-[2.8rem] font-bold">{eur(state.equity)}</p>
{deposited > 0 && (
<p className="amount pb-1 text-[1.3rem]">
<Delta value={gain}>{signedEur(gain)}</Delta>
</p>
)}
</div>
<div className="mt-5 grid grid-cols-3 gap-3">
<Stat label="à investir">{eur(state.cash, 0)}</Stat>
<div className="mt-3 grid grid-cols-3 gap-2 text-sm">
<Stat label="liquidités">{eur(state.cash, 0)}</Stat>
<Stat label="versés">{eur(deposited, 0)}</Stat>
<Stat label="mis à l'abri">{eur(toPea, 0)}</Stat>
<Stat label="partis au PEA">{eur(toPea, 0)}</Stat>
</div>
{!realActive && (
<p className="mt-4 text-[14px] leading-relaxed text-muted">
Tant que l&apos;IA n&apos;a pas prouvé en simulation qu&apos;elle bat le S&amp;P 500, elle ne te propose aucun trade réel : ton argent attend sur le compte. Tu peux
quand même noter ici ce que tu fais de ton côté.
<p className="mt-3 text-xs leading-relaxed text-muted">
Tant que l&apos;IA n&apos;a pas prouvé en simulation qu&apos;elle bat le S&amp;P 500, elle ne te propose pas de trade réel : ton argent attend sur le compte. Tu peux quand même
enregistrer ici ce que tu fais de ton côté.
</p>
)}
<div className="mt-5 border-t border-line pt-4">
<div className="mt-4">
<CashForms cash={state.cash} />
</div>
</Card>
<Card title="Mes actions chez Trade Republic">
<div className="flex flex-col gap-4">
<Card title="2 · Mes actions chez Trade Republic">
<div className="flex flex-col gap-3">
<RealPositions positions={state.positions} />
<AddHolding />
</div>
</Card>
<Suspense fallback={<CardSkeleton title="Mon PEA" height="h-40" />}>
<Suspense fallback={<CardSkeleton title="3 · Mon PEA" height="h-40" />}>
<PeaSection />
</Suspense>
{closed.length > 0 && (
<Card title="Mes trades réels terminés">
<Card title="Historique réel">
<ClosedList positions={closed} />
</Card>
)}
<p className="px-1 text-[13px] leading-relaxed text-muted">
Trade Republic ne permet à aucune application de se connecter à ton compte. L&apos;app ne te demandera donc jamais tes identifiants : tu lui dis ce que tu as, elle fait les
calculs et te dit quoi faire.
</p>
</>
);
}
@ -107,23 +94,15 @@ async function PeaSection() {
const plan = settings.peaPlan ?? defaultPeaPlan(parisDate());
const pea = await getPea(settings);
return (
<section id="pea" className="scroll-mt-6">
<Card>
<p className="mb-1 flex items-center gap-2 text-[15px] text-muted">
<span className="h-2.5 w-2.5 rounded-full bg-accent" aria-hidden />
Mon PEA, la part à l&apos;abri
</p>
<section id="pea">
<Card title="3 · Mon PEA (cœur)">
{pea && (
<>
<p className="amount text-[2.4rem] font-bold">{eur(pea.value)}</p>
<div className="mb-5 mt-5 grid grid-cols-3 gap-3">
<div className="mb-4 grid grid-cols-3 gap-2 text-sm">
<Stat label="valeur">{eur(pea.value, 0)}</Stat>
<Stat label="versés">{eur(pea.invested, 0)}</Stat>
<Stat label="gain">{signedEur(pea.gain)}</Stat>
<Stat label="parts d'ETF">{pea.shares.toLocaleString("fr-FR", { maximumFractionDigits: 3 })}</Stat>
<Stat label="parts">{pea.shares.toLocaleString("fr-FR", { maximumFractionDigits: 3 })}</Stat>
</div>
</>
)}
<div className={pea ? "border-t border-line pt-4" : "mt-3"}>
<PeaForm
has={Boolean(settings.peaPlan)}
symbol={plan.etfSymbol}
@ -132,7 +111,6 @@ async function PeaSection() {
start={plan.startDate}
calibration={plan.calibration?.shares ?? null}
/>
</div>
</Card>
</section>
);
@ -140,7 +118,7 @@ async function PeaSection() {
export default function AccountPage() {
return (
<Page title="Mon compte" subtitle="Ton compte Trade Republic : le compte-titres où travaille la cagnotte, et le PEA où l'argent est à l'abri." action={<SettingsLink />}>
<Page title="Mon compte" subtitle="Ton compte Trade Republic : compte-titres (satellite) et PEA (cœur)." action={<SettingsLink />}>
<Suspense fallback={<CardSkeleton height="h-64" />}>
<AccountContent />
</Suspense>

View File

@ -2,7 +2,6 @@ import { Suspense } from "react";
import Link from "next/link";
import { connection } from "next/server";
import { logout, saveSettings } from "@/app/actions";
import { BackLink } from "@/components/nav";
import { PushManager } from "@/components/push-manager";
import { RunNow } from "@/components/run-now";
import { Card, CardSkeleton, inputCls, Page, primaryBtn, secondaryBtn } from "@/components/ui";
@ -12,10 +11,10 @@ import { getSettings } from "@/lib/settings";
function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
return (
<label className="flex flex-col gap-1 text-[15px]">
<span className="font-semibold">{label}</span>
<label className="flex flex-col gap-1 text-sm">
<span className="font-medium">{label}</span>
{children}
{hint && <span className="text-[13px] text-muted">{hint}</span>}
{hint && <span className="text-xs text-muted">{hint}</span>}
</label>
);
}
@ -34,7 +33,7 @@ async function SettingsForm() {
</Field>
<Field
label="Budget IA mensuel ($)"
hint={aiEnabled() ? "L'IA s'arrête d'elle-même si le plafond est atteint." : "Clé Anthropic absente : l'IA est en pause (les idées sans IA continuent)."}
hint={aiEnabled() ? "L'IA s'arrête d'elle-même si le plafond est atteint." : "⚠️ Clé Anthropic absente : l'IA est en pause (les idées sans IA continuent)."}
>
<input className={inputCls} name="aiBudget" inputMode="decimal" defaultValue={s.aiMonthlyBudgetUsd} />
</Field>
@ -57,24 +56,20 @@ async function Diagnostics() {
await connection();
const d = await getDiagnostics();
const row = (ok: boolean, label: string, value: React.ReactNode) => (
<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 />
<li className="flex items-start justify-between gap-3">
<span>
{label}
{!ok && <span className="sr-only"> (à vérifier)</span>}
</span>
{ok ? "✅" : "⚠️"} {label}
</span>
<span className="num shrink-0 text-right text-muted">{value}</span>
</li>
);
return (
<Card title="Diagnostic de l'IA">
<ul className="-my-1 divide-y divide-line text-[15px]">
<ul className="flex flex-col gap-2 text-sm">
{row(d.aiOn, "Clé Anthropic", d.aiOn ? "présente" : "absente")}
{row(d.news48h > 0, "Actus des 48 dernières heures", d.news48h)}
{row(!d.aiOn || d.triagedTotal > 0, "Actus triées par l'IA (48 h)", d.triagedTotal)}
{row(d.positiveStrong > 0, "Actus positives ≥ 6/10 (48 h)", d.positiveStrong)}
{row(!d.aiOn || d.triagedTotal > 0, "Actus triées par l'IA", d.triagedTotal)}
{row(d.positiveStrong > 0, "Actus positives ≥ 6/10", d.positiveStrong)}
{row(d.signals.length > 0, "Analyses (7 derniers jours)", d.signals.length)}
{row(true, "Coût IA ce mois-ci", `${d.spend.monthUsd.toFixed(2)} $`)}
{row(Boolean(d.lastTick), "Dernière mise à jour", ago(d.lastTick?.at))}
@ -82,8 +77,8 @@ async function Diagnostics() {
</ul>
{d.signals.length > 0 && (
<details className="mt-3">
<summary className="cursor-pointer text-[15px] font-semibold text-accent">Décisions récentes de l&apos;IA</summary>
<ul className="mt-2 flex flex-col gap-1.5 text-[13px]">
<summary className="cursor-pointer text-sm font-medium text-accent">Décisions récentes de l&apos;IA</summary>
<ul className="mt-2 flex flex-col gap-1.5 text-xs">
{d.signals.map((s) => (
<li key={s.id}>
<b>{s.name}</b> · {s.decision === "buy" ? "achat" : "passe"} ({s.confidence} %)
@ -97,8 +92,8 @@ async function Diagnostics() {
(l, i) =>
l && (
<details key={i} className="mt-2">
<summary className="cursor-pointer text-[15px] font-semibold text-accent">Journal {i ? "du rendez-vous" : "de la mise à jour"}</summary>
<ul className="mt-2 list-disc pl-5 text-[13px] text-muted">
<summary className="cursor-pointer text-sm font-medium text-accent">Journal {i ? "du rendez-vous" : "de la mise à jour"}</summary>
<ul className="mt-2 list-disc pl-5 text-xs text-muted">
{l.log.length ? l.log.map((x, j) => <li key={j}>{x}</li>) : <li>Rien à signaler.</li>}
</ul>
</details>
@ -112,7 +107,11 @@ export default function SettingsPage() {
return (
<Page
title="Réglages"
action={<BackLink href="/" label="Ce soir" />}
action={
<Link href="/" className="text-sm font-medium text-accent">
‹ Accueil
</Link>
}
>
<Card title="Notifications iPhone">
<PushManager />
@ -123,7 +122,7 @@ export default function SettingsPage() {
</Suspense>
<Card title="Compte Trade Republic et PEA">
<p className="mb-3 text-[15px] text-muted">Versements, liquidités, actions détenues et plan PEA se règlent dans l&apos;onglet « Mon compte ».</p>
<p className="mb-3 text-sm text-muted">Versements, liquidités, actions détenues et plan PEA se règlent dans l&apos;onglet « Mon compte ».</p>
<Link href="/reel" className={`${secondaryBtn} w-full`}>
Ouvrir Mon compte
</Link>
@ -142,7 +141,7 @@ export default function SettingsPage() {
Se déconnecter
</button>
</form>
<p className="text-center text-[13px] leading-relaxed text-muted">
<p className="text-center text-xs leading-relaxed text-muted">
Outil d&apos;aide à la décision, pas un conseil en investissement. Les performances passées ne préjugent pas des performances futures.
</p>
</Page>

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 { runEvening, runEveningNow, tick } from "@/lib/jobs";
import { FEE_EUR } from "@/lib/engine/fills";
import { roundShares } from "@/lib/engine/risk";
import {
@ -26,7 +26,7 @@ import { addHolding, deleteHolding, recordDeposit, recordSale, setCash } from "@
import { defaultPeaPlan, getSettings, updateSettings } from "@/lib/settings";
import { addDays, parisDate } from "@/lib/time";
import { getDb, schema } from "@/lib/db";
import { and, eq } from "drizzle-orm";
import { eq } from "drizzle-orm";
/** Les actions serveur sont des points d'entrée publics : chacune vérifie la session. */
async function requireAuth() {
@ -95,11 +95,11 @@ export async function sandboxBuy(input: {
targetPct?: number;
}): Promise<{ ok: boolean; message: string }> {
await requireAuth();
const quote = await getQuote(input.symbol, { fresh: true });
const quote = await getQuote(input.symbol);
if (!quote) return { ok: false, message: "Cours introuvable." };
if (!isSupportedCurrency(quote.currency)) return { ok: false, message: "Seules les actions en euros ou en dollars sont gérées." };
const ref = input.type === "limit" && input.limitPrice ? input.limitPrice : quote.price;
const fx = (await getFxToEur(quote.currency, { fresh: true })) ?? 1;
const fx = (await getFxToEur(quote.currency)) ?? 1;
const shares = input.amountEur ? roundShares(input.amountEur / (ref * fx)) : (input.shares ?? 0);
if (!(shares > 0)) return { ok: false, message: "Indique un montant ou un nombre d'actions." };
const state = await getPortfolioState("sandbox");
@ -131,11 +131,6 @@ export async function sandboxSell(positionId: number): Promise<{ ok: boolean; me
const db = await getDb();
const [pos] = await db.select().from(schema.positions).where(eq(schema.positions.id, positionId));
if (!pos || pos.portfolioId !== "sandbox" || pos.status !== "open") return { ok: false, message: "Position introuvable." };
const [already] = await db
.select({ id: schema.orders.id })
.from(schema.orders)
.where(and(eq(schema.orders.positionId, pos.id), eq(schema.orders.side, "sell"), eq(schema.orders.status, "pending")));
if (already) return { ok: false, message: "Une vente est déjà en attente pour cette position (elle partira à la réouverture)." };
const r = await placeOrder({
portfolioId: "sandbox",
symbol: pos.symbol,
@ -169,13 +164,6 @@ export async function resetSandbox() {
revalidatePath("/", "layout");
}
/** Remet la cagnotte de l'IA à 200 € et relance la simulation à partir d'aujourd'hui. */
export async function resetAiPot() {
await requireAuth();
await resetAiSim();
revalidatePath("/", "layout");
}
export async function askAi(symbol: string, question: string): Promise<{ ok: true; answer: AskAnswer } | { ok: false; message: string }> {
await requireAuth();
try {
@ -345,8 +333,7 @@ export async function deleteHoldingAction(positionId: number) {
export async function runNow(mode: "tick" | "evening"): Promise<string[]> {
await requireAuth();
// « Préparer le rendez-vous maintenant » : on le refait même s'il a déjà eu lieu aujourd'hui.
const log = mode === "evening" ? await runEvening({ force: true }) : await tick();
const log = mode === "evening" ? await runEvening() : await tick();
revalidatePath("/", "layout");
return log;
}

View File

@ -1,52 +1,34 @@
@import "tailwindcss";
/*
* Cagnotte : un carnet d'épargne à deux compartiments.
* Cobalt « tampon » = ce qui est à l'abri (PEA) et les actions à faire.
* Ocre = la cagnotte que l'IA fait travailler.
* Vert / rouge = uniquement les gains et les pertes.
*/
:root {
--bg: #f1f2f6;
--bg: #f6f5f1;
--surface: #ffffff;
--surface-2: #e8eaf1;
--border: #dcdfe8;
--text: #151a30;
--muted: #5d6278;
--accent: #2f44c9;
--accent-soft: #e3e7fb;
--accent-ink: #ffffff;
--pot: #b97a0e;
--pot-soft: #f6ecd7;
--gain: #0e7f57;
--gain-soft: #dcf1e8;
--danger: #c0383e;
--danger-soft: #f8e2e3;
--warn: #9a6400;
--warn-soft: #f6ecd7;
color-scheme: light;
--surface-2: #efede7;
--border: #e2dfd6;
--text: #1b1a17;
--muted: #6d6a62;
--accent: #0f7b5f;
--accent-soft: #dcefe7;
--danger: #b4233c;
--danger-soft: #f8e1e5;
--warn: #9a6200;
--warn-soft: #f7ecd6;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0d1020;
--surface: #161a2c;
--surface-2: #1f2438;
--border: #2a3047;
--text: #e8eaf4;
--muted: #9ba1b8;
--accent: #8d9bff;
--accent-soft: #232a52;
--accent-ink: #0d1020;
--pot: #e7b54a;
--pot-soft: #3a2e14;
--gain: #4fd19c;
--gain-soft: #123528;
--danger: #ff7b80;
--danger-soft: #3d1a1f;
--warn: #e7b54a;
--warn-soft: #3a2e14;
color-scheme: dark;
--bg: #0f1012;
--surface: #17191c;
--surface-2: #1f2226;
--border: #2a2e33;
--text: #ecebe6;
--muted: #9a988f;
--accent: #3ccf9f;
--accent-soft: #123a2e;
--danger: #ff6b81;
--danger-soft: #3b1820;
--warn: #f0b44c;
--warn-soft: #3a2c12;
}
}
@ -59,17 +41,12 @@
--color-muted: var(--muted);
--color-accent: var(--accent);
--color-accent-soft: var(--accent-soft);
--color-accent-ink: var(--accent-ink);
--color-pot: var(--pot);
--color-pot-soft: var(--pot-soft);
--color-gain: var(--gain);
--color-gain-soft: var(--gain-soft);
--color-danger: var(--danger);
--color-danger-soft: var(--danger-soft);
--color-warn: var(--warn);
--color-warn-soft: var(--warn-soft);
--font-sans: var(--font-atkinson);
--font-display: var(--font-bricolage);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
html {
@ -80,60 +57,8 @@ body {
background: var(--bg);
color: var(--text);
-webkit-tap-highlight-color: transparent;
font-size: 16px;
line-height: 1.5;
}
/* Titres et montants : Bricolage Grotesque, resserrée en grand comme un relevé de compte. */
.display {
font-family: var(--font-bricolage);
font-variation-settings: "wdth" 88, "opsz" 48;
letter-spacing: -0.02em;
line-height: 1.05;
}
.amount {
font-family: var(--font-bricolage);
font-variation-settings: "wdth" 82, "opsz" 96;
font-variant-numeric: tabular-nums;
letter-spacing: -0.03em;
line-height: 1;
}
.num {
font-variant-numeric: tabular-nums;
}
:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
border-radius: 10px;
}
/* Le seul mouvement non déclenché : la barre « à l'abri / cagnotte IA » se remplit à l'ouverture. */
@keyframes grow {
from {
transform: scaleX(0);
}
}
.bar-fill {
transform-origin: left;
animation: grow 700ms cubic-bezier(0.2, 0.8, 0.2, 1) both;
}
@keyframes shimmer {
50% {
opacity: 0.55;
}
}
.skeleton {
background: var(--surface-2);
animation: shimmer 1.4s ease-in-out infinite;
}
@media (prefers-reduced-motion: reduce) {
.bar-fill,
.skeleton {
animation: none;
}
}

View File

@ -1,11 +1,9 @@
import type { Metadata, Viewport } from "next";
import { Atkinson_Hyperlegible_Next, Bricolage_Grotesque } from "next/font/google";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
// Montants et titres : Bricolage Grotesque (largeur et taille optique variables).
const display = Bricolage_Grotesque({ variable: "--font-bricolage", subsets: ["latin"], axes: ["wdth", "opsz"] });
// Texte : Atkinson Hyperlegible Next, dessinée pour être lisible par tous.
const body = Atkinson_Hyperlegible_Next({ variable: "--font-atkinson", subsets: ["latin"], adjustFontFallback: false });
const geistSans = Geist({ variable: "--font-geist-sans", subsets: ["latin"] });
const geistMono = Geist_Mono({ variable: "--font-geist-mono", subsets: ["latin"] });
export const metadata: Metadata = {
title: "Cagnotte",
@ -18,14 +16,14 @@ export const viewport: Viewport = {
initialScale: 1,
viewportFit: "cover",
themeColor: [
{ media: "(prefers-color-scheme: light)", color: "#f1f2f6" },
{ media: "(prefers-color-scheme: dark)", color: "#0d1020" },
{ media: "(prefers-color-scheme: light)", color: "#f6f5f1" },
{ media: "(prefers-color-scheme: dark)", color: "#0f1012" },
],
};
export default function RootLayout({ children }: LayoutProps<"/">) {
return (
<html lang="fr" className={`${display.variable} ${body.variable} h-full antialiased`}>
<html lang="fr" className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}>
<body className="min-h-full font-sans">{children}</body>
</html>
);

View File

@ -3,12 +3,9 @@ import { LoginForm } from "./login-form";
export default function LoginPage() {
return (
<main className="mx-auto flex min-h-dvh w-full max-w-sm flex-col justify-center px-6">
<div className="flex h-3 w-24 gap-1 overflow-hidden rounded-full" aria-hidden>
<div className="bar-fill w-1/2 rounded-full bg-accent" />
<div className="bar-fill flex-1 rounded-full bg-pot" style={{ animationDelay: "120ms" }} />
</div>
<h1 className="display mt-6 text-[2.6rem] font-bold">Cagnotte</h1>
<p className="mt-2 text-[16px] leading-snug text-muted">La moitié à l&apos;abri, la moitié qui travaille. L&apos;IA t&apos;aide à décider.</p>
<p className="text-4xl">🌱</p>
<h1 className="mt-3 text-2xl font-semibold tracking-tight">Cagnotte</h1>
<p className="mt-1 text-sm text-muted">Ton argent travaille, l&apos;IA t&apos;aide à décider.</p>
<LoginForm />
</main>
);

View File

@ -19,15 +19,15 @@ import { Delta, Empty, inputCls, primaryBtn, secondaryBtn } from "./ui";
function Result({ r }: { r: FormResult }) {
if (!r) return null;
return <p className={`text-[14px] font-semibold ${r.ok ? "text-gain" : "text-danger"}`}>{r.message}</p>;
return <p className={`text-sm ${r.ok ? "text-accent" : "text-danger"}`}>{r.message}</p>;
}
function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
return (
<label className="flex flex-col gap-1.5 text-[15px]">
<span className="font-semibold">{label}</span>
<label className="flex flex-col gap-1 text-sm">
<span className="font-medium">{label}</span>
{children}
{hint && <span className="text-[13px] text-muted">{hint}</span>}
{hint && <span className="text-xs text-muted">{hint}</span>}
</label>
);
}
@ -56,11 +56,11 @@ export function AccountForm(props: { openedAt: string | null; monthly: number; d
<input className={inputCls} name="depositDay" inputMode="numeric" defaultValue={props.day} />
</Field>
</div>
<label className="flex items-start gap-2 text-[15px]">
<label className="flex items-start gap-2 text-sm">
<input type="checkbox" name="autoDeposit" defaultChecked={props.auto} className="mt-1 h-4 w-4 accent-[var(--accent)]" />
<span>
J&apos;ai programmé ce virement chaque mois
<span className="block text-[13px] text-muted">L&apos;app l&apos;ajoutera toute seule à tes liquidités à chaque échéance.</span>
<span className="block text-xs text-muted">L&apos;app l&apos;ajoutera toute seule à tes liquidités à chaque échéance.</span>
</span>
</label>
<button className={primaryBtn} disabled={pending}>
@ -131,7 +131,7 @@ export function AddHolding() {
return (
<div className="flex flex-col gap-3 rounded-xl border border-line p-3">
<p className="text-[15px] font-semibold">Ajouter une action détenue chez Trade Republic</p>
<p className="text-sm font-semibold">Ajouter une action détenue chez Trade Republic</p>
<input
className={inputCls}
placeholder="Rechercher l'action"
@ -143,11 +143,11 @@ export function AddHolding() {
}}
/>
{!picked && hits.length > 0 && (
<ul className="overflow-hidden rounded-xl border border-line text-[15px]">
<ul className="overflow-hidden rounded-xl border border-line text-sm">
{hits.map((h) => (
<li key={h.symbol}>
<button className="w-full bg-surface-2 px-3 py-2.5 text-left" onClick={() => (setPicked(h), setHits([]))}>
{h.name} <span className="text-[13px] text-muted">· {h.symbol}</span>
{h.name} <span className="text-xs text-muted">· {h.symbol}</span>
</button>
</li>
))}
@ -164,11 +164,11 @@ export function AddHolding() {
<Field label="Stop (% sous le prix d'achat)" hint="Laisse vide si tu n'as pas mis d'ordre Stop.">
<input className={inputCls} inputMode="decimal" value={stop} onChange={(e) => setStop(e.target.value)} />
</Field>
<label className="flex items-start gap-2 text-[15px]">
<label className="flex items-start gap-2 text-sm">
<input type="checkbox" checked={paid} onChange={(e) => setPaid(e.target.checked)} className="mt-1 h-4 w-4" />
<span>
Retirer le coût de mes liquidités
<span className="block text-[13px] text-muted">Décoche si ces liquidités ne sont pas encore comptées dans l&apos;app (achat ancien).</span>
<span className="block text-xs text-muted">Décoche si ces liquidités ne sont pas encore comptées dans l&apos;app (achat ancien).</span>
</span>
</label>
<div className="grid grid-cols-2 gap-2">
@ -217,14 +217,14 @@ function RealPosition({ p }: { p: PositionView }) {
const [res, setRes] = useState<FormResult>(null);
const [pending, start] = useTransition();
return (
<li className="rounded-2xl bg-surface-2 p-4">
<li className="rounded-xl bg-surface-2 p-3">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<p className="font-semibold">{p.name}</p>
<p className="num text-[13px] text-muted">
<p className="num text-xs text-muted">
{fmtShares(p.shares)} × {price(p.entryPrice, p.currency)} → {p.price !== null ? price(p.price, p.currency) : "?"}
</p>
{p.stopPrice && <p className="num text-[13px] text-muted">Stop {price(p.stopPrice, p.currency)}</p>}
{p.stopPrice && <p className="num text-xs text-muted">Stop {price(p.stopPrice, p.currency)}</p>}
</div>
<div className="text-right">
<p className="num font-semibold">{eur(p.valueEur)}</p>
@ -275,11 +275,11 @@ export function PeaForm(props: { has: boolean; symbol: string; amount: number; d
const [has, setHas] = useState(props.has);
return (
<form action={action} className="flex flex-col gap-3">
<label className="flex items-start gap-2 text-[15px]">
<label className="flex items-start gap-2 text-sm">
<input type="checkbox" name="hasPea" checked={has} onChange={(e) => setHas(e.target.checked)} className="mt-1 h-4 w-4" />
<span>
J&apos;ai un PEA avec un plan d&apos;épargne ETF
<span className="block text-[13px] text-muted">L&apos;app calcule sa valeur toute seule, chaque jour, à partir du cours de l&apos;ETF.</span>
<span className="block text-xs text-muted">L&apos;app calcule sa valeur toute seule, chaque jour, à partir du cours de l&apos;ETF.</span>
</span>
</label>
{has && (

View File

@ -42,64 +42,58 @@ export function ActionCard({ id, kind, training, status, symbol, payload }: Prop
}
});
const kindLabel = { buy: "Acheter", sell: "Vendre", move_stop: "Protéger un gain", to_pea: "Mettre à l'abri" }[kind] ?? "À faire";
const kindTone = ({ buy: "gain", sell: "danger", move_stop: "accent", to_pea: "accent" } as const)[kind as "buy"] ?? "neutral";
const done = status !== "pending";
const icon = { buy: "🟢", sell: "🔴", move_stop: "🛡️", to_pea: "🏦" }[kind] ?? "•";
return (
<article className={`rounded-2xl bg-surface-2 p-4 ${done ? "opacity-70" : ""}`}>
<div className="mb-2.5 flex flex-wrap items-center gap-2">
<Badge tone={kindTone}>{kindLabel}</Badge>
{training ? <Badge tone="pot">Entraînement</Badge> : <Badge tone="accent">Argent réel</Badge>}
{done && <Badge>{status === "done" ? (training ? "Tu l'aurais pris" : "Fait") : status === "expired" ? "Expirée" : "Passée"}</Badge>}
<article className="rounded-2xl border border-line bg-surface-2 p-4">
<div className="mb-2 flex flex-wrap items-center gap-2">
{training ? <Badge tone="warn">Entraînement</Badge> : <Badge tone="accent">Argent réel</Badge>}
{status !== "pending" && <Badge>{status === "done" ? (training ? "Tu l'aurais pris" : "Fait") : "Passé"}</Badge>}
</div>
<h3 className="display text-[1.15rem] font-semibold">{payload.title}</h3>
<h3 className="text-base font-semibold leading-snug">
{icon} {payload.title}
</h3>
<ol className="mt-3 flex flex-col gap-2 text-[15px] leading-relaxed">
{payload.steps.map((s, i) => (
<li key={s} className="flex gap-3">
<span className="amount mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-surface text-[0.9rem] font-bold text-accent" aria-hidden>
{i + 1}
</span>
<span>{s}</span>
</li>
<button type="button" onClick={() => setOpen(!open)} className="mt-2 text-sm font-medium text-accent">
{open ? "Masquer le pourquoi" : "Pourquoi ?"}
</button>
{open && <p className="mt-2 whitespace-pre-line text-sm leading-relaxed text-muted">{payload.why}</p>}
<ol className="mt-3 flex list-decimal flex-col gap-1.5 pl-5 text-sm leading-relaxed">
{payload.steps.map((s) => (
<li key={s}>{s}</li>
))}
</ol>
<button type="button" onClick={() => setOpen(!open)} aria-expanded={open} className="mt-3 text-[14px] font-semibold text-accent">
{open ? "Masquer l'explication" : "Pourquoi ce conseil ?"}
</button>
{open && <p className="mt-2 whitespace-pre-line text-[15px] leading-relaxed text-muted">{payload.why}</p>}
{kind === "buy" && symbol && !done && (
{kind === "buy" && symbol && (
<Link href={sandboxHref(symbol, payload)} className={`${training ? primaryBtn : secondaryBtn} mt-4 w-full`}>
Essayer dans mon bac à sable
🧪 Essayer dans mon bac à sable
</Link>
)}
{status === "pending" && (
<div className="mt-4 flex flex-col gap-3 border-t border-line pt-4">
<div className="mt-3 flex flex-col gap-3">
{needsFill && (
<div className="grid grid-cols-2 gap-2">
<label className="text-[13px] text-muted">
Prix obtenu ({payload.currency === "USD" ? "$" : "€"})
<input className={`${inputCls} mt-1 bg-surface!`} inputMode="decimal" value={priceVal} onChange={(e) => setPrice(e.target.value)} placeholder="prix réel" />
<label className="text-xs text-muted">
Prix exécuté ({payload.currency === "USD" ? "$" : "€"})
<input className={`${inputCls} mt-1`} inputMode="decimal" value={priceVal} onChange={(e) => setPrice(e.target.value)} placeholder="prix réel" />
</label>
<label className="text-[13px] text-muted">
<label className="text-xs text-muted">
Nombre d&apos;actions
<input className={`${inputCls} mt-1 bg-surface!`} inputMode="decimal" value={sharesVal} onChange={(e) => setShares(e.target.value)} />
<input className={`${inputCls} mt-1`} inputMode="decimal" value={sharesVal} onChange={(e) => setShares(e.target.value)} />
</label>
</div>
)}
<div className="grid grid-cols-2 gap-2">
<button className={training ? `${secondaryBtn} bg-surface!` : primaryBtn} disabled={pending} onClick={() => answer("done")}>
{training ? "Je l'aurais pris" : "C'est fait"}
<button className={training ? secondaryBtn : primaryBtn} disabled={pending} onClick={() => answer("done")}>
{training ? "✅ Je l'aurais pris" : "✅ C'est fait"}
</button>
<button className={`${secondaryBtn} bg-surface!`} disabled={pending} onClick={() => answer("skipped")}>
Je passe
<button className={secondaryBtn} disabled={pending} onClick={() => answer("skipped")}>
❌ Je passe
</button>
</div>
{error && <p className="text-[14px] text-danger">{error}</p>}
{error && <p className="text-sm text-danger">{error}</p>}
</div>
)}
</article>

View File

@ -5,7 +5,7 @@ import { findIdeasNow } from "@/app/actions";
import { secondaryBtn } from "./ui";
/** Lance l'analyse du soir tout de suite, sans attendre le rendez-vous. */
export function FindIdeas({ label = "Chercher des idées maintenant" }: { label?: string }) {
export function FindIdeas({ label = "🔎 Chercher des idées maintenant" }: { label?: string }) {
const [pending, start] = useTransition();
const [log, setLog] = useState<string[] | null>(null);
return (
@ -26,7 +26,7 @@ export function FindIdeas({ label = "Chercher des idées maintenant" }: { label?
>
{pending ? "Analyse en cours… (jusqu'à 1 minute)" : label}
</button>
{log && log.length > 0 && <p className="text-[13px] text-muted">{log.at(-1)}</p>}
{log && log.length > 0 && <p className="text-xs text-muted">{log.at(-1)}</p>}
</div>
);
}

View File

@ -4,10 +4,10 @@ import Link from "next/link";
import { usePathname } from "next/navigation";
const TABS = [
{ href: "/", label: "Ce soir", icon: "M12 3a6 6 0 0 0 0 12 6 6 0 0 1 0-12zM4 20h16M7 17h10" },
{ href: "/", label: "Accueil", icon: "M3 11.5 12 4l9 7.5V20a1 1 0 0 1-1 1h-5v-6h-6v6H4a1 1 0 0 1-1-1z" },
{ href: "/actions", label: "Actions", icon: "M3 17l5-5 4 4 8-8M15 8h5v5" },
{ href: "/bac-a-sable", label: "Bac à sable", icon: "M4 19h16M6 16l3-6 3 3 4-7 2 10" },
{ href: "/ia", label: "L'IA", icon: "M12 3v3m0 12v3M3 12h3m12 0h3M7 7h10v10H7zM10 10h4v4h-4z" },
{ href: "/ia", label: "IA", icon: "M12 3v3m0 12v3M3 12h3m12 0h3M7 7h10v10H7zM10 10h4v4h-4z" },
{ href: "/reel", label: "Mon compte", icon: "M3 7h18v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1zM3 7l2-3h14l2 3M16 13h2" },
];
@ -18,22 +18,19 @@ export function Nav() {
/** La même barre sans onglet actif : affichée instantanément, avant que l'adresse soit connue. */
export function NavBar({ pathname }: { pathname: string | null }) {
return (
<nav className="fixed inset-x-0 bottom-0 z-20 border-t border-line bg-bg/90 pb-[env(safe-area-inset-bottom)] backdrop-blur-md">
<ul className="mx-auto flex max-w-lg px-1">
<nav className="fixed inset-x-0 bottom-0 z-20 border-t border-line bg-surface/95 pb-[env(safe-area-inset-bottom)] backdrop-blur">
<ul className="mx-auto flex max-w-lg">
{TABS.map((t) => {
const active = pathname !== null && (t.href === "/" ? pathname === "/" : pathname.startsWith(t.href));
return (
<li key={t.href} className="flex-1">
<Link
href={t.href}
aria-current={active ? "page" : undefined}
className={`flex flex-col items-center gap-1 pb-2 pt-2 text-[12px] font-semibold ${active ? "text-accent" : "text-muted"}`}
className={`flex flex-col items-center gap-1 py-2.5 text-[11px] font-medium ${active ? "text-accent" : "text-muted"}`}
>
<span className={`flex h-8 w-14 items-center justify-center rounded-full transition-colors ${active ? "bg-accent-soft" : ""}`}>
<svg viewBox="0 0 24 24" className="h-[22px] w-[22px]" fill="none" stroke="currentColor" strokeWidth={1.8} strokeLinecap="round" strokeLinejoin="round" aria-hidden>
<svg viewBox="0 0 24 24" className="h-6 w-6" fill="none" stroke="currentColor" strokeWidth={1.7} strokeLinecap="round" strokeLinejoin="round" aria-hidden>
<path d={t.icon} />
</svg>
</span>
{t.label}
</Link>
</li>
@ -47,22 +44,10 @@ export function NavBar({ pathname }: { pathname: string | null }) {
/** Raccourci vers les réglages, en haut à droite des pages. */
export function SettingsLink() {
return (
<Link href="/reglages" aria-label="Réglages" className="flex h-10 w-10 items-center justify-center rounded-full bg-surface text-muted dark:ring-1 dark:ring-line">
<svg viewBox="0 0 24 24" className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth={1.8} strokeLinecap="round" strokeLinejoin="round" aria-hidden>
<Link href="/reglages" aria-label="Réglages" className="flex h-9 w-9 items-center justify-center rounded-full border border-line bg-surface text-muted">
<svg viewBox="0 0 24 24" className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth={1.7} strokeLinecap="round" strokeLinejoin="round" aria-hidden>
<path d="M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19 12l2-1-2-4-2 .5-1.5-1L15 4h-6l-.5 2.5-1.5 1L5 7l-2 4 2 1-2 1 2 4 2-.5 1.5 1L9 20h6l.5-2.5 1.5-1 2 .5 2-4z" />
</svg>
</Link>
);
}
/** Lien retour en haut d'une page secondaire. */
export function BackLink({ href, label }: { href: string; label: string }) {
return (
<Link href={href} className="inline-flex h-10 items-center gap-1 rounded-full bg-surface px-3.5 text-[14px] font-semibold text-ink dark:ring-1 dark:ring-line">
<svg viewBox="0 0 24 24" className="h-4 w-4" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" aria-hidden>
<path d="M15 5l-7 7 7 7" />
</svg>
{label}
</Link>
);
}

View File

@ -1,11 +1,12 @@
import { CardSkeleton, Page } from "./ui";
import { Page } from "./ui";
/** Affiché pendant le chargement des données d'une page. */
export function PageSkeleton({ title }: { title: string }) {
return (
<Page title={title}>
<CardSkeleton height="h-28" />
<CardSkeleton height="h-40" />
{[0, 1, 2].map((i) => (
<div key={i} className="h-32 animate-pulse rounded-2xl border border-line bg-surface" />
))}
</Page>
);
}

View File

@ -11,37 +11,35 @@ export function PositionList({ positions, sellable = false }: { positions: Posit
const [pending, start] = useTransition();
if (!positions.length) return <Empty>Aucune position ouverte.</Empty>;
return (
<ul className="-my-1 divide-y divide-line">
<ul className="flex flex-col gap-2">
{positions.map((p) => (
<li key={p.id} className="py-3">
<li key={p.id} className="rounded-xl bg-surface-2 p-3">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<Link href={`/actions/${encodeURIComponent(p.symbol)}`} className="font-semibold">
{p.name}
</Link>
<p className="num mt-0.5 text-[13px] text-muted">
{shares(p.shares)} action{p.shares > 1 ? "s" : ""}, achat {price(p.entryPrice, p.currency)}, cours {p.price !== null ? price(p.price, p.currency) : "inconnu"}
<p className="num text-xs text-muted">
{shares(p.shares)} × {price(p.entryPrice, p.currency)} → {p.price !== null ? price(p.price, p.currency) : "?"}
</p>
</div>
<div className="shrink-0 text-right">
<p className="amount text-[1.2rem] font-semibold">{eur(p.valueEur)}</p>
<p className="mt-0.5 text-[13px]">
<div className="text-right">
<p className="num font-semibold">{eur(p.valueEur)}</p>
<Delta value={p.pnlOpenEur}>
{signedEur(p.pnlOpenEur)} ({pct(p.pnlOpenPct)})
</Delta>
</p>
</div>
</div>
{(p.stopPrice || p.targetPrice || p.maxExitDate) && (
<div className="num mt-2 flex flex-wrap gap-x-4 gap-y-1 text-[13px] text-muted">
{p.stopPrice ? <span>Stop {price(p.stopPrice, p.currency)}</span> : null}
{p.targetPrice ? <span>Objectif {price(p.targetPrice, p.currency)}</span> : null}
{p.maxExitDate ? <span>Vente au plus tard le {p.maxExitDate.split("-").reverse().join("/")}</span> : null}
</div>
<p className="num mt-2 text-xs text-muted">
{p.stopPrice ? `Stop ${price(p.stopPrice, p.currency)}` : ""}
{p.targetPrice ? ` · Objectif ${price(p.targetPrice, p.currency)}` : ""}
{p.maxExitDate ? ` · Sortie au plus tard le ${p.maxExitDate}` : ""}
</p>
)}
{sellable && (
<button
className={`${secondaryBtn} mt-3 h-10 w-full`}
className={`${secondaryBtn} mt-3 h-9 w-full`}
disabled={pending}
onClick={() =>
start(async () => {
@ -62,20 +60,18 @@ export function PositionList({ positions, sellable = false }: { positions: Posit
export function PendingOrders({ orders, cancellable = false }: { orders: Order[]; cancellable?: boolean }) {
const [pending, start] = useTransition();
return (
<ul className="-my-1 divide-y divide-line text-[15px]">
<ul className="flex flex-col gap-2 text-sm">
{orders.map((o) => (
<li key={o.id} className="flex items-center justify-between gap-3 py-3">
<li key={o.id} className="flex items-center justify-between gap-3 rounded-xl bg-surface-2 p-3">
<span>
<span className="font-semibold">
{o.side === "buy" ? "Achat" : "Vente"} de {shares(o.shares)} {o.name}
</span>
<span className="num block text-[13px] text-muted">
{o.type === "limit" && o.limitPrice ? `Cours limite ${price(o.limitPrice, o.currency)}` : "Au marché"}
{o.validUntil ? `, valable jusqu'au ${o.validUntil.split("-").reverse().join("/")}` : ""}
{o.side === "buy" ? "Achat" : "Vente"} {shares(o.shares)} {o.name}
<span className="num block text-xs text-muted">
{o.type === "limit" && o.limitPrice ? `limite ${price(o.limitPrice, o.currency)}` : "au marché"}
{o.validUntil ? ` · valable jusqu'au ${o.validUntil}` : ""}
</span>
</span>
{cancellable && (
<button className="shrink-0 text-[14px] font-semibold text-danger" disabled={pending} onClick={() => start(() => cancelSandboxOrder(o.id))}>
<button className="text-sm font-medium text-danger" disabled={pending} onClick={() => start(() => cancelSandboxOrder(o.id))}>
Annuler
</button>
)}
@ -88,13 +84,13 @@ export function PendingOrders({ orders, cancellable = false }: { orders: Order[]
export function ClosedList({ positions }: { positions: Position[] }) {
if (!positions.length) return <Empty>Pas encore de trade terminé.</Empty>;
return (
<ul className="-my-1 divide-y divide-line text-[15px]">
<ul className="flex flex-col divide-y divide-line text-sm">
{positions.map((p) => (
<li key={p.id} className="flex items-center justify-between gap-3 py-3">
<span className="min-w-0">
<span className="block truncate font-semibold">{p.name}</span>
<span className="block text-[13px] text-muted">
{p.closedAt?.toLocaleDateString("fr-FR")}, {EXIT_REASONS[p.exitReason ?? ""] ?? p.exitReason}
<li key={p.id} className="flex items-center justify-between gap-3 py-2.5">
<span>
<span className="font-medium">{p.name}</span>
<span className="block text-xs text-muted">
{p.closedAt?.toLocaleDateString("fr-FR")} · {EXIT_REASONS[p.exitReason ?? ""] ?? p.exitReason}
</span>
</span>
<Delta value={p.pnlEur ?? 0}>{signedEur(p.pnlEur ?? 0)}</Delta>

View File

@ -49,13 +49,13 @@ export function PushManager() {
const s = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array(key) });
setSub(s);
await subscribePush(JSON.parse(JSON.stringify(s)));
setMsg("Notifications activées.");
setMsg("Notifications activées ✅");
});
if (status === "loading") return <p className="text-[15px] text-muted">Vérification…</p>;
if (status === "loading") return <p className="text-sm text-muted">Vérification…</p>;
if (status === "needs-install")
return (
<ol className="list-decimal pl-5 text-[15px] leading-relaxed">
<ol className="list-decimal pl-5 text-sm leading-relaxed">
<li>Ouvre ce site dans <b>Safari</b>.</li>
<li>
Touche le bouton <b>Partager</b> (carré avec une flèche vers le haut).
@ -66,13 +66,13 @@ export function PushManager() {
<li>Ouvre l&apos;app depuis la nouvelle icône, reviens ici et active les notifications.</li>
</ol>
);
if (status === "unsupported") return <p className="text-[15px] text-muted">Ce navigateur ne gère pas les notifications. Sur iPhone, il faut iOS 16.4 ou plus récent.</p>;
if (status === "unsupported") return <p className="text-sm text-muted">Ce navigateur ne gère pas les notifications. Sur iPhone, il faut iOS 16.4 ou plus récent.</p>;
return (
<div className="flex flex-col gap-2">
{sub ? (
<>
<p className="text-[15px]">Cet appareil recevra ton rendez-vous du soir.</p>
<p className="text-sm">✅ Cet appareil recevra ton rendez-vous du soir.</p>
<div className="grid grid-cols-2 gap-2">
<button className={secondaryBtn} disabled={pending} onClick={() => start(async () => setMsg((await testPush()) ? "Notification envoyée !" : "Échec de l'envoi."))}>
Tester
@ -97,7 +97,7 @@ export function PushManager() {
Activer les notifications
</button>
)}
{msg && <p className="text-[15px] text-muted">{msg}</p>}
{msg && <p className="text-sm text-muted">{msg}</p>}
</div>
);
}

View File

@ -1,31 +0,0 @@
"use client";
import { useTransition } from "react";
import { resetAiPot } from "@/app/actions";
import { primaryBtn, secondaryBtn } from "./ui";
/** Remettre la cagnotte de l'IA à zéro : mise en avant quand elle est bloquée, discrète sinon. */
export function ResetAi({ stuck }: { stuck: boolean }) {
const [pending, start] = useTransition();
const reset = () => {
if (
confirm(
"Remettre la cagnotte de l'IA à 200 € ? Ses trades et sa courbe sont effacés, et la simulation repart d'aujourd'hui : il faudra de nouveau 3 mois et 20 trades pour passer au réel.",
)
) {
start(() => resetAiPot());
}
};
if (stuck) {
return (
<button className={`${primaryBtn} w-full`} disabled={pending} onClick={reset}>
{pending ? "Remise à zéro…" : "Remettre la cagnotte de l'IA à 200 €"}
</button>
);
}
return (
<button className={`${secondaryBtn} w-full`} disabled={pending} onClick={reset}>
{pending ? "Remise à zéro…" : "Remettre la cagnotte de l'IA à zéro"}
</button>
);
}

View File

@ -7,7 +7,7 @@ export function ResetSandbox() {
const [pending, start] = useTransition();
return (
<button
className="self-center py-2 text-[14px] font-semibold text-muted underline underline-offset-4"
className="self-center text-sm text-muted underline"
disabled={pending}
onClick={() => {
if (confirm("Remettre ton bac à sable à 200 € et effacer son historique ?")) start(() => resetSandbox());

View File

@ -18,16 +18,16 @@ export function RunNow() {
});
return (
<div className="flex flex-col gap-2">
<p className="text-[15px] text-muted">Normalement tout est automatique. Ces boutons servent à tester.</p>
<p className="text-sm text-muted">Normalement tout est automatique. Ces boutons servent à tester.</p>
<button className={secondaryBtn} disabled={pending} onClick={() => run("tick")}>
Mettre à jour (actus, ordres, stops)
</button>
<button className={secondaryBtn} disabled={pending} onClick={() => run("evening")}>
Préparer le rendez-vous maintenant
</button>
{pending && <p className="text-[15px] text-muted">En cours… (jusqu&apos;à 1-2 minutes)</p>}
{pending && <p className="text-sm text-muted">En cours… (jusqu&apos;à 1-2 minutes)</p>}
{log && (
<ul className="mt-1 list-disc pl-5 text-[13px] text-muted">
<ul className="mt-1 list-disc pl-5 text-xs text-muted">
{log.length ? log.map((l, i) => <li key={i}>{l}</li>) : <li>Rien à faire pour l&apos;instant.</li>}
</ul>
)}

View File

@ -20,8 +20,8 @@ export type StockRow = {
const FILTERS = [
{ id: "all", label: "Toutes" },
{ id: "US", label: "États-Unis" },
{ id: "EU", label: "Europe" },
{ id: "US", label: "🇺🇸 US" },
{ id: "EU", label: "🇪🇺 Europe" },
{ id: "news", label: "Avec actus" },
{ id: "up", label: "En hausse" },
{ id: "down", label: "En baisse" },
@ -53,58 +53,55 @@ export function StockBrowser({ rows }: { rows: StockRow[] }) {
return (
<div className="flex flex-col gap-3">
<input className={`${inputCls} bg-surface! dark:border-line`} aria-label="Rechercher une action" placeholder="Apple, LVMH, Airbus…" value={query} onChange={(e) => setQuery(e.target.value)} type="search" />
<div className="-mx-4 flex gap-2 overflow-x-auto px-4 pb-1" role="group" aria-label="Filtrer les actions">
<input className={inputCls} placeholder="Rechercher : Apple, LVMH, Airbus…" value={query} onChange={(e) => setQuery(e.target.value)} type="search" />
<div className="-mx-4 flex gap-2 overflow-x-auto px-4 pb-1">
{FILTERS.map((f) => (
<button
key={f.id}
onClick={() => setFilter(f.id)}
aria-pressed={filter === f.id}
className={`h-9 shrink-0 rounded-full px-4 text-[14px] font-semibold ${filter === f.id ? "bg-ink text-bg" : "bg-surface text-muted dark:ring-1 dark:ring-line"}`}
className={`shrink-0 rounded-full border px-3 py-1.5 text-sm font-medium ${filter === f.id ? "border-accent bg-accent-soft text-accent" : "border-line bg-surface text-muted"}`}
>
{f.label}
</button>
))}
</div>
<ul className="divide-y divide-line overflow-hidden rounded-[22px] bg-surface dark:ring-1 dark:ring-line">
<ul className="overflow-hidden rounded-2xl border border-line bg-surface">
{list.map((r) => (
<li key={r.symbol}>
<Link href={`/actions/${encodeURIComponent(r.symbol)}`} className="flex items-center justify-between gap-3 px-5 py-3.5 active:bg-surface-2">
<li key={r.symbol} className="border-b border-line last:border-0">
<Link href={`/actions/${encodeURIComponent(r.symbol)}`} className="flex items-center justify-between gap-3 px-4 py-3 active:bg-surface-2">
<span className="min-w-0">
<span className="flex items-center gap-2 font-semibold">
<span className="flex items-center gap-1.5 font-medium">
<span className="truncate">{r.name}</span>
{r.held && <Badge tone="accent">Détenue</Badge>}
{r.held && <Badge tone="accent">détenue</Badge>}
</span>
<span className="block text-[13px] text-muted">
<span className="block text-xs text-muted">
{r.symbol}
{r.news > 0 && `, ${r.news} actu${r.news > 1 ? "s" : ""} récente${r.news > 1 ? "s" : ""}`}
{r.news > 0 && ` · 📰 ${r.news} actu${r.news > 1 ? "s" : ""}`}
</span>
</span>
<span className="shrink-0 text-right">
<span className="amount block text-[1.15rem] font-semibold">{r.price !== null ? price(r.price, r.currency) : "–"}</span>
{r.changePct !== null && <span className={`num text-[13px] font-semibold ${r.changePct >= 0 ? "text-gain" : "text-danger"}`}>{pct(r.changePct, 2)}</span>}
<span className="num block font-semibold">{r.price !== null ? price(r.price, r.currency) : "—"}</span>
{r.changePct !== null && <span className={`num text-xs ${r.changePct >= 0 ? "text-accent" : "text-danger"}`}>{pct(r.changePct, 2)}</span>}
</span>
</Link>
</li>
))}
{showHits &&
hits.map((h) => (
<li key={h.symbol}>
<Link href={`/actions/${encodeURIComponent(h.symbol)}`} className="flex items-center justify-between gap-3 px-5 py-3.5">
<li key={h.symbol} className="border-b border-line last:border-0">
<Link href={`/actions/${encodeURIComponent(h.symbol)}`} className="flex items-center justify-between gap-3 px-4 py-3">
<span>
<span className="font-semibold">{h.name}</span>
<span className="block text-[13px] text-muted">
{h.symbol}, {h.exchange}
<span className="font-medium">{h.name}</span>
<span className="block text-xs text-muted">
{h.symbol} · {h.exchange}
</span>
</span>
<Badge>{h.type === "ETF" ? "ETF" : "Action"}</Badge>
</Link>
</li>
))}
{!list.length && !(showHits && hits.length) && (
<li className="px-5 py-8 text-center text-[15px] text-muted">Aucune action ne correspond. Essaie le nom de l&apos;entreprise, par exemple « Airbus ».</li>
)}
{!list.length && !(showHits && hits.length) && <li className="px-4 py-6 text-center text-sm text-muted">Aucune action trouvée.</li>}
</ul>
</div>
);

View File

@ -16,14 +16,14 @@ export function StockChart({ bars, lastPrice, stop, target }: { bars: Bar[]; las
const y = (v: number) => H - 6 - ((v - min) / span) * (H - 12);
const path = closes.map((c, i) => `${i ? "L" : "M"}${x(i).toFixed(1)},${y(c).toFixed(1)}`).join(" ");
const up = closes.at(-1)! >= closes[0];
const color = up ? "var(--gain)" : "var(--danger)";
const color = up ? "var(--accent)" : "var(--danger)";
return (
<svg viewBox={`0 0 ${W} ${H}`} className="h-40 w-full" preserveAspectRatio="none" role="img" aria-label="Évolution du cours">
<path d={`${path} L${W},${H} L0,${H} Z`} fill={color} opacity={0.12} />
<svg viewBox={`0 0 ${W} ${H}`} className="h-32 w-full" preserveAspectRatio="none" role="img" aria-label="Évolution du cours">
<path d={`${path} L${W},${H} L0,${H} Z`} fill={color} opacity={0.1} />
<path d={path} fill="none" stroke={color} strokeWidth={2} vectorEffect="non-scaling-stroke" strokeLinejoin="round" />
{stop != null && <line x1={0} x2={W} y1={y(stop)} y2={y(stop)} stroke="var(--danger)" strokeDasharray="4 4" vectorEffect="non-scaling-stroke" />}
{target != null && <line x1={0} x2={W} y1={y(target)} y2={y(target)} stroke="var(--gain)" strokeDasharray="4 4" vectorEffect="non-scaling-stroke" />}
{target != null && <line x1={0} x2={W} y1={y(target)} y2={y(target)} stroke="var(--accent)" strokeDasharray="4 4" vectorEffect="non-scaling-stroke" />}
</svg>
);
}

View File

@ -58,91 +58,90 @@ export function TradePanel({ symbol, currency, lastPrice, fxToEur, cash, askLeft
setMessage({ ok: r.ok, text: r.message });
});
const toggle = (active: boolean) => (active ? "bg-ink text-bg" : "bg-surface-2 text-muted");
const toggle = (active: boolean) => (active ? "border-accent bg-accent-soft text-accent" : "border-line bg-surface-2 text-muted");
return (
<>
<Card title="Acheter dans mon bac à sable">
<p className="num -mt-2 mb-4 text-[14px] text-muted">{eur(cash)} disponibles</p>
<Card title="Acheter dans mon bac à sable" action={<span className="num text-xs text-muted">dispo {eur(cash)}</span>}>
<div className="flex flex-col gap-3">
<div className="grid grid-cols-2 gap-2 text-[15px] font-semibold">
<button className={`h-10 rounded-full ${toggle(mode === "amount")}`} onClick={() => setMode("amount")}>
<div className="grid grid-cols-2 gap-2 text-sm font-medium">
<button className={`h-10 rounded-xl border ${toggle(mode === "amount")}`} onClick={() => setMode("amount")}>
Montant en €
</button>
<button className={`h-10 rounded-full ${toggle(mode === "shares")}`} onClick={() => setMode("shares")}>
<button className={`h-10 rounded-xl border ${toggle(mode === "shares")}`} onClick={() => setMode("shares")}>
Nb d&apos;actions
</button>
</div>
{mode === "amount" ? (
<label className="text-[13px] text-muted">
<label className="text-xs text-muted">
Montant à investir (€)
<input className={`${inputCls} mt-1`} inputMode="decimal" value={amount} onChange={(e) => setAmount(e.target.value)} />
<span className="mt-2 flex gap-2">
<span className="mt-1 flex gap-2">
{[50, 100, 150].map((v) => (
<button key={v} className="h-8 rounded-full bg-surface-2 px-3 text-[13px] font-semibold" onClick={() => setAmount(String(v))}>
<button key={v} className="rounded-full border border-line px-2.5 py-1 text-xs" onClick={() => setAmount(String(v))}>
{v} €
</button>
))}
<button className="h-8 rounded-full bg-surface-2 px-3 text-[13px] font-semibold" onClick={() => setAmount(String(Math.floor(Math.max(cash - 1, 0))))}>
<button className="rounded-full border border-line px-2.5 py-1 text-xs" onClick={() => setAmount(String(Math.floor(Math.max(cash - 1, 0))))}>
Tout
</button>
</span>
</label>
) : (
<label className="text-[13px] text-muted">
<label className="text-xs text-muted">
Nombre d&apos;actions (fractions possibles)
<input className={`${inputCls} mt-1`} inputMode="decimal" value={shares} onChange={(e) => setShares(e.target.value)} />
</label>
)}
<div className="grid grid-cols-2 gap-2 text-[15px] font-semibold">
<button className={`h-10 rounded-full ${toggle(type === "market")}`} onClick={() => setType("market")}>
<div className="grid grid-cols-2 gap-2 text-sm font-medium">
<button className={`h-10 rounded-xl border ${toggle(type === "market")}`} onClick={() => setType("market")}>
Au marché
</button>
<button className={`h-10 rounded-full ${toggle(type === "limit")}`} onClick={() => setType("limit")}>
<button className={`h-10 rounded-xl border ${toggle(type === "limit")}`} onClick={() => setType("limit")}>
Cours limité
</button>
</div>
{type === "limit" && (
<label className="text-[13px] text-muted">
<label className="text-xs text-muted">
N&apos;acheter que si le cours descend à ({currency === "EUR" ? "€" : "$"})
<input className={`${inputCls} mt-1`} inputMode="decimal" value={limit} onChange={(e) => setLimit(e.target.value)} />
</label>
)}
<div className="grid grid-cols-2 gap-2">
<label className="text-[13px] text-muted">
<label className="text-xs text-muted">
Stop : vendre si −{stop || "?"} %
<input className={`${inputCls} mt-1`} inputMode="decimal" value={stopPct} onChange={(e) => setStopPct(e.target.value)} placeholder="aucun" />
</label>
<label className="text-[13px] text-muted">
<label className="text-xs text-muted">
Objectif : vendre à +{target || "?"} %
<input className={`${inputCls} mt-1`} inputMode="decimal" value={targetPct} onChange={(e) => setTargetPct(e.target.value)} placeholder="aucun" />
</label>
</div>
<div className="rounded-2xl bg-surface-2 p-4 text-[15px]">
<div className="rounded-xl bg-surface-2 p-3 text-sm">
<p className="num">
Environ {qty.toLocaleString("fr-FR", { maximumFractionDigits: 4 })} action pour {eur(costEur)}, plus 1 € de frais.
≈ {qty.toLocaleString("fr-FR", { maximumFractionDigits: 4 })} action · {eur(costEur)} + 1 € de frais
</p>
{stop > 0 && unit > 0 && (
<p className="num mt-1.5 text-[14px] leading-relaxed text-muted">
Vente automatique à {price(unit * (1 - stop / 100), currency)} : tu ne perdrais pas plus d&apos;environ {eur(maxLoss ?? 0, 0)}.
{target > 0 && ` Objectif de vente à ${price(unit * (1 + target / 100), currency)}.`}
<p className="num mt-1 text-xs text-muted">
Stop à {price(unit * (1 - stop / 100), currency)} → perte max ≈ {eur(maxLoss ?? 0, 0)}
{target > 0 && ` · objectif ${price(unit * (1 + target / 100), currency)}`}
</p>
)}
{tooMuch && <p className="mt-1 text-[13px] text-danger">Pas assez de liquidités dans ton bac à sable.</p>}
{tooMuch && <p className="mt-1 text-xs text-danger">Pas assez de liquidités dans ton bac à sable.</p>}
</div>
<button className={primaryBtn} disabled={buying || qty <= 0 || tooMuch} onClick={buy}>
{buying ? "Envoi…" : "Acheter (argent fictif)"}
</button>
{message && (
<p className={`text-[15px] ${message.ok ? "text-gain" : "text-danger"}`}>
<p className={`text-sm ${message.ok ? "text-accent" : "text-danger"}`}>
{message.text}{" "}
{message.ok && (
<Link href="/bac-a-sable" className="font-semibold underline">
<Link href="/bac-a-sable" className="font-medium underline">
Voir mon bac à sable
</Link>
)}
@ -151,12 +150,12 @@ export function TradePanel({ symbol, currency, lastPrice, fxToEur, cash, askLeft
</div>
</Card>
<Card title="L'avis de l'IA">
<Card title="🤖 L'avis de l'IA">
{!aiOn ? (
<p className="text-[15px] text-muted">L&apos;IA n&apos;est pas branchée (clé Anthropic manquante, voir le README). Tout le reste fonctionne sans elle.</p>
<p className="text-sm text-muted">L&apos;IA n&apos;est pas branchée (clé Anthropic manquante, voir le README). Tout le reste fonctionne sans elle.</p>
) : (
<div className="flex flex-col gap-2">
<p className="text-[13px] text-muted">{askLeft} avis restant(s) aujourd&apos;hui</p>
<p className="text-xs text-muted">{askLeft} avis restant(s) aujourd&apos;hui</p>
<input className={inputCls} placeholder="Ex. : c'est le bon moment pour acheter ?" value={question} onChange={(e) => setQuestion(e.target.value)} />
<button
className={secondaryBtn}
@ -173,16 +172,14 @@ export function TradePanel({ symbol, currency, lastPrice, fxToEur, cash, askLeft
{asking ? "L'IA réfléchit… (≈ 20 s)" : "Demander son avis"}
</button>
{answer && (
<div className="mt-1 flex flex-col gap-2 text-[15px]">
<div className="mt-1 flex flex-col gap-2 text-sm">
<p>
<Badge tone={answer.verdict === "acheter" ? "gain" : answer.verdict === "éviter" ? "danger" : "pot"}>
{answer.verdict.charAt(0).toUpperCase() + answer.verdict.slice(1)}
</Badge>{" "}
<Badge tone={answer.verdict === "acheter" ? "accent" : answer.verdict === "éviter" ? "danger" : "warn"}>{answer.verdict.toUpperCase()}</Badge>{" "}
<span className="text-muted">confiance {Math.round(answer.confidence)} %</span>
</p>
<p className="leading-relaxed">{answer.explanation}</p>
<p className="leading-relaxed text-muted">Risques : {answer.risks}</p>
<button className="self-start text-[15px] font-semibold text-accent" onClick={() => setStopPct(String(Math.round(answer.suggestedStopPct)))}>
<p className="leading-relaxed text-muted">⚠️ {answer.risks}</p>
<button className="self-start text-sm font-medium text-accent" onClick={() => setStopPct(String(Math.round(answer.suggestedStopPct)))}>
Utiliser son stop conseillé ({Math.round(answer.suggestedStopPct)} %)
</button>
</div>
@ -202,7 +199,7 @@ function RealProposal({ symbol, stopPct }: { symbol: string; stopPct: number })
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
return (
<Card title="Pour de vrai (Trade Republic)">
<p className="mb-3 text-[15px] text-muted">Le contrôle des risques vérifie la taille et le stop, puis te prépare une fiche pas à pas.</p>
<p className="mb-3 text-sm text-muted">Le contrôle des risques vérifie la taille et le stop, puis te prépare une fiche pas à pas.</p>
<button
className={`${secondaryBtn} w-full`}
disabled={pending}
@ -215,7 +212,7 @@ function RealProposal({ symbol, stopPct }: { symbol: string; stopPct: number })
>
Vérifier et créer la fiche réelle
</button>
{msg && <p className={`mt-2 text-[15px] ${msg.ok ? "text-gain" : "text-danger"}`}>{msg.text}</p>}
{msg && <p className={`mt-2 text-sm ${msg.ok ? "text-accent" : "text-danger"}`}>{msg.text}</p>}
</Card>
);
}

View File

@ -1,36 +1,28 @@
import type { ReactNode } from "react";
/** Une page : grand titre à gauche, sous-titre court, action éventuelle en haut à droite. */
export function Page({ title, subtitle, action, children }: { title: string; subtitle?: ReactNode; action?: ReactNode; children: ReactNode }) {
return (
<main className="mx-auto w-full max-w-lg px-4 pb-32 pt-[max(env(safe-area-inset-top),1.5rem)]">
<header className="mb-6 flex items-start justify-between gap-3">
<main className="mx-auto w-full max-w-lg px-4 pb-28 pt-[max(env(safe-area-inset-top),1.25rem)]">
<header className="mb-5 flex items-start justify-between gap-3">
<div className="min-w-0">
<h1 className="display text-[2.1rem] font-bold">{title}</h1>
{subtitle && <p className="mt-2 max-w-[34ch] text-[15px] leading-snug text-muted">{subtitle}</p>}
<h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
{subtitle && <p className="mt-1 text-sm text-muted">{subtitle}</p>}
</div>
{action && <div className="shrink-0 pt-1.5">{action}</div>}
{action && <div className="shrink-0 pt-1">{action}</div>}
</header>
<div className="flex flex-col gap-4">{children}</div>
</main>
);
}
type Tone = "accent" | "warn" | "danger" | "pot";
/** Un bloc de la page. `tone` le met en avant (à faire, à configurer, alerte). */
export function Card({ title, action, children, tone }: { title?: ReactNode; action?: ReactNode; children: ReactNode; tone?: Tone }) {
const toneCls = {
accent: "bg-surface ring-2 ring-accent/45",
warn: "bg-pot-soft",
pot: "bg-pot-soft",
danger: "bg-danger-soft",
};
export function Card({ title, action, children, tone }: { title?: ReactNode; action?: ReactNode; children: ReactNode; tone?: "accent" | "warn" | "danger" }) {
const toneCls =
tone === "accent" ? "border-accent/40" : tone === "warn" ? "border-warn/40" : tone === "danger" ? "border-danger/40" : "border-line";
return (
<section className={`rounded-[22px] p-5 ${tone ? toneCls[tone] : "bg-surface dark:ring-1 dark:ring-line"}`}>
<section className={`rounded-2xl border bg-surface p-4 ${toneCls}`}>
{(title || action) && (
<div className="mb-4 flex items-center justify-between gap-3">
{title && <h2 className="display text-[1.2rem] font-semibold">{title}</h2>}
<div className="mb-3 flex items-center justify-between gap-3">
{title && <h2 className="text-sm font-semibold uppercase tracking-wide text-muted">{title}</h2>}
{action}
</div>
)}
@ -39,50 +31,46 @@ export function Card({ title, action, children, tone }: { title?: ReactNode; act
);
}
export function Badge({ children, tone = "neutral" }: { children: ReactNode; tone?: "neutral" | "accent" | "warn" | "danger" | "gain" | "pot" }) {
export function Badge({ children, tone = "neutral" }: { children: ReactNode; tone?: "neutral" | "accent" | "warn" | "danger" }) {
const cls = {
neutral: "bg-surface-2 text-muted",
accent: "bg-accent-soft text-accent",
warn: "bg-warn-soft text-warn",
pot: "bg-pot-soft text-pot",
gain: "bg-gain-soft text-gain",
danger: "bg-danger-soft text-danger",
}[tone];
return <span className={`inline-flex items-center rounded-md px-2 py-0.5 text-[13px] font-semibold ${cls}`}>{children}</span>;
return <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${cls}`}>{children}</span>;
}
/** Un gain en vert, une perte en rouge. */
export function Delta({ value, children }: { value: number; children: ReactNode }) {
return <span className={`num font-semibold ${value >= 0 ? "text-gain" : "text-danger"}`}>{children}</span>;
return <span className={`num font-medium ${value >= 0 ? "text-accent" : "text-danger"}`}>{children}</span>;
}
/** Bloc de chargement : la forme de la section, pendant que les cours arrivent. */
/** Bloc de chargement pour une section qui attend des cours de bourse. */
export function CardSkeleton({ title, height = "h-24" }: { title?: string; height?: string }) {
return (
<section className="rounded-[22px] bg-surface p-5 dark:ring-1 dark:ring-line" aria-busy="true">
{title ? <h2 className="display mb-4 text-[1.2rem] font-semibold text-muted">{title}</h2> : <div className="skeleton mb-4 h-5 w-32 rounded-md" />}
<div className={`${height} skeleton rounded-2xl`} />
<section className="rounded-2xl border border-line bg-surface p-4">
{title && <h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-muted">{title}</h2>}
<div className={`${height} animate-pulse rounded-xl bg-surface-2`} />
</section>
);
}
/** Un chiffre et sa légende, séparés des voisins par un filet. À placer dans une grille. */
export function Stat({ label, children }: { label: string; children: ReactNode }) {
return (
<div className="min-w-0 border-l border-line pl-3 first:border-l-0 first:pl-0">
<p className="amount truncate text-[1.35rem] font-semibold">{children}</p>
<p className="mt-1 text-[13px] text-muted">{label}</p>
<div className="rounded-xl bg-surface-2 p-2.5 text-center">
<p className="num font-semibold">{children}</p>
<p className="text-xs text-muted">{label}</p>
</div>
);
}
export function Empty({ children }: { children: ReactNode }) {
return <p className="py-1 text-[15px] leading-relaxed text-muted">{children}</p>;
return <p className="py-2 text-sm text-muted">{children}</p>;
}
export const buttonCls =
"inline-flex h-12 items-center justify-center gap-2 rounded-full px-5 text-[15px] font-bold transition-transform active:scale-[0.98] disabled:opacity-45";
export const primaryBtn = `${buttonCls} bg-accent text-accent-ink`;
export const secondaryBtn = `${buttonCls} bg-surface-2 text-ink`;
"inline-flex h-11 items-center justify-center rounded-xl px-4 text-sm font-semibold transition active:scale-[0.98] disabled:opacity-50";
export const primaryBtn = `${buttonCls} bg-accent text-white dark:text-black`;
export const secondaryBtn = `${buttonCls} border border-line bg-surface-2 text-ink`;
export const inputCls =
"h-12 w-full rounded-xl border border-transparent bg-surface-2 px-3.5 text-base text-ink outline-none placeholder:text-muted/70 focus:border-accent";
"h-11 w-full rounded-xl border border-line bg-surface-2 px-3 text-base text-ink outline-none focus:border-accent";

View File

@ -118,7 +118,7 @@ describe("intégration", () => {
});
it("prépare un rendez-vous même sans IA, et calcule PEA, classement et critères", async () => {
const log = await runEvening({ force: true });
const log = await runEvening();
expect(log.join(" ")).toContain("Rendez-vous créé");
const db = await getDb();
const [rdv] = await db.select().from(schema.rendezvous);
@ -137,88 +137,10 @@ describe("intégration", () => {
expect(board.map((b) => b.label).sort()).toEqual(["L'IA", "S&P 500", "Toi"]);
});
it("n'exécute un ordre qu'une fois même si deux mises à jour tournent en même temps", async () => {
const db = await getDb();
await db.delete(schema.positions).where(eq(schema.positions.portfolioId, "sandbox"));
await db.delete(schema.orders).where(eq(schema.orders.portfolioId, "sandbox"));
await db.update(schema.portfolios).set({ cash: 200 }).where(eq(schema.portfolios.id, "sandbox"));
const quote = (await getQuote("KO"))!;
const [order] = await db
.insert(schema.orders)
.values({
portfolioId: "sandbox",
symbol: "KO",
name: "Coca-Cola",
currency: quote.currency,
side: "buy",
type: "limit",
shares: 1,
limitPrice: quote.price * 1.2,
validUntil: addDays(parisDate(), 5),
createdAt: new Date(Date.now() - 5 * 86_400_000),
})
.returning();
await Promise.all([processAll(), processAll(), processAll()]);
const positions = await db.select().from(schema.positions).where(eq(schema.positions.portfolioId, "sandbox"));
expect(positions).toHaveLength(1);
const [o] = await db.select().from(schema.orders).where(eq(schema.orders.id, order.id));
expect(o.status).toBe("filled");
const s = await getPortfolioState("sandbox");
expect(s.cash).toBeCloseTo(200 - positions[0].shares * positions[0].entryPrice * positions[0].entryFx - 1, 6);
// Vente : la position ne peut être clôturée qu'une fois.
const { closePosition } = await import("./portfolio");
const results = await Promise.all([closePosition(positions[0], 70, 1, "manual"), closePosition(positions[0], 70, 1, "manual")]);
expect(results.filter(Boolean)).toHaveLength(1);
});
it("un double appui sur « C'est fait » n'enregistre l'achat réel qu'une fois", async () => {
const db = await getDb();
await db.delete(schema.positions).where(eq(schema.positions.portfolioId, "real"));
const [card] = await db
.insert(schema.actions)
.values({
rendezvousId: 0,
kind: "buy",
training: false,
symbol: "KO",
payload: { title: "Acheter", why: "", steps: [], name: "Coca-Cola", currency: "USD", shares: 1, limitPrice: 60, stopPrice: 55 },
})
.returning();
const r = await Promise.allSettled([respondToCard(card.id, "done"), respondToCard(card.id, "done")]);
expect(r.filter((x) => x.status === "fulfilled")).toHaveLength(1);
const real = await getPortfolioState("real");
expect(real.positions).toHaveLength(1);
});
it("verrous : une seule mise à jour à la fois, une chose par jour", async () => {
const { claimKv, claimLock, releaseLock } = await import("./settings");
expect(await claimLock("testLock", 60_000)).toBe(true);
expect(await claimLock("testLock", 60_000)).toBe(false);
await releaseLock("testLock");
expect(await claimLock("testLock", 60_000)).toBe(true);
expect(await claimKv("testDay", "2026-11-18")).toBe(true);
expect(await claimKv("testDay", "2026-11-18")).toBe(false);
expect(await claimKv("testDay", "2026-11-19")).toBe(true);
});
it("remet la cagnotte de l'IA à zéro et relance la simulation", async () => {
const db = await getDb();
const { resetAiSim } = await import("./jobs");
await db.update(schema.portfolios).set({ cash: 120 }).where(eq(schema.portfolios.id, "ai_sim"));
await db.insert(schema.cashFlows).values({ portfolioId: "ai_sim", amount: 50, kind: "deposit", date: "2026-10-05" });
await resetAiSim();
const ai = await getPortfolioState("ai_sim");
expect(ai.cash).toBe(200);
const flows = await db.select().from(schema.cashFlows).where(eq(schema.cashFlows.portfolioId, "ai_sim"));
expect(flows).toHaveLength(0);
expect((await ensureSetup()).simStartDate).toBe(parisDate());
});
it("sans IA, propose une idée du filtre et permet un achat fractionné", async () => {
const { refreshIdeas } = await import("./ideas");
const ideas = await refreshIdeas(true);
await runEvening({ force: true });
await runEvening();
const db = await getDb();
const cards = await db.select().from(schema.actions).where(eq(schema.actions.status, "pending"));
// Le marché ne donne pas toujours d'idée : la fiche n'existe que s'il y en a une.

View File

@ -1,10 +1,10 @@
import "server-only";
import { and, desc, eq, or } from "drizzle-orm";
import { desc, eq } from "drizzle-orm";
import { getDb, schema } from "./db";
import { FEE_EUR } from "./engine/fills";
import { checkBuy } from "./engine/risk";
import { getFxToEur, getNextEarningsDate, getQuote, isSupportedCurrency } from "./market";
import { addCash, closePosition, getPortfolioState } from "./portfolio";
import { closePosition, getPortfolioState } from "./portfolio";
import { parisDate } from "./time";
export type Card = typeof schema.actions.$inferSelect;
@ -17,16 +17,10 @@ export async function getLatestRendezvous() {
return { ...rdv, cards };
}
/**
* Fiches encore à traiter hors du dernier rendez-vous : tes trades proposés à la main,
* et les virements vers le PEA (qui ne doivent pas disparaître le lendemain).
*/
export async function getPendingAdhocCards(): Promise<Card[]> {
const db = await getDb();
return db
.select()
.from(schema.actions)
.where(and(eq(schema.actions.status, "pending"), or(eq(schema.actions.rendezvousId, 0), eq(schema.actions.kind, "to_pea"))));
const rows = await db.select().from(schema.actions).where(eq(schema.actions.rendezvousId, 0));
return rows.filter((r) => r.status === "pending");
}
/**
@ -35,31 +29,17 @@ export async function getPendingAdhocCards(): Promise<Card[]> {
*/
export async function respondToCard(id: number, answer: "done" | "skipped", fill?: { price?: number; shares?: number }) {
const db = await getDb();
// Réservation atomique : un double appui sur « C'est fait » n'enregistre pas l'achat deux fois.
const [card] = await db
.update(schema.actions)
.set({ status: answer, respondedAt: new Date() })
.where(and(eq(schema.actions.id, id), eq(schema.actions.status, "pending")))
.returning();
if (!card) throw new Error("Fiche introuvable ou déjà traitée.");
try {
if (answer === "done" && !card.training) await applyRealCard(card, fill);
} catch (e) {
await db.update(schema.actions).set({ status: "pending", respondedAt: null }).where(eq(schema.actions.id, id));
throw e;
}
}
const [card] = await db.select().from(schema.actions).where(eq(schema.actions.id, id));
if (!card || card.status !== "pending") throw new Error("Fiche introuvable ou déjà traitée.");
async function applyRealCard(card: Card, fill?: { price?: number; shares?: number }) {
const db = await getDb();
{
if (answer === "done" && !card.training) {
const p = card.payload;
if (card.kind === "buy" && card.symbol) {
const shares = fill?.shares ?? p.shares!;
const price = fill?.price ?? p.limitPrice!;
if (!(shares > 0) || !(price > 0)) throw new Error("Indique le prix et le nombre d'actions réellement obtenus.");
const fx = (await getFxToEur(p.currency!)) ?? 1;
await addCash("real", -(shares * price * fx + FEE_EUR));
const [pf] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, "real"));
await db.update(schema.portfolios).set({ cash: pf.cash - (shares * price * fx + FEE_EUR) }).where(eq(schema.portfolios.id, "real"));
await db.insert(schema.positions).values({
portfolioId: "real",
symbol: card.symbol,
@ -85,18 +65,20 @@ async function applyRealCard(card: Card, fill?: { price?: number; shares?: numbe
} else if (card.kind === "move_stop" && p.positionId) {
await db.update(schema.positions).set({ stopPrice: p.stopPrice }).where(eq(schema.positions.id, p.positionId));
} else if (card.kind === "to_pea" && p.amountEur) {
await addCash("real", -p.amountEur);
const [pf] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, "real"));
await db.update(schema.portfolios).set({ cash: pf.cash - p.amountEur }).where(eq(schema.portfolios.id, "real"));
await db.insert(schema.cashFlows).values({ portfolioId: "real", amount: -p.amountEur, kind: "to_pea", date: parisDate() });
// Nouveau plus haut de référence : la valeur de la cagnotte juste après le virement.
const state = await getPortfolioState("real");
await db.update(schema.portfolios).set({ highWaterMark: state.equity }).where(eq(schema.portfolios.id, "real"));
}
}
await db.update(schema.actions).set({ status: answer, respondedAt: new Date() }).where(eq(schema.actions.id, id));
}
/** Un trade réel que TU proposes : il passe par le même contrôle des risques que l'IA. */
export async function proposeManualRealBuy(symbol: string, stopPct: number) {
const quote = await getQuote(symbol, { fresh: true });
const quote = await getQuote(symbol);
if (!quote) throw new Error("Cours introuvable.");
if (!isSupportedCurrency(quote.currency)) throw new Error("Seules les actions en euros ou en dollars sont gérées.");
const fx = (await getFxToEur(quote.currency))!;

View File

@ -149,7 +149,7 @@ export const actions = pgTable("actions", {
training: boolean("training").notNull(), // true = entraînement (réel pas encore débloqué)
symbol: text("symbol"),
payload: jsonb("payload").$type<ActionPayload>().notNull(),
status: text("status").notNull().default("pending"), // pending | done | skipped | expired
status: text("status").notNull().default("pending"), // pending | done | skipped
respondedAt: timestamp("responded_at", { withTimezone: true }),
});

View File

@ -1,5 +1,5 @@
import "server-only";
import { and, desc, gte, isNotNull } from "drizzle-orm";
import { desc, gte, isNotNull } from "drizzle-orm";
import { aiEnabled, getAiSpend } from "./ai";
import { getDb, schema } from "./db";
import type { RunLog } from "./jobs";
@ -15,7 +15,7 @@ export async function getDiagnostics() {
db
.select({ triage: schema.news.triage })
.from(schema.news)
.where(and(isNotNull(schema.news.triagedAt), gte(schema.news.publishedAt, since48h))),
.where(isNotNull(schema.news.triagedAt)),
db.select().from(schema.signals).where(gte(schema.signals.createdAt, since7d)).orderBy(desc(schema.signals.createdAt)).limit(10),
getAiSpend(),
getKv<RunLog>("lastTickLog"),

View File

@ -1,11 +1,11 @@
import { describe, expect, it } from "vitest";
import { evaluateBuyLimit, evaluateExit, type Bar } from "./fills";
import { aiSimStuck, checkBuy, tierFor } from "./risk";
import { checkBuy, tierFor } from "./risk";
import { screenBars } from "./screen";
import { computePea } from "./pea";
import { benchmarkWithFlows, computeGate, equityWithoutDeposits, maxDrawdownPct } from "./gate";
import { computeGate, maxDrawdownPct } from "./gate";
import { circuitBreakerTripped, computeRatchet } from "./ratchet";
import { addTradingDays, dueDeposits, easterSunday, isTradingDay } from "../time";
import { addTradingDays } from "../time";
const bar = (date: string, open: number, high: number, low: number, close: number): Bar => ({
date,
@ -188,72 +188,6 @@ describe("cliquet et coupe-circuit", () => {
});
});
describe("calendrier Trade Republic", () => {
it("connaît Pâques et les jours fériés", () => {
expect(easterSunday(2026)).toBe("2026-04-05");
expect(easterSunday(2027)).toBe("2027-03-28");
expect(isTradingDay("2026-04-03")).toBe(false); // Vendredi saint
expect(isTradingDay("2026-04-06")).toBe(false); // lundi de Pâques
expect(isTradingDay("2026-12-24")).toBe(false);
expect(isTradingDay("2026-11-18")).toBe(true);
});
it("saute les jours fériés en comptant les jours de bourse", () => {
expect(addTradingDays("2026-12-23", 1)).toBe("2026-12-28");
expect(addTradingDays("2026-04-02", 1)).toBe("2026-04-07");
});
it("rattrape les virements mensuels manqués, sans doublon", () => {
expect(dueDeposits("2026-09-05", 5, null, "2026-11-18")).toEqual(["2026-09-05", "2026-10-05", "2026-11-05"]);
expect(dueDeposits("2026-09-05", 5, "2026-10", "2026-11-18")).toEqual(["2026-11-05"]);
expect(dueDeposits("2026-09-05", 5, "2026-11", "2026-11-18")).toEqual([]);
expect(dueDeposits("2026-11-20", 20, null, "2026-11-18")).toEqual([]);
});
});
describe("cagnotte de l'IA avec versements mensuels", () => {
it("compare au S&P 500 avec les mêmes versements aux mêmes dates", () => {
const bars = [bar("2026-09-01", 100, 100, 100, 100), bar("2026-10-05", 50, 50, 50, 50)];
// 200 € à 100 (2 parts) + 50 € à 50 (1 part) = 3 parts à 60 = 180 € pour 250 € versés.
const r = benchmarkWithFlows(bars, 60, [
{ date: "2026-09-01", amount: 200 },
{ date: "2026-10-05", amount: 50 },
]);
expect(r).toBeCloseTo(-28, 6);
});
it("un versement ne masque pas une perte dans la pire baisse", () => {
const curve = equityWithoutDeposits(
[
{ date: "2026-09-01", equity: 200 },
{ date: "2026-10-01", equity: 150 },
{ date: "2026-10-06", equity: 200 },
],
[{ date: "2026-10-05", amount: 50 }],
);
expect(curve).toEqual([200, 150, 150]);
expect(maxDrawdownPct(curve)).toBeCloseTo(25, 6);
});
it("repère une cagnotte bloquée sous le minimum", () => {
expect(aiSimStuck({ cash: 140, positions: [], pendingOrders: [] })).toBe(true);
expect(aiSimStuck({ cash: 140, positions: [{}], pendingOrders: [] })).toBe(false);
expect(aiSimStuck({ cash: 190, positions: [], pendingOrders: [] })).toBe(false);
});
});
describe("trous de cotation", () => {
it("vend à l'objectif à l'ouverture si le cours ouvre au-dessus, même si le stop est touché ensuite", () => {
const r = evaluateExit({
entryDate: "2026-10-12",
today: "2026-10-13",
stop: 93,
target: 110,
maxExitDate: null,
bars: [bar("2026-10-13", 112, 113, 92, 95)],
currentPrice: 95,
brokerOpen: true,
});
expect(r).toEqual({ price: 112, reason: "target", date: "2026-10-13" });
});
});
describe("filtre d'idées sans IA", () => {
const series = (closes: number[]): Bar[] =>
closes.map((c, i) => ({ date: `d${String(i).padStart(3, "0")}`, open: c, high: c, low: c, close: c }));

View File

@ -64,10 +64,7 @@ export function evaluateExit(input: ExitInput): ExitResult {
for (const bar of bars) {
if (bar.date <= entryDate || bar.date > today) continue;
// Ouverture au-delà du stop ou de l'objectif (trou de cotation) : l'ordre part à l'ouverture.
if (stop !== null && bar.open <= stop) return { price: bar.open, reason: "stop", date: bar.date };
if (target !== null && bar.open >= target) return { price: bar.open, reason: "target", date: bar.date };
// Stop et objectif touchés dans la même journée sans trou : on ne sait pas lequel d'abord, on suppose le pire.
// Si le stop et l'objectif sont touchés le même jour, on suppose le pire : le stop.
if (stop !== null && bar.low <= stop) {
return { price: Math.min(bar.open, stop), reason: "stop", date: bar.date };
}

View File

@ -3,14 +3,13 @@
* 3 mois de simulation, 20 trades clôturés, meilleur que le S&P 500 après frais et coût de l'IA,
* pire baisse inférieure à 25 %, au moins 80 % des rendez-vous suivis.
*/
import type { Bar } from "./fills";
export type GateInput = {
simDays: number;
closedTrades: number;
aiReturnPct: number; // rendement de la cagnotte IA sur l'argent versé, frais Trade Republic inclus
aiReturnPct: number; // rendement de la cagnotte IA, frais Trade Republic inclus
aiCostEur: number; // coût cumulé de l'IA
initialCash: number; // argent versé au total (départ + versements mensuels)
initialCash: number;
benchmarkReturnPct: number;
maxDrawdownPct: number;
actionsTotal: number;
@ -53,38 +52,6 @@ export function maxDrawdownPct(equities: number[]): number {
return worst;
}
export type Flow = { date: string; amount: number };
/**
* Ce qu'aurait rapporté le S&P 500 avec exactement les mêmes versements, aux mêmes dates
* (le capital de départ puis chaque versement mensuel achète des parts de l'ETF ce jour-là).
* Comparaison équitable avec une cagnotte qui reçoit de l'argent tous les mois. En %.
*/
export function benchmarkWithFlows(bars: Bar[], lastPrice: number | null, flows: Flow[]): number {
const sorted = [...bars].sort((a, b) => a.date.localeCompare(b.date));
let units = 0;
let invested = 0;
for (const f of flows) {
const bar = sorted.find((b) => b.date >= f.date) ?? sorted.at(-1);
if (!bar) continue;
units += f.amount / bar.close;
invested += f.amount;
}
const price = lastPrice ?? sorted.at(-1)?.close;
if (!invested || !price) return 0;
return ((units * price) / invested - 1) * 100;
}
/**
* Valeurs de la cagnotte sans l'effet des versements : on retire de chaque valeur l'argent versé
* après le départ. Un versement ne masque donc pas une perte dans le calcul de la pire baisse.
*/
export function equityWithoutDeposits(snaps: { date: string; equity: number }[], deposits: Flow[]): number[] {
return [...snaps]
.sort((a, b) => a.date.localeCompare(b.date))
.map((s) => s.equity - deposits.filter((d) => d.date <= s.date).reduce((t, d) => t + d.amount, 0));
}
function fmt(n: number): string {
return `${n >= 0 ? "+" : ""}${n.toFixed(1)} %`;
}

View File

@ -109,11 +109,6 @@ export function checkBuy(input: RiskInput): RiskResult {
};
}
/** La cagnotte n'a plus de quoi ouvrir une position (minimum 150 € + frais) et n'en détient aucune. */
export function aiSimStuck(s: { cash: number; positions: unknown[]; pendingOrders: unknown[] }): boolean {
return s.positions.length === 0 && s.pendingOrders.length === 0 && s.cash < MIN_POSITION_EUR + 2 * FEE_EUR;
}
/** Fractions d'actions : 4 décimales, arrondi vers le bas pour ne jamais dépasser le budget. */
export function roundShares(n: number): number {
return Math.floor(n * 10_000) / 10_000;

View File

@ -1,18 +1,18 @@
import "server-only";
import { and, eq, gte, inArray, isNotNull, isNull, ne, sql } from "drizzle-orm";
import { and, eq, isNull, ne } from "drizzle-orm";
import { aiEnabled, analyzeCandidate, AiUnavailableError, type Analysis } from "./ai";
import { getDb, schema } from "./db";
import { aiSimStuck, checkBuy, MIN_CONFIDENCE, MIN_POSITION_EUR } from "./engine/risk";
import { checkBuy, MIN_CONFIDENCE } 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 { collectNews, recentNews, triagePending } from "./news";
import { getOpenSymbols, getPortfolioState, placeOrder, processAll, snapshotEquity, type PortfolioState } from "./portfolio";
import { sendPush } from "./push";
import { claimKv, claimLock, getKv, getSettings, releaseLock, setKv, SIM_INITIAL_CASH, updateSettings, type Settings } from "./settings";
import { getKv, getSettings, setKv, SIM_INITIAL_CASH, updateSettings, type Settings } from "./settings";
import { getIdeas, refreshIdeas, type Idea } from "./ideas";
import { getGateStatus, totalDeposited } from "./stats";
import { addDays, addTradingDays, dueDeposits, isTradeRepublicOpen, isTradingDay, parisDate, parisMinutes } from "./time";
import { addDays, addTradingDays, isTradeRepublicOpen, isWeekend, parisDate, parisMinutes } from "./time";
import { findStock, UNIVERSE } from "./universe";
const UNIVERSE_COLLECT_EVERY_MS = 3 * 3_600_000;
@ -25,55 +25,36 @@ const AUTO_TICK_EVERY_MS = 20 * 60_000;
* Ainsi l'app vit même sans la tâche planifiée GitHub (en local, ou si elle n'est pas branchée).
*/
export async function shouldAutoTick(): Promise<boolean> {
// Réservé de façon atomique : deux pages ouvertes en même temps ne lancent qu'une mise à jour.
return claimLock("autoTickAt", AUTO_TICK_EVERY_MS);
}
/** Durée de vie du verrou de mise à jour : au-delà, on considère qu'elle a planté en route. */
const TICK_LOCK_MS = 6 * 60_000;
/** Lance une étape et note son échec dans le journal sans arrêter les suivantes. */
async function step(log: string[], label: string, fn: () => Promise<void>) {
try {
await fn();
} catch (e) {
console.error(`[tick] ${label}`, e);
log.push(`⚠️ ${label} : ${e instanceof Error ? e.message : String(e)}`);
}
const last = (await getKv<number>("lastTickAt")) ?? 0;
if (Date.now() - last < AUTO_TICK_EVERY_MS) return false;
await setKv("lastTickAt", Date.now()); // réservé tout de suite : pas deux mises à jour en même temps
return true;
}
/**
* Appelé toutes les 30 minutes par GitHub Actions, à l'ouverture de l'app, ou à la main.
* Décide seul quoi faire selon l'heure de Paris.
* Une seule mise à jour à la fois (verrou en base), et une étape en panne n'empêche pas les autres.
*/
export async function tick(now = new Date()): Promise<string[]> {
if (!(await claimLock("tickLock", TICK_LOCK_MS))) return ["Une mise à jour est déjà en cours : rien à faire."];
const log: string[] = [];
try {
await setKv("lastTickAt", Date.now());
const settings = await getSettings();
const today = parisDate(now);
const minutes = parisMinutes(now);
await step(log, "Ordres et stops", async () => {
log.push(...(await processAll()));
});
await step(log, "Virement mensuel", () => monthlyDeposit(settings, today, log));
await step(log, "Versement simulé de l'IA", () => aiMonthlyDeposit(settings, today, log));
await monthlyDeposit(settings, today, log);
// Les actus et les idées se collectent tous les jours (week-end compris) pour que l'app ne soit jamais vide.
await step(log, "Collecte des actus", async () => {
const held = await getOpenSymbols(["real", "ai_sim"]);
const last = (await getKv<number>("lastUniverseCollect")) ?? 0;
const collectUniverse = Date.now() - last > UNIVERSE_COLLECT_EVERY_MS;
const symbols = collectUniverse ? UNIVERSE.map((s) => s.symbol) : held;
if (!symbols.length) return;
if (symbols.length) {
const n = await collectNews(symbols);
if (collectUniverse) await setKv("lastUniverseCollect", Date.now());
log.push(`${n} nouvelles actus collectées`);
});
await step(log, "Tri des actus", async () => {
}
try {
const t = await triagePending(log);
if (t) log.push(`${t} actus triées par l'IA`);
@ -81,96 +62,42 @@ export async function tick(now = new Date()): Promise<string[]> {
if (!(e instanceof AiUnavailableError)) throw e;
log.push(e.message);
}
});
await step(log, "Alertes urgentes", async () => {
log.push(...(await urgentAlerts()));
});
await step(log, "Filtre d'idées", async () => {
try {
const ideas = await refreshIdeas();
log.push(`${ideas.items.length} idée(s) repérée(s) par le filtre`);
});
await step(log, "Nettoyage", async () => {
if (!(await claimKv("lastPurge", today))) return;
const n = await purgeOldNews();
if (n) log.push(`${n} vieilles actus supprimées`);
});
} catch (e) {
log.push(`Filtre d'idées indisponible : ${e instanceof Error ? e.message : e}`);
}
// Pas de rendez-vous le week-end ni les jours fériés de Trade Republic.
if (isTradingDay(today) && minutes >= settings.rendezvousMinutes - 30 && (await getKv<string>("lastEvening")) !== today) {
await step(log, "Rendez-vous du soir", async () => {
if (!isWeekend(today)) {
const lastEvening = await getKv<string>("lastEvening");
if (lastEvening !== today && minutes >= settings.rendezvousMinutes - 30) {
log.push(...(await runEvening()));
});
}
}
await setKv("lastTickLog", { at: new Date().toISOString(), log });
return log;
} finally {
await releaseLock("tickLock").catch(() => {});
}
}
export type RunLog = { at: string; log: string[] };
/**
* Virements mensuels vers le compte-titres (supposés programmés chez ta banque).
* Les mois manqués (app pas mise à jour pendant un moment) sont rattrapés, chacun à sa date.
*/
/** Virement mensuel vers le compte-titres (supposé programmé chez ta banque). */
async function monthlyDeposit(settings: Settings, today: string, log: string[]) {
if (!settings.realDepositsStart || today < settings.realDepositsStart) return;
const dates = dueDeposits(settings.realDepositsStart, settings.realDepositDay, await getKv<string>("lastDeposit"), today);
if (!dates.length) return;
// Réservé avant d'écrire : deux mises à jour simultanées ne comptent pas deux fois le même virement.
if (!(await claimKv("lastDeposit", dates.at(-1)!.slice(0, 7)))) return;
const month = today.slice(0, 7);
if (Number(today.slice(8, 10)) < settings.realDepositDay) return;
if ((await getKv<string>("lastDeposit")) === month) return;
const db = await getDb();
const [p] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, "real"));
const amount = settings.realMonthlyDeposit;
for (const date of dates) {
await db.insert(schema.cashFlows).values({ portfolioId: "real", amount, kind: "deposit", date });
await db.insert(schema.cashFlows).values({ portfolioId: "real", amount, kind: "deposit", date: today });
await db
.update(schema.portfolios)
.set({
cash: sql`${schema.portfolios.cash} + ${amount}`,
highWaterMark: sql`${schema.portfolios.highWaterMark} + ${amount}`,
})
.set({ cash: p.cash + amount, highWaterMark: p.highWaterMark + amount })
.where(eq(schema.portfolios.id, "real"));
log.push(`Virement mensuel de ${amount} € du ${date} ajouté au compte-titres`);
}
}
/**
* La cagnotte simulée de l'IA reçoit chaque mois le même versement que ton compte-titres
* (50 € par défaut), au même jour. Comme en vrai : après quelques pertes, elle n'est pas
* bloquée pour toujours sous le minimum de 150 € par position.
* Le premier versement tombe le mois qui suit le début de la simulation.
*/
async function aiMonthlyDeposit(settings: Settings, today: string, log: string[]) {
const amount = settings.realMonthlyDeposit;
if (!(amount > 0)) return;
const dates = dueDeposits(addDays(settings.simStartDate, 1), settings.realDepositDay, await getKv<string>("lastAiDeposit"), today);
if (!dates.length) return;
if (!(await claimKv("lastAiDeposit", dates.at(-1)!.slice(0, 7)))) return;
const db = await getDb();
for (const date of dates) {
await db.insert(schema.cashFlows).values({ portfolioId: "ai_sim", amount, kind: "deposit", date });
await addCash("ai_sim", amount);
log.push(`Versement simulé de ${amount} € du ${date} ajouté à la cagnotte de l'IA`);
}
}
/**
* Remet la cagnotte de l'IA à zéro (200 € neufs) et relance la simulation : les 3 mois
* et les 20 trades exigés repartent d'aujourd'hui. Les analyses passées restent visibles.
*/
export async function resetAiSim() {
const db = await getDb();
await db.delete(schema.orders).where(eq(schema.orders.portfolioId, "ai_sim"));
await db.delete(schema.positions).where(eq(schema.positions.portfolioId, "ai_sim"));
await db.delete(schema.equitySnapshots).where(eq(schema.equitySnapshots.portfolioId, "ai_sim"));
await db.delete(schema.cashFlows).where(eq(schema.cashFlows.portfolioId, "ai_sim"));
await db
.update(schema.portfolios)
.set({ cash: SIM_INITIAL_CASH, initialCash: SIM_INITIAL_CASH, highWaterMark: SIM_INITIAL_CASH, createdAt: new Date() })
.where(eq(schema.portfolios.id, "ai_sim"));
await db.delete(schema.kv).where(eq(schema.kv.key, "lastAiDeposit"));
await updateSettings({ simStartDate: parisDate() });
await setKv("lastDeposit", month);
log.push(`Virement mensuel de ${amount} € ajouté au compte-titres`);
}
/** Alerte immédiate seulement pour un événement grave et négatif sur une action que tu détiens vraiment. */
@ -178,21 +105,11 @@ async function urgentAlerts(): Promise<string[]> {
const held = await getOpenSymbols(["real"]);
if (!held.length) return [];
const db = await getDb();
const rows = await db
.select()
.from(schema.news)
.where(
and(
isNull(schema.news.alertedAt),
isNotNull(schema.news.triagedAt),
inArray(schema.news.symbol, held),
gte(schema.news.publishedAt, new Date(Date.now() - 48 * 3_600_000)),
),
);
const rows = await db.select().from(schema.news).where(isNull(schema.news.alertedAt));
const log: string[] = [];
for (const n of rows) {
const t = n.triage;
if (!t || t.severity !== "high" || t.direction !== "negative") continue;
if (!held.includes(n.symbol) || !t || t.severity !== "high" || t.direction !== "negative") continue;
const name = findStock(n.symbol)?.name ?? n.symbol;
await sendPush(`⚠️ Alerte sur ${name}`, `${t.reason} Ton stop te protège ; regarde l'app quand tu peux.`, "/actus");
await db.update(schema.news).set({ alertedAt: new Date() }).where(eq(schema.news.id, n.id));
@ -244,24 +161,13 @@ export async function runEveningNow(): Promise<string[]> {
}
/** Le rendez-vous du soir : analyse, décisions, fiches et notification. */
export async function runEvening(opts: { manual?: boolean; force?: boolean } = {}): Promise<string[]> {
// Un seul rendez-vous en préparation à la fois (la tâche planifiée et un bouton peuvent tomber ensemble).
if (!(await claimLock("eveningLock", TICK_LOCK_MS))) return ["Un rendez-vous est déjà en préparation : patiente une minute."];
try {
return await prepareEvening(opts);
} finally {
await releaseLock("eveningLock").catch(() => {});
}
}
async function prepareEvening(opts: { manual?: boolean; force?: boolean }): Promise<string[]> {
export async function runEvening(opts: { manual?: boolean } = {}): Promise<string[]> {
const log: string[] = [];
const db = await getDb();
const today = parisDate();
const summary: string[] = [];
// Une recherche à la demande ne remplace pas le vrai rendez-vous du soir (ni sa notification).
if (opts.force) await setKv("lastEvening", today);
else if (!opts.manual && !(await claimKv("lastEvening", today))) return ["Le rendez-vous du jour est déjà prêt."];
if (!opts.manual) await setKv("lastEvening", today);
const [rdv] = await db
.insert(schema.rendezvous)
@ -273,19 +179,6 @@ async function prepareEvening(opts: { manual?: boolean; force?: boolean }): Prom
await db
.delete(schema.actions)
.where(and(eq(schema.actions.rendezvousId, rdv.id), eq(schema.actions.status, "pending"), ne(schema.actions.kind, "to_pea")));
// Les fiches des jours précédents restées sans réponse ne sont plus valables (prix périmés) :
// elles passent « expirées » au lieu de traîner. Le virement vers le PEA, lui, reste à faire.
await db
.update(schema.actions)
.set({ status: "expired" })
.where(
and(
eq(schema.actions.status, "pending"),
ne(schema.actions.rendezvousId, rdv.id),
ne(schema.actions.rendezvousId, 0),
ne(schema.actions.kind, "to_pea"),
),
);
let settings = await getSettings();
const ai = await getPortfolioState("ai_sim");
@ -311,8 +204,7 @@ async function prepareEvening(opts: { manual?: boolean; force?: boolean }): Prom
const ideas = (await getIdeas())?.items ?? [];
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 exclude = await getOpenSymbols(["ai_sim", "real"]);
const candidates = pickCandidates(news, exclude, ideas);
const results = await Promise.allSettled(candidates.map((c) => analyze(c, news, today)));
for (const r of results) {
@ -334,7 +226,7 @@ async function prepareEvening(opts: { manual?: boolean; force?: boolean }): Prom
// 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 fx = (await getFxToEur(best.currency)) ?? 1;
const earnings = await getNextEarningsDate(best.symbol);
const riskInput = (s: PortfolioState) => ({
equity: s.equity,
@ -441,11 +333,6 @@ async function prepareEvening(opts: { manual?: boolean; force?: boolean }): Prom
for (const p of aiAfter.positions) {
summary.push(`Cagnotte IA : ${p.name} ${p.pnlOpenPct >= 0 ? "+" : ""}${p.pnlOpenPct.toFixed(1)} %`);
}
if (aiSimStuck(aiAfter)) {
summary.push(
`La cagnotte de l'IA n'a plus que ${aiAfter.cash.toFixed(0)} €, sous le minimum de ${MIN_POSITION_EUR} € par position. Elle reprendra après le prochain versement de ${settings.realMonthlyDeposit} €, ou tu peux la remettre à zéro dans l'onglet IA.`,
);
}
await snapshotEquity();
const cards = await db.select().from(schema.actions).where(and(eq(schema.actions.rendezvousId, rdv.id), eq(schema.actions.status, "pending")));
@ -464,7 +351,7 @@ async function prepareEvening(opts: { manual?: boolean; force?: boolean }): Prom
async function analyze(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 }),
getQuote(c.symbol),
getBars(c.symbol, addDays(today, -45)),
getNextEarningsDate(c.symbol),
]);
@ -585,7 +472,7 @@ export function fmtShares(n: number): string {
async function reviewRealPositions(real: PortfolioState, rdvId: number, today: string) {
const db = await getDb();
const quotes = await getQuotes(real.positions.map((p) => p.symbol), { fresh: true });
const quotes = await getQuotes(real.positions.map((p) => p.symbol));
for (const p of real.positions) {
const price = quotes.get(p.symbol)?.price;
if (!price) continue;

View File

@ -1,160 +0,0 @@
import "server-only";
import { inArray, sql } from "drizzle-orm";
import { after } from "next/server";
import { getDb, schema } from "./db";
/**
* Cache des données de marché (cours, historiques, actus Yahoo) à deux étages :
* 1. la mémoire du serveur (instantané, mais perdue à chaque nouveau serveur sur Vercel),
* 2. la base de données (partagée par tous les serveurs, ~10 ms).
*
* Yahoo met 0,3 à 2 s par appel : c'est ce qui rendait chaque onglet lent à s'ouvrir.
* Désormais une page affiche tout de suite la dernière valeur connue (« stale ») et la
* rafraîchit en arrière-plan, après l'envoi de la page. Seul le moteur d'ordres exige un
* cours frais (`requireFresh`), car il décide d'exécuter ou non un ordre.
*/
export type Ttl = { freshMs: number; staleMs: number };
type Stored = { at: number; v: unknown };
const g = globalThis as unknown as { __mktMem?: Map<string, Stored>; __mktInflight?: Map<string, Promise<unknown>> };
const mem = (g.__mktMem ??= new Map());
const inflight = (g.__mktInflight ??= new Map());
const dbKey = (key: string) => `m:${key}`;
/** Lance un travail après l'envoi de la page (ou tout de suite hors d'une requête : tâche planifiée, tests). */
function inBackground(fn: () => Promise<unknown>) {
const run = () => fn().catch((e) => console.error("[market] rafraîchissement en arrière-plan", e));
try {
after(run);
} catch {
void run();
}
}
async function readDb(keys: string[]): Promise<Map<string, Stored>> {
const out = new Map<string, Stored>();
if (!keys.length) return out;
try {
const db = await getDb();
const rows = await db
.select({ key: schema.kv.key, value: schema.kv.value })
.from(schema.kv)
.where(inArray(schema.kv.key, keys.map(dbKey)));
for (const r of rows) out.set(r.key.slice(2), r.value as Stored);
} catch (e) {
console.error("[market] lecture du cache impossible", e);
}
return out;
}
async function writeDb(entries: [string, Stored][]) {
if (!entries.length) return;
try {
const db = await getDb();
await db
.insert(schema.kv)
.values(entries.map(([key, value]) => ({ key: dbKey(key), value })))
.onConflictDoUpdate({ target: schema.kv.key, set: { value: sql`excluded.value`, updatedAt: new Date() } });
} catch (e) {
console.error("[market] écriture du cache impossible", e);
}
}
function remember(key: string, v: unknown) {
const s = { at: Date.now(), v };
mem.set(key, s);
return s;
}
/** Va chercher la valeur à la source (une seule fois même si plusieurs pages la demandent en même temps). */
function refresh<T>(key: string, fetcher: () => Promise<T>): Promise<T> {
const running = inflight.get(key);
if (running) return running as Promise<T>;
const p = (async () => {
const v = await fetcher();
await writeDb([[key, remember(key, v)]]);
return v;
})().finally(() => inflight.delete(key));
inflight.set(key, p);
return p;
}
/** Une valeur, avec la logique « frais / encore utilisable / à recharger ». */
export async function cached<T>(key: string, ttl: Ttl, fetcher: () => Promise<T>, opts: { requireFresh?: boolean } = {}): Promise<T> {
const now = Date.now();
let hit = mem.get(key);
if (!hit || now - hit.at >= ttl.freshMs) {
const fromDb = (await readDb([key])).get(key);
if (fromDb && (!hit || fromDb.at > hit.at)) {
hit = fromDb;
mem.set(key, fromDb);
}
}
if (hit && now - hit.at < ttl.freshMs) return hit.v as T;
if (hit && !opts.requireFresh && now - hit.at < ttl.staleMs) {
inBackground(() => refresh(key, fetcher));
return hit.v as T;
}
return refresh(key, fetcher);
}
/**
* Plusieurs valeurs d'un coup (les cours de 92 actions) : une seule lecture en base,
* puis un seul appel à la source pour toutes celles qui manquent ou sont trop vieilles.
*/
export async function cachedMany<T>(
keys: string[],
ttl: Ttl,
fetchMany: (missing: string[]) => Promise<Map<string, T>>,
opts: { requireFresh?: boolean } = {},
): Promise<Map<string, T>> {
const now = Date.now();
const hits = new Map<string, Stored>();
const toRead: string[] = [];
for (const k of keys) {
const h = mem.get(k);
if (h) hits.set(k, h);
if (!h || now - h.at >= ttl.freshMs) toRead.push(k);
}
for (const [k, s] of await readDb(toRead)) {
const h = hits.get(k);
if (!h || s.at > h.at) {
hits.set(k, s);
mem.set(k, s);
}
}
const mustFetch: string[] = [];
const canRefreshLater: string[] = [];
for (const k of keys) {
const h = hits.get(k);
if (h && now - h.at < ttl.freshMs) continue;
if (h && !opts.requireFresh && now - h.at < ttl.staleMs) canRefreshLater.push(k);
else mustFetch.push(k);
}
const load = async (list: string[]) => {
const pending = list.filter((k) => !inflight.has(k));
if (pending.length) {
const p = (async () => {
const got = await fetchMany(pending);
await writeDb([...got].map(([k, v]) => [k, remember(k, v)] as [string, Stored]));
return got;
})().finally(() => pending.forEach((k) => inflight.delete(k)));
pending.forEach((k) => inflight.set(k, p));
}
await Promise.all(list.map((k) => inflight.get(k)).filter(Boolean)).catch(() => {});
};
if (canRefreshLater.length) inBackground(() => load(canRefreshLater));
if (mustFetch.length) await load(mustFetch);
const out = new Map<string, T>();
for (const k of keys) {
const h = mem.get(k) ?? hits.get(k);
if (h) out.set(k, h.v as T);
}
return out;
}

View File

@ -1,7 +1,6 @@
import "server-only";
import YahooFinance from "yahoo-finance2";
import type { Bar } from "./engine/fills";
import { cached, cachedMany, type Ttl } from "./market-cache";
import { addDays, parisDate } from "./time";
import { findStock } from "./universe";
@ -16,23 +15,34 @@ export type Quote = {
changePct: number | null;
};
/**
* `fresh` : exiger un cours de moins d'une minute (exécution d'ordres, stops, achat).
* Sans `fresh`, une page peut afficher un cours de moins de 6 h, rafraîchi en arrière-plan.
*/
export type MarketOpts = { fresh?: boolean };
const SUPPORTED_CURRENCIES = new Set(["EUR", "USD"]);
// Durées de vie : « frais » = servi tel quel ; « encore utilisable » = affiché puis rafraîchi en arrière-plan.
const QUOTE_TTL: Ttl = { freshMs: 60_000, staleMs: 6 * 3_600_000 };
const BARS_TTL: Ttl = { freshMs: 15 * 60_000, staleMs: 3 * 86_400_000 };
const EARNINGS_TTL: Ttl = { freshMs: 12 * 3_600_000, staleMs: 7 * 86_400_000 };
const NEWS_TTL: Ttl = { freshMs: 10 * 60_000, staleMs: 6 * 3_600_000 };
const SEARCH_TTL: Ttl = { freshMs: 24 * 3_600_000, staleMs: 7 * 86_400_000 };
// ---------------------------------------------------------------------------
// Cache mémoire partagé par toutes les requêtes du serveur.
// Yahoo est lent (0,3 à 2 s par appel) : sans cache, chaque page en enchaînait une dizaine.
// Les appels identiques en cours sont aussi mutualisés (une seule requête pour 3 demandes simultanées).
// ---------------------------------------------------------------------------
async function fetchQuotes(symbols: string[]): Promise<Map<string, Quote>> {
const out = new Map<string, Quote>();
type Entry = { at: number; value: Promise<unknown> };
const g = globalThis as unknown as { __marketCache?: Map<string, Entry> };
const cache = (g.__marketCache ??= new Map());
function memo<T>(key: string, ttlMs: number, fn: () => Promise<T>): Promise<T> {
const hit = cache.get(key);
if (hit && Date.now() - hit.at < ttlMs) return hit.value as Promise<T>;
const value = fn().catch((err) => {
cache.delete(key); // une erreur n'est jamais gardée en cache
throw err;
});
cache.set(key, { at: Date.now(), value });
return value;
}
const QUOTE_TTL_MS = 60_000;
const quoteCache = new Map<string, { at: number; quote: Quote }>();
const inflightQuotes = new Map<string, Promise<void>>();
async function fetchQuotes(symbols: string[]): Promise<void> {
// Yahoo accepte de gros paquets ; on découpe par 50 par prudence.
for (let i = 0; i < symbols.length; i += 50) {
const chunk = symbols.slice(i, i + 50);
@ -45,43 +55,49 @@ async function fetchQuotes(symbols: string[]): Promise<Map<string, Quote>> {
}
for (const r of rows) {
if (r.regularMarketPrice == null || !r.currency) continue;
out.set(r.symbol, {
quoteCache.set(r.symbol, {
at: Date.now(),
quote: {
symbol: r.symbol,
name: findStock(r.symbol)?.name ?? r.longName ?? r.shortName ?? r.symbol,
price: r.regularMarketPrice,
currency: r.currency,
changePct: r.regularMarketChangePercent ?? null,
},
});
}
}
return out;
}
export async function getQuotes(symbols: string[], opts: MarketOpts = {}): Promise<Map<string, Quote>> {
export async function getQuotes(symbols: string[]): Promise<Map<string, Quote>> {
const unique = [...new Set(symbols)];
const byKey = await cachedMany(
unique.map((s) => `q:${s}`),
QUOTE_TTL,
async (keys) => {
const got = await fetchQuotes(keys.map((k) => k.slice(2)));
return new Map([...got].map(([s, q]) => [`q:${s}`, q]));
},
{ requireFresh: opts.fresh },
);
const fresh = (s: string) => {
const hit = quoteCache.get(s);
return hit && Date.now() - hit.at < QUOTE_TTL_MS;
};
const missing = unique.filter((s) => !fresh(s) && !inflightQuotes.has(s));
if (missing.length) {
const p = fetchQuotes(missing).finally(() => missing.forEach((s) => inflightQuotes.delete(s)));
missing.forEach((s) => inflightQuotes.set(s, p));
}
await Promise.all(unique.map((s) => inflightQuotes.get(s)).filter(Boolean));
const out = new Map<string, Quote>();
for (const [k, q] of byKey) out.set(k.slice(2), q as Quote);
for (const s of unique) {
const hit = quoteCache.get(s);
if (hit) out.set(s, hit.quote);
}
return out;
}
export async function getQuote(symbol: string, opts: MarketOpts = {}): Promise<Quote | null> {
return (await getQuotes([symbol], opts)).get(symbol) ?? null;
export async function getQuote(symbol: string): Promise<Quote | null> {
return (await getQuotes([symbol])).get(symbol) ?? null;
}
/** Taux de conversion vers l'euro : 1 unité de `currency` = n €. Null si devise non gérée. */
export async function getFxToEur(currency: string, opts: MarketOpts = {}): Promise<number | null> {
export async function getFxToEur(currency: string): Promise<number | null> {
if (currency === "EUR") return 1;
if (currency !== "USD") return null;
const q = await getQuote("EURUSD=X", opts);
const q = await getQuote("EURUSD=X");
return q ? 1 / q.price : null;
}
@ -89,70 +105,75 @@ export function isSupportedCurrency(currency: string): boolean {
return SUPPORTED_CURRENCIES.has(currency);
}
type StoredBars = { from: string; bars: Bar[] };
/**
* Barres journalières depuis une date (incluse), datées à l'heure de Paris.
* On garde au moins 9 mois d'historique par action, puis on découpe : une seule requête
* sert le graphique, le PEA, l'indice et le moteur. Les jours passés ne changent plus,
* donc un historique de la veille reste utilisable (le cours du jour vient de getQuote).
* On télécharge au moins 9 mois d'historique une seule fois par action (cache 15 min),
* puis on découpe : une seule requête sert le graphique, le PEA, l'indice et le moteur.
*/
const BARS_TTL_MS = 15 * 60_000;
const barsFrom = new Map<string, string>();
export async function getBars(symbol: string, fromDate: string): Promise<Bar[]> {
const minFrom = addDays(parisDate(), -270);
const from = fromDate < minFrom ? fromDate : minFrom;
const load = async (): Promise<StoredBars> => {
const known = barsFrom.get(symbol);
const from = known && known <= fromDate ? known : fromDate < minFrom ? fromDate : minFrom;
barsFrom.set(symbol, from);
const all = await memo(`bars:${symbol}:${from}`, BARS_TTL_MS, async () => {
const chart = await yf.chart(symbol, { period1: from, interval: "1d" });
const bars = chart.quotes
return chart.quotes
.filter((q) => q.open != null && q.high != null && q.low != null && q.close != null)
.map((q) => ({ date: parisDate(q.date), open: q.open!, high: q.high!, low: q.low!, close: q.close! }));
return { from, bars };
};
let stored = await cached(`bars:${symbol}`, BARS_TTL, load);
// Historique en cache trop court (ex. PEA commencé il y a plus de 9 mois) : on recharge plus loin.
if (stored.from > fromDate) stored = await cached(`bars:${symbol}`, { freshMs: 0, staleMs: 0 }, load);
return stored.bars.filter((b) => b.date >= fromDate);
.map((q) => ({
date: parisDate(q.date),
open: q.open!,
high: q.high!,
low: q.low!,
close: q.close!,
}));
});
return all.filter((b) => b.date >= fromDate);
}
/** Prochaine date de résultats trimestriels (AAAA-MM-JJ), ou null si inconnue. */
export async function getNextEarningsDate(symbol: string): Promise<string | null> {
const today = parisDate();
const dates = await cached(`earnings:${symbol}`, EARNINGS_TTL, async () => {
return memo(`earnings:${symbol}`, 12 * 3_600_000, async () => {
try {
const s = await yf.quoteSummary(symbol, { modules: ["calendarEvents"] });
return (s.calendarEvents?.earnings?.earningsDate ?? []).map((d) => parisDate(d));
const dates = s.calendarEvents?.earnings?.earningsDate ?? [];
const today = parisDate();
const next = dates.map((d) => parisDate(d)).filter((d) => d >= today).sort()[0];
return next ?? null;
} catch {
return [] as string[];
return null;
}
});
return dates.filter((d) => d >= today).sort()[0] ?? null;
}
export type RawNews = { id: string; symbol: string; title: string; publisher: string; url: string; publishedAt: Date };
/** Actus récentes d'une action. Recherche par symbole (US) ou par nom (Europe), puis filtre sur la société. */
export async function getNews(symbol: string, opts: MarketOpts = {}): Promise<RawNews[]> {
const rows = await cached(
`news:${symbol}`,
NEWS_TTL,
async () => {
export async function getNews(symbol: string): Promise<RawNews[]> {
return memo(`news:${symbol}`, 10 * 60_000, async () => {
const stock = findStock(symbol);
const query = stock?.market === "EU" ? stock.name : symbol;
const res = await yf.search(query, { newsCount: 8, quotesCount: 0 });
return res.news
.filter((n) => n.relatedTickers?.includes(symbol))
.map((n) => ({ id: n.uuid, symbol, title: n.title, publisher: n.publisher, url: n.link, publishedAt: n.providerPublishTime }));
},
{ requireFresh: opts.fresh },
);
// Les dates reviennent du cache en texte : on les retransforme en dates.
return rows.map((n) => ({ ...n, publishedAt: new Date(n.publishedAt) }));
.map((n) => ({
id: n.uuid,
symbol,
title: n.title,
publisher: n.publisher,
url: n.link,
publishedAt: n.providerPublishTime,
}));
});
}
export type SearchHit = { symbol: string; name: string; exchange: string; type: string };
/** Recherche d'actions ou d'ETF (en euros ou en dollars, les seules devises gérées). */
export async function searchInstruments(query: string): Promise<SearchHit[]> {
return cached(`search:${query.toLowerCase()}`, SEARCH_TTL, async () => {
return memo(`search:${query.toLowerCase()}`, 10 * 60_000, async () => {
const res = await yf.search(query, { quotesCount: 10, newsCount: 0 });
const hits: SearchHit[] = [];
for (const q of res.quotes) {

View File

@ -1,5 +1,5 @@
import "server-only";
import { and, desc, eq, gte, isNull, lt } from "drizzle-orm";
import { desc, eq, gte, isNull } from "drizzle-orm";
import { aiEnabled, triageNews, TriageFailedError } from "./ai";
import { getDb, schema } from "./db";
import { getNews } from "./market";
@ -36,14 +36,7 @@ export async function collectNews(symbols: string[]): Promise<number> {
export async function triagePending(log: string[] = []): Promise<number> {
if (!aiEnabled()) return 0;
const db = await getDb();
// Seulement les actus récentes, et pas plus de 150 par passage : la mise à jour reste rapide
// et une panne passagère ne fait pas exploser la facture IA d'un coup au retour.
const pending = await db
.select()
.from(schema.news)
.where(and(isNull(schema.news.triagedAt), gte(schema.news.publishedAt, new Date(Date.now() - MAX_AGE_HOURS * 3_600_000))))
.orderBy(desc(schema.news.publishedAt))
.limit(150);
const pending = await db.select().from(schema.news).where(isNull(schema.news.triagedAt));
let done = 0;
for (let i = 0; i < pending.length; i += 25) {
const batch = pending.slice(i, i + 25);
@ -82,16 +75,6 @@ export async function triagePending(log: string[] = []): Promise<number> {
return done;
}
/** Supprime les actus de plus de 30 jours : la table ne grossit plus sans fin (et les pages restent rapides). */
export async function purgeOldNews(days = 30): Promise<number> {
const db = await getDb();
const rows = await db
.delete(schema.news)
.where(lt(schema.news.publishedAt, new Date(Date.now() - days * 86_400_000)))
.returning({ id: schema.news.id });
return rows.length;
}
export type NewsRow = typeof schema.news.$inferSelect;
/** Nombre d'actus récentes par action (pour la liste des actions). */

View File

@ -1,9 +1,9 @@
import "server-only";
import { and, eq, inArray, sql } from "drizzle-orm";
import { and, eq, inArray } from "drizzle-orm";
import { getDb, schema } from "./db";
import { evaluateBuyLimit, evaluateExit, FEE_EUR, withSlippage, type Bar } from "./engine/fills";
import { getBars, getFxToEur, getQuotes, type Quote } from "./market";
import { addTradingDays, isTradeRepublicOpen, parisDate } from "./time";
import { addDays, isTradeRepublicOpen, parisDate } from "./time";
export type PortfolioId = "ai_sim" | "sandbox" | "real";
export type Position = typeof schema.positions.$inferSelect;
@ -97,7 +97,7 @@ export async function placeOrder(o: NewOrder): Promise<{ order: Order; filled: b
.values({
...o,
limitPrice: o.limitPrice ?? null,
validUntil: o.validUntil ?? (o.type === "limit" ? addTradingDays(parisDate(), 1) : null),
validUntil: o.validUntil ?? (o.type === "limit" ? addDays(parisDate(), 1) : null),
})
.returning();
const filled = await tryFillOrder(order);
@ -116,13 +116,14 @@ async function tryFillOrder(order: Order, bars?: Bar[]): Promise<boolean> {
const now = new Date();
const today = parisDate(now);
const open = isTradeRepublicOpen(now);
const quote = (await getQuotes([order.symbol], { fresh: true })).get(order.symbol) ?? null;
const fx = await getFxToEur(order.currency, { fresh: true });
const quote = (await getQuotes([order.symbol])).get(order.symbol) ?? null;
const fx = await getFxToEur(order.currency);
if (fx === null) return false;
if (order.type === "market") {
if (!open || !quote) return false;
return executeOrder(order, quote.price, fx);
await executeOrder(order, quote.price, fx);
return true;
}
if (order.side === "buy" && order.limitPrice !== null) {
const createdDate = parisDate(order.createdAt);
@ -135,54 +136,29 @@ async function tryFillOrder(order: Order, bars?: Bar[]): Promise<boolean> {
currentPrice: quote?.price ?? null,
brokerOpen: open,
});
if (res.status === "filled") return executeOrder(order, res.price, fx);
if (res.status === "filled") {
await executeOrder(order, res.price, fx);
return true;
}
if (res.status === "expired") {
const db = await getDb();
await db
.update(schema.orders)
.set({ status: "expired" })
.where(and(eq(schema.orders.id, order.id), eq(schema.orders.status, "pending")));
await db.update(schema.orders).set({ status: "expired" }).where(eq(schema.orders.id, order.id));
}
}
return false;
}
/** Change le statut d'un ordre encore en attente. Renvoie false si quelqu'un l'a déjà traité. */
async function settleOrder(orderId: number, set: Partial<Order>): Promise<boolean> {
const db = await getDb();
const rows = await db
.update(schema.orders)
.set(set)
.where(and(eq(schema.orders.id, orderId), eq(schema.orders.status, "pending")))
.returning({ id: schema.orders.id });
return rows.length > 0;
}
/** Ajoute (ou retire) des liquidités en une seule instruction : deux mises à jour simultanées ne s'écrasent pas. */
export async function addCash(portfolioId: string, amount: number) {
const db = await getDb();
await db
.update(schema.portfolios)
.set({ cash: sql`${schema.portfolios.cash} + ${amount}` })
.where(eq(schema.portfolios.id, portfolioId));
}
/**
* Exécute un ordre. L'ordre est d'abord « réservé » (en attente → exécuté) de façon atomique :
* si deux mises à jour tournent en même temps, une seule l'exécute.
*/
async function executeOrder(order: Order, rawPrice: number, fx: number): Promise<boolean> {
async function executeOrder(order: Order, rawPrice: number, fx: number) {
const db = await getDb();
const price = withSlippage(rawPrice, order.side as "buy" | "sell");
if (order.side === "buy") {
const [p] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, order.portfolioId));
const cost = order.shares * price * fx + FEE_EUR;
if (cost > p.cash + 0.01) {
await settleOrder(order.id, { status: "cancelled", note: "Pas assez de liquidités." });
return false;
await db.update(schema.orders).set({ status: "cancelled", note: "Pas assez de liquidités." }).where(eq(schema.orders.id, order.id));
return;
}
if (!(await settleOrder(order.id, { status: "filled", filledAt: new Date(), fillPrice: price }))) return false;
await addCash(p.id, -cost);
await db.update(schema.portfolios).set({ cash: p.cash - cost }).where(eq(schema.portfolios.id, p.id));
const [pos] = await db
.insert(schema.positions)
.values({
@ -201,30 +177,27 @@ async function executeOrder(order: Order, rawPrice: number, fx: number): Promise
signalId: order.signalId,
})
.returning();
await db.update(schema.orders).set({ positionId: pos.id }).where(eq(schema.orders.id, order.id));
return true;
}
if (!order.positionId) return false;
await db
.update(schema.orders)
.set({ status: "filled", filledAt: new Date(), fillPrice: price, positionId: pos.id })
.where(eq(schema.orders.id, order.id));
} else if (order.positionId) {
const [pos] = await db.select().from(schema.positions).where(eq(schema.positions.id, order.positionId));
if (!pos || pos.status !== "open") {
// Position déjà vendue (stop, objectif...) : l'ordre de vente n'a plus d'objet, il ne doit pas rester en attente.
await settleOrder(order.id, { status: "cancelled", note: "Position déjà clôturée." });
return false;
if (!pos || pos.status !== "open") return;
await closePosition(pos, rawPrice, fx, "manual");
await db.update(schema.orders).set({ status: "filled", filledAt: new Date(), fillPrice: price }).where(eq(schema.orders.id, order.id));
}
if (!(await settleOrder(order.id, { status: "filled", filledAt: new Date(), fillPrice: price }))) return false;
return closePosition(pos, rawPrice, fx, "manual");
}
/**
* Clôture une position (prix brut, glissement et frais appliqués ici).
* Atomique : une position ne peut être vendue qu'une fois. Renvoie false si elle l'était déjà.
*/
export async function closePosition(pos: Position, rawPrice: number, fx: number, reason: string, applySlippage = true): Promise<boolean> {
/** Clôture une position (prix brut, glissement et frais appliqués ici). */
export async function closePosition(pos: Position, rawPrice: number, fx: number, reason: string, applySlippage = true) {
const db = await getDb();
const price = applySlippage ? withSlippage(rawPrice, "sell") : rawPrice;
const proceeds = pos.shares * price * fx - FEE_EUR;
const cost = pos.shares * pos.entryPrice * pos.entryFx + pos.feesEur;
const closed = await db
const [p] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, pos.portfolioId));
await db.update(schema.portfolios).set({ cash: p.cash + proceeds }).where(eq(schema.portfolios.id, p.id));
await db
.update(schema.positions)
.set({
status: "closed",
@ -235,16 +208,7 @@ export async function closePosition(pos: Position, rawPrice: number, fx: number,
feesEur: pos.feesEur + FEE_EUR,
pnlEur: proceeds - cost,
})
.where(and(eq(schema.positions.id, pos.id), eq(schema.positions.status, "open")))
.returning({ id: schema.positions.id });
if (!closed.length) return false;
await addCash(pos.portfolioId, proceeds);
// Les ordres de vente encore en attente sur cette position n'ont plus d'objet.
await db
.update(schema.orders)
.set({ status: "cancelled", note: "Position déjà clôturée." })
.where(and(eq(schema.orders.positionId, pos.id), eq(schema.orders.side, "sell"), eq(schema.orders.status, "pending")));
return true;
.where(eq(schema.positions.id, pos.id));
}
export async function cancelOrder(orderId: number) {
@ -272,7 +236,7 @@ export async function processAll(): Promise<string[]> {
const now = new Date();
const today = parisDate(now);
const brokerOpen = isTradeRepublicOpen(now);
const quotes = await getQuotes(symbols, { fresh: true });
const quotes = await getQuotes(symbols);
const barsCache = new Map<string, Bar[]>();
const barsFor = async (symbol: string, from: string) => {
const key = `${symbol}:${from}`;
@ -302,7 +266,7 @@ export async function processAll(): Promise<string[]> {
brokerOpen,
});
if (!res) continue;
if (!(await closePosition(pos, res.price, fx, res.reason))) continue;
await closePosition(pos, res.price, fx, res.reason);
const label = { stop: "stop déclenché", target: "objectif atteint", time: "durée maximale atteinte" }[res.reason];
log.push(`${pos.name} vendue (${label}) — ${pos.portfolioId}`);
}

View File

@ -1,5 +1,5 @@
import "server-only";
import { eq, sql } from "drizzle-orm";
import { eq } from "drizzle-orm";
import { getDb, schema } from "./db";
import { FEE_EUR } from "./engine/fills";
import { getFxToEur, getQuote, isSupportedCurrency } from "./market";
@ -21,14 +21,11 @@ async function realPortfolio() {
/** Tu as versé de l'argent sur ton compte-titres (compte dans les versements : sert au coupe-circuit et au cliquet). */
export async function recordDeposit(amount: number, date = parisDate()) {
if (!Number.isFinite(amount) || amount === 0) throw new Error("Montant invalide.");
const db = await getDb();
const { db, p } = await realPortfolio();
await db.insert(schema.cashFlows).values({ portfolioId: "real", amount, kind: amount > 0 ? "deposit" : "withdrawal", date });
await db
.update(schema.portfolios)
.set({
cash: sql`${schema.portfolios.cash} + ${amount}`,
highWaterMark: sql`greatest(0, ${schema.portfolios.highWaterMark} + ${amount})`,
})
.set({ cash: p.cash + amount, highWaterMark: Math.max(0, p.highWaterMark + amount) })
.where(eq(schema.portfolios.id, "real"));
}
@ -58,13 +55,10 @@ export async function addHolding(input: {
if (!quote) throw new Error("Action introuvable.");
if (!isSupportedCurrency(quote.currency)) throw new Error("Seules les actions en euros ou en dollars sont gérées.");
const fx = (await getFxToEur(quote.currency)) ?? 1;
const db = await getDb();
const { db, p } = await realPortfolio();
if (input.paidFromCash) {
const cost = input.shares * input.price * fx + FEE_EUR;
await db
.update(schema.portfolios)
.set({ cash: sql`greatest(0, ${schema.portfolios.cash} - ${cost})` })
.where(eq(schema.portfolios.id, "real"));
await db.update(schema.portfolios).set({ cash: Math.max(0, p.cash - cost) }).where(eq(schema.portfolios.id, "real"));
}
await db.insert(schema.positions).values({
portfolioId: "real",

View File

@ -1,6 +1,6 @@
import "server-only";
import { cache } from "react";
import { eq, sql } from "drizzle-orm";
import { eq } from "drizzle-orm";
import { getDb, schema } from "./db";
import type { PeaPlan } from "./engine/pea";
import { parisDate } from "./time";
@ -67,48 +67,6 @@ export async function setKv(key: string, value: unknown): Promise<void> {
.onConflictDoUpdate({ target: schema.kv.key, set: { value, updatedAt: new Date() } });
}
/**
* Écrit `value` seulement si la clé n'a pas déjà cette valeur, de façon atomique.
* Renvoie true si c'est nous qui l'avons écrite : sert à faire une chose une seule fois
* (virement du mois, rendez-vous du jour) même si deux mises à jour tournent en même temps.
*/
export async function claimKv(key: string, value: unknown): Promise<boolean> {
const db = await getDb();
const rows = await db
.insert(schema.kv)
.values({ key, value })
.onConflictDoUpdate({
target: schema.kv.key,
set: { value, updatedAt: new Date() },
setWhere: sql`${schema.kv.value} is distinct from ${JSON.stringify(value)}::jsonb`,
})
.returning({ key: schema.kv.key });
return rows.length > 0;
}
/**
* Verrou atomique avec durée de vie : renvoie true si on l'a pris (personne ne l'a pris
* depuis `ttlMs`). Un verrou oublié (serveur coupé en route) expire tout seul.
*/
export async function claimLock(key: string, ttlMs: number): Promise<boolean> {
const db = await getDb();
const now = Date.now();
const rows = await db
.insert(schema.kv)
.values({ key, value: now })
.onConflictDoUpdate({
target: schema.kv.key,
set: { value: now, updatedAt: new Date() },
setWhere: sql`jsonb_typeof(${schema.kv.value}) <> 'number' or (${schema.kv.value})::text::numeric < ${now - ttlMs}`,
})
.returning({ key: schema.kv.key });
return rows.length > 0;
}
export async function releaseLock(key: string): Promise<void> {
await setKv(key, 0);
}
const g = globalThis as unknown as { __setupDone?: boolean };
/** Crée les réglages et les trois portefeuilles au premier lancement (une seule fois par serveur). */

View File

@ -2,7 +2,7 @@ import "server-only";
import { and, eq, ne } from "drizzle-orm";
import { aiSpendSince } from "./ai";
import { getDb, schema } from "./db";
import { benchmarkWithFlows, computeGate, equityWithoutDeposits, maxDrawdownPct, type Criterion, type Flow } from "./engine/gate";
import { computeGate, maxDrawdownPct, type Criterion } from "./engine/gate";
import { computePea, type PeaResult } from "./engine/pea";
import { getBars, getFxToEur, getQuote } from "./market";
import { getPortfolioState, type PortfolioState } from "./portfolio";
@ -33,34 +33,11 @@ export type GateStatus = {
aiCostEur: number;
};
/** Versements mensuels simulés reçus par la cagnotte de l'IA (comme ton vrai virement). */
export async function aiDeposits(): Promise<Flow[]> {
const db = await getDb();
const rows = await db
.select({ date: schema.cashFlows.date, amount: schema.cashFlows.amount })
.from(schema.cashFlows)
.where(and(eq(schema.cashFlows.portfolioId, "ai_sim"), eq(schema.cashFlows.kind, "deposit")));
return rows;
}
/** Performance de la cagnotte IA sur tout l'argent qu'elle a reçu (départ + versements), en %. */
export function aiPerformance(ai: PortfolioState, deposits: Flow[]) {
const contributed = ai.initialCash + deposits.reduce((s, d) => s + d.amount, 0);
return { contributed, pct: contributed > 0 ? (ai.equity / contributed - 1) * 100 : 0 };
}
/** Le S&P 500 avec les mêmes versements que la cagnotte de l'IA, aux mêmes dates. */
async function benchmarkForAi(s: Settings, initialCash: number, deposits: Flow[]): Promise<number> {
const symbol = benchmarkSymbol(s);
const [bars, quote] = await Promise.all([getBars(symbol, s.simStartDate).catch((e) => (console.error("[indice]", e), [])), getQuote(symbol)]);
return benchmarkWithFlows(bars, quote?.price ?? null, [{ date: s.simStartDate, amount: initialCash }, ...deposits]);
}
export async function getGateStatus(settings?: Settings, ai?: PortfolioState): Promise<GateStatus> {
const s = settings ?? (await getSettings());
const db = await getDb();
// Tout est lancé en parallèle : la page attend la requête la plus lente, pas leur somme.
const [aiState, closed, snaps, acts, usdToEur, spent, deposits] = await Promise.all([
const [aiState, closed, snaps, acts, usdToEur, spent, bench] = await Promise.all([
ai ?? getPortfolioState("ai_sim"),
db
.select({ id: schema.positions.id })
@ -70,24 +47,20 @@ export async function getGateStatus(settings?: Settings, ai?: PortfolioState): P
db.select({ status: schema.actions.status }).from(schema.actions).where(ne(schema.actions.kind, "to_pea")),
getFxToEur("USD").then((x) => x ?? 0.9),
aiSpendSince(s.simStartDate),
aiDeposits(),
benchmarkReturnPct(benchmarkSymbol(s), s.simStartDate),
]);
const aiCostEur = spent * usdToEur;
const perf = aiPerformance(aiState, deposits);
const bench = await benchmarkForAi(s, aiState.initialCash, deposits);
const curve = equityWithoutDeposits([...snaps, { date: parisDate(), equity: aiState.equity }], deposits);
const gate = computeGate({
simDays: daysBetween(s.simStartDate, parisDate()),
closedTrades: closed.length,
aiReturnPct: perf.pct,
aiReturnPct: (aiState.equity / aiState.initialCash - 1) * 100,
aiCostEur,
initialCash: perf.contributed,
initialCash: aiState.initialCash,
benchmarkReturnPct: bench,
maxDrawdownPct: maxDrawdownPct(curve),
maxDrawdownPct: maxDrawdownPct([...snaps.sort((a, b) => a.date.localeCompare(b.date)).map((x) => x.equity), aiState.equity]),
actionsTotal: acts.length,
// « Expirée » = fiche restée sans réponse : elle ne compte pas comme suivie.
actionsAnswered: acts.filter((a) => a.status === "done" || a.status === "skipped").length,
actionsAnswered: acts.filter((a) => a.status !== "pending").length,
});
return {
unlocked: gate.unlocked,
@ -101,10 +74,9 @@ export async function getGateStatus(settings?: Settings, ai?: PortfolioState): P
export type Leaderboard = { label: string; pct: number; detail: string }[];
export async function getLeaderboard(settings: Settings, ai: PortfolioState, sandbox: PortfolioState): Promise<Leaderboard> {
const [bench, deposits] = await Promise.all([benchmarkReturnPct(benchmarkSymbol(settings), settings.simStartDate), aiDeposits()]);
const perf = aiPerformance(ai, deposits);
const bench = await benchmarkReturnPct(benchmarkSymbol(settings), settings.simStartDate);
const rows = [
{ label: "L'IA", pct: perf.pct, detail: eur(ai.equity) },
{ label: "L'IA", pct: (ai.equity / ai.initialCash - 1) * 100, detail: eur(ai.equity) },
{ label: "Toi", pct: (sandbox.equity / sandbox.initialCash - 1) * 100, detail: eur(sandbox.equity) },
{ label: "S&P 500", pct: bench, detail: "sans rien faire" },
];

View File

@ -40,82 +40,26 @@ export function addDays(date: string, n: number): string {
return d.toISOString().slice(0, 10);
}
/** Dimanche de Pâques (algorithme grégorien anonyme), au format AAAA-MM-JJ. */
export function easterSunday(year: number): string {
const a = year % 19;
const b = Math.floor(year / 100);
const c = year % 100;
const d = Math.floor(b / 4);
const e = b % 4;
const f = Math.floor((b + 8) / 25);
const g = Math.floor((b - f + 1) / 3);
const h = (19 * a + b - d - g + 15) % 30;
const i = Math.floor(c / 4);
const k = c % 4;
const l = (32 + 2 * e + 2 * i - h - k) % 7;
const m = Math.floor((a + 11 * h + 22 * l) / 451);
const month = Math.floor((h + l - 7 * m + 114) / 31);
const day = ((h + l - 7 * m + 114) % 31) + 1;
return `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
}
/**
* Jours fériés où Trade Republic (LS Exchange) ne cote pas : 1er janvier, Vendredi saint,
* lundi de Pâques, 24, 25, 26 et 31 décembre.
*/
export function isTradeRepublicHoliday(date: string): boolean {
if (["01-01", "12-24", "12-25", "12-26", "12-31"].includes(date.slice(5))) return true;
const easter = easterSunday(Number(date.slice(0, 4)));
return date === addDays(easter, -2) || date === addDays(easter, 1);
}
/** Jour où l'on peut passer des ordres chez Trade Republic. */
export function isTradingDay(date: string): boolean {
return !isWeekend(date) && !isTradeRepublicHoliday(date);
}
/** Ajoute n jours de bourse (hors week-ends et jours fériés de Trade Republic). */
/** Ajoute n jours de bourse (lundi-vendredi ; les jours fériés sont ignorés). */
export function addTradingDays(date: string, n: number): string {
let d = date;
let left = n;
while (left > 0) {
d = addDays(d, 1);
if (isTradingDay(d)) left--;
if (!isWeekend(d)) left--;
}
return d;
}
/**
* Dates des virements mensuels dus et pas encore comptés : un par mois, à partir du mois qui
* suit `lastMonth` (AAAA-MM, ou null) jusqu'à aujourd'hui, jamais avant `start`.
* Rattrape les mois où l'app ne s'est pas mise à jour : aucun virement n'est oublié.
*/
export function dueDeposits(start: string, day: number, lastMonth: string | null, today: string): string[] {
const out: string[] = [];
let [y, m] = start.split("-").map(Number);
for (let guard = 0; guard < 600; guard++) {
const month = `${y}-${String(m).padStart(2, "0")}`;
const date = `${month}-${String(day).padStart(2, "0")}`;
if (date > today) break;
if (date >= start && (!lastMonth || month > lastMonth)) out.push(date);
m++;
if (m > 12) {
m = 1;
y++;
}
}
return out;
}
export function daysBetween(from: string, to: string): number {
return Math.round(
(new Date(`${to}T12:00:00Z`).getTime() - new Date(`${from}T12:00:00Z`).getTime()) / 86_400_000,
);
}
/** Trade Republic (LS Exchange) : du lundi au vendredi hors jours fériés, de 7h30 à 23h00, heure de Paris. */
/** Trade Republic (LS Exchange) : du lundi au vendredi, de 7h30 à 23h00, heure de Paris. */
export function isTradeRepublicOpen(d: Date = new Date()): boolean {
if (!isTradingDay(parisDate(d))) return false;
if (isWeekend(parisDate(d))) return false;
const m = parisMinutes(d);
return m >= 7 * 60 + 30 && m < 23 * 60;
}