Compare commits

..

2 Commits

Author SHA1 Message Date
David
77a165afaa Upgrade Next.js to 16.4.6 (security advisory)
Some checks failed
Tick / tick (push) Failing after 1s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 19:06:29 +01:00
David
234efda586 Fix trade proposals, speed, Trade Republic setup and stock UI
- Buy by EUR amount (fractional shares, like Trade Republic): 200 EUR can
  now reach every large cap; risk engine sizes in whole euros
- No-AI screener (pullback in uptrend) feeds training cards and AI candidates
- Auto-update on app open via after(); "find ideas now" button (3/day)
- New Actions tab: stock list, stock page with chart, news, AI opinion,
  sandbox buy by amount or shares
- "Mon compte" tab: declare deposits, cash, holdings and PEA plan
  (no broker credentials, no PEA invented by default)
- Yahoo data cached and deduplicated, pages stream per section
- Tests: fractional sizing, screener, no-AI idea flow

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 19:05:20 +01:00
42 changed files with 3079 additions and 730 deletions

View File

@ -9,6 +9,19 @@ App web (installable sur iPhone) qui t'aide à investir 100 €/mois :
> Outil d'aide à la décision, pas un conseil en investissement. La majorité des traders particuliers perdent de l'argent ; l'app est conçue pour le mesurer honnêtement.
**Les onglets** :
- **Accueil** : ce qu'il y a à faire (fiches du rendez-vous), bouton « Chercher des idées maintenant », patrimoine, classement.
- **Actions** : toutes les actions suivies avec leur cours ; une fiche par action (graphique, actus, avis de l'IA, achat dans le bac à sable par montant en € ou en nombre d'actions).
- **Bac à sable** : ta cagnotte virtuelle de 200 €.
- **IA** : la cagnotte et les analyses de l'IA.
- **Mon compte** : ton compte Trade Republic. Trade Republic n'a pas d'API : tu déclares tes versements, tes liquidités, les actions que tu détiens et ton plan PEA, l'app tient les comptes. Aucun identifiant n'est jamais demandé.
**Achats par montant** : comme Trade Republic, l'app achète des fractions d'actions (« Montant : 150 € »). Même avec 200 €, toutes les grandes actions sont accessibles.
**Sans clé Anthropic**, l'app fonctionne quand même : un filtre simple (repli dans une tendance haussière) repère des idées à tester dans le bac à sable. Avec la clé, ces idées servent aussi de candidates à l'IA.
**Mise à jour automatique** : à chaque ouverture de l'app (au plus toutes les 20 minutes), ordres, stops, actus et idées se mettent à jour en arrière-plan. La tâche GitHub Actions reste utile pour le rendez-vous du soir et les notifications quand l'app est fermée.
---
## Lancer l'app sur ton Mac

View File

@ -0,0 +1,2 @@
ALTER TABLE "orders" ALTER COLUMN "shares" SET DATA TYPE double precision;--> statement-breakpoint
ALTER TABLE "positions" ALTER COLUMN "shares" SET DATA TYPE double precision;

View File

@ -0,0 +1,881 @@
{
"id": "44ea687c-f514-404a-be73-0f8f65cca593",
"prevId": "4dbfbae0-5e55-4b56-8cc8-1bce887ea407",
"version": "7",
"dialect": "postgresql",
"tables": {
"public.actions": {
"name": "actions",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "serial",
"primaryKey": true,
"notNull": true
},
"rendezvous_id": {
"name": "rendezvous_id",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"kind": {
"name": "kind",
"type": "text",
"primaryKey": false,
"notNull": true
},
"training": {
"name": "training",
"type": "boolean",
"primaryKey": false,
"notNull": true
},
"symbol": {
"name": "symbol",
"type": "text",
"primaryKey": false,
"notNull": false
},
"payload": {
"name": "payload",
"type": "jsonb",
"primaryKey": false,
"notNull": true
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'pending'"
},
"responded_at": {
"name": "responded_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.ai_usage": {
"name": "ai_usage",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "serial",
"primaryKey": true,
"notNull": true
},
"at": {
"name": "at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"model": {
"name": "model",
"type": "text",
"primaryKey": false,
"notNull": true
},
"purpose": {
"name": "purpose",
"type": "text",
"primaryKey": false,
"notNull": true
},
"input_tokens": {
"name": "input_tokens",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"output_tokens": {
"name": "output_tokens",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"cost_usd": {
"name": "cost_usd",
"type": "double precision",
"primaryKey": false,
"notNull": true
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.cash_flows": {
"name": "cash_flows",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "serial",
"primaryKey": true,
"notNull": true
},
"portfolio_id": {
"name": "portfolio_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"amount": {
"name": "amount",
"type": "double precision",
"primaryKey": false,
"notNull": true
},
"kind": {
"name": "kind",
"type": "text",
"primaryKey": false,
"notNull": true
},
"date": {
"name": "date",
"type": "text",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.equity_snapshots": {
"name": "equity_snapshots",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "serial",
"primaryKey": true,
"notNull": true
},
"portfolio_id": {
"name": "portfolio_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"date": {
"name": "date",
"type": "text",
"primaryKey": false,
"notNull": true
},
"equity": {
"name": "equity",
"type": "double precision",
"primaryKey": false,
"notNull": true
}
},
"indexes": {
"equity_portfolio_date_idx": {
"name": "equity_portfolio_date_idx",
"columns": [
{
"expression": "portfolio_id",
"isExpression": false,
"asc": true,
"nulls": "last"
},
{
"expression": "date",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.kv": {
"name": "kv",
"schema": "",
"columns": {
"key": {
"name": "key",
"type": "text",
"primaryKey": true,
"notNull": true
},
"value": {
"name": "value",
"type": "jsonb",
"primaryKey": false,
"notNull": true
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.news": {
"name": "news",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"symbol": {
"name": "symbol",
"type": "text",
"primaryKey": false,
"notNull": true
},
"title": {
"name": "title",
"type": "text",
"primaryKey": false,
"notNull": true
},
"publisher": {
"name": "publisher",
"type": "text",
"primaryKey": false,
"notNull": false
},
"url": {
"name": "url",
"type": "text",
"primaryKey": false,
"notNull": false
},
"published_at": {
"name": "published_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"triage": {
"name": "triage",
"type": "jsonb",
"primaryKey": false,
"notNull": false
},
"triaged_at": {
"name": "triaged_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"alerted_at": {
"name": "alerted_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.orders": {
"name": "orders",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "serial",
"primaryKey": true,
"notNull": true
},
"portfolio_id": {
"name": "portfolio_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"symbol": {
"name": "symbol",
"type": "text",
"primaryKey": false,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"currency": {
"name": "currency",
"type": "text",
"primaryKey": false,
"notNull": true
},
"side": {
"name": "side",
"type": "text",
"primaryKey": false,
"notNull": true
},
"type": {
"name": "type",
"type": "text",
"primaryKey": false,
"notNull": true
},
"limit_price": {
"name": "limit_price",
"type": "double precision",
"primaryKey": false,
"notNull": false
},
"shares": {
"name": "shares",
"type": "double precision",
"primaryKey": false,
"notNull": true
},
"stop_price": {
"name": "stop_price",
"type": "double precision",
"primaryKey": false,
"notNull": false
},
"target_price": {
"name": "target_price",
"type": "double precision",
"primaryKey": false,
"notNull": false
},
"max_exit_date": {
"name": "max_exit_date",
"type": "text",
"primaryKey": false,
"notNull": false
},
"position_id": {
"name": "position_id",
"type": "integer",
"primaryKey": false,
"notNull": false
},
"signal_id": {
"name": "signal_id",
"type": "integer",
"primaryKey": false,
"notNull": false
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'pending'"
},
"valid_until": {
"name": "valid_until",
"type": "text",
"primaryKey": false,
"notNull": false
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"filled_at": {
"name": "filled_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"fill_price": {
"name": "fill_price",
"type": "double precision",
"primaryKey": false,
"notNull": false
},
"note": {
"name": "note",
"type": "text",
"primaryKey": false,
"notNull": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.portfolios": {
"name": "portfolios",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"initial_cash": {
"name": "initial_cash",
"type": "double precision",
"primaryKey": false,
"notNull": true
},
"cash": {
"name": "cash",
"type": "double precision",
"primaryKey": false,
"notNull": true
},
"high_water_mark": {
"name": "high_water_mark",
"type": "double precision",
"primaryKey": false,
"notNull": true,
"default": 0
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.positions": {
"name": "positions",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "serial",
"primaryKey": true,
"notNull": true
},
"portfolio_id": {
"name": "portfolio_id",
"type": "text",
"primaryKey": false,
"notNull": true
},
"symbol": {
"name": "symbol",
"type": "text",
"primaryKey": false,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"currency": {
"name": "currency",
"type": "text",
"primaryKey": false,
"notNull": true
},
"shares": {
"name": "shares",
"type": "double precision",
"primaryKey": false,
"notNull": true
},
"entry_price": {
"name": "entry_price",
"type": "double precision",
"primaryKey": false,
"notNull": true
},
"entry_fx": {
"name": "entry_fx",
"type": "double precision",
"primaryKey": false,
"notNull": true
},
"opened_at": {
"name": "opened_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true
},
"stop_price": {
"name": "stop_price",
"type": "double precision",
"primaryKey": false,
"notNull": false
},
"target_price": {
"name": "target_price",
"type": "double precision",
"primaryKey": false,
"notNull": false
},
"max_exit_date": {
"name": "max_exit_date",
"type": "text",
"primaryKey": false,
"notNull": false
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "'open'"
},
"closed_at": {
"name": "closed_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
},
"exit_price": {
"name": "exit_price",
"type": "double precision",
"primaryKey": false,
"notNull": false
},
"exit_fx": {
"name": "exit_fx",
"type": "double precision",
"primaryKey": false,
"notNull": false
},
"exit_reason": {
"name": "exit_reason",
"type": "text",
"primaryKey": false,
"notNull": false
},
"fees_eur": {
"name": "fees_eur",
"type": "double precision",
"primaryKey": false,
"notNull": true,
"default": 0
},
"pnl_eur": {
"name": "pnl_eur",
"type": "double precision",
"primaryKey": false,
"notNull": false
},
"signal_id": {
"name": "signal_id",
"type": "integer",
"primaryKey": false,
"notNull": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.push_subscriptions": {
"name": "push_subscriptions",
"schema": "",
"columns": {
"endpoint": {
"name": "endpoint",
"type": "text",
"primaryKey": true,
"notNull": true
},
"keys": {
"name": "keys",
"type": "jsonb",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.rendezvous": {
"name": "rendezvous",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "serial",
"primaryKey": true,
"notNull": true
},
"date": {
"name": "date",
"type": "text",
"primaryKey": false,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"summary": {
"name": "summary",
"type": "text",
"primaryKey": false,
"notNull": true
},
"notified_at": {
"name": "notified_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": false
}
},
"indexes": {
"rendezvous_date_idx": {
"name": "rendezvous_date_idx",
"columns": [
{
"expression": "date",
"isExpression": false,
"asc": true,
"nulls": "last"
}
],
"isUnique": true,
"concurrently": false,
"method": "btree",
"with": {}
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
},
"public.signals": {
"name": "signals",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "serial",
"primaryKey": true,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"date": {
"name": "date",
"type": "text",
"primaryKey": false,
"notNull": true
},
"symbol": {
"name": "symbol",
"type": "text",
"primaryKey": false,
"notNull": true
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true
},
"decision": {
"name": "decision",
"type": "text",
"primaryKey": false,
"notNull": true
},
"confidence": {
"name": "confidence",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"thesis": {
"name": "thesis",
"type": "text",
"primaryKey": false,
"notNull": true
},
"risks": {
"name": "risks",
"type": "text",
"primaryKey": false,
"notNull": true
},
"expected_move_pct": {
"name": "expected_move_pct",
"type": "double precision",
"primaryKey": false,
"notNull": true
},
"stop_pct": {
"name": "stop_pct",
"type": "double precision",
"primaryKey": false,
"notNull": true
},
"target_pct": {
"name": "target_pct",
"type": "double precision",
"primaryKey": false,
"notNull": true
},
"horizon_days": {
"name": "horizon_days",
"type": "integer",
"primaryKey": false,
"notNull": true
},
"price_at_signal": {
"name": "price_at_signal",
"type": "double precision",
"primaryKey": false,
"notNull": true
},
"currency": {
"name": "currency",
"type": "text",
"primaryKey": false,
"notNull": true
},
"news_ids": {
"name": "news_ids",
"type": "jsonb",
"primaryKey": false,
"notNull": true
},
"risk_verdict": {
"name": "risk_verdict",
"type": "text",
"primaryKey": false,
"notNull": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
}
},
"enums": {},
"schemas": {},
"sequences": {},
"roles": {},
"policies": {},
"views": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
}
}

View File

@ -8,6 +8,13 @@
"when": 1791720025887,
"tag": "0000_init",
"breakpoints": true
},
{
"idx": 1,
"version": "7",
"when": 1794851302883,
"tag": "0001_friendly_bloodscream",
"breakpoints": true
}
]
}

View File

@ -18,7 +18,7 @@
"@electric-sql/pglite": "^0.5.8",
"drizzle-orm": "^0.45.4",
"jose": "^6.2.12",
"next": "16.4.0",
"next": "16.4.6",
"postgres": "^3.4.9",
"react": "19.3.0",
"react-dom": "19.3.0",
@ -35,7 +35,7 @@
"@types/web-push": "^3.6.4",
"drizzle-kit": "^0.31.11",
"eslint": "^9",
"eslint-config-next": "16.4.0",
"eslint-config-next": "16.4.6",
"tailwindcss": "^4",
"tsx": "^4.23.15",
"typescript": "^5",

100
pnpm-lock.yaml generated
View File

@ -21,8 +21,8 @@ importers:
specifier: ^6.2.12
version: 6.2.12
next:
specifier: 16.4.0
version: 16.4.0(@babel/core@7.29.7)(@types/node@20.19.43)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)
specifier: 16.4.6
version: 16.4.6(@babel/core@7.29.7)(@types/node@20.19.43)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)
postgres:
specifier: ^3.4.9
version: 3.4.9
@ -67,8 +67,8 @@ importers:
specifier: ^9
version: 9.39.5(jiti@2.7.0)
eslint-config-next:
specifier: 16.4.0
version: 16.4.0(@typescript-eslint/parser@8.71.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)
specifier: 16.4.6
version: 16.4.6(@typescript-eslint/parser@8.71.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3)
tailwindcss:
specifier: ^4
version: 4.3.3
@ -893,56 +893,56 @@ packages:
'@emnapi/core': ^1.7.1 || ^2.0.0-alpha.4
'@emnapi/runtime': ^1.7.1 || ^2.0.0-alpha.4
'@next/env@16.4.0':
resolution: {integrity: sha512-pyLlT5oafGlX8X7xjgGNXz5dNIDSxREm+qD6i9VLSZiZFopA/XWl8NM/KPmLx/8EG/++c49iid3gNWSQW1+2dQ==}
'@next/env@16.4.6':
resolution: {integrity: sha512-SunBjJ6t+oBtecS3dTjdVuMhUogP5wD/vrGL5EVuQYM1iS4O5ilL51HkiJ3sPjMzRHiCChvr4dbaSJbR7F3lxA==}
'@next/eslint-plugin-next@16.4.0':
resolution: {integrity: sha512-ffeflB/dL8RrvWejQximw01pOpKHN692Y3FjDB82DCd0YVvXvBD6vY7mcZp27yvSVFVM6wA73xVodEKF4spizA==}
'@next/eslint-plugin-next@16.4.6':
resolution: {integrity: sha512-HdqERVOafOD8JaUSAkwf9aSu/1rsHlkN8C5GcXYBH3C/z1MxBhZFxB5rz/xqMMRiIj7r9tIv8OCLQ9JWUxCvWA==}
'@next/swc-darwin-arm64@16.4.0':
resolution: {integrity: sha512-yyZ+9MgViAKLLb5l1gPBGjRwnq3teNLb5Zx6JEw8LzNSTjlsnp+baUHFxTgl7PpjCmKf48VQfyipG1eBflb48Q==}
'@next/swc-darwin-arm64@16.4.6':
resolution: {integrity: sha512-kJ4VVZkley17xKaJx72QN2IBqjrj7zenCQZaUF0l9ShS/1Mt2kW4+Z5KGG6vgr3L/J562xTOizVyM1iA/u5nlg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [darwin]
'@next/swc-darwin-x64@16.4.0':
resolution: {integrity: sha512-RePEEejEj1Auf5s9qEcG0JbcDP3ceNUS/ofNX8AhxzgIjTVlZIHMatlp16YplcSMpsVo/ZMQHJTjbMYJznjGUg==}
'@next/swc-darwin-x64@16.4.6':
resolution: {integrity: sha512-eIPGZIqC+8JKaeZmvnCANJQF4xWkkHqSnAAajtFxgwDMAOnCgxNvP52SeWZ41PyVwoe+Le/NQuZSaQ8j7YshSA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [darwin]
'@next/swc-linux-arm64-gnu@16.4.0':
resolution: {integrity: sha512-HhsyCqd+NpmvDDVY/LqkAN24f+QVvXh3ie+PfcwKinWL2Mu826JymQxJXGjAIfmJ4VlHjp4Pe/nZtXtUoEMAqw==}
'@next/swc-linux-arm64-gnu@16.4.6':
resolution: {integrity: sha512-9nI6O8vvczH2D9ZNdMGqb/3NuT15T9ksOZnAmx9/gjF2cOi74+xxyf1Hk96uIMfm14c9y6wHeBq6SH8g6udvcA==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
'@next/swc-linux-arm64-musl@16.4.0':
resolution: {integrity: sha512-sN9Pf+Zh+RpZAOmbR7d8KAA8T61CVhawtbEJ2Bk6QrRzx6Z/6haaF4UiwBzytM96GRRRWZh9/WALIEO3npMamA==}
'@next/swc-linux-arm64-musl@16.4.6':
resolution: {integrity: sha512-7/qPhTxDp2ScluOJOhLuhWmlA17o1yZ0SIgpISBCpBxXgtnK4+KGywBpFkfLPiU1rnSM1faFGzYkH6i7JdTrqA==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
'@next/swc-linux-x64-gnu@16.4.0':
resolution: {integrity: sha512-D5M5xLWQVd1CvR+L7BickM1weRfmM41x3L1NWcnKY/oyJJqr1qwaCgmu3dMAhLBOMdZwSuDCRV6DJRRpiUkbDQ==}
'@next/swc-linux-x64-gnu@16.4.6':
resolution: {integrity: sha512-oOpbNa8XOW1qCGd9VvzC4fbkkRxEls7/WI6tz+YHC0xRA7KpV1U7DrAnCPjzVyOk/karzWEepCOcTIDmwK8FwQ==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
'@next/swc-linux-x64-musl@16.4.0':
resolution: {integrity: sha512-8d5WLS6a9YalqpOgXdlbvonFu+sIgjA+CO6tGzetrpPVcUL56foa7B7664h41rAlbLi5fJwK4vWji3zf4QDy+w==}
'@next/swc-linux-x64-musl@16.4.6':
resolution: {integrity: sha512-aM8CZ+OR2EwXaAYw7KGkW2GDmNDsLBIRe1MMRZCJPTdw/xhTD0IMUVO4sf3KqrzuRouGzwwLZn34+gFeVXiUQA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
'@next/swc-win32-arm64-msvc@16.4.0':
resolution: {integrity: sha512-sQuOIiW3snb48UwrBcDMvFA/u03qtw2LeuSIxFIQ9AJuW9UG/4Ddsfo+eV73PnZwBhyncMtsKVh7PrzMol2/fA==}
'@next/swc-win32-arm64-msvc@16.4.6':
resolution: {integrity: sha512-U0p7/tEtqvHX2crhd841CDwKtp5CFkKXVjOhmfccR3Pvp64sj8KBwRqsvltqLOwVBbj0NtkxwXSDpEHYGbxeXQ==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [win32]
'@next/swc-win32-x64-msvc@16.4.0':
resolution: {integrity: sha512-6/33lCuxpdHUy27RegyGM/5uTpF7YZd3UR4D0gpkOA/tWY5YR7msbQjqPgCZmSmxrrTLGCXYA4A8vT2H5DPGTQ==}
'@next/swc-win32-x64-msvc@16.4.6':
resolution: {integrity: sha512-3ZG15/5WIdlTQsIEvc9sPTTSL5XFrlLklIKmfF4fwsDnoAhu6NcBDXsk3mbGxNyo6aVLEGex+fHCv2MahY7a9g==}
engines: {node: '>= 10'}
cpu: [x64]
os: [win32]
@ -1834,8 +1834,8 @@ packages:
resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}
engines: {node: '>=10'}
eslint-config-next@16.4.0:
resolution: {integrity: sha512-2RHLYswzc+hNRktWAjIL6XAvwb1cKcjLawJ5KWywAxn/JivNHtG42ZigL1yobVXDqsimuuL2F9jcEcnHFzbppQ==}
eslint-config-next@16.4.6:
resolution: {integrity: sha512-IBGGrVf9E6pL0NGL0hmeicVGeSyv1VEzIWq6IecDqkw+YFByhEtDJS9u1r6s6a1VxK6rssh69KyNFQUgfaacqw==}
peerDependencies:
eslint: '>=9.0.0'
typescript: '>=3.3.1'
@ -2638,8 +2638,8 @@ packages:
resolution: {integrity: sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==}
engines: {node: '>=18'}
next@16.4.0:
resolution: {integrity: sha512-N2C+9q89Z/oLrsepSRS4jRMtwmUZAoZuAHU0e9T6+sAB5DdhADmrnOW+zjYijlrYFmVfmQhGVGy9eMFoB7UgKg==}
next@16.4.6:
resolution: {integrity: sha512-QZJiYhaZLJMo2KpkQGQIwvmd79WVsAWeYIU554a8d7zArS3si/IRy3lBNV/rtYhE70oLwdLYhPAXLPx8HwcwtA==}
engines: {node: '>=20.9.0'}
hasBin: true
peerDependencies:
@ -3915,37 +3915,37 @@ snapshots:
'@tybys/wasm-util': 0.10.4
optional: true
'@next/env@16.4.0': {}
'@next/env@16.4.6': {}
'@next/eslint-plugin-next@16.4.0(eslint@9.39.5(jiti@2.7.0))':
'@next/eslint-plugin-next@16.4.6(eslint@9.39.5(jiti@2.7.0))':
dependencies:
'@eslint-community/eslint-utils': 4.9.1(eslint@9.39.5(jiti@2.7.0))
fast-glob: 3.3.1
transitivePeerDependencies:
- eslint
'@next/swc-darwin-arm64@16.4.0':
'@next/swc-darwin-arm64@16.4.6':
optional: true
'@next/swc-darwin-x64@16.4.0':
'@next/swc-darwin-x64@16.4.6':
optional: true
'@next/swc-linux-arm64-gnu@16.4.0':
'@next/swc-linux-arm64-gnu@16.4.6':
optional: true
'@next/swc-linux-arm64-musl@16.4.0':
'@next/swc-linux-arm64-musl@16.4.6':
optional: true
'@next/swc-linux-x64-gnu@16.4.0':
'@next/swc-linux-x64-gnu@16.4.6':
optional: true
'@next/swc-linux-x64-musl@16.4.0':
'@next/swc-linux-x64-musl@16.4.6':
optional: true
'@next/swc-win32-arm64-msvc@16.4.0':
'@next/swc-win32-arm64-msvc@16.4.6':
optional: true
'@next/swc-win32-x64-msvc@16.4.0':
'@next/swc-win32-x64-msvc@16.4.6':
optional: true
'@nodelib/fs.scandir@2.1.5':
@ -4819,9 +4819,9 @@ snapshots:
escape-string-regexp@4.0.0: {}
eslint-config-next@16.4.0(@typescript-eslint/parser@8.71.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3):
eslint-config-next@16.4.6(@typescript-eslint/parser@8.71.1(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3))(eslint@9.39.5(jiti@2.7.0))(typescript@5.9.3):
dependencies:
'@next/eslint-plugin-next': 16.4.0(eslint@9.39.5(jiti@2.7.0))
'@next/eslint-plugin-next': 16.4.6(eslint@9.39.5(jiti@2.7.0))
eslint: 9.39.5(jiti@2.7.0)
eslint-import-resolver-node: 0.3.10
eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0)(eslint@9.39.5(jiti@2.7.0))
@ -5676,9 +5676,9 @@ snapshots:
dependencies:
content-type: 2.1.0
next@16.4.0(@babel/core@7.29.7)(@types/node@20.19.43)(react-dom@19.3.0(react@19.3.0))(react@19.3.0):
next@16.4.6(@babel/core@7.29.7)(@types/node@20.19.43)(react-dom@19.3.0(react@19.3.0))(react@19.3.0):
dependencies:
'@next/env': 16.4.0
'@next/env': 16.4.6
'@swc/helpers': 0.5.23
baseline-browser-mapping: 2.11.28
caniuse-lite: 1.0.30001815
@ -5687,14 +5687,14 @@ snapshots:
react-dom: 19.3.0(react@19.3.0)
styled-jsx: 5.1.6(@babel/core@7.29.7)(react@19.3.0)
optionalDependencies:
'@next/swc-darwin-arm64': 16.4.0
'@next/swc-darwin-x64': 16.4.0
'@next/swc-linux-arm64-gnu': 16.4.0
'@next/swc-linux-arm64-musl': 16.4.0
'@next/swc-linux-x64-gnu': 16.4.0
'@next/swc-linux-x64-musl': 16.4.0
'@next/swc-win32-arm64-msvc': 16.4.0
'@next/swc-win32-x64-msvc': 16.4.0
'@next/swc-darwin-arm64': 16.4.6
'@next/swc-darwin-x64': 16.4.6
'@next/swc-linux-arm64-gnu': 16.4.6
'@next/swc-linux-arm64-musl': 16.4.6
'@next/swc-linux-x64-gnu': 16.4.6
'@next/swc-linux-x64-musl': 16.4.6
'@next/swc-win32-arm64-msvc': 16.4.6
'@next/swc-win32-x64-msvc': 16.4.6
sharp: 0.35.5(@types/node@20.19.43)
transitivePeerDependencies:
- '@babel/core'

View File

@ -0,0 +1,146 @@
import { Suspense } from "react";
import Link from "next/link";
import { notFound } from "next/navigation";
import { connection } from "next/server";
import { and, desc, eq } from "drizzle-orm";
import { PositionList } from "@/components/positions";
import { StockChart } from "@/components/stock-chart";
import { TradePanel } from "@/components/trade-panel";
import { Badge, Card, CardSkeleton, Empty, Page } from "@/components/ui";
import { aiEnabled, getAiSpend } from "@/lib/ai";
import { getDb, schema } from "@/lib/db";
import { pct, price, timeAgo } from "@/lib/format";
import { getBars, getFxToEur, getNews, getNextEarningsDate, getQuote, isSupportedCurrency } from "@/lib/market";
import { getPortfolioState } from "@/lib/portfolio";
import { getSettings } from "@/lib/settings";
import { addDays, formatDateFr, parisDate } from "@/lib/time";
import { findStock } from "@/lib/universe";
type Props = PageProps<"/actions/[symbol]">;
function numParam(v: string | string[] | undefined): number | undefined {
const n = Number(Array.isArray(v) ? v[0] : v);
return Number.isFinite(n) && n > 0 ? n : undefined;
}
async function StockContent({ params, searchParams }: Props) {
await connection();
const symbol = decodeURIComponent((await params).symbol);
const sp = await searchParams;
const quote = await getQuote(symbol);
if (!quote) notFound();
const db = await getDb();
const [bars, fx, earnings, sandbox, spend, settings, signals, dbNews] = await Promise.all([
getBars(symbol, addDays(parisDate(), -95)).catch(() => []),
getFxToEur(quote.currency),
getNextEarningsDate(symbol),
getPortfolioState("sandbox"),
getAiSpend(),
getSettings(),
db.select().from(schema.signals).where(eq(schema.signals.symbol, symbol)).orderBy(desc(schema.signals.createdAt)).limit(1),
db.select().from(schema.news).where(and(eq(schema.news.symbol, symbol))).orderBy(desc(schema.news.publishedAt)).limit(8),
]);
const news = dbNews.length ? dbNews : (await getNews(symbol).catch(() => [])).map((n) => ({ ...n, triage: null }));
const held = sandbox.positions.filter((p) => p.symbol === symbol);
const signal = signals[0];
const first = bars[0]?.close;
const change3m = first ? (quote.price / first - 1) * 100 : null;
const supported = isSupportedCurrency(quote.currency) && fx !== null;
const stock = findStock(symbol);
return (
<Page
title={stock?.name ?? quote.name}
subtitle={`${symbol}${stock ? ` · ${stock.market === "US" ? "Bourse américaine" : "Bourse européenne"}` : ""}`}
action={
<Link href="/actions" className="text-sm font-medium text-accent">
‹ Actions
</Link>
}
>
<Card>
<div className="flex items-end justify-between gap-3">
<p className="num text-3xl font-semibold">{price(quote.price, quote.currency)}</p>
<div className="text-right text-sm">
{quote.changePct !== null && <p className={`num font-semibold ${quote.changePct >= 0 ? "text-accent" : "text-danger"}`}>{pct(quote.changePct, 2)} auj.</p>}
{change3m !== null && <p className={`num text-xs ${change3m >= 0 ? "text-accent" : "text-danger"}`}>{pct(change3m)} sur 3 mois</p>}
</div>
</div>
{quote.currency === "USD" && fx && <p className="num mt-1 text-xs text-muted">≈ {(quote.price * fx).toFixed(2)} € chez Trade Republic</p>}
<div className="mt-3">
<StockChart bars={bars} lastPrice={quote.price} stop={held[0]?.stopPrice} target={held[0]?.targetPrice} />
</div>
{earnings && <p className="mt-2 text-xs text-muted">📅 Prochains résultats : {formatDateFr(earnings)}</p>}
</Card>
{held.length > 0 && (
<Card title="Dans mon bac à sable">
<PositionList positions={held} sellable />
</Card>
)}
{signal && (
<Card title={`Dernière analyse de l'IA · ${formatDateFr(signal.date)}`}>
<p className="mb-2">
<Badge tone={signal.decision === "buy" ? "accent" : "neutral"}>{signal.decision === "buy" ? "Achat" : "On passe"}</Badge>{" "}
<span className="text-xs text-muted">confiance {signal.confidence} %</span>
</p>
<p className="text-sm leading-relaxed">{signal.thesis}</p>
<p className="mt-1 text-sm leading-relaxed text-muted">⚠️ {signal.risks}</p>
</Card>
)}
{supported ? (
<TradePanel
symbol={symbol}
currency={quote.currency}
lastPrice={quote.price}
fxToEur={fx!}
cash={sandbox.cash}
askLeft={Math.max(0, settings.askDailyLimit - spend.askToday)}
aiOn={aiEnabled()}
realActive={Boolean(settings.realUnlockedAt) && !settings.realLockedReason}
defaults={{ amount: numParam(sp.montant), stopPct: numParam(sp.stop), targetPct: numParam(sp.objectif) }}
/>
) : (
<Card>
<Empty>Cette action est cotée en {quote.currency} : seules les actions en euros ou en dollars sont gérées.</Empty>
</Card>
)}
<Card title="Actus récentes">
{!news.length && <Empty>Pas d&apos;actu récente.</Empty>}
<ul className="divide-y divide-line">
{news.map((n) => (
<li key={n.id} className="py-2.5">
<a href={n.url ?? "#"} target="_blank" rel="noreferrer" className="text-sm font-medium leading-snug">
{n.title}
</a>
{n.triage?.reason && <p className="mt-1 text-xs leading-relaxed text-muted">{n.triage.reason}</p>}
<p className="mt-1 text-xs text-muted">
{n.publisher} · {timeAgo(n.publishedAt)}
{n.triage && ` · ${n.triage.direction === "positive" ? "▲" : n.triage.direction === "negative" ? "▼" : "•"} ${n.triage.relevance}/10`}
</p>
</li>
))}
</ul>
</Card>
</Page>
);
}
export default function StockPage(props: Props) {
return (
<Suspense
fallback={
<Page title="Chargement…">
<CardSkeleton height="h-40" />
<CardSkeleton height="h-64" />
</Page>
}
>
<StockContent {...props} />
</Suspense>
);
}

View File

@ -0,0 +1,75 @@
import { Suspense } from "react";
import Link from "next/link";
import { connection } from "next/server";
import { StockBrowser, type StockRow } from "@/components/stock-browser";
import { Card, CardSkeleton, Empty, Page } from "@/components/ui";
import { pct } from "@/lib/format";
import { getIdeas } from "@/lib/ideas";
import { getQuotes } from "@/lib/market";
import { newsCounts } from "@/lib/news";
import { getOpenSymbols } from "@/lib/portfolio";
import { UNIVERSE } from "@/lib/universe";
async function Ideas() {
await connection();
const ideas = await getIdeas();
const items = ideas?.items.slice(0, 4) ?? [];
return (
<Card title="Idées du moment" action={<span className="text-xs text-muted">filtre sans IA</span>}>
{!items.length && <Empty>Les idées se calculent à l&apos;ouverture de l&apos;app : reviens dans une minute.</Empty>}
<ul className="flex flex-col gap-2">
{items.map((i) => (
<li key={i.symbol}>
<Link href={`/actions/${encodeURIComponent(i.symbol)}`} className="block rounded-xl bg-surface-2 p-3">
<span className="flex items-center justify-between gap-2">
<span className="font-semibold">{i.name}</span>
<span className="num text-sm text-danger">{pct(i.pullbackPct)} sur 5 j</span>
</span>
<span className="mt-1 block text-xs leading-relaxed text-muted">{i.reason}</span>
</Link>
</li>
))}
</ul>
</Card>
);
}
async function Market() {
await connection();
const [quotes, newsCount, held] = await Promise.all([getQuotes(UNIVERSE.map((s) => s.symbol)), newsCounts(48), getOpenSymbols(["sandbox", "real"])]);
const rows: StockRow[] = UNIVERSE.map((s) => {
const q = quotes.get(s.symbol);
return {
symbol: s.symbol,
name: s.name,
market: s.market,
price: q?.price ?? null,
currency: q?.currency ?? (s.market === "US" ? "USD" : "EUR"),
changePct: q?.changePct ?? null,
news: newsCount.get(s.symbol) ?? 0,
held: held.includes(s.symbol),
};
});
return <StockBrowser rows={rows} />;
}
export default function ActionsPage() {
return (
<Page
title="Actions"
subtitle="Les grandes actions US et Europe suivies par l'app. Touche une action pour la voir et l'acheter dans ton bac à sable."
action={
<Link href="/actus" className="text-sm font-medium text-accent">
📰 Actus
</Link>
}
>
<Suspense fallback={<CardSkeleton title="Idées du moment" />}>
<Ideas />
</Suspense>
<Suspense fallback={<CardSkeleton height="h-96" />}>
<Market />
</Suspense>
</Page>
);
}

View File

@ -1,58 +1,64 @@
import { Suspense } from "react";
import Link from "next/link";
import { connection } from "next/server";
import { PageSkeleton } from "@/components/page-skeleton";
import { SandboxTrader } from "@/components/sandbox-trader";
import { PositionList, ClosedList, PendingOrders } from "@/components/positions";
import { Card, Page } from "@/components/ui";
import { eur, pct } from "@/lib/format";
import { getClosedPositions, getPortfolioState } from "@/lib/portfolio";
import { getAiSpend } from "@/lib/ai";
import { getSettings } from "@/lib/settings";
import { ClosedList, PendingOrders, PositionList } from "@/components/positions";
import { ResetSandbox } from "@/components/reset-sandbox";
import { Card, CardSkeleton, Delta, Page, primaryBtn, Stat } from "@/components/ui";
import { eur, pct, signedEur } from "@/lib/format";
import { getClosedPositions, getPortfolioState } from "@/lib/portfolio";
import { isTradeRepublicOpen } from "@/lib/time";
async function SandboxPageContent() {
async function SandboxContent() {
await connection();
const [state, closed, spend, settings] = await Promise.all([
getPortfolioState("sandbox"),
getClosedPositions("sandbox"),
getAiSpend(),
getSettings(),
]);
const [state, closed] = await Promise.all([getPortfolioState("sandbox"), getClosedPositions("sandbox")]);
const perf = (state.equity / state.initialCash - 1) * 100;
const realized = closed.reduce((s, p) => s + (p.pnlEur ?? 0), 0);
const wins = closed.filter((p) => (p.pnlEur ?? 0) > 0).length;
return (
<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>
<Delta value={perf}>{pct(perf)}</Delta>
</div>
<p className="num mt-1 text-sm text-muted">Liquidités : {eur(state.cash)}</p>
<div className="mt-3 grid grid-cols-3 gap-2 text-sm">
<Stat label="liquidités">{eur(state.cash, 0)}</Stat>
<Stat label="gains encaissés">{signedEur(realized)}</Stat>
<Stat label="trades gagnants">{closed.length ? `${wins}/${closed.length}` : "—"}</Stat>
</div>
<Link href="/actions" className={`${primaryBtn} mt-4 w-full`}>
+ Acheter une action
</Link>
{!isTradeRepublicOpen() && (
<p className="mt-2 text-xs text-muted">Trade Republic est fermé (7h30-23h en semaine) : tes ordres s&apos;exécuteront à la réouverture, comme en vrai.</p>
)}
</Card>
<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="Mes positions">
<PositionList positions={state.positions} sellable />
</Card>
<Card title="Historique">
<ClosedList positions={closed} />
</Card>
<ResetSandbox />
</Page>
</>
);
}
export default function SandboxPage() {
return (
<Suspense fallback={<PageSkeleton title={"Bac à sable"} />}>
<SandboxPageContent />
</Suspense>
<Page title="Bac à sable" subtitle="Argent fictif, cours réels, frais Trade Republic (1 € par ordre). Entraîne-toi sans risque.">
<Suspense fallback={<CardSkeleton title="Ma cagnotte virtuelle" height="h-40" />}>
<SandboxContent />
</Suspense>
</Page>
);
}

View File

@ -1,10 +1,19 @@
import { Nav } from "@/components/nav";
import { Suspense } from "react";
import { AutoTick } from "@/components/auto-tick";
import { Nav, NavBar } from "@/components/nav";
export const maxDuration = 300;
export default function AppLayout({ children }: LayoutProps<"/">) {
return (
<>
{children}
<Nav />
<Suspense fallback={<NavBar pathname={null} />}>
<Nav />
</Suspense>
<Suspense fallback={null}>
<AutoTick />
</Suspense>
</>
);
}

View File

@ -1,75 +1,129 @@
import { Suspense } from "react";
import { connection } from "next/server";
import { PageSkeleton } from "@/components/page-skeleton";
import Link from "next/link";
import { connection } from "next/server";
import { ActionCard } from "@/components/action-card";
import { Badge, Card, Delta, Empty, Page } from "@/components/ui";
import { FindIdeas } from "@/components/find-ideas";
import { SettingsLink } from "@/components/nav";
import { Badge, Card, CardSkeleton, Delta, Empty, Page, primaryBtn } from "@/components/ui";
import { aiEnabled, getAiSpend } from "@/lib/ai";
import { getLatestRendezvous, getPendingAdhocCards } from "@/lib/cards";
import { eur, pct, signedEur } from "@/lib/format";
import { getIdeas } from "@/lib/ideas";
import { getPortfolioState } from "@/lib/portfolio";
import { getSettings } from "@/lib/settings";
import { getGateStatus, getLeaderboard, getPea } from "@/lib/stats";
import { formatDateFr, parisDate } from "@/lib/time";
function hhmm(minutes: number) {
return `${String(Math.floor(minutes / 60)).padStart(2, "0")}h${String(minutes % 60).padStart(2, "0")}`;
}
async function HomeContent() {
/** Ce que tu as à faire : seulement la base de données, donc instantané. */
async function Todo() {
await connection();
const settings = await getSettings();
const [ai, sandbox, real, rdv, adhoc, spend] = await Promise.all([
getPortfolioState("ai_sim"),
getPortfolioState("sandbox"),
getPortfolioState("real"),
getLatestRendezvous(),
getPendingAdhocCards(),
getAiSpend(),
]);
const [pea, gate, board] = await Promise.all([getPea(settings), getGateStatus(settings, ai), getLeaderboard(settings, ai, sandbox)]);
const total = (pea?.value ?? 0) + real.equity;
const hh = String(Math.floor(settings.rendezvousMinutes / 60)).padStart(2, "0");
const mm = String(settings.rendezvousMinutes % 60).padStart(2, "0");
const [settings, rdv, adhoc, ideas] = await Promise.all([getSettings(), getLatestRendezvous(), getPendingAdhocCards(), getIdeas()]);
const isToday = rdv?.date === parisDate();
const metCount = gate.criteria.filter((c) => c.ok).length;
const cards = [...(rdv?.cards ?? []), ...adhoc];
const pending = cards.filter((c) => c.status === "pending");
const shown = isToday ? cards : pending;
return (
<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>
<>
{!settings.trAccountOpenedAt && (
<Card tone="warn" title="À configurer">
<p className="text-sm leading-relaxed">
Indique à l&apos;app où en est ton compte Trade Republic (versements, PEA, actions déjà achetées). Ça prend 1 minute, et aucun identifiant n&apos;est demandé.
</p>
<Link href="/reel" className={`${primaryBtn} mt-3 w-full`}>
Configurer mon compte
</Link>
</div>
</Card>
</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}
title={rdv ? `Rendez-vous · ${isToday ? "aujourd'hui" : formatDateFr(rdv.date)}` : "Rendez-vous du soir"}
tone={pending.length ? "accent" : undefined}
action={pending.length ? <Badge tone="accent">{pending.length} à traiter</Badge> : undefined}
>
{!rdv && <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>}
{rdv?.summary && isToday && <p className="mb-3 whitespace-pre-line text-sm leading-relaxed">{rdv.summary}</p>}
{!shown.length && (
<Empty>
Rien à faire pour l&apos;instant. Ton prochain rendez-vous arrive à {hhmm(settings.rendezvousMinutes)} (en semaine), ou lance une recherche tout de suite.
</Empty>
)}
<div className="flex flex-col gap-3">
{[...(rdv?.cards ?? []), ...adhoc].map((c) => (
<ActionCard key={c.id} id={c.id} kind={c.kind} training={c.training} status={c.status} payload={c.payload} />
{shown.map((c) => (
<ActionCard key={c.id} id={c.id} kind={c.kind} training={c.training} status={c.status} symbol={c.symbol} payload={c.payload} />
))}
</div>
<div className="mt-3">
<FindIdeas />
</div>
</Card>
<Card title="Classement depuis le début" action={<Link href="/ia" className="text-sm font-medium text-accent">Détails</Link>}>
{!pending.length && ideas && ideas.items.length > 0 && (
<Card title="Idées à tester" action={<Link href="/actions" className="text-sm font-medium text-accent">Toutes les actions</Link>}>
<ul className="flex flex-col gap-2">
{ideas.items.slice(0, 3).map((i) => (
<li key={i.symbol}>
<Link href={`/actions/${encodeURIComponent(i.symbol)}?montant=150&stop=7&objectif=12`} className="flex items-center justify-between gap-3 rounded-xl bg-surface-2 px-3 py-2.5">
<span className="font-medium">{i.name}</span>
<span className="num text-xs text-muted">
tendance +{i.trendPct} % · repli {i.pullbackPct} %
</span>
</Link>
</li>
))}
</ul>
<p className="mt-2 text-xs text-muted">Repérées par une règle simple (sans IA). À essayer dans ton bac à sable.</p>
</Card>
)}
</>
);
}
/** Patrimoine : dépend des cours (PEA + compte-titres). */
async function Wealth() {
await connection();
const settings = await getSettings();
const [real, pea] = await Promise.all([getPortfolioState("real"), getPea(settings)]);
const total = (pea?.value ?? 0) + real.equity;
return (
<Card title="Mon patrimoine">
<p className="num text-3xl font-semibold tracking-tight">{eur(total)}</p>
<div className="mt-4 grid grid-cols-2 gap-3 text-sm">
<Link href="/reel#pea" className="rounded-xl bg-surface-2 p-3">
<p className="text-muted">PEA · cœur</p>
<p className="num mt-1 text-lg font-semibold">{eur(pea?.value ?? 0)}</p>
{pea && pea.invested > 0 ? (
<p className="text-xs">
<Delta value={pea.gain}>{signedEur(pea.gain)}</Delta> <span className="text-muted">sur {eur(pea.invested, 0)}</span>
</p>
) : (
<p className="text-xs text-muted">{settings.peaPlan ? "Premier achat à venir" : "Pas encore configuré ›"}</p>
)}
</Link>
<Link href="/reel" className="rounded-xl bg-surface-2 p-3">
<p className="text-muted">Compte-titres</p>
<p className="num mt-1 text-lg font-semibold">{eur(real.equity)}</p>
<p className="text-xs text-muted">{real.positions.length ? `${real.positions.length} position(s)` : `${eur(real.cash, 0)} en liquidités ›`}</p>
</Link>
</div>
</Card>
);
}
/** Classement et critères du mode réel : dépendent de l'indice S&P 500. */
async function Progress() {
await connection();
const settings = await getSettings();
const [ai, sandbox, spend] = await Promise.all([getPortfolioState("ai_sim"), getPortfolioState("sandbox"), getAiSpend()]);
const [gate, board] = await Promise.all([getGateStatus(settings, ai), getLeaderboard(settings, ai, sandbox)]);
const met = gate.criteria.filter((c) => c.ok).length;
return (
<>
<Card title="Classement" action={<Link href="/ia" className="text-sm font-medium text-accent">Détails</Link>}>
<ol className="flex flex-col gap-2">
{board.map((row, i) => (
<li key={row.label} className="flex items-center justify-between rounded-xl bg-surface-2 px-3 py-2.5">
@ -84,23 +138,26 @@ async function HomeContent() {
<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>}
>
<Card title="Passage à l'argent réel" action={gate.realActive ? <Badge tone="accent">Débloqué</Badge> : <Badge tone="warn">{met}/5 critères</Badge>}>
{settings.realLockedReason && <p className="mb-3 text-sm text-danger">Coupe-circuit : {settings.realLockedReason}</p>}
<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>
<div className="mb-3 h-2 overflow-hidden rounded-full bg-surface-2">
<div className="h-full rounded-full bg-accent" style={{ width: `${(met / 5) * 100}%` }} />
</div>
<details>
<summary className="cursor-pointer text-sm font-medium text-accent">Voir les 5 critères</summary>
<ul className="mt-2 flex flex-col gap-2 text-sm">
{gate.criteria.map((c) => (
<li key={c.label} className="flex items-center justify-between gap-3">
<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>
</details>
</Card>
<Card title="Budget IA ce mois-ci">
@ -114,17 +171,25 @@ async function HomeContent() {
</p>
</>
) : (
<Empty>IA pas encore branchée : ajoute ta clé Anthropic (voir Réglages).</Empty>
<Empty>IA pas encore branchée : ajoute ta clé Anthropic (ANTHROPIC_API_KEY, voir le README). En attendant, l&apos;app te propose des idées sans IA.</Empty>
)}
</Card>
</Page>
</>
);
}
export default function Home() {
return (
<Suspense fallback={<PageSkeleton title={"Bonsoir 👋"} />}>
<HomeContent />
</Suspense>
<Page title="Cagnotte 🌱" subtitle="Ce qu'il y a à faire aujourd'hui." action={<SettingsLink />}>
<Suspense fallback={<CardSkeleton title="Rendez-vous du soir" height="h-32" />}>
<Todo />
</Suspense>
<Suspense fallback={<CardSkeleton title="Mon patrimoine" height="h-28" />}>
<Wealth />
</Suspense>
<Suspense fallback={<CardSkeleton title="Classement" height="h-36" />}>
<Progress />
</Suspense>
</Page>
);
}

View File

@ -1,78 +1,127 @@
import { Suspense } from "react";
import { connection } from "next/server";
import { PageSkeleton } from "@/components/page-skeleton";
import { eq } from "drizzle-orm";
import { ManualRealTrade } from "@/components/manual-real-trade";
import { ClosedList, PositionList } from "@/components/positions";
import { Badge, Card, Empty, Page } from "@/components/ui";
import { AccountForm, AddHolding, CashForms, PeaForm, RealPositions } from "@/components/account-forms";
import { SettingsLink } from "@/components/nav";
import { ClosedList } from "@/components/positions";
import { Badge, Card, CardSkeleton, Delta, Page, Stat } from "@/components/ui";
import { getDb, schema } from "@/lib/db";
import { eur } from "@/lib/format";
import { eur, signedEur } from "@/lib/format";
import { getClosedPositions, getPortfolioState } from "@/lib/portfolio";
import { getSettings } from "@/lib/settings";
import { getGateStatus } from "@/lib/stats";
import { defaultPeaPlan, getSettings } from "@/lib/settings";
import { getPea } from "@/lib/stats";
import { formatDateFr, parisDate } from "@/lib/time";
async function RealPageContent() {
async function AccountContent() {
await connection();
const db = await getDb();
const settings = await getSettings();
const [state, closed, flows, gate] = await Promise.all([
const [state, closed, flows] = await Promise.all([
getPortfolioState("real"),
getClosedPositions("real"),
db.select().from(schema.cashFlows).where(eq(schema.cashFlows.portfolioId, "real")),
getGateStatus(settings),
]);
const deposited = flows.filter((f) => f.kind === "deposit").reduce((s, f) => s + f.amount, 0);
const toPea = -flows.filter((f) => f.kind === "to_pea").reduce((s, f) => s + f.amount, 0);
const deposited = flows.filter((f) => f.kind === "deposit" || f.kind === "withdrawal").reduce((s, f) => s + f.amount, 0);
const toPea = Math.max(0, -flows.filter((f) => f.kind === "to_pea").reduce((s, f) => s + f.amount, 0));
const realActive = Boolean(settings.realUnlockedAt) && !settings.realLockedReason;
const configured = Boolean(settings.trAccountOpenedAt);
const gain = state.equity + toPea - deposited;
return (
<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>
<>
<Card>
<p className="text-sm leading-relaxed text-muted">
🔒 Trade Republic n&apos;offre pas de connexion pour les applications : l&apos;app ne se branche jamais à ton compte et ne te demandera jamais tes identifiants.
Tu lui indiques ce que tu as, elle fait les calculs et te dit quoi faire.
</p>
</Card>
<Card title="1 · Mon compte-titres" tone={configured ? undefined : "warn"} action={configured ? <Badge tone="accent">configuré</Badge> : <Badge tone="warn">à faire</Badge>}>
{configured && <p className="mb-3 text-xs text-muted">Ouvert le {formatDateFr(settings.trAccountOpenedAt!)}.</p>}
<AccountForm
openedAt={settings.trAccountOpenedAt}
monthly={settings.realMonthlyDeposit}
day={settings.realDepositDay}
auto={Boolean(settings.realDepositsStart)}
firstTime={!configured && deposited === 0}
/>
</Card>
<Card title="Ma cagnotte réelle" action={realActive ? <Badge tone="accent">Mode réel actif</Badge> : <Badge tone="warn">Simulation d&apos;abord</Badge>}>
<div className="flex items-end justify-between">
<p className="num text-3xl font-semibold">{eur(state.equity)}</p>
{deposited > 0 && <Delta value={gain}>{signedEur(gain)}</Delta>}
</div>
{!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.
<div className="mt-3 grid grid-cols-3 gap-2 text-sm">
<Stat label="liquidités">{eur(state.cash, 0)}</Stat>
<Stat label="versés">{eur(deposited, 0)}</Stat>
<Stat label="partis au PEA">{eur(toPea, 0)}</Stat>
</div>
{!realActive && (
<p className="mt-3 text-xs leading-relaxed text-muted">
Tant que l&apos;IA n&apos;a pas prouvé en simulation qu&apos;elle bat le S&amp;P 500, elle ne te propose pas de trade réel : ton argent attend sur le compte. Tu peux quand même
enregistrer ici ce que tu fais de ton côté.
</p>
)}
<div className="mt-4">
<CashForms cash={state.cash} />
</div>
</Card>
{gate.realActive && (
<Card title="Proposer mon propre trade">
<ManualRealTrade />
<Card title="2 · Mes actions chez Trade Republic">
<div className="flex flex-col gap-3">
<RealPositions positions={state.positions} />
<AddHolding />
</div>
</Card>
<Suspense fallback={<CardSkeleton title="3 · Mon PEA" height="h-40" />}>
<PeaSection />
</Suspense>
{closed.length > 0 && (
<Card title="Historique réel">
<ClosedList positions={closed} />
</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} />
async function PeaSection() {
await connection();
const settings = await getSettings();
const plan = settings.peaPlan ?? defaultPeaPlan(parisDate());
const pea = await getPea(settings);
return (
<section id="pea">
<Card title="3 · Mon PEA (cœur)">
{pea && (
<div className="mb-4 grid grid-cols-3 gap-2 text-sm">
<Stat label="valeur">{eur(pea.value, 0)}</Stat>
<Stat label="versés">{eur(pea.invested, 0)}</Stat>
<Stat label="parts">{pea.shares.toLocaleString("fr-FR", { maximumFractionDigits: 3 })}</Stat>
</div>
)}
<PeaForm
has={Boolean(settings.peaPlan)}
symbol={plan.etfSymbol}
amount={plan.monthlyAmount}
day={plan.dayOfMonth}
start={plan.startDate}
calibration={plan.calibration?.shares ?? null}
/>
</Card>
</section>
);
}
export default function AccountPage() {
return (
<Page title="Mon compte" subtitle="Ton compte Trade Republic : compte-titres (satellite) et PEA (cœur)." action={<SettingsLink />}>
<Suspense fallback={<CardSkeleton height="h-64" />}>
<AccountContent />
</Suspense>
</Page>
);
}
export default function RealPage() {
return (
<Suspense fallback={<PageSkeleton title={"Compte-titres"} />}>
<RealPageContent />
</Suspense>
);
}

View File

@ -1,15 +1,13 @@
import { Suspense } from "react";
import Link from "next/link";
import { connection } from "next/server";
import { PageSkeleton } from "@/components/page-skeleton";
import { logout, saveSettings } from "@/app/actions";
import { PushManager } from "@/components/push-manager";
import { RunNow } from "@/components/run-now";
import { Card, inputCls, Page, primaryBtn, secondaryBtn } from "@/components/ui";
import { Card, CardSkeleton, inputCls, Page, primaryBtn, secondaryBtn } from "@/components/ui";
import { aiEnabled } from "@/lib/ai";
import { getSettings } from "@/lib/settings";
export const maxDuration = 300;
function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
return (
<label className="flex flex-col gap-1 text-sm">
@ -20,74 +18,57 @@ function Field({ label, hint, children }: { label: string; hint?: string; childr
);
}
async function SettingsPageContent() {
async function SettingsForm() {
await connection();
const s = await getSettings();
const hh = String(Math.floor(s.rendezvousMinutes / 60)).padStart(2, "0");
const mm = String(s.rendezvousMinutes % 60).padStart(2, "0");
const plan = s.peaPlan;
return (
<Page title="Réglages">
<form action={saveSettings}>
<Card title="Rendez-vous et IA">
<div className="flex flex-col gap-3">
<Field label="Heure du rendez-vous" hint="Le soir, en semaine. L'IA prépare tes fiches 30 minutes avant.">
<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 (les idées sans IA continuent)."}
>
<input className={inputCls} name="aiBudget" inputMode="decimal" defaultValue={s.aiMonthlyBudgetUsd} />
</Field>
<button className={primaryBtn} type="submit">
Enregistrer
</button>
</div>
</Card>
</form>
);
}
export default function SettingsPage() {
return (
<Page
title="Réglages"
action={
<Link href="/" className="text-sm font-medium text-accent">
‹ Accueil
</Link>
}
>
<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>
<Suspense fallback={<CardSkeleton title="Rendez-vous et IA" />}>
<SettingsForm />
</Suspense>
<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="Compte Trade Republic et PEA">
<p className="mb-3 text-sm text-muted">Versements, liquidités, actions détenues et plan PEA se règlent dans l&apos;onglet « Mon compte ».</p>
<Link href="/reel" className={`${secondaryBtn} w-full`}>
Ouvrir Mon compte
</Link>
</Card>
<Card title="Lancer à la main">
<RunNow />
@ -104,11 +85,3 @@ async function SettingsPageContent() {
</Page>
);
}
export default function SettingsPage() {
return (
<Suspense fallback={<PageSkeleton title={"Réglages"} />}>
<SettingsPageContent />
</Suspense>
);
}

View File

@ -6,11 +6,24 @@ import { revalidatePath } from "next/cache";
import { askAboutStock, AiUnavailableError, type AskAnswer } from "@/lib/ai";
import { createSessionToken, isValidSession, safeEqual, SESSION_COOKIE, SESSION_DAYS } from "@/lib/auth";
import { proposeManualRealBuy, respondToCard } from "@/lib/cards";
import { runEvening, tick } from "@/lib/jobs";
import { getBars, getNews, getNextEarningsDate, getQuote, isSupportedCurrency, searchInstruments, type Quote, type SearchHit } from "@/lib/market";
import { runEvening, runEveningNow, tick } from "@/lib/jobs";
import { FEE_EUR } from "@/lib/engine/fills";
import { roundShares } from "@/lib/engine/risk";
import {
getBars,
getFxToEur,
getNews,
getNextEarningsDate,
getQuote,
isSupportedCurrency,
searchInstruments,
type Quote,
type SearchHit,
} from "@/lib/market";
import { cancelOrder, getPortfolioState, placeOrder } from "@/lib/portfolio";
import { removeSubscription, saveSubscription, sendPush } from "@/lib/push";
import { getSettings, updateSettings } from "@/lib/settings";
import { addHolding, deleteHolding, recordDeposit, recordSale, setCash } from "@/lib/real";
import { defaultPeaPlan, getSettings, updateSettings } from "@/lib/settings";
import { addDays, parisDate } from "@/lib/time";
import { getDb, schema } from "@/lib/db";
import { eq } from "drizzle-orm";
@ -73,7 +86,9 @@ export async function quoteFor(symbol: string): Promise<Quote | null> {
export async function sandboxBuy(input: {
symbol: string;
shares: number;
/** Soit un montant en euros (comme « Montant » chez Trade Republic), soit un nombre d'actions. */
amountEur?: number;
shares?: number;
type: "market" | "limit";
limitPrice?: number;
stopPct?: number;
@ -84,6 +99,13 @@ export async function sandboxBuy(input: {
if (!quote) return { ok: false, message: "Cours introuvable." };
if (!isSupportedCurrency(quote.currency)) return { ok: false, message: "Seules les actions en euros ou en dollars sont gérées." };
const ref = input.type === "limit" && input.limitPrice ? input.limitPrice : quote.price;
const fx = (await getFxToEur(quote.currency)) ?? 1;
const shares = input.amountEur ? roundShares(input.amountEur / (ref * fx)) : (input.shares ?? 0);
if (!(shares > 0)) return { ok: false, message: "Indique un montant ou un nombre d'actions." };
const state = await getPortfolioState("sandbox");
if (shares * ref * fx + FEE_EUR > state.cash + 0.01) {
return { ok: false, message: `Pas assez de liquidités : il te reste ${state.cash.toFixed(2)} € (frais de 1 € compris).` };
}
try {
const r = await placeOrder({
portfolioId: "sandbox",
@ -92,12 +114,12 @@ export async function sandboxBuy(input: {
currency: quote.currency,
side: "buy",
type: input.type,
shares: Math.floor(input.shares),
shares,
limitPrice: input.type === "limit" ? input.limitPrice : null,
stopPrice: input.stopPct ? Math.round(ref * (1 - input.stopPct / 100) * 100) / 100 : null,
targetPrice: input.targetPct ? Math.round(ref * (1 + input.targetPct / 100) * 100) / 100 : null,
});
revalidatePath("/bac-a-sable");
revalidatePath("/", "layout");
return { ok: true, message: r.message };
} catch (e) {
return { ok: false, message: e instanceof Error ? e.message : "Erreur." };
@ -119,7 +141,7 @@ export async function sandboxSell(positionId: number): Promise<{ ok: boolean; me
shares: pos.shares,
positionId: pos.id,
});
revalidatePath("/bac-a-sable");
revalidatePath("/", "layout");
return { ok: true, message: r.message };
}
@ -128,7 +150,7 @@ export async function cancelSandboxOrder(orderId: number) {
const db = await getDb();
const [o] = await db.select().from(schema.orders).where(eq(schema.orders.id, orderId));
if (o?.portfolioId === "sandbox") await cancelOrder(orderId);
revalidatePath("/bac-a-sable");
revalidatePath("/", "layout");
}
export async function resetSandbox() {
@ -195,32 +217,118 @@ export async function testPush(): Promise<number> {
// --- Réglages --------------------------------------------------------------
/** Lit un nombre saisi à la française (« 12,5 ») ; null si vide ou illisible. */
function parseNum(v: FormDataEntryValue | null): number | null {
const s = String(v ?? "").trim().replace(/\s/g, "").replace(",", ".");
if (!s) return null;
const n = Number(s);
return Number.isFinite(n) ? n : null;
}
function clampDay(n: number | null, d: number) {
return Math.min(28, Math.max(1, Math.round(n ?? d)));
}
export async function saveSettings(formData: FormData): Promise<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");
const [hh, mm] = (String(formData.get("rendezvous") ?? "") || "19:00").split(":").map(Number);
await updateSettings({
rendezvousMinutes: hh * 60 + (mm || 0),
aiMonthlyBudgetUsd: Math.max(1, num("aiBudget", s.aiMonthlyBudgetUsd)),
realMonthlyDeposit: num("realDeposit", s.realMonthlyDeposit),
realDepositDay: Math.min(28, Math.max(1, num("realDepositDay", s.realDepositDay))),
realDepositsStart: str("realDepositsStart") || null,
aiMonthlyBudgetUsd: Math.max(1, parseNum(formData.get("aiBudget")) ?? s.aiMonthlyBudgetUsd),
});
revalidatePath("/", "layout");
}
export type FormResult = { ok: boolean; message: string } | null;
/** Configuration du compte Trade Republic : ouverture, versement mensuel, argent déjà versé. */
export async function saveAccount(_prev: FormResult, formData: FormData): Promise<FormResult> {
await requireAuth();
const s = await getSettings();
const opened = String(formData.get("openedAt") ?? "").trim() || null;
const firstDeposit = parseNum(formData.get("alreadyDeposited"));
const monthly = parseNum(formData.get("monthlyDeposit"));
const day = clampDay(parseNum(formData.get("depositDay")), s.realDepositDay);
const auto = formData.get("autoDeposit") === "on";
const today = parisDate();
// Le prochain virement automatique compté par l'app : ce mois-ci si le jour n'est pas passé, sinon le mois prochain.
const nextDeposit = (() => {
const thisMonth = `${today.slice(0, 7)}-${String(day).padStart(2, "0")}`;
if (thisMonth >= today) return thisMonth;
const d = new Date(`${today.slice(0, 7)}-01T12:00:00Z`);
d.setUTCMonth(d.getUTCMonth() + 1);
return `${d.toISOString().slice(0, 7)}-${String(day).padStart(2, "0")}`;
})();
await updateSettings({
trAccountOpenedAt: opened ?? s.trAccountOpenedAt ?? today,
realMonthlyDeposit: monthly ?? s.realMonthlyDeposit,
realDepositDay: day,
realDepositsStart: auto ? (s.realDepositsStart ?? nextDeposit) : null,
});
if (firstDeposit && firstDeposit > 0) await recordDeposit(firstDeposit);
revalidatePath("/", "layout");
return { ok: true, message: "Compte enregistré ✅" };
}
export async function savePea(_prev: FormResult, formData: FormData): Promise<FormResult> {
await requireAuth();
const s = await getSettings();
if (formData.get("hasPea") !== "on") {
await updateSettings({ peaPlan: null });
revalidatePath("/", "layout");
return { ok: true, message: "PEA retiré du suivi." };
}
const base = s.peaPlan ?? defaultPeaPlan(parisDate());
const symbol = String(formData.get("peaSymbol") ?? "").trim().toUpperCase() || base.etfSymbol;
const quote = await getQuote(symbol);
if (!quote) return { ok: false, message: `ETF « ${symbol} » introuvable. Garde ESE.PA si tu as un doute.` };
const calShares = parseNum(formData.get("calibrationShares"));
await updateSettings({
peaPlan: {
etfSymbol: str("peaSymbol") || s.peaPlan?.etfSymbol || "ESE.PA",
etfName: str("peaName") || s.peaPlan?.etfName || "ETF S&P 500",
monthlyAmount: num("peaAmount", s.peaPlan?.monthlyAmount ?? 50),
dayOfMonth: Math.min(28, Math.max(1, num("peaDay", s.peaPlan?.dayOfMonth ?? 5))),
startDate: str("peaStart") || s.peaPlan?.startDate || parisDate(),
calibration: calShares ? { date: parisDate(), shares: Number(calShares) } : (s.peaPlan?.calibration ?? null),
etfSymbol: symbol,
etfName: quote.name,
monthlyAmount: parseNum(formData.get("peaAmount")) ?? base.monthlyAmount,
dayOfMonth: clampDay(parseNum(formData.get("peaDay")), base.dayOfMonth),
startDate: String(formData.get("peaStart") ?? "").trim() || base.startDate,
calibration: calShares !== null ? { date: parisDate(), shares: calShares } : (base.calibration ?? null),
},
});
revalidatePath("/", "layout");
return { ok: true, message: "PEA enregistré ✅" };
}
async function realAction(fn: () => Promise<void>, ok: string): Promise<FormResult> {
await requireAuth();
try {
await fn();
revalidatePath("/", "layout");
return { ok: true, message: ok };
} catch (e) {
return { ok: false, message: e instanceof Error ? e.message : "Erreur." };
}
}
export async function depositAction(_prev: FormResult, formData: FormData): Promise<FormResult> {
const amount = parseNum(formData.get("amount"));
return realAction(async () => recordDeposit(amount ?? NaN), "Versement enregistré ✅");
}
export async function setCashAction(_prev: FormResult, formData: FormData): Promise<FormResult> {
const cash = parseNum(formData.get("cash"));
return realAction(async () => setCash(cash ?? NaN), "Solde corrigé ✅");
}
export async function addHoldingAction(input: { symbol: string; shares: number; price: number; stopPct: number | null; paidFromCash: boolean }) {
return realAction(() => addHolding(input), "Position ajoutée ✅");
}
export async function recordSaleAction(positionId: number, price?: number) {
return realAction(() => recordSale(positionId, price), "Vente enregistrée ✅");
}
export async function deleteHoldingAction(positionId: number) {
return realAction(() => deleteHolding(positionId), "Position supprimée.");
}
export async function runNow(mode: "tick" | "evening"): Promise<string[]> {
@ -229,3 +337,11 @@ export async function runNow(mode: "tick" | "evening"): Promise<string[]> {
revalidatePath("/", "layout");
return log;
}
/** « Chercher des idées maintenant » depuis l'accueil (limité à 3 fois par jour). */
export async function findIdeasNow(): Promise<string[]> {
await requireAuth();
const log = await runEveningNow();
revalidatePath("/", "layout");
return log;
}

View File

@ -0,0 +1,312 @@
"use client";
import { useActionState, useEffect, useState, useTransition } from "react";
import {
addHoldingAction,
deleteHoldingAction,
depositAction,
recordSaleAction,
savePea,
saveAccount,
searchStocks,
setCashAction,
type FormResult,
} from "@/app/actions";
import type { SearchHit } from "@/lib/market";
import type { PositionView } from "@/lib/portfolio";
import { eur, pct, price, shares as fmtShares, signedEur } from "@/lib/format";
import { Delta, Empty, inputCls, primaryBtn, secondaryBtn } from "./ui";
function Result({ r }: { r: FormResult }) {
if (!r) return null;
return <p className={`text-sm ${r.ok ? "text-accent" : "text-danger"}`}>{r.message}</p>;
}
function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
return (
<label className="flex flex-col gap-1 text-sm">
<span className="font-medium">{label}</span>
{children}
{hint && <span className="text-xs text-muted">{hint}</span>}
</label>
);
}
const num = (s: string) => Number(s.replace(",", ".").replace(/\s/g, ""));
// ---------------------------------------------------------------------------
export function AccountForm(props: { openedAt: string | null; monthly: number; day: number; auto: boolean; firstTime: boolean }) {
const [state, action, pending] = useActionState(saveAccount, null);
return (
<form action={action} className="flex flex-col gap-3">
<Field label="Compte ouvert le" hint="Laisse la date du jour si tu ne sais plus.">
<input className={inputCls} type="date" name="openedAt" defaultValue={props.openedAt ?? new Date().toISOString().slice(0, 10)} />
</Field>
{props.firstTime && (
<Field label="Argent déjà versé sur le compte-titres (€)" hint="Ce que tu as viré jusqu'ici. Mets 0 si rien encore.">
<input className={inputCls} name="alreadyDeposited" inputMode="decimal" placeholder="ex. 50" />
</Field>
)}
<div className="grid grid-cols-2 gap-2">
<Field label="Virement / mois (€)">
<input className={inputCls} name="monthlyDeposit" inputMode="decimal" defaultValue={props.monthly} />
</Field>
<Field label="Jour du virement">
<input className={inputCls} name="depositDay" inputMode="numeric" defaultValue={props.day} />
</Field>
</div>
<label className="flex items-start gap-2 text-sm">
<input type="checkbox" name="autoDeposit" defaultChecked={props.auto} className="mt-1 h-4 w-4 accent-[var(--accent)]" />
<span>
J&apos;ai programmé ce virement chaque mois
<span className="block text-xs text-muted">L&apos;app l&apos;ajoutera toute seule à tes liquidités à chaque échéance.</span>
</span>
</label>
<button className={primaryBtn} disabled={pending}>
{pending ? "Enregistrement…" : "Enregistrer"}
</button>
<Result r={state} />
</form>
);
}
export function CashForms({ cash }: { cash: number }) {
const [dep, depAction, depPending] = useActionState(depositAction, null);
const [fix, fixAction, fixPending] = useActionState(setCashAction, null);
return (
<div className="grid gap-3">
<form action={depAction} className="flex flex-col gap-2">
<Field label="J'ai versé de l'argent (€)" hint="Un virement exceptionnel. Un montant négatif = un retrait.">
<div className="flex gap-2">
<input className={inputCls} name="amount" inputMode="decimal" placeholder="ex. 50" />
<button className={`${secondaryBtn} shrink-0`} disabled={depPending}>
Ajouter
</button>
</div>
</Field>
<Result r={dep} />
</form>
<form action={fixAction} className="flex flex-col gap-2">
<Field label="Liquidités affichées par Trade Republic (€)" hint="Pour corriger un petit écart (frais, dividendes, intérêts).">
<div className="flex gap-2">
<input className={inputCls} name="cash" inputMode="decimal" defaultValue={cash.toFixed(2)} />
<button className={`${secondaryBtn} shrink-0`} disabled={fixPending}>
Corriger
</button>
</div>
</Field>
<Result r={fix} />
</form>
</div>
);
}
// ---------------------------------------------------------------------------
export function AddHolding() {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const [hits, setHits] = useState<SearchHit[]>([]);
const [picked, setPicked] = useState<SearchHit | null>(null);
const [qty, setQty] = useState("");
const [px, setPx] = useState("");
const [stop, setStop] = useState("7");
const [paid, setPaid] = useState(true);
const [res, setRes] = useState<FormResult>(null);
const [pending, start] = useTransition();
useEffect(() => {
if (picked || query.trim().length < 2) return;
const t = setTimeout(() => searchStocks(query).then(setHits).catch(() => setHits([])), 350);
return () => clearTimeout(t);
}, [query, picked]);
if (!open)
return (
<button className={`${secondaryBtn} w-full`} onClick={() => setOpen(true)}>
+ Ajouter une action que je détiens
</button>
);
return (
<div className="flex flex-col gap-3 rounded-xl border border-line p-3">
<p className="text-sm font-semibold">Ajouter une action détenue chez Trade Republic</p>
<input
className={inputCls}
placeholder="Rechercher l'action"
value={picked ? `${picked.name} (${picked.symbol})` : 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>
)}
<div className="grid grid-cols-2 gap-2">
<Field label="Nombre d'actions">
<input className={inputCls} inputMode="decimal" value={qty} onChange={(e) => setQty(e.target.value)} placeholder="ex. 0,8421" />
</Field>
<Field label="Prix d'achat unitaire" hint="Dans la devise de l'action ($ ou €).">
<input className={inputCls} inputMode="decimal" value={px} onChange={(e) => setPx(e.target.value)} />
</Field>
</div>
<Field label="Stop (% sous le prix d'achat)" hint="Laisse vide si tu n'as pas mis d'ordre Stop.">
<input className={inputCls} inputMode="decimal" value={stop} onChange={(e) => setStop(e.target.value)} />
</Field>
<label className="flex items-start gap-2 text-sm">
<input type="checkbox" checked={paid} onChange={(e) => setPaid(e.target.checked)} className="mt-1 h-4 w-4" />
<span>
Retirer le coût de mes liquidités
<span className="block text-xs text-muted">Décoche si ces liquidités ne sont pas encore comptées dans l&apos;app (achat ancien).</span>
</span>
</label>
<div className="grid grid-cols-2 gap-2">
<button
className={primaryBtn}
disabled={pending || !picked || !(num(qty) > 0) || !(num(px) > 0)}
onClick={() =>
start(async () => {
const r = await addHoldingAction({ symbol: picked!.symbol, shares: num(qty), price: num(px), stopPct: num(stop) || null, paidFromCash: paid });
setRes(r);
if (r?.ok) {
setPicked(null);
setQuery("");
setQty("");
setPx("");
setOpen(false);
}
})
}
>
Ajouter
</button>
<button className={secondaryBtn} onClick={() => setOpen(false)}>
Annuler
</button>
</div>
<Result r={res} />
</div>
);
}
export function RealPositions({ positions }: { positions: PositionView[] }) {
if (!positions.length) return <Empty>Aucune action détenue pour l&apos;instant.</Empty>;
return (
<ul className="flex flex-col gap-2">
{positions.map((p) => (
<RealPosition key={p.id} p={p} />
))}
</ul>
);
}
function RealPosition({ p }: { p: PositionView }) {
const [selling, setSelling] = useState(false);
const [px, setPx] = useState(p.price?.toFixed(2) ?? "");
const [res, setRes] = useState<FormResult>(null);
const [pending, start] = useTransition();
return (
<li className="rounded-xl bg-surface-2 p-3">
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<p className="font-semibold">{p.name}</p>
<p className="num text-xs text-muted">
{fmtShares(p.shares)} × {price(p.entryPrice, p.currency)} → {p.price !== null ? price(p.price, p.currency) : "?"}
</p>
{p.stopPrice && <p className="num text-xs text-muted">Stop {price(p.stopPrice, 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>
{selling ? (
<div className="mt-3 flex flex-col gap-2">
<Field label={`Prix de vente obtenu (${p.currency === "USD" ? "$" : "€"})`}>
<input className={inputCls} inputMode="decimal" value={px} onChange={(e) => setPx(e.target.value)} />
</Field>
<div className="grid grid-cols-2 gap-2">
<button className={primaryBtn} disabled={pending} onClick={() => start(async () => setRes(await recordSaleAction(p.id, num(px) || undefined)))}>
Enregistrer la vente
</button>
<button className={secondaryBtn} onClick={() => setSelling(false)}>
Annuler
</button>
</div>
</div>
) : (
<div className="mt-3 grid grid-cols-2 gap-2">
<button className={`${secondaryBtn} h-9`} onClick={() => setSelling(true)}>
J&apos;ai vendu
</button>
<button
className={`${secondaryBtn} h-9 text-danger`}
disabled={pending}
onClick={() => {
if (confirm("Supprimer cette position (erreur de saisie) ? Tes liquidités ne changent pas.")) start(async () => setRes(await deleteHoldingAction(p.id)));
}}
>
Supprimer
</button>
</div>
)}
<Result r={res} />
</li>
);
}
// ---------------------------------------------------------------------------
export function PeaForm(props: { has: boolean; symbol: string; amount: number; day: number; start: string; calibration: number | null }) {
const [state, action, pending] = useActionState(savePea, null);
const [has, setHas] = useState(props.has);
return (
<form action={action} className="flex flex-col gap-3">
<label className="flex items-start gap-2 text-sm">
<input type="checkbox" name="hasPea" checked={has} onChange={(e) => setHas(e.target.checked)} className="mt-1 h-4 w-4" />
<span>
J&apos;ai un PEA avec un plan d&apos;épargne ETF
<span className="block text-xs text-muted">L&apos;app calcule sa valeur toute seule, chaque jour, à partir du cours de l&apos;ETF.</span>
</span>
</label>
{has && (
<>
<Field label="ETF du plan" hint="Symbole Yahoo. Par défaut : BNP Paribas Easy S&P 500 (ESE.PA), éligible PEA.">
<input className={inputCls} name="peaSymbol" defaultValue={props.symbol} autoCapitalize="characters" />
</Field>
<div className="grid grid-cols-2 gap-2">
<Field label="Montant / mois (€)">
<input className={inputCls} name="peaAmount" inputMode="decimal" defaultValue={props.amount} />
</Field>
<Field label="Jour du prélèvement">
<input className={inputCls} name="peaDay" inputMode="numeric" defaultValue={props.day} />
</Field>
</div>
<Field label="Premier prélèvement le">
<input className={inputCls} type="date" name="peaStart" defaultValue={props.start} />
</Field>
<Field label="Parts détenues aujourd'hui (facultatif)" hint="Le nombre exact affiché par Trade Republic, pour corriger un écart.">
<input className={inputCls} name="calibrationShares" inputMode="decimal" placeholder={props.calibration !== null ? String(props.calibration) : "ex. 4,2731"} />
</Field>
</>
)}
<button className={primaryBtn} disabled={pending}>
{pending ? "Enregistrement…" : "Enregistrer le PEA"}
</button>
<Result r={state} />
</form>
);
}

View File

@ -1,5 +1,6 @@
"use client";
import Link from "next/link";
import { useState, useTransition } from "react";
import { respondCard } from "@/app/actions";
import type { ActionPayload } from "@/lib/db/schema";
@ -10,10 +11,20 @@ type Props = {
kind: string;
training: boolean;
status: string;
symbol?: string | null;
payload: ActionPayload;
};
export function ActionCard({ id, kind, training, status, payload }: Props) {
/** Lien vers la fiche de l'action, formulaire d'achat pré-rempli avec la recette. */
function sandboxHref(symbol: string, p: ActionPayload) {
const q = new URLSearchParams();
if (p.amountEur) q.set("montant", String(Math.min(p.amountEur, 198)));
if (p.stopPct) q.set("stop", String(p.stopPct));
if (p.targetPct) q.set("objectif", String(p.targetPct));
return `/actions/${encodeURIComponent(symbol)}?${q}`;
}
export function ActionCard({ id, kind, training, status, symbol, payload }: Props) {
const [pending, start] = useTransition();
const [open, setOpen] = useState(false);
const [priceVal, setPrice] = useState(payload.limitPrice?.toString() ?? "");
@ -25,7 +36,7 @@ export function ActionCard({ id, kind, training, status, payload }: Props) {
start(async () => {
setError(null);
try {
await respondCard(id, a, needsFill ? Number(priceVal.replace(",", ".")) : undefined, needsFill ? Number(sharesVal) : undefined);
await respondCard(id, a, needsFill ? Number(priceVal.replace(",", ".")) : undefined, needsFill ? Number(sharesVal.replace(",", ".")) : undefined);
} catch (e) {
setError(e instanceof Error ? e.message : "Erreur");
}
@ -54,8 +65,14 @@ export function ActionCard({ id, kind, training, status, payload }: Props) {
))}
</ol>
{kind === "buy" && symbol && (
<Link href={sandboxHref(symbol, payload)} className={`${training ? primaryBtn : secondaryBtn} mt-4 w-full`}>
🧪 Essayer dans mon bac à sable
</Link>
)}
{status === "pending" && (
<div className="mt-4 flex flex-col gap-3">
<div className="mt-3 flex flex-col gap-3">
{needsFill && (
<div className="grid grid-cols-2 gap-2">
<label className="text-xs text-muted">
@ -64,12 +81,12 @@ export function ActionCard({ id, kind, training, status, payload }: Props) {
</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)} />
<input className={`${inputCls} mt-1`} inputMode="decimal" value={sharesVal} onChange={(e) => setShares(e.target.value)} />
</label>
</div>
)}
<div className="grid grid-cols-2 gap-2">
<button className={primaryBtn} disabled={pending} onClick={() => answer("done")}>
<button className={training ? secondaryBtn : primaryBtn} disabled={pending} onClick={() => answer("done")}>
{training ? "✅ Je l'aurais pris" : "✅ C'est fait"}
</button>
<button className={secondaryBtn} disabled={pending} onClick={() => answer("skipped")}>

View File

@ -0,0 +1,24 @@
import { after, connection } from "next/server";
import { shouldAutoTick, tick } from "@/lib/jobs";
/**
* Invisible : à l'ouverture de l'app, relance la mise à jour (ordres, stops, actus, idées)
* si elle a plus de 20 minutes. Elle tourne après l'envoi de la page : aucun ralentissement.
*/
export async function AutoTick() {
await connection();
try {
if (await shouldAutoTick()) {
after(async () => {
try {
await tick();
} catch (e) {
console.error("[auto-tick]", e);
}
});
}
} catch (e) {
console.error("[auto-tick]", e);
}
return null;
}

View File

@ -0,0 +1,32 @@
"use client";
import { useState, useTransition } from "react";
import { findIdeasNow } from "@/app/actions";
import { secondaryBtn } from "./ui";
/** Lance l'analyse du soir tout de suite, sans attendre le rendez-vous. */
export function FindIdeas({ label = "🔎 Chercher des idées maintenant" }: { label?: string }) {
const [pending, start] = useTransition();
const [log, setLog] = useState<string[] | null>(null);
return (
<div className="flex flex-col gap-2">
<button
className={`${secondaryBtn} w-full`}
disabled={pending}
onClick={() =>
start(async () => {
setLog(null);
try {
setLog(await findIdeasNow());
} catch (e) {
setLog([e instanceof Error ? e.message : "Erreur"]);
}
})
}
>
{pending ? "Analyse en cours… (jusqu'à 1 minute)" : label}
</button>
{log && log.length > 0 && <p className="text-xs text-muted">{log.at(-1)}</p>}
</div>
);
}

View File

@ -1,66 +0,0 @@
"use client";
import { useEffect, useState, useTransition } from "react";
import { proposeRealBuy, searchStocks } from "@/app/actions";
import type { SearchHit } from "@/lib/market";
import { inputCls, primaryBtn } from "./ui";
/** Ton idée de trade réel : elle passe par le même contrôle des risques que l'IA. */
export function ManualRealTrade() {
const [query, setQuery] = useState("");
const [hits, setHits] = useState<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>
);
}

View File

@ -5,19 +5,23 @@ import { usePathname } from "next/navigation";
const TABS = [
{ href: "/", label: "Accueil", icon: "M3 11.5 12 4l9 7.5V20a1 1 0 0 1-1 1h-5v-6h-6v6H4a1 1 0 0 1-1-1z" },
{ href: "/actions", label: "Actions", icon: "M3 17l5-5 4 4 8-8M15 8h5v5" },
{ href: "/bac-a-sable", label: "Bac à sable", icon: "M4 19h16M6 16l3-6 3 3 4-7 2 10" },
{ href: "/ia", label: "IA", icon: "M12 3v3m0 12v3M3 12h3m12 0h3M7 7h10v10H7zM10 10h4v4h-4z" },
{ href: "/actus", label: "Actus", icon: "M5 4h11a2 2 0 0 1 2 2v13a1 1 0 0 0 2 0V8M5 4v15a1 1 0 0 0 1 1h13M8 8h6M8 12h6M8 16h4" },
{ href: "/reglages", label: "Réglages", icon: "M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19 12l2-1-2-4-2 .5-1.5-1L15 4h-6l-.5 2.5-1.5 1L5 7l-2 4 2 1v0l-2 1 2 4 2-.5 1.5 1L9 20h6l.5-2.5 1.5-1 2 .5 2-4z" },
{ href: "/reel", label: "Mon compte", icon: "M3 7h18v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1zM3 7l2-3h14l2 3M16 13h2" },
];
export function Nav() {
const pathname = usePathname();
return <NavBar pathname={usePathname()} />;
}
/** La même barre sans onglet actif : affichée instantanément, avant que l'adresse soit connue. */
export function NavBar({ pathname }: { pathname: string | null }) {
return (
<nav className="fixed inset-x-0 bottom-0 z-20 border-t border-line bg-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);
const active = pathname !== null && (t.href === "/" ? pathname === "/" : pathname.startsWith(t.href));
return (
<li key={t.href} className="flex-1">
<Link
@ -36,3 +40,14 @@ export function Nav() {
</nav>
);
}
/** Raccourci vers les réglages, en haut à droite des pages. */
export function SettingsLink() {
return (
<Link href="/reglages" aria-label="Réglages" className="flex h-9 w-9 items-center justify-center rounded-full border border-line bg-surface text-muted">
<svg viewBox="0 0 24 24" className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth={1.7} strokeLinecap="round" strokeLinejoin="round" aria-hidden>
<path d="M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19 12l2-1-2-4-2 .5-1.5-1L15 4h-6l-.5 2.5-1.5 1L5 7l-2 4 2 1-2 1 2 4 2-.5 1.5 1L9 20h6l.5-2.5 1.5-1 2 .5 2-4z" />
</svg>
</Link>
);
}

View File

@ -1,8 +1,9 @@
"use client";
import Link from "next/link";
import { useTransition } from "react";
import { cancelSandboxOrder, sandboxSell } from "@/app/actions";
import { eur, EXIT_REASONS, pct, price, signedEur } from "@/lib/format";
import { eur, EXIT_REASONS, pct, price, shares, signedEur } from "@/lib/format";
import type { Order, Position, PositionView } from "@/lib/portfolio";
import { Delta, Empty, secondaryBtn } from "./ui";
@ -14,10 +15,12 @@ export function PositionList({ positions, sellable = false }: { positions: Posit
{positions.map((p) => (
<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>
<div className="min-w-0">
<Link href={`/actions/${encodeURIComponent(p.symbol)}`} className="font-semibold">
{p.name}
</Link>
<p className="num text-xs text-muted">
{p.shares} × {price(p.entryPrice, p.currency)} → {p.price !== null ? price(p.price, p.currency) : "?"}
{shares(p.shares)} × {price(p.entryPrice, p.currency)} → {p.price !== null ? price(p.price, p.currency) : "?"}
</p>
</div>
<div className="text-right">
@ -61,7 +64,7 @@ export function PendingOrders({ orders, cancellable = false }: { orders: Order[]
{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}
{o.side === "buy" ? "Achat" : "Vente"} {shares(o.shares)} {o.name}
<span className="num block text-xs text-muted">
{o.type === "limit" && o.limitPrice ? `limite ${price(o.limitPrice, o.currency)}` : "au marché"}
{o.validUntil ? ` · valable jusqu'au ${o.validUntil}` : ""}

View File

@ -1,183 +0,0 @@
"use client";
import { useEffect, useState, useTransition } from "react";
import { askAi, quoteFor, sandboxBuy, searchStocks } from "@/app/actions";
import type { AskAnswer } from "@/lib/ai";
import { pct, price } from "@/lib/format";
import type { Quote, SearchHit } from "@/lib/market";
import { Badge, Card, inputCls, primaryBtn, secondaryBtn } from "./ui";
export function SandboxTrader({ askLeft }: { askLeft: number }) {
const [query, setQuery] = useState("");
const [hits, setHits] = useState<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>
);
}

View File

@ -0,0 +1,108 @@
"use client";
import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { searchStocks } from "@/app/actions";
import type { SearchHit } from "@/lib/market";
import { pct, price } from "@/lib/format";
import { Badge, inputCls } from "./ui";
export type StockRow = {
symbol: string;
name: string;
market: "US" | "EU";
price: number | null;
currency: string;
changePct: number | null;
news: number;
held: boolean;
};
const FILTERS = [
{ id: "all", label: "Toutes" },
{ id: "US", label: "🇺🇸 US" },
{ id: "EU", label: "🇪🇺 Europe" },
{ id: "news", label: "Avec actus" },
{ id: "up", label: "En hausse" },
{ id: "down", label: "En baisse" },
] as const;
export function StockBrowser({ rows }: { rows: StockRow[] }) {
const [filter, setFilter] = useState<(typeof FILTERS)[number]["id"]>("all");
const [query, setQuery] = useState("");
const [hits, setHits] = useState<SearchHit[]>([]);
const q = query.trim().toLowerCase();
const list = useMemo(() => {
let r = rows;
if (filter === "US" || filter === "EU") r = r.filter((x) => x.market === filter);
if (filter === "news") r = r.filter((x) => x.news > 0).sort((a, b) => b.news - a.news);
if (filter === "up") r = r.filter((x) => (x.changePct ?? 0) > 0).sort((a, b) => (b.changePct ?? 0) - (a.changePct ?? 0));
if (filter === "down") r = r.filter((x) => (x.changePct ?? 0) < 0).sort((a, b) => (a.changePct ?? 0) - (b.changePct ?? 0));
if (q) r = r.filter((x) => x.name.toLowerCase().includes(q) || x.symbol.toLowerCase().includes(q));
return r;
}, [rows, filter, q]);
// Pas trouvée dans la liste surveillée ? On cherche dans toute la bourse.
useEffect(() => {
if (q.length < 2 || list.length > 0) return;
const t = setTimeout(() => searchStocks(q).then(setHits).catch(() => setHits([])), 350);
return () => clearTimeout(t);
}, [q, list.length]);
const showHits = q.length >= 2 && list.length === 0;
return (
<div className="flex flex-col gap-3">
<input className={inputCls} placeholder="Rechercher : Apple, LVMH, Airbus…" value={query} onChange={(e) => setQuery(e.target.value)} type="search" />
<div className="-mx-4 flex gap-2 overflow-x-auto px-4 pb-1">
{FILTERS.map((f) => (
<button
key={f.id}
onClick={() => setFilter(f.id)}
className={`shrink-0 rounded-full border px-3 py-1.5 text-sm font-medium ${filter === f.id ? "border-accent bg-accent-soft text-accent" : "border-line bg-surface text-muted"}`}
>
{f.label}
</button>
))}
</div>
<ul className="overflow-hidden rounded-2xl border border-line bg-surface">
{list.map((r) => (
<li key={r.symbol} className="border-b border-line last:border-0">
<Link href={`/actions/${encodeURIComponent(r.symbol)}`} className="flex items-center justify-between gap-3 px-4 py-3 active:bg-surface-2">
<span className="min-w-0">
<span className="flex items-center gap-1.5 font-medium">
<span className="truncate">{r.name}</span>
{r.held && <Badge tone="accent">détenue</Badge>}
</span>
<span className="block text-xs text-muted">
{r.symbol}
{r.news > 0 && ` · 📰 ${r.news} actu${r.news > 1 ? "s" : ""}`}
</span>
</span>
<span className="shrink-0 text-right">
<span className="num block font-semibold">{r.price !== null ? price(r.price, r.currency) : "—"}</span>
{r.changePct !== null && <span className={`num text-xs ${r.changePct >= 0 ? "text-accent" : "text-danger"}`}>{pct(r.changePct, 2)}</span>}
</span>
</Link>
</li>
))}
{showHits &&
hits.map((h) => (
<li key={h.symbol} className="border-b border-line last:border-0">
<Link href={`/actions/${encodeURIComponent(h.symbol)}`} className="flex items-center justify-between gap-3 px-4 py-3">
<span>
<span className="font-medium">{h.name}</span>
<span className="block text-xs text-muted">
{h.symbol} · {h.exchange}
</span>
</span>
<Badge>{h.type === "ETF" ? "ETF" : "Action"}</Badge>
</Link>
</li>
))}
{!list.length && !(showHits && hits.length) && <li className="px-4 py-6 text-center text-sm text-muted">Aucune action trouvée.</li>}
</ul>
</div>
);
}

View File

@ -0,0 +1,29 @@
import type { Bar } from "@/lib/engine/fills";
/** Courbe de cours en SVG, rendue côté serveur (aucune librairie, aucun JavaScript côté téléphone). */
export function StockChart({ bars, lastPrice, stop, target }: { bars: Bar[]; lastPrice?: number | null; stop?: number | null; target?: number | null }) {
const closes = bars.map((b) => b.close);
if (lastPrice) closes.push(lastPrice);
if (closes.length < 2) return <p className="py-6 text-center text-sm text-muted">Pas d&apos;historique disponible.</p>;
const W = 320;
const H = 120;
const levels = [stop, target].filter((x): x is number => typeof x === "number");
const min = Math.min(...closes, ...levels);
const max = Math.max(...closes, ...levels);
const span = max - min || 1;
const x = (i: number) => (i / (closes.length - 1)) * W;
const y = (v: number) => H - 6 - ((v - min) / span) * (H - 12);
const path = closes.map((c, i) => `${i ? "L" : "M"}${x(i).toFixed(1)},${y(c).toFixed(1)}`).join(" ");
const up = closes.at(-1)! >= closes[0];
const color = up ? "var(--accent)" : "var(--danger)";
return (
<svg viewBox={`0 0 ${W} ${H}`} className="h-32 w-full" preserveAspectRatio="none" role="img" aria-label="Évolution du cours">
<path d={`${path} L${W},${H} L0,${H} Z`} fill={color} opacity={0.1} />
<path d={path} fill="none" stroke={color} strokeWidth={2} vectorEffect="non-scaling-stroke" strokeLinejoin="round" />
{stop != null && <line x1={0} x2={W} y1={y(stop)} y2={y(stop)} stroke="var(--danger)" strokeDasharray="4 4" vectorEffect="non-scaling-stroke" />}
{target != null && <line x1={0} x2={W} y1={y(target)} y2={y(target)} stroke="var(--accent)" strokeDasharray="4 4" vectorEffect="non-scaling-stroke" />}
</svg>
);
}

View File

@ -0,0 +1,218 @@
"use client";
import Link from "next/link";
import { useState, useTransition } from "react";
import { askAi, proposeRealBuy, sandboxBuy } from "@/app/actions";
import type { AskAnswer } from "@/lib/ai";
import { eur, price } from "@/lib/format";
import { Badge, Card, inputCls, primaryBtn, secondaryBtn } from "./ui";
type Props = {
symbol: string;
currency: string;
lastPrice: number;
fxToEur: number;
cash: number;
askLeft: number;
aiOn: boolean;
realActive: boolean;
defaults: { amount?: number; stopPct?: number; targetPct?: number };
};
const num = (s: string) => Number(s.replace(",", ".")) || 0;
export function TradePanel({ symbol, currency, lastPrice, fxToEur, cash, askLeft, aiOn, realActive, defaults }: Props) {
const [mode, setMode] = useState<"amount" | "shares">("amount");
const [amount, setAmount] = useState(String(defaults.amount ?? Math.min(150, Math.floor(Math.max(cash - 1, 0)))));
const [shares, setShares] = useState("1");
const [type, setType] = useState<"market" | "limit">("market");
const [limit, setLimit] = useState(lastPrice.toFixed(2));
const [stopPct, setStopPct] = useState(String(defaults.stopPct ?? 7));
const [targetPct, setTargetPct] = useState(defaults.targetPct ? String(defaults.targetPct) : "12");
const [message, setMessage] = useState<{ ok: boolean; text: string } | null>(null);
const [question, setQuestion] = useState("");
const [answer, setAnswer] = useState<AskAnswer | null>(null);
const [buying, startBuy] = useTransition();
const [asking, startAsk] = useTransition();
const unit = type === "limit" ? num(limit) : lastPrice;
const qty = mode === "amount" ? (unit > 0 ? num(amount) / (unit * fxToEur) : 0) : num(shares);
const costEur = qty * unit * fxToEur;
const stop = num(stopPct);
const target = num(targetPct);
const maxLoss = stop > 0 ? costEur * (stop / 100) + 2 : null;
const tooMuch = costEur + 1 > cash + 0.01;
const buy = () =>
startBuy(async () => {
setMessage(null);
const r = await sandboxBuy({
symbol,
type,
amountEur: mode === "amount" ? num(amount) : undefined,
shares: mode === "shares" ? num(shares) : undefined,
limitPrice: type === "limit" ? unit : undefined,
stopPct: stop || undefined,
targetPct: target || undefined,
});
setMessage({ ok: r.ok, text: r.message });
});
const toggle = (active: boolean) => (active ? "border-accent bg-accent-soft text-accent" : "border-line bg-surface-2 text-muted");
return (
<>
<Card title="Acheter dans mon bac à sable" action={<span className="num text-xs text-muted">dispo {eur(cash)}</span>}>
<div className="flex flex-col gap-3">
<div className="grid grid-cols-2 gap-2 text-sm font-medium">
<button className={`h-10 rounded-xl border ${toggle(mode === "amount")}`} onClick={() => setMode("amount")}>
Montant en €
</button>
<button className={`h-10 rounded-xl border ${toggle(mode === "shares")}`} onClick={() => setMode("shares")}>
Nb d&apos;actions
</button>
</div>
{mode === "amount" ? (
<label className="text-xs text-muted">
Montant à investir (€)
<input className={`${inputCls} mt-1`} inputMode="decimal" value={amount} onChange={(e) => setAmount(e.target.value)} />
<span className="mt-1 flex gap-2">
{[50, 100, 150].map((v) => (
<button key={v} className="rounded-full border border-line px-2.5 py-1 text-xs" onClick={() => setAmount(String(v))}>
{v} €
</button>
))}
<button className="rounded-full border border-line px-2.5 py-1 text-xs" onClick={() => setAmount(String(Math.floor(Math.max(cash - 1, 0))))}>
Tout
</button>
</span>
</label>
) : (
<label className="text-xs text-muted">
Nombre d&apos;actions (fractions possibles)
<input className={`${inputCls} mt-1`} inputMode="decimal" value={shares} onChange={(e) => setShares(e.target.value)} />
</label>
)}
<div className="grid grid-cols-2 gap-2 text-sm font-medium">
<button className={`h-10 rounded-xl border ${toggle(type === "market")}`} onClick={() => setType("market")}>
Au marché
</button>
<button className={`h-10 rounded-xl border ${toggle(type === "limit")}`} onClick={() => setType("limit")}>
Cours limité
</button>
</div>
{type === "limit" && (
<label className="text-xs text-muted">
N&apos;acheter que si le cours descend à ({currency === "EUR" ? "€" : "$"})
<input className={`${inputCls} mt-1`} inputMode="decimal" value={limit} onChange={(e) => setLimit(e.target.value)} />
</label>
)}
<div className="grid grid-cols-2 gap-2">
<label className="text-xs text-muted">
Stop : vendre si −{stop || "?"} %
<input className={`${inputCls} mt-1`} inputMode="decimal" value={stopPct} onChange={(e) => setStopPct(e.target.value)} placeholder="aucun" />
</label>
<label className="text-xs text-muted">
Objectif : vendre à +{target || "?"} %
<input className={`${inputCls} mt-1`} inputMode="decimal" value={targetPct} onChange={(e) => setTargetPct(e.target.value)} placeholder="aucun" />
</label>
</div>
<div className="rounded-xl bg-surface-2 p-3 text-sm">
<p className="num">
≈ {qty.toLocaleString("fr-FR", { maximumFractionDigits: 4 })} action · {eur(costEur)} + 1 € de frais
</p>
{stop > 0 && unit > 0 && (
<p className="num mt-1 text-xs text-muted">
Stop à {price(unit * (1 - stop / 100), currency)} → perte max ≈ {eur(maxLoss ?? 0, 0)}
{target > 0 && ` · objectif ${price(unit * (1 + target / 100), currency)}`}
</p>
)}
{tooMuch && <p className="mt-1 text-xs text-danger">Pas assez de liquidités dans ton bac à sable.</p>}
</div>
<button className={primaryBtn} disabled={buying || qty <= 0 || tooMuch} onClick={buy}>
{buying ? "Envoi…" : "Acheter (argent fictif)"}
</button>
{message && (
<p className={`text-sm ${message.ok ? "text-accent" : "text-danger"}`}>
{message.text}{" "}
{message.ok && (
<Link href="/bac-a-sable" className="font-medium underline">
Voir mon bac à sable
</Link>
)}
</p>
)}
</div>
</Card>
<Card title="🤖 L'avis de l'IA">
{!aiOn ? (
<p className="text-sm text-muted">L&apos;IA n&apos;est pas branchée (clé Anthropic manquante, voir le README). Tout le reste fonctionne sans elle.</p>
) : (
<div className="flex flex-col gap-2">
<p className="text-xs text-muted">{askLeft} avis restant(s) aujourd&apos;hui</p>
<input className={inputCls} placeholder="Ex. : c'est le bon moment pour acheter ?" value={question} onChange={(e) => setQuestion(e.target.value)} />
<button
className={secondaryBtn}
disabled={asking || askLeft <= 0}
onClick={() =>
startAsk(async () => {
setAnswer(null);
const r = await askAi(symbol, question);
if (r.ok) setAnswer(r.answer);
else setMessage({ ok: false, text: r.message });
})
}
>
{asking ? "L'IA réfléchit… (≈ 20 s)" : "Demander son avis"}
</button>
{answer && (
<div className="mt-1 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>
)}
</Card>
{realActive && <RealProposal symbol={symbol} stopPct={stop || 7} />}
</>
);
}
/** Mode réel débloqué : crée une fiche réelle, contrôlée par les mêmes règles que l'IA. */
function RealProposal({ symbol, stopPct }: { symbol: string; stopPct: number }) {
const [pending, start] = useTransition();
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
return (
<Card title="Pour de vrai (Trade Republic)">
<p className="mb-3 text-sm text-muted">Le contrôle des risques vérifie la taille et le stop, puis te prépare une fiche pas à pas.</p>
<button
className={`${secondaryBtn} w-full`}
disabled={pending}
onClick={() =>
start(async () => {
const r = await proposeRealBuy(symbol, stopPct);
setMsg(r.ok ? { ok: true, text: "Fiche créée : retrouve-la sur l'accueil." } : { ok: false, text: r.reason });
})
}
>
Vérifier et créer la fiche réelle
</button>
{msg && <p className={`mt-2 text-sm ${msg.ok ? "text-accent" : "text-danger"}`}>{msg.text}</p>}
</Card>
);
}

View File

@ -1,11 +1,14 @@
import type { ReactNode } from "react";
export function Page({ title, subtitle, children }: { title: string; subtitle?: ReactNode; children: ReactNode }) {
export function Page({ title, subtitle, action, children }: { title: string; subtitle?: ReactNode; action?: ReactNode; children: ReactNode }) {
return (
<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 className="mb-5 flex items-start justify-between gap-3">
<div className="min-w-0">
<h1 className="text-2xl font-semibold tracking-tight">{title}</h1>
{subtitle && <p className="mt-1 text-sm text-muted">{subtitle}</p>}
</div>
{action && <div className="shrink-0 pt-1">{action}</div>}
</header>
<div className="flex flex-col gap-4">{children}</div>
</main>
@ -42,6 +45,25 @@ export function Delta({ value, children }: { value: number; children: ReactNode
return <span className={`num font-medium ${value >= 0 ? "text-accent" : "text-danger"}`}>{children}</span>;
}
/** Bloc de chargement pour une section qui attend des cours de bourse. */
export function CardSkeleton({ title, height = "h-24" }: { title?: string; height?: string }) {
return (
<section className="rounded-2xl border border-line bg-surface p-4">
{title && <h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-muted">{title}</h2>}
<div className={`${height} animate-pulse rounded-xl bg-surface-2`} />
</section>
);
}
export function Stat({ label, children }: { label: string; children: ReactNode }) {
return (
<div className="rounded-xl bg-surface-2 p-2.5 text-center">
<p className="num font-semibold">{children}</p>
<p className="text-xs text-muted">{label}</p>
</div>
);
}
export function Empty({ children }: { children: ReactNode }) {
return <p className="py-2 text-sm text-muted">{children}</p>;
}

View File

@ -6,7 +6,7 @@ import { gte } from "drizzle-orm";
import { z } from "zod";
import { getDb, schema } from "./db";
import { getSettings } from "./settings";
import { parisDate } from "./time";
import { addDays, parisDate } from "./time";
/**
* L'IA en entonnoir, validée pour tenir dans 5-10 €/mois :
@ -48,21 +48,23 @@ async function recordUsage(model: string, purpose: string, usage: { input_tokens
});
}
export async function getAiSpend(): Promise<{ monthUsd: number; totalUsd: number; askToday: number }> {
export async function getAiSpend(): Promise<{ monthUsd: number; askToday: number }> {
const db = await getDb();
const rows = await db.select().from(schema.aiUsage);
const monthStart = `${parisDate().slice(0, 7)}-01`;
const today = parisDate();
// Marge d'un jour pour le fuseau horaire, puis filtre exact à l'heure de Paris.
const rows = await db
.select({ at: schema.aiUsage.at, costUsd: schema.aiUsage.costUsd, purpose: schema.aiUsage.purpose })
.from(schema.aiUsage)
.where(gte(schema.aiUsage.at, new Date(`${addDays(monthStart, -1)}T00:00:00Z`)));
let monthUsd = 0;
let totalUsd = 0;
let askToday = 0;
for (const r of rows) {
totalUsd += r.costUsd;
const d = parisDate(r.at);
if (d >= monthStart) monthUsd += r.costUsd;
if (r.purpose === "ask" && d === today) askToday++;
}
return { monthUsd, totalUsd, askToday };
return { monthUsd, askToday };
}
/** Bloque les appels si le plafond mensuel est atteint. Le tri des actus garde une petite réserve. */
@ -171,6 +173,8 @@ export type AnalysisContext = {
closes30d: { date: string; close: number }[];
nextEarningsDate: string | null;
news: { title: string; publisher: string | null; publishedAt: string; triage: string }[];
/** Si l'action vient du filtre technique (repli dans une tendance haussière) plutôt que d'une actu. */
technicalSignal?: string | null;
today: string;
};
@ -184,6 +188,7 @@ Méthode :
3. Les effets les plus fiables sont la dérive après des résultats nettement meilleurs que prévu, les annonces concrètes (contrats, rachats d'actions, relèvement des prévisions) et les réactions excessives à une nouvelle mineure.
4. Sois sélectif : la plupart du temps, la bonne réponse est "pass". Ne réponds "buy" avec une confiance ≥ 70 que si l'argument est solide et pas encore dans le prix.
5. Ne t'appuie que sur les données fournies et sur des connaissances générales sûres. Ne cite aucun chiffre que tu n'as pas.
6. Si "technicalSignal" est rempli, l'action t'est proposée pour un repli dans une tendance haussière, pas pour une actu : vérifie dans les actus et le cours que le recul n'a pas une mauvaise raison durable.
Écris thesis et risks en français simple, sans jargon, comme pour un ami qui débute.`;

View File

@ -13,7 +13,7 @@ delete process.env.DATABASE_URL;
delete process.env.ANTHROPIC_API_KEY;
const { getDb, schema } = await import("./db");
const { ensureSetup } = await import("./settings");
const { defaultPeaPlan, ensureSetup } = await import("./settings");
const { collectNews } = await import("./news");
const { getPortfolioState, placeOrder, processAll } = await import("./portfolio");
const { getQuote } = await import("./market");
@ -125,7 +125,8 @@ describe("intégration", () => {
expect(rdv.summary).toContain("Anthropic");
const settings = await ensureSetup();
const pea = await getPea({ ...settings, peaPlan: { ...settings.peaPlan!, startDate: addDays(parisDate(), -120) } });
expect(settings.peaPlan).toBeNull(); // pas de PEA inventé tant que tu ne l'as pas déclaré
const pea = await getPea({ ...settings, peaPlan: defaultPeaPlan(addDays(parisDate(), -120)) });
expect(pea!.invested).toBeGreaterThanOrEqual(150);
expect(pea!.value).toBeGreaterThan(0);
@ -135,4 +136,21 @@ describe("intégration", () => {
const board = await getLeaderboard(settings, await getPortfolioState("ai_sim"), await getPortfolioState("sandbox"));
expect(board.map((b) => b.label).sort()).toEqual(["L'IA", "S&P 500", "Toi"]);
});
it("sans IA, propose une idée du filtre et permet un achat fractionné", async () => {
const { refreshIdeas } = await import("./ideas");
const ideas = await refreshIdeas(true);
await runEvening();
const db = await getDb();
const cards = await db.select().from(schema.actions).where(eq(schema.actions.status, "pending"));
// Le marché ne donne pas toujours d'idée : la fiche n'existe que s'il y en a une.
if (ideas.items.length) expect(cards.some((c) => c.training && c.payload.source === "screen")).toBe(true);
// Une fraction d'une action chère, comme « Montant » chez Trade Republic.
const s = await getPortfolioState("sandbox");
const q = (await getQuote("MC.PA"))!;
const r = await placeOrder({ portfolioId: "sandbox", symbol: "MC.PA", name: q.name, currency: "EUR", side: "buy", type: "limit", shares: 0.25, limitPrice: q.price * 2 });
expect(r.order.shares).toBe(0.25);
expect(s.cash).toBeGreaterThan(0);
});
});

View File

@ -107,16 +107,18 @@ export async function proposeManualRealBuy(symbol: string, stopPct: number) {
training: false,
symbol,
payload: {
title: `Acheter ${r.shares} ${quote.name} (~${Math.round(r.costEur)} €) — ton idée`,
title: `Acheter ${quote.name} pour ${r.amountEur} € — ton idée`,
why: "Trade proposé par toi, validé par le contrôle des risques.",
steps: [
`Dans Trade Republic (compte-titres), cherche « ${quote.name} ».`,
`Acheter → Ordre à cours limité : ${r.shares} action(s), limite ${r.limitPrice.toFixed(2)} ${cur}.`,
`Dès que l'achat est fait : ordre Stop (vente) à ${r.stopPrice.toFixed(2)} ${cur}. Perte maximale ≈ ${r.maxLossEur.toFixed(0)} €.`,
`Dans Trade Republic (compte-titres), cherche « ${quote.name} » et touche Acheter.`,
`Choisis « Montant » et saisis ${r.amountEur} €. N'achète pas si le cours dépasse ${r.limitPrice.toFixed(2)} ${cur}.`,
`Une fois acheté : ordre Stop (vente) à ${r.stopPrice.toFixed(2)} ${cur}. Perte maximale ≈ ${r.maxLossEur.toFixed(0)} €.`,
],
name: quote.name,
currency: quote.currency,
shares: r.shares,
amountEur: r.amountEur,
source: "manual",
limitPrice: r.limitPrice,
stopPrice: r.stopPrice,
targetPrice: r.targetPrice,

View File

@ -38,7 +38,7 @@ export const positions = pgTable("positions", {
symbol: text("symbol").notNull(),
name: text("name").notNull(),
currency: text("currency").notNull(),
shares: integer("shares").notNull(),
shares: doublePrecision("shares").notNull(),
entryPrice: doublePrecision("entry_price").notNull(), // devise locale
entryFx: doublePrecision("entry_fx").notNull(), // 1 unité locale = entryFx €
openedAt: timestamp("opened_at", { withTimezone: true }).notNull(),
@ -64,7 +64,7 @@ export const orders = pgTable("orders", {
side: text("side").notNull(), // buy | sell
type: text("type").notNull(), // market | limit
limitPrice: doublePrecision("limit_price"),
shares: integer("shares").notNull(),
shares: doublePrecision("shares").notNull(),
stopPrice: doublePrecision("stop_price"), // appliqué à la position à l'exécution
targetPrice: doublePrecision("target_price"),
maxExitDate: text("max_exit_date"),
@ -167,6 +167,9 @@ export type ActionPayload = {
positionId?: number;
signalId?: number;
amountEur?: number;
stopPct?: number;
targetPct?: number;
source?: "ai" | "screen" | "manual";
};
export const aiUsage = pgTable("ai_usage", {

View File

@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { evaluateBuyLimit, evaluateExit, type Bar } from "./fills";
import { checkBuy, tierFor } from "./risk";
import { screenBars } from "./screen";
import { computePea } from "./pea";
import { computeGate, maxDrawdownPct } from "./gate";
import { circuitBreakerTripped, computeRatchet } from "./ratchet";
@ -103,7 +104,9 @@ describe("contrôle des risques", () => {
const r = checkBuy(base);
expect(r.ok).toBe(true);
if (!r.ok) return;
expect(r.shares).toBe(3);
expect(r.amountEur).toBe(198);
expect(r.shares).toBeCloseTo(198 / (60.3 / 1.12), 3);
expect(r.costEur).toBeLessThanOrEqual(198);
expect(r.costEur).toBeGreaterThanOrEqual(150);
expect(r.stopPrice).toBeCloseTo(60.3 * 0.93, 1);
expect(r.maxExitDate).toBe(addTradingDays("2026-10-12", 10));
@ -114,8 +117,16 @@ describe("contrôle des risques", () => {
expect(r.ok).toBe(false);
});
it("refuse une action trop chère pour la cagnotte", () => {
it("achète une fraction d'une action chère (achat par montant)", () => {
const r = checkBuy({ ...base, symbol: "ASML.AS", priceLocal: 1600, fxToEur: 1 });
expect(r.ok).toBe(true);
if (!r.ok) return;
expect(r.shares).toBeLessThan(1);
expect(r.amountEur).toBe(198);
});
it("refuse quand il reste trop peu de liquidités", () => {
const r = checkBuy({ ...base, cash: 90 });
expect(r.ok).toBe(false);
});
@ -176,3 +187,24 @@ describe("cliquet et coupe-circuit", () => {
expect(circuitBreakerTripped(160, 300)).toBe(false);
});
});
describe("filtre d'idées sans IA", () => {
const series = (closes: number[]): Bar[] =>
closes.map((c, i) => ({ date: `d${String(i).padStart(3, "0")}`, open: c, high: c, low: c, close: c }));
const up = Array.from({ length: 60 }, (_, i) => 100 + i);
it("repère un repli dans une tendance haussière", () => {
const r = screenBars(series(up), 150);
expect(r).not.toBeNull();
expect(r!.pullbackPct).toBeLessThan(-2);
});
it("ignore une action en baisse", () => {
const down = Array.from({ length: 60 }, (_, i) => 200 - i);
expect(screenBars(series(down), 138)).toBeNull();
});
it("ignore une action qui n'a pas reculé", () => {
expect(screenBars(series(up), 160)).toBeNull();
});
});

View File

@ -43,6 +43,7 @@ export type RiskResult =
| {
ok: true;
shares: number;
amountEur: number; // montant à investir chez Trade Republic (achat par montant)
limitPrice: number;
stopPrice: number;
targetPrice: number;
@ -81,12 +82,14 @@ export function checkBuy(input: RiskInput): RiskResult {
if (tier.maxRiskPct !== null) {
budget = Math.min(budget, (equity * tier.maxRiskPct) / (stopPct / 100));
}
const shares = Math.floor(budget / priceEur);
// Trade Republic permet d'acheter par montant (fractions d'actions) : on investit un montant rond en euros.
const amountEur = Math.floor(Math.max(budget, 0));
const shares = roundShares(amountEur / priceEur);
const costEur = shares * priceEur;
if (shares < 1 || costEur < MIN_POSITION_EUR) {
if (shares <= 0 || amountEur < MIN_POSITION_EUR) {
return {
ok: false,
reason: `Position trop petite (${Math.round(Math.max(costEur, 0))} € possible, minimum ${MIN_POSITION_EUR} € pour que les frais restent faibles).`,
reason: `Pas assez de liquidités (${amountEur} € possibles, minimum ${MIN_POSITION_EUR} € par position pour que les frais restent faibles).`,
};
}
@ -96,6 +99,7 @@ export function checkBuy(input: RiskInput): RiskResult {
return {
ok: true,
shares,
amountEur,
limitPrice,
stopPrice,
targetPrice,
@ -105,6 +109,11 @@ export function checkBuy(input: RiskInput): RiskResult {
};
}
/** Fractions d'actions : 4 décimales, arrondi vers le bas pour ne jamais dépasser le budget. */
export function roundShares(n: number): number {
return Math.floor(n * 10_000) / 10_000;
}
function round(n: number): number {
return Math.round(n * 100) / 100;
}

42
src/lib/engine/screen.ts Normal file
View File

@ -0,0 +1,42 @@
/**
* Filtre « repli dans une tendance haussière » : fonction pure, testée dans engine.test.ts.
*
* Idée : une grande action solidement orientée à la hausse (moyenne 20 jours au-dessus de la
* moyenne 50 jours, cours au-dessus de la moyenne 50 jours) qui vient de reculer de 2 à 8 %
* en une semaine. On achète le repli, pas le sommet. Ce n'est pas une garantie : c'est une
* règle simple, mesurée honnêtement dans le bac à sable.
*/
import type { Bar } from "./fills";
export type Screen = {
score: number;
trendPct: number; // écart moyenne 20 j / moyenne 50 j, en %
pullbackPct: number; // variation sur 5 séances, en % (négatif = repli)
reason: string;
};
function sma(values: number[], n: number): number | null {
if (values.length < n) return null;
const slice = values.slice(-n);
return slice.reduce((s, x) => s + x, 0) / n;
}
export function screenBars(bars: Bar[], lastPrice: number): Screen | null {
const closes = bars.map((b) => b.close);
if (closes.length < 55) return null;
const sma20 = sma(closes, 20)!;
const sma50 = sma(closes, 50)!;
const ref = closes[closes.length - 6]; // il y a 5 séances
const trendPct = (sma20 / sma50 - 1) * 100;
const pullbackPct = (lastPrice / ref - 1) * 100;
const aboveTrend = lastPrice > sma50;
if (!aboveTrend || trendPct < 1 || pullbackPct > -2 || pullbackPct < -8) return null;
const score = trendPct + Math.min(-pullbackPct, 6);
return {
score: Math.round(score * 10) / 10,
trendPct: Math.round(trendPct * 10) / 10,
pullbackPct: Math.round(pullbackPct * 10) / 10,
reason: `Tendance de fond haussière (moyenne 20 j ${trendPct.toFixed(1)} % au-dessus de la moyenne 50 j), mais recul de ${(-pullbackPct).toFixed(1)} % cette semaine : un point d'entrée possible.`,
};
}

View File

@ -10,6 +10,11 @@ export function pct(n: number, digits = 1): string {
return `${n >= 0 ? "+" : ""}${n.toLocaleString("fr-FR", { minimumFractionDigits: digits, maximumFractionDigits: digits })} %`;
}
/** Nombre d'actions, fractions comprises (« 0,4213 »). */
export function shares(n: number): string {
return n.toLocaleString("fr-FR", { maximumFractionDigits: 4 });
}
export function signedEur(n: number): string {
return `${n >= 0 ? "+" : ""}${eur(n)}`;
}

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

@ -0,0 +1,48 @@
import "server-only";
import { getBars, getQuotes } from "./market";
import { getKv, setKv } from "./settings";
import { addDays, parisDate } from "./time";
import { UNIVERSE, findStock } from "./universe";
import { screenBars, type Screen } from "./engine/screen";
/**
* Idées « sans IA » : un filtre simple et transparent sur toutes les actions surveillées.
* Il sert (1) à proposer quelque chose même sans clé Anthropic, (2) à donner plus de
* candidates à l'IA quand l'actualité seule n'en fournit pas assez.
* Calculé au plus une fois toutes les 6 heures, stocké en base : les pages ne font que le lire.
*/
export type Idea = Screen & { symbol: string; name: string; currency: string; price: number; changePct: number | null };
export type IdeasSnapshot = { at: string; date: string; items: Idea[] };
const REFRESH_MS = 6 * 3_600_000;
export async function getIdeas(): Promise<IdeasSnapshot | null> {
return getKv<IdeasSnapshot>("ideas");
}
export async function refreshIdeas(force = false): Promise<IdeasSnapshot> {
const prev = await getIdeas();
if (!force && prev && Date.now() - new Date(prev.at).getTime() < REFRESH_MS) return prev;
const from = addDays(parisDate(), -110);
const quotes = await getQuotes(UNIVERSE.map((s) => s.symbol));
const items: Idea[] = [];
// 8 historiques en parallèle : assez rapide (~10 s) sans se faire bloquer par Yahoo.
for (let i = 0; i < UNIVERSE.length; i += 8) {
const chunk = UNIVERSE.slice(i, i + 8);
const results = await Promise.allSettled(chunk.map((s) => getBars(s.symbol, from)));
results.forEach((r, j) => {
if (r.status !== "fulfilled") return;
const stock = chunk[j];
const q = quotes.get(stock.symbol);
if (!q) return;
const screen = screenBars(r.value, q.price);
if (!screen) return;
items.push({ ...screen, symbol: stock.symbol, name: findStock(stock.symbol)?.name ?? q.name, currency: q.currency, price: q.price, changePct: q.changePct });
});
}
items.sort((a, b) => b.score - a.score);
const snap: IdeasSnapshot = { at: new Date().toISOString(), date: parisDate(), items: items.slice(0, 8) };
await setKv("ideas", snap);
return snap;
}

View File

@ -1,5 +1,5 @@
import "server-only";
import { and, eq, isNull } from "drizzle-orm";
import { and, eq, isNull, ne } from "drizzle-orm";
import { aiEnabled, analyzeCandidate, AiUnavailableError, type Analysis } from "./ai";
import { getDb, schema } from "./db";
import { checkBuy, MIN_CONFIDENCE } from "./engine/risk";
@ -9,19 +9,35 @@ import { getBars, getFxToEur, getNextEarningsDate, getQuote, getQuotes } from ".
import { collectNews, recentNews, triagePending } from "./news";
import { getOpenSymbols, getPortfolioState, placeOrder, processAll, snapshotEquity, type PortfolioState } from "./portfolio";
import { sendPush } from "./push";
import { getKv, getSettings, setKv, updateSettings, type Settings } from "./settings";
import { getKv, getSettings, setKv, SIM_INITIAL_CASH, updateSettings, type Settings } from "./settings";
import { getIdeas, refreshIdeas, type Idea } from "./ideas";
import { getGateStatus, totalDeposited } from "./stats";
import { addDays, addTradingDays, isTradeRepublicOpen, isWeekend, parisDate, parisMinutes } from "./time";
import { findStock, UNIVERSE } from "./universe";
const UNIVERSE_COLLECT_EVERY_MS = 3 * 3_600_000;
const AUTO_TICK_EVERY_MS = 20 * 60_000;
/**
* Appelé toutes les 30 minutes par GitHub Actions (ou à la main depuis les réglages).
* Mise à jour automatique quand tu ouvres l'app : si la dernière mise à jour date de plus de
* 20 minutes, on la relance en arrière-plan (après l'affichage de la page, sans la ralentir).
* Ainsi l'app vit même sans la tâche planifiée GitHub (en local, ou si elle n'est pas branchée).
*/
export async function shouldAutoTick(): Promise<boolean> {
const last = (await getKv<number>("lastTickAt")) ?? 0;
if (Date.now() - last < AUTO_TICK_EVERY_MS) return false;
await setKv("lastTickAt", Date.now()); // réservé tout de suite : pas deux mises à jour en même temps
return true;
}
/**
* Appelé toutes les 30 minutes par GitHub Actions, à l'ouverture de l'app, ou à la main.
* Décide seul quoi faire selon l'heure de Paris.
*/
export async function tick(now = new Date()): Promise<string[]> {
const log: string[] = [];
await setKv("lastTickAt", Date.now());
const settings = await getSettings();
const today = parisDate(now);
const minutes = parisMinutes(now);
@ -29,25 +45,32 @@ export async function tick(now = new Date()): Promise<string[]> {
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()));
// Les actus et les idées se collectent tous les jours (week-end compris) pour que l'app ne soit jamais vide.
const held = await getOpenSymbols(["real", "ai_sim"]);
const last = (await getKv<number>("lastUniverseCollect")) ?? 0;
const collectUniverse = Date.now() - last > UNIVERSE_COLLECT_EVERY_MS;
const symbols = collectUniverse ? UNIVERSE.map((s) => s.symbol) : held;
if (symbols.length) {
const n = await collectNews(symbols);
if (collectUniverse) await setKv("lastUniverseCollect", Date.now());
log.push(`${n} nouvelles actus collectées`);
}
try {
const t = await triagePending();
if (t) log.push(`${t} actus triées par l'IA`);
} catch (e) {
if (!(e instanceof AiUnavailableError)) throw e;
log.push(e.message);
}
log.push(...(await urgentAlerts()));
try {
const ideas = await refreshIdeas();
log.push(`${ideas.items.length} idée(s) repérée(s) par le filtre`);
} catch (e) {
log.push(`Filtre d'idées indisponible : ${e instanceof Error ? e.message : e}`);
}
if (!isWeekend(today)) {
const lastEvening = await getKv<string>("lastEvening");
if (lastEvening !== today && minutes >= settings.rendezvousMinutes - 30) {
log.push(...(await runEvening()));
@ -92,34 +115,67 @@ async function urgentAlerts(): Promise<string[]> {
return log;
}
type Candidate = { symbol: string; score: number; newsIds: string[] };
type Candidate = { symbol: string; score: number; newsIds: string[]; technical?: string };
function pickCandidates(rows: Awaited<ReturnType<typeof recentNews>>, exclude: string[]): Candidate[] {
const MAX_CANDIDATES = 3;
/**
* Les candidates analysées par l'IA : d'abord les actions portées par une actu positive
* (pertinence ≥ 6/10), puis, s'il reste de la place, les meilleures idées du filtre technique.
*/
function pickCandidates(rows: Awaited<ReturnType<typeof recentNews>>, exclude: string[], ideas: Idea[]): Candidate[] {
const bySymbol = new Map<string, Candidate>();
for (const n of rows) {
const t = n.triage;
if (!t || t.direction !== "positive" || t.relevance < 7 || exclude.includes(n.symbol) || !findStock(n.symbol)) continue;
if (!t || t.direction !== "positive" || t.relevance < 6 || exclude.includes(n.symbol) || !findStock(n.symbol)) continue;
const c = bySymbol.get(n.symbol) ?? { symbol: n.symbol, score: 0, newsIds: [] };
c.score = Math.max(c.score, t.relevance) + 0.5 * c.newsIds.length;
c.newsIds.push(n.id);
bySymbol.set(n.symbol, c);
}
return [...bySymbol.values()].sort((a, b) => b.score - a.score).slice(0, 3);
const fromNews = [...bySymbol.values()].sort((a, b) => b.score - a.score).slice(0, MAX_CANDIDATES);
for (const idea of ideas) {
if (fromNews.length >= MAX_CANDIDATES) break;
if (exclude.includes(idea.symbol) || fromNews.some((c) => c.symbol === idea.symbol)) continue;
fromNews.push({ symbol: idea.symbol, score: idea.score, newsIds: [], technical: idea.reason });
}
return fromNews;
}
const MANUAL_RUNS_PER_DAY = 3;
/** Lancement à la demande (« Chercher des idées maintenant ») : limité pour garder le budget IA. */
export async function runEveningNow(): Promise<string[]> {
const today = parisDate();
const key = `manualRuns:${today}`;
const used = (await getKv<number>(key)) ?? 0;
if (used >= MANUAL_RUNS_PER_DAY) {
return [`Déjà ${MANUAL_RUNS_PER_DAY} recherches aujourd'hui : reviens demain (ça protège ton budget IA).`];
}
await setKv(key, used + 1);
await refreshIdeas().catch(() => null);
return runEvening({ manual: true });
}
/** Le rendez-vous du soir : analyse, décisions, fiches et notification. */
export async function runEvening(): Promise<string[]> {
export async function runEvening(opts: { manual?: boolean } = {}): Promise<string[]> {
const log: string[] = [];
const db = await getDb();
const today = parisDate();
const summary: string[] = [];
await setKv("lastEvening", today);
// Une recherche à la demande ne remplace pas le vrai rendez-vous du soir (ni sa notification).
if (!opts.manual) await setKv("lastEvening", today);
const [rdv] = await db
.insert(schema.rendezvous)
.values({ date: today, summary: "" })
.onConflictDoUpdate({ target: schema.rendezvous.date, set: { createdAt: new Date() } })
.returning();
// Relancé le même jour : on remplace les fiches encore sans réponse au lieu de les dupliquer.
// (sauf le virement mensuel vers le PEA, qui n'est créé qu'une fois par mois).
await db
.delete(schema.actions)
.where(and(eq(schema.actions.rendezvousId, rdv.id), eq(schema.actions.status, "pending"), ne(schema.actions.kind, "to_pea")));
let settings = await getSettings();
const ai = await getPortfolioState("ai_sim");
@ -142,10 +198,11 @@ export async function runEvening(): Promise<string[]> {
// 1. Analyse des meilleures candidates.
let best: { analysis: Analysis; signalId: number; symbol: string; name: string; price: number; currency: string } | null = null;
let analyzed = 0;
const ideas = (await getIdeas())?.items ?? [];
if (aiEnabled()) {
const news = await recentNews(30);
const exclude = await getOpenSymbols(["ai_sim", "real"]);
const candidates = pickCandidates(news, exclude);
const candidates = pickCandidates(news, exclude, ideas);
const results = await Promise.allSettled(candidates.map((c) => analyze(c, news, today)));
for (const r of results) {
if (r.status === "rejected") {
@ -209,7 +266,9 @@ export async function runEvening(): Promise<string[]> {
summary.push(`🤖 L'IA aimait ${best.name}, mais le contrôle des risques a dit non : ${aiRisk.reason}`);
}
const forCard = gate.realActive ? checkBuy(riskInput(real)) : aiRisk;
// Fiche d'entraînement : dimensionnée sur ton bac à sable (ou sur 200 € neufs s'il est plein),
// pour que tu aies toujours quelque chose à essayer, même quand la cagnotte de l'IA est déjà investie.
const forCard = gate.realActive ? checkBuy(riskInput(real)) : trainingRisk(riskInput, await getPortfolioState("sandbox"));
if (forCard.ok) {
const training = !gate.realActive;
await db.insert(schema.actions).values({
@ -222,8 +281,21 @@ export async function runEvening(): Promise<string[]> {
} else if (gate.realActive) {
summary.push(`Pas de proposition réelle sur ${best.name} : ${forCard.reason}`);
}
} else if (aiEnabled()) {
summary.push(`😴 Rien d'intéressant ce soir. L'IA a étudié ${analyzed} candidate(s) et préfère attendre.`);
} else {
if (aiEnabled()) summary.push(`😴 L'IA a étudié ${analyzed} candidate(s) et préfère attendre ce soir.`);
// Sans conviction de l'IA (ou sans IA), on te propose la meilleure idée du filtre, pour t'entraîner.
const held = await getOpenSymbols(["sandbox"]);
const idea = ideas.find((i) => !held.includes(i.symbol));
if (idea) {
await db.insert(schema.actions).values({
rendezvousId: rdv.id,
kind: "buy",
training: true,
symbol: idea.symbol,
payload: ideaPayload(idea),
});
summary.push(`🔎 Idée du filtre (sans IA) à tester dans ton bac à sable : ${idea.name}.`);
}
}
// 3. Revue des positions réelles : vendre, ou remonter le stop pour protéger un gain.
@ -295,6 +367,7 @@ async function analyze(c: Candidate, news: Awaited<ReturnType<typeof recentNews>
publishedAt: n.publishedAt.toISOString(),
triage: n.triage ? `${n.triage.eventType}, pertinence ${n.triage.relevance}/10 : ${n.triage.reason}` : "",
})),
technicalSignal: c.technical ?? null,
today,
});
if (!analysis) return null;
@ -325,38 +398,74 @@ function money(n: number, currency: string) {
return `${n.toFixed(2)} ${currency === "EUR" ? "€" : "$"}`;
}
type RiskOk = Extract<ReturnType<typeof checkBuy>, { ok: true }>;
/** Dimensionne une fiche d'entraînement sur ton bac à sable, ou sur 200 € neufs s'il n'a plus de place. */
function trainingRisk(riskInput: (s: PortfolioState) => Parameters<typeof checkBuy>[0], sandbox: PortfolioState) {
const r = checkBuy(riskInput(sandbox));
if (r.ok) return r;
const fresh = { ...sandbox, equity: SIM_INITIAL_CASH, cash: SIM_INITIAL_CASH, positions: [], pendingOrders: [] };
return checkBuy(riskInput(fresh));
}
/** En euros, comme dans Trade Republic (les actions américaines y sont cotées en euros). */
function inEur(n: number, currency: string, fx: number) {
return currency === "EUR" ? `${n.toFixed(2)} €` : `${n.toFixed(2)} $ (≈ ${(n * fx).toFixed(2)} €)`;
}
function buyPayload(
best: { analysis: Analysis; signalId: number; symbol: string; name: string; currency: string },
r: Extract<ReturnType<typeof checkBuy>, { ok: true }>,
r: RiskOk,
fx: number,
training: boolean,
): ActionPayload {
const isUs = best.currency === "USD";
return {
title: `Acheter ${r.shares} ${best.name} (~${Math.round(r.costEur)} €)`,
title: `Acheter ${best.name} pour ${r.amountEur} €`,
why: `${best.analysis.thesis}\n\nRisques : ${best.analysis.risks}`,
steps: [
training
? "Entraînement : le mode réel n'est pas encore débloqué. Dis simplement si tu aurais pris ce trade."
: `Dans Trade Republic (compte-titres), cherche « ${best.name} ».`,
`Choisis Acheter → Ordre à cours limité : ${r.shares} action(s), limite ${money(r.limitPrice, best.currency)}${isUs ? ` (≈ ${(r.limitPrice * fx).toFixed(2)} € chez Trade Republic)` : ""}.`,
isUs
? "Validité : jusqu'à demain soir."
: "Validité : jusqu'à demain soir (le marché européen est fermé, l'ordre partira à l'ouverture de 9h).",
`Dès que l'achat est fait : ordre Stop (vente) à ${money(r.stopPrice, best.currency)}${isUs ? ` (≈ ${(r.stopPrice * fx).toFixed(2)} €)` : ""}. Perte maximale ≈ ${r.maxLossEur.toFixed(0)} €.`,
`L'app te dira quand vendre : objectif ${money(r.targetPrice, best.currency)}, au plus tard le ${r.maxExitDate}.`,
? "Entraînement : le mode réel n'est pas encore débloqué. Essaie ce trade dans ton bac à sable, ou dis simplement si tu l'aurais pris."
: `Dans Trade Republic (compte-titres), cherche « ${best.name} » et touche Acheter.`,
`Choisis « Montant » et saisis ${r.amountEur} € (≈ ${fmtShares(r.shares)} action). N'achète pas si le cours dépasse ${inEur(r.limitPrice, best.currency, fx)}.`,
`Une fois acheté : ordre Stop (vente) à ${inEur(r.stopPrice, best.currency, fx)}. Perte maximale ≈ ${r.maxLossEur.toFixed(0)} €.`,
`L'app te dira quand vendre : objectif ${inEur(r.targetPrice, best.currency, fx)}, au plus tard le ${r.maxExitDate}.`,
],
name: best.name,
currency: best.currency,
shares: r.shares,
amountEur: r.amountEur,
limitPrice: r.limitPrice,
stopPrice: r.stopPrice,
targetPrice: r.targetPrice,
maxExitDate: r.maxExitDate,
signalId: best.signalId,
stopPct: Math.round((1 - r.stopPrice / r.limitPrice) * 1000) / 10,
targetPct: Math.round((r.targetPrice / r.limitPrice - 1) * 1000) / 10,
};
}
/** Fiche d'entraînement issue du filtre technique (sans IA). */
function ideaPayload(idea: Idea): ActionPayload {
return {
title: `Idée à tester : ${idea.name}`,
why: `${idea.reason}\n\nCette idée vient d'une règle simple, pas de l'IA. Teste-la dans ton bac à sable pour voir si elle marche.`,
steps: [
"Entraînement uniquement : essaie-la dans ton bac à sable avec un stop à 7 %.",
"Le bac à sable vendra tout seul si le stop ou l'objectif (+12 %) est touché.",
],
name: idea.name,
currency: idea.currency,
stopPct: 7,
targetPct: 12,
amountEur: 150,
source: "screen",
};
}
export function fmtShares(n: number): string {
return n.toLocaleString("fr-FR", { maximumFractionDigits: 4 });
}
async function reviewRealPositions(real: PortfolioState, rdvId: number, today: string) {
const db = await getDb();
const quotes = await getQuotes(real.positions.map((p) => p.symbol));

View File

@ -1,7 +1,7 @@
import "server-only";
import YahooFinance from "yahoo-finance2";
import type { Bar } from "./engine/fills";
import { parisDate } from "./time";
import { addDays, parisDate } from "./time";
import { findStock } from "./universe";
/** Cours, historiques, actus et dates de résultats, via Yahoo Finance (gratuit, US + Europe). */
@ -16,32 +16,76 @@ export type Quote = {
};
const SUPPORTED_CURRENCIES = new Set(["EUR", "USD"]);
const quoteCache = new Map<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);
// ---------------------------------------------------------------------------
// Cache mémoire partagé par toutes les requêtes du serveur.
// Yahoo est lent (0,3 à 2 s par appel) : sans cache, chaque page en enchaînait une dizaine.
// Les appels identiques en cours sont aussi mutualisés (une seule requête pour 3 demandes simultanées).
// ---------------------------------------------------------------------------
type Entry = { at: number; value: Promise<unknown> };
const g = globalThis as unknown as { __marketCache?: Map<string, Entry> };
const cache = (g.__marketCache ??= new Map());
function memo<T>(key: string, ttlMs: number, fn: () => Promise<T>): Promise<T> {
const hit = cache.get(key);
if (hit && Date.now() - hit.at < ttlMs) return hit.value as Promise<T>;
const value = fn().catch((err) => {
cache.delete(key); // une erreur n'est jamais gardée en cache
throw err;
});
cache.set(key, { at: Date.now(), value });
return value;
}
const QUOTE_TTL_MS = 60_000;
const quoteCache = new Map<string, { at: number; quote: Quote }>();
const inflightQuotes = new Map<string, Promise<void>>();
async function fetchQuotes(symbols: string[]): Promise<void> {
// Yahoo accepte de gros paquets ; on découpe par 50 par prudence.
for (let i = 0; i < symbols.length; i += 50) {
const chunk = symbols.slice(i, i + 50);
let rows: Awaited<ReturnType<typeof yf.quote>> = [];
try {
rows = await yf.quote(chunk);
} catch (err) {
console.error("[market] cours indisponibles :", chunk.join(","), err);
continue;
}
for (const r of rows) {
if (r.regularMarketPrice == null || !r.currency) continue;
const quote: Quote = {
symbol: r.symbol,
name: findStock(r.symbol)?.name ?? r.longName ?? r.shortName ?? r.symbol,
price: r.regularMarketPrice,
currency: r.currency,
changePct: r.regularMarketChangePercent ?? null,
};
quoteCache.set(r.symbol, { at: Date.now(), quote });
out.set(r.symbol, quote);
quoteCache.set(r.symbol, {
at: Date.now(),
quote: {
symbol: r.symbol,
name: findStock(r.symbol)?.name ?? r.longName ?? r.shortName ?? r.symbol,
price: r.regularMarketPrice,
currency: r.currency,
changePct: r.regularMarketChangePercent ?? null,
},
});
}
}
}
export async function getQuotes(symbols: string[]): Promise<Map<string, Quote>> {
const unique = [...new Set(symbols)];
const fresh = (s: string) => {
const hit = quoteCache.get(s);
return hit && Date.now() - hit.at < QUOTE_TTL_MS;
};
const missing = unique.filter((s) => !fresh(s) && !inflightQuotes.has(s));
if (missing.length) {
const p = fetchQuotes(missing).finally(() => missing.forEach((s) => inflightQuotes.delete(s)));
missing.forEach((s) => inflightQuotes.set(s, p));
}
await Promise.all(unique.map((s) => inflightQuotes.get(s)).filter(Boolean));
const out = new Map<string, Quote>();
for (const s of unique) {
const hit = quoteCache.get(s);
if (hit) out.set(s, hit.quote);
}
return out;
}
@ -61,67 +105,87 @@ export function isSupportedCurrency(currency: string): boolean {
return SUPPORTED_CURRENCIES.has(currency);
}
/** Barres journalières depuis une date (incluse), datées à l'heure de Paris. */
/**
* Barres journalières depuis une date (incluse), datées à l'heure de Paris.
* On télécharge au moins 9 mois d'historique une seule fois par action (cache 15 min),
* puis on découpe : une seule requête sert le graphique, le PEA, l'indice et le moteur.
*/
const BARS_TTL_MS = 15 * 60_000;
const barsFrom = new Map<string, string>();
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!,
}));
const minFrom = addDays(parisDate(), -270);
const known = barsFrom.get(symbol);
const from = known && known <= fromDate ? known : fromDate < minFrom ? fromDate : minFrom;
barsFrom.set(symbol, from);
const all = await memo(`bars:${symbol}:${from}`, BARS_TTL_MS, async () => {
const chart = await yf.chart(symbol, { period1: from, interval: "1d" });
return chart.quotes
.filter((q) => q.open != null && q.high != null && q.low != null && q.close != null)
.map((q) => ({
date: parisDate(q.date),
open: q.open!,
high: q.high!,
low: q.low!,
close: q.close!,
}));
});
return all.filter((b) => b.date >= fromDate);
}
/** Prochaine date de résultats trimestriels (AAAA-MM-JJ), ou null si inconnue. */
export async function getNextEarningsDate(symbol: string): Promise<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;
}
return memo(`earnings:${symbol}`, 12 * 3_600_000, async () => {
try {
const s = await yf.quoteSummary(symbol, { modules: ["calendarEvents"] });
const dates = s.calendarEvents?.earnings?.earningsDate ?? [];
const today = parisDate();
const next = dates.map((d) => parisDate(d)).filter((d) => d >= today).sort()[0];
return next ?? null;
} catch {
return null;
}
});
}
export type RawNews = { id: string; symbol: string; title: string; publisher: string; url: string; publishedAt: Date };
/** Actus récentes d'une action. Recherche par symbole (US) ou par nom (Europe), puis filtre sur la société. */
export async function getNews(symbol: string): Promise<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,
}));
return memo(`news:${symbol}`, 10 * 60_000, async () => {
const stock = findStock(symbol);
const query = stock?.market === "EU" ? stock.name : symbol;
const res = await yf.search(query, { newsCount: 8, quotesCount: 0 });
return res.news
.filter((n) => n.relatedTickers?.includes(symbol))
.map((n) => ({
id: n.uuid,
symbol,
title: n.title,
publisher: n.publisher,
url: n.link,
publishedAt: n.providerPublishTime,
}));
});
}
export type SearchHit = { symbol: string; name: string; exchange: string; type: string };
/** Recherche d'actions ou d'ETF pour le bac à sable. */
/** Recherche d'actions ou d'ETF (en euros ou en dollars, les seules devises gérées). */
export async function searchInstruments(query: string): Promise<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;
return memo(`search:${query.toLowerCase()}`, 10 * 60_000, async () => {
const res = await yf.search(query, { quotesCount: 10, newsCount: 0 });
const hits: SearchHit[] = [];
for (const q of res.quotes) {
if (!("symbol" in q) || !q.isYahooFinance) continue;
if (q.quoteType !== "EQUITY" && q.quoteType !== "ETF") continue;
hits.push({
symbol: q.symbol,
name: findStock(q.symbol)?.name || ("longname" in q && q.longname) || ("shortname" in q && q.shortname) || q.symbol,
exchange: ("exchDisp" in q && q.exchDisp) || "",
type: q.quoteType,
});
}
return hits;
});
}

View File

@ -67,6 +67,18 @@ export async function triagePending(): Promise<number> {
export type NewsRow = typeof schema.news.$inferSelect;
/** Nombre d'actus récentes par action (pour la liste des actions). */
export async function newsCounts(hours = 48): Promise<Map<string, number>> {
const db = await getDb();
const rows = await db
.select({ symbol: schema.news.symbol })
.from(schema.news)
.where(gte(schema.news.publishedAt, new Date(Date.now() - hours * 3_600_000)));
const out = new Map<string, number>();
for (const r of rows) out.set(r.symbol, (out.get(r.symbol) ?? 0) + 1);
return out;
}
export async function recentNews(hours = 36): Promise<NewsRow[]> {
const db = await getDb();
return db

View File

@ -30,19 +30,23 @@ export type PortfolioState = {
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));
const [[p], open, pendingOrders] = await Promise.all([
db.select().from(schema.portfolios).where(eq(schema.portfolios.id, id)),
db
.select()
.from(schema.positions)
.where(and(eq(schema.positions.portfolioId, id), eq(schema.positions.status, "open"))),
db
.select()
.from(schema.orders)
.where(and(eq(schema.orders.portfolioId, id), eq(schema.orders.status, "pending"))),
]);
if (!p) throw new Error(`Portefeuille ${id} introuvable`);
const open = await db
.select()
.from(schema.positions)
.where(and(eq(schema.positions.portfolioId, id), eq(schema.positions.status, "open")));
const pendingOrders = await db
.select()
.from(schema.orders)
.where(and(eq(schema.orders.portfolioId, id), eq(schema.orders.status, "pending")));
const q = quotes ?? (open.length ? await getQuotes(open.map((x) => x.symbol)) : new Map<string, Quote>());
const fxUsd = open.some((x) => x.currency === "USD") ? await getFxToEur("USD") : 1;
const [q, fxUsd] = await Promise.all([
quotes ?? (open.length ? getQuotes(open.map((x) => x.symbol)) : new Map<string, Quote>()),
open.some((x) => x.currency === "USD") ? getFxToEur("USD") : 1,
]);
const positions: PositionView[] = open.map((pos) => {
const price = q.get(pos.symbol)?.price ?? null;
const fx = pos.currency === "USD" ? (fxUsd ?? pos.entryFx) : 1;
@ -85,7 +89,8 @@ type NewOrder = {
/** Enregistre un ordre simulé et tente de l'exécuter tout de suite. */
export async function placeOrder(o: NewOrder): Promise<{ order: Order; filled: boolean; message: string }> {
if (o.portfolioId === "real") throw new Error("Les ordres réels se passent dans Trade Republic.");
if (!Number.isInteger(o.shares) || o.shares < 1) throw new Error("Nombre d'actions invalide.");
// Fractions autorisées, comme chez Trade Republic (achat par montant).
if (!Number.isFinite(o.shares) || o.shares <= 0) throw new Error("Quantité invalide.");
const db = await getDb();
const [order] = await db
.insert(schema.orders)

93
src/lib/real.ts Normal file
View File

@ -0,0 +1,93 @@
import "server-only";
import { eq } from "drizzle-orm";
import { getDb, schema } from "./db";
import { FEE_EUR } from "./engine/fills";
import { getFxToEur, getQuote, isSupportedCurrency } from "./market";
import { closePosition } from "./portfolio";
import { parisDate } from "./time";
/**
* Suivi de ton compte-titres Trade Republic.
* Trade Republic n'a pas d'API officielle : l'app ne se connecte jamais à ton compte et ne te
* demande jamais tes identifiants. Tu lui dis ce que tu as fait, elle tient les comptes.
*/
async function realPortfolio() {
const db = await getDb();
const [p] = await db.select().from(schema.portfolios).where(eq(schema.portfolios.id, "real"));
return { db, p };
}
/** Tu as versé de l'argent sur ton compte-titres (compte dans les versements : sert au coupe-circuit et au cliquet). */
export async function recordDeposit(amount: number, date = parisDate()) {
if (!Number.isFinite(amount) || amount === 0) throw new Error("Montant invalide.");
const { db, p } = await realPortfolio();
await db.insert(schema.cashFlows).values({ portfolioId: "real", amount, kind: amount > 0 ? "deposit" : "withdrawal", date });
await db
.update(schema.portfolios)
.set({ cash: p.cash + amount, highWaterMark: Math.max(0, p.highWaterMark + amount) })
.where(eq(schema.portfolios.id, "real"));
}
/** Corrige les liquidités pour coller exactement à ce qu'affiche Trade Republic (n'est pas un versement). */
export async function setCash(cash: number) {
if (!Number.isFinite(cash) || cash < 0) throw new Error("Solde invalide.");
const { db, p } = await realPortfolio();
const delta = Math.round((cash - p.cash) * 100) / 100;
if (delta === 0) return;
await db.insert(schema.cashFlows).values({ portfolioId: "real", amount: delta, kind: "adjust", date: parisDate() });
await db.update(schema.portfolios).set({ cash }).where(eq(schema.portfolios.id, "real"));
}
/**
* Enregistre une action que tu détiens déjà chez Trade Republic (achat fait hors de l'app,
* ou avant d'utiliser l'app). Si `paidFromCash`, le coût est retiré des liquidités suivies.
*/
export async function addHolding(input: {
symbol: string;
shares: number;
price: number; // prix d'achat unitaire, devise de cotation
stopPct?: number | null;
paidFromCash: boolean;
}) {
if (!(input.shares > 0) || !(input.price > 0)) throw new Error("Quantité ou prix invalide.");
const quote = await getQuote(input.symbol);
if (!quote) throw new Error("Action introuvable.");
if (!isSupportedCurrency(quote.currency)) throw new Error("Seules les actions en euros ou en dollars sont gérées.");
const fx = (await getFxToEur(quote.currency)) ?? 1;
const { db, p } = await realPortfolio();
if (input.paidFromCash) {
const cost = input.shares * input.price * fx + FEE_EUR;
await db.update(schema.portfolios).set({ cash: Math.max(0, p.cash - cost) }).where(eq(schema.portfolios.id, "real"));
}
await db.insert(schema.positions).values({
portfolioId: "real",
symbol: input.symbol,
name: quote.name,
currency: quote.currency,
shares: input.shares,
entryPrice: input.price,
entryFx: fx,
openedAt: new Date(),
stopPrice: input.stopPct ? Math.round(input.price * (1 - input.stopPct / 100) * 100) / 100 : null,
feesEur: input.paidFromCash ? FEE_EUR : 0,
});
}
/** Tu as vendu une position chez Trade Republic : on la clôture au prix réellement obtenu. */
export async function recordSale(positionId: number, price?: number) {
const db = await getDb();
const [pos] = await db.select().from(schema.positions).where(eq(schema.positions.id, positionId));
if (!pos || pos.portfolioId !== "real" || pos.status !== "open") throw new Error("Position introuvable.");
const px = price && price > 0 ? price : ((await getQuote(pos.symbol))?.price ?? pos.entryPrice);
const fx = (await getFxToEur(pos.currency)) ?? pos.entryFx;
await closePosition(pos, px, fx, "manual", false);
}
/** Supprime une position saisie par erreur (sans toucher aux liquidités). */
export async function deleteHolding(positionId: number) {
const db = await getDb();
const [pos] = await db.select().from(schema.positions).where(eq(schema.positions.id, positionId));
if (!pos || pos.portfolioId !== "real") throw new Error("Position introuvable.");
await db.delete(schema.positions).where(eq(schema.positions.id, positionId));
}

View File

@ -16,23 +16,31 @@ export type Settings = {
askDailyLimit: number;
realUnlockedAt: string | null;
realLockedReason: string | null;
/** Date à laquelle tu as déclaré ton compte Trade Republic ouvert (null = pas encore). */
trAccountOpenedAt: string | null;
};
export const SIM_INITIAL_CASH = 200;
/** Le plan PEA par défaut, proposé quand tu configures ton compte. */
export function defaultPeaPlan(startDate: string): PeaPlan {
return {
etfSymbol: DEFAULT_PEA_ETF.symbol,
etfName: DEFAULT_PEA_ETF.name,
monthlyAmount: 50,
dayOfMonth: 5,
startDate,
calibration: null,
};
}
function defaults(): Settings {
const today = parisDate();
return {
simStartDate: today,
rendezvousMinutes: 19 * 60,
peaPlan: {
etfSymbol: DEFAULT_PEA_ETF.symbol,
etfName: DEFAULT_PEA_ETF.name,
monthlyAmount: 50,
dayOfMonth: 5,
startDate: today,
calibration: null,
},
// Pas de PEA tant que tu ne l'as pas déclaré : sinon l'app inventerait des versements.
peaPlan: null,
realMonthlyDeposit: 50,
realDepositDay: 5,
realDepositsStart: null,
@ -40,6 +48,7 @@ function defaults(): Settings {
askDailyLimit: 10,
realUnlockedAt: null,
realLockedReason: null,
trAccountOpenedAt: null,
};
}
@ -57,7 +66,9 @@ export async function setKv(key: string, value: unknown): Promise<void> {
.onConflictDoUpdate({ target: schema.kv.key, set: { value, updatedAt: new Date() } });
}
/** Crée les réglages et les trois portefeuilles au premier lancement. */
const g = globalThis as unknown as { __setupDone?: boolean };
/** Crée les réglages et les trois portefeuilles au premier lancement (une seule fois par serveur). */
export async function ensureSetup(): Promise<Settings> {
const db = await getDb();
let settings = await getKv<Settings>("settings");
@ -67,6 +78,8 @@ export async function ensureSetup(): Promise<Settings> {
} else {
settings = { ...defaults(), ...settings };
}
if (g.__setupDone) return settings;
g.__setupDone = true;
await db
.insert(schema.portfolios)
.values([

View File

@ -8,10 +8,17 @@ import { getBars, getFxToEur, getQuote } from "./market";
import { getPortfolioState, type PortfolioState } from "./portfolio";
import { getSettings, type Settings } from "./settings";
import { daysBetween, parisDate } from "./time";
import { DEFAULT_PEA_ETF } from "./universe";
import { eur } from "./format";
/** L'ETF S&P 500 de référence : celui de ton PEA, ou l'ETF par défaut si tu n'as pas encore de PEA. */
export function benchmarkSymbol(s: Settings): string {
return s.peaPlan?.etfSymbol ?? DEFAULT_PEA_ETF.symbol;
}
/** Rendement de l'ETF S&P 500 (celui du PEA) depuis une date, en %. */
export async function benchmarkReturnPct(symbol: string, since: string): Promise<number> {
const bars = await getBars(symbol, since);
const bars = await getBars(symbol, since).catch((e) => (console.error("[indice]", e), []));
const first = bars.find((b) => b.date >= since);
const last = (await getQuote(symbol))?.price ?? bars.at(-1)?.close;
if (!first || !last) return 0;
@ -29,16 +36,20 @@ export type GateStatus = {
export async function getGateStatus(settings?: Settings, ai?: PortfolioState): Promise<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;
// Tout est lancé en parallèle : la page attend la requête la plus lente, pas leur somme.
const [aiState, closed, snaps, acts, usdToEur, spent, bench] = await Promise.all([
ai ?? getPortfolioState("ai_sim"),
db
.select({ id: schema.positions.id })
.from(schema.positions)
.where(and(eq(schema.positions.portfolioId, "ai_sim"), eq(schema.positions.status, "closed"))),
db.select().from(schema.equitySnapshots).where(eq(schema.equitySnapshots.portfolioId, "ai_sim")),
db.select({ status: schema.actions.status }).from(schema.actions).where(ne(schema.actions.kind, "to_pea")),
getFxToEur("USD").then((x) => x ?? 0.9),
aiSpendSince(s.simStartDate),
benchmarkReturnPct(benchmarkSymbol(s), s.simStartDate),
]);
const aiCostEur = spent * usdToEur;
const gate = computeGate({
simDays: daysBetween(s.simStartDate, parisDate()),
@ -63,10 +74,10 @@ export async function getGateStatus(settings?: Settings, ai?: PortfolioState): P
export type Leaderboard = { label: string; pct: number; detail: string }[];
export async function getLeaderboard(settings: Settings, ai: PortfolioState, sandbox: PortfolioState): Promise<Leaderboard> {
const bench = settings.peaPlan ? await benchmarkReturnPct(settings.peaPlan.etfSymbol, settings.simStartDate) : 0;
const bench = await benchmarkReturnPct(benchmarkSymbol(settings), settings.simStartDate);
const rows = [
{ label: "L'IA", pct: (ai.equity / ai.initialCash - 1) * 100, detail: `${ai.equity.toFixed(2)} €` },
{ label: "Toi", pct: (sandbox.equity / sandbox.initialCash - 1) * 100, detail: `${sandbox.equity.toFixed(2)} €` },
{ label: "L'IA", pct: (ai.equity / ai.initialCash - 1) * 100, detail: eur(ai.equity) },
{ label: "Toi", pct: (sandbox.equity / sandbox.initialCash - 1) * 100, detail: eur(sandbox.equity) },
{ label: "S&P 500", pct: bench, detail: "sans rien faire" },
];
return rows.sort((a, b) => b.pct - a.pct);
@ -77,12 +88,17 @@ export async function getPea(settings: Settings): Promise<(PeaResult & { etfName
if (!plan) return null;
const today = parisDate();
if (plan.startDate > today) return { shares: 0, invested: 0, value: 0, gain: 0, contributions: [], etfName: plan.etfName, price: null };
const [bars, quote] = await Promise.all([getBars(plan.etfSymbol, plan.startDate), getQuote(plan.etfSymbol)]);
const [bars, quote] = await Promise.all([
// Yahoo en panne ou symbole erroné : on affiche 0 plutôt que de casser la page.
getBars(plan.etfSymbol, plan.startDate).catch((e) => (console.error("[pea]", e), [])),
getQuote(plan.etfSymbol),
]);
return { ...computePea(plan, bars, quote?.price ?? null, today), etfName: plan.etfName, price: quote?.price ?? null };
}
export async function totalDeposited(): Promise<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);
// Les corrections de solde ne sont pas des versements : elles ne comptent pas pour le coupe-circuit.
return rows.filter((r) => r.kind !== "adjust").reduce((s, r) => s + r.amount, 0);
}