diff --git a/README.md b/README.md
index f79ccf1..f61f51e 100644
--- a/README.md
+++ b/README.md
@@ -9,6 +9,19 @@ App web (installable sur iPhone) qui t'aide à investir 100 €/mois :
> Outil d'aide à la décision, pas un conseil en investissement. La majorité des traders particuliers perdent de l'argent ; l'app est conçue pour le mesurer honnêtement.
+**Les onglets** :
+- **Accueil** : ce qu'il y a à faire (fiches du rendez-vous), bouton « Chercher des idées maintenant », patrimoine, classement.
+- **Actions** : toutes les actions suivies avec leur cours ; une fiche par action (graphique, actus, avis de l'IA, achat dans le bac à sable par montant en € ou en nombre d'actions).
+- **Bac à sable** : ta cagnotte virtuelle de 200 €.
+- **IA** : la cagnotte et les analyses de l'IA.
+- **Mon compte** : ton compte Trade Republic. Trade Republic n'a pas d'API : tu déclares tes versements, tes liquidités, les actions que tu détiens et ton plan PEA, l'app tient les comptes. Aucun identifiant n'est jamais demandé.
+
+**Achats par montant** : comme Trade Republic, l'app achète des fractions d'actions (« Montant : 150 € »). Même avec 200 €, toutes les grandes actions sont accessibles.
+
+**Sans clé Anthropic**, l'app fonctionne quand même : un filtre simple (repli dans une tendance haussière) repère des idées à tester dans le bac à sable. Avec la clé, ces idées servent aussi de candidates à l'IA.
+
+**Mise à jour automatique** : à chaque ouverture de l'app (au plus toutes les 20 minutes), ordres, stops, actus et idées se mettent à jour en arrière-plan. La tâche GitHub Actions reste utile pour le rendez-vous du soir et les notifications quand l'app est fermée.
+
---
## Lancer l'app sur ton Mac
diff --git a/drizzle/0001_friendly_bloodscream.sql b/drizzle/0001_friendly_bloodscream.sql
new file mode 100644
index 0000000..56a292c
--- /dev/null
+++ b/drizzle/0001_friendly_bloodscream.sql
@@ -0,0 +1,2 @@
+ALTER TABLE "orders" ALTER COLUMN "shares" SET DATA TYPE double precision;--> statement-breakpoint
+ALTER TABLE "positions" ALTER COLUMN "shares" SET DATA TYPE double precision;
\ No newline at end of file
diff --git a/drizzle/meta/0001_snapshot.json b/drizzle/meta/0001_snapshot.json
new file mode 100644
index 0000000..d3e8cf9
--- /dev/null
+++ b/drizzle/meta/0001_snapshot.json
@@ -0,0 +1,881 @@
+{
+ "id": "44ea687c-f514-404a-be73-0f8f65cca593",
+ "prevId": "4dbfbae0-5e55-4b56-8cc8-1bce887ea407",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.actions": {
+ "name": "actions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "rendezvous_id": {
+ "name": "rendezvous_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "training": {
+ "name": "training",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "symbol": {
+ "name": "symbol",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "responded_at": {
+ "name": "responded_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.ai_usage": {
+ "name": "ai_usage",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "at": {
+ "name": "at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "model": {
+ "name": "model",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "purpose": {
+ "name": "purpose",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "input_tokens": {
+ "name": "input_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "output_tokens": {
+ "name": "output_tokens",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "cost_usd": {
+ "name": "cost_usd",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.cash_flows": {
+ "name": "cash_flows",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "portfolio_id": {
+ "name": "portfolio_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "amount": {
+ "name": "amount",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "date": {
+ "name": "date",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.equity_snapshots": {
+ "name": "equity_snapshots",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "portfolio_id": {
+ "name": "portfolio_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "date": {
+ "name": "date",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "equity": {
+ "name": "equity",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "equity_portfolio_date_idx": {
+ "name": "equity_portfolio_date_idx",
+ "columns": [
+ {
+ "expression": "portfolio_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "date",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.kv": {
+ "name": "kv",
+ "schema": "",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.news": {
+ "name": "news",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "symbol": {
+ "name": "symbol",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "publisher": {
+ "name": "publisher",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "published_at": {
+ "name": "published_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "triage": {
+ "name": "triage",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "triaged_at": {
+ "name": "triaged_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "alerted_at": {
+ "name": "alerted_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.orders": {
+ "name": "orders",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "portfolio_id": {
+ "name": "portfolio_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "symbol": {
+ "name": "symbol",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "currency": {
+ "name": "currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "side": {
+ "name": "side",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "limit_price": {
+ "name": "limit_price",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "shares": {
+ "name": "shares",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stop_price": {
+ "name": "stop_price",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "target_price": {
+ "name": "target_price",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "max_exit_date": {
+ "name": "max_exit_date",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "position_id": {
+ "name": "position_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "signal_id": {
+ "name": "signal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'pending'"
+ },
+ "valid_until": {
+ "name": "valid_until",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "filled_at": {
+ "name": "filled_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "fill_price": {
+ "name": "fill_price",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "note": {
+ "name": "note",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.portfolios": {
+ "name": "portfolios",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "initial_cash": {
+ "name": "initial_cash",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "cash": {
+ "name": "cash",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "high_water_mark": {
+ "name": "high_water_mark",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.positions": {
+ "name": "positions",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "portfolio_id": {
+ "name": "portfolio_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "symbol": {
+ "name": "symbol",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "currency": {
+ "name": "currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "shares": {
+ "name": "shares",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "entry_price": {
+ "name": "entry_price",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "entry_fx": {
+ "name": "entry_fx",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "opened_at": {
+ "name": "opened_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stop_price": {
+ "name": "stop_price",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "target_price": {
+ "name": "target_price",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "max_exit_date": {
+ "name": "max_exit_date",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'open'"
+ },
+ "closed_at": {
+ "name": "closed_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "exit_price": {
+ "name": "exit_price",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "exit_fx": {
+ "name": "exit_fx",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "exit_reason": {
+ "name": "exit_reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "fees_eur": {
+ "name": "fees_eur",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "pnl_eur": {
+ "name": "pnl_eur",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "signal_id": {
+ "name": "signal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.push_subscriptions": {
+ "name": "push_subscriptions",
+ "schema": "",
+ "columns": {
+ "endpoint": {
+ "name": "endpoint",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "keys": {
+ "name": "keys",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.rendezvous": {
+ "name": "rendezvous",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "date": {
+ "name": "date",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "notified_at": {
+ "name": "notified_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "rendezvous_date_idx": {
+ "name": "rendezvous_date_idx",
+ "columns": [
+ {
+ "expression": "date",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.signals": {
+ "name": "signals",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "date": {
+ "name": "date",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "symbol": {
+ "name": "symbol",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "decision": {
+ "name": "decision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "confidence": {
+ "name": "confidence",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "thesis": {
+ "name": "thesis",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "risks": {
+ "name": "risks",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expected_move_pct": {
+ "name": "expected_move_pct",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "stop_pct": {
+ "name": "stop_pct",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "target_pct": {
+ "name": "target_pct",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "horizon_days": {
+ "name": "horizon_days",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "price_at_signal": {
+ "name": "price_at_signal",
+ "type": "double precision",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "currency": {
+ "name": "currency",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "news_ids": {
+ "name": "news_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "risk_verdict": {
+ "name": "risk_verdict",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {},
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json
index 7ff96e6..42a2a22 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -8,6 +8,13 @@
"when": 1791720025887,
"tag": "0000_init",
"breakpoints": true
+ },
+ {
+ "idx": 1,
+ "version": "7",
+ "when": 1794851302883,
+ "tag": "0001_friendly_bloodscream",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/src/app/(app)/actions/[symbol]/page.tsx b/src/app/(app)/actions/[symbol]/page.tsx
new file mode 100644
index 0000000..b3aec9a
--- /dev/null
+++ b/src/app/(app)/actions/[symbol]/page.tsx
@@ -0,0 +1,146 @@
+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, Empty, Page } from "@/components/ui";
+import { aiEnabled, getAiSpend } from "@/lib/ai";
+import { getDb, schema } from "@/lib/db";
+import { pct, price, timeAgo } from "@/lib/format";
+import { getBars, getFxToEur, getNews, getNextEarningsDate, getQuote, isSupportedCurrency } from "@/lib/market";
+import { getPortfolioState } from "@/lib/portfolio";
+import { getSettings } from "@/lib/settings";
+import { addDays, formatDateFr, parisDate } from "@/lib/time";
+import { findStock } from "@/lib/universe";
+
+type Props = PageProps<"/actions/[symbol]">;
+
+function numParam(v: string | string[] | undefined): number | undefined {
+ const n = Number(Array.isArray(v) ? v[0] : v);
+ return Number.isFinite(n) && n > 0 ? n : undefined;
+}
+
+async function StockContent({ params, searchParams }: Props) {
+ await connection();
+ const symbol = decodeURIComponent((await params).symbol);
+ const sp = await searchParams;
+ const quote = await getQuote(symbol);
+ if (!quote) notFound();
+
+ const db = await getDb();
+ const [bars, fx, earnings, sandbox, spend, settings, signals, dbNews] = await Promise.all([
+ getBars(symbol, addDays(parisDate(), -95)).catch(() => []),
+ getFxToEur(quote.currency),
+ getNextEarningsDate(symbol),
+ getPortfolioState("sandbox"),
+ getAiSpend(),
+ getSettings(),
+ db.select().from(schema.signals).where(eq(schema.signals.symbol, symbol)).orderBy(desc(schema.signals.createdAt)).limit(1),
+ db.select().from(schema.news).where(and(eq(schema.news.symbol, symbol))).orderBy(desc(schema.news.publishedAt)).limit(8),
+ ]);
+ const news = dbNews.length ? dbNews : (await getNews(symbol).catch(() => [])).map((n) => ({ ...n, triage: null }));
+ const held = sandbox.positions.filter((p) => p.symbol === symbol);
+ const signal = signals[0];
+ const first = bars[0]?.close;
+ const change3m = first ? (quote.price / first - 1) * 100 : null;
+ const supported = isSupportedCurrency(quote.currency) && fx !== null;
+ const stock = findStock(symbol);
+
+ return (
+
+ ‹ Actions
+
+ }
+ >
+
+
+
{price(quote.price, quote.currency)}
+
+ {quote.changePct !== null &&
= 0 ? "text-accent" : "text-danger"}`}>{pct(quote.changePct, 2)} auj.
}
+ {change3m !== null &&
= 0 ? "text-accent" : "text-danger"}`}>{pct(change3m)} sur 3 mois
}
+
+
+ {quote.currency === "USD" && fx && ≈ {(quote.price * fx).toFixed(2)} € chez Trade Republic
}
+
+
+
+ {earnings && 📅 Prochains résultats : {formatDateFr(earnings)}
}
+
+
+ {held.length > 0 && (
+
+
+
+ )}
+
+ {signal && (
+
+
+ {signal.decision === "buy" ? "Achat" : "On passe"} {" "}
+ confiance {signal.confidence} %
+
+ {signal.thesis}
+ ⚠️ {signal.risks}
+
+ )}
+
+ {supported ? (
+
+ ) : (
+
+ Cette action est cotée en {quote.currency} : seules les actions en euros ou en dollars sont gérées.
+
+ )}
+
+
+ {!news.length && Pas d'actu récente. }
+
+
+
+ );
+}
+
+export default function StockPage(props: Props) {
+ return (
+
+
+
+
+ }
+ >
+
+
+ );
+}
diff --git a/src/app/(app)/actions/page.tsx b/src/app/(app)/actions/page.tsx
new file mode 100644
index 0000000..a80f300
--- /dev/null
+++ b/src/app/(app)/actions/page.tsx
@@ -0,0 +1,75 @@
+import { Suspense } from "react";
+import Link from "next/link";
+import { connection } from "next/server";
+import { StockBrowser, type StockRow } from "@/components/stock-browser";
+import { Card, CardSkeleton, Empty, Page } from "@/components/ui";
+import { pct } from "@/lib/format";
+import { getIdeas } from "@/lib/ideas";
+import { getQuotes } from "@/lib/market";
+import { newsCounts } from "@/lib/news";
+import { getOpenSymbols } from "@/lib/portfolio";
+import { UNIVERSE } from "@/lib/universe";
+
+async function Ideas() {
+ await connection();
+ const ideas = await getIdeas();
+ const items = ideas?.items.slice(0, 4) ?? [];
+ return (
+ filtre sans IA}>
+ {!items.length && Les idées se calculent à l'ouverture de l'app : reviens dans une minute. }
+
+ {items.map((i) => (
+
+
+
+ {i.name}
+ {pct(i.pullbackPct)} sur 5 j
+
+ {i.reason}
+
+
+ ))}
+
+
+ );
+}
+
+async function Market() {
+ await connection();
+ const [quotes, newsCount, held] = await Promise.all([getQuotes(UNIVERSE.map((s) => s.symbol)), newsCounts(48), getOpenSymbols(["sandbox", "real"])]);
+ const rows: StockRow[] = UNIVERSE.map((s) => {
+ const q = quotes.get(s.symbol);
+ return {
+ symbol: s.symbol,
+ name: s.name,
+ market: s.market,
+ price: q?.price ?? null,
+ currency: q?.currency ?? (s.market === "US" ? "USD" : "EUR"),
+ changePct: q?.changePct ?? null,
+ news: newsCount.get(s.symbol) ?? 0,
+ held: held.includes(s.symbol),
+ };
+ });
+ return ;
+}
+
+export default function ActionsPage() {
+ return (
+
+ 📰 Actus
+
+ }
+ >
+ }>
+
+
+ }>
+
+
+
+ );
+}
diff --git a/src/app/(app)/bac-a-sable/page.tsx b/src/app/(app)/bac-a-sable/page.tsx
index c9cdffc..9b971f8 100644
--- a/src/app/(app)/bac-a-sable/page.tsx
+++ b/src/app/(app)/bac-a-sable/page.tsx
@@ -1,58 +1,64 @@
import { Suspense } from "react";
+import Link from "next/link";
import { connection } from "next/server";
-import { PageSkeleton } from "@/components/page-skeleton";
-import { SandboxTrader } from "@/components/sandbox-trader";
-import { PositionList, ClosedList, PendingOrders } from "@/components/positions";
-import { Card, Page } from "@/components/ui";
-import { eur, pct } from "@/lib/format";
-import { getClosedPositions, getPortfolioState } from "@/lib/portfolio";
-import { getAiSpend } from "@/lib/ai";
-import { getSettings } from "@/lib/settings";
+import { ClosedList, PendingOrders, PositionList } from "@/components/positions";
import { ResetSandbox } from "@/components/reset-sandbox";
+import { Card, CardSkeleton, Delta, Page, primaryBtn, Stat } from "@/components/ui";
+import { eur, pct, signedEur } from "@/lib/format";
+import { getClosedPositions, getPortfolioState } from "@/lib/portfolio";
+import { isTradeRepublicOpen } from "@/lib/time";
-
-async function SandboxPageContent() {
+async function SandboxContent() {
await connection();
- const [state, closed, spend, settings] = await Promise.all([
- getPortfolioState("sandbox"),
- getClosedPositions("sandbox"),
- getAiSpend(),
- getSettings(),
- ]);
+ const [state, closed] = await Promise.all([getPortfolioState("sandbox"), getClosedPositions("sandbox")]);
const perf = (state.equity / state.initialCash - 1) * 100;
+ const realized = closed.reduce((s, p) => s + (p.pnlEur ?? 0), 0);
+ const wins = closed.filter((p) => (p.pnlEur ?? 0) > 0).length;
return (
-
+ <>
{eur(state.equity)}
-
= 0 ? "text-accent" : "text-danger"}`}>{pct(perf)}
+
{pct(perf)}
- Liquidités : {eur(state.cash)}
+
+ {eur(state.cash, 0)}
+ {signedEur(realized)}
+ {closed.length ? `${wins}/${closed.length}` : "—"}
+
+
+ + Acheter une action
+
+ {!isTradeRepublicOpen() && (
+ Trade Republic est fermé (7h30-23h en semaine) : tes ordres s'exécuteront à la réouverture, comme en vrai.
+ )}
-
-
-
-
-
{state.pendingOrders.length > 0 && (
)}
+
+
+
+
+
-
+ >
);
}
export default function SandboxPage() {
return (
- }>
-
-
+
+ }>
+
+
+
);
}
diff --git a/src/app/(app)/layout.tsx b/src/app/(app)/layout.tsx
index e156f3f..1d7f817 100644
--- a/src/app/(app)/layout.tsx
+++ b/src/app/(app)/layout.tsx
@@ -1,10 +1,19 @@
-import { Nav } from "@/components/nav";
+import { Suspense } from "react";
+import { AutoTick } from "@/components/auto-tick";
+import { Nav, NavBar } from "@/components/nav";
+
+export const maxDuration = 300;
export default function AppLayout({ children }: LayoutProps<"/">) {
return (
<>
{children}
-
+ }>
+
+
+
+
+
>
);
}
diff --git a/src/app/(app)/page.tsx b/src/app/(app)/page.tsx
index a49ca28..a83c00a 100644
--- a/src/app/(app)/page.tsx
+++ b/src/app/(app)/page.tsx
@@ -1,75 +1,129 @@
import { Suspense } from "react";
-import { connection } from "next/server";
-import { PageSkeleton } from "@/components/page-skeleton";
import Link from "next/link";
+import { connection } from "next/server";
import { ActionCard } from "@/components/action-card";
-import { Badge, Card, Delta, Empty, Page } from "@/components/ui";
+import { FindIdeas } from "@/components/find-ideas";
+import { SettingsLink } from "@/components/nav";
+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";
+import { getIdeas } from "@/lib/ideas";
import { getPortfolioState } from "@/lib/portfolio";
import { getSettings } from "@/lib/settings";
import { getGateStatus, getLeaderboard, getPea } from "@/lib/stats";
import { formatDateFr, parisDate } from "@/lib/time";
+function hhmm(minutes: number) {
+ return `${String(Math.floor(minutes / 60)).padStart(2, "0")}h${String(minutes % 60).padStart(2, "0")}`;
+}
-async function HomeContent() {
+/** Ce que tu as à faire : seulement la base de données, donc instantané. */
+async function Todo() {
await connection();
- const settings = await getSettings();
- const [ai, sandbox, real, rdv, adhoc, spend] = await Promise.all([
- getPortfolioState("ai_sim"),
- getPortfolioState("sandbox"),
- getPortfolioState("real"),
- getLatestRendezvous(),
- getPendingAdhocCards(),
- getAiSpend(),
- ]);
- const [pea, gate, board] = await Promise.all([getPea(settings), getGateStatus(settings, ai), getLeaderboard(settings, ai, sandbox)]);
-
- const total = (pea?.value ?? 0) + real.equity;
- const hh = String(Math.floor(settings.rendezvousMinutes / 60)).padStart(2, "0");
- const mm = String(settings.rendezvousMinutes % 60).padStart(2, "0");
+ const [settings, rdv, adhoc, ideas] = await Promise.all([getSettings(), getLatestRendezvous(), getPendingAdhocCards(), getIdeas()]);
const isToday = rdv?.date === parisDate();
- const metCount = gate.criteria.filter((c) => c.ok).length;
+ const cards = [...(rdv?.cards ?? []), ...adhoc];
+ const pending = cards.filter((c) => c.status === "pending");
+ const shown = isToday ? cards : pending;
return (
-
-
- {eur(total)}
-
-
-
PEA · cœur
-
{eur(pea?.value ?? 0)}
- {pea && pea.invested > 0 ? (
-
- {signedEur(pea.gain)} sur {eur(pea.invested, 0)} versés
-
- ) : (
-
Premier achat à venir
- )}
-
-
-
Compte-titres · satellite
-
{eur(real.equity)}
-
{gate.realActive ? `${real.positions.length} position(s)` : "Cagnotte en attente ›"}
+ <>
+ {!settings.trAccountOpenedAt && (
+
+
+ Indique à l'app où en est ton compte Trade Republic (versements, PEA, actions déjà achetées). Ça prend 1 minute, et aucun identifiant n'est demandé.
+
+
+ Configurer mon compte
-
-
+
+ )}
c.status === "pending") ? "accent" : undefined}
+ title={rdv ? `Rendez-vous · ${isToday ? "aujourd'hui" : formatDateFr(rdv.date)}` : "Rendez-vous du soir"}
+ tone={pending.length ? "accent" : undefined}
+ action={pending.length ? {pending.length} à traiter : undefined}
>
- {!rdv && Ton premier rendez-vous arrivera ce soir à {hh}h{mm}. L'IA prépare tout pendant la journée. }
- {rdv?.summary && {rdv.summary}
}
+ {rdv?.summary && isToday && {rdv.summary}
}
+ {!shown.length && (
+
+ Rien à faire pour l'instant. Ton prochain rendez-vous arrive à {hhmm(settings.rendezvousMinutes)} (en semaine), ou lance une recherche tout de suite.
+
+ )}
- {[...(rdv?.cards ?? []), ...adhoc].map((c) => (
-
+ {shown.map((c) => (
+
))}
+
+
+
- Détails}>
+ {!pending.length && ideas && ideas.items.length > 0 && (
+ Toutes les actions}>
+
+ {ideas.items.slice(0, 3).map((i) => (
+
+
+ {i.name}
+
+ tendance +{i.trendPct} % · repli {i.pullbackPct} %
+
+
+
+ ))}
+
+ Repérées par une règle simple (sans IA). À essayer dans ton bac à sable.
+
+ )}
+ >
+ );
+}
+
+/** 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 (
+
+ {eur(total)}
+
+
+
PEA · cœur
+
{eur(pea?.value ?? 0)}
+ {pea && pea.invested > 0 ? (
+
+ {signedEur(pea.gain)} sur {eur(pea.invested, 0)}
+
+ ) : (
+
{settings.peaPlan ? "Premier achat à venir" : "Pas encore configuré ›"}
+ )}
+
+
+
Compte-titres
+
{eur(real.equity)}
+
{real.positions.length ? `${real.positions.length} position(s)` : `${eur(real.cash, 0)} en liquidités ›`}
+
+
+
+ );
+}
+
+/** Classement et critères du mode réel : dépendent de l'indice S&P 500. */
+async function Progress() {
+ await connection();
+ const settings = await getSettings();
+ const [ai, sandbox, spend] = await Promise.all([getPortfolioState("ai_sim"), getPortfolioState("sandbox"), getAiSpend()]);
+ const [gate, board] = await Promise.all([getGateStatus(settings, ai), getLeaderboard(settings, ai, sandbox)]);
+ const met = gate.criteria.filter((c) => c.ok).length;
+
+ return (
+ <>
+ Détails}>
{board.map((row, i) => (
@@ -84,23 +138,26 @@ async function HomeContent() {
L'IA et toi partez chacun de 200 € virtuels. Le S&P 500, c'est ce que tu aurais gagné sans rien faire.
- Débloqué : {metCount}/5 critères }
- >
+ Débloqué : {met}/5 critères }>
{settings.realLockedReason && Coupe-circuit : {settings.realLockedReason}
}
-
- {gate.criteria.map((c) => (
-
-
- {c.ok ? "✅" : "⏳"} {c.label}
-
-
- {c.value} / {c.target}
-
-
- ))}
-
+
+
+ Voir les 5 critères
+
+ {gate.criteria.map((c) => (
+
+
+ {c.ok ? "✅" : "⏳"} {c.label}
+
+
+ {c.value} / {c.target}
+
+
+ ))}
+
+
@@ -114,17 +171,25 @@ async function HomeContent() {
>
) : (
- IA pas encore branchée : ajoute ta clé Anthropic (voir Réglages).
+ IA pas encore branchée : ajoute ta clé Anthropic (ANTHROPIC_API_KEY, voir le README). En attendant, l'app te propose des idées sans IA.
)}
-
+ >
);
}
export default function Home() {
return (
- }>
-
-
+ }>
+ }>
+
+
+ }>
+
+
+ }>
+
+
+
);
}
diff --git a/src/app/(app)/reel/page.tsx b/src/app/(app)/reel/page.tsx
index 3339704..a21f9eb 100644
--- a/src/app/(app)/reel/page.tsx
+++ b/src/app/(app)/reel/page.tsx
@@ -1,78 +1,127 @@
import { Suspense } from "react";
import { connection } from "next/server";
-import { PageSkeleton } from "@/components/page-skeleton";
import { eq } from "drizzle-orm";
-import { ManualRealTrade } from "@/components/manual-real-trade";
-import { ClosedList, PositionList } from "@/components/positions";
-import { Badge, Card, Empty, Page } from "@/components/ui";
+import { AccountForm, AddHolding, CashForms, PeaForm, RealPositions } from "@/components/account-forms";
+import { SettingsLink } from "@/components/nav";
+import { ClosedList } from "@/components/positions";
+import { Badge, Card, CardSkeleton, Delta, Page, Stat } from "@/components/ui";
import { getDb, schema } from "@/lib/db";
-import { eur } from "@/lib/format";
+import { eur, signedEur } from "@/lib/format";
import { getClosedPositions, getPortfolioState } from "@/lib/portfolio";
-import { getSettings } from "@/lib/settings";
-import { getGateStatus } from "@/lib/stats";
+import { defaultPeaPlan, getSettings } from "@/lib/settings";
+import { getPea } from "@/lib/stats";
+import { formatDateFr, parisDate } from "@/lib/time";
-
-async function RealPageContent() {
+async function AccountContent() {
await connection();
const db = await getDb();
const settings = await getSettings();
- const [state, closed, flows, gate] = await Promise.all([
+ const [state, closed, flows] = await Promise.all([
getPortfolioState("real"),
getClosedPositions("real"),
db.select().from(schema.cashFlows).where(eq(schema.cashFlows.portfolioId, "real")),
- getGateStatus(settings),
]);
- const deposited = flows.filter((f) => f.kind === "deposit").reduce((s, f) => s + f.amount, 0);
- const toPea = -flows.filter((f) => f.kind === "to_pea").reduce((s, f) => s + f.amount, 0);
+ const deposited = flows.filter((f) => f.kind === "deposit" || f.kind === "withdrawal").reduce((s, f) => s + f.amount, 0);
+ const toPea = Math.max(0, -flows.filter((f) => f.kind === "to_pea").reduce((s, f) => s + f.amount, 0));
+ const realActive = Boolean(settings.realUnlockedAt) && !settings.realLockedReason;
+ const configured = Boolean(settings.trAccountOpenedAt);
+ const gain = state.equity + toPea - deposited;
return (
-
- Mode réel actif : Simulation }>
- {eur(state.equity)}
-
-
-
{eur(state.cash, 0)}
-
liquidités
-
-
-
{eur(deposited, 0)}
-
versés
-
-
-
{eur(toPea, 0)}
-
partis au PEA
-
+ <>
+
+
+ 🔒 Trade Republic n'offre pas de connexion pour les applications : l'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.
+
+
+
+
configuré : à faire }>
+ {configured && Ouvert le {formatDateFr(settings.trAccountOpenedAt!)}.
}
+
+
+
+
Mode réel actif : Simulation d'abord }>
+
+
{eur(state.equity)}
+ {deposited > 0 &&
{signedEur(gain)} }
- {!settings.realDepositsStart && (
- Indique la date de ton premier virement dans Réglages : l'app ajoutera ensuite tes 50 € chaque mois.
- )}
- {!gate.realActive && (
-
- Ton argent s'accumule sans rien acheter tant que l'IA n'a pas prouvé en simulation qu'elle bat le S&P 500.
+
+ {eur(state.cash, 0)}
+ {eur(deposited, 0)}
+ {eur(toPea, 0)}
+
+ {!realActive && (
+
+ Tant que l'IA n'a pas prouvé en simulation qu'elle bat le S&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é.
)}
+
+
+
- {gate.realActive && (
-
-
+
+
+
+
+ }>
+
+
+
+ {closed.length > 0 && (
+
+
)}
+ >
+ );
+}
-
- {state.positions.length ? : Aucune position réelle. }
-
-
-
+async function PeaSection() {
+ await connection();
+ const settings = await getSettings();
+ const plan = settings.peaPlan ?? defaultPeaPlan(parisDate());
+ const pea = await getPea(settings);
+ return (
+
+
+ {pea && (
+
+ {eur(pea.value, 0)}
+ {eur(pea.invested, 0)}
+ {pea.shares.toLocaleString("fr-FR", { maximumFractionDigits: 3 })}
+
+ )}
+
+
+ );
+}
+
+export default function AccountPage() {
+ return (
+ }>
+ }>
+
+
);
}
-
-export default function RealPage() {
- return (
- }>
-
-
- );
-}
diff --git a/src/app/(app)/reglages/page.tsx b/src/app/(app)/reglages/page.tsx
index 839410f..c335bad 100644
--- a/src/app/(app)/reglages/page.tsx
+++ b/src/app/(app)/reglages/page.tsx
@@ -1,15 +1,13 @@
import { Suspense } from "react";
+import Link from "next/link";
import { connection } from "next/server";
-import { PageSkeleton } from "@/components/page-skeleton";
import { logout, saveSettings } from "@/app/actions";
import { PushManager } from "@/components/push-manager";
import { RunNow } from "@/components/run-now";
-import { Card, inputCls, Page, primaryBtn, secondaryBtn } from "@/components/ui";
+import { Card, CardSkeleton, inputCls, Page, primaryBtn, secondaryBtn } from "@/components/ui";
import { aiEnabled } from "@/lib/ai";
import { getSettings } from "@/lib/settings";
-export const maxDuration = 300;
-
function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
return (
@@ -20,74 +18,57 @@ function Field({ label, hint, children }: { label: string; hint?: string; childr
);
}
-async function SettingsPageContent() {
+async function SettingsForm() {
await connection();
const s = await getSettings();
const hh = String(Math.floor(s.rendezvousMinutes / 60)).padStart(2, "0");
const mm = String(s.rendezvousMinutes % 60).padStart(2, "0");
- const plan = s.peaPlan;
-
return (
-
+
+ );
+}
+
+export default function SettingsPage() {
+ return (
+
+ ‹ Accueil
+
+ }
+ >
-
+
+ Versements, liquidités, actions détenues et plan PEA se règlent dans l'onglet « Mon compte ».
+
+ Ouvrir Mon compte
+
+
@@ -104,11 +85,3 @@ async function SettingsPageContent() {
);
}
-
-export default function SettingsPage() {
- return (
- }>
-
-
- );
-}
diff --git a/src/app/actions.ts b/src/app/actions.ts
index 2ea800a..91f4e3f 100644
--- a/src/app/actions.ts
+++ b/src/app/actions.ts
@@ -6,11 +6,24 @@ import { revalidatePath } from "next/cache";
import { askAboutStock, AiUnavailableError, type AskAnswer } from "@/lib/ai";
import { createSessionToken, isValidSession, safeEqual, SESSION_COOKIE, SESSION_DAYS } from "@/lib/auth";
import { proposeManualRealBuy, respondToCard } from "@/lib/cards";
-import { runEvening, tick } from "@/lib/jobs";
-import { getBars, getNews, getNextEarningsDate, getQuote, isSupportedCurrency, searchInstruments, type Quote, type SearchHit } from "@/lib/market";
+import { runEvening, runEveningNow, tick } from "@/lib/jobs";
+import { FEE_EUR } from "@/lib/engine/fills";
+import { roundShares } from "@/lib/engine/risk";
+import {
+ getBars,
+ getFxToEur,
+ getNews,
+ getNextEarningsDate,
+ getQuote,
+ isSupportedCurrency,
+ searchInstruments,
+ type Quote,
+ type SearchHit,
+} from "@/lib/market";
import { cancelOrder, getPortfolioState, placeOrder } from "@/lib/portfolio";
import { removeSubscription, saveSubscription, sendPush } from "@/lib/push";
-import { getSettings, updateSettings } from "@/lib/settings";
+import { addHolding, deleteHolding, recordDeposit, recordSale, setCash } from "@/lib/real";
+import { defaultPeaPlan, getSettings, updateSettings } from "@/lib/settings";
import { addDays, parisDate } from "@/lib/time";
import { getDb, schema } from "@/lib/db";
import { eq } from "drizzle-orm";
@@ -73,7 +86,9 @@ export async function quoteFor(symbol: string): Promise {
export async function sandboxBuy(input: {
symbol: string;
- shares: number;
+ /** Soit un montant en euros (comme « Montant » chez Trade Republic), soit un nombre d'actions. */
+ amountEur?: number;
+ shares?: number;
type: "market" | "limit";
limitPrice?: number;
stopPct?: number;
@@ -84,6 +99,13 @@ export async function sandboxBuy(input: {
if (!quote) return { ok: false, message: "Cours introuvable." };
if (!isSupportedCurrency(quote.currency)) return { ok: false, message: "Seules les actions en euros ou en dollars sont gérées." };
const ref = input.type === "limit" && input.limitPrice ? input.limitPrice : quote.price;
+ const fx = (await getFxToEur(quote.currency)) ?? 1;
+ const 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");
+ if (shares * ref * fx + FEE_EUR > state.cash + 0.01) {
+ return { ok: false, message: `Pas assez de liquidités : il te reste ${state.cash.toFixed(2)} € (frais de 1 € compris).` };
+ }
try {
const r = await placeOrder({
portfolioId: "sandbox",
@@ -92,12 +114,12 @@ export async function sandboxBuy(input: {
currency: quote.currency,
side: "buy",
type: input.type,
- shares: Math.floor(input.shares),
+ shares,
limitPrice: input.type === "limit" ? input.limitPrice : null,
stopPrice: input.stopPct ? Math.round(ref * (1 - input.stopPct / 100) * 100) / 100 : null,
targetPrice: input.targetPct ? Math.round(ref * (1 + input.targetPct / 100) * 100) / 100 : null,
});
- revalidatePath("/bac-a-sable");
+ revalidatePath("/", "layout");
return { ok: true, message: r.message };
} catch (e) {
return { ok: false, message: e instanceof Error ? e.message : "Erreur." };
@@ -119,7 +141,7 @@ export async function sandboxSell(positionId: number): Promise<{ ok: boolean; me
shares: pos.shares,
positionId: pos.id,
});
- revalidatePath("/bac-a-sable");
+ revalidatePath("/", "layout");
return { ok: true, message: r.message };
}
@@ -128,7 +150,7 @@ export async function cancelSandboxOrder(orderId: number) {
const db = await getDb();
const [o] = await db.select().from(schema.orders).where(eq(schema.orders.id, orderId));
if (o?.portfolioId === "sandbox") await cancelOrder(orderId);
- revalidatePath("/bac-a-sable");
+ revalidatePath("/", "layout");
}
export async function resetSandbox() {
@@ -195,32 +217,118 @@ export async function testPush(): Promise {
// --- Réglages --------------------------------------------------------------
+/** Lit un nombre saisi à la française (« 12,5 ») ; null si vide ou illisible. */
+function parseNum(v: FormDataEntryValue | null): number | null {
+ const s = String(v ?? "").trim().replace(/\s/g, "").replace(",", ".");
+ if (!s) return null;
+ const n = Number(s);
+ return Number.isFinite(n) ? n : null;
+}
+
+function clampDay(n: number | null, d: number) {
+ return Math.min(28, Math.max(1, Math.round(n ?? d)));
+}
+
export async function saveSettings(formData: FormData): Promise {
await requireAuth();
const s = await getSettings();
- const num = (k: string, d: number) => {
- const v = Number(formData.get(k));
- return Number.isFinite(v) && formData.get(k) !== "" ? v : d;
- };
- const str = (k: string) => String(formData.get(k) ?? "").trim();
- const [hh, mm] = (str("rendezvous") || "19:00").split(":").map(Number);
- const calShares = str("calibrationShares");
+ const [hh, mm] = (String(formData.get("rendezvous") ?? "") || "19:00").split(":").map(Number);
await updateSettings({
rendezvousMinutes: hh * 60 + (mm || 0),
- aiMonthlyBudgetUsd: Math.max(1, num("aiBudget", s.aiMonthlyBudgetUsd)),
- realMonthlyDeposit: num("realDeposit", s.realMonthlyDeposit),
- realDepositDay: Math.min(28, Math.max(1, num("realDepositDay", s.realDepositDay))),
- realDepositsStart: str("realDepositsStart") || null,
+ aiMonthlyBudgetUsd: Math.max(1, parseNum(formData.get("aiBudget")) ?? s.aiMonthlyBudgetUsd),
+ });
+ revalidatePath("/", "layout");
+}
+
+export type FormResult = { ok: boolean; message: string } | null;
+
+/** Configuration du compte Trade Republic : ouverture, versement mensuel, argent déjà versé. */
+export async function saveAccount(_prev: FormResult, formData: FormData): Promise {
+ await requireAuth();
+ const s = await getSettings();
+ const opened = String(formData.get("openedAt") ?? "").trim() || null;
+ const firstDeposit = parseNum(formData.get("alreadyDeposited"));
+ const monthly = parseNum(formData.get("monthlyDeposit"));
+ const day = clampDay(parseNum(formData.get("depositDay")), s.realDepositDay);
+ const auto = formData.get("autoDeposit") === "on";
+ const today = parisDate();
+ // Le prochain virement automatique compté par l'app : ce mois-ci si le jour n'est pas passé, sinon le mois prochain.
+ const nextDeposit = (() => {
+ const thisMonth = `${today.slice(0, 7)}-${String(day).padStart(2, "0")}`;
+ if (thisMonth >= today) return thisMonth;
+ const d = new Date(`${today.slice(0, 7)}-01T12:00:00Z`);
+ d.setUTCMonth(d.getUTCMonth() + 1);
+ return `${d.toISOString().slice(0, 7)}-${String(day).padStart(2, "0")}`;
+ })();
+ await updateSettings({
+ trAccountOpenedAt: opened ?? s.trAccountOpenedAt ?? today,
+ realMonthlyDeposit: monthly ?? s.realMonthlyDeposit,
+ realDepositDay: day,
+ realDepositsStart: auto ? (s.realDepositsStart ?? nextDeposit) : null,
+ });
+ if (firstDeposit && firstDeposit > 0) await recordDeposit(firstDeposit);
+ revalidatePath("/", "layout");
+ return { ok: true, message: "Compte enregistré ✅" };
+}
+
+export async function savePea(_prev: FormResult, formData: FormData): Promise {
+ await requireAuth();
+ const s = await getSettings();
+ if (formData.get("hasPea") !== "on") {
+ await updateSettings({ peaPlan: null });
+ revalidatePath("/", "layout");
+ return { ok: true, message: "PEA retiré du suivi." };
+ }
+ const base = s.peaPlan ?? defaultPeaPlan(parisDate());
+ const symbol = String(formData.get("peaSymbol") ?? "").trim().toUpperCase() || base.etfSymbol;
+ const quote = await getQuote(symbol);
+ if (!quote) return { ok: false, message: `ETF « ${symbol} » introuvable. Garde ESE.PA si tu as un doute.` };
+ const calShares = parseNum(formData.get("calibrationShares"));
+ await updateSettings({
peaPlan: {
- etfSymbol: str("peaSymbol") || s.peaPlan?.etfSymbol || "ESE.PA",
- etfName: str("peaName") || s.peaPlan?.etfName || "ETF S&P 500",
- monthlyAmount: num("peaAmount", s.peaPlan?.monthlyAmount ?? 50),
- dayOfMonth: Math.min(28, Math.max(1, num("peaDay", s.peaPlan?.dayOfMonth ?? 5))),
- startDate: str("peaStart") || s.peaPlan?.startDate || parisDate(),
- calibration: calShares ? { date: parisDate(), shares: Number(calShares) } : (s.peaPlan?.calibration ?? null),
+ etfSymbol: symbol,
+ etfName: quote.name,
+ monthlyAmount: parseNum(formData.get("peaAmount")) ?? base.monthlyAmount,
+ dayOfMonth: clampDay(parseNum(formData.get("peaDay")), base.dayOfMonth),
+ startDate: String(formData.get("peaStart") ?? "").trim() || base.startDate,
+ calibration: calShares !== null ? { date: parisDate(), shares: calShares } : (base.calibration ?? null),
},
});
revalidatePath("/", "layout");
+ return { ok: true, message: "PEA enregistré ✅" };
+}
+
+async function realAction(fn: () => Promise, ok: string): Promise {
+ await requireAuth();
+ try {
+ await fn();
+ revalidatePath("/", "layout");
+ return { ok: true, message: ok };
+ } catch (e) {
+ return { ok: false, message: e instanceof Error ? e.message : "Erreur." };
+ }
+}
+
+export async function depositAction(_prev: FormResult, formData: FormData): Promise {
+ const amount = parseNum(formData.get("amount"));
+ return realAction(async () => recordDeposit(amount ?? NaN), "Versement enregistré ✅");
+}
+
+export async function setCashAction(_prev: FormResult, formData: FormData): Promise {
+ const cash = parseNum(formData.get("cash"));
+ return realAction(async () => setCash(cash ?? NaN), "Solde corrigé ✅");
+}
+
+export async function addHoldingAction(input: { symbol: string; shares: number; price: number; stopPct: number | null; paidFromCash: boolean }) {
+ return realAction(() => addHolding(input), "Position ajoutée ✅");
+}
+
+export async function recordSaleAction(positionId: number, price?: number) {
+ return realAction(() => recordSale(positionId, price), "Vente enregistrée ✅");
+}
+
+export async function deleteHoldingAction(positionId: number) {
+ return realAction(() => deleteHolding(positionId), "Position supprimée.");
}
export async function runNow(mode: "tick" | "evening"): Promise {
@@ -229,3 +337,11 @@ export async function runNow(mode: "tick" | "evening"): Promise {
revalidatePath("/", "layout");
return log;
}
+
+/** « Chercher des idées maintenant » depuis l'accueil (limité à 3 fois par jour). */
+export async function findIdeasNow(): Promise {
+ await requireAuth();
+ const log = await runEveningNow();
+ revalidatePath("/", "layout");
+ return log;
+}
diff --git a/src/components/account-forms.tsx b/src/components/account-forms.tsx
new file mode 100644
index 0000000..660d1a9
--- /dev/null
+++ b/src/components/account-forms.tsx
@@ -0,0 +1,312 @@
+"use client";
+
+import { useActionState, useEffect, useState, useTransition } from "react";
+import {
+ addHoldingAction,
+ deleteHoldingAction,
+ depositAction,
+ recordSaleAction,
+ savePea,
+ saveAccount,
+ searchStocks,
+ setCashAction,
+ type FormResult,
+} from "@/app/actions";
+import type { SearchHit } from "@/lib/market";
+import type { PositionView } from "@/lib/portfolio";
+import { eur, pct, price, shares as fmtShares, signedEur } from "@/lib/format";
+import { Delta, Empty, inputCls, primaryBtn, secondaryBtn } from "./ui";
+
+function Result({ r }: { r: FormResult }) {
+ if (!r) return null;
+ return {r.message}
;
+}
+
+function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
+ return (
+
+ {label}
+ {children}
+ {hint && {hint} }
+
+ );
+}
+
+const num = (s: string) => Number(s.replace(",", ".").replace(/\s/g, ""));
+
+// ---------------------------------------------------------------------------
+
+export function AccountForm(props: { openedAt: string | null; monthly: number; day: number; auto: boolean; firstTime: boolean }) {
+ const [state, action, pending] = useActionState(saveAccount, null);
+ return (
+
+ );
+}
+
+export function CashForms({ cash }: { cash: number }) {
+ const [dep, depAction, depPending] = useActionState(depositAction, null);
+ const [fix, fixAction, fixPending] = useActionState(setCashAction, null);
+ return (
+
+ );
+}
+
+// ---------------------------------------------------------------------------
+
+export function AddHolding() {
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const [hits, setHits] = useState([]);
+ const [picked, setPicked] = useState(null);
+ const [qty, setQty] = useState("");
+ const [px, setPx] = useState("");
+ const [stop, setStop] = useState("7");
+ const [paid, setPaid] = useState(true);
+ const [res, setRes] = useState(null);
+ const [pending, start] = useTransition();
+
+ useEffect(() => {
+ if (picked || query.trim().length < 2) return;
+ const t = setTimeout(() => searchStocks(query).then(setHits).catch(() => setHits([])), 350);
+ return () => clearTimeout(t);
+ }, [query, picked]);
+
+ if (!open)
+ return (
+ setOpen(true)}>
+ + Ajouter une action que je détiens
+
+ );
+
+ return (
+
+ );
+}
+
+export function RealPositions({ positions }: { positions: PositionView[] }) {
+ if (!positions.length) return Aucune action détenue pour l'instant. ;
+ return (
+
+ {positions.map((p) => (
+
+ ))}
+
+ );
+}
+
+function RealPosition({ p }: { p: PositionView }) {
+ const [selling, setSelling] = useState(false);
+ const [px, setPx] = useState(p.price?.toFixed(2) ?? "");
+ const [res, setRes] = useState(null);
+ const [pending, start] = useTransition();
+ return (
+
+
+
+
{p.name}
+
+ {fmtShares(p.shares)} × {price(p.entryPrice, p.currency)} → {p.price !== null ? price(p.price, p.currency) : "?"}
+
+ {p.stopPrice &&
Stop {price(p.stopPrice, p.currency)}
}
+
+
+
{eur(p.valueEur)}
+
+ {signedEur(p.pnlOpenEur)} ({pct(p.pnlOpenPct)})
+
+
+
+ {selling ? (
+
+
+ setPx(e.target.value)} />
+
+
+ start(async () => setRes(await recordSaleAction(p.id, num(px) || undefined)))}>
+ Enregistrer la vente
+
+ setSelling(false)}>
+ Annuler
+
+
+
+ ) : (
+
+ setSelling(true)}>
+ J'ai vendu
+
+ {
+ if (confirm("Supprimer cette position (erreur de saisie) ? Tes liquidités ne changent pas.")) start(async () => setRes(await deleteHoldingAction(p.id)));
+ }}
+ >
+ Supprimer
+
+
+ )}
+
+
+ );
+}
+
+// ---------------------------------------------------------------------------
+
+export function PeaForm(props: { has: boolean; symbol: string; amount: number; day: number; start: string; calibration: number | null }) {
+ const [state, action, pending] = useActionState(savePea, null);
+ const [has, setHas] = useState(props.has);
+ return (
+
+ );
+}
diff --git a/src/components/action-card.tsx b/src/components/action-card.tsx
index 2a249c2..2b2b21d 100644
--- a/src/components/action-card.tsx
+++ b/src/components/action-card.tsx
@@ -1,5 +1,6 @@
"use client";
+import Link from "next/link";
import { useState, useTransition } from "react";
import { respondCard } from "@/app/actions";
import type { ActionPayload } from "@/lib/db/schema";
@@ -10,10 +11,20 @@ type Props = {
kind: string;
training: boolean;
status: string;
+ symbol?: string | null;
payload: ActionPayload;
};
-export function ActionCard({ id, kind, training, status, payload }: Props) {
+/** Lien vers la fiche de l'action, formulaire d'achat pré-rempli avec la recette. */
+function sandboxHref(symbol: string, p: ActionPayload) {
+ const q = new URLSearchParams();
+ if (p.amountEur) q.set("montant", String(Math.min(p.amountEur, 198)));
+ if (p.stopPct) q.set("stop", String(p.stopPct));
+ if (p.targetPct) q.set("objectif", String(p.targetPct));
+ return `/actions/${encodeURIComponent(symbol)}?${q}`;
+}
+
+export function ActionCard({ id, kind, training, status, symbol, payload }: Props) {
const [pending, start] = useTransition();
const [open, setOpen] = useState(false);
const [priceVal, setPrice] = useState(payload.limitPrice?.toString() ?? "");
@@ -25,7 +36,7 @@ export function ActionCard({ id, kind, training, status, payload }: Props) {
start(async () => {
setError(null);
try {
- await respondCard(id, a, needsFill ? Number(priceVal.replace(",", ".")) : undefined, needsFill ? Number(sharesVal) : undefined);
+ await respondCard(id, a, needsFill ? Number(priceVal.replace(",", ".")) : undefined, needsFill ? Number(sharesVal.replace(",", ".")) : undefined);
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
}
@@ -54,8 +65,14 @@ export function ActionCard({ id, kind, training, status, payload }: Props) {
))}
+ {kind === "buy" && symbol && (
+
+ 🧪 Essayer dans mon bac à sable
+
+ )}
+
{status === "pending" && (
-
+
{needsFill && (
@@ -64,12 +81,12 @@ export function ActionCard({ id, kind, training, status, payload }: Props) {
Nombre d'actions
- setShares(e.target.value)} />
+ setShares(e.target.value)} />
)}
-
answer("done")}>
+ answer("done")}>
{training ? "✅ Je l'aurais pris" : "✅ C'est fait"}
answer("skipped")}>
diff --git a/src/components/auto-tick.tsx b/src/components/auto-tick.tsx
new file mode 100644
index 0000000..4356636
--- /dev/null
+++ b/src/components/auto-tick.tsx
@@ -0,0 +1,24 @@
+import { after, connection } from "next/server";
+import { shouldAutoTick, tick } from "@/lib/jobs";
+
+/**
+ * Invisible : à l'ouverture de l'app, relance la mise à jour (ordres, stops, actus, idées)
+ * si elle a plus de 20 minutes. Elle tourne après l'envoi de la page : aucun ralentissement.
+ */
+export async function AutoTick() {
+ await connection();
+ try {
+ if (await shouldAutoTick()) {
+ after(async () => {
+ try {
+ await tick();
+ } catch (e) {
+ console.error("[auto-tick]", e);
+ }
+ });
+ }
+ } catch (e) {
+ console.error("[auto-tick]", e);
+ }
+ return null;
+}
diff --git a/src/components/find-ideas.tsx b/src/components/find-ideas.tsx
new file mode 100644
index 0000000..4d0d830
--- /dev/null
+++ b/src/components/find-ideas.tsx
@@ -0,0 +1,32 @@
+"use client";
+
+import { useState, useTransition } from "react";
+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 }) {
+ const [pending, start] = useTransition();
+ const [log, setLog] = useState(null);
+ return (
+
+
+ start(async () => {
+ setLog(null);
+ try {
+ setLog(await findIdeasNow());
+ } catch (e) {
+ setLog([e instanceof Error ? e.message : "Erreur"]);
+ }
+ })
+ }
+ >
+ {pending ? "Analyse en cours… (jusqu'à 1 minute)" : label}
+
+ {log && log.length > 0 &&
{log.at(-1)}
}
+
+ );
+}
diff --git a/src/components/manual-real-trade.tsx b/src/components/manual-real-trade.tsx
deleted file mode 100644
index 6c06577..0000000
--- a/src/components/manual-real-trade.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-"use client";
-
-import { useEffect, useState, useTransition } from "react";
-import { proposeRealBuy, searchStocks } from "@/app/actions";
-import type { SearchHit } from "@/lib/market";
-import { inputCls, primaryBtn } from "./ui";
-
-/** Ton idée de trade réel : elle passe par le même contrôle des risques que l'IA. */
-export function ManualRealTrade() {
- const [query, setQuery] = useState("");
- const [hits, setHits] = useState([]);
- const [picked, setPicked] = useState(null);
- const [stopPct, setStopPct] = useState("7");
- const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
- const [pending, start] = useTransition();
-
- useEffect(() => {
- if (query.trim().length < 2) return;
- const t = setTimeout(() => searchStocks(query).then(setHits).catch(() => setHits([])), 350);
- return () => clearTimeout(t);
- }, [query]);
-
- return (
-
-
Même règles que l'IA : stop obligatoire, taille limitée, une seule position sous 400 €.
-
{
- setPicked(null);
- setQuery(e.target.value);
- if (e.target.value.trim().length < 2) setHits([]);
- }}
- />
- {!picked && hits.length > 0 && (
-
- {hits.map((h) => (
-
- (setPicked(h), setHits([]))}>
- {h.name} · {h.symbol}
-
-
- ))}
-
- )}
-
- Stop (% sous le prix, entre 4 et 10)
- setStopPct(e.target.value)} />
-
-
- start(async () => {
- const r = await proposeRealBuy(picked!.symbol, Number(stopPct) || 7);
- setMsg(r.ok ? { ok: true, text: "Fiche créée : retrouve-la sur l'accueil." } : { ok: false, text: r.reason });
- })
- }
- >
- Vérifier et créer la fiche
-
- {msg &&
{msg.text}
}
-
- );
-}
diff --git a/src/components/nav.tsx b/src/components/nav.tsx
index 5cb2171..5f55675 100644
--- a/src/components/nav.tsx
+++ b/src/components/nav.tsx
@@ -5,19 +5,23 @@ import { usePathname } from "next/navigation";
const TABS = [
{ 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: "IA", icon: "M12 3v3m0 12v3M3 12h3m12 0h3M7 7h10v10H7zM10 10h4v4h-4z" },
- { href: "/actus", label: "Actus", icon: "M5 4h11a2 2 0 0 1 2 2v13a1 1 0 0 0 2 0V8M5 4v15a1 1 0 0 0 1 1h13M8 8h6M8 12h6M8 16h4" },
- { href: "/reglages", label: "Réglages", icon: "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 1v0l-2 1 2 4 2-.5 1.5 1L9 20h6l.5-2.5 1.5-1 2 .5 2-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" },
];
export function Nav() {
- const pathname = usePathname();
+ return ;
+}
+
+/** 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 (
{TABS.map((t) => {
- const active = t.href === "/" ? pathname === "/" : pathname.startsWith(t.href);
+ const active = pathname !== null && (t.href === "/" ? pathname === "/" : pathname.startsWith(t.href));
return (
);
}
+
+/** Raccourci vers les réglages, en haut à droite des pages. */
+export function SettingsLink() {
+ return (
+
+
+
+
+
+ );
+}
diff --git a/src/components/positions.tsx b/src/components/positions.tsx
index f371bb0..c71c7ed 100644
--- a/src/components/positions.tsx
+++ b/src/components/positions.tsx
@@ -1,8 +1,9 @@
"use client";
+import Link from "next/link";
import { useTransition } from "react";
import { cancelSandboxOrder, sandboxSell } from "@/app/actions";
-import { eur, EXIT_REASONS, pct, price, signedEur } from "@/lib/format";
+import { eur, EXIT_REASONS, pct, price, shares, signedEur } from "@/lib/format";
import type { Order, Position, PositionView } from "@/lib/portfolio";
import { Delta, Empty, secondaryBtn } from "./ui";
@@ -14,10 +15,12 @@ export function PositionList({ positions, sellable = false }: { positions: Posit
{positions.map((p) => (
-
-
{p.name}
+
+
+ {p.name}
+
- {p.shares} × {price(p.entryPrice, p.currency)} → {p.price !== null ? price(p.price, p.currency) : "?"}
+ {shares(p.shares)} × {price(p.entryPrice, p.currency)} → {p.price !== null ? price(p.price, p.currency) : "?"}
@@ -61,7 +64,7 @@ export function PendingOrders({ orders, cancellable = false }: { orders: Order[]
{orders.map((o) => (
- {o.side === "buy" ? "Achat" : "Vente"} {o.shares} {o.name}
+ {o.side === "buy" ? "Achat" : "Vente"} {shares(o.shares)} {o.name}
{o.type === "limit" && o.limitPrice ? `limite ${price(o.limitPrice, o.currency)}` : "au marché"}
{o.validUntil ? ` · valable jusqu'au ${o.validUntil}` : ""}
diff --git a/src/components/sandbox-trader.tsx b/src/components/sandbox-trader.tsx
deleted file mode 100644
index 2e73545..0000000
--- a/src/components/sandbox-trader.tsx
+++ /dev/null
@@ -1,183 +0,0 @@
-"use client";
-
-import { useEffect, useState, useTransition } from "react";
-import { askAi, quoteFor, sandboxBuy, searchStocks } from "@/app/actions";
-import type { AskAnswer } from "@/lib/ai";
-import { pct, price } from "@/lib/format";
-import type { Quote, SearchHit } from "@/lib/market";
-import { Badge, Card, inputCls, primaryBtn, secondaryBtn } from "./ui";
-
-export function SandboxTrader({ askLeft }: { askLeft: number }) {
- const [query, setQuery] = useState("");
- const [hits, setHits] = useState([]);
- const [quote, setQuote] = useState(null);
- const [shares, setShares] = useState("1");
- const [type, setType] = useState<"market" | "limit">("market");
- const [limit, setLimit] = useState("");
- const [stopPct, setStopPct] = useState("7");
- const [targetPct, setTargetPct] = useState("");
- const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null);
- const [question, setQuestion] = useState("");
- const [answer, setAnswer] = useState(null);
- const [asking, startAsk] = useTransition();
- const [buying, startBuy] = useTransition();
-
- useEffect(() => {
- if (query.trim().length < 2) return;
- const t = setTimeout(() => searchStocks(query).then(setHits).catch(() => setHits([])), 350);
- return () => clearTimeout(t);
- }, [query]);
-
- async function pick(symbol: string) {
- setHits([]);
- setQuery("");
- setAnswer(null);
- setMessage(null);
- const q = await quoteFor(symbol);
- setQuote(q);
- if (q) setLimit(q.price.toFixed(2));
- }
-
- const n = Math.max(0, Math.floor(Number(shares) || 0));
- const unit = type === "limit" ? Number(limit.replace(",", ".")) || 0 : (quote?.price ?? 0);
-
- return (
-
- {
- setQuery(e.target.value);
- if (e.target.value.trim().length < 2) setHits([]);
- }}
- />
- {hits.length > 0 && (
-
- {hits.map((h) => (
-
- pick(h.symbol)}>
-
- {h.name}
-
- {h.symbol} · {h.exchange}
-
-
- {h.type === "ETF" ? "ETF" : "Action"}
-
-
- ))}
-
- )}
-
- {quote && (
-
-
-
-
{quote.name}
-
{quote.symbol}
-
-
-
{price(quote.price, quote.currency)}
- {quote.changePct !== null && (
-
= 0 ? "text-accent" : "text-danger"}`}>{pct(quote.changePct, 2)} aujourd'hui
- )}
-
-
-
-
- setType("market")}>
- Au marché
-
- setType("limit")}>
- Cours limité
-
-
-
-
- Nombre d'actions
- setShares(e.target.value)} />
-
- {type === "limit" && (
-
- Prix limite
- setLimit(e.target.value)} />
-
- )}
-
- Stop (% sous le prix)
- setStopPct(e.target.value)} placeholder="aucun" />
-
-
- Objectif (% de gain)
- setTargetPct(e.target.value)} placeholder="aucun" />
-
-
-
- Coût ≈ {price(n * unit, quote.currency)} + 1 € de frais
-
-
- startBuy(async () => {
- const r = await sandboxBuy({
- symbol: quote.symbol,
- shares: n,
- type,
- limitPrice: type === "limit" ? unit : undefined,
- stopPct: Number(stopPct) || undefined,
- targetPct: Number(targetPct) || undefined,
- });
- setMessage({ ok: r.ok, text: r.message });
- })
- }
- >
- Acheter {n} action{n > 1 ? "s" : ""}
-
- {message &&
{message.text}
}
-
-
-
🤖 Demander l'avis de l'IA
-
{askLeft} avis restant(s) aujourd'hui
-
setQuestion(e.target.value)}
- />
-
- startAsk(async () => {
- setAnswer(null);
- const r = await askAi(quote.symbol, question);
- if (r.ok) setAnswer(r.answer);
- else setMessage({ ok: false, text: r.message });
- })
- }
- >
- {asking ? "L'IA réfléchit…" : "Demander"}
-
- {answer && (
-
-
-
- {answer.verdict.toUpperCase()}
- {" "}
- confiance {Math.round(answer.confidence)} %
-
-
{answer.explanation}
-
⚠️ {answer.risks}
-
setStopPct(String(Math.round(answer.suggestedStopPct)))}>
- Utiliser son stop conseillé ({Math.round(answer.suggestedStopPct)} %)
-
-
- )}
-
-
- )}
-
- );
-}
diff --git a/src/components/stock-browser.tsx b/src/components/stock-browser.tsx
new file mode 100644
index 0000000..dd48e43
--- /dev/null
+++ b/src/components/stock-browser.tsx
@@ -0,0 +1,108 @@
+"use client";
+
+import Link from "next/link";
+import { useEffect, useMemo, useState } from "react";
+import { searchStocks } from "@/app/actions";
+import type { SearchHit } from "@/lib/market";
+import { pct, price } from "@/lib/format";
+import { Badge, inputCls } from "./ui";
+
+export type StockRow = {
+ symbol: string;
+ name: string;
+ market: "US" | "EU";
+ price: number | null;
+ currency: string;
+ changePct: number | null;
+ news: number;
+ held: boolean;
+};
+
+const FILTERS = [
+ { id: "all", label: "Toutes" },
+ { id: "US", label: "🇺🇸 US" },
+ { id: "EU", label: "🇪🇺 Europe" },
+ { id: "news", label: "Avec actus" },
+ { id: "up", label: "En hausse" },
+ { id: "down", label: "En baisse" },
+] as const;
+
+export function StockBrowser({ rows }: { rows: StockRow[] }) {
+ const [filter, setFilter] = useState<(typeof FILTERS)[number]["id"]>("all");
+ const [query, setQuery] = useState("");
+ const [hits, setHits] = useState([]);
+
+ const q = query.trim().toLowerCase();
+ const list = useMemo(() => {
+ let r = rows;
+ if (filter === "US" || filter === "EU") r = r.filter((x) => x.market === filter);
+ if (filter === "news") r = r.filter((x) => x.news > 0).sort((a, b) => b.news - a.news);
+ if (filter === "up") r = r.filter((x) => (x.changePct ?? 0) > 0).sort((a, b) => (b.changePct ?? 0) - (a.changePct ?? 0));
+ if (filter === "down") r = r.filter((x) => (x.changePct ?? 0) < 0).sort((a, b) => (a.changePct ?? 0) - (b.changePct ?? 0));
+ if (q) r = r.filter((x) => x.name.toLowerCase().includes(q) || x.symbol.toLowerCase().includes(q));
+ return r;
+ }, [rows, filter, q]);
+
+ // Pas trouvée dans la liste surveillée ? On cherche dans toute la bourse.
+ useEffect(() => {
+ if (q.length < 2 || list.length > 0) return;
+ const t = setTimeout(() => searchStocks(q).then(setHits).catch(() => setHits([])), 350);
+ return () => clearTimeout(t);
+ }, [q, list.length]);
+ const showHits = q.length >= 2 && list.length === 0;
+
+ return (
+
+
setQuery(e.target.value)} type="search" />
+
+ {FILTERS.map((f) => (
+ setFilter(f.id)}
+ 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}
+
+ ))}
+
+
+
+ {list.map((r) => (
+
+
+
+
+ {r.name}
+ {r.held && détenue }
+
+
+ {r.symbol}
+ {r.news > 0 && ` · 📰 ${r.news} actu${r.news > 1 ? "s" : ""}`}
+
+
+
+ {r.price !== null ? price(r.price, r.currency) : "—"}
+ {r.changePct !== null && = 0 ? "text-accent" : "text-danger"}`}>{pct(r.changePct, 2)} }
+
+
+
+ ))}
+ {showHits &&
+ hits.map((h) => (
+
+
+
+ {h.name}
+
+ {h.symbol} · {h.exchange}
+
+
+ {h.type === "ETF" ? "ETF" : "Action"}
+
+
+ ))}
+ {!list.length && !(showHits && hits.length) && Aucune action trouvée. }
+
+
+ );
+}
diff --git a/src/components/stock-chart.tsx b/src/components/stock-chart.tsx
new file mode 100644
index 0000000..4488fef
--- /dev/null
+++ b/src/components/stock-chart.tsx
@@ -0,0 +1,29 @@
+import type { Bar } from "@/lib/engine/fills";
+
+/** Courbe de cours en SVG, rendue côté serveur (aucune librairie, aucun JavaScript côté téléphone). */
+export function StockChart({ bars, lastPrice, stop, target }: { bars: Bar[]; lastPrice?: number | null; stop?: number | null; target?: number | null }) {
+ const closes = bars.map((b) => b.close);
+ if (lastPrice) closes.push(lastPrice);
+ if (closes.length < 2) return Pas d'historique disponible.
;
+
+ const W = 320;
+ const H = 120;
+ const levels = [stop, target].filter((x): x is number => typeof x === "number");
+ const min = Math.min(...closes, ...levels);
+ const max = Math.max(...closes, ...levels);
+ const span = max - min || 1;
+ const x = (i: number) => (i / (closes.length - 1)) * W;
+ 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(--accent)" : "var(--danger)";
+
+ return (
+
+
+
+ {stop != null && }
+ {target != null && }
+
+ );
+}
diff --git a/src/components/trade-panel.tsx b/src/components/trade-panel.tsx
new file mode 100644
index 0000000..c761428
--- /dev/null
+++ b/src/components/trade-panel.tsx
@@ -0,0 +1,218 @@
+"use client";
+
+import Link from "next/link";
+import { useState, useTransition } from "react";
+import { askAi, proposeRealBuy, sandboxBuy } from "@/app/actions";
+import type { AskAnswer } from "@/lib/ai";
+import { eur, price } from "@/lib/format";
+import { Badge, Card, inputCls, primaryBtn, secondaryBtn } from "./ui";
+
+type Props = {
+ symbol: string;
+ currency: string;
+ lastPrice: number;
+ fxToEur: number;
+ cash: number;
+ askLeft: number;
+ aiOn: boolean;
+ realActive: boolean;
+ defaults: { amount?: number; stopPct?: number; targetPct?: number };
+};
+
+const num = (s: string) => Number(s.replace(",", ".")) || 0;
+
+export function TradePanel({ symbol, currency, lastPrice, fxToEur, cash, askLeft, aiOn, realActive, defaults }: Props) {
+ const [mode, setMode] = useState<"amount" | "shares">("amount");
+ const [amount, setAmount] = useState(String(defaults.amount ?? Math.min(150, Math.floor(Math.max(cash - 1, 0)))));
+ const [shares, setShares] = useState("1");
+ const [type, setType] = useState<"market" | "limit">("market");
+ const [limit, setLimit] = useState(lastPrice.toFixed(2));
+ const [stopPct, setStopPct] = useState(String(defaults.stopPct ?? 7));
+ const [targetPct, setTargetPct] = useState(defaults.targetPct ? String(defaults.targetPct) : "12");
+ const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null);
+ const [question, setQuestion] = useState("");
+ const [answer, setAnswer] = useState(null);
+ const [buying, startBuy] = useTransition();
+ const [asking, startAsk] = useTransition();
+
+ const unit = type === "limit" ? num(limit) : lastPrice;
+ const qty = mode === "amount" ? (unit > 0 ? num(amount) / (unit * fxToEur) : 0) : num(shares);
+ const costEur = qty * unit * fxToEur;
+ const stop = num(stopPct);
+ const target = num(targetPct);
+ const maxLoss = stop > 0 ? costEur * (stop / 100) + 2 : null;
+ const tooMuch = costEur + 1 > cash + 0.01;
+
+ const buy = () =>
+ startBuy(async () => {
+ setMessage(null);
+ const r = await sandboxBuy({
+ symbol,
+ type,
+ amountEur: mode === "amount" ? num(amount) : undefined,
+ shares: mode === "shares" ? num(shares) : undefined,
+ limitPrice: type === "limit" ? unit : undefined,
+ stopPct: stop || undefined,
+ targetPct: target || undefined,
+ });
+ setMessage({ ok: r.ok, text: r.message });
+ });
+
+ const toggle = (active: boolean) => (active ? "border-accent bg-accent-soft text-accent" : "border-line bg-surface-2 text-muted");
+
+ return (
+ <>
+ dispo {eur(cash)}
}>
+
+
+ setMode("amount")}>
+ Montant en €
+
+ setMode("shares")}>
+ Nb d'actions
+
+
+
+ {mode === "amount" ? (
+
+ Montant à investir (€)
+ setAmount(e.target.value)} />
+
+ {[50, 100, 150].map((v) => (
+ setAmount(String(v))}>
+ {v} €
+
+ ))}
+ setAmount(String(Math.floor(Math.max(cash - 1, 0))))}>
+ Tout
+
+
+
+ ) : (
+
+ Nombre d'actions (fractions possibles)
+ setShares(e.target.value)} />
+
+ )}
+
+
+ setType("market")}>
+ Au marché
+
+ setType("limit")}>
+ Cours limité
+
+
+ {type === "limit" && (
+
+ N'acheter que si le cours descend à ({currency === "EUR" ? "€" : "$"})
+ setLimit(e.target.value)} />
+
+ )}
+
+
+
+ Stop : vendre si −{stop || "?"} %
+ setStopPct(e.target.value)} placeholder="aucun" />
+
+
+ Objectif : vendre à +{target || "?"} %
+ setTargetPct(e.target.value)} placeholder="aucun" />
+
+
+
+
+
+ ≈ {qty.toLocaleString("fr-FR", { maximumFractionDigits: 4 })} action · {eur(costEur)} + 1 € de frais
+
+ {stop > 0 && unit > 0 && (
+
+ Stop à {price(unit * (1 - stop / 100), currency)} → perte max ≈ {eur(maxLoss ?? 0, 0)}
+ {target > 0 && ` · objectif ${price(unit * (1 + target / 100), currency)}`}
+
+ )}
+ {tooMuch &&
Pas assez de liquidités dans ton bac à sable.
}
+
+
+
+ {buying ? "Envoi…" : "Acheter (argent fictif)"}
+
+ {message && (
+
+ {message.text}{" "}
+ {message.ok && (
+
+ Voir mon bac à sable
+
+ )}
+
+ )}
+
+
+
+
+ {!aiOn ? (
+ L'IA n'est pas branchée (clé Anthropic manquante, voir le README). Tout le reste fonctionne sans elle.
+ ) : (
+
+
{askLeft} avis restant(s) aujourd'hui
+
setQuestion(e.target.value)} />
+
+ startAsk(async () => {
+ setAnswer(null);
+ const r = await askAi(symbol, question);
+ if (r.ok) setAnswer(r.answer);
+ else setMessage({ ok: false, text: r.message });
+ })
+ }
+ >
+ {asking ? "L'IA réfléchit… (≈ 20 s)" : "Demander son avis"}
+
+ {answer && (
+
+
+ {answer.verdict.toUpperCase()} {" "}
+ confiance {Math.round(answer.confidence)} %
+
+
{answer.explanation}
+
⚠️ {answer.risks}
+
setStopPct(String(Math.round(answer.suggestedStopPct)))}>
+ Utiliser son stop conseillé ({Math.round(answer.suggestedStopPct)} %)
+
+
+ )}
+
+ )}
+
+
+ {realActive && }
+ >
+ );
+}
+
+/** Mode réel débloqué : crée une fiche réelle, contrôlée par les mêmes règles que l'IA. */
+function RealProposal({ symbol, stopPct }: { symbol: string; stopPct: number }) {
+ const [pending, start] = useTransition();
+ const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
+ return (
+
+ Le contrôle des risques vérifie la taille et le stop, puis te prépare une fiche pas à pas.
+
+ start(async () => {
+ const r = await proposeRealBuy(symbol, stopPct);
+ setMsg(r.ok ? { ok: true, text: "Fiche créée : retrouve-la sur l'accueil." } : { ok: false, text: r.reason });
+ })
+ }
+ >
+ Vérifier et créer la fiche réelle
+
+ {msg && {msg.text}
}
+
+ );
+}
diff --git a/src/components/ui.tsx b/src/components/ui.tsx
index 167252b..878aed8 100644
--- a/src/components/ui.tsx
+++ b/src/components/ui.tsx
@@ -1,11 +1,14 @@
import type { ReactNode } from "react";
-export function Page({ title, subtitle, children }: { title: string; subtitle?: ReactNode; children: ReactNode }) {
+export function Page({ title, subtitle, action, children }: { title: string; subtitle?: ReactNode; action?: ReactNode; children: ReactNode }) {
return (
-
- {title}
- {subtitle && {subtitle}
}
+
+
+
{title}
+ {subtitle &&
{subtitle}
}
+
+ {action && {action}
}
{children}
@@ -42,6 +45,25 @@ export function Delta({ value, children }: { value: number; children: ReactNode
return = 0 ? "text-accent" : "text-danger"}`}>{children} ;
}
+/** Bloc de chargement pour une section qui attend des cours de bourse. */
+export function CardSkeleton({ title, height = "h-24" }: { title?: string; height?: string }) {
+ return (
+
+ );
+}
+
+export function Stat({ label, children }: { label: string; children: ReactNode }) {
+ return (
+
+ );
+}
+
export function Empty({ children }: { children: ReactNode }) {
return {children}
;
}
diff --git a/src/lib/ai.ts b/src/lib/ai.ts
index d093c7f..e371d13 100644
--- a/src/lib/ai.ts
+++ b/src/lib/ai.ts
@@ -6,7 +6,7 @@ import { gte } from "drizzle-orm";
import { z } from "zod";
import { getDb, schema } from "./db";
import { getSettings } from "./settings";
-import { parisDate } from "./time";
+import { addDays, parisDate } from "./time";
/**
* L'IA en entonnoir, validée pour tenir dans 5-10 €/mois :
@@ -48,21 +48,23 @@ async function recordUsage(model: string, purpose: string, usage: { input_tokens
});
}
-export async function getAiSpend(): Promise<{ monthUsd: number; totalUsd: number; askToday: number }> {
+export async function getAiSpend(): Promise<{ monthUsd: number; askToday: number }> {
const db = await getDb();
- const rows = await db.select().from(schema.aiUsage);
const monthStart = `${parisDate().slice(0, 7)}-01`;
const today = parisDate();
+ // Marge d'un jour pour le fuseau horaire, puis filtre exact à l'heure de Paris.
+ const rows = await db
+ .select({ at: schema.aiUsage.at, costUsd: schema.aiUsage.costUsd, purpose: schema.aiUsage.purpose })
+ .from(schema.aiUsage)
+ .where(gte(schema.aiUsage.at, new Date(`${addDays(monthStart, -1)}T00:00:00Z`)));
let monthUsd = 0;
- let totalUsd = 0;
let askToday = 0;
for (const r of rows) {
- totalUsd += r.costUsd;
const d = parisDate(r.at);
if (d >= monthStart) monthUsd += r.costUsd;
if (r.purpose === "ask" && d === today) askToday++;
}
- return { monthUsd, totalUsd, askToday };
+ return { monthUsd, askToday };
}
/** Bloque les appels si le plafond mensuel est atteint. Le tri des actus garde une petite réserve. */
@@ -171,6 +173,8 @@ export type AnalysisContext = {
closes30d: { date: string; close: number }[];
nextEarningsDate: string | null;
news: { title: string; publisher: string | null; publishedAt: string; triage: string }[];
+ /** Si l'action vient du filtre technique (repli dans une tendance haussière) plutôt que d'une actu. */
+ technicalSignal?: string | null;
today: string;
};
@@ -184,6 +188,7 @@ Méthode :
3. Les effets les plus fiables sont la dérive après des résultats nettement meilleurs que prévu, les annonces concrètes (contrats, rachats d'actions, relèvement des prévisions) et les réactions excessives à une nouvelle mineure.
4. Sois sélectif : la plupart du temps, la bonne réponse est "pass". Ne réponds "buy" avec une confiance ≥ 70 que si l'argument est solide et pas encore dans le prix.
5. Ne t'appuie que sur les données fournies et sur des connaissances générales sûres. Ne cite aucun chiffre que tu n'as pas.
+6. Si "technicalSignal" est rempli, l'action t'est proposée pour un repli dans une tendance haussière, pas pour une actu : vérifie dans les actus et le cours que le recul n'a pas une mauvaise raison durable.
Écris thesis et risks en français simple, sans jargon, comme pour un ami qui débute.`;
diff --git a/src/lib/app.integration.test.ts b/src/lib/app.integration.test.ts
index 5a32b18..4745c9a 100644
--- a/src/lib/app.integration.test.ts
+++ b/src/lib/app.integration.test.ts
@@ -13,7 +13,7 @@ delete process.env.DATABASE_URL;
delete process.env.ANTHROPIC_API_KEY;
const { getDb, schema } = await import("./db");
-const { ensureSetup } = await import("./settings");
+const { defaultPeaPlan, ensureSetup } = await import("./settings");
const { collectNews } = await import("./news");
const { getPortfolioState, placeOrder, processAll } = await import("./portfolio");
const { getQuote } = await import("./market");
@@ -125,7 +125,8 @@ describe("intégration", () => {
expect(rdv.summary).toContain("Anthropic");
const settings = await ensureSetup();
- const pea = await getPea({ ...settings, peaPlan: { ...settings.peaPlan!, startDate: addDays(parisDate(), -120) } });
+ expect(settings.peaPlan).toBeNull(); // pas de PEA inventé tant que tu ne l'as pas déclaré
+ const pea = await getPea({ ...settings, peaPlan: defaultPeaPlan(addDays(parisDate(), -120)) });
expect(pea!.invested).toBeGreaterThanOrEqual(150);
expect(pea!.value).toBeGreaterThan(0);
@@ -135,4 +136,21 @@ describe("intégration", () => {
const board = await getLeaderboard(settings, await getPortfolioState("ai_sim"), await getPortfolioState("sandbox"));
expect(board.map((b) => b.label).sort()).toEqual(["L'IA", "S&P 500", "Toi"]);
});
+
+ 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();
+ 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.
+ if (ideas.items.length) expect(cards.some((c) => c.training && c.payload.source === "screen")).toBe(true);
+
+ // Une fraction d'une action chère, comme « Montant » chez Trade Republic.
+ const s = await getPortfolioState("sandbox");
+ const q = (await getQuote("MC.PA"))!;
+ const r = await placeOrder({ portfolioId: "sandbox", symbol: "MC.PA", name: q.name, currency: "EUR", side: "buy", type: "limit", shares: 0.25, limitPrice: q.price * 2 });
+ expect(r.order.shares).toBe(0.25);
+ expect(s.cash).toBeGreaterThan(0);
+ });
});
diff --git a/src/lib/cards.ts b/src/lib/cards.ts
index 8050d51..33c083b 100644
--- a/src/lib/cards.ts
+++ b/src/lib/cards.ts
@@ -107,16 +107,18 @@ export async function proposeManualRealBuy(symbol: string, stopPct: number) {
training: false,
symbol,
payload: {
- title: `Acheter ${r.shares} ${quote.name} (~${Math.round(r.costEur)} €) — ton idée`,
+ title: `Acheter ${quote.name} pour ${r.amountEur} € — ton idée`,
why: "Trade proposé par toi, validé par le contrôle des risques.",
steps: [
- `Dans Trade Republic (compte-titres), cherche « ${quote.name} ».`,
- `Acheter → Ordre à cours limité : ${r.shares} action(s), limite ${r.limitPrice.toFixed(2)} ${cur}.`,
- `Dès que l'achat est fait : ordre Stop (vente) à ${r.stopPrice.toFixed(2)} ${cur}. Perte maximale ≈ ${r.maxLossEur.toFixed(0)} €.`,
+ `Dans Trade Republic (compte-titres), cherche « ${quote.name} » et touche Acheter.`,
+ `Choisis « Montant » et saisis ${r.amountEur} €. N'achète pas si le cours dépasse ${r.limitPrice.toFixed(2)} ${cur}.`,
+ `Une fois acheté : ordre Stop (vente) à ${r.stopPrice.toFixed(2)} ${cur}. Perte maximale ≈ ${r.maxLossEur.toFixed(0)} €.`,
],
name: quote.name,
currency: quote.currency,
shares: r.shares,
+ amountEur: r.amountEur,
+ source: "manual",
limitPrice: r.limitPrice,
stopPrice: r.stopPrice,
targetPrice: r.targetPrice,
diff --git a/src/lib/db/schema.ts b/src/lib/db/schema.ts
index 16d16f6..cbf8ca6 100644
--- a/src/lib/db/schema.ts
+++ b/src/lib/db/schema.ts
@@ -38,7 +38,7 @@ export const positions = pgTable("positions", {
symbol: text("symbol").notNull(),
name: text("name").notNull(),
currency: text("currency").notNull(),
- shares: integer("shares").notNull(),
+ shares: doublePrecision("shares").notNull(),
entryPrice: doublePrecision("entry_price").notNull(), // devise locale
entryFx: doublePrecision("entry_fx").notNull(), // 1 unité locale = entryFx €
openedAt: timestamp("opened_at", { withTimezone: true }).notNull(),
@@ -64,7 +64,7 @@ export const orders = pgTable("orders", {
side: text("side").notNull(), // buy | sell
type: text("type").notNull(), // market | limit
limitPrice: doublePrecision("limit_price"),
- shares: integer("shares").notNull(),
+ shares: doublePrecision("shares").notNull(),
stopPrice: doublePrecision("stop_price"), // appliqué à la position à l'exécution
targetPrice: doublePrecision("target_price"),
maxExitDate: text("max_exit_date"),
@@ -167,6 +167,9 @@ export type ActionPayload = {
positionId?: number;
signalId?: number;
amountEur?: number;
+ stopPct?: number;
+ targetPct?: number;
+ source?: "ai" | "screen" | "manual";
};
export const aiUsage = pgTable("ai_usage", {
diff --git a/src/lib/engine/engine.test.ts b/src/lib/engine/engine.test.ts
index 4112a43..5f930a8 100644
--- a/src/lib/engine/engine.test.ts
+++ b/src/lib/engine/engine.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { evaluateBuyLimit, evaluateExit, type Bar } from "./fills";
import { checkBuy, tierFor } from "./risk";
+import { screenBars } from "./screen";
import { computePea } from "./pea";
import { computeGate, maxDrawdownPct } from "./gate";
import { circuitBreakerTripped, computeRatchet } from "./ratchet";
@@ -103,7 +104,9 @@ describe("contrôle des risques", () => {
const r = checkBuy(base);
expect(r.ok).toBe(true);
if (!r.ok) return;
- expect(r.shares).toBe(3);
+ expect(r.amountEur).toBe(198);
+ expect(r.shares).toBeCloseTo(198 / (60.3 / 1.12), 3);
+ expect(r.costEur).toBeLessThanOrEqual(198);
expect(r.costEur).toBeGreaterThanOrEqual(150);
expect(r.stopPrice).toBeCloseTo(60.3 * 0.93, 1);
expect(r.maxExitDate).toBe(addTradingDays("2026-10-12", 10));
@@ -114,8 +117,16 @@ describe("contrôle des risques", () => {
expect(r.ok).toBe(false);
});
- it("refuse une action trop chère pour la cagnotte", () => {
+ it("achète une fraction d'une action chère (achat par montant)", () => {
const r = checkBuy({ ...base, symbol: "ASML.AS", priceLocal: 1600, fxToEur: 1 });
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.shares).toBeLessThan(1);
+ expect(r.amountEur).toBe(198);
+ });
+
+ it("refuse quand il reste trop peu de liquidités", () => {
+ const r = checkBuy({ ...base, cash: 90 });
expect(r.ok).toBe(false);
});
@@ -176,3 +187,24 @@ describe("cliquet et coupe-circuit", () => {
expect(circuitBreakerTripped(160, 300)).toBe(false);
});
});
+
+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 }));
+ const up = Array.from({ length: 60 }, (_, i) => 100 + i);
+
+ it("repère un repli dans une tendance haussière", () => {
+ const r = screenBars(series(up), 150);
+ expect(r).not.toBeNull();
+ expect(r!.pullbackPct).toBeLessThan(-2);
+ });
+
+ it("ignore une action en baisse", () => {
+ const down = Array.from({ length: 60 }, (_, i) => 200 - i);
+ expect(screenBars(series(down), 138)).toBeNull();
+ });
+
+ it("ignore une action qui n'a pas reculé", () => {
+ expect(screenBars(series(up), 160)).toBeNull();
+ });
+});
diff --git a/src/lib/engine/risk.ts b/src/lib/engine/risk.ts
index 633f520..257e846 100644
--- a/src/lib/engine/risk.ts
+++ b/src/lib/engine/risk.ts
@@ -43,6 +43,7 @@ export type RiskResult =
| {
ok: true;
shares: number;
+ amountEur: number; // montant à investir chez Trade Republic (achat par montant)
limitPrice: number;
stopPrice: number;
targetPrice: number;
@@ -81,12 +82,14 @@ export function checkBuy(input: RiskInput): RiskResult {
if (tier.maxRiskPct !== null) {
budget = Math.min(budget, (equity * tier.maxRiskPct) / (stopPct / 100));
}
- const shares = Math.floor(budget / priceEur);
+ // Trade Republic permet d'acheter par montant (fractions d'actions) : on investit un montant rond en euros.
+ const amountEur = Math.floor(Math.max(budget, 0));
+ const shares = roundShares(amountEur / priceEur);
const costEur = shares * priceEur;
- if (shares < 1 || costEur < MIN_POSITION_EUR) {
+ if (shares <= 0 || amountEur < MIN_POSITION_EUR) {
return {
ok: false,
- reason: `Position trop petite (${Math.round(Math.max(costEur, 0))} € possible, minimum ${MIN_POSITION_EUR} € pour que les frais restent faibles).`,
+ reason: `Pas assez de liquidités (${amountEur} € possibles, minimum ${MIN_POSITION_EUR} € par position pour que les frais restent faibles).`,
};
}
@@ -96,6 +99,7 @@ export function checkBuy(input: RiskInput): RiskResult {
return {
ok: true,
shares,
+ amountEur,
limitPrice,
stopPrice,
targetPrice,
@@ -105,6 +109,11 @@ export function checkBuy(input: RiskInput): RiskResult {
};
}
+/** 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;
+}
+
function round(n: number): number {
return Math.round(n * 100) / 100;
}
diff --git a/src/lib/engine/screen.ts b/src/lib/engine/screen.ts
new file mode 100644
index 0000000..2d4c16a
--- /dev/null
+++ b/src/lib/engine/screen.ts
@@ -0,0 +1,42 @@
+/**
+ * Filtre « repli dans une tendance haussière » : fonction pure, testée dans engine.test.ts.
+ *
+ * Idée : une grande action solidement orientée à la hausse (moyenne 20 jours au-dessus de la
+ * moyenne 50 jours, cours au-dessus de la moyenne 50 jours) qui vient de reculer de 2 à 8 %
+ * en une semaine. On achète le repli, pas le sommet. Ce n'est pas une garantie : c'est une
+ * règle simple, mesurée honnêtement dans le bac à sable.
+ */
+import type { Bar } from "./fills";
+
+export type Screen = {
+ score: number;
+ trendPct: number; // écart moyenne 20 j / moyenne 50 j, en %
+ pullbackPct: number; // variation sur 5 séances, en % (négatif = repli)
+ reason: string;
+};
+
+function sma(values: number[], n: number): number | null {
+ if (values.length < n) return null;
+ const slice = values.slice(-n);
+ return slice.reduce((s, x) => s + x, 0) / n;
+}
+
+export function screenBars(bars: Bar[], lastPrice: number): Screen | null {
+ const closes = bars.map((b) => b.close);
+ if (closes.length < 55) return null;
+ const sma20 = sma(closes, 20)!;
+ const sma50 = sma(closes, 50)!;
+ const ref = closes[closes.length - 6]; // il y a 5 séances
+ const trendPct = (sma20 / sma50 - 1) * 100;
+ const pullbackPct = (lastPrice / ref - 1) * 100;
+ const aboveTrend = lastPrice > sma50;
+
+ if (!aboveTrend || trendPct < 1 || pullbackPct > -2 || pullbackPct < -8) return null;
+ const score = trendPct + Math.min(-pullbackPct, 6);
+ return {
+ score: Math.round(score * 10) / 10,
+ trendPct: Math.round(trendPct * 10) / 10,
+ pullbackPct: Math.round(pullbackPct * 10) / 10,
+ reason: `Tendance de fond haussière (moyenne 20 j ${trendPct.toFixed(1)} % au-dessus de la moyenne 50 j), mais recul de ${(-pullbackPct).toFixed(1)} % cette semaine : un point d'entrée possible.`,
+ };
+}
diff --git a/src/lib/format.ts b/src/lib/format.ts
index 452002f..41bc039 100644
--- a/src/lib/format.ts
+++ b/src/lib/format.ts
@@ -10,6 +10,11 @@ export function pct(n: number, digits = 1): string {
return `${n >= 0 ? "+" : ""}${n.toLocaleString("fr-FR", { minimumFractionDigits: digits, maximumFractionDigits: digits })} %`;
}
+/** Nombre d'actions, fractions comprises (« 0,4213 »). */
+export function shares(n: number): string {
+ return n.toLocaleString("fr-FR", { maximumFractionDigits: 4 });
+}
+
export function signedEur(n: number): string {
return `${n >= 0 ? "+" : ""}${eur(n)}`;
}
diff --git a/src/lib/ideas.ts b/src/lib/ideas.ts
new file mode 100644
index 0000000..ae7774e
--- /dev/null
+++ b/src/lib/ideas.ts
@@ -0,0 +1,48 @@
+import "server-only";
+import { getBars, getQuotes } from "./market";
+import { getKv, setKv } from "./settings";
+import { addDays, parisDate } from "./time";
+import { UNIVERSE, findStock } from "./universe";
+import { screenBars, type Screen } from "./engine/screen";
+
+/**
+ * Idées « sans IA » : un filtre simple et transparent sur toutes les actions surveillées.
+ * Il sert (1) à proposer quelque chose même sans clé Anthropic, (2) à donner plus de
+ * candidates à l'IA quand l'actualité seule n'en fournit pas assez.
+ * Calculé au plus une fois toutes les 6 heures, stocké en base : les pages ne font que le lire.
+ */
+export type Idea = Screen & { symbol: string; name: string; currency: string; price: number; changePct: number | null };
+export type IdeasSnapshot = { at: string; date: string; items: Idea[] };
+
+const REFRESH_MS = 6 * 3_600_000;
+
+export async function getIdeas(): Promise {
+ return getKv("ideas");
+}
+
+export async function refreshIdeas(force = false): Promise {
+ const prev = await getIdeas();
+ if (!force && prev && Date.now() - new Date(prev.at).getTime() < REFRESH_MS) return prev;
+
+ const from = addDays(parisDate(), -110);
+ const quotes = await getQuotes(UNIVERSE.map((s) => s.symbol));
+ const items: Idea[] = [];
+ // 8 historiques en parallèle : assez rapide (~10 s) sans se faire bloquer par Yahoo.
+ for (let i = 0; i < UNIVERSE.length; i += 8) {
+ const chunk = UNIVERSE.slice(i, i + 8);
+ const results = await Promise.allSettled(chunk.map((s) => getBars(s.symbol, from)));
+ results.forEach((r, j) => {
+ if (r.status !== "fulfilled") return;
+ const stock = chunk[j];
+ const q = quotes.get(stock.symbol);
+ if (!q) return;
+ const screen = screenBars(r.value, q.price);
+ if (!screen) return;
+ items.push({ ...screen, symbol: stock.symbol, name: findStock(stock.symbol)?.name ?? q.name, currency: q.currency, price: q.price, changePct: q.changePct });
+ });
+ }
+ items.sort((a, b) => b.score - a.score);
+ const snap: IdeasSnapshot = { at: new Date().toISOString(), date: parisDate(), items: items.slice(0, 8) };
+ await setKv("ideas", snap);
+ return snap;
+}
diff --git a/src/lib/jobs.ts b/src/lib/jobs.ts
index 749d1de..0dbd950 100644
--- a/src/lib/jobs.ts
+++ b/src/lib/jobs.ts
@@ -1,5 +1,5 @@
import "server-only";
-import { and, eq, isNull } 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 { checkBuy, MIN_CONFIDENCE } from "./engine/risk";
@@ -9,19 +9,35 @@ import { getBars, getFxToEur, getNextEarningsDate, getQuote, getQuotes } from ".
import { collectNews, recentNews, triagePending } from "./news";
import { getOpenSymbols, getPortfolioState, placeOrder, processAll, snapshotEquity, type PortfolioState } from "./portfolio";
import { sendPush } from "./push";
-import { getKv, getSettings, setKv, 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, isTradeRepublicOpen, isWeekend, parisDate, parisMinutes } from "./time";
import { findStock, UNIVERSE } from "./universe";
const UNIVERSE_COLLECT_EVERY_MS = 3 * 3_600_000;
+const AUTO_TICK_EVERY_MS = 20 * 60_000;
+
/**
- * Appelé toutes les 30 minutes par GitHub Actions (ou à la main depuis les réglages).
+ * Mise à jour automatique quand tu ouvres l'app : si la dernière mise à jour date de plus de
+ * 20 minutes, on la relance en arrière-plan (après l'affichage de la page, sans la ralentir).
+ * Ainsi l'app vit même sans la tâche planifiée GitHub (en local, ou si elle n'est pas branchée).
+ */
+export async function shouldAutoTick(): Promise {
+ const last = (await getKv("lastTickAt")) ?? 0;
+ if (Date.now() - last < AUTO_TICK_EVERY_MS) return false;
+ await setKv("lastTickAt", Date.now()); // réservé tout de suite : pas deux mises à jour en même temps
+ return true;
+}
+
+/**
+ * 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.
*/
export async function tick(now = new Date()): Promise {
const log: string[] = [];
+ await setKv("lastTickAt", Date.now());
const settings = await getSettings();
const today = parisDate(now);
const minutes = parisMinutes(now);
@@ -29,25 +45,32 @@ export async function tick(now = new Date()): Promise {
log.push(...(await processAll()));
await monthlyDeposit(settings, today, log);
- if (!isWeekend(today)) {
- const held = await getOpenSymbols(["real", "ai_sim"]);
- const last = (await getKv("lastUniverseCollect")) ?? 0;
- const collectUniverse = Date.now() - last > UNIVERSE_COLLECT_EVERY_MS && minutes >= 7 * 60 && minutes <= 22 * 60 + 30;
- const symbols = collectUniverse ? UNIVERSE.map((s) => s.symbol) : held;
- if (symbols.length) {
- const n = await collectNews(symbols);
- if (collectUniverse) await setKv("lastUniverseCollect", Date.now());
- log.push(`${n} nouvelles actus collectées`);
- }
- try {
- const t = await triagePending();
- if (t) log.push(`${t} actus triées par l'IA`);
- } catch (e) {
- if (!(e instanceof AiUnavailableError)) throw e;
- log.push(e.message);
- }
- log.push(...(await urgentAlerts()));
+ // Les actus et les idées se collectent tous les jours (week-end compris) pour que l'app ne soit jamais vide.
+ const held = await getOpenSymbols(["real", "ai_sim"]);
+ const last = (await getKv("lastUniverseCollect")) ?? 0;
+ const collectUniverse = Date.now() - last > UNIVERSE_COLLECT_EVERY_MS;
+ const symbols = collectUniverse ? UNIVERSE.map((s) => s.symbol) : held;
+ if (symbols.length) {
+ const n = await collectNews(symbols);
+ if (collectUniverse) await setKv("lastUniverseCollect", Date.now());
+ log.push(`${n} nouvelles actus collectées`);
+ }
+ try {
+ const t = await triagePending();
+ if (t) log.push(`${t} actus triées par l'IA`);
+ } catch (e) {
+ if (!(e instanceof AiUnavailableError)) throw e;
+ log.push(e.message);
+ }
+ log.push(...(await urgentAlerts()));
+ try {
+ const ideas = await refreshIdeas();
+ log.push(`${ideas.items.length} idée(s) repérée(s) par le filtre`);
+ } catch (e) {
+ log.push(`Filtre d'idées indisponible : ${e instanceof Error ? e.message : e}`);
+ }
+ if (!isWeekend(today)) {
const lastEvening = await getKv("lastEvening");
if (lastEvening !== today && minutes >= settings.rendezvousMinutes - 30) {
log.push(...(await runEvening()));
@@ -92,34 +115,67 @@ async function urgentAlerts(): Promise {
return log;
}
-type Candidate = { symbol: string; score: number; newsIds: string[] };
+type Candidate = { symbol: string; score: number; newsIds: string[]; technical?: string };
-function pickCandidates(rows: Awaited>, exclude: string[]): Candidate[] {
+const MAX_CANDIDATES = 3;
+
+/**
+ * Les candidates analysées par l'IA : d'abord les actions portées par une actu positive
+ * (pertinence ≥ 6/10), puis, s'il reste de la place, les meilleures idées du filtre technique.
+ */
+function pickCandidates(rows: Awaited>, exclude: string[], ideas: Idea[]): Candidate[] {
const bySymbol = new Map();
for (const n of rows) {
const t = n.triage;
- if (!t || t.direction !== "positive" || t.relevance < 7 || exclude.includes(n.symbol) || !findStock(n.symbol)) continue;
+ if (!t || t.direction !== "positive" || t.relevance < 6 || exclude.includes(n.symbol) || !findStock(n.symbol)) continue;
const c = bySymbol.get(n.symbol) ?? { symbol: n.symbol, score: 0, newsIds: [] };
c.score = Math.max(c.score, t.relevance) + 0.5 * c.newsIds.length;
c.newsIds.push(n.id);
bySymbol.set(n.symbol, c);
}
- return [...bySymbol.values()].sort((a, b) => b.score - a.score).slice(0, 3);
+ const fromNews = [...bySymbol.values()].sort((a, b) => b.score - a.score).slice(0, MAX_CANDIDATES);
+ for (const idea of ideas) {
+ if (fromNews.length >= MAX_CANDIDATES) break;
+ if (exclude.includes(idea.symbol) || fromNews.some((c) => c.symbol === idea.symbol)) continue;
+ fromNews.push({ symbol: idea.symbol, score: idea.score, newsIds: [], technical: idea.reason });
+ }
+ return fromNews;
+}
+
+const MANUAL_RUNS_PER_DAY = 3;
+
+/** Lancement à la demande (« Chercher des idées maintenant ») : limité pour garder le budget IA. */
+export async function runEveningNow(): Promise {
+ const today = parisDate();
+ const key = `manualRuns:${today}`;
+ const used = (await getKv(key)) ?? 0;
+ if (used >= MANUAL_RUNS_PER_DAY) {
+ return [`Déjà ${MANUAL_RUNS_PER_DAY} recherches aujourd'hui : reviens demain (ça protège ton budget IA).`];
+ }
+ await setKv(key, used + 1);
+ await refreshIdeas().catch(() => null);
+ return runEvening({ manual: true });
}
/** Le rendez-vous du soir : analyse, décisions, fiches et notification. */
-export async function runEvening(): Promise {
+export async function runEvening(opts: { manual?: boolean } = {}): Promise {
const log: string[] = [];
const db = await getDb();
const today = parisDate();
const summary: string[] = [];
- await setKv("lastEvening", today);
+ // Une recherche à la demande ne remplace pas le vrai rendez-vous du soir (ni sa notification).
+ if (!opts.manual) await setKv("lastEvening", today);
const [rdv] = await db
.insert(schema.rendezvous)
.values({ date: today, summary: "" })
.onConflictDoUpdate({ target: schema.rendezvous.date, set: { createdAt: new Date() } })
.returning();
+ // Relancé le même jour : on remplace les fiches encore sans réponse au lieu de les dupliquer.
+ // (sauf le virement mensuel vers le PEA, qui n'est créé qu'une fois par mois).
+ await db
+ .delete(schema.actions)
+ .where(and(eq(schema.actions.rendezvousId, rdv.id), eq(schema.actions.status, "pending"), ne(schema.actions.kind, "to_pea")));
let settings = await getSettings();
const ai = await getPortfolioState("ai_sim");
@@ -142,10 +198,11 @@ export async function runEvening(): Promise {
// 1. Analyse des meilleures candidates.
let best: { analysis: Analysis; signalId: number; symbol: string; name: string; price: number; currency: string } | null = null;
let analyzed = 0;
+ const ideas = (await getIdeas())?.items ?? [];
if (aiEnabled()) {
const news = await recentNews(30);
const exclude = await getOpenSymbols(["ai_sim", "real"]);
- const candidates = pickCandidates(news, exclude);
+ const candidates = pickCandidates(news, exclude, ideas);
const results = await Promise.allSettled(candidates.map((c) => analyze(c, news, today)));
for (const r of results) {
if (r.status === "rejected") {
@@ -209,7 +266,9 @@ export async function runEvening(): Promise {
summary.push(`🤖 L'IA aimait ${best.name}, mais le contrôle des risques a dit non : ${aiRisk.reason}`);
}
- const forCard = gate.realActive ? checkBuy(riskInput(real)) : aiRisk;
+ // Fiche d'entraînement : dimensionnée sur ton bac à sable (ou sur 200 € neufs s'il est plein),
+ // pour que tu aies toujours quelque chose à essayer, même quand la cagnotte de l'IA est déjà investie.
+ const forCard = gate.realActive ? checkBuy(riskInput(real)) : trainingRisk(riskInput, await getPortfolioState("sandbox"));
if (forCard.ok) {
const training = !gate.realActive;
await db.insert(schema.actions).values({
@@ -222,8 +281,21 @@ export async function runEvening(): Promise {
} else if (gate.realActive) {
summary.push(`Pas de proposition réelle sur ${best.name} : ${forCard.reason}`);
}
- } else if (aiEnabled()) {
- summary.push(`😴 Rien d'intéressant ce soir. L'IA a étudié ${analyzed} candidate(s) et préfère attendre.`);
+ } else {
+ if (aiEnabled()) summary.push(`😴 L'IA a étudié ${analyzed} candidate(s) et préfère attendre ce soir.`);
+ // Sans conviction de l'IA (ou sans IA), on te propose la meilleure idée du filtre, pour t'entraîner.
+ const held = await getOpenSymbols(["sandbox"]);
+ const idea = ideas.find((i) => !held.includes(i.symbol));
+ if (idea) {
+ await db.insert(schema.actions).values({
+ rendezvousId: rdv.id,
+ kind: "buy",
+ training: true,
+ symbol: idea.symbol,
+ payload: ideaPayload(idea),
+ });
+ summary.push(`🔎 Idée du filtre (sans IA) à tester dans ton bac à sable : ${idea.name}.`);
+ }
}
// 3. Revue des positions réelles : vendre, ou remonter le stop pour protéger un gain.
@@ -295,6 +367,7 @@ async function analyze(c: Candidate, news: Awaited
publishedAt: n.publishedAt.toISOString(),
triage: n.triage ? `${n.triage.eventType}, pertinence ${n.triage.relevance}/10 : ${n.triage.reason}` : "",
})),
+ technicalSignal: c.technical ?? null,
today,
});
if (!analysis) return null;
@@ -325,38 +398,74 @@ function money(n: number, currency: string) {
return `${n.toFixed(2)} ${currency === "EUR" ? "€" : "$"}`;
}
+type RiskOk = Extract, { ok: true }>;
+
+/** Dimensionne une fiche d'entraînement sur ton bac à sable, ou sur 200 € neufs s'il n'a plus de place. */
+function trainingRisk(riskInput: (s: PortfolioState) => Parameters[0], sandbox: PortfolioState) {
+ const r = checkBuy(riskInput(sandbox));
+ if (r.ok) return r;
+ const fresh = { ...sandbox, equity: SIM_INITIAL_CASH, cash: SIM_INITIAL_CASH, positions: [], pendingOrders: [] };
+ return checkBuy(riskInput(fresh));
+}
+
+/** En euros, comme dans Trade Republic (les actions américaines y sont cotées en euros). */
+function inEur(n: number, currency: string, fx: number) {
+ return currency === "EUR" ? `${n.toFixed(2)} €` : `${n.toFixed(2)} $ (≈ ${(n * fx).toFixed(2)} €)`;
+}
+
function buyPayload(
best: { analysis: Analysis; signalId: number; symbol: string; name: string; currency: string },
- r: Extract, { ok: true }>,
+ r: RiskOk,
fx: number,
training: boolean,
): ActionPayload {
- const isUs = best.currency === "USD";
return {
- title: `Acheter ${r.shares} ${best.name} (~${Math.round(r.costEur)} €)`,
+ title: `Acheter ${best.name} pour ${r.amountEur} €`,
why: `${best.analysis.thesis}\n\nRisques : ${best.analysis.risks}`,
steps: [
training
- ? "Entraînement : le mode réel n'est pas encore débloqué. Dis simplement si tu aurais pris ce trade."
- : `Dans Trade Republic (compte-titres), cherche « ${best.name} ».`,
- `Choisis Acheter → Ordre à cours limité : ${r.shares} action(s), limite ${money(r.limitPrice, best.currency)}${isUs ? ` (≈ ${(r.limitPrice * fx).toFixed(2)} € chez Trade Republic)` : ""}.`,
- isUs
- ? "Validité : jusqu'à demain soir."
- : "Validité : jusqu'à demain soir (le marché européen est fermé, l'ordre partira à l'ouverture de 9h).",
- `Dès que l'achat est fait : ordre Stop (vente) à ${money(r.stopPrice, best.currency)}${isUs ? ` (≈ ${(r.stopPrice * fx).toFixed(2)} €)` : ""}. Perte maximale ≈ ${r.maxLossEur.toFixed(0)} €.`,
- `L'app te dira quand vendre : objectif ${money(r.targetPrice, best.currency)}, au plus tard le ${r.maxExitDate}.`,
+ ? "Entraînement : le mode réel n'est pas encore débloqué. Essaie ce trade dans ton bac à sable, ou dis simplement si tu l'aurais pris."
+ : `Dans Trade Republic (compte-titres), cherche « ${best.name} » et touche Acheter.`,
+ `Choisis « Montant » et saisis ${r.amountEur} € (≈ ${fmtShares(r.shares)} action). N'achète pas si le cours dépasse ${inEur(r.limitPrice, best.currency, fx)}.`,
+ `Une fois acheté : ordre Stop (vente) à ${inEur(r.stopPrice, best.currency, fx)}. Perte maximale ≈ ${r.maxLossEur.toFixed(0)} €.`,
+ `L'app te dira quand vendre : objectif ${inEur(r.targetPrice, best.currency, fx)}, au plus tard le ${r.maxExitDate}.`,
],
name: best.name,
currency: best.currency,
shares: r.shares,
+ amountEur: r.amountEur,
limitPrice: r.limitPrice,
stopPrice: r.stopPrice,
targetPrice: r.targetPrice,
maxExitDate: r.maxExitDate,
signalId: best.signalId,
+ stopPct: Math.round((1 - r.stopPrice / r.limitPrice) * 1000) / 10,
+ targetPct: Math.round((r.targetPrice / r.limitPrice - 1) * 1000) / 10,
};
}
+/** Fiche d'entraînement issue du filtre technique (sans IA). */
+function ideaPayload(idea: Idea): ActionPayload {
+ return {
+ title: `Idée à tester : ${idea.name}`,
+ why: `${idea.reason}\n\nCette idée vient d'une règle simple, pas de l'IA. Teste-la dans ton bac à sable pour voir si elle marche.`,
+ steps: [
+ "Entraînement uniquement : essaie-la dans ton bac à sable avec un stop à 7 %.",
+ "Le bac à sable vendra tout seul si le stop ou l'objectif (+12 %) est touché.",
+ ],
+ name: idea.name,
+ currency: idea.currency,
+ stopPct: 7,
+ targetPct: 12,
+ amountEur: 150,
+ source: "screen",
+ };
+}
+
+export function fmtShares(n: number): string {
+ return n.toLocaleString("fr-FR", { maximumFractionDigits: 4 });
+}
+
async function reviewRealPositions(real: PortfolioState, rdvId: number, today: string) {
const db = await getDb();
const quotes = await getQuotes(real.positions.map((p) => p.symbol));
diff --git a/src/lib/market.ts b/src/lib/market.ts
index d537a35..c619aed 100644
--- a/src/lib/market.ts
+++ b/src/lib/market.ts
@@ -1,7 +1,7 @@
import "server-only";
import YahooFinance from "yahoo-finance2";
import type { Bar } from "./engine/fills";
-import { parisDate } from "./time";
+import { addDays, parisDate } from "./time";
import { findStock } from "./universe";
/** Cours, historiques, actus et dates de résultats, via Yahoo Finance (gratuit, US + Europe). */
@@ -16,32 +16,76 @@ export type Quote = {
};
const SUPPORTED_CURRENCIES = new Set(["EUR", "USD"]);
-const quoteCache = new Map();
-const QUOTE_TTL_MS = 60_000;
-export async function getQuotes(symbols: string[]): Promise> {
- const out = new Map();
- const missing: string[] = [];
- for (const s of new Set(symbols)) {
- const hit = quoteCache.get(s);
- if (hit && Date.now() - hit.at < QUOTE_TTL_MS) out.set(s, hit.quote);
- else missing.push(s);
- }
- if (missing.length) {
- const rows = await yf.quote(missing);
+// ---------------------------------------------------------------------------
+// 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).
+// ---------------------------------------------------------------------------
+
+type Entry = { at: number; value: Promise };
+const g = globalThis as unknown as { __marketCache?: Map };
+const cache = (g.__marketCache ??= new Map());
+
+function memo(key: string, ttlMs: number, fn: () => Promise): Promise {
+ const hit = cache.get(key);
+ if (hit && Date.now() - hit.at < ttlMs) return hit.value as Promise;
+ const value = fn().catch((err) => {
+ cache.delete(key); // une erreur n'est jamais gardée en cache
+ throw err;
+ });
+ cache.set(key, { at: Date.now(), value });
+ return value;
+}
+
+const QUOTE_TTL_MS = 60_000;
+const quoteCache = new Map();
+const inflightQuotes = new Map>();
+
+async function fetchQuotes(symbols: string[]): Promise {
+ // 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);
+ let rows: Awaited> = [];
+ try {
+ rows = await yf.quote(chunk);
+ } catch (err) {
+ console.error("[market] cours indisponibles :", chunk.join(","), err);
+ continue;
+ }
for (const r of rows) {
if (r.regularMarketPrice == null || !r.currency) continue;
- const quote: 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,
- };
- quoteCache.set(r.symbol, { at: Date.now(), quote });
- out.set(r.symbol, quote);
+ 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,
+ },
+ });
}
}
+}
+
+export async function getQuotes(symbols: string[]): Promise> {
+ const unique = [...new Set(symbols)];
+ const fresh = (s: string) => {
+ const hit = quoteCache.get(s);
+ return hit && Date.now() - hit.at < QUOTE_TTL_MS;
+ };
+ const missing = unique.filter((s) => !fresh(s) && !inflightQuotes.has(s));
+ if (missing.length) {
+ const p = fetchQuotes(missing).finally(() => missing.forEach((s) => inflightQuotes.delete(s)));
+ missing.forEach((s) => inflightQuotes.set(s, p));
+ }
+ await Promise.all(unique.map((s) => inflightQuotes.get(s)).filter(Boolean));
+ const out = new Map();
+ for (const s of unique) {
+ const hit = quoteCache.get(s);
+ if (hit) out.set(s, hit.quote);
+ }
return out;
}
@@ -61,67 +105,87 @@ export function isSupportedCurrency(currency: string): boolean {
return SUPPORTED_CURRENCIES.has(currency);
}
-/** Barres journalières depuis une date (incluse), datées à l'heure de Paris. */
+/**
+ * Barres journalières depuis une date (incluse), datées à l'heure de Paris.
+ * On télécharge au moins 9 mois d'historique une seule fois par action (cache 15 min),
+ * puis on découpe : une seule requête sert le graphique, le PEA, l'indice et le moteur.
+ */
+const BARS_TTL_MS = 15 * 60_000;
+const barsFrom = new Map();
+
export async function getBars(symbol: string, fromDate: string): Promise {
- const chart = await yf.chart(symbol, { period1: fromDate, interval: "1d" });
- 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!,
- }));
+ const minFrom = addDays(parisDate(), -270);
+ const known = barsFrom.get(symbol);
+ const from = known && known <= fromDate ? known : fromDate < minFrom ? fromDate : minFrom;
+ barsFrom.set(symbol, from);
+ const all = await memo(`bars:${symbol}:${from}`, BARS_TTL_MS, async () => {
+ const chart = await yf.chart(symbol, { period1: from, interval: "1d" });
+ 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 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 {
- try {
- const s = await yf.quoteSummary(symbol, { modules: ["calendarEvents"] });
- const dates = s.calendarEvents?.earnings?.earningsDate ?? [];
- const today = parisDate();
- const next = dates.map((d) => parisDate(d)).filter((d) => d >= today).sort()[0];
- return next ?? null;
- } catch {
- return null;
- }
+ return memo(`earnings:${symbol}`, 12 * 3_600_000, async () => {
+ try {
+ const s = await yf.quoteSummary(symbol, { modules: ["calendarEvents"] });
+ const dates = s.calendarEvents?.earnings?.earningsDate ?? [];
+ const today = parisDate();
+ const next = dates.map((d) => parisDate(d)).filter((d) => d >= today).sort()[0];
+ return next ?? null;
+ } catch {
+ return null;
+ }
+ });
}
export type RawNews = { id: string; symbol: string; title: string; publisher: string; url: string; publishedAt: Date };
/** Actus récentes d'une action. Recherche par symbole (US) ou par nom (Europe), puis filtre sur la société. */
export async function getNews(symbol: string): Promise {
- 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,
- }));
+ return memo(`news:${symbol}`, 10 * 60_000, async () => {
+ const stock = findStock(symbol);
+ const query = stock?.market === "EU" ? stock.name : symbol;
+ const res = await yf.search(query, { newsCount: 8, quotesCount: 0 });
+ return res.news
+ .filter((n) => n.relatedTickers?.includes(symbol))
+ .map((n) => ({
+ id: n.uuid,
+ symbol,
+ title: n.title,
+ publisher: n.publisher,
+ url: n.link,
+ publishedAt: n.providerPublishTime,
+ }));
+ });
}
export type SearchHit = { symbol: string; name: string; exchange: string; type: string };
-/** Recherche d'actions ou d'ETF pour le bac à sable. */
+/** Recherche d'actions ou d'ETF (en euros ou en dollars, les seules devises gérées). */
export async function searchInstruments(query: string): Promise {
- const res = await yf.search(query, { quotesCount: 8, newsCount: 0 });
- const hits: SearchHit[] = [];
- for (const q of res.quotes) {
- if (!("symbol" in q) || !q.isYahooFinance) continue;
- if (q.quoteType !== "EQUITY" && q.quoteType !== "ETF") continue;
- hits.push({
- symbol: q.symbol,
- name: ("longname" in q && q.longname) || ("shortname" in q && q.shortname) || q.symbol,
- exchange: ("exchDisp" in q && q.exchDisp) || "",
- type: q.quoteType,
- });
- }
- return hits;
+ 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) {
+ if (!("symbol" in q) || !q.isYahooFinance) continue;
+ if (q.quoteType !== "EQUITY" && q.quoteType !== "ETF") continue;
+ hits.push({
+ symbol: q.symbol,
+ name: findStock(q.symbol)?.name || ("longname" in q && q.longname) || ("shortname" in q && q.shortname) || q.symbol,
+ exchange: ("exchDisp" in q && q.exchDisp) || "",
+ type: q.quoteType,
+ });
+ }
+ return hits;
+ });
}
diff --git a/src/lib/news.ts b/src/lib/news.ts
index 17ba967..b95b085 100644
--- a/src/lib/news.ts
+++ b/src/lib/news.ts
@@ -67,6 +67,18 @@ export async function triagePending(): Promise {
export type NewsRow = typeof schema.news.$inferSelect;
+/** Nombre d'actus récentes par action (pour la liste des actions). */
+export async function newsCounts(hours = 48): Promise> {
+ const db = await getDb();
+ const rows = await db
+ .select({ symbol: schema.news.symbol })
+ .from(schema.news)
+ .where(gte(schema.news.publishedAt, new Date(Date.now() - hours * 3_600_000)));
+ const out = new Map();
+ for (const r of rows) out.set(r.symbol, (out.get(r.symbol) ?? 0) + 1);
+ return out;
+}
+
export async function recentNews(hours = 36): Promise {
const db = await getDb();
return db
diff --git a/src/lib/portfolio.ts b/src/lib/portfolio.ts
index e756472..b44a73d 100644
--- a/src/lib/portfolio.ts
+++ b/src/lib/portfolio.ts
@@ -30,19 +30,23 @@ export type PortfolioState = {
export async function getPortfolioState(id: PortfolioId, quotes?: Map): Promise {
const db = await getDb();
- const [p] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, id));
+ const [[p], open, pendingOrders] = await Promise.all([
+ db.select().from(schema.portfolios).where(eq(schema.portfolios.id, id)),
+ db
+ .select()
+ .from(schema.positions)
+ .where(and(eq(schema.positions.portfolioId, id), eq(schema.positions.status, "open"))),
+ db
+ .select()
+ .from(schema.orders)
+ .where(and(eq(schema.orders.portfolioId, id), eq(schema.orders.status, "pending"))),
+ ]);
if (!p) throw new Error(`Portefeuille ${id} introuvable`);
- const open = await db
- .select()
- .from(schema.positions)
- .where(and(eq(schema.positions.portfolioId, id), eq(schema.positions.status, "open")));
- const pendingOrders = await db
- .select()
- .from(schema.orders)
- .where(and(eq(schema.orders.portfolioId, id), eq(schema.orders.status, "pending")));
- const q = quotes ?? (open.length ? await getQuotes(open.map((x) => x.symbol)) : new Map());
- const fxUsd = open.some((x) => x.currency === "USD") ? await getFxToEur("USD") : 1;
+ const [q, fxUsd] = await Promise.all([
+ quotes ?? (open.length ? getQuotes(open.map((x) => x.symbol)) : new Map()),
+ open.some((x) => x.currency === "USD") ? getFxToEur("USD") : 1,
+ ]);
const positions: PositionView[] = open.map((pos) => {
const price = q.get(pos.symbol)?.price ?? null;
const fx = pos.currency === "USD" ? (fxUsd ?? pos.entryFx) : 1;
@@ -85,7 +89,8 @@ type NewOrder = {
/** Enregistre un ordre simulé et tente de l'exécuter tout de suite. */
export async function placeOrder(o: NewOrder): Promise<{ order: Order; filled: boolean; message: string }> {
if (o.portfolioId === "real") throw new Error("Les ordres réels se passent dans Trade Republic.");
- if (!Number.isInteger(o.shares) || o.shares < 1) throw new Error("Nombre d'actions invalide.");
+ // Fractions autorisées, comme chez Trade Republic (achat par montant).
+ if (!Number.isFinite(o.shares) || o.shares <= 0) throw new Error("Quantité invalide.");
const db = await getDb();
const [order] = await db
.insert(schema.orders)
diff --git a/src/lib/real.ts b/src/lib/real.ts
new file mode 100644
index 0000000..8f05462
--- /dev/null
+++ b/src/lib/real.ts
@@ -0,0 +1,93 @@
+import "server-only";
+import { eq } from "drizzle-orm";
+import { getDb, schema } from "./db";
+import { FEE_EUR } from "./engine/fills";
+import { getFxToEur, getQuote, isSupportedCurrency } from "./market";
+import { closePosition } from "./portfolio";
+import { parisDate } from "./time";
+
+/**
+ * Suivi de ton compte-titres Trade Republic.
+ * Trade Republic n'a pas d'API officielle : l'app ne se connecte jamais à ton compte et ne te
+ * demande jamais tes identifiants. Tu lui dis ce que tu as fait, elle tient les comptes.
+ */
+
+async function realPortfolio() {
+ const db = await getDb();
+ const [p] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, "real"));
+ return { db, p };
+}
+
+/** Tu as versé de l'argent sur ton compte-titres (compte dans les versements : sert au coupe-circuit et au cliquet). */
+export async function recordDeposit(amount: number, date = parisDate()) {
+ if (!Number.isFinite(amount) || amount === 0) throw new Error("Montant invalide.");
+ const { db, p } = await realPortfolio();
+ await db.insert(schema.cashFlows).values({ portfolioId: "real", amount, kind: amount > 0 ? "deposit" : "withdrawal", date });
+ await db
+ .update(schema.portfolios)
+ .set({ cash: p.cash + amount, highWaterMark: Math.max(0, p.highWaterMark + amount) })
+ .where(eq(schema.portfolios.id, "real"));
+}
+
+/** Corrige les liquidités pour coller exactement à ce qu'affiche Trade Republic (n'est pas un versement). */
+export async function setCash(cash: number) {
+ if (!Number.isFinite(cash) || cash < 0) throw new Error("Solde invalide.");
+ const { db, p } = await realPortfolio();
+ const delta = Math.round((cash - p.cash) * 100) / 100;
+ if (delta === 0) return;
+ await db.insert(schema.cashFlows).values({ portfolioId: "real", amount: delta, kind: "adjust", date: parisDate() });
+ await db.update(schema.portfolios).set({ cash }).where(eq(schema.portfolios.id, "real"));
+}
+
+/**
+ * Enregistre une action que tu détiens déjà chez Trade Republic (achat fait hors de l'app,
+ * ou avant d'utiliser l'app). Si `paidFromCash`, le coût est retiré des liquidités suivies.
+ */
+export async function addHolding(input: {
+ symbol: string;
+ shares: number;
+ price: number; // prix d'achat unitaire, devise de cotation
+ stopPct?: number | null;
+ paidFromCash: boolean;
+}) {
+ if (!(input.shares > 0) || !(input.price > 0)) throw new Error("Quantité ou prix invalide.");
+ const quote = await getQuote(input.symbol);
+ if (!quote) throw new Error("Action introuvable.");
+ if (!isSupportedCurrency(quote.currency)) throw new Error("Seules les actions en euros ou en dollars sont gérées.");
+ const fx = (await getFxToEur(quote.currency)) ?? 1;
+ const { db, p } = await realPortfolio();
+ if (input.paidFromCash) {
+ const cost = input.shares * input.price * fx + FEE_EUR;
+ await db.update(schema.portfolios).set({ cash: Math.max(0, p.cash - cost) }).where(eq(schema.portfolios.id, "real"));
+ }
+ await db.insert(schema.positions).values({
+ portfolioId: "real",
+ symbol: input.symbol,
+ name: quote.name,
+ currency: quote.currency,
+ shares: input.shares,
+ entryPrice: input.price,
+ entryFx: fx,
+ openedAt: new Date(),
+ stopPrice: input.stopPct ? Math.round(input.price * (1 - input.stopPct / 100) * 100) / 100 : null,
+ feesEur: input.paidFromCash ? FEE_EUR : 0,
+ });
+}
+
+/** Tu as vendu une position chez Trade Republic : on la clôture au prix réellement obtenu. */
+export async function recordSale(positionId: number, price?: number) {
+ const db = await getDb();
+ const [pos] = await db.select().from(schema.positions).where(eq(schema.positions.id, positionId));
+ if (!pos || pos.portfolioId !== "real" || pos.status !== "open") throw new Error("Position introuvable.");
+ const px = price && price > 0 ? price : ((await getQuote(pos.symbol))?.price ?? pos.entryPrice);
+ const fx = (await getFxToEur(pos.currency)) ?? pos.entryFx;
+ await closePosition(pos, px, fx, "manual", false);
+}
+
+/** Supprime une position saisie par erreur (sans toucher aux liquidités). */
+export async function deleteHolding(positionId: number) {
+ const db = await getDb();
+ const [pos] = await db.select().from(schema.positions).where(eq(schema.positions.id, positionId));
+ if (!pos || pos.portfolioId !== "real") throw new Error("Position introuvable.");
+ await db.delete(schema.positions).where(eq(schema.positions.id, positionId));
+}
diff --git a/src/lib/settings.ts b/src/lib/settings.ts
index d661d0d..b62dc21 100644
--- a/src/lib/settings.ts
+++ b/src/lib/settings.ts
@@ -16,23 +16,31 @@ export type Settings = {
askDailyLimit: number;
realUnlockedAt: string | null;
realLockedReason: string | null;
+ /** Date à laquelle tu as déclaré ton compte Trade Republic ouvert (null = pas encore). */
+ trAccountOpenedAt: string | null;
};
export const SIM_INITIAL_CASH = 200;
+/** Le plan PEA par défaut, proposé quand tu configures ton compte. */
+export function defaultPeaPlan(startDate: string): PeaPlan {
+ return {
+ etfSymbol: DEFAULT_PEA_ETF.symbol,
+ etfName: DEFAULT_PEA_ETF.name,
+ monthlyAmount: 50,
+ dayOfMonth: 5,
+ startDate,
+ calibration: null,
+ };
+}
+
function defaults(): Settings {
const today = parisDate();
return {
simStartDate: today,
rendezvousMinutes: 19 * 60,
- peaPlan: {
- etfSymbol: DEFAULT_PEA_ETF.symbol,
- etfName: DEFAULT_PEA_ETF.name,
- monthlyAmount: 50,
- dayOfMonth: 5,
- startDate: today,
- calibration: null,
- },
+ // Pas de PEA tant que tu ne l'as pas déclaré : sinon l'app inventerait des versements.
+ peaPlan: null,
realMonthlyDeposit: 50,
realDepositDay: 5,
realDepositsStart: null,
@@ -40,6 +48,7 @@ function defaults(): Settings {
askDailyLimit: 10,
realUnlockedAt: null,
realLockedReason: null,
+ trAccountOpenedAt: null,
};
}
@@ -57,7 +66,9 @@ export async function setKv(key: string, value: unknown): Promise {
.onConflictDoUpdate({ target: schema.kv.key, set: { value, updatedAt: new Date() } });
}
-/** Crée les réglages et les trois portefeuilles au premier lancement. */
+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). */
export async function ensureSetup(): Promise {
const db = await getDb();
let settings = await getKv("settings");
@@ -67,6 +78,8 @@ export async function ensureSetup(): Promise {
} else {
settings = { ...defaults(), ...settings };
}
+ if (g.__setupDone) return settings;
+ g.__setupDone = true;
await db
.insert(schema.portfolios)
.values([
diff --git a/src/lib/stats.ts b/src/lib/stats.ts
index 10a82fb..01b5e99 100644
--- a/src/lib/stats.ts
+++ b/src/lib/stats.ts
@@ -8,10 +8,17 @@ import { getBars, getFxToEur, getQuote } from "./market";
import { getPortfolioState, type PortfolioState } from "./portfolio";
import { getSettings, type Settings } from "./settings";
import { daysBetween, parisDate } from "./time";
+import { DEFAULT_PEA_ETF } from "./universe";
+import { eur } from "./format";
+
+/** L'ETF S&P 500 de référence : celui de ton PEA, ou l'ETF par défaut si tu n'as pas encore de PEA. */
+export function benchmarkSymbol(s: Settings): string {
+ return s.peaPlan?.etfSymbol ?? DEFAULT_PEA_ETF.symbol;
+}
/** Rendement de l'ETF S&P 500 (celui du PEA) depuis une date, en %. */
export async function benchmarkReturnPct(symbol: string, since: string): Promise {
- const bars = await getBars(symbol, since);
+ const bars = await getBars(symbol, since).catch((e) => (console.error("[indice]", e), []));
const first = bars.find((b) => b.date >= since);
const last = (await getQuote(symbol))?.price ?? bars.at(-1)?.close;
if (!first || !last) return 0;
@@ -29,16 +36,20 @@ export type GateStatus = {
export async function getGateStatus(settings?: Settings, ai?: PortfolioState): Promise {
const s = settings ?? (await getSettings());
const db = await getDb();
- const aiState = ai ?? (await getPortfolioState("ai_sim"));
- const closed = await db
- .select({ id: schema.positions.id })
- .from(schema.positions)
- .where(and(eq(schema.positions.portfolioId, "ai_sim"), eq(schema.positions.status, "closed")));
- const snaps = await db.select().from(schema.equitySnapshots).where(eq(schema.equitySnapshots.portfolioId, "ai_sim"));
- const acts = await db.select({ status: schema.actions.status }).from(schema.actions).where(ne(schema.actions.kind, "to_pea"));
- const usdToEur = (await getFxToEur("USD")) ?? 0.9;
- const aiCostEur = (await aiSpendSince(s.simStartDate)) * usdToEur;
- const bench = s.peaPlan ? await benchmarkReturnPct(s.peaPlan.etfSymbol, s.simStartDate) : 0;
+ // Tout est lancé en parallèle : la page attend la requête la plus lente, pas leur somme.
+ const [aiState, closed, snaps, acts, usdToEur, spent, bench] = await Promise.all([
+ ai ?? getPortfolioState("ai_sim"),
+ db
+ .select({ id: schema.positions.id })
+ .from(schema.positions)
+ .where(and(eq(schema.positions.portfolioId, "ai_sim"), eq(schema.positions.status, "closed"))),
+ db.select().from(schema.equitySnapshots).where(eq(schema.equitySnapshots.portfolioId, "ai_sim")),
+ db.select({ status: schema.actions.status }).from(schema.actions).where(ne(schema.actions.kind, "to_pea")),
+ getFxToEur("USD").then((x) => x ?? 0.9),
+ aiSpendSince(s.simStartDate),
+ benchmarkReturnPct(benchmarkSymbol(s), s.simStartDate),
+ ]);
+ const aiCostEur = spent * usdToEur;
const gate = computeGate({
simDays: daysBetween(s.simStartDate, parisDate()),
@@ -63,10 +74,10 @@ export async function getGateStatus(settings?: Settings, ai?: PortfolioState): P
export type Leaderboard = { label: string; pct: number; detail: string }[];
export async function getLeaderboard(settings: Settings, ai: PortfolioState, sandbox: PortfolioState): Promise {
- const bench = settings.peaPlan ? await benchmarkReturnPct(settings.peaPlan.etfSymbol, settings.simStartDate) : 0;
+ const bench = await benchmarkReturnPct(benchmarkSymbol(settings), settings.simStartDate);
const rows = [
- { label: "L'IA", pct: (ai.equity / ai.initialCash - 1) * 100, detail: `${ai.equity.toFixed(2)} €` },
- { label: "Toi", pct: (sandbox.equity / sandbox.initialCash - 1) * 100, detail: `${sandbox.equity.toFixed(2)} €` },
+ { 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" },
];
return rows.sort((a, b) => b.pct - a.pct);
@@ -77,12 +88,17 @@ export async function getPea(settings: Settings): Promise<(PeaResult & { etfName
if (!plan) return null;
const today = parisDate();
if (plan.startDate > today) return { shares: 0, invested: 0, value: 0, gain: 0, contributions: [], etfName: plan.etfName, price: null };
- const [bars, quote] = await Promise.all([getBars(plan.etfSymbol, plan.startDate), getQuote(plan.etfSymbol)]);
+ const [bars, quote] = await Promise.all([
+ // Yahoo en panne ou symbole erroné : on affiche 0 plutôt que de casser la page.
+ getBars(plan.etfSymbol, plan.startDate).catch((e) => (console.error("[pea]", e), [])),
+ getQuote(plan.etfSymbol),
+ ]);
return { ...computePea(plan, bars, quote?.price ?? null, today), etfName: plan.etfName, price: quote?.price ?? null };
}
export async function totalDeposited(): Promise {
const db = await getDb();
const rows = await db.select().from(schema.cashFlows).where(eq(schema.cashFlows.portfolioId, "real"));
- return rows.reduce((s, r) => s + r.amount, 0);
+ // Les corrections de solde ne sont pas des versements : elles ne comptent pas pour le coupe-circuit.
+ return rows.filter((r) => r.kind !== "adjust").reduce((s, r) => s + r.amount, 0);
}