Cagnotte V1: IA news-driven trading sim, sandbox, PEA tracking, PWA
Some checks failed
Tick / tick (push) Failing after 1s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
David 2026-11-13 19:06:17 +01:00
parent 0d4fca29f8
commit 27a358038a
69 changed files with 7993 additions and 126 deletions

22
.github/workflows/tick.yml vendored Normal file
View File

@ -0,0 +1,22 @@
# Réveille l'app toutes les 30 minutes en semaine (de 7h à 23h30, heure de Paris).
# L'app décide seule quoi faire : collecte des actus, ordres, stops, rendez-vous du soir.
name: Tick
on:
schedule:
- cron: "*/30 5-21 * * 1-5" # en UTC
workflow_dispatch: {}
jobs:
tick:
runs-on: ubuntu-latest
timeout-minutes: 7
steps:
- name: Appeler l'app
env:
APP_URL: ${{ secrets.APP_URL }}
CRON_SECRET: ${{ secrets.CRON_SECRET }}
run: |
curl -fsS --max-time 320 \
-H "Authorization: Bearer $CRON_SECRET" \
"$APP_URL/api/cron/tick"

4
.gitignore vendored
View File

@ -32,6 +32,10 @@ yarn-error.log*
# env files (can opt-in for committing if needed) # env files (can opt-in for committing if needed)
.env* .env*
!.env.example
# base locale embarquée (PGlite)
/.data
# vercel # vercel
.vercel .vercel

114
README.md
View File

@ -1,36 +1,108 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). # Cagnotte 🌱
## Getting Started App web (installable sur iPhone) qui t'aide à investir 100 €/mois :
First, run the development server: - **50 € → PEA** : plan d'épargne automatique sur un ETF S&P 500, chez Trade Republic. L'app calcule sa valeur toute seule.
- **50 € → compte-titres** : la cagnotte « satellite ». Chaque soir de semaine, l'IA analyse l'actualité et te propose (ou non) un trade, sous forme de fiche à exécuter en 20 secondes dans Trade Republic.
**Simulation d'abord.** L'IA gère une cagnotte virtuelle de 200 €. Le mode réel ne se débloque que si, après 3 mois et 20 trades, elle bat le S&P 500 après tous les frais (Trade Republic + IA), avec une baisse maximale inférieure à 25 % et au moins 80 % de rendez-vous suivis.
> 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.
---
## Lancer l'app sur ton Mac
```bash ```bash
npm run dev pnpm install
# or pnpm setup:env # crée .env.local (mot de passe local : cagnotte-local)
yarn dev pnpm dev # puis ouvre http://localhost:3000
# or
pnpm dev
# or
bun dev
``` ```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. En local, la base de données est embarquée dans `.data/` : rien à installer. Pour que l'IA fonctionne, ajoute `ANTHROPIC_API_KEY=...` dans `.env.local`.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. Tests : `pnpm test` (moteur, risques, PEA, critères) et `pnpm test:integration` (vraie base + vrais cours).
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. ---
## Learn More ## Mettre l'app en ligne (gratuit, sauf l'IA)
To learn more about Next.js, take a look at the following resources: ### 1. Clé Anthropic (l'IA, 5 à 10 €/mois)
1. Crée un compte sur [console.anthropic.com](https://console.anthropic.com).
2. **Billing** : ajoute 10 $ de crédit, et **coupe la recharge automatique**.
3. **Limits** : fixe une limite de dépense mensuelle (par exemple 10 $).
4. **API Keys** → *Create Key*. Copie la clé `sk-ant-...`.
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. L'app a aussi son propre plafond (8 $/mois par défaut, modifiable dans Réglages).
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! ### 2. Base de données Supabase
1. Crée un compte sur [supabase.com](https://supabase.com) → *New project* (région Europe, par exemple Paris ou Francfort). Note le mot de passe de la base.
2. Bouton **Connect** → onglet **Transaction pooler** → copie l'URL (port `6543`) et remplace `[YOUR-PASSWORD]` par ton mot de passe.
## Deploy on Vercel Les tables se créent toutes seules au premier lancement (`AUTO_MIGRATE=1`).
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. ### 3. Code sur GitHub
Pousse ce dossier dans un dépôt GitHub **privé**.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. ### 4. Hébergement Vercel
1. Crée un compte sur [vercel.com](https://vercel.com) avec ton GitHub → *Add New Project* → choisis le dépôt.
2. Avant *Deploy*, ouvre **Environment Variables** et ajoute :
| Variable | Valeur |
|---|---|
| `APP_PASSWORD` | ton mot de passe pour entrer dans l'app |
| `SESSION_SECRET`, `CRON_SECRET`, `NEXT_PUBLIC_VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` | sortie de `pnpm tsx scripts/setup-env.mts --print` |
| `VAPID_SUBJECT` | `mailto:ton-email` |
| `ANTHROPIC_API_KEY` | la clé de l'étape 1 |
| `DATABASE_URL` | l'URL Supabase de l'étape 2 |
| `AUTO_MIGRATE` | `1` |
3. *Deploy*. Note l'adresse obtenue, par exemple `https://cagnotte-xxx.vercel.app`.
### 5. Réveil automatique (GitHub Actions)
Dans le dépôt GitHub → **Settings → Secrets and variables → Actions** → *New repository secret* :
- `APP_URL` = l'adresse Vercel (sans `/` à la fin)
- `CRON_SECRET` = la même valeur que dans Vercel
Puis onglet **Actions** → *Tick* → *Run workflow* pour tester. Ensuite, il tourne seul toutes les 30 minutes en semaine.
### 6. Sur ton iPhone
1. Ouvre l'adresse Vercel dans **Safari** et connecte-toi.
2. **Partager** → **Sur l'écran d'accueil** → *Ajouter*.
3. Ouvre l'app depuis l'icône (reconnecte-toi une fois), puis **Réglages → Activer les notifications** → *Tester*.
Il faut iOS 16.4 ou plus récent.
---
## Comment ça marche
```
GitHub Actions (toutes les 30 min, en semaine)
└─> /api/cron/tick
├─ ordres et stops simulés (cours Yahoo Finance, frais Trade Republic : 1 € par ordre)
├─ actus de 92 grandes actions US + Europe → tri par Claude Haiku (quelques centimes)
├─ alerte immédiate seulement si un événement grave touche une position réelle
└─ à 18h30 : rendez-vous du soir
├─ analyse approfondie des 3 meilleures candidates par Claude Sonnet (débat haussier/baissier)
├─ contrôle des risques (code fixe, jamais l'IA) → l'IA achète dans sa cagnotte simulée
├─ fiche « recette » pour toi (entraînement tant que le réel n'est pas débloqué)
├─ revue des positions réelles, cliquet vers le PEA, coupe-circuit
└─ notification sur l'iPhone
```
**Règles du contrôle des risques** (`src/lib/engine/risk.ts`) :
- 1 position à la fois sous 400 €, 2 entre 400 et 1 000 €, 4 au-delà ;
- au moins 150 € par position, sinon les frais mangent le gain ;
- stop obligatoire, entre 4 et 10 % ;
- sortie au plus tard après 15 jours de bourse ;
- pas d'achat dans les 4 jours avant des résultats trimestriels ;
- achats d'actions uniquement : pas de vente à découvert, pas de levier.
**Le cliquet** : chaque mois, la moitié des gains au-dessus du plus haut de la cagnotte réelle part vers le PEA.
**Le coupe-circuit** : si la cagnotte réelle tombe sous 50 % de ce que tu y as versé, retour en simulation.
**Limites connues** :
- La simulation utilise des barres journalières. Si un stop et un objectif sont touchés le même jour, on suppose le stop.
- Les jours fériés ne sont pas gérés.
- Les cours US viennent de la Bourse américaine, alors que Trade Republic cote sur LS Exchange avec un petit écart. On compte 0,1 % de glissement par ordre.

8
drizzle.config.ts Normal file
View File

@ -0,0 +1,8 @@
import { defineConfig } from "drizzle-kit";
export default defineConfig({
dialect: "postgresql",
schema: "./src/lib/db/schema.ts",
out: "./drizzle",
dbCredentials: { url: process.env.DATABASE_URL ?? "" },
});

147
drizzle/0000_init.sql Normal file
View File

@ -0,0 +1,147 @@
CREATE TABLE "actions" (
"id" serial PRIMARY KEY NOT NULL,
"rendezvous_id" integer NOT NULL,
"kind" text NOT NULL,
"training" boolean NOT NULL,
"symbol" text,
"payload" jsonb NOT NULL,
"status" text DEFAULT 'pending' NOT NULL,
"responded_at" timestamp with time zone
);
--> statement-breakpoint
CREATE TABLE "ai_usage" (
"id" serial PRIMARY KEY NOT NULL,
"at" timestamp with time zone DEFAULT now() NOT NULL,
"model" text NOT NULL,
"purpose" text NOT NULL,
"input_tokens" integer NOT NULL,
"output_tokens" integer NOT NULL,
"cost_usd" double precision NOT NULL
);
--> statement-breakpoint
CREATE TABLE "cash_flows" (
"id" serial PRIMARY KEY NOT NULL,
"portfolio_id" text NOT NULL,
"amount" double precision NOT NULL,
"kind" text NOT NULL,
"date" text NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "equity_snapshots" (
"id" serial PRIMARY KEY NOT NULL,
"portfolio_id" text NOT NULL,
"date" text NOT NULL,
"equity" double precision NOT NULL
);
--> statement-breakpoint
CREATE TABLE "kv" (
"key" text PRIMARY KEY NOT NULL,
"value" jsonb NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "news" (
"id" text PRIMARY KEY NOT NULL,
"symbol" text NOT NULL,
"title" text NOT NULL,
"publisher" text,
"url" text,
"published_at" timestamp with time zone NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"triage" jsonb,
"triaged_at" timestamp with time zone,
"alerted_at" timestamp with time zone
);
--> statement-breakpoint
CREATE TABLE "orders" (
"id" serial PRIMARY KEY NOT NULL,
"portfolio_id" text NOT NULL,
"symbol" text NOT NULL,
"name" text NOT NULL,
"currency" text NOT NULL,
"side" text NOT NULL,
"type" text NOT NULL,
"limit_price" double precision,
"shares" integer NOT NULL,
"stop_price" double precision,
"target_price" double precision,
"max_exit_date" text,
"position_id" integer,
"signal_id" integer,
"status" text DEFAULT 'pending' NOT NULL,
"valid_until" text,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"filled_at" timestamp with time zone,
"fill_price" double precision,
"note" text
);
--> statement-breakpoint
CREATE TABLE "portfolios" (
"id" text PRIMARY KEY NOT NULL,
"name" text NOT NULL,
"initial_cash" double precision NOT NULL,
"cash" double precision NOT NULL,
"high_water_mark" double precision DEFAULT 0 NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "positions" (
"id" serial PRIMARY KEY NOT NULL,
"portfolio_id" text NOT NULL,
"symbol" text NOT NULL,
"name" text NOT NULL,
"currency" text NOT NULL,
"shares" integer NOT NULL,
"entry_price" double precision NOT NULL,
"entry_fx" double precision NOT NULL,
"opened_at" timestamp with time zone NOT NULL,
"stop_price" double precision,
"target_price" double precision,
"max_exit_date" text,
"status" text DEFAULT 'open' NOT NULL,
"closed_at" timestamp with time zone,
"exit_price" double precision,
"exit_fx" double precision,
"exit_reason" text,
"fees_eur" double precision DEFAULT 0 NOT NULL,
"pnl_eur" double precision,
"signal_id" integer
);
--> statement-breakpoint
CREATE TABLE "push_subscriptions" (
"endpoint" text PRIMARY KEY NOT NULL,
"keys" jsonb NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL
);
--> statement-breakpoint
CREATE TABLE "rendezvous" (
"id" serial PRIMARY KEY NOT NULL,
"date" text NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"summary" text NOT NULL,
"notified_at" timestamp with time zone
);
--> statement-breakpoint
CREATE TABLE "signals" (
"id" serial PRIMARY KEY NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"date" text NOT NULL,
"symbol" text NOT NULL,
"name" text NOT NULL,
"decision" text NOT NULL,
"confidence" integer NOT NULL,
"thesis" text NOT NULL,
"risks" text NOT NULL,
"expected_move_pct" double precision NOT NULL,
"stop_pct" double precision NOT NULL,
"target_pct" double precision NOT NULL,
"horizon_days" integer NOT NULL,
"price_at_signal" double precision NOT NULL,
"currency" text NOT NULL,
"news_ids" jsonb NOT NULL,
"risk_verdict" text
);
--> statement-breakpoint
CREATE UNIQUE INDEX "equity_portfolio_date_idx" ON "equity_snapshots" USING btree ("portfolio_id","date");--> statement-breakpoint
CREATE UNIQUE INDEX "rendezvous_date_idx" ON "rendezvous" USING btree ("date");

View File

@ -0,0 +1,881 @@
{
"id": "4dbfbae0-5e55-4b56-8cc8-1bce887ea407",
"prevId": "00000000-0000-0000-0000-000000000000",
"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": "integer",
"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": "integer",
"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": {}
}
}

View File

@ -0,0 +1,13 @@
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1791720025887,
"tag": "0000_init",
"breakpoints": true
}
]
}

View File

@ -1,7 +1,10 @@
import type { NextConfig } from "next"; import type { NextConfig } from "next";
const nextConfig: NextConfig = { const nextConfig: NextConfig = {
/* config options here */ // PGlite (base locale) charge ses fichiers WebAssembly à l'exécution : on ne l'empaquette pas.
serverExternalPackages: ["@electric-sql/pglite"],
// Les fichiers de migration SQL sont lus à l'exécution : on les embarque dans les fonctions Vercel.
outputFileTracingIncludes: { "/**": ["./drizzle/**"] },
cacheComponents: true, cacheComponents: true,
partialPrefetching: true, partialPrefetching: true,
turbopack: { turbopack: {

View File

@ -6,22 +6,40 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "eslint" "lint": "eslint",
"test": "vitest run",
"test:integration": "INTEGRATION=1 vitest run",
"db:generate": "drizzle-kit generate",
"db:migrate": "drizzle-kit migrate",
"setup:env": "tsx scripts/setup-env.mts"
}, },
"dependencies": { "dependencies": {
"@anthropic-ai/sdk": "^0.133.0",
"@electric-sql/pglite": "^0.5.8",
"drizzle-orm": "^0.45.4",
"jose": "^6.2.12",
"next": "16.4.0", "next": "16.4.0",
"postgres": "^3.4.9",
"react": "19.3.0", "react": "19.3.0",
"react-dom": "19.3.0" "react-dom": "19.3.0",
"server-only": "^0.0.1",
"web-push": "^3.6.7",
"yahoo-finance2": "^4.0.3",
"zod": "^4.6.5"
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/turbopack": "^4", "@tailwindcss/turbopack": "^4",
"@types/node": "^20", "@types/node": "^20",
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",
"@types/web-push": "^3.6.4",
"drizzle-kit": "^0.31.11",
"eslint": "^9", "eslint": "^9",
"eslint-config-next": "16.4.0", "eslint-config-next": "16.4.0",
"tailwindcss": "^4", "tailwindcss": "^4",
"typescript": "^5" "tsx": "^4.23.15",
"typescript": "^5",
"vitest": "^5.0.3"
}, },
"packageManager": "pnpm@10.13.1" "packageManager": "pnpm@10.13.1"
} }

2332
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

28
public/sw.js Normal file
View File

@ -0,0 +1,28 @@
// Service worker : reçoit les notifications et ouvre l'app au bon endroit.
self.addEventListener("push", (event) => {
const data = event.data ? event.data.json() : {};
event.waitUntil(
self.registration.showNotification(data.title || "Cagnotte", {
body: data.body || "",
icon: "/pwa-icon/192",
badge: "/pwa-icon/192",
data: { url: data.url || "/" },
}),
);
});
self.addEventListener("notificationclick", (event) => {
event.notification.close();
const url = (event.notification.data && event.notification.data.url) || "/";
event.waitUntil(
self.clients.matchAll({ type: "window", includeUncontrolled: true }).then((clients) => {
for (const client of clients) {
if ("focus" in client) {
client.navigate(url);
return client.focus();
}
}
return self.clients.openWindow(url);
}),
);
});

19
scripts/check-data.mts Normal file
View File

@ -0,0 +1,19 @@
// Vérifie que les sources de cours gratuites répondent (US, Europe, ETF PEA, taux EUR/USD).
// Usage : pnpm tsx scripts/check-data.mts
import YahooFinance from "yahoo-finance2";
const yf = new YahooFinance({ suppressNotices: ["yahooSurvey"] });
const quotes = await yf.quote(["AAPL", "ASML.AS", "ESE.PA", "EURUSD=X", "MC.PA"]);
for (const q of quotes) {
console.log(q.symbol, q.regularMarketPrice, q.currency, q.marketState, q.longName);
}
const chart = await yf.chart("ESE.PA", { period1: "2026-09-01", interval: "1d" });
console.log("barres ESE.PA :", chart.quotes.length, chart.quotes.at(-1));
const search = await yf.search("ASML", { newsCount: 3, quotesCount: 1 });
console.log(search.news.map((n) => [n.title, n.publisher, n.providerPublishTime]));
const summary = await yf.quoteSummary("AAPL", { modules: ["calendarEvents"] });
console.log("prochains résultats AAPL :", JSON.stringify(summary.calendarEvents?.earnings));

10
scripts/check-news.mts Normal file
View File

@ -0,0 +1,10 @@
// Regarde la forme des actus Yahoo pour quelques actions (US et Europe).
// Usage : pnpm tsx scripts/check-news.mts
import YahooFinance from "yahoo-finance2";
const yf = new YahooFinance({ suppressNotices: ["yahooSurvey"] });
for (const q of ["AAPL", "MC.PA", "LVMH", "SAP.DE", "Airbus"]) {
const s = await yf.search(q, { newsCount: 6, quotesCount: 0 });
console.log("\n==", q);
for (const n of s.news) console.log(" -", n.relatedTickers?.join(","), "|", n.title, "|", n.providerPublishTime.toISOString());
}

View File

@ -0,0 +1,17 @@
// Vérifie que chaque action surveillée a bien un cours, en euros ou en dollars.
// Usage : pnpm tsx scripts/check-universe.mts
import YahooFinance from "yahoo-finance2";
import { UNIVERSE } from "../src/lib/universe";
const yf = new YahooFinance({ suppressNotices: ["yahooSurvey"] });
const rows = await yf.quote(UNIVERSE.map((s) => s.symbol));
const found = new Map(rows.map((r) => [r.symbol, r]));
let bad = 0;
for (const s of UNIVERSE) {
const r = found.get(s.symbol);
if (!r || r.regularMarketPrice == null || !["EUR", "USD"].includes(r.currency ?? "")) {
bad++;
console.log("PROBLEME", s.symbol, s.name, r?.currency, r?.regularMarketPrice);
}
}
console.log(`${UNIVERSE.length - bad}/${UNIVERSE.length} actions OK`);

17
scripts/mint-session.mts Normal file
View File

@ -0,0 +1,17 @@
// Outil de test : affiche un jeton de session valide (lit SESSION_SECRET dans .env.local).
// Usage : pnpm tsx scripts/mint-session.mts
import { readFileSync } from "node:fs";
import { SignJWT } from "jose";
const env = Object.fromEntries(
readFileSync(".env.local", "utf8")
.split("\n")
.filter((l) => l && !l.startsWith("#") && l.includes("="))
.map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]),
);
const token = await new SignJWT({ sub: "owner" })
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime("1d")
.sign(new TextEncoder().encode(env.SESSION_SECRET));
console.log(token);

36
scripts/setup-env.mts Normal file
View File

@ -0,0 +1,36 @@
// Génère les secrets de l'app (session, tâches planifiées, clés de notification).
// Usage : pnpm tsx scripts/setup-env.mts -> crée .env.local pour le développement
// pnpm tsx scripts/setup-env.mts --print -> affiche des valeurs neuves (à coller dans Vercel)
import { randomBytes } from "node:crypto";
import { existsSync, writeFileSync } from "node:fs";
import webpush from "web-push";
const vapid = webpush.generateVAPIDKeys();
const values = {
SESSION_SECRET: randomBytes(32).toString("hex"),
CRON_SECRET: randomBytes(24).toString("hex"),
NEXT_PUBLIC_VAPID_PUBLIC_KEY: vapid.publicKey,
VAPID_PRIVATE_KEY: vapid.privateKey,
};
if (process.argv.includes("--print")) {
for (const [k, v] of Object.entries(values)) console.log(`${k}=${v}`);
process.exit(0);
}
if (existsSync(".env.local")) {
console.log(".env.local existe déjà : rien n'a été modifié.");
process.exit(0);
}
const lines = [
"# Développement local uniquement. Ne jamais publier ce fichier.",
"APP_PASSWORD=cagnotte-local",
...Object.entries(values).map(([k, v]) => `${k}=${v}`),
"VAPID_SUBJECT=mailto:moi@example.com",
"# ANTHROPIC_API_KEY=sk-ant-... (à ajouter quand tu auras ta clé)",
"# DATABASE_URL=... (vide en local : base embarquée dans .data/)",
"",
];
writeFileSync(".env.local", lines.join("\n"), { mode: 0o600 });
console.log(".env.local créé. Mot de passe local : cagnotte-local");

View File

@ -0,0 +1,77 @@
import { Suspense } from "react";
import { connection } from "next/server";
import { PageSkeleton } from "@/components/page-skeleton";
import { Badge, Card, Empty, Page } from "@/components/ui";
import { timeAgo } from "@/lib/format";
import { recentNews } from "@/lib/news";
import { findStock } from "@/lib/universe";
const EVENT_LABELS: Record<string, string> = {
earnings: "Résultats",
guidance: "Prévisions",
contract: "Contrat",
m_and_a: "Rachat / fusion",
regulatory: "Régulation",
legal: "Justice",
management: "Direction",
product: "Produit",
analyst: "Analystes",
macro: "Économie",
opinion: "Opinion",
other: "Autre",
};
async function NewsPageContent() {
await connection();
const rows = await recentNews(48);
const important = rows.filter((n) => (n.triage?.relevance ?? 0) >= 7).sort((a, b) => (b.triage?.relevance ?? 0) - (a.triage?.relevance ?? 0));
const others = rows.filter((n) => (n.triage?.relevance ?? 0) < 7).slice(0, 60);
const item = (n: (typeof rows)[number]) => {
const t = n.triage;
return (
<li key={n.id} className="py-3">
<div className="mb-1 flex flex-wrap items-center gap-1.5">
<span className="text-xs font-semibold">{findStock(n.symbol)?.name ?? n.symbol}</span>
{t && (
<>
<Badge tone={t.direction === "positive" ? "accent" : t.direction === "negative" ? "danger" : "neutral"}>
{t.direction === "positive" ? "▲ positif" : t.direction === "negative" ? "▼ négatif" : "neutre"}
</Badge>
<Badge>{EVENT_LABELS[t.eventType] ?? t.eventType}</Badge>
<span className="num text-xs text-muted">{t.relevance}/10</span>
</>
)}
{!t && <Badge>pas encore triée</Badge>}
</div>
<a href={n.url ?? "#"} target="_blank" rel="noreferrer" className="text-sm font-medium leading-snug">
{n.title}
</a>
{t?.reason && <p className="mt-1 text-xs leading-relaxed text-muted">{t.reason}</p>}
<p className="mt-1 text-xs text-muted">
{n.publisher} · {timeAgo(n.publishedAt)}
</p>
</li>
);
};
return (
<Page title="Actus" subtitle="Les actus des 48 dernières heures, notées par l'IA de 0 à 10.">
<Card title="Importantes (7/10 et plus)">
{important.length ? <ul className="divide-y divide-line">{important.map(item)}</ul> : <Empty>Rien de marquant pour l&apos;instant.</Empty>}
</Card>
<Card title="Les autres">
{others.length ? <ul className="divide-y divide-line">{others.map(item)}</ul> : <Empty>Aucune actu collectée pour l&apos;instant.</Empty>}
</Card>
</Page>
);
}
export default function NewsPage() {
return (
<Suspense fallback={<PageSkeleton title={"Actus"} />}>
<NewsPageContent />
</Suspense>
);
}

View File

@ -0,0 +1,58 @@
import { Suspense } from "react";
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 { ResetSandbox } from "@/components/reset-sandbox";
async function SandboxPageContent() {
await connection();
const [state, closed, spend, settings] = await Promise.all([
getPortfolioState("sandbox"),
getClosedPositions("sandbox"),
getAiSpend(),
getSettings(),
]);
const perf = (state.equity / state.initialCash - 1) * 100;
return (
<Page title="Bac à sable" subtitle="Argent fictif, cours réels, frais Trade Republic. Entraîne-toi sans risque.">
<Card title="Ma cagnotte virtuelle">
<div className="flex items-end justify-between">
<p className="num text-3xl font-semibold">{eur(state.equity)}</p>
<p className={`num text-lg font-semibold ${perf >= 0 ? "text-accent" : "text-danger"}`}>{pct(perf)}</p>
</div>
<p className="num mt-1 text-sm text-muted">Liquidités : {eur(state.cash)}</p>
</Card>
<SandboxTrader askLeft={Math.max(0, settings.askDailyLimit - spend.askToday)} />
<Card title="Mes positions">
<PositionList positions={state.positions} sellable />
</Card>
{state.pendingOrders.length > 0 && (
<Card title="Ordres en attente">
<PendingOrders orders={state.pendingOrders} cancellable />
</Card>
)}
<Card title="Historique">
<ClosedList positions={closed} />
</Card>
<ResetSandbox />
</Page>
);
}
export default function SandboxPage() {
return (
<Suspense fallback={<PageSkeleton title={"Bac à sable"} />}>
<SandboxPageContent />
</Suspense>
);
}

89
src/app/(app)/ia/page.tsx Normal file
View File

@ -0,0 +1,89 @@
import { Suspense } from "react";
import { connection } from "next/server";
import { PageSkeleton } from "@/components/page-skeleton";
import { desc } from "drizzle-orm";
import { ClosedList, PendingOrders, PositionList } from "@/components/positions";
import { Badge, Card, Empty, Page } from "@/components/ui";
import { getDb, schema } from "@/lib/db";
import { eur, pct } from "@/lib/format";
import { getClosedPositions, getPortfolioState } from "@/lib/portfolio";
async function AiPageContent() {
await connection();
const db = await getDb();
const [state, closed, signals] = await Promise.all([
getPortfolioState("ai_sim"),
getClosedPositions("ai_sim", 100),
db.select().from(schema.signals).orderBy(desc(schema.signals.createdAt)).limit(20),
]);
const perf = (state.equity / state.initialCash - 1) * 100;
const wins = closed.filter((p) => (p.pnlEur ?? 0) > 0).length;
const fees = closed.reduce((s, p) => s + p.feesEur, 0);
return (
<Page title="La cagnotte de l'IA" subtitle="200 € virtuels, gérés seuls par l'IA avec exactement les règles du réel.">
<Card title="Résultat">
<div className="flex items-end justify-between">
<p className="num text-3xl font-semibold">{eur(state.equity)}</p>
<p className={`num text-lg font-semibold ${perf >= 0 ? "text-accent" : "text-danger"}`}>{pct(perf)}</p>
</div>
<div className="num mt-3 grid grid-cols-3 gap-2 text-center text-sm">
<div className="rounded-xl bg-surface-2 p-2">
<p className="text-lg font-semibold">{closed.length}</p>
<p className="text-xs text-muted">trades</p>
</div>
<div className="rounded-xl bg-surface-2 p-2">
<p className="text-lg font-semibold">{closed.length ? Math.round((wins / closed.length) * 100) : 0} %</p>
<p className="text-xs text-muted">gagnants</p>
</div>
<div className="rounded-xl bg-surface-2 p-2">
<p className="text-lg font-semibold">{eur(fees, 0)}</p>
<p className="text-xs text-muted">frais payés</p>
</div>
</div>
</Card>
<Card title="Position en cours">
<PositionList positions={state.positions} />
{state.pendingOrders.length > 0 && (
<div className="mt-3">
<PendingOrders orders={state.pendingOrders} />
</div>
)}
</Card>
<Card title="Dernières analyses">
{!signals.length && <Empty>Aucune analyse pour l&apos;instant. Elles arrivent chaque soir.</Empty>}
<ul className="flex flex-col gap-3">
{signals.map((s) => (
<li key={s.id} className="rounded-xl bg-surface-2 p-3 text-sm">
<div className="flex flex-wrap items-center gap-2">
<span className="font-semibold">{s.name}</span>
<Badge tone={s.decision === "buy" ? "accent" : "neutral"}>{s.decision === "buy" ? "Achat" : "On passe"}</Badge>
<span className="text-xs text-muted">
{s.date} · confiance {s.confidence} %
</span>
</div>
<p className="mt-2 leading-relaxed">{s.thesis}</p>
<p className="mt-1 leading-relaxed text-muted">⚠️ {s.risks}</p>
{s.riskVerdict && s.riskVerdict !== "accepté" && <p className="mt-1 text-xs text-warn">Contrôle des risques : {s.riskVerdict}</p>}
</li>
))}
</ul>
</Card>
<Card title="Trades terminés">
<ClosedList positions={closed} />
</Card>
</Page>
);
}
export default function AiPage() {
return (
<Suspense fallback={<PageSkeleton title={"La cagnotte de l'IA"} />}>
<AiPageContent />
</Suspense>
);
}

10
src/app/(app)/layout.tsx Normal file
View File

@ -0,0 +1,10 @@
import { Nav } from "@/components/nav";
export default function AppLayout({ children }: LayoutProps<"/">) {
return (
<>
{children}
<Nav />
</>
);
}

130
src/app/(app)/page.tsx Normal file
View File

@ -0,0 +1,130 @@
import { Suspense } from "react";
import { connection } from "next/server";
import { PageSkeleton } from "@/components/page-skeleton";
import Link from "next/link";
import { ActionCard } from "@/components/action-card";
import { Badge, Card, Delta, Empty, Page } from "@/components/ui";
import { aiEnabled, getAiSpend } from "@/lib/ai";
import { getLatestRendezvous, getPendingAdhocCards } from "@/lib/cards";
import { eur, pct, signedEur } from "@/lib/format";
import { getPortfolioState } from "@/lib/portfolio";
import { getSettings } from "@/lib/settings";
import { getGateStatus, getLeaderboard, getPea } from "@/lib/stats";
import { formatDateFr, parisDate } from "@/lib/time";
async function HomeContent() {
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 isToday = rdv?.date === parisDate();
const metCount = gate.criteria.filter((c) => c.ok).length;
return (
<Page title="Bonsoir 👋" subtitle={`Rendez-vous chaque soir de semaine à ${hh}h${mm}`}>
<Card title="Mon patrimoine">
<p className="num text-3xl font-semibold tracking-tight">{eur(total)}</p>
<div className="mt-4 grid grid-cols-2 gap-3 text-sm">
<div className="rounded-xl bg-surface-2 p-3">
<p className="text-muted">PEA · cœur</p>
<p className="num mt-1 text-lg font-semibold">{eur(pea?.value ?? 0)}</p>
{pea && pea.invested > 0 ? (
<p className="text-xs">
<Delta value={pea.gain}>{signedEur(pea.gain)}</Delta> <span className="text-muted">sur {eur(pea.invested, 0)} versés</span>
</p>
) : (
<p className="text-xs text-muted">Premier achat à venir</p>
)}
</div>
<Link href="/reel" className="rounded-xl bg-surface-2 p-3">
<p className="text-muted">Compte-titres · satellite</p>
<p className="num mt-1 text-lg font-semibold">{eur(real.equity)}</p>
<p className="text-xs text-muted">{gate.realActive ? `${real.positions.length} position(s)` : "Cagnotte en attente ›"}</p>
</Link>
</div>
</Card>
<Card
title={rdv ? `Rendez-vous · ${isToday ? "ce soir" : formatDateFr(rdv.date)}` : "Rendez-vous du soir"}
tone={rdv?.cards.some((c) => c.status === "pending") ? "accent" : undefined}
>
{!rdv && <Empty>Ton premier rendez-vous arrivera ce soir à {hh}h{mm}. L&apos;IA prépare tout pendant la journée.</Empty>}
{rdv?.summary && <p className="mb-3 whitespace-pre-line text-sm leading-relaxed">{rdv.summary}</p>}
<div className="flex flex-col gap-3">
{[...(rdv?.cards ?? []), ...adhoc].map((c) => (
<ActionCard key={c.id} id={c.id} kind={c.kind} training={c.training} status={c.status} payload={c.payload} />
))}
</div>
</Card>
<Card title="Classement depuis le début" action={<Link href="/ia" className="text-sm font-medium text-accent">Détails</Link>}>
<ol className="flex flex-col gap-2">
{board.map((row, i) => (
<li key={row.label} className="flex items-center justify-between rounded-xl bg-surface-2 px-3 py-2.5">
<span className="font-medium">
{["🥇", "🥈", "🥉"][i]} {row.label}
<span className="ml-2 text-xs font-normal text-muted">{row.detail}</span>
</span>
<Delta value={row.pct}>{pct(row.pct)}</Delta>
</li>
))}
</ol>
<p className="mt-3 text-xs text-muted">L&apos;IA et toi partez chacun de 200 € virtuels. Le S&amp;P 500, c&apos;est ce que tu aurais gagné sans rien faire.</p>
</Card>
<Card
title="Passage à l'argent réel"
action={gate.realActive ? <Badge tone="accent">Débloqué</Badge> : <Badge tone="warn">{metCount}/5 critères</Badge>}
>
{settings.realLockedReason && <p className="mb-3 text-sm text-danger">Coupe-circuit : {settings.realLockedReason}</p>}
<ul className="flex flex-col gap-2 text-sm">
{gate.criteria.map((c) => (
<li key={c.label} className="flex items-center justify-between gap-3">
<span>
{c.ok ? "✅" : "⏳"} {c.label}
</span>
<span className="num shrink-0 text-muted">
{c.value} <span className="text-xs">/ {c.target}</span>
</span>
</li>
))}
</ul>
</Card>
<Card title="Budget IA ce mois-ci">
{aiEnabled() ? (
<>
<div className="h-2 overflow-hidden rounded-full bg-surface-2">
<div className="h-full rounded-full bg-accent" style={{ width: `${Math.min(100, (spend.monthUsd / settings.aiMonthlyBudgetUsd) * 100)}%` }} />
</div>
<p className="num mt-2 text-sm text-muted">
{spend.monthUsd.toFixed(2)} $ sur {settings.aiMonthlyBudgetUsd} $ · coût déduit des résultats de l&apos;IA
</p>
</>
) : (
<Empty>IA pas encore branchée : ajoute ta clé Anthropic (voir Réglages).</Empty>
)}
</Card>
</Page>
);
}
export default function Home() {
return (
<Suspense fallback={<PageSkeleton title={"Bonsoir 👋"} />}>
<HomeContent />
</Suspense>
);
}

View File

@ -0,0 +1,78 @@
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 { getDb, schema } from "@/lib/db";
import { eur } from "@/lib/format";
import { getClosedPositions, getPortfolioState } from "@/lib/portfolio";
import { getSettings } from "@/lib/settings";
import { getGateStatus } from "@/lib/stats";
async function RealPageContent() {
await connection();
const db = await getDb();
const settings = await getSettings();
const [state, closed, flows, gate] = 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);
return (
<Page title="Compte-titres" subtitle="Le suivi de ta vraie cagnotte chez Trade Republic.">
<Card title="Ma cagnotte réelle" action={gate.realActive ? <Badge tone="accent">Mode réel actif</Badge> : <Badge tone="warn">Simulation</Badge>}>
<p className="num text-3xl font-semibold">{eur(state.equity)}</p>
<div className="num mt-3 grid grid-cols-3 gap-2 text-center text-sm">
<div className="rounded-xl bg-surface-2 p-2">
<p className="font-semibold">{eur(state.cash, 0)}</p>
<p className="text-xs text-muted">liquidités</p>
</div>
<div className="rounded-xl bg-surface-2 p-2">
<p className="font-semibold">{eur(deposited, 0)}</p>
<p className="text-xs text-muted">versés</p>
</div>
<div className="rounded-xl bg-surface-2 p-2">
<p className="font-semibold">{eur(toPea, 0)}</p>
<p className="text-xs text-muted">partis au PEA</p>
</div>
</div>
{!settings.realDepositsStart && (
<p className="mt-3 text-sm text-muted">Indique la date de ton premier virement dans Réglages : l&apos;app ajoutera ensuite tes 50 € chaque mois.</p>
)}
{!gate.realActive && (
<p className="mt-3 text-sm text-muted">
Ton argent s&apos;accumule sans rien acheter tant que l&apos;IA n&apos;a pas prouvé en simulation qu&apos;elle bat le S&amp;P 500.
</p>
)}
</Card>
{gate.realActive && (
<Card title="Proposer mon propre trade">
<ManualRealTrade />
</Card>
)}
<Card title="Positions réelles">
{state.positions.length ? <PositionList positions={state.positions} /> : <Empty>Aucune position réelle.</Empty>}
</Card>
<Card title="Historique réel">
<ClosedList positions={closed} />
</Card>
</Page>
);
}
export default function RealPage() {
return (
<Suspense fallback={<PageSkeleton title={"Compte-titres"} />}>
<RealPageContent />
</Suspense>
);
}

View File

@ -0,0 +1,114 @@
import { Suspense } from "react";
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 { 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 (
<label className="flex flex-col gap-1 text-sm">
<span className="font-medium">{label}</span>
{children}
{hint && <span className="text-xs text-muted">{hint}</span>}
</label>
);
}
async function SettingsPageContent() {
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 (
<Page title="Réglages">
<Card title="Notifications iPhone">
<PushManager />
</Card>
<form action={saveSettings} className="flex flex-col gap-4">
<Card title="Rendez-vous et IA">
<div className="flex flex-col gap-3">
<Field label="Heure du rendez-vous" hint="Le soir, en semaine.">
<input className={inputCls} type="time" name="rendezvous" defaultValue={`${hh}:${mm}`} />
</Field>
<Field label="Budget IA mensuel ($)" hint={aiEnabled() ? "L'IA s'arrête d'elle-même si le plafond est atteint." : "⚠️ Clé Anthropic absente : l'IA est en pause."}>
<input className={inputCls} name="aiBudget" inputMode="decimal" defaultValue={s.aiMonthlyBudgetUsd} />
</Field>
</div>
</Card>
<Card title="Mon PEA (calcul automatique)">
<div className="flex flex-col gap-3">
<Field label="ETF du plan d'épargne" hint="Symbole Yahoo. Par défaut : BNP Paribas Easy S&P 500 (ESE.PA), éligible PEA.">
<input className={inputCls} name="peaSymbol" defaultValue={plan?.etfSymbol} />
</Field>
<input type="hidden" name="peaName" defaultValue={plan?.etfName} />
<div className="grid grid-cols-2 gap-2">
<Field label="Montant / mois (€)">
<input className={inputCls} name="peaAmount" inputMode="decimal" defaultValue={plan?.monthlyAmount} />
</Field>
<Field label="Jour du prélèvement">
<input className={inputCls} name="peaDay" inputMode="numeric" defaultValue={plan?.dayOfMonth} />
</Field>
</div>
<Field label="Date de début du plan">
<input className={inputCls} type="date" name="peaStart" defaultValue={plan?.startDate} />
</Field>
<Field label="Recalage (facultatif)" hint="Le nombre exact de parts affiché dans Trade Republic, si tu veux corriger un petit écart.">
<input className={inputCls} name="calibrationShares" inputMode="decimal" placeholder={plan?.calibration ? String(plan.calibration.shares) : "ex. 4,2731"} />
</Field>
</div>
</Card>
<Card title="Compte-titres (satellite)">
<div className="flex flex-col gap-3">
<div className="grid grid-cols-2 gap-2">
<Field label="Virement / mois (€)">
<input className={inputCls} name="realDeposit" inputMode="decimal" defaultValue={s.realMonthlyDeposit} />
</Field>
<Field label="Jour du virement">
<input className={inputCls} name="realDepositDay" inputMode="numeric" defaultValue={s.realDepositDay} />
</Field>
</div>
<Field label="Premier virement le" hint="Laisse vide tant que ton compte n'est pas ouvert. L'app ajoutera ensuite chaque virement toute seule.">
<input className={inputCls} type="date" name="realDepositsStart" defaultValue={s.realDepositsStart ?? ""} />
</Field>
</div>
</Card>
<button className={primaryBtn} type="submit">
Enregistrer
</button>
</form>
<Card title="Lancer à la main">
<RunNow />
</Card>
<form action={logout}>
<button className={`${secondaryBtn} w-full`} type="submit">
Se déconnecter
</button>
</form>
<p className="text-center text-xs leading-relaxed text-muted">
Outil d&apos;aide à la décision, pas un conseil en investissement. Les performances passées ne préjugent pas des performances futures.
</p>
</Page>
);
}
export default function SettingsPage() {
return (
<Suspense fallback={<PageSkeleton title={"Réglages"} />}>
<SettingsPageContent />
</Suspense>
);
}

231
src/app/actions.ts Normal file
View File

@ -0,0 +1,231 @@
"use server";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
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 { cancelOrder, getPortfolioState, placeOrder } from "@/lib/portfolio";
import { removeSubscription, saveSubscription, sendPush } from "@/lib/push";
import { getSettings, updateSettings } from "@/lib/settings";
import { addDays, parisDate } from "@/lib/time";
import { getDb, schema } from "@/lib/db";
import { eq } from "drizzle-orm";
/** Les actions serveur sont des points d'entrée publics : chacune vérifie la session. */
async function requireAuth() {
const jar = await cookies();
if (!(await isValidSession(jar.get(SESSION_COOKIE)?.value))) throw new Error("Non connecté");
}
export async function login(_prev: string | null, formData: FormData): Promise<string | null> {
const expected = process.env.APP_PASSWORD;
const given = String(formData.get("password") ?? "");
if (!expected) return "APP_PASSWORD n'est pas configuré sur le serveur.";
if (!safeEqual(given, expected)) return "Mot de passe incorrect.";
const jar = await cookies();
jar.set(SESSION_COOKIE, await createSessionToken(), {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: SESSION_DAYS * 86_400,
path: "/",
});
redirect("/");
}
export async function logout() {
const jar = await cookies();
jar.delete(SESSION_COOKIE);
redirect("/login");
}
// --- Fiches du rendez-vous -------------------------------------------------
export async function respondCard(id: number, answer: "done" | "skipped", price?: number, shares?: number) {
await requireAuth();
await respondToCard(id, answer, { price: price || undefined, shares: shares || undefined });
revalidatePath("/", "layout");
}
export async function proposeRealBuy(symbol: string, stopPct: number) {
await requireAuth();
const r = await proposeManualRealBuy(symbol, stopPct);
revalidatePath("/", "layout");
return r;
}
// --- Bac à sable -----------------------------------------------------------
export async function searchStocks(query: string): Promise<SearchHit[]> {
await requireAuth();
if (query.trim().length < 2) return [];
return searchInstruments(query.trim());
}
export async function quoteFor(symbol: string): Promise<Quote | null> {
await requireAuth();
return getQuote(symbol);
}
export async function sandboxBuy(input: {
symbol: string;
shares: number;
type: "market" | "limit";
limitPrice?: number;
stopPct?: number;
targetPct?: number;
}): Promise<{ ok: boolean; message: string }> {
await requireAuth();
const quote = await getQuote(input.symbol);
if (!quote) return { ok: false, message: "Cours introuvable." };
if (!isSupportedCurrency(quote.currency)) return { ok: false, message: "Seules les actions en euros ou en dollars sont gérées." };
const ref = input.type === "limit" && input.limitPrice ? input.limitPrice : quote.price;
try {
const r = await placeOrder({
portfolioId: "sandbox",
symbol: input.symbol,
name: quote.name,
currency: quote.currency,
side: "buy",
type: input.type,
shares: Math.floor(input.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");
return { ok: true, message: r.message };
} catch (e) {
return { ok: false, message: e instanceof Error ? e.message : "Erreur." };
}
}
export async function sandboxSell(positionId: number): Promise<{ ok: boolean; message: string }> {
await requireAuth();
const db = await getDb();
const [pos] = await db.select().from(schema.positions).where(eq(schema.positions.id, positionId));
if (!pos || pos.portfolioId !== "sandbox" || pos.status !== "open") return { ok: false, message: "Position introuvable." };
const r = await placeOrder({
portfolioId: "sandbox",
symbol: pos.symbol,
name: pos.name,
currency: pos.currency,
side: "sell",
type: "market",
shares: pos.shares,
positionId: pos.id,
});
revalidatePath("/bac-a-sable");
return { ok: true, message: r.message };
}
export async function cancelSandboxOrder(orderId: number) {
await requireAuth();
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");
}
export async function resetSandbox() {
await requireAuth();
const db = await getDb();
await db.delete(schema.positions).where(eq(schema.positions.portfolioId, "sandbox"));
await db.delete(schema.orders).where(eq(schema.orders.portfolioId, "sandbox"));
await db.delete(schema.equitySnapshots).where(eq(schema.equitySnapshots.portfolioId, "sandbox"));
const s = await getPortfolioState("sandbox");
await db.update(schema.portfolios).set({ cash: s.initialCash, createdAt: new Date() }).where(eq(schema.portfolios.id, "sandbox"));
revalidatePath("/", "layout");
}
export async function askAi(symbol: string, question: string): Promise<{ ok: true; answer: AskAnswer } | { ok: false; message: string }> {
await requireAuth();
try {
const quote = await getQuote(symbol);
if (!quote) return { ok: false, message: "Cours introuvable." };
const today = parisDate();
const [bars, news, earnings] = await Promise.all([
getBars(symbol, addDays(today, -45)),
getNews(symbol).catch(() => []),
getNextEarningsDate(symbol),
]);
const answer = await askAboutStock(
{
symbol,
company: quote.name,
currency: quote.currency,
price: quote.price,
changeTodayPct: quote.changePct,
closes30d: bars.slice(-30).map((b) => ({ date: b.date, close: Math.round(b.close * 100) / 100 })),
nextEarningsDate: earnings,
news: news.slice(0, 8).map((n) => ({ title: n.title, publishedAt: n.publishedAt.toISOString() })),
today,
},
question.slice(0, 500),
);
if (!answer) return { ok: false, message: "L'IA n'a pas pu répondre. Réessaie plus tard." };
return { ok: true, answer };
} catch (e) {
if (e instanceof AiUnavailableError) return { ok: false, message: e.message };
console.error(e);
return { ok: false, message: "Erreur pendant l'analyse." };
}
}
// --- Notifications ---------------------------------------------------------
export async function subscribePush(sub: { endpoint: string; keys: { p256dh: string; auth: string } }) {
await requireAuth();
await saveSubscription(sub);
}
export async function unsubscribePush(endpoint: string) {
await requireAuth();
await removeSubscription(endpoint);
}
export async function testPush(): Promise<number> {
await requireAuth();
return sendPush("Test réussi 🎉", "Tu recevras ici ton rendez-vous du soir.", "/");
}
// --- Réglages --------------------------------------------------------------
export async function saveSettings(formData: FormData): Promise<void> {
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");
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,
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),
},
});
revalidatePath("/", "layout");
}
export async function runNow(mode: "tick" | "evening"): Promise<string[]> {
await requireAuth();
const log = mode === "evening" ? await runEvening() : await tick();
revalidatePath("/", "layout");
return log;
}

View File

@ -0,0 +1,19 @@
import { NextResponse, type NextRequest } from "next/server";
import { safeEqual } from "@/lib/auth";
import { tick } from "@/lib/jobs";
export const maxDuration = 300;
/** Appelé toutes les 30 minutes par GitHub Actions avec l'en-tête « Authorization: Bearer CRON_SECRET ». */
async function handle(request: NextRequest) {
const expected = process.env.CRON_SECRET;
const given = request.headers.get("authorization")?.replace(/^Bearer /, "") ?? "";
if (!expected || !safeEqual(given, expected)) {
return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
}
const log = await tick();
return NextResponse.json({ ok: true, log });
}
export const GET = handle;
export const POST = handle;

9
src/app/apple-icon.tsx Normal file
View File

@ -0,0 +1,9 @@
import { ImageResponse } from "next/og";
import { IconArt } from "@/lib/icon-art";
export const size = { width: 180, height: 180 };
export const contentType = "image/png";
export default function AppleIcon() {
return new ImageResponse(<IconArt size={180} />, size);
}

View File

@ -1,26 +1,64 @@
@import "tailwindcss"; @import "tailwindcss";
:root { :root {
--background: #ffffff; --bg: #f6f5f1;
--foreground: #171717; --surface: #ffffff;
} --surface-2: #efede7;
--border: #e2dfd6;
@theme inline { --text: #1b1a17;
--color-background: var(--background); --muted: #6d6a62;
--color-foreground: var(--foreground); --accent: #0f7b5f;
--font-sans: var(--font-geist-sans); --accent-soft: #dcefe7;
--font-mono: var(--font-geist-mono); --danger: #b4233c;
--danger-soft: #f8e1e5;
--warn: #9a6200;
--warn-soft: #f7ecd6;
} }
@media (prefers-color-scheme: dark) { @media (prefers-color-scheme: dark) {
:root { :root {
--background: #0a0a0a; --bg: #0f1012;
--foreground: #ededed; --surface: #17191c;
--surface-2: #1f2226;
--border: #2a2e33;
--text: #ecebe6;
--muted: #9a988f;
--accent: #3ccf9f;
--accent-soft: #123a2e;
--danger: #ff6b81;
--danger-soft: #3b1820;
--warn: #f0b44c;
--warn-soft: #3a2c12;
} }
} }
body { @theme inline {
background: var(--background); --color-bg: var(--bg);
color: var(--foreground); --color-surface: var(--surface);
font-family: Arial, Helvetica, sans-serif; --color-surface-2: var(--surface-2);
--color-line: var(--border);
--color-ink: var(--text);
--color-muted: var(--muted);
--color-accent: var(--accent);
--color-accent-soft: var(--accent-soft);
--color-danger: var(--danger);
--color-danger-soft: var(--danger-soft);
--color-warn: var(--warn);
--color-warn-soft: var(--warn-soft);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
html {
background: var(--bg);
}
body {
background: var(--bg);
color: var(--text);
-webkit-tap-highlight-color: transparent;
}
.num {
font-variant-numeric: tabular-nums;
} }

View File

@ -1,29 +1,30 @@
import type { Metadata } from "next"; import type { Metadata, Viewport } from "next";
import { Geist, Geist_Mono } from "next/font/google"; import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css"; import "./globals.css";
const geistSans = Geist({ const geistSans = Geist({ variable: "--font-geist-sans", subsets: ["latin"] });
variable: "--font-geist-sans", const geistMono = Geist_Mono({ variable: "--font-geist-mono", subsets: ["latin"] });
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = { export const metadata: Metadata = {
title: "Create Next App", title: "Cagnotte",
description: "Generated by create next app", description: "Trading d'actions guidé par l'IA, en simulation d'abord.",
appleWebApp: { capable: true, title: "Cagnotte", statusBarStyle: "default" },
};
export const viewport: Viewport = {
width: "device-width",
initialScale: 1,
viewportFit: "cover",
themeColor: [
{ media: "(prefers-color-scheme: light)", color: "#f6f5f1" },
{ media: "(prefers-color-scheme: dark)", color: "#0f1012" },
],
}; };
export default function RootLayout({ children }: LayoutProps<"/">) { export default function RootLayout({ children }: LayoutProps<"/">) {
return ( return (
<html <html lang="fr" className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}>
lang="en" <body className="min-h-full font-sans">{children}</body>
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
>
<body className="min-h-full flex flex-col">{children}</body>
</html> </html>
); );
} }

View File

@ -0,0 +1,18 @@
"use client";
import { useActionState } from "react";
import { login } from "@/app/actions";
import { inputCls, primaryBtn } from "@/components/ui";
export function LoginForm() {
const [error, action, pending] = useActionState(login, null);
return (
<form action={action} className="mt-8 flex flex-col gap-3">
<input className={inputCls} type="password" name="password" placeholder="Mot de passe" autoComplete="current-password" required />
<button className={primaryBtn} disabled={pending}>
{pending ? "Connexion…" : "Entrer"}
</button>
{error && <p className="text-sm text-danger">{error}</p>}
</form>
);
}

12
src/app/login/page.tsx Normal file
View File

@ -0,0 +1,12 @@
import { LoginForm } from "./login-form";
export default function LoginPage() {
return (
<main className="mx-auto flex min-h-dvh w-full max-w-sm flex-col justify-center px-6">
<p className="text-4xl">🌱</p>
<h1 className="mt-3 text-2xl font-semibold tracking-tight">Cagnotte</h1>
<p className="mt-1 text-sm text-muted">Ton argent travaille, l&apos;IA t&apos;aide à décider.</p>
<LoginForm />
</main>
);
}

18
src/app/manifest.ts Normal file
View File

@ -0,0 +1,18 @@
import type { MetadataRoute } from "next";
export default function manifest(): MetadataRoute.Manifest {
return {
name: "Cagnotte",
short_name: "Cagnotte",
description: "Trading d'actions guidé par l'IA, en simulation d'abord.",
start_url: "/",
display: "standalone",
background_color: "#f6f5f1",
theme_color: "#0f7b5f",
lang: "fr",
icons: [
{ src: "/pwa-icon/192", sizes: "192x192", type: "image/png" },
{ src: "/pwa-icon/512", sizes: "512x512", type: "image/png" },
],
};
}

View File

@ -1,69 +0,0 @@
import Image from "next/image";
export default function Home() {
return (
<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black">
<main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
<Image
className="dark:invert h-5 w-[100px]"
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the{" "}
<code className="rounded bg-black/[.06] px-1.5 py-0.5 font-mono text-[0.9em] dark:bg-white/[.08]">
page.tsx
</code>{" "}
file.
</h1>
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
Looking for a starting point or more instructions? Head over to{" "}
<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Templates
</a>{" "}
or the{" "}
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Learning
</a>{" "}
center.
</p>
</div>
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
<a
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert h-[14px] w-4"
src="/vercel.svg"
alt="Vercel logomark"
width={16}
height={14}
/>
Deploy Now
</a>
<a
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Documentation
</a>
</div>
</main>
</div>
);
}

View File

@ -0,0 +1,10 @@
import { ImageResponse } from "next/og";
import { IconArt } from "@/lib/icon-art";
const SIZES = new Set([192, 512]);
export async function GET(_req: Request, ctx: RouteContext<"/pwa-icon/[size]">) {
const size = Number((await ctx.params).size);
if (!SIZES.has(size)) return new Response("Not found", { status: 404 });
return new ImageResponse(<IconArt size={size} />, { width: size, height: size });
}

View File

@ -0,0 +1,84 @@
"use client";
import { useState, useTransition } from "react";
import { respondCard } from "@/app/actions";
import type { ActionPayload } from "@/lib/db/schema";
import { Badge, inputCls, primaryBtn, secondaryBtn } from "./ui";
type Props = {
id: number;
kind: string;
training: boolean;
status: string;
payload: ActionPayload;
};
export function ActionCard({ id, kind, training, status, payload }: Props) {
const [pending, start] = useTransition();
const [open, setOpen] = useState(false);
const [priceVal, setPrice] = useState(payload.limitPrice?.toString() ?? "");
const [sharesVal, setShares] = useState(payload.shares?.toString() ?? "");
const [error, setError] = useState<string | null>(null);
const needsFill = !training && (kind === "buy" || kind === "sell");
const answer = (a: "done" | "skipped") =>
start(async () => {
setError(null);
try {
await respondCard(id, a, needsFill ? Number(priceVal.replace(",", ".")) : undefined, needsFill ? Number(sharesVal) : undefined);
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
}
});
const icon = { buy: "🟢", sell: "🔴", move_stop: "🛡️", to_pea: "🏦" }[kind] ?? "•";
return (
<article className="rounded-2xl border border-line bg-surface-2 p-4">
<div className="mb-2 flex flex-wrap items-center gap-2">
{training ? <Badge tone="warn">Entraînement</Badge> : <Badge tone="accent">Argent réel</Badge>}
{status !== "pending" && <Badge>{status === "done" ? (training ? "Tu l'aurais pris" : "Fait") : "Passé"}</Badge>}
</div>
<h3 className="text-base font-semibold leading-snug">
{icon} {payload.title}
</h3>
<button type="button" onClick={() => setOpen(!open)} className="mt-2 text-sm font-medium text-accent">
{open ? "Masquer le pourquoi" : "Pourquoi ?"}
</button>
{open && <p className="mt-2 whitespace-pre-line text-sm leading-relaxed text-muted">{payload.why}</p>}
<ol className="mt-3 flex list-decimal flex-col gap-1.5 pl-5 text-sm leading-relaxed">
{payload.steps.map((s) => (
<li key={s}>{s}</li>
))}
</ol>
{status === "pending" && (
<div className="mt-4 flex flex-col gap-3">
{needsFill && (
<div className="grid grid-cols-2 gap-2">
<label className="text-xs text-muted">
Prix exécuté ({payload.currency === "USD" ? "$" : "€"})
<input className={`${inputCls} mt-1`} inputMode="decimal" value={priceVal} onChange={(e) => setPrice(e.target.value)} placeholder="prix réel" />
</label>
<label className="text-xs text-muted">
Nombre d&apos;actions
<input className={`${inputCls} mt-1`} inputMode="numeric" value={sharesVal} onChange={(e) => setShares(e.target.value)} />
</label>
</div>
)}
<div className="grid grid-cols-2 gap-2">
<button className={primaryBtn} disabled={pending} onClick={() => answer("done")}>
{training ? "✅ Je l'aurais pris" : "✅ C'est fait"}
</button>
<button className={secondaryBtn} disabled={pending} onClick={() => answer("skipped")}>
❌ Je passe
</button>
</div>
{error && <p className="text-sm text-danger">{error}</p>}
</div>
)}
</article>
);
}

View File

@ -0,0 +1,66 @@
"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<SearchHit[]>([]);
const [picked, setPicked] = useState<SearchHit | null>(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 (
<div className="flex flex-col gap-3">
<p className="text-sm text-muted">Même règles que l&apos;IA : stop obligatoire, taille limitée, une seule position sous 400 €.</p>
<input
className={inputCls}
placeholder="Rechercher une action"
value={picked ? picked.name : query}
onChange={(e) => {
setPicked(null);
setQuery(e.target.value);
if (e.target.value.trim().length < 2) setHits([]);
}}
/>
{!picked && hits.length > 0 && (
<ul className="overflow-hidden rounded-xl border border-line text-sm">
{hits.map((h) => (
<li key={h.symbol}>
<button className="w-full bg-surface-2 px-3 py-2.5 text-left" onClick={() => (setPicked(h), setHits([]))}>
{h.name} <span className="text-xs text-muted">· {h.symbol}</span>
</button>
</li>
))}
</ul>
)}
<label className="text-xs text-muted">
Stop (% sous le prix, entre 4 et 10)
<input className={`${inputCls} mt-1`} inputMode="decimal" value={stopPct} onChange={(e) => setStopPct(e.target.value)} />
</label>
<button
className={primaryBtn}
disabled={!picked || pending}
onClick={() =>
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
</button>
{msg && <p className={`text-sm ${msg.ok ? "text-accent" : "text-danger"}`}>{msg.text}</p>}
</div>
);
}

38
src/components/nav.tsx Normal file
View File

@ -0,0 +1,38 @@
"use client";
import Link from "next/link";
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: "/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" },
];
export function Nav() {
const pathname = usePathname();
return (
<nav className="fixed inset-x-0 bottom-0 z-20 border-t border-line bg-surface/95 pb-[env(safe-area-inset-bottom)] backdrop-blur">
<ul className="mx-auto flex max-w-lg">
{TABS.map((t) => {
const active = t.href === "/" ? pathname === "/" : pathname.startsWith(t.href);
return (
<li key={t.href} className="flex-1">
<Link
href={t.href}
className={`flex flex-col items-center gap-1 py-2.5 text-[11px] font-medium ${active ? "text-accent" : "text-muted"}`}
>
<svg viewBox="0 0 24 24" className="h-6 w-6" fill="none" stroke="currentColor" strokeWidth={1.7} strokeLinecap="round" strokeLinejoin="round" aria-hidden>
<path d={t.icon} />
</svg>
{t.label}
</Link>
</li>
);
})}
</ul>
</nav>
);
}

View File

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

View File

@ -0,0 +1,98 @@
"use client";
import { useTransition } from "react";
import { cancelSandboxOrder, sandboxSell } from "@/app/actions";
import { eur, EXIT_REASONS, pct, price, signedEur } from "@/lib/format";
import type { Order, Position, PositionView } from "@/lib/portfolio";
import { Delta, Empty, secondaryBtn } from "./ui";
export function PositionList({ positions, sellable = false }: { positions: PositionView[]; sellable?: boolean }) {
const [pending, start] = useTransition();
if (!positions.length) return <Empty>Aucune position ouverte.</Empty>;
return (
<ul className="flex flex-col gap-2">
{positions.map((p) => (
<li key={p.id} className="rounded-xl bg-surface-2 p-3">
<div className="flex items-start justify-between gap-3">
<div>
<p className="font-semibold">{p.name}</p>
<p className="num text-xs text-muted">
{p.shares} × {price(p.entryPrice, p.currency)} → {p.price !== null ? price(p.price, p.currency) : "?"}
</p>
</div>
<div className="text-right">
<p className="num font-semibold">{eur(p.valueEur)}</p>
<Delta value={p.pnlOpenEur}>
{signedEur(p.pnlOpenEur)} ({pct(p.pnlOpenPct)})
</Delta>
</div>
</div>
{(p.stopPrice || p.targetPrice || p.maxExitDate) && (
<p className="num mt-2 text-xs text-muted">
{p.stopPrice ? `Stop ${price(p.stopPrice, p.currency)}` : ""}
{p.targetPrice ? ` · Objectif ${price(p.targetPrice, p.currency)}` : ""}
{p.maxExitDate ? ` · Sortie au plus tard le ${p.maxExitDate}` : ""}
</p>
)}
{sellable && (
<button
className={`${secondaryBtn} mt-3 h-9 w-full`}
disabled={pending}
onClick={() =>
start(async () => {
const r = await sandboxSell(p.id);
if (!r.ok) alert(r.message);
})
}
>
Vendre
</button>
)}
</li>
))}
</ul>
);
}
export function PendingOrders({ orders, cancellable = false }: { orders: Order[]; cancellable?: boolean }) {
const [pending, start] = useTransition();
return (
<ul className="flex flex-col gap-2 text-sm">
{orders.map((o) => (
<li key={o.id} className="flex items-center justify-between gap-3 rounded-xl bg-surface-2 p-3">
<span>
{o.side === "buy" ? "Achat" : "Vente"} {o.shares} {o.name}
<span className="num block text-xs text-muted">
{o.type === "limit" && o.limitPrice ? `limite ${price(o.limitPrice, o.currency)}` : "au marché"}
{o.validUntil ? ` · valable jusqu'au ${o.validUntil}` : ""}
</span>
</span>
{cancellable && (
<button className="text-sm font-medium text-danger" disabled={pending} onClick={() => start(() => cancelSandboxOrder(o.id))}>
Annuler
</button>
)}
</li>
))}
</ul>
);
}
export function ClosedList({ positions }: { positions: Position[] }) {
if (!positions.length) return <Empty>Pas encore de trade terminé.</Empty>;
return (
<ul className="flex flex-col divide-y divide-line text-sm">
{positions.map((p) => (
<li key={p.id} className="flex items-center justify-between gap-3 py-2.5">
<span>
<span className="font-medium">{p.name}</span>
<span className="block text-xs text-muted">
{p.closedAt?.toLocaleDateString("fr-FR")} · {EXIT_REASONS[p.exitReason ?? ""] ?? p.exitReason}
</span>
</span>
<Delta value={p.pnlEur ?? 0}>{signedEur(p.pnlEur ?? 0)}</Delta>
</li>
))}
</ul>
);
}

View File

@ -0,0 +1,103 @@
"use client";
import { useEffect, useState, useTransition } from "react";
import { subscribePush, testPush, unsubscribePush } from "@/app/actions";
import { primaryBtn, secondaryBtn } from "./ui";
function urlBase64ToUint8Array(base64String: string) {
const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
const raw = window.atob(base64);
return Uint8Array.from(raw, (c) => c.charCodeAt(0));
}
type Status = "loading" | "unsupported" | "needs-install" | "ready";
export function PushManager() {
const [status, setStatus] = useState<Status>("loading");
const [sub, setSub] = useState<PushSubscription | null>(null);
const [msg, setMsg] = useState<string | null>(null);
const [pending, start] = useTransition();
useEffect(() => {
const ios = /iPad|iPhone|iPod/.test(navigator.userAgent);
const standalone = window.matchMedia("(display-mode: standalone)").matches;
const supported = "serviceWorker" in navigator && "PushManager" in window;
let next: Status = "ready";
if (ios && !standalone) next = "needs-install";
else if (!supported) next = "unsupported";
// Détection faite côté navigateur uniquement, après le premier rendu.
// eslint-disable-next-line react-hooks/set-state-in-effect
setStatus(next);
if (next === "ready") {
navigator.serviceWorker
.register("/sw.js", { scope: "/", updateViaCache: "none" })
.then((reg) => reg.pushManager.getSubscription())
.then(setSub)
.catch(() => setStatus("unsupported"));
}
}, []);
const subscribe = () =>
start(async () => {
setMsg(null);
const key = process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY;
if (!key) return setMsg("Clé de notification absente côté serveur.");
const perm = await Notification.requestPermission();
if (perm !== "granted") return setMsg("Notifications refusées. Autorise-les dans Réglages iPhone → Notifications → Cagnotte.");
const reg = await navigator.serviceWorker.ready;
const s = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array(key) });
setSub(s);
await subscribePush(JSON.parse(JSON.stringify(s)));
setMsg("Notifications activées ✅");
});
if (status === "loading") return <p className="text-sm text-muted">Vérification…</p>;
if (status === "needs-install")
return (
<ol className="list-decimal pl-5 text-sm leading-relaxed">
<li>Ouvre ce site dans <b>Safari</b>.</li>
<li>
Touche le bouton <b>Partager</b> (carré avec une flèche vers le haut).
</li>
<li>
Choisis <b>« Sur l&apos;écran d&apos;accueil »</b>, puis <b>Ajouter</b>.
</li>
<li>Ouvre l&apos;app depuis la nouvelle icône, reviens ici et active les notifications.</li>
</ol>
);
if (status === "unsupported") return <p className="text-sm text-muted">Ce navigateur ne gère pas les notifications. Sur iPhone, il faut iOS 16.4 ou plus récent.</p>;
return (
<div className="flex flex-col gap-2">
{sub ? (
<>
<p className="text-sm">✅ Cet appareil recevra ton rendez-vous du soir.</p>
<div className="grid grid-cols-2 gap-2">
<button className={secondaryBtn} disabled={pending} onClick={() => start(async () => setMsg((await testPush()) ? "Notification envoyée !" : "Échec de l'envoi."))}>
Tester
</button>
<button
className={secondaryBtn}
disabled={pending}
onClick={() =>
start(async () => {
await unsubscribePush(sub.endpoint);
await sub.unsubscribe();
setSub(null);
})
}
>
Désactiver
</button>
</div>
</>
) : (
<button className={primaryBtn} disabled={pending} onClick={subscribe}>
Activer les notifications
</button>
)}
{msg && <p className="text-sm text-muted">{msg}</p>}
</div>
);
}

View File

@ -0,0 +1,19 @@
"use client";
import { useTransition } from "react";
import { resetSandbox } from "@/app/actions";
export function ResetSandbox() {
const [pending, start] = useTransition();
return (
<button
className="self-center text-sm text-muted underline"
disabled={pending}
onClick={() => {
if (confirm("Remettre ton bac à sable à 200 € et effacer son historique ?")) start(() => resetSandbox());
}}
>
Recommencer le bac à sable à zéro
</button>
);
}

View File

@ -0,0 +1,36 @@
"use client";
import { useState, useTransition } from "react";
import { runNow } from "@/app/actions";
import { secondaryBtn } from "./ui";
export function RunNow() {
const [pending, start] = useTransition();
const [log, setLog] = useState<string[] | null>(null);
const run = (mode: "tick" | "evening") =>
start(async () => {
setLog(null);
try {
setLog(await runNow(mode));
} catch (e) {
setLog([e instanceof Error ? e.message : "Erreur"]);
}
});
return (
<div className="flex flex-col gap-2">
<p className="text-sm text-muted">Normalement tout est automatique. Ces boutons servent à tester.</p>
<button className={secondaryBtn} disabled={pending} onClick={() => run("tick")}>
Mettre à jour (actus, ordres, stops)
</button>
<button className={secondaryBtn} disabled={pending} onClick={() => run("evening")}>
Préparer le rendez-vous maintenant
</button>
{pending && <p className="text-sm text-muted">En cours… (jusqu&apos;à 1-2 minutes)</p>}
{log && (
<ul className="mt-1 list-disc pl-5 text-xs text-muted">
{log.length ? log.map((l, i) => <li key={i}>{l}</li>) : <li>Rien à faire pour l&apos;instant.</li>}
</ul>
)}
</div>
);
}

View File

@ -0,0 +1,183 @@
"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<SearchHit[]>([]);
const [quote, setQuote] = useState<Quote | null>(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<AskAnswer | null>(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 (
<Card title="Acheter une action">
<input
className={inputCls}
placeholder="Rechercher : Apple, LVMH, Airbus…"
value={query}
onChange={(e) => {
setQuery(e.target.value);
if (e.target.value.trim().length < 2) setHits([]);
}}
/>
{hits.length > 0 && (
<ul className="mt-2 overflow-hidden rounded-xl border border-line">
{hits.map((h) => (
<li key={h.symbol}>
<button className="flex w-full items-center justify-between gap-3 bg-surface-2 px-3 py-2.5 text-left text-sm" onClick={() => pick(h.symbol)}>
<span>
<span className="font-medium">{h.name}</span>
<span className="block text-xs text-muted">
{h.symbol} · {h.exchange}
</span>
</span>
<Badge>{h.type === "ETF" ? "ETF" : "Action"}</Badge>
</button>
</li>
))}
</ul>
)}
{quote && (
<div className="mt-4 flex flex-col gap-3">
<div className="flex items-end justify-between">
<div>
<p className="font-semibold">{quote.name}</p>
<p className="text-xs text-muted">{quote.symbol}</p>
</div>
<div className="text-right">
<p className="num text-xl font-semibold">{price(quote.price, quote.currency)}</p>
{quote.changePct !== null && (
<p className={`num text-xs ${quote.changePct >= 0 ? "text-accent" : "text-danger"}`}>{pct(quote.changePct, 2)} aujourd&apos;hui</p>
)}
</div>
</div>
<div className="grid grid-cols-2 gap-2">
<button className={type === "market" ? primaryBtn : secondaryBtn} onClick={() => setType("market")}>
Au marché
</button>
<button className={type === "limit" ? primaryBtn : secondaryBtn} onClick={() => setType("limit")}>
Cours limité
</button>
</div>
<div className="grid grid-cols-2 gap-2">
<label className="text-xs text-muted">
Nombre d&apos;actions
<input className={`${inputCls} mt-1`} inputMode="numeric" value={shares} onChange={(e) => setShares(e.target.value)} />
</label>
{type === "limit" && (
<label className="text-xs text-muted">
Prix limite
<input className={`${inputCls} mt-1`} inputMode="decimal" value={limit} onChange={(e) => setLimit(e.target.value)} />
</label>
)}
<label className="text-xs text-muted">
Stop (% sous le prix)
<input className={`${inputCls} mt-1`} inputMode="decimal" value={stopPct} onChange={(e) => setStopPct(e.target.value)} placeholder="aucun" />
</label>
<label className="text-xs text-muted">
Objectif (% de gain)
<input className={`${inputCls} mt-1`} inputMode="decimal" value={targetPct} onChange={(e) => setTargetPct(e.target.value)} placeholder="aucun" />
</label>
</div>
<p className="num text-sm text-muted">
Coût ≈ {price(n * unit, quote.currency)} + 1 € de frais
</p>
<button
className={primaryBtn}
disabled={buying || n < 1}
onClick={() =>
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" : ""}
</button>
{message && <p className={`text-sm ${message.ok ? "text-accent" : "text-danger"}`}>{message.text}</p>}
<div className="mt-2 rounded-xl border border-line p-3">
<p className="text-sm font-semibold">🤖 Demander l&apos;avis de l&apos;IA</p>
<p className="text-xs text-muted">{askLeft} avis restant(s) aujourd&apos;hui</p>
<input
className={`${inputCls} mt-2`}
placeholder="Ex. : c'est le bon moment pour acheter ?"
value={question}
onChange={(e) => setQuestion(e.target.value)}
/>
<button
className={`${secondaryBtn} mt-2 w-full`}
disabled={asking || askLeft <= 0}
onClick={() =>
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"}
</button>
{answer && (
<div className="mt-3 flex flex-col gap-2 text-sm">
<p>
<Badge tone={answer.verdict === "acheter" ? "accent" : answer.verdict === "éviter" ? "danger" : "warn"}>
{answer.verdict.toUpperCase()}
</Badge>{" "}
<span className="text-muted">confiance {Math.round(answer.confidence)} %</span>
</p>
<p className="leading-relaxed">{answer.explanation}</p>
<p className="leading-relaxed text-muted">⚠️ {answer.risks}</p>
<button className="self-start text-sm font-medium text-accent" onClick={() => setStopPct(String(Math.round(answer.suggestedStopPct)))}>
Utiliser son stop conseillé ({Math.round(answer.suggestedStopPct)} %)
</button>
</div>
)}
</div>
</div>
)}
</Card>
);
}

54
src/components/ui.tsx Normal file
View File

@ -0,0 +1,54 @@
import type { ReactNode } from "react";
export function Page({ title, subtitle, children }: { title: string; subtitle?: ReactNode; children: ReactNode }) {
return (
<main className="mx-auto w-full max-w-lg px-4 pb-28 pt-[max(env(safe-area-inset-top),1.25rem)]">
<header className="mb-5">
<h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
{subtitle && <p className="mt-1 text-sm text-muted">{subtitle}</p>}
</header>
<div className="flex flex-col gap-4">{children}</div>
</main>
);
}
export function Card({ title, action, children, tone }: { title?: ReactNode; action?: ReactNode; children: ReactNode; tone?: "accent" | "warn" | "danger" }) {
const toneCls =
tone === "accent" ? "border-accent/40" : tone === "warn" ? "border-warn/40" : tone === "danger" ? "border-danger/40" : "border-line";
return (
<section className={`rounded-2xl border bg-surface p-4 ${toneCls}`}>
{(title || action) && (
<div className="mb-3 flex items-center justify-between gap-3">
{title && <h2 className="text-sm font-semibold uppercase tracking-wide text-muted">{title}</h2>}
{action}
</div>
)}
{children}
</section>
);
}
export function Badge({ children, tone = "neutral" }: { children: ReactNode; tone?: "neutral" | "accent" | "warn" | "danger" }) {
const cls = {
neutral: "bg-surface-2 text-muted",
accent: "bg-accent-soft text-accent",
warn: "bg-warn-soft text-warn",
danger: "bg-danger-soft text-danger",
}[tone];
return <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${cls}`}>{children}</span>;
}
export function Delta({ value, children }: { value: number; children: ReactNode }) {
return <span className={`num font-medium ${value >= 0 ? "text-accent" : "text-danger"}`}>{children}</span>;
}
export function Empty({ children }: { children: ReactNode }) {
return <p className="py-2 text-sm text-muted">{children}</p>;
}
export const buttonCls =
"inline-flex h-11 items-center justify-center rounded-xl px-4 text-sm font-semibold transition active:scale-[0.98] disabled:opacity-50";
export const primaryBtn = `${buttonCls} bg-accent text-white dark:text-black`;
export const secondaryBtn = `${buttonCls} border border-line bg-surface-2 text-ink`;
export const inputCls =
"h-11 w-full rounded-xl border border-line bg-surface-2 px-3 text-base text-ink outline-none focus:border-accent";

236
src/lib/ai.ts Normal file
View File

@ -0,0 +1,236 @@
import "server-only";
import Anthropic from "@anthropic-ai/sdk";
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
import { betaZodOutputFormat } from "@anthropic-ai/sdk/helpers/beta/zod";
import { gte } from "drizzle-orm";
import { z } from "zod";
import { getDb, schema } from "./db";
import { getSettings } from "./settings";
import { parisDate } from "./time";
/**
* L'IA en entonnoir, validée pour tenir dans 5-10 €/mois :
* - Claude Haiku 5.5 trie les actus (quelques centimes par jour)
* - Claude Sonnet 5.5 analyse en profondeur les 2-3 meilleures candidates
*/
export const TRIAGE_MODEL = "claude-haiku-5-5";
export const ANALYSIS_MODEL = "claude-sonnet-5-5";
/** Prix en $ par million de jetons (entrée, sortie). */
const PRICING: Record<string, [number, number]> = {
"claude-haiku-5-5": [0.1, 0.5],
"claude-sonnet-5-5": [2, 10],
"claude-opus-5-5": [4, 20],
};
let client: Anthropic | null = null;
export function aiEnabled(): boolean {
return Boolean(process.env.ANTHROPIC_API_KEY);
}
function getClient(): Anthropic {
if (!aiEnabled()) throw new AiUnavailableError("Clé Anthropic absente : ajoute ANTHROPIC_API_KEY.");
client ??= new Anthropic();
return client;
}
export class AiUnavailableError extends Error {}
async function recordUsage(model: string, purpose: string, usage: { input_tokens: number; output_tokens: number }) {
const [inPrice, outPrice] = PRICING[model] ?? PRICING[ANALYSIS_MODEL];
const costUsd = (usage.input_tokens * inPrice + usage.output_tokens * outPrice) / 1_000_000;
const db = await getDb();
await db.insert(schema.aiUsage).values({
model,
purpose,
inputTokens: usage.input_tokens,
outputTokens: usage.output_tokens,
costUsd,
});
}
export async function getAiSpend(): Promise<{ monthUsd: number; totalUsd: 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();
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 };
}
/** Bloque les appels si le plafond mensuel est atteint. Le tri des actus garde une petite réserve. */
async function assertBudget(purpose: "triage" | "analysis" | "ask") {
const settings = await getSettings();
const { monthUsd, askToday } = await getAiSpend();
const cap = settings.aiMonthlyBudgetUsd * (purpose === "triage" ? 1 : 0.9);
if (monthUsd >= cap) {
throw new AiUnavailableError(`Budget IA du mois atteint (${monthUsd.toFixed(2)} $ / ${settings.aiMonthlyBudgetUsd} $).`);
}
if (purpose === "ask" && askToday >= settings.askDailyLimit) {
throw new AiUnavailableError(`Limite de ${settings.askDailyLimit} avis par jour atteinte. Reviens demain !`);
}
}
export async function aiSpendSince(date: string): Promise<number> {
const db = await getDb();
const rows = await db
.select({ cost: schema.aiUsage.costUsd })
.from(schema.aiUsage)
.where(gte(schema.aiUsage.at, new Date(`${date}T00:00:00Z`)));
return rows.reduce((s, r) => s + r.cost, 0);
}
// ---------------------------------------------------------------------------
// 1. Tri des actus (Haiku)
// ---------------------------------------------------------------------------
const TriageSchema = z.object({
items: z.array(
z.object({
id: z.string(),
relevance: z.number().describe("0 à 10 : impact probable sur le cours de CETTE action dans les jours qui viennent"),
direction: z.enum(["positive", "negative", "neutral"]),
eventType: z.enum([
"earnings",
"guidance",
"contract",
"m_and_a",
"regulatory",
"legal",
"management",
"product",
"analyst",
"macro",
"opinion",
"other",
]),
severity: z.enum(["low", "medium", "high"]).describe("high = événement grave ou majeur pour l'entreprise"),
reason: z.string().describe("une phrase courte en français"),
}),
),
});
export type TriageInput = { id: string; symbol: string; company: string; title: string; publisher: string | null };
export type TriageOutput = z.infer<typeof TriageSchema>["items"][number];
const TRIAGE_SYSTEM = `Tu tries des titres d'actualité financière pour un système de trading swing (positions de quelques jours à 3 semaines) sur de grandes actions américaines et européennes.
Pour chaque titre, évalue l'impact probable sur le cours de l'action indiquée (pas sur le marché en général).
Sois exigeant : les articles d'opinion, les listes « 3 actions à acheter », les rappels de faits connus et les articles qui ne citent la société qu'en passant valent 0 à 3.
Un fait nouveau et concret (résultats, prévisions, gros contrat, rachat, enquête, départ de dirigeant, rappel de produit, décision réglementaire) vaut 6 à 10 selon son ampleur.
Renvoie un élément par titre, avec le même id.`;
export async function triageNews(batch: TriageInput[]): Promise<TriageOutput[]> {
if (!batch.length) return [];
await assertBudget("triage");
const lines = batch.map((b) => `[${b.id}] ${b.company} (${b.symbol}) — ${b.title}${b.publisher ? ` — ${b.publisher}` : ""}`);
const response = await getClient().messages.parse({
model: TRIAGE_MODEL,
max_tokens: 8000,
output_config: { effort: "low", format: zodOutputFormat(TriageSchema) },
system: TRIAGE_SYSTEM,
messages: [{ role: "user", content: lines.join("\n") }],
});
await recordUsage(TRIAGE_MODEL, "triage", response.usage);
if (response.stop_reason === "refusal" || !response.parsed_output) return [];
return response.parsed_output.items;
}
// ---------------------------------------------------------------------------
// 2. Analyse approfondie d'une candidate (Sonnet)
// ---------------------------------------------------------------------------
const AnalysisSchema = z.object({
bullCase: z.string().describe("les meilleurs arguments pour acheter, 2-3 phrases"),
bearCase: z.string().describe("les meilleurs arguments contre, 2-3 phrases"),
pricedIn: z.boolean().describe("true si le marché a déjà largement intégré la nouvelle dans le cours"),
decision: z.enum(["buy", "pass"]),
confidence: z.number().describe("0 à 100"),
expectedMovePct: z.number().describe("hausse attendue en % sur l'horizon"),
horizonDays: z.number().describe("jours de bourse, entre 2 et 15"),
stopPct: z.number().describe("distance du stop sous le prix d'achat, en %, entre 4 et 10"),
targetPct: z.number().describe("objectif de gain en %"),
thesis: z.string().describe("pour un débutant, en français simple, 2-3 phrases : pourquoi acheter"),
risks: z.string().describe("en français simple, 1-2 phrases : ce qui peut mal tourner"),
});
export type Analysis = z.infer<typeof AnalysisSchema>;
export type AnalysisContext = {
symbol: string;
company: string;
currency: string;
price: number;
changeTodayPct: number | null;
closes30d: { date: string; close: number }[];
nextEarningsDate: string | null;
news: { title: string; publisher: string | null; publishedAt: string; triage: string }[];
today: string;
};
const ANALYSIS_SYSTEM = `Tu es l'analyste d'un système de trading swing pour un particulier débutant au petit capital.
Règles du système : achat d'actions uniquement (pas de vente à découvert, pas de levier), positions de 2 à 15 jours de bourse, un stop obligatoire.
Ton travail : décider si les actualités récentes créent une opportunité d'achat que le marché n'a pas encore entièrement intégrée.
Méthode :
1. Construis le meilleur argument haussier, puis le meilleur argument baissier.
2. Regarde le mouvement du cours depuis la nouvelle : si l'action a déjà fortement monté, la nouvelle est probablement intégrée.
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.
Écris thesis et risks en français simple, sans jargon, comme pour un ami qui débute.`;
export async function analyzeCandidate(ctx: AnalysisContext): Promise<Analysis | null> {
await assertBudget("analysis");
const response = await getClient().beta.messages.parse({
model: ANALYSIS_MODEL,
max_tokens: 16000,
betas: ["server-side-fallback-2026-07-01"],
fallbacks: "default",
output_config: { effort: "medium", format: betaZodOutputFormat(AnalysisSchema) },
system: ANALYSIS_SYSTEM,
messages: [{ role: "user", content: `Données (JSON) :\n${JSON.stringify(ctx, null, 1)}` }],
});
await recordUsage(response.model, "analysis", response.usage);
if (response.stop_reason === "refusal") return null;
return response.parsed_output ?? null;
}
// ---------------------------------------------------------------------------
// 3. « Demande à l'IA » depuis le bac à sable (Sonnet)
// ---------------------------------------------------------------------------
const AskSchema = z.object({
verdict: z.enum(["acheter", "attendre", "éviter"]),
confidence: z.number().describe("0 à 100"),
explanation: z.string().describe("3-5 phrases en français simple"),
risks: z.string().describe("1-2 phrases"),
suggestedStopPct: z.number().describe("stop conseillé en % sous le prix actuel, entre 4 et 10"),
});
export type AskAnswer = z.infer<typeof AskSchema>;
export async function askAboutStock(ctx: Omit<AnalysisContext, "news"> & { news: { title: string; publishedAt: string }[] }, question: string): Promise<AskAnswer | null> {
await assertBudget("ask");
const response = await getClient().beta.messages.parse({
model: ANALYSIS_MODEL,
max_tokens: 8000,
betas: ["server-side-fallback-2026-07-01"],
fallbacks: "default",
output_config: { effort: "low", format: betaZodOutputFormat(AskSchema) },
system: `${ANALYSIS_SYSTEM}\n\nIci, l'utilisateur s'entraîne dans son bac à sable (argent fictif) et te demande ton avis. Réponds honnêtement, y compris pour lui dire d'attendre. Ce n'est pas un conseil financier personnalisé.`,
messages: [
{ role: "user", content: `Question : ${question || "Que penses-tu d'acheter cette action maintenant ?"}\n\nDonnées (JSON) :\n${JSON.stringify(ctx, null, 1)}` },
],
});
await recordUsage(response.model, "ask", response.usage);
if (response.stop_reason === "refusal") return null;
return response.parsed_output ?? null;
}

View File

@ -0,0 +1,138 @@
/**
* Test d'intégration : vraie base (PGlite temporaire) + vrais cours Yahoo.
* Lancer avec : pnpm test:integration
*/
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { eq } from "drizzle-orm";
import { beforeAll, describe, expect, it } from "vitest";
process.env.PGLITE_DIR = mkdtempSync(path.join(tmpdir(), "cagnotte-test-"));
delete process.env.DATABASE_URL;
delete process.env.ANTHROPIC_API_KEY;
const { getDb, schema } = await import("./db");
const { ensureSetup } = await import("./settings");
const { collectNews } = await import("./news");
const { getPortfolioState, placeOrder, processAll } = await import("./portfolio");
const { getQuote } = await import("./market");
const { respondToCard } = await import("./cards");
const { runEvening } = await import("./jobs");
const { getGateStatus, getPea, getLeaderboard } = await import("./stats");
const { addDays, parisDate } = await import("./time");
describe("intégration", () => {
beforeAll(async () => {
await ensureSetup();
});
it("crée les trois portefeuilles", async () => {
const s = await getPortfolioState("sandbox");
expect(s.cash).toBe(200);
expect((await getPortfolioState("real")).cash).toBe(0);
});
it("collecte des actus réelles", async () => {
const n = await collectNews(["AAPL", "AIR.PA"]);
expect(n).toBeGreaterThan(0);
});
it("exécute un ordre limite à partir des barres journalières, puis déclenche le stop", async () => {
const db = await getDb();
const quote = (await getQuote("KO"))!;
const { order } = await placeOrder({
portfolioId: "sandbox",
symbol: "KO",
name: "Coca-Cola",
currency: quote.currency,
side: "buy",
type: "limit",
shares: 2,
limitPrice: quote.price * 1.2,
stopPrice: quote.price * 0.5,
validUntil: addDays(parisDate(), 5),
});
// On antidate l'ordre de 5 jours : les barres suivantes passent forcément sous la limite.
await db
.update(schema.orders)
.set({ status: "pending", createdAt: new Date(Date.now() - 5 * 86_400_000) })
.where(eq(schema.orders.id, order.id));
await db.delete(schema.positions).where(eq(schema.positions.portfolioId, "sandbox"));
await db.update(schema.portfolios).set({ cash: 200 }).where(eq(schema.portfolios.id, "sandbox"));
const log = await processAll();
expect(log.join(" ")).toContain("Ordre exécuté");
let s = await getPortfolioState("sandbox");
expect(s.positions).toHaveLength(1);
expect(s.cash).toBeLessThan(200);
// Stop au-dessus du cours, position antidatée : le stop doit partir.
await db
.update(schema.positions)
.set({ stopPrice: quote.price * 2, openedAt: new Date(Date.now() - 5 * 86_400_000) })
.where(eq(schema.positions.id, s.positions[0].id));
const log2 = await processAll();
expect(log2.join(" ")).toContain("stop");
s = await getPortfolioState("sandbox");
expect(s.positions).toHaveLength(0);
const [closed] = await db.select().from(schema.positions).where(eq(schema.positions.portfolioId, "sandbox"));
expect(closed.exitReason).toBe("stop");
expect(closed.feesEur).toBe(2);
});
it("enregistre un achat réel confirmé puis sa vente", async () => {
const db = await getDb();
await db.update(schema.portfolios).set({ cash: 300 }).where(eq(schema.portfolios.id, "real"));
const [card] = await db
.insert(schema.actions)
.values({
rendezvousId: 0,
kind: "buy",
training: false,
symbol: "KO",
payload: { title: "Acheter", why: "", steps: [], name: "Coca-Cola", currency: "USD", shares: 3, limitPrice: 60, stopPrice: 55 },
})
.returning();
await respondToCard(card.id, "done", { price: 61, shares: 3 });
const real = await getPortfolioState("real");
expect(real.positions).toHaveLength(1);
expect(real.positions[0].entryPrice).toBe(61);
expect(real.cash).toBeLessThan(300 - 3 * 61 * 0.8);
const [sell] = await db
.insert(schema.actions)
.values({
rendezvousId: 0,
kind: "sell",
training: false,
symbol: "KO",
payload: { title: "Vendre", why: "", steps: [], positionId: real.positions[0].id },
})
.returning();
await respondToCard(sell.id, "done", { price: 65 });
const after = await getPortfolioState("real");
expect(after.positions).toHaveLength(0);
const [pos] = await db.select().from(schema.positions).where(eq(schema.positions.portfolioId, "real"));
expect(pos.pnlEur).toBeGreaterThan(0);
});
it("prépare un rendez-vous même sans IA, et calcule PEA, classement et critères", async () => {
const log = await runEvening();
expect(log.join(" ")).toContain("Rendez-vous créé");
const db = await getDb();
const [rdv] = await db.select().from(schema.rendezvous);
expect(rdv.summary).toContain("Anthropic");
const settings = await ensureSetup();
const pea = await getPea({ ...settings, peaPlan: { ...settings.peaPlan!, startDate: addDays(parisDate(), -120) } });
expect(pea!.invested).toBeGreaterThanOrEqual(150);
expect(pea!.value).toBeGreaterThan(0);
const gate = await getGateStatus();
expect(gate.criteria).toHaveLength(5);
expect(gate.unlocked).toBe(false);
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"]);
});
});

38
src/lib/auth.ts Normal file
View File

@ -0,0 +1,38 @@
import { jwtVerify, SignJWT } from "jose";
/** Accès protégé par un mot de passe unique (APP_PASSWORD), session de 90 jours. */
export const SESSION_COOKIE = "session";
export const SESSION_DAYS = 90;
function secret(): Uint8Array {
const s = process.env.SESSION_SECRET;
if (!s || s.length < 32) throw new Error("SESSION_SECRET manquant (32 caractères minimum).");
return new TextEncoder().encode(s);
}
export async function createSessionToken(): Promise<string> {
return new SignJWT({ sub: "owner" })
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime(`${SESSION_DAYS}d`)
.sign(secret());
}
export async function isValidSession(token: string | undefined): Promise<boolean> {
if (!token) return false;
try {
await jwtVerify(token, secret());
return true;
} catch {
return false;
}
}
/** Comparaison à temps constant pour ne pas révéler le mot de passe par chronométrage. */
export function safeEqual(a: string, b: string): boolean {
const ea = new TextEncoder().encode(a);
const eb = new TextEncoder().encode(b);
let diff = ea.length ^ eb.length;
for (let i = 0; i < Math.max(ea.length, eb.length); i++) diff |= (ea[i] ?? 0) ^ (eb[i] ?? 0);
return diff === 0;
}

127
src/lib/cards.ts Normal file
View File

@ -0,0 +1,127 @@
import "server-only";
import { desc, eq } from "drizzle-orm";
import { getDb, schema } from "./db";
import { FEE_EUR } from "./engine/fills";
import { checkBuy } from "./engine/risk";
import { getFxToEur, getNextEarningsDate, getQuote, isSupportedCurrency } from "./market";
import { closePosition, getPortfolioState } from "./portfolio";
import { parisDate } from "./time";
export type Card = typeof schema.actions.$inferSelect;
export async function getLatestRendezvous() {
const db = await getDb();
const [rdv] = await db.select().from(schema.rendezvous).orderBy(desc(schema.rendezvous.date)).limit(1);
if (!rdv) return null;
const cards = await db.select().from(schema.actions).where(eq(schema.actions.rendezvousId, rdv.id));
return { ...rdv, cards };
}
export async function getPendingAdhocCards(): Promise<Card[]> {
const db = await getDb();
const rows = await db.select().from(schema.actions).where(eq(schema.actions.rendezvousId, 0));
return rows.filter((r) => r.status === "pending");
}
/**
* Réponse à une fiche. Pour une fiche réelle « C'est fait », on enregistre ce que tu as
* réellement fait dans Trade Republic (prix et quantité exécutés).
*/
export async function respondToCard(id: number, answer: "done" | "skipped", fill?: { price?: number; shares?: number }) {
const db = await getDb();
const [card] = await db.select().from(schema.actions).where(eq(schema.actions.id, id));
if (!card || card.status !== "pending") throw new Error("Fiche introuvable ou déjà traitée.");
if (answer === "done" && !card.training) {
const p = card.payload;
if (card.kind === "buy" && card.symbol) {
const shares = fill?.shares ?? p.shares!;
const price = fill?.price ?? p.limitPrice!;
const fx = (await getFxToEur(p.currency!)) ?? 1;
const [pf] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, "real"));
await db.update(schema.portfolios).set({ cash: pf.cash - (shares * price * fx + FEE_EUR) }).where(eq(schema.portfolios.id, "real"));
await db.insert(schema.positions).values({
portfolioId: "real",
symbol: card.symbol,
name: p.name ?? card.symbol,
currency: p.currency!,
shares,
entryPrice: price,
entryFx: fx,
openedAt: new Date(),
stopPrice: p.stopPrice ?? null,
targetPrice: p.targetPrice ?? null,
maxExitDate: p.maxExitDate ?? null,
feesEur: FEE_EUR,
signalId: p.signalId ?? null,
});
} else if (card.kind === "sell" && p.positionId) {
const [pos] = await db.select().from(schema.positions).where(eq(schema.positions.id, p.positionId));
if (pos?.status === "open") {
const price = fill?.price ?? (await getQuote(pos.symbol))?.price ?? pos.entryPrice;
const fx = (await getFxToEur(pos.currency)) ?? pos.entryFx;
await closePosition(pos, price, fx, "manual", false);
}
} else if (card.kind === "move_stop" && p.positionId) {
await db.update(schema.positions).set({ stopPrice: p.stopPrice }).where(eq(schema.positions.id, p.positionId));
} else if (card.kind === "to_pea" && p.amountEur) {
const [pf] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, "real"));
await db.update(schema.portfolios).set({ cash: pf.cash - p.amountEur }).where(eq(schema.portfolios.id, "real"));
await db.insert(schema.cashFlows).values({ portfolioId: "real", amount: -p.amountEur, kind: "to_pea", date: parisDate() });
// Nouveau plus haut de référence : la valeur de la cagnotte juste après le virement.
const state = await getPortfolioState("real");
await db.update(schema.portfolios).set({ highWaterMark: state.equity }).where(eq(schema.portfolios.id, "real"));
}
}
await db.update(schema.actions).set({ status: answer, respondedAt: new Date() }).where(eq(schema.actions.id, id));
}
/** Un trade réel que TU proposes : il passe par le même contrôle des risques que l'IA. */
export async function proposeManualRealBuy(symbol: string, stopPct: number) {
const quote = await getQuote(symbol);
if (!quote) throw new Error("Cours introuvable.");
if (!isSupportedCurrency(quote.currency)) throw new Error("Seules les actions en euros ou en dollars sont gérées.");
const fx = (await getFxToEur(quote.currency))!;
const real = await getPortfolioState("real");
const today = parisDate();
const r = checkBuy({
equity: real.equity,
cash: real.cash,
openPositions: real.positions.length,
heldSymbols: real.positions.map((p) => p.symbol),
symbol,
priceLocal: quote.price,
fxToEur: fx,
stopPct,
targetPct: stopPct * 2,
horizonDays: 15,
nextEarningsDate: await getNextEarningsDate(symbol),
today,
});
if (!r.ok) return { ok: false as const, reason: r.reason };
const cur = quote.currency === "EUR" ? "€" : "$";
const db = await getDb();
await db.insert(schema.actions).values({
rendezvousId: 0,
kind: "buy",
training: false,
symbol,
payload: {
title: `Acheter ${r.shares} ${quote.name} (~${Math.round(r.costEur)} €) — 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)} €.`,
],
name: quote.name,
currency: quote.currency,
shares: r.shares,
limitPrice: r.limitPrice,
stopPrice: r.stopPrice,
targetPrice: r.targetPrice,
maxExitDate: r.maxExitDate,
},
});
return { ok: true as const };
}

49
src/lib/db/index.ts Normal file
View File

@ -0,0 +1,49 @@
import "server-only";
import { mkdir } from "node:fs/promises";
import path from "node:path";
import { drizzle as drizzlePg } from "drizzle-orm/postgres-js";
import { migrate as migratePg } from "drizzle-orm/postgres-js/migrator";
import postgres from "postgres";
import * as schema from "./schema";
/**
* En production : Supabase (variable DATABASE_URL, URL du « transaction pooler »).
* En local sans DATABASE_URL : PGlite, une base Postgres embarquée dans le dossier .data/.
*/
type Db = ReturnType<typeof drizzlePg<typeof schema>>;
const globalForDb = globalThis as unknown as { dbPromise?: Promise<Db> };
const MIGRATIONS = path.join(process.cwd(), "drizzle");
async function createDb(): Promise<Db> {
const url = process.env.DATABASE_URL;
if (url) {
// prepare: false est requis par le pooler de Supabase (mode transaction).
const client = postgres(url, { prepare: false, max: 3 });
const db = drizzlePg(client, { schema });
if (process.env.AUTO_MIGRATE === "1") await migratePg(db, { migrationsFolder: MIGRATIONS });
return db;
}
const { PGlite } = await import("@electric-sql/pglite");
const { drizzle: drizzleLite } = await import("drizzle-orm/pglite");
const { migrate: migrateLite } = await import("drizzle-orm/pglite/migrator");
const dir = process.env.PGLITE_DIR ?? path.join(process.cwd(), ".data");
await mkdir(dir, { recursive: true });
const client = new PGlite(path.join(dir, "pglite"));
const db = drizzleLite(client, { schema });
await migrateLite(db, { migrationsFolder: MIGRATIONS });
// Les deux pilotes exposent la même API de requêtes Drizzle.
return db as unknown as Db;
}
export function getDb(): Promise<Db> {
// En cas d'échec, on oublie la promesse pour réessayer au prochain appel.
globalForDb.dbPromise ??= createDb().catch((err) => {
globalForDb.dbPromise = undefined;
throw err;
});
return globalForDb.dbPromise;
}
export { schema };

197
src/lib/db/schema.ts Normal file
View File

@ -0,0 +1,197 @@
import {
boolean,
doublePrecision,
integer,
jsonb,
pgTable,
serial,
text,
timestamp,
uniqueIndex,
} from "drizzle-orm/pg-core";
/** Réglages et état divers, stockés en clé/valeur JSON. */
export const kv = pgTable("kv", {
key: text("key").primaryKey(),
value: jsonb("value").notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
});
/**
* Trois portefeuilles :
* - ai_sim : la cagnotte virtuelle de l'IA (sert à débloquer le réel)
* - sandbox : ton bac à sable personnel
* - real : le suivi de ton compte-titres Trade Republic (ordres passés par toi)
*/
export const portfolios = pgTable("portfolios", {
id: text("id").primaryKey(),
name: text("name").notNull(),
initialCash: doublePrecision("initial_cash").notNull(),
cash: doublePrecision("cash").notNull(),
highWaterMark: doublePrecision("high_water_mark").notNull().default(0),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});
export const positions = pgTable("positions", {
id: serial("id").primaryKey(),
portfolioId: text("portfolio_id").notNull(),
symbol: text("symbol").notNull(),
name: text("name").notNull(),
currency: text("currency").notNull(),
shares: integer("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(),
stopPrice: doublePrecision("stop_price"),
targetPrice: doublePrecision("target_price"),
maxExitDate: text("max_exit_date"), // AAAA-MM-JJ (heure de Paris)
status: text("status").notNull().default("open"), // open | closed
closedAt: timestamp("closed_at", { withTimezone: true }),
exitPrice: doublePrecision("exit_price"),
exitFx: doublePrecision("exit_fx"),
exitReason: text("exit_reason"), // stop | target | time | manual
feesEur: doublePrecision("fees_eur").notNull().default(0),
pnlEur: doublePrecision("pnl_eur"),
signalId: integer("signal_id"),
});
export const orders = pgTable("orders", {
id: serial("id").primaryKey(),
portfolioId: text("portfolio_id").notNull(),
symbol: text("symbol").notNull(),
name: text("name").notNull(),
currency: text("currency").notNull(),
side: text("side").notNull(), // buy | sell
type: text("type").notNull(), // market | limit
limitPrice: doublePrecision("limit_price"),
shares: integer("shares").notNull(),
stopPrice: doublePrecision("stop_price"), // appliqué à la position à l'exécution
targetPrice: doublePrecision("target_price"),
maxExitDate: text("max_exit_date"),
positionId: integer("position_id"), // pour une vente
signalId: integer("signal_id"),
status: text("status").notNull().default("pending"), // pending | filled | cancelled | expired
validUntil: text("valid_until"), // AAAA-MM-JJ inclus
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
filledAt: timestamp("filled_at", { withTimezone: true }),
fillPrice: doublePrecision("fill_price"),
note: text("note"),
});
/** Mouvements d'argent sur un portefeuille (virements mensuels, cliquet vers le PEA). */
export const cashFlows = pgTable("cash_flows", {
id: serial("id").primaryKey(),
portfolioId: text("portfolio_id").notNull(),
amount: doublePrecision("amount").notNull(), // + dépôt, - retrait
kind: text("kind").notNull(), // deposit | to_pea
date: text("date").notNull(), // AAAA-MM-JJ
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});
export const news = pgTable("news", {
id: text("id").primaryKey(), // empreinte du lien
symbol: text("symbol").notNull(),
title: text("title").notNull(),
publisher: text("publisher"),
url: text("url"),
publishedAt: timestamp("published_at", { withTimezone: true }).notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
triage: jsonb("triage").$type<NewsTriage>(),
triagedAt: timestamp("triaged_at", { withTimezone: true }),
alertedAt: timestamp("alerted_at", { withTimezone: true }),
});
export type NewsTriage = {
relevance: number; // 0-10
direction: "positive" | "negative" | "neutral";
eventType: string;
severity: "low" | "medium" | "high";
reason: string;
};
export const signals = pgTable("signals", {
id: serial("id").primaryKey(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
date: text("date").notNull(),
symbol: text("symbol").notNull(),
name: text("name").notNull(),
decision: text("decision").notNull(), // buy | pass
confidence: integer("confidence").notNull(),
thesis: text("thesis").notNull(),
risks: text("risks").notNull(),
expectedMovePct: doublePrecision("expected_move_pct").notNull(),
stopPct: doublePrecision("stop_pct").notNull(),
targetPct: doublePrecision("target_pct").notNull(),
horizonDays: integer("horizon_days").notNull(),
priceAtSignal: doublePrecision("price_at_signal").notNull(),
currency: text("currency").notNull(),
newsIds: jsonb("news_ids").$type<string[]>().notNull(),
riskVerdict: text("risk_verdict"),
});
export const rendezvous = pgTable(
"rendezvous",
{
id: serial("id").primaryKey(),
date: text("date").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
summary: text("summary").notNull(),
notifiedAt: timestamp("notified_at", { withTimezone: true }),
},
(t) => [uniqueIndex("rendezvous_date_idx").on(t.date)],
);
/** Fiches « recette » présentées au rendez-vous. */
export const actions = pgTable("actions", {
id: serial("id").primaryKey(),
rendezvousId: integer("rendezvous_id").notNull(),
kind: text("kind").notNull(), // buy | sell | move_stop | to_pea
training: boolean("training").notNull(), // true = entraînement (réel pas encore débloqué)
symbol: text("symbol"),
payload: jsonb("payload").$type<ActionPayload>().notNull(),
status: text("status").notNull().default("pending"), // pending | done | skipped
respondedAt: timestamp("responded_at", { withTimezone: true }),
});
export type ActionPayload = {
title: string;
why: string;
steps: string[];
name?: string;
currency?: string;
shares?: number;
limitPrice?: number;
stopPrice?: number;
targetPrice?: number;
maxExitDate?: string;
positionId?: number;
signalId?: number;
amountEur?: number;
};
export const aiUsage = pgTable("ai_usage", {
id: serial("id").primaryKey(),
at: timestamp("at", { withTimezone: true }).notNull().defaultNow(),
model: text("model").notNull(),
purpose: text("purpose").notNull(), // triage | analysis | ask
inputTokens: integer("input_tokens").notNull(),
outputTokens: integer("output_tokens").notNull(),
costUsd: doublePrecision("cost_usd").notNull(),
});
export const pushSubscriptions = pgTable("push_subscriptions", {
endpoint: text("endpoint").primaryKey(),
keys: jsonb("keys").$type<{ p256dh: string; auth: string }>().notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
});
export const equitySnapshots = pgTable(
"equity_snapshots",
{
id: serial("id").primaryKey(),
portfolioId: text("portfolio_id").notNull(),
date: text("date").notNull(),
equity: doublePrecision("equity").notNull(),
},
(t) => [uniqueIndex("equity_portfolio_date_idx").on(t.portfolioId, t.date)],
);

View File

@ -0,0 +1,178 @@
import { describe, expect, it } from "vitest";
import { evaluateBuyLimit, evaluateExit, type Bar } from "./fills";
import { checkBuy, tierFor } from "./risk";
import { computePea } from "./pea";
import { computeGate, maxDrawdownPct } from "./gate";
import { circuitBreakerTripped, computeRatchet } from "./ratchet";
import { addTradingDays } from "../time";
const bar = (date: string, open: number, high: number, low: number, close: number): Bar => ({
date,
open,
high,
low,
close,
});
describe("evaluateBuyLimit", () => {
const base = { limit: 100, createdDate: "2026-10-12", validUntil: "2026-10-13", brokerOpen: true };
it("exécute le jour même si le cours actuel est sous la limite", () => {
const r = evaluateBuyLimit({ ...base, today: "2026-10-12", bars: [], currentPrice: 99.5 });
expect(r).toEqual({ status: "filled", price: 99.5, date: "2026-10-12" });
});
it("exécute à l'ouverture si le cours ouvre sous la limite le lendemain", () => {
const r = evaluateBuyLimit({
...base,
today: "2026-10-13",
bars: [bar("2026-10-12", 101, 102, 100.5, 101), bar("2026-10-13", 98, 99, 97, 98)],
currentPrice: 98,
});
expect(r).toEqual({ status: "filled", price: 98, date: "2026-10-13" });
});
it("expire après sa date de validité", () => {
const r = evaluateBuyLimit({
...base,
today: "2026-10-14",
bars: [bar("2026-10-13", 105, 106, 104, 105)],
currentPrice: 99,
});
expect(r.status).toBe("expired");
});
it("reste en attente si Trade Republic est fermé", () => {
const r = evaluateBuyLimit({ ...base, brokerOpen: false, today: "2026-10-12", bars: [], currentPrice: 90 });
expect(r.status).toBe("pending");
});
});
describe("evaluateExit", () => {
const base = { entryDate: "2026-10-12", stop: 93, target: 110, maxExitDate: "2026-11-02", brokerOpen: true };
it("ignore la journée d'achat dans les barres", () => {
const r = evaluateExit({ ...base, today: "2026-10-12", bars: [bar("2026-10-12", 95, 96, 90, 95)], currentPrice: 95 });
expect(r).toBeNull();
});
it("déclenche le stop au prix d'ouverture en cas de trou de cotation", () => {
const r = evaluateExit({ ...base, today: "2026-10-14", bars: [bar("2026-10-13", 88, 90, 87, 89)], currentPrice: 89 });
expect(r).toEqual({ price: 88, reason: "stop", date: "2026-10-13" });
});
it("suppose le stop si stop et objectif sont touchés le même jour", () => {
const r = evaluateExit({ ...base, today: "2026-10-13", bars: [bar("2026-10-13", 100, 111, 92, 105)], currentPrice: 105 });
expect(r?.reason).toBe("stop");
});
it("prend l'objectif", () => {
const r = evaluateExit({ ...base, today: "2026-10-13", bars: [bar("2026-10-13", 104, 112, 103, 111)], currentPrice: 111 });
expect(r).toEqual({ price: 110, reason: "target", date: "2026-10-13" });
});
it("sort à la date maximale", () => {
const r = evaluateExit({ ...base, today: "2026-11-02", bars: [], currentPrice: 101 });
expect(r).toEqual({ price: 101, reason: "time", date: "2026-11-02" });
});
});
describe("contrôle des risques", () => {
const base = {
equity: 200,
cash: 200,
openPositions: 0,
heldSymbols: [],
symbol: "KO",
priceLocal: 60,
fxToEur: 1 / 1.12,
stopPct: 7,
targetPct: 12,
horizonDays: 10,
nextEarningsDate: null,
today: "2026-10-12",
};
it("paliers de positions selon la cagnotte", () => {
expect(tierFor(200).maxPositions).toBe(1);
expect(tierFor(600).maxPositions).toBe(2);
expect(tierFor(2000).maxPositions).toBe(4);
});
it("dimensionne une position avec stop et objectif", () => {
const r = checkBuy(base);
expect(r.ok).toBe(true);
if (!r.ok) return;
expect(r.shares).toBe(3);
expect(r.costEur).toBeGreaterThanOrEqual(150);
expect(r.stopPrice).toBeCloseTo(60.3 * 0.93, 1);
expect(r.maxExitDate).toBe(addTradingDays("2026-10-12", 10));
});
it("refuse une 2e position sous 400 €", () => {
const r = checkBuy({ ...base, openPositions: 1 });
expect(r.ok).toBe(false);
});
it("refuse une action trop chère pour la cagnotte", () => {
const r = checkBuy({ ...base, symbol: "ASML.AS", priceLocal: 1600, fxToEur: 1 });
expect(r.ok).toBe(false);
});
it("refuse avant des résultats trimestriels", () => {
const r = checkBuy({ ...base, nextEarningsDate: "2026-10-14" });
expect(r.ok).toBe(false);
});
it("borne le stop entre 4 et 10 %", () => {
const r = checkBuy({ ...base, stopPct: 30 });
expect(r.ok && r.stopPrice).toBeCloseTo(60.3 * 0.9, 1);
});
});
describe("PEA", () => {
it("achète des fractions de parts à chaque prélèvement", () => {
const bars = [bar("2026-08-05", 30, 30, 30, 30), bar("2026-09-07", 32, 32, 32, 32), bar("2026-10-05", 35, 35, 35, 35)];
const plan = { etfSymbol: "ESE.PA", etfName: "ETF", monthlyAmount: 50, dayOfMonth: 5, startDate: "2026-08-01" };
const r = computePea(plan, bars, 36, "2026-10-11");
expect(r.contributions.map((c) => c.date)).toEqual(["2026-08-05", "2026-09-07", "2026-10-05"]);
expect(r.invested).toBe(150);
expect(r.shares).toBeCloseTo(50 / 30 + 50 / 32 + 50 / 35, 6);
expect(r.value).toBeCloseTo(r.shares * 36, 6);
});
});
describe("déblocage du réel", () => {
it("reste verrouillé tant qu'un critère manque", () => {
const g = computeGate({
simDays: 95,
closedTrades: 22,
aiReturnPct: 9,
aiCostEur: 4,
initialCash: 200,
benchmarkReturnPct: 5,
maxDrawdownPct: 12,
actionsTotal: 40,
actionsAnswered: 30,
});
expect(g.netReturnPct).toBeCloseTo(7);
expect(g.unlocked).toBe(false); // 75 % de rendez-vous suivis seulement
});
it("calcule la pire baisse", () => {
expect(maxDrawdownPct([200, 220, 176, 230])).toBeCloseTo(20);
});
});
describe("cliquet et coupe-circuit", () => {
it("envoie la moitié des gains au-dessus du plus haut vers le PEA", () => {
expect(computeRatchet(300, 240, 300)).toEqual({ transfer: 30, newHighWaterMark: 270 });
});
it("ne fait rien sous le plus haut", () => {
expect(computeRatchet(200, 240, 200).transfer).toBe(0);
});
it("déclenche le coupe-circuit sous 50 % des versements", () => {
expect(circuitBreakerTripped(140, 300)).toBe(true);
expect(circuitBreakerTripped(160, 300)).toBe(false);
});
});

83
src/lib/engine/fills.ts Normal file
View File

@ -0,0 +1,83 @@
/**
* Moteur d'exécution simulé : décide si un ordre limite est exécuté et si une position
* touche son stop, son objectif ou sa date de sortie maximale.
* Fonctions pures, testées dans fills.test.ts.
*/
export type Bar = { date: string; open: number; high: number; low: number; close: number };
/** Frais Trade Republic par ordre, en euros. */
export const FEE_EUR = 1;
/** Écart achat/vente moyen supposé chez Trade Republic (0,1 %). */
export const SLIPPAGE = 0.001;
export function withSlippage(price: number, side: "buy" | "sell"): number {
return side === "buy" ? price * (1 + SLIPPAGE) : price * (1 - SLIPPAGE);
}
type BuyLimitInput = {
limit: number;
createdDate: string;
today: string;
validUntil: string | null;
bars: Bar[];
currentPrice: number | null;
brokerOpen: boolean;
};
export type BuyLimitResult =
| { status: "filled"; price: number; date: string }
| { status: "expired" }
| { status: "pending" };
export function evaluateBuyLimit(input: BuyLimitInput): BuyLimitResult {
const { limit, createdDate, today, validUntil, bars, currentPrice, brokerOpen } = input;
const lastDay = validUntil && validUntil < today ? validUntil : today;
// Jours complets après la création : si le plus bas est passé sous la limite, l'ordre est exécuté.
for (const bar of bars) {
if (bar.date <= createdDate || bar.date > lastDay) continue;
if (bar.low <= limit) return { status: "filled", price: Math.min(bar.open, limit), date: bar.date };
}
if (validUntil && today > validUntil) return { status: "expired" };
if (brokerOpen && currentPrice !== null && currentPrice <= limit) {
return { status: "filled", price: currentPrice, date: today };
}
return { status: "pending" };
}
type ExitInput = {
entryDate: string;
today: string;
stop: number | null;
target: number | null;
maxExitDate: string | null;
bars: Bar[];
currentPrice: number | null;
brokerOpen: boolean;
};
export type ExitResult = { price: number; reason: "stop" | "target" | "time"; date: string } | null;
export function evaluateExit(input: ExitInput): ExitResult {
const { entryDate, today, stop, target, maxExitDate, bars, currentPrice, brokerOpen } = input;
for (const bar of bars) {
if (bar.date <= entryDate || bar.date > today) continue;
// Si le stop et l'objectif sont touchés le même jour, on suppose le pire : le stop.
if (stop !== null && bar.low <= stop) {
return { price: Math.min(bar.open, stop), reason: "stop", date: bar.date };
}
if (target !== null && bar.high >= target) {
return { price: Math.max(bar.open, target), reason: "target", date: bar.date };
}
}
if (brokerOpen && currentPrice !== null) {
if (stop !== null && currentPrice <= stop) return { price: currentPrice, reason: "stop", date: today };
if (target !== null && currentPrice >= target) {
return { price: currentPrice, reason: "target", date: today };
}
if (maxExitDate && today >= maxExitDate) return { price: currentPrice, reason: "time", date: today };
}
return null;
}

57
src/lib/engine/gate.ts Normal file
View File

@ -0,0 +1,57 @@
/**
* Critères de déblocage du mode réel, validés ensemble :
* 3 mois de simulation, 20 trades clôturés, meilleur que le S&P 500 après frais et coût de l'IA,
* pire baisse inférieure à 25 %, au moins 80 % des rendez-vous suivis.
*/
export type GateInput = {
simDays: number;
closedTrades: number;
aiReturnPct: number; // rendement de la cagnotte IA, frais Trade Republic inclus
aiCostEur: number; // coût cumulé de l'IA
initialCash: number;
benchmarkReturnPct: number;
maxDrawdownPct: number;
actionsTotal: number;
actionsAnswered: number;
};
export type Criterion = { label: string; ok: boolean; value: string; target: string };
export function computeGate(i: GateInput): { unlocked: boolean; criteria: Criterion[]; netReturnPct: number } {
const netReturnPct = i.aiReturnPct - (i.aiCostEur / i.initialCash) * 100;
const discipline = i.actionsTotal === 0 ? 0 : (i.actionsAnswered / i.actionsTotal) * 100;
const criteria: Criterion[] = [
{ label: "Durée de simulation", ok: i.simDays >= 90, value: `${i.simDays} j`, target: "90 j" },
{ label: "Trades clôturés", ok: i.closedTrades >= 20, value: `${i.closedTrades}`, target: "20" },
{
label: "IA contre S&P 500 (après tous les frais)",
ok: i.closedTrades > 0 && netReturnPct > i.benchmarkReturnPct,
value: `${fmt(netReturnPct)} vs ${fmt(i.benchmarkReturnPct)}`,
target: "meilleure",
},
{ label: "Pire baisse", ok: i.maxDrawdownPct < 25, value: `${i.maxDrawdownPct.toFixed(1)} %`, target: "< 25 %" },
{
label: "Rendez-vous suivis",
ok: i.actionsTotal > 0 && discipline >= 80,
value: `${discipline.toFixed(0)} %`,
target: "≥ 80 %",
},
];
return { unlocked: criteria.every((c) => c.ok), criteria, netReturnPct };
}
/** Pire baisse depuis un plus haut, en %. */
export function maxDrawdownPct(equities: number[]): number {
let peak = -Infinity;
let worst = 0;
for (const e of equities) {
peak = Math.max(peak, e);
if (peak > 0) worst = Math.max(worst, ((peak - e) / peak) * 100);
}
return worst;
}
function fmt(n: number): string {
return `${n >= 0 ? "+" : ""}${n.toFixed(1)} %`;
}

56
src/lib/engine/pea.ts Normal file
View File

@ -0,0 +1,56 @@
/**
* Valeur du PEA calculée automatiquement à partir du plan d'épargne :
* à chaque date de prélèvement, Trade Republic achète des fractions de parts au cours du jour.
*/
import type { Bar } from "./fills";
export type PeaPlan = {
etfSymbol: string;
etfName: string;
monthlyAmount: number;
dayOfMonth: number; // 1-28
startDate: string; // AAAA-MM-JJ
/** Recalage facultatif : nombre de parts réel lu dans Trade Republic à une date donnée. */
calibration?: { date: string; shares: number } | null;
};
export type PeaResult = {
shares: number;
invested: number;
value: number;
gain: number;
contributions: { date: string; price: number; shares: number }[];
};
export function computePea(plan: PeaPlan, bars: Bar[], lastPrice: number | null, today: string): PeaResult {
const sorted = [...bars].sort((a, b) => a.date.localeCompare(b.date));
const contributions: PeaResult["contributions"] = [];
let [y, m] = plan.startDate.split("-").map(Number);
for (;;) {
const target = `${y}-${String(m).padStart(2, "0")}-${String(plan.dayOfMonth).padStart(2, "0")}`;
if (target > today) break;
if (target >= plan.startDate) {
// Exécution au premier jour de bourse à partir de la date prévue.
const bar = sorted.find((b) => b.date >= target);
if (!bar) break;
contributions.push({ date: bar.date, price: bar.close, shares: plan.monthlyAmount / bar.close });
}
m++;
if (m > 12) {
m = 1;
y++;
}
}
let shares = contributions.reduce((s, c) => s + c.shares, 0);
const cal = plan.calibration;
if (cal) {
const after = contributions.filter((c) => c.date > cal.date).reduce((s, c) => s + c.shares, 0);
shares = cal.shares + after;
}
const invested = contributions.length * plan.monthlyAmount;
const price = lastPrice ?? sorted.at(-1)?.close ?? 0;
const value = shares * price;
return { shares, invested, value, gain: value - invested, contributions };
}

19
src/lib/engine/ratchet.ts Normal file
View File

@ -0,0 +1,19 @@
/**
* Le cliquet : quand la cagnotte réelle dépasse son plus haut, la moitié du gain
* part sur le PEA (à l'abri), l'autre moitié reste pour grossir les positions.
*/
export const RATCHET_SHARE = 0.5;
export const MIN_TRANSFER_EUR = 10;
/** Coupe-circuit : si la cagnotte réelle vaut moins de 50 % de ce que tu y as versé, retour en simulation. */
export const CIRCUIT_BREAKER_RATIO = 0.5;
export function computeRatchet(equity: number, highWaterMark: number, cash: number) {
if (highWaterMark <= 0 || equity <= highWaterMark) return { transfer: 0, newHighWaterMark: Math.max(highWaterMark, equity) };
const transfer = Math.floor(Math.min((equity - highWaterMark) * RATCHET_SHARE, cash));
if (transfer < MIN_TRANSFER_EUR) return { transfer: 0, newHighWaterMark: highWaterMark };
return { transfer, newHighWaterMark: equity - transfer };
}
export function circuitBreakerTripped(equity: number, totalDeposited: number): boolean {
return totalDeposited > 0 && equity < totalDeposited * CIRCUIT_BREAKER_RATIO;
}

110
src/lib/engine/risk.ts Normal file
View File

@ -0,0 +1,110 @@
/**
* Contrôle des risques : du code fixe, jamais l'IA. Chaque achat, qu'il vienne de l'IA
* ou de toi sur le portefeuille réel, passe par ici.
*/
import { addTradingDays, daysBetween } from "../time";
import { FEE_EUR } from "./fills";
export const MIN_CONFIDENCE = 70;
export const MIN_POSITION_EUR = 150;
export const MAX_HOLD_TRADING_DAYS = 15; // 3 semaines
export const EARNINGS_BLACKOUT_DAYS = 4; // pas d'achat si des résultats tombent dans les 4 jours
export type Tier = { maxPositions: number; budgetShare: number; maxRiskPct: number | null };
/** Règles validées : 1 position sous 400 €, 2 entre 400 et 1 000 €, 4 au-delà. */
export function tierFor(equity: number): Tier {
if (equity < 400) return { maxPositions: 1, budgetShare: 1, maxRiskPct: null };
if (equity <= 1000) return { maxPositions: 2, budgetShare: 0.5, maxRiskPct: 0.05 };
return { maxPositions: 4, budgetShare: 0.25, maxRiskPct: 0.03 };
}
export function clampStopPct(stopPct: number): number {
if (!Number.isFinite(stopPct) || stopPct <= 0) return 7;
return Math.min(10, Math.max(4, stopPct));
}
export type RiskInput = {
equity: number; // valeur totale du portefeuille en €
cash: number;
openPositions: number;
heldSymbols: string[];
symbol: string;
priceLocal: number;
fxToEur: number; // 1 unité locale = fxToEur €
stopPct: number;
targetPct: number;
horizonDays: number;
nextEarningsDate: string | null;
today: string;
};
export type RiskResult =
| {
ok: true;
shares: number;
limitPrice: number;
stopPrice: number;
targetPrice: number;
maxExitDate: string;
costEur: number;
maxLossEur: number;
}
| { ok: false; reason: string };
export function checkBuy(input: RiskInput): RiskResult {
const { equity, cash, openPositions, heldSymbols, symbol, priceLocal, fxToEur, today } = input;
if (heldSymbols.includes(symbol)) return { ok: false, reason: "Tu détiens déjà cette action." };
const tier = tierFor(equity);
if (openPositions >= tier.maxPositions) {
return {
ok: false,
reason: `Nombre maximum de positions atteint (${tier.maxPositions} pour une cagnotte de ${Math.round(equity)} €).`,
};
}
if (input.nextEarningsDate) {
const days = daysBetween(today, input.nextEarningsDate);
if (days >= 0 && days <= EARNINGS_BLACKOUT_DAYS) {
return { ok: false, reason: "Résultats trimestriels dans moins de 4 jours : c'est un pari, pas une analyse." };
}
}
const stopPct = clampStopPct(input.stopPct);
const targetPct = Math.min(25, Math.max(stopPct * 1.5, input.targetPct || stopPct * 2));
// Limite légèrement au-dessus du cours pour avoir de bonnes chances d'être exécuté.
const limitPrice = round(priceLocal * 1.005);
const priceEur = limitPrice * fxToEur;
let budget = Math.min(cash, equity * tier.budgetShare) - FEE_EUR * 2;
if (tier.maxRiskPct !== null) {
budget = Math.min(budget, (equity * tier.maxRiskPct) / (stopPct / 100));
}
const shares = Math.floor(budget / priceEur);
const costEur = shares * priceEur;
if (shares < 1 || costEur < 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).`,
};
}
const stopPrice = round(limitPrice * (1 - stopPct / 100));
const targetPrice = round(limitPrice * (1 + targetPct / 100));
const hold = Math.min(MAX_HOLD_TRADING_DAYS, Math.max(2, Math.round(input.horizonDays || MAX_HOLD_TRADING_DAYS)));
return {
ok: true,
shares,
limitPrice,
stopPrice,
targetPrice,
maxExitDate: addTradingDays(today, hold),
costEur,
maxLossEur: shares * (limitPrice - stopPrice) * fxToEur + FEE_EUR * 2,
};
}
function round(n: number): number {
return Math.round(n * 100) / 100;
}

30
src/lib/format.ts Normal file
View File

@ -0,0 +1,30 @@
export function eur(n: number, digits = 2): string {
return n.toLocaleString("fr-FR", { style: "currency", currency: "EUR", minimumFractionDigits: digits, maximumFractionDigits: digits });
}
export function price(n: number, currency: string): string {
return n.toLocaleString("fr-FR", { style: "currency", currency, minimumFractionDigits: 2, maximumFractionDigits: 2 });
}
export function pct(n: number, digits = 1): string {
return `${n >= 0 ? "+" : ""}${n.toLocaleString("fr-FR", { minimumFractionDigits: digits, maximumFractionDigits: digits })} %`;
}
export function signedEur(n: number): string {
return `${n >= 0 ? "+" : ""}${eur(n)}`;
}
export function timeAgo(d: Date): string {
const min = Math.round((Date.now() - d.getTime()) / 60_000);
if (min < 60) return `il y a ${Math.max(1, min)} min`;
const h = Math.round(min / 60);
if (h < 24) return `il y a ${h} h`;
return `il y a ${Math.round(h / 24)} j`;
}
export const EXIT_REASONS: Record<string, string> = {
stop: "stop déclenché",
target: "objectif atteint",
time: "durée max. atteinte",
manual: "vente manuelle",
};

21
src/lib/icon-art.tsx Normal file
View File

@ -0,0 +1,21 @@
/** Dessin de l'icône de l'app (une pousse sur fond vert), partagé par les icônes PWA et Apple. */
export function IconArt({ size }: { size: number }) {
return (
<div
style={{
width: size,
height: size,
display: "flex",
alignItems: "center",
justifyContent: "center",
background: "linear-gradient(145deg, #11926f 0%, #0b5e47 100%)",
}}
>
<svg width={size * 0.6} height={size * 0.6} viewBox="0 0 24 24" fill="none" stroke="#ffffff" strokeWidth={1.8} strokeLinecap="round" strokeLinejoin="round">
<path d="M4 19h16" />
<path d="M6 15l4-4 3 3 5-6" />
<path d="M14 8h4v4" />
</svg>
</div>
);
}

410
src/lib/jobs.ts Normal file
View File

@ -0,0 +1,410 @@
import "server-only";
import { and, eq, isNull } from "drizzle-orm";
import { aiEnabled, analyzeCandidate, AiUnavailableError, type Analysis } from "./ai";
import { getDb, schema } from "./db";
import { checkBuy, MIN_CONFIDENCE } from "./engine/risk";
import { circuitBreakerTripped, computeRatchet } from "./engine/ratchet";
import type { ActionPayload } from "./db/schema";
import { getBars, getFxToEur, getNextEarningsDate, getQuote, getQuotes } from "./market";
import { collectNews, 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 { 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;
/**
* Appelé toutes les 30 minutes par GitHub Actions (ou à la main depuis les réglages).
* Décide seul quoi faire selon l'heure de Paris.
*/
export async function tick(now = new Date()): Promise<string[]> {
const log: string[] = [];
const settings = await getSettings();
const today = parisDate(now);
const minutes = parisMinutes(now);
log.push(...(await processAll()));
await monthlyDeposit(settings, today, log);
if (!isWeekend(today)) {
const held = await getOpenSymbols(["real", "ai_sim"]);
const last = (await getKv<number>("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()));
const lastEvening = await getKv<string>("lastEvening");
if (lastEvening !== today && minutes >= settings.rendezvousMinutes - 30) {
log.push(...(await runEvening()));
}
}
return log;
}
/** Virement mensuel vers le compte-titres (supposé programmé chez ta banque). */
async function monthlyDeposit(settings: Settings, today: string, log: string[]) {
if (!settings.realDepositsStart || today < settings.realDepositsStart) return;
const month = today.slice(0, 7);
if (Number(today.slice(8, 10)) < settings.realDepositDay) return;
if ((await getKv<string>("lastDeposit")) === month) return;
const db = await getDb();
const [p] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, "real"));
const amount = settings.realMonthlyDeposit;
await db.insert(schema.cashFlows).values({ portfolioId: "real", amount, kind: "deposit", date: today });
await db
.update(schema.portfolios)
.set({ cash: p.cash + amount, highWaterMark: p.highWaterMark + amount })
.where(eq(schema.portfolios.id, "real"));
await setKv("lastDeposit", month);
log.push(`Virement mensuel de ${amount} € ajouté au compte-titres`);
}
/** Alerte immédiate seulement pour un événement grave et négatif sur une action que tu détiens vraiment. */
async function urgentAlerts(): Promise<string[]> {
const held = await getOpenSymbols(["real"]);
if (!held.length) return [];
const db = await getDb();
const rows = await db.select().from(schema.news).where(isNull(schema.news.alertedAt));
const log: string[] = [];
for (const n of rows) {
const t = n.triage;
if (!held.includes(n.symbol) || !t || t.severity !== "high" || t.direction !== "negative") continue;
const name = findStock(n.symbol)?.name ?? n.symbol;
await sendPush(`⚠️ Alerte sur ${name}`, `${t.reason} Ton stop te protège ; regarde l'app quand tu peux.`, "/actus");
await db.update(schema.news).set({ alertedAt: new Date() }).where(eq(schema.news.id, n.id));
log.push(`Alerte envoyée : ${name}`);
}
return log;
}
type Candidate = { symbol: string; score: number; newsIds: string[] };
function pickCandidates(rows: Awaited<ReturnType<typeof recentNews>>, exclude: string[]): Candidate[] {
const bySymbol = new Map<string, Candidate>();
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;
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);
}
/** Le rendez-vous du soir : analyse, décisions, fiches et notification. */
export async function runEvening(): Promise<string[]> {
const log: string[] = [];
const db = await getDb();
const today = parisDate();
const summary: string[] = [];
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();
let settings = await getSettings();
const ai = await getPortfolioState("ai_sim");
const real = await getPortfolioState("real");
let gate = await getGateStatus(settings, ai);
if (!settings.realUnlockedAt && gate.unlocked) {
settings = await updateSettings({ realUnlockedAt: today, realLockedReason: null });
gate = { ...gate, realActive: true };
summary.push("🎉 Tous les critères sont remplis : le mode réel est débloqué.");
}
// Coupe-circuit du réel.
if (gate.realActive && circuitBreakerTripped(real.equity, await totalDeposited())) {
settings = await updateSettings({ realLockedReason: `Cagnotte réelle sous 50 % des versements le ${today}` });
gate = { ...gate, realActive: false };
summary.push("🛑 Coupe-circuit : ta cagnotte réelle a perdu plus de 50 %. Retour en simulation, plus aucune proposition réelle.");
}
// 1. Analyse des meilleures candidates.
let best: { analysis: Analysis; signalId: number; symbol: string; name: string; price: number; currency: string } | null = null;
let analyzed = 0;
if (aiEnabled()) {
const news = await recentNews(30);
const exclude = await getOpenSymbols(["ai_sim", "real"]);
const candidates = pickCandidates(news, exclude);
const results = await Promise.allSettled(candidates.map((c) => analyze(c, news, today)));
for (const r of results) {
if (r.status === "rejected") {
log.push(`Analyse échouée : ${r.reason instanceof Error ? r.reason.message : r.reason}`);
continue;
}
if (!r.value) continue;
analyzed++;
const v = r.value;
if (v.analysis.decision === "buy" && v.analysis.confidence >= MIN_CONFIDENCE && (!best || v.analysis.confidence > best.analysis.confidence)) {
best = v;
}
}
log.push(`${candidates.length} candidates, ${analyzed} analysées`);
} else {
summary.push("L'IA n'est pas encore branchée (clé Anthropic manquante).");
}
// 2. Décision pour la cagnotte IA (simulation, exécutée automatiquement) et fiche pour toi.
if (best) {
const fx = (await getFxToEur(best.currency)) ?? 1;
const earnings = await getNextEarningsDate(best.symbol);
const riskInput = (s: PortfolioState) => ({
equity: s.equity,
cash: s.cash,
openPositions: s.positions.length + s.pendingOrders.filter((o) => o.side === "buy").length,
heldSymbols: s.positions.map((p) => p.symbol),
symbol: best.symbol,
priceLocal: best.price,
fxToEur: fx,
stopPct: best.analysis.stopPct,
targetPct: best.analysis.targetPct,
horizonDays: best.analysis.horizonDays,
nextEarningsDate: earnings,
today,
});
const aiRisk = checkBuy(riskInput(ai));
await db
.update(schema.signals)
.set({ riskVerdict: aiRisk.ok ? "accepté" : aiRisk.reason })
.where(eq(schema.signals.id, best.signalId));
if (aiRisk.ok) {
await placeOrder({
portfolioId: "ai_sim",
symbol: best.symbol,
name: best.name,
currency: best.currency,
side: "buy",
type: "limit",
shares: aiRisk.shares,
limitPrice: aiRisk.limitPrice,
stopPrice: aiRisk.stopPrice,
targetPrice: aiRisk.targetPrice,
maxExitDate: aiRisk.maxExitDate,
signalId: best.signalId,
validUntil: addTradingDays(today, 1),
});
summary.push(`🤖 L'IA achète ${aiRisk.shares} ${best.name} dans sa cagnotte simulée (confiance ${best.analysis.confidence} %).`);
} else {
summary.push(`🤖 L'IA aimait ${best.name}, mais le contrôle des risques a dit non : ${aiRisk.reason}`);
}
const forCard = gate.realActive ? checkBuy(riskInput(real)) : aiRisk;
if (forCard.ok) {
const training = !gate.realActive;
await db.insert(schema.actions).values({
rendezvousId: rdv.id,
kind: "buy",
training,
symbol: best.symbol,
payload: buyPayload(best, forCard, fx, training),
});
} else if (gate.realActive) {
summary.push(`Pas de proposition réelle sur ${best.name} : ${forCard.reason}`);
}
} else if (aiEnabled()) {
summary.push(`😴 Rien d'intéressant ce soir. L'IA a étudié ${analyzed} candidate(s) et préfère attendre.`);
}
// 3. Revue des positions réelles : vendre, ou remonter le stop pour protéger un gain.
if (real.positions.length) await reviewRealPositions(real, rdv.id, today);
// 4. Le cliquet, une fois par mois.
const month = today.slice(0, 7);
if (gate.realActive && (await getKv<string>("lastRatchet")) !== month) {
const r = computeRatchet(real.equity, real.highWaterMark, real.cash);
if (r.transfer > 0) {
await db.insert(schema.actions).values({
rendezvousId: rdv.id,
kind: "to_pea",
training: false,
payload: {
title: `Vire ${r.transfer} € de gains vers ton PEA`,
why: "Ta cagnotte a dépassé son plus haut : la moitié du gain part à l'abri sur le PEA (règle du cliquet).",
steps: [
"Dans Trade Republic, ouvre ton compte-titres.",
`Retire ${r.transfer} € vers ton compte bancaire, puis verse-les sur ton PEA.`,
"Ajoute-les à ton plan d'épargne ETF S&P 500 (ou achète des parts).",
],
amountEur: r.transfer,
},
});
}
await setKv("lastRatchet", month);
}
// 5. Résumé de la simulation.
const aiAfter = await getPortfolioState("ai_sim");
for (const p of aiAfter.positions) {
summary.push(`Cagnotte IA : ${p.name} ${p.pnlOpenPct >= 0 ? "+" : ""}${p.pnlOpenPct.toFixed(1)} %`);
}
await snapshotEquity();
const cards = await db.select().from(schema.actions).where(and(eq(schema.actions.rendezvousId, rdv.id), eq(schema.actions.status, "pending")));
await db.update(schema.rendezvous).set({ summary: summary.join("\n") }).where(eq(schema.rendezvous.id, rdv.id));
const body = cards.length
? cards.map((c) => (c.training ? "Entraînement : " : "") + c.payload.title).join(" · ")
: summary[0] ?? "Rien à faire ce soir.";
const sent = await sendPush("Ton rendez-vous du soir", body, "/");
await db.update(schema.rendezvous).set({ notifiedAt: sent ? new Date() : null }).where(eq(schema.rendezvous.id, rdv.id));
log.push(`Rendez-vous créé (${cards.length} fiche(s), ${sent} notification(s))`);
return log;
}
async function analyze(c: Candidate, news: Awaited<ReturnType<typeof recentNews>>, today: string) {
const stock = findStock(c.symbol)!;
const [quote, bars, earnings] = await Promise.all([
getQuote(c.symbol),
getBars(c.symbol, addDays(today, -45)),
getNextEarningsDate(c.symbol),
]);
if (!quote) return null;
const items = news.filter((n) => n.symbol === c.symbol).slice(0, 8);
const analysis = await analyzeCandidate({
symbol: c.symbol,
company: stock.name,
currency: quote.currency,
price: quote.price,
changeTodayPct: quote.changePct,
closes30d: bars.slice(-30).map((b) => ({ date: b.date, close: Math.round(b.close * 100) / 100 })),
nextEarningsDate: earnings,
news: items.map((n) => ({
title: n.title,
publisher: n.publisher,
publishedAt: n.publishedAt.toISOString(),
triage: n.triage ? `${n.triage.eventType}, pertinence ${n.triage.relevance}/10 : ${n.triage.reason}` : "",
})),
today,
});
if (!analysis) return null;
const db = await getDb();
const [signal] = await db
.insert(schema.signals)
.values({
date: today,
symbol: c.symbol,
name: stock.name,
decision: analysis.decision,
confidence: Math.round(analysis.confidence),
thesis: analysis.thesis,
risks: analysis.risks,
expectedMovePct: analysis.expectedMovePct,
stopPct: analysis.stopPct,
targetPct: analysis.targetPct,
horizonDays: Math.round(analysis.horizonDays),
priceAtSignal: quote.price,
currency: quote.currency,
newsIds: items.map((n) => n.id),
})
.returning();
return { analysis, signalId: signal.id, symbol: c.symbol, name: stock.name, price: quote.price, currency: quote.currency };
}
function money(n: number, currency: string) {
return `${n.toFixed(2)} ${currency === "EUR" ? "€" : "$"}`;
}
function buyPayload(
best: { analysis: Analysis; signalId: number; symbol: string; name: string; currency: string },
r: Extract<ReturnType<typeof checkBuy>, { ok: true }>,
fx: number,
training: boolean,
): ActionPayload {
const isUs = best.currency === "USD";
return {
title: `Acheter ${r.shares} ${best.name} (~${Math.round(r.costEur)} €)`,
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}.`,
],
name: best.name,
currency: best.currency,
shares: r.shares,
limitPrice: r.limitPrice,
stopPrice: r.stopPrice,
targetPrice: r.targetPrice,
maxExitDate: r.maxExitDate,
signalId: best.signalId,
};
}
async function reviewRealPositions(real: PortfolioState, rdvId: number, today: string) {
const db = await getDb();
const quotes = await getQuotes(real.positions.map((p) => p.symbol));
for (const p of real.positions) {
const price = quotes.get(p.symbol)?.price;
if (!price) continue;
const sellReason =
p.targetPrice && price >= p.targetPrice
? "L'objectif est atteint : on encaisse le gain."
: p.maxExitDate && today >= p.maxExitDate
? "La durée maximale de 3 semaines est atteinte : l'effet de l'actu est épuisé."
: null;
if (sellReason) {
await db.insert(schema.actions).values({
rendezvousId: rdvId,
kind: "sell",
training: false,
symbol: p.symbol,
payload: {
title: `Vendre tes ${p.shares} ${p.name}`,
why: `${sellReason} Gain actuel : ${p.pnlOpenEur >= 0 ? "+" : ""}${p.pnlOpenEur.toFixed(2)} €.`,
steps: [
"Dans Trade Republic, annule d'abord ton ordre Stop sur cette action.",
`Puis Vendre → ${p.shares} action(s) au marché${isTradeRepublicOpen() ? "" : " (demain dès 7h30)"}.`,
],
name: p.name,
currency: p.currency,
shares: p.shares,
positionId: p.id,
},
});
} else if (p.pnlOpenPct >= 5 && p.stopPrice !== null && p.stopPrice < p.entryPrice) {
const newStop = Math.round(p.entryPrice * 100) / 100;
await db.insert(schema.actions).values({
rendezvousId: rdvId,
kind: "move_stop",
training: false,
symbol: p.symbol,
payload: {
title: `Remonter le stop de ${p.name} à ${money(newStop, p.currency)}`,
why: `Tu gagnes déjà ${p.pnlOpenPct.toFixed(1)} %. En plaçant le stop à ton prix d'achat, ce trade ne peut plus te faire perdre d'argent.`,
steps: ["Dans Trade Republic, modifie ton ordre Stop sur cette action.", `Nouveau prix de stop : ${money(newStop, p.currency)}.`],
name: p.name,
currency: p.currency,
stopPrice: newStop,
positionId: p.id,
},
});
}
}
}

127
src/lib/market.ts Normal file
View File

@ -0,0 +1,127 @@
import "server-only";
import YahooFinance from "yahoo-finance2";
import type { Bar } from "./engine/fills";
import { parisDate } from "./time";
import { findStock } from "./universe";
/** Cours, historiques, actus et dates de résultats, via Yahoo Finance (gratuit, US + Europe). */
const yf = new YahooFinance({ suppressNotices: ["yahooSurvey"] });
export type Quote = {
symbol: string;
name: string;
price: number;
currency: string;
changePct: number | null;
};
const SUPPORTED_CURRENCIES = new Set(["EUR", "USD"]);
const quoteCache = new Map<string, { at: number; quote: Quote }>();
const QUOTE_TTL_MS = 60_000;
export async function getQuotes(symbols: string[]): Promise<Map<string, Quote>> {
const out = new Map<string, Quote>();
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);
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);
}
}
return out;
}
export async function getQuote(symbol: string): Promise<Quote | null> {
return (await getQuotes([symbol])).get(symbol) ?? null;
}
/** Taux de conversion vers l'euro : 1 unité de `currency` = n €. Null si devise non gérée. */
export async function getFxToEur(currency: string): Promise<number | null> {
if (currency === "EUR") return 1;
if (currency !== "USD") return null;
const q = await getQuote("EURUSD=X");
return q ? 1 / q.price : null;
}
export function isSupportedCurrency(currency: string): boolean {
return SUPPORTED_CURRENCIES.has(currency);
}
/** Barres journalières depuis une date (incluse), datées à l'heure de Paris. */
export async function getBars(symbol: string, fromDate: string): Promise<Bar[]> {
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!,
}));
}
/** Prochaine date de résultats trimestriels (AAAA-MM-JJ), ou null si inconnue. */
export async function getNextEarningsDate(symbol: string): Promise<string | null> {
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<RawNews[]> {
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. */
export async function searchInstruments(query: string): Promise<SearchHit[]> {
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;
}

77
src/lib/news.ts Normal file
View File

@ -0,0 +1,77 @@
import "server-only";
import { desc, eq, gte, isNull } from "drizzle-orm";
import { aiEnabled, triageNews } from "./ai";
import { getDb, schema } from "./db";
import { getNews } from "./market";
import { findStock } from "./universe";
const MAX_AGE_HOURS = 48;
/** Récupère les actus récentes des actions données (6 requêtes en parallèle au maximum). */
export async function collectNews(symbols: string[]): Promise<number> {
const db = await getDb();
const cutoff = Date.now() - MAX_AGE_HOURS * 3_600_000;
let inserted = 0;
for (let i = 0; i < symbols.length; i += 6) {
const chunk = symbols.slice(i, i + 6);
const results = await Promise.allSettled(chunk.map((s) => getNews(s)));
const rows = results
.flatMap((r) => (r.status === "fulfilled" ? r.value : []))
.filter((n) => n.publishedAt.getTime() >= cutoff);
if (!rows.length) continue;
const res = await db
.insert(schema.news)
.values(rows.map((n) => ({ ...n, id: `${n.symbol}:${n.id}` })))
.onConflictDoNothing()
.returning({ id: schema.news.id });
inserted += res.length;
}
return inserted;
}
/** Fait trier par Haiku toutes les actus pas encore notées, par paquets de 40. */
export async function triagePending(): Promise<number> {
if (!aiEnabled()) return 0;
const db = await getDb();
const pending = await db.select().from(schema.news).where(isNull(schema.news.triagedAt));
let done = 0;
for (let i = 0; i < pending.length; i += 40) {
const batch = pending.slice(i, i + 40);
const out = await triageNews(
batch.map((n) => ({
id: n.id,
symbol: n.symbol,
company: findStock(n.symbol)?.name ?? n.symbol,
title: n.title,
publisher: n.publisher,
})),
);
const byId = new Map(out.map((o) => [o.id, o]));
const now = new Date();
for (const n of batch) {
const t = byId.get(n.id);
await db
.update(schema.news)
.set({
triagedAt: now,
triage: t
? { relevance: t.relevance, direction: t.direction, eventType: t.eventType, severity: t.severity, reason: t.reason }
: { relevance: 0, direction: "neutral", eventType: "other", severity: "low", reason: "Non évaluée." },
})
.where(eq(schema.news.id, n.id));
done++;
}
}
return done;
}
export type NewsRow = typeof schema.news.$inferSelect;
export async function recentNews(hours = 36): Promise<NewsRow[]> {
const db = await getDb();
return db
.select()
.from(schema.news)
.where(gte(schema.news.publishedAt, new Date(Date.now() - hours * 3_600_000)))
.orderBy(desc(schema.news.publishedAt));
}

303
src/lib/portfolio.ts Normal file
View File

@ -0,0 +1,303 @@
import "server-only";
import { and, eq, inArray } from "drizzle-orm";
import { getDb, schema } from "./db";
import { evaluateBuyLimit, evaluateExit, FEE_EUR, withSlippage, type Bar } from "./engine/fills";
import { getBars, getFxToEur, getQuotes, type Quote } from "./market";
import { addDays, isTradeRepublicOpen, parisDate } from "./time";
export type PortfolioId = "ai_sim" | "sandbox" | "real";
export type Position = typeof schema.positions.$inferSelect;
export type Order = typeof schema.orders.$inferSelect;
export type PositionView = Position & {
price: number | null;
valueEur: number;
pnlOpenEur: number;
pnlOpenPct: number;
};
export type PortfolioState = {
id: PortfolioId;
name: string;
initialCash: number;
cash: number;
equity: number;
highWaterMark: number;
createdAt: Date;
positions: PositionView[];
pendingOrders: Order[];
};
export async function getPortfolioState(id: PortfolioId, quotes?: Map<string, Quote>): Promise<PortfolioState> {
const db = await getDb();
const [p] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, id));
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<string, Quote>());
const fxUsd = open.some((x) => x.currency === "USD") ? await 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;
const valueEur = pos.shares * (price ?? pos.entryPrice) * fx;
const costEur = pos.shares * pos.entryPrice * pos.entryFx;
return { ...pos, price, valueEur, pnlOpenEur: valueEur - costEur, pnlOpenPct: ((valueEur - costEur) / costEur) * 100 };
});
const equity = p.cash + positions.reduce((s, x) => s + x.valueEur, 0);
return {
id,
name: p.name,
initialCash: p.initialCash,
cash: p.cash,
equity,
highWaterMark: p.highWaterMark,
createdAt: p.createdAt,
positions,
pendingOrders,
};
}
type NewOrder = {
portfolioId: PortfolioId;
symbol: string;
name: string;
currency: string;
side: "buy" | "sell";
type: "market" | "limit";
shares: number;
limitPrice?: number | null;
stopPrice?: number | null;
targetPrice?: number | null;
maxExitDate?: string | null;
positionId?: number | null;
signalId?: number | null;
validUntil?: string | null;
note?: string | null;
};
/** 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.");
const db = await getDb();
const [order] = await db
.insert(schema.orders)
.values({
...o,
limitPrice: o.limitPrice ?? null,
validUntil: o.validUntil ?? (o.type === "limit" ? addDays(parisDate(), 1) : null),
})
.returning();
const filled = await tryFillOrder(order);
return {
order,
filled,
message: filled
? "Ordre exécuté."
: isTradeRepublicOpen()
? "Ordre en attente : il s'exécutera si le cours atteint ta limite."
: "Trade Republic est fermé (ouvert 7h30-23h en semaine) : l'ordre s'exécutera à la réouverture.",
};
}
async function tryFillOrder(order: Order, bars?: Bar[]): Promise<boolean> {
const now = new Date();
const today = parisDate(now);
const open = isTradeRepublicOpen(now);
const quote = (await getQuotes([order.symbol])).get(order.symbol) ?? null;
const fx = await getFxToEur(order.currency);
if (fx === null) return false;
if (order.type === "market") {
if (!open || !quote) return false;
await executeOrder(order, quote.price, fx);
return true;
}
if (order.side === "buy" && order.limitPrice !== null) {
const createdDate = parisDate(order.createdAt);
const res = evaluateBuyLimit({
limit: order.limitPrice,
createdDate,
today,
validUntil: order.validUntil,
bars: bars ?? (createdDate < today ? await getBars(order.symbol, createdDate) : []),
currentPrice: quote?.price ?? null,
brokerOpen: open,
});
if (res.status === "filled") {
await executeOrder(order, res.price, fx);
return true;
}
if (res.status === "expired") {
const db = await getDb();
await db.update(schema.orders).set({ status: "expired" }).where(eq(schema.orders.id, order.id));
}
}
return false;
}
async function executeOrder(order: Order, rawPrice: number, fx: number) {
const db = await getDb();
const price = withSlippage(rawPrice, order.side as "buy" | "sell");
if (order.side === "buy") {
const [p] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, order.portfolioId));
const cost = order.shares * price * fx + FEE_EUR;
if (cost > p.cash + 0.01) {
await db.update(schema.orders).set({ status: "cancelled", note: "Pas assez de liquidités." }).where(eq(schema.orders.id, order.id));
return;
}
await db.update(schema.portfolios).set({ cash: p.cash - cost }).where(eq(schema.portfolios.id, p.id));
const [pos] = await db
.insert(schema.positions)
.values({
portfolioId: order.portfolioId,
symbol: order.symbol,
name: order.name,
currency: order.currency,
shares: order.shares,
entryPrice: price,
entryFx: fx,
openedAt: new Date(),
stopPrice: order.stopPrice,
targetPrice: order.targetPrice,
maxExitDate: order.maxExitDate,
feesEur: FEE_EUR,
signalId: order.signalId,
})
.returning();
await db
.update(schema.orders)
.set({ status: "filled", filledAt: new Date(), fillPrice: price, positionId: pos.id })
.where(eq(schema.orders.id, order.id));
} else if (order.positionId) {
const [pos] = await db.select().from(schema.positions).where(eq(schema.positions.id, order.positionId));
if (!pos || pos.status !== "open") return;
await closePosition(pos, rawPrice, fx, "manual");
await db.update(schema.orders).set({ status: "filled", filledAt: new Date(), fillPrice: price }).where(eq(schema.orders.id, order.id));
}
}
/** Clôture une position (prix brut, glissement et frais appliqués ici). */
export async function closePosition(pos: Position, rawPrice: number, fx: number, reason: string, applySlippage = true) {
const db = await getDb();
const price = applySlippage ? withSlippage(rawPrice, "sell") : rawPrice;
const proceeds = pos.shares * price * fx - FEE_EUR;
const cost = pos.shares * pos.entryPrice * pos.entryFx + pos.feesEur;
const [p] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, pos.portfolioId));
await db.update(schema.portfolios).set({ cash: p.cash + proceeds }).where(eq(schema.portfolios.id, p.id));
await db
.update(schema.positions)
.set({
status: "closed",
closedAt: new Date(),
exitPrice: price,
exitFx: fx,
exitReason: reason,
feesEur: pos.feesEur + FEE_EUR,
pnlEur: proceeds - cost,
})
.where(eq(schema.positions.id, pos.id));
}
export async function cancelOrder(orderId: number) {
const db = await getDb();
await db
.update(schema.orders)
.set({ status: "cancelled" })
.where(and(eq(schema.orders.id, orderId), eq(schema.orders.status, "pending")));
}
/**
* Passe en revue les ordres en attente et les positions ouvertes des portefeuilles simulés :
* exécutions, stops, objectifs et sorties à 3 semaines.
* Pour le portefeuille réel, seul le stop est appliqué automatiquement (il est placé chez Trade Republic) ;
* les ventes sur objectif ou par le temps te sont proposées au rendez-vous.
*/
export async function processAll(): Promise<string[]> {
const db = await getDb();
const log: string[] = [];
const pending = await db.select().from(schema.orders).where(eq(schema.orders.status, "pending"));
const open = await db.select().from(schema.positions).where(eq(schema.positions.status, "open"));
const symbols = [...new Set([...pending.map((o) => o.symbol), ...open.map((p) => p.symbol)])];
if (!symbols.length) return log;
const now = new Date();
const today = parisDate(now);
const brokerOpen = isTradeRepublicOpen(now);
const quotes = await getQuotes(symbols);
const barsCache = new Map<string, Bar[]>();
const barsFor = async (symbol: string, from: string) => {
const key = `${symbol}:${from}`;
if (!barsCache.has(key)) barsCache.set(key, from < today ? await getBars(symbol, from) : []);
return barsCache.get(key)!;
};
for (const order of pending) {
if (order.portfolioId === "real") continue;
const filled = await tryFillOrder(order, await barsFor(order.symbol, parisDate(order.createdAt)));
if (filled) log.push(`Ordre exécuté : ${order.side === "buy" ? "achat" : "vente"} ${order.shares} ${order.name} (${order.portfolioId})`);
}
for (const pos of open) {
const fx = await getFxToEur(pos.currency);
if (fx === null) continue;
const isReal = pos.portfolioId === "real";
const entryDate = parisDate(pos.openedAt);
const res = evaluateExit({
entryDate,
today,
stop: pos.stopPrice,
target: isReal ? null : pos.targetPrice,
maxExitDate: isReal ? null : pos.maxExitDate,
bars: await barsFor(pos.symbol, entryDate),
currentPrice: quotes.get(pos.symbol)?.price ?? null,
brokerOpen,
});
if (!res) continue;
await closePosition(pos, res.price, fx, res.reason);
const label = { stop: "stop déclenché", target: "objectif atteint", time: "durée maximale atteinte" }[res.reason];
log.push(`${pos.name} vendue (${label}) — ${pos.portfolioId}`);
}
return log;
}
/** Enregistre la valeur du jour de chaque portefeuille (sert au calcul de la pire baisse et aux courbes). */
export async function snapshotEquity(ids: PortfolioId[] = ["ai_sim", "sandbox", "real"]) {
const db = await getDb();
const date = parisDate();
for (const id of ids) {
const s = await getPortfolioState(id);
await db
.insert(schema.equitySnapshots)
.values({ portfolioId: id, date, equity: s.equity })
.onConflictDoUpdate({
target: [schema.equitySnapshots.portfolioId, schema.equitySnapshots.date],
set: { equity: s.equity },
});
}
}
export async function getClosedPositions(id: PortfolioId, limit = 50): Promise<Position[]> {
const db = await getDb();
const rows = await db
.select()
.from(schema.positions)
.where(and(eq(schema.positions.portfolioId, id), eq(schema.positions.status, "closed")));
return rows.sort((a, b) => (b.closedAt?.getTime() ?? 0) - (a.closedAt?.getTime() ?? 0)).slice(0, limit);
}
export async function getOpenSymbols(ids: PortfolioId[]): Promise<string[]> {
const db = await getDb();
const rows = await db
.select({ symbol: schema.positions.symbol })
.from(schema.positions)
.where(and(inArray(schema.positions.portfolioId, ids), eq(schema.positions.status, "open")));
return [...new Set(rows.map((r) => r.symbol))];
}

48
src/lib/push.ts Normal file
View File

@ -0,0 +1,48 @@
import "server-only";
import { eq } from "drizzle-orm";
import webpush from "web-push";
import { getDb, schema } from "./db";
let configured = false;
function configure(): boolean {
if (configured) return true;
const pub = process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY;
const priv = process.env.VAPID_PRIVATE_KEY;
if (!pub || !priv) return false;
webpush.setVapidDetails(process.env.VAPID_SUBJECT ?? "mailto:admin@example.com", pub, priv);
configured = true;
return true;
}
export async function saveSubscription(sub: { endpoint: string; keys: { p256dh: string; auth: string } }) {
const db = await getDb();
await db
.insert(schema.pushSubscriptions)
.values({ endpoint: sub.endpoint, keys: sub.keys })
.onConflictDoUpdate({ target: schema.pushSubscriptions.endpoint, set: { keys: sub.keys } });
}
export async function removeSubscription(endpoint: string) {
const db = await getDb();
await db.delete(schema.pushSubscriptions).where(eq(schema.pushSubscriptions.endpoint, endpoint));
}
/** Envoie une notification sur tous les appareils abonnés. Renvoie le nombre d'envois réussis. */
export async function sendPush(title: string, body: string, url = "/"): Promise<number> {
if (!configure()) return 0;
const db = await getDb();
const subs = await db.select().from(schema.pushSubscriptions);
let sent = 0;
for (const s of subs) {
try {
await webpush.sendNotification({ endpoint: s.endpoint, keys: s.keys }, JSON.stringify({ title, body, url }));
sent++;
} catch (err) {
const status = (err as { statusCode?: number }).statusCode;
// 404/410 : l'abonnement n'existe plus (app désinstallée, notifications coupées).
if (status === 404 || status === 410) await removeSubscription(s.endpoint);
else console.error("Échec d'envoi de notification", err);
}
}
return sent;
}

89
src/lib/settings.ts Normal file
View File

@ -0,0 +1,89 @@
import "server-only";
import { eq } from "drizzle-orm";
import { getDb, schema } from "./db";
import type { PeaPlan } from "./engine/pea";
import { parisDate } from "./time";
import { DEFAULT_PEA_ETF } from "./universe";
export type Settings = {
simStartDate: string;
rendezvousMinutes: number; // minutes depuis minuit, heure de Paris
peaPlan: PeaPlan | null;
realMonthlyDeposit: number;
realDepositDay: number;
realDepositsStart: string | null; // date du premier virement vers le compte-titres
aiMonthlyBudgetUsd: number;
askDailyLimit: number;
realUnlockedAt: string | null;
realLockedReason: string | null;
};
export const SIM_INITIAL_CASH = 200;
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,
},
realMonthlyDeposit: 50,
realDepositDay: 5,
realDepositsStart: null,
aiMonthlyBudgetUsd: 8,
askDailyLimit: 10,
realUnlockedAt: null,
realLockedReason: null,
};
}
export async function getKv<T>(key: string): Promise<T | null> {
const db = await getDb();
const rows = await db.select().from(schema.kv).where(eq(schema.kv.key, key));
return (rows[0]?.value as T) ?? null;
}
export async function setKv(key: string, value: unknown): Promise<void> {
const db = await getDb();
await db
.insert(schema.kv)
.values({ key, value })
.onConflictDoUpdate({ target: schema.kv.key, set: { value, updatedAt: new Date() } });
}
/** Crée les réglages et les trois portefeuilles au premier lancement. */
export async function ensureSetup(): Promise<Settings> {
const db = await getDb();
let settings = await getKv<Settings>("settings");
if (!settings) {
settings = defaults();
await setKv("settings", settings);
} else {
settings = { ...defaults(), ...settings };
}
await db
.insert(schema.portfolios)
.values([
{ id: "ai_sim", name: "Cagnotte IA (simulation)", initialCash: SIM_INITIAL_CASH, cash: SIM_INITIAL_CASH, highWaterMark: SIM_INITIAL_CASH },
{ id: "sandbox", name: "Mon bac à sable", initialCash: SIM_INITIAL_CASH, cash: SIM_INITIAL_CASH, highWaterMark: SIM_INITIAL_CASH },
{ id: "real", name: "Compte-titres Trade Republic", initialCash: 0, cash: 0, highWaterMark: 0 },
])
.onConflictDoNothing();
return settings;
}
export async function getSettings(): Promise<Settings> {
return ensureSetup();
}
export async function updateSettings(patch: Partial<Settings>): Promise<Settings> {
const next = { ...(await getSettings()), ...patch };
await setKv("settings", next);
return next;
}

88
src/lib/stats.ts Normal file
View File

@ -0,0 +1,88 @@
import "server-only";
import { and, eq, ne } from "drizzle-orm";
import { aiSpendSince } from "./ai";
import { getDb, schema } from "./db";
import { computeGate, maxDrawdownPct, type Criterion } from "./engine/gate";
import { computePea, type PeaResult } from "./engine/pea";
import { getBars, getFxToEur, getQuote } from "./market";
import { getPortfolioState, type PortfolioState } from "./portfolio";
import { getSettings, type Settings } from "./settings";
import { daysBetween, parisDate } from "./time";
/** Rendement de l'ETF S&P 500 (celui du PEA) depuis une date, en %. */
export async function benchmarkReturnPct(symbol: string, since: string): Promise<number> {
const bars = await getBars(symbol, since);
const first = bars.find((b) => b.date >= since);
const last = (await getQuote(symbol))?.price ?? bars.at(-1)?.close;
if (!first || !last) return 0;
return (last / first.close - 1) * 100;
}
export type GateStatus = {
unlocked: boolean; // critères remplis aujourd'hui
realActive: boolean; // mode réel en service (débloqué et pas coupé par le coupe-circuit)
criteria: Criterion[];
netReturnPct: number;
aiCostEur: number;
};
export async function getGateStatus(settings?: Settings, ai?: PortfolioState): Promise<GateStatus> {
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;
const gate = computeGate({
simDays: daysBetween(s.simStartDate, parisDate()),
closedTrades: closed.length,
aiReturnPct: (aiState.equity / aiState.initialCash - 1) * 100,
aiCostEur,
initialCash: aiState.initialCash,
benchmarkReturnPct: bench,
maxDrawdownPct: maxDrawdownPct([...snaps.sort((a, b) => a.date.localeCompare(b.date)).map((x) => x.equity), aiState.equity]),
actionsTotal: acts.length,
actionsAnswered: acts.filter((a) => a.status !== "pending").length,
});
return {
unlocked: gate.unlocked,
realActive: Boolean(s.realUnlockedAt) && !s.realLockedReason,
criteria: gate.criteria,
netReturnPct: gate.netReturnPct,
aiCostEur,
};
}
export type Leaderboard = { label: string; pct: number; detail: string }[];
export async function getLeaderboard(settings: Settings, ai: PortfolioState, sandbox: PortfolioState): Promise<Leaderboard> {
const bench = settings.peaPlan ? await benchmarkReturnPct(settings.peaPlan.etfSymbol, settings.simStartDate) : 0;
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: "S&P 500", pct: bench, detail: "sans rien faire" },
];
return rows.sort((a, b) => b.pct - a.pct);
}
export async function getPea(settings: Settings): Promise<(PeaResult & { etfName: string; price: number | null }) | null> {
const plan = settings.peaPlan;
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)]);
return { ...computePea(plan, bars, quote?.price ?? null, today), etfName: plan.etfName, price: quote?.price ?? null };
}
export async function totalDeposited(): Promise<number> {
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);
}

74
src/lib/time.ts Normal file
View File

@ -0,0 +1,74 @@
/** Utilitaires de date à l'heure de Paris (les marchés et ton rendez-vous suivent cette heure). */
const TZ = "Europe/Paris";
function parts(d: Date) {
const fmt = new Intl.DateTimeFormat("en-CA", {
timeZone: TZ,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
weekday: "short",
hourCycle: "h23",
});
const p = Object.fromEntries(fmt.formatToParts(d).map((x) => [x.type, x.value]));
return p as Record<"year" | "month" | "day" | "hour" | "minute" | "weekday", string>;
}
/** Date du jour à Paris au format AAAA-MM-JJ. */
export function parisDate(d: Date = new Date()): string {
const p = parts(d);
return `${p.year}-${p.month}-${p.day}`;
}
/** Heure de Paris en minutes depuis minuit. */
export function parisMinutes(d: Date = new Date()): number {
const p = parts(d);
return Number(p.hour) * 60 + Number(p.minute);
}
export function isWeekend(date: string): boolean {
const day = new Date(`${date}T12:00:00Z`).getUTCDay();
return day === 0 || day === 6;
}
export function addDays(date: string, n: number): string {
const d = new Date(`${date}T12:00:00Z`);
d.setUTCDate(d.getUTCDate() + n);
return d.toISOString().slice(0, 10);
}
/** Ajoute n jours de bourse (lundi-vendredi ; les jours fériés sont ignorés). */
export function addTradingDays(date: string, n: number): string {
let d = date;
let left = n;
while (left > 0) {
d = addDays(d, 1);
if (!isWeekend(d)) left--;
}
return d;
}
export function daysBetween(from: string, to: string): number {
return Math.round(
(new Date(`${to}T12:00:00Z`).getTime() - new Date(`${from}T12:00:00Z`).getTime()) / 86_400_000,
);
}
/** Trade Republic (LS Exchange) : du lundi au vendredi, de 7h30 à 23h00, heure de Paris. */
export function isTradeRepublicOpen(d: Date = new Date()): boolean {
if (isWeekend(parisDate(d))) return false;
const m = parisMinutes(d);
return m >= 7 * 60 + 30 && m < 23 * 60;
}
export function formatDateFr(date: string): string {
return new Date(`${date}T12:00:00Z`).toLocaleDateString("fr-FR", {
weekday: "long",
day: "numeric",
month: "long",
timeZone: "UTC",
});
}

115
src/lib/universe.ts Normal file
View File

@ -0,0 +1,115 @@
/**
* Les actions que l'IA surveille : grandes sociétés liquides du S&P 500 et de l'Euro Stoxx 50.
* Symboles au format Yahoo Finance. Toutes sont disponibles chez Trade Republic (cherche le nom).
*/
export type Stock = { symbol: string; name: string; market: "US" | "EU" };
const US: [string, string][] = [
["AAPL", "Apple"],
["MSFT", "Microsoft"],
["NVDA", "Nvidia"],
["AMZN", "Amazon"],
["GOOGL", "Alphabet (Google)"],
["META", "Meta Platforms"],
["TSLA", "Tesla"],
["AVGO", "Broadcom"],
["JPM", "JPMorgan Chase"],
["V", "Visa"],
["MA", "Mastercard"],
["UNH", "UnitedHealth"],
["XOM", "ExxonMobil"],
["JNJ", "Johnson & Johnson"],
["PG", "Procter & Gamble"],
["HD", "Home Depot"],
["COST", "Costco"],
["ABBV", "AbbVie"],
["KO", "Coca-Cola"],
["PEP", "PepsiCo"],
["MRK", "Merck & Co"],
["LLY", "Eli Lilly"],
["BAC", "Bank of America"],
["WMT", "Walmart"],
["NFLX", "Netflix"],
["AMD", "AMD"],
["CRM", "Salesforce"],
["ORCL", "Oracle"],
["ADBE", "Adobe"],
["CSCO", "Cisco"],
["INTC", "Intel"],
["DIS", "Walt Disney"],
["MCD", "McDonald's"],
["NKE", "Nike"],
["PFE", "Pfizer"],
["T", "AT&T"],
["VZ", "Verizon"],
["CVX", "Chevron"],
["BA", "Boeing"],
["IBM", "IBM"],
["QCOM", "Qualcomm"],
["UBER", "Uber"],
["PYPL", "PayPal"],
["SBUX", "Starbucks"],
];
const EU: [string, string][] = [
["ASML.AS", "ASML"],
["MC.PA", "LVMH"],
["SAP.DE", "SAP"],
["SIE.DE", "Siemens"],
["TTE.PA", "TotalEnergies"],
["SAN.PA", "Sanofi"],
["OR.PA", "L'Oréal"],
["AIR.PA", "Airbus"],
["ALV.DE", "Allianz"],
["DTE.DE", "Deutsche Telekom"],
["SU.PA", "Schneider Electric"],
["AI.PA", "Air Liquide"],
["BNP.PA", "BNP Paribas"],
["IBE.MC", "Iberdrola"],
["SAN.MC", "Banco Santander"],
["ITX.MC", "Inditex"],
["BBVA.MC", "BBVA"],
["ENEL.MI", "Enel"],
["ENI.MI", "Eni"],
["ISP.MI", "Intesa Sanpaolo"],
["UCG.MI", "UniCredit"],
["RACE.MI", "Ferrari"],
["STLAM.MI", "Stellantis"],
["INGA.AS", "ING"],
["ADYEN.AS", "Adyen"],
["PRX.AS", "Prosus"],
["AD.AS", "Ahold Delhaize"],
["BAS.DE", "BASF"],
["BAYN.DE", "Bayer"],
["BMW.DE", "BMW"],
["MBG.DE", "Mercedes-Benz"],
["VOW3.DE", "Volkswagen"],
["DB1.DE", "Deutsche Börse"],
["IFX.DE", "Infineon"],
["MUV2.DE", "Munich Re"],
["ADS.DE", "Adidas"],
["DHL.DE", "DHL Group"],
["RHM.DE", "Rheinmetall"],
["RMS.PA", "Hermès"],
["CS.PA", "AXA"],
["DG.PA", "Vinci"],
["EL.PA", "EssilorLuxottica"],
["SAF.PA", "Safran"],
["BN.PA", "Danone"],
["RI.PA", "Pernod Ricard"],
["SGO.PA", "Saint-Gobain"],
["NOKIA.HE", "Nokia"],
["ABI.BR", "AB InBev"],
];
export const UNIVERSE: Stock[] = [
...US.map(([symbol, name]) => ({ symbol, name, market: "US" as const })),
...EU.map(([symbol, name]) => ({ symbol, name, market: "EU" as const })),
];
export function findStock(symbol: string): Stock | undefined {
return UNIVERSE.find((s) => s.symbol === symbol);
}
/** ETF S&P 500 éligible PEA par défaut (BNP Paribas Easy S&P 500, en euros). */
export const DEFAULT_PEA_ETF = { symbol: "ESE.PA", name: "BNP Paribas Easy S&P 500 UCITS ETF" };

15
src/proxy.ts Normal file
View File

@ -0,0 +1,15 @@
import { NextResponse, type NextRequest } from "next/server";
import { isValidSession, SESSION_COOKIE } from "@/lib/auth";
/** Toutes les pages demandent d'être connecté, sauf la connexion, les tâches planifiées et les fichiers de l'app. */
export async function proxy(request: NextRequest) {
if (await isValidSession(request.cookies.get(SESSION_COOKIE)?.value)) return NextResponse.next();
if (request.nextUrl.pathname.startsWith("/api/")) {
return NextResponse.json({ error: "Non connecté" }, { status: 401 });
}
return NextResponse.redirect(new URL("/login", request.url));
}
export const config = {
matcher: ["/((?!login|api/cron|manifest.webmanifest|sw.js|pwa-icon|apple-icon|icon|favicon.ico|_next).*)"],
};

1
src/test/empty.ts Normal file
View File

@ -0,0 +1 @@
export {};

18
vitest.config.mts Normal file
View File

@ -0,0 +1,18 @@
import path from "node:path";
import { defineConfig } from "vitest/config";
export default defineConfig({
resolve: {
alias: {
"@": path.resolve(import.meta.dirname, "src"),
// « server-only » n'a de sens que dans Next.js ; en test on le neutralise.
"server-only": path.resolve(import.meta.dirname, "src/test/empty.ts"),
},
},
test: {
include: ["src/**/*.test.ts"],
// Les tests d'intégration (réseau + base) ne tournent que sur demande : pnpm test:integration
exclude: process.env.INTEGRATION ? [] : ["src/**/*.integration.test.ts"],
testTimeout: 120_000,
},
});