trading-app/src/lib/engine/risk.ts
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

120 lines
4.3 KiB
TypeScript

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