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