Make the AI actually trade in simulation and speed up Vercel
Some checks failed
Tick / tick (push) Failing after 1s
Some checks failed
Tick / tick (push) Failing after 1s
- Pin Vercel functions to Paris (cdg1), next to the Supabase database - Triage: smaller batches, a truncated answer is retried instead of silently scoring every news item 0/10 (which starved the AI) - Analysis prompt calibrated (buy at confidence >= 60 with tight stop) - Settings read once per page render - New AI diagnostic card in Settings: news, triage, decisions, run logs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
77a165afaa
commit
82093744f3
@ -6,6 +6,7 @@ import { PushManager } from "@/components/push-manager";
|
|||||||
import { RunNow } from "@/components/run-now";
|
import { RunNow } from "@/components/run-now";
|
||||||
import { Card, CardSkeleton, inputCls, Page, primaryBtn, secondaryBtn } from "@/components/ui";
|
import { Card, CardSkeleton, inputCls, Page, primaryBtn, secondaryBtn } from "@/components/ui";
|
||||||
import { aiEnabled } from "@/lib/ai";
|
import { aiEnabled } from "@/lib/ai";
|
||||||
|
import { getDiagnostics } from "@/lib/diagnostics";
|
||||||
import { getSettings } from "@/lib/settings";
|
import { getSettings } from "@/lib/settings";
|
||||||
|
|
||||||
function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
|
function Field({ label, hint, children }: { label: string; hint?: string; children: React.ReactNode }) {
|
||||||
@ -45,6 +46,63 @@ async function SettingsForm() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function ago(iso: string | undefined) {
|
||||||
|
if (!iso) return "jamais";
|
||||||
|
return new Date(iso).toLocaleString("fr-FR", { timeZone: "Europe/Paris", dateStyle: "short", timeStyle: "short" });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pourquoi l'IA trade ou non : tout ce qui s'est passé lors des dernières mises à jour. */
|
||||||
|
async function Diagnostics() {
|
||||||
|
await connection();
|
||||||
|
const d = await getDiagnostics();
|
||||||
|
const row = (ok: boolean, label: string, value: React.ReactNode) => (
|
||||||
|
<li className="flex items-start justify-between gap-3">
|
||||||
|
<span>
|
||||||
|
{ok ? "✅" : "⚠️"} {label}
|
||||||
|
</span>
|
||||||
|
<span className="num shrink-0 text-right text-muted">{value}</span>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<Card title="Diagnostic de l'IA">
|
||||||
|
<ul className="flex flex-col gap-2 text-sm">
|
||||||
|
{row(d.aiOn, "Clé Anthropic", d.aiOn ? "présente" : "absente")}
|
||||||
|
{row(d.news48h > 0, "Actus des 48 dernières heures", d.news48h)}
|
||||||
|
{row(!d.aiOn || d.triagedTotal > 0, "Actus triées par l'IA", d.triagedTotal)}
|
||||||
|
{row(d.positiveStrong > 0, "Actus positives ≥ 6/10", d.positiveStrong)}
|
||||||
|
{row(d.signals.length > 0, "Analyses (7 derniers jours)", d.signals.length)}
|
||||||
|
{row(true, "Coût IA ce mois-ci", `${d.spend.monthUsd.toFixed(2)} $`)}
|
||||||
|
{row(Boolean(d.lastTick), "Dernière mise à jour", ago(d.lastTick?.at))}
|
||||||
|
{row(Boolean(d.lastEvening), "Dernier rendez-vous", ago(d.lastEvening?.at))}
|
||||||
|
</ul>
|
||||||
|
{d.signals.length > 0 && (
|
||||||
|
<details className="mt-3">
|
||||||
|
<summary className="cursor-pointer text-sm font-medium text-accent">Décisions récentes de l'IA</summary>
|
||||||
|
<ul className="mt-2 flex flex-col gap-1.5 text-xs">
|
||||||
|
{d.signals.map((s) => (
|
||||||
|
<li key={s.id}>
|
||||||
|
<b>{s.name}</b> · {s.decision === "buy" ? "achat" : "passe"} ({s.confidence} %)
|
||||||
|
{s.riskVerdict && s.riskVerdict !== "accepté" ? ` · refusé : ${s.riskVerdict}` : s.riskVerdict ? " · exécuté" : ""}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
{[d.lastTick, d.lastEvening].map(
|
||||||
|
(l, i) =>
|
||||||
|
l && (
|
||||||
|
<details key={i} className="mt-2">
|
||||||
|
<summary className="cursor-pointer text-sm font-medium text-accent">Journal {i ? "du rendez-vous" : "de la mise à jour"}</summary>
|
||||||
|
<ul className="mt-2 list-disc pl-5 text-xs text-muted">
|
||||||
|
{l.log.length ? l.log.map((x, j) => <li key={j}>{x}</li>) : <li>Rien à signaler.</li>}
|
||||||
|
</ul>
|
||||||
|
</details>
|
||||||
|
),
|
||||||
|
)}
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export default function SettingsPage() {
|
export default function SettingsPage() {
|
||||||
return (
|
return (
|
||||||
<Page
|
<Page
|
||||||
@ -70,6 +128,10 @@ export default function SettingsPage() {
|
|||||||
</Link>
|
</Link>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
<Suspense fallback={<CardSkeleton title="Diagnostic de l'IA" height="h-40" />}>
|
||||||
|
<Diagnostics />
|
||||||
|
</Suspense>
|
||||||
|
|
||||||
<Card title="Lancer à la main">
|
<Card title="Lancer à la main">
|
||||||
<RunNow />
|
<RunNow />
|
||||||
</Card>
|
</Card>
|
||||||
|
|||||||
@ -34,6 +34,7 @@ function getClient(): Anthropic {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class AiUnavailableError extends Error {}
|
export class AiUnavailableError extends Error {}
|
||||||
|
export class TriageFailedError extends Error {}
|
||||||
|
|
||||||
async function recordUsage(model: string, purpose: string, usage: { input_tokens: number; output_tokens: number }) {
|
async function recordUsage(model: string, purpose: string, usage: { input_tokens: number; output_tokens: number }) {
|
||||||
const [inPrice, outPrice] = PRICING[model] ?? PRICING[ANALYSIS_MODEL];
|
const [inPrice, outPrice] = PRICING[model] ?? PRICING[ANALYSIS_MODEL];
|
||||||
@ -134,13 +135,17 @@ export async function triageNews(batch: TriageInput[]): Promise<TriageOutput[]>
|
|||||||
const lines = batch.map((b) => `[${b.id}] ${b.company} (${b.symbol}) — ${b.title}${b.publisher ? ` — ${b.publisher}` : ""}`);
|
const lines = batch.map((b) => `[${b.id}] ${b.company} (${b.symbol}) — ${b.title}${b.publisher ? ` — ${b.publisher}` : ""}`);
|
||||||
const response = await getClient().messages.parse({
|
const response = await getClient().messages.parse({
|
||||||
model: TRIAGE_MODEL,
|
model: TRIAGE_MODEL,
|
||||||
max_tokens: 8000,
|
max_tokens: 16000,
|
||||||
output_config: { effort: "low", format: zodOutputFormat(TriageSchema) },
|
output_config: { effort: "low", format: zodOutputFormat(TriageSchema) },
|
||||||
system: TRIAGE_SYSTEM,
|
system: TRIAGE_SYSTEM,
|
||||||
messages: [{ role: "user", content: lines.join("\n") }],
|
messages: [{ role: "user", content: lines.join("\n") }],
|
||||||
});
|
});
|
||||||
await recordUsage(TRIAGE_MODEL, "triage", response.usage);
|
await recordUsage(TRIAGE_MODEL, "triage", response.usage);
|
||||||
if (response.stop_reason === "refusal" || !response.parsed_output) return [];
|
// Réponse coupée ou refusée : on le signale au lieu de noter tout le paquet 0/10 en silence
|
||||||
|
// (c'est ce qui empêchait l'IA de trouver la moindre candidate).
|
||||||
|
if (response.stop_reason !== "end_turn" || !response.parsed_output) {
|
||||||
|
throw new TriageFailedError(`Tri des actus interrompu (${response.stop_reason}).`);
|
||||||
|
}
|
||||||
return response.parsed_output.items;
|
return response.parsed_output.items;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -186,7 +191,8 @@ Méthode :
|
|||||||
1. Construis le meilleur argument haussier, puis le meilleur argument baissier.
|
1. Construis le meilleur argument haussier, puis le meilleur argument baissier.
|
||||||
2. Regarde le mouvement du cours depuis la nouvelle : si l'action a déjà fortement monté, la nouvelle est probablement intégrée.
|
2. Regarde le mouvement du cours depuis la nouvelle : si l'action a déjà fortement monté, la nouvelle est probablement intégrée.
|
||||||
3. Les effets les plus fiables sont la dérive après des résultats nettement meilleurs que prévu, les annonces concrètes (contrats, rachats d'actions, relèvement des prévisions) et les réactions excessives à une nouvelle mineure.
|
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.
|
4. Sois sélectif mais pas paralysé : c'est une simulation qui sert à mesurer ta méthode, et une cagnotte qui ne trade jamais ne prouve rien. Réponds "buy" (confiance ≥ 60) quand le rapport gain attendu / risque est favorable avec un stop serré ; "pass" quand l'argument est faible, déjà dans le prix, ou que des résultats arrivent dans les jours qui viennent.
|
||||||
|
La confiance doit être calibrée : 60 = avantage modeste mais réel, 75 = argument solide, 90 = rare.
|
||||||
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.
|
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.
|
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.
|
||||||
|
|
||||||
|
|||||||
36
src/lib/diagnostics.ts
Normal file
36
src/lib/diagnostics.ts
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
import "server-only";
|
||||||
|
import { desc, gte, isNotNull } from "drizzle-orm";
|
||||||
|
import { aiEnabled, getAiSpend } from "./ai";
|
||||||
|
import { getDb, schema } from "./db";
|
||||||
|
import type { RunLog } from "./jobs";
|
||||||
|
import { getKv } from "./settings";
|
||||||
|
|
||||||
|
/** Ce qu'il faut savoir pour comprendre pourquoi l'IA trade (ou pas). */
|
||||||
|
export async function getDiagnostics() {
|
||||||
|
const db = await getDb();
|
||||||
|
const since48h = new Date(Date.now() - 48 * 3_600_000);
|
||||||
|
const since7d = new Date(Date.now() - 7 * 86_400_000);
|
||||||
|
const [news, triaged, signals, spend, lastTick, lastEvening] = await Promise.all([
|
||||||
|
db.select({ id: schema.news.id }).from(schema.news).where(gte(schema.news.publishedAt, since48h)),
|
||||||
|
db
|
||||||
|
.select({ triage: schema.news.triage })
|
||||||
|
.from(schema.news)
|
||||||
|
.where(isNotNull(schema.news.triagedAt)),
|
||||||
|
db.select().from(schema.signals).where(gte(schema.signals.createdAt, since7d)).orderBy(desc(schema.signals.createdAt)).limit(10),
|
||||||
|
getAiSpend(),
|
||||||
|
getKv<RunLog>("lastTickLog"),
|
||||||
|
getKv<RunLog>("lastEveningLog"),
|
||||||
|
]);
|
||||||
|
const scored = triaged.filter((t) => t.triage && t.triage.reason !== "Non évaluée.");
|
||||||
|
return {
|
||||||
|
aiOn: aiEnabled(),
|
||||||
|
cronConfigured: Boolean(process.env.CRON_SECRET),
|
||||||
|
news48h: news.length,
|
||||||
|
triagedTotal: triaged.length,
|
||||||
|
positiveStrong: scored.filter((t) => t.triage!.direction === "positive" && t.triage!.relevance >= 6).length,
|
||||||
|
signals,
|
||||||
|
spend,
|
||||||
|
lastTick,
|
||||||
|
lastEvening,
|
||||||
|
};
|
||||||
|
}
|
||||||
@ -5,7 +5,7 @@
|
|||||||
import { addTradingDays, daysBetween } from "../time";
|
import { addTradingDays, daysBetween } from "../time";
|
||||||
import { FEE_EUR } from "./fills";
|
import { FEE_EUR } from "./fills";
|
||||||
|
|
||||||
export const MIN_CONFIDENCE = 70;
|
export const MIN_CONFIDENCE = 60;
|
||||||
export const MIN_POSITION_EUR = 150;
|
export const MIN_POSITION_EUR = 150;
|
||||||
export const MAX_HOLD_TRADING_DAYS = 15; // 3 semaines
|
export const MAX_HOLD_TRADING_DAYS = 15; // 3 semaines
|
||||||
export const EARNINGS_BLACKOUT_DAYS = 4; // pas d'achat si des résultats tombent dans les 4 jours
|
export const EARNINGS_BLACKOUT_DAYS = 4; // pas d'achat si des résultats tombent dans les 4 jours
|
||||||
|
|||||||
@ -56,7 +56,7 @@ export async function tick(now = new Date()): Promise<string[]> {
|
|||||||
log.push(`${n} nouvelles actus collectées`);
|
log.push(`${n} nouvelles actus collectées`);
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const t = await triagePending();
|
const t = await triagePending(log);
|
||||||
if (t) log.push(`${t} actus triées par l'IA`);
|
if (t) log.push(`${t} actus triées par l'IA`);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (!(e instanceof AiUnavailableError)) throw e;
|
if (!(e instanceof AiUnavailableError)) throw e;
|
||||||
@ -76,9 +76,12 @@ export async function tick(now = new Date()): Promise<string[]> {
|
|||||||
log.push(...(await runEvening()));
|
log.push(...(await runEvening()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
await setKv("lastTickLog", { at: new Date().toISOString(), log });
|
||||||
return log;
|
return log;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type RunLog = { at: string; log: string[] };
|
||||||
|
|
||||||
/** Virement mensuel vers le compte-titres (supposé programmé chez ta banque). */
|
/** Virement mensuel vers le compte-titres (supposé programmé chez ta banque). */
|
||||||
async function monthlyDeposit(settings: Settings, today: string, log: string[]) {
|
async function monthlyDeposit(settings: Settings, today: string, log: string[]) {
|
||||||
if (!settings.realDepositsStart || today < settings.realDepositsStart) return;
|
if (!settings.realDepositsStart || today < settings.realDepositsStart) return;
|
||||||
@ -341,6 +344,7 @@ export async function runEvening(opts: { manual?: boolean } = {}): Promise<strin
|
|||||||
const sent = await sendPush("Ton rendez-vous du soir", body, "/");
|
const sent = await sendPush("Ton rendez-vous du soir", body, "/");
|
||||||
await db.update(schema.rendezvous).set({ notifiedAt: sent ? new Date() : null }).where(eq(schema.rendezvous.id, rdv.id));
|
await db.update(schema.rendezvous).set({ notifiedAt: sent ? new Date() : null }).where(eq(schema.rendezvous.id, rdv.id));
|
||||||
log.push(`Rendez-vous créé (${cards.length} fiche(s), ${sent} notification(s))`);
|
log.push(`Rendez-vous créé (${cards.length} fiche(s), ${sent} notification(s))`);
|
||||||
|
await setKv("lastEveningLog", { at: new Date().toISOString(), log: [...log, ...summary] });
|
||||||
return log;
|
return log;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
import "server-only";
|
import "server-only";
|
||||||
import { desc, eq, gte, isNull } from "drizzle-orm";
|
import { desc, eq, gte, isNull } from "drizzle-orm";
|
||||||
import { aiEnabled, triageNews } from "./ai";
|
import { aiEnabled, triageNews, TriageFailedError } from "./ai";
|
||||||
import { getDb, schema } from "./db";
|
import { getDb, schema } from "./db";
|
||||||
import { getNews } from "./market";
|
import { getNews } from "./market";
|
||||||
import { findStock } from "./universe";
|
import { findStock } from "./universe";
|
||||||
@ -29,23 +29,33 @@ export async function collectNews(symbols: string[]): Promise<number> {
|
|||||||
return inserted;
|
return inserted;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Fait trier par Haiku toutes les actus pas encore notées, par paquets de 40. */
|
/**
|
||||||
export async function triagePending(): Promise<number> {
|
* Fait trier par Haiku toutes les actus pas encore notées, par paquets de 25.
|
||||||
|
* Un paquet dont la réponse échoue reste « à trier » et sera retenté à la prochaine mise à jour.
|
||||||
|
*/
|
||||||
|
export async function triagePending(log: string[] = []): Promise<number> {
|
||||||
if (!aiEnabled()) return 0;
|
if (!aiEnabled()) return 0;
|
||||||
const db = await getDb();
|
const db = await getDb();
|
||||||
const pending = await db.select().from(schema.news).where(isNull(schema.news.triagedAt));
|
const pending = await db.select().from(schema.news).where(isNull(schema.news.triagedAt));
|
||||||
let done = 0;
|
let done = 0;
|
||||||
for (let i = 0; i < pending.length; i += 40) {
|
for (let i = 0; i < pending.length; i += 25) {
|
||||||
const batch = pending.slice(i, i + 40);
|
const batch = pending.slice(i, i + 25);
|
||||||
const out = await triageNews(
|
let out: Awaited<ReturnType<typeof triageNews>>;
|
||||||
batch.map((n) => ({
|
try {
|
||||||
id: n.id,
|
out = await triageNews(
|
||||||
symbol: n.symbol,
|
batch.map((n) => ({
|
||||||
company: findStock(n.symbol)?.name ?? n.symbol,
|
id: n.id,
|
||||||
title: n.title,
|
symbol: n.symbol,
|
||||||
publisher: n.publisher,
|
company: findStock(n.symbol)?.name ?? n.symbol,
|
||||||
})),
|
title: n.title,
|
||||||
);
|
publisher: n.publisher,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
if (!(e instanceof TriageFailedError)) throw e;
|
||||||
|
log.push(e.message);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
const byId = new Map(out.map((o) => [o.id, o]));
|
const byId = new Map(out.map((o) => [o.id, o]));
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
for (const n of batch) {
|
for (const n of batch) {
|
||||||
|
|||||||
@ -1,4 +1,5 @@
|
|||||||
import "server-only";
|
import "server-only";
|
||||||
|
import { cache } from "react";
|
||||||
import { eq } from "drizzle-orm";
|
import { eq } from "drizzle-orm";
|
||||||
import { getDb, schema } from "./db";
|
import { getDb, schema } from "./db";
|
||||||
import type { PeaPlan } from "./engine/pea";
|
import type { PeaPlan } from "./engine/pea";
|
||||||
@ -91,8 +92,11 @@ export async function ensureSetup(): Promise<Settings> {
|
|||||||
return settings;
|
return settings;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Une seule lecture en base par affichage de page, même si plusieurs blocs demandent les réglages. */
|
||||||
|
const getSettingsCached = cache(ensureSetup);
|
||||||
|
|
||||||
export async function getSettings(): Promise<Settings> {
|
export async function getSettings(): Promise<Settings> {
|
||||||
return ensureSetup();
|
return getSettingsCached();
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function updateSettings(patch: Partial<Settings>): Promise<Settings> {
|
export async function updateSettings(patch: Partial<Settings>): Promise<Settings> {
|
||||||
|
|||||||
4
vercel.json
Normal file
4
vercel.json
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://openapi.vercel.sh/vercel.json",
|
||||||
|
"regions": ["cdg1"]
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user