mirror of
https://github.com/db9979/wibosim.git
synced 2026-12-06 13:34:09 +01:00
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUhQVoPUusUzxgxLWkK
135 lines
13 KiB
JavaScript
135 lines
13 KiB
JavaScript
// Depot: Kennzahlen, Margin, Positionen, offene & bedingte Orders, Rückrufe, Rang und Journal.
|
||
import { S, sub, changed, loggedIn } from './state.js';
|
||
import { request } from './net.js';
|
||
import { toast, ask, gl } from './ui.js';
|
||
import { prefill } from './trade.js';
|
||
import { esc, $, int, num, eur, pct, chg, chgEur, frac, dirCls, countdown, now, when, dateY, time, patch, meter } from './util.js';
|
||
|
||
let depotAcc = 'main';
|
||
let journalOpen = false;
|
||
const ACC_LABEL = { main: 'Hauptdepot', battle: 'Battle-Depot', fund: 'Clan-Fonds' };
|
||
|
||
const STATUS = { open: 'offen', partial: 'teilausgeführt', queued: 'gesammelt (Auktion)', conditional: 'überwacht', pending: 'wartet auf Einstieg' };
|
||
const TYPE = { limit: 'Limit', market: 'Market', stop: 'Stop-Loss', stoplimit: 'Stop-Limit', takeprofit: 'Take-Profit', trailing: 'Trailing-Stop' };
|
||
const TIFL = { day: 'Tag', gtc: 'GTC', gtd: 'GTD', ioc: 'IOC', fok: 'FOK' };
|
||
|
||
function render() {
|
||
const el = $('#v-depot');
|
||
if (!loggedIn()) { patch(el, '<div class="card page"><div class="body"><p>Bitte <button type="button" class="linkish" data-act="login">anmelden</button>, um dein Depot zu sehen. Jeder startet mit Spielgeld.</p></div></div>'); return; }
|
||
if ((depotAcc === 'battle' && !S.battlePortfolio) || (depotAcc === 'fund' && !S.fundPortfolio)) depotAcc = 'main';
|
||
const p = depotAcc === 'battle' ? S.battlePortfolio : depotAcc === 'fund' ? S.fundPortfolio : S.portfolio;
|
||
if (!p) { patch(el, '<p class="muted pad">Lade Depot …</p>'); return; }
|
||
const usage = p.marginUsage ?? 0;
|
||
const mcls = usage >= 0.8 ? 'hi' : usage >= 0.5 ? 'mid' : '';
|
||
const rank = p.kind === 'main'
|
||
? (p.rank ? `<b>${int(p.rank.rank)}</b> von ${int(p.rank.of)}` : `<span class="muted">noch nicht in der Wertung: mind. ${int(p.minTradesRanked)} Trades (${int(p.trades)} bisher)</span>`) : '–';
|
||
const warn = [];
|
||
if (p.locked) warn.push('<div class="banner-in down-b" role="alert"><b>Depot gesperrt:</b> Das Eigenkapital ist negativ. Nur das Abbauen von Positionen ist erlaubt – ggf. hilft ein Nachschuss durch die Spielleitung.</div>');
|
||
if (usage >= 0.8) warn.push(`<div class="banner-in down-b" role="alert"><b>Margin kritisch (${frac(usage, 0)}):</b> Ab 100 % droht die Zwangsglattstellung. Short-Positionen reduzieren oder Liquidität erhöhen.</div>`);
|
||
else if (usage >= 0.5) warn.push(`<div class="banner-in">Margin-Auslastung ${frac(usage, 0)} – behalte deine ${gl('Leerverkauf', 'Short-Positionen')} im Blick.</div>`);
|
||
for (const r of p.recalls ?? []) warn.push(`<div class="banner-in down-b" role="alert"><b>Rückruf ${esc(r.symbol)}:</b> Leihgeber fordern Aktien zurück. Short-Position bis <b>${when(r.deadline)}</b> (noch <span class="cd" data-until="${r.deadline}">${countdown(r.deadline - now())}</span>) auf höchstens ${int(r.targetShort)} St. reduzieren, sonst wird zwangsweise eingedeckt.</div>`);
|
||
|
||
const pos = p.positions ?? [];
|
||
const posRows = pos.map((x) => `<tr>
|
||
<td><button type="button" class="sym-btn" data-act="sym" data-sym="${esc(x.symbol)}"><b>${esc(x.symbol)}</b></button>${x.short ? ' <span class="badge-s short">Short</span>' : ''}</td>
|
||
<td class="num">${int(x.qty)}</td><td class="num">${num(x.avgCost)}</td><td class="num">${num(x.last)}</td>
|
||
<td class="num">${eur(x.value)}</td><td class="num">${chgEur(x.pnl)}<small class="block">${chg(x.pnlPct)}</small></td>
|
||
<td class="num">${chg(x.dayChange)}</td><td class="num">${x.short ? frac(x.borrowRate, 1) : '–'}</td>
|
||
<td class="row-actions"><button type="button" class="btn ghost small" data-act="posTrade" data-sym="${esc(x.symbol)}">Handeln</button><button type="button" class="btn ghost small" data-act="posClose" data-sym="${esc(x.symbol)}" data-qty="${x.qty}" data-k="close-${esc(x.symbol)}">${x.short ? 'Eindecken' : 'Verkaufen'}</button></td></tr>`).join('');
|
||
const ordRows = (p.orders ?? []).map((o) => `<tr>
|
||
<td>${esc(o.symbol)}</td><td class="${o.side === 'buy' ? 'up' : 'down'}">${o.side === 'buy' ? '▲ Kauf' : '▼ Verkauf'}</td><td>${esc(TYPE[o.type] ?? o.type)}${o.peak ? ` · Iceberg ${int(o.peak)}` : ''}${o.bracket ? ' · Bracket' : ''}</td>
|
||
<td class="num">${o.price ? num(o.price) : 'Market'}</td><td class="num">${int(o.filled)} / ${int(o.qty)}</td>
|
||
<td>${esc(TIFL[o.tif] ?? o.tif ?? '')}${o.expireAt && o.tif === 'gtd' ? ` bis ${dateY(o.expireAt)}` : ''}</td>
|
||
<td><span class="badge-s ${o.status === 'queued' ? 'auction' : ''}">${esc(STATUS[o.status] ?? o.status)}</span></td>
|
||
<td><button type="button" class="btn ghost small" data-act="cancel" data-id="${esc(o.id)}" data-k="cx-${esc(o.id)}" aria-label="Order ${esc(o.id)} stornieren">Stornieren</button></td></tr>`).join('');
|
||
const condRows = (p.cond ?? []).map((c) => `<tr>
|
||
<td>${esc(c.symbol)}</td><td class="${c.side === 'buy' ? 'up' : 'down'}">${c.side === 'buy' ? '▲ Kauf' : '▼ Verkauf'}</td>
|
||
<td>${esc(c.label ?? TYPE[c.type])}${c.oco ? ` · ${gl('OCO')}` : ''}${c.parent ? ' · Bracket' : ''}</td>
|
||
<td class="num">${num(c.trigger)}${c.trailPct ? `<small class="block">${num(c.trailPct * 100, 1)} % Abstand</small>` : ''}</td><td class="num">${c.limit ? num(c.limit) : '–'}</td>
|
||
<td class="num">${int(c.qty)}</td><td><span class="badge-s">${esc(STATUS[c.status] ?? c.status)}</span></td>
|
||
<td><button type="button" class="btn ghost small" data-act="cancel" data-id="${esc(c.id)}" data-k="cx-${esc(c.id)}" aria-label="Bedingte Order ${esc(c.id)} löschen">Löschen</button></td></tr>`).join('');
|
||
const comp = p.compliance;
|
||
patch(el, `<div class="page">
|
||
${S.battlePortfolio || S.fundPortfolio ? `<div class="seg w-auto" role="group" aria-label="Depot wählen">${['main', S.battlePortfolio ? 'battle' : null, S.fundPortfolio ? 'fund' : null].filter(Boolean).map((k) => `<button type="button" data-act="depotAcc" data-acc="${k}" aria-pressed="${depotAcc === k}">${ACC_LABEL[k]}</button>`).join('')}</div>` : ''}
|
||
${p.kind === 'main' && p.fundValue ? `<p class="muted small">Im Depotwert enthalten: Clan-Fondsanteile ${eur(p.fundValue)} (<button type="button" class="linkish" data-act="view" data-view="clans">Clans & Fonds</button>). Kaufkraft und Margin beziehen sich nur auf das Hauptdepot.</p>` : ''}
|
||
${p.kind === 'fund' ? `<p class="muted small">Clan-Fonds: NAV ${num(p.nav)} € je Anteil (${chg(p.returnPct)} seit Auflage) · ${num(p.totalUnits, 2)} Anteile im Umlauf. Nur Long-Positionen.</p>` : ''}
|
||
${warn.join('')}
|
||
<div class="card"><div class="body">
|
||
<div class="kpis big">
|
||
<div><small>Depotwert</small><b>${eur(p.equity)}</b></div>
|
||
<div><small>Rendite</small><b>${chg(p.returnPct)}</b></div>
|
||
<div><small>Heute</small><b>${chgEur(p.dayPnL)}</b><small>${chg(p.dayPnLPct)}</small></div>
|
||
<div><small>Bargeld</small><b>${eur(p.cash)}</b></div>
|
||
<div><small>${gl('Kaufkraft')}</small><b>${eur(p.available)}</b></div>
|
||
<div><small>Realisiert</small><b>${chgEur(p.realized)}</b></div>
|
||
<div><small>Gebühren</small><b>${eur(p.fees)}</b></div>
|
||
<div><small>Leihgebühren</small><b>${eur(p.borrowAccrued)}</b></div>
|
||
<div><small>Trades</small><b>${int(p.trades)}</b></div>
|
||
<div><small>Rang</small><b class="rank-l">${rank}</b></div>
|
||
</div>
|
||
<div class="margin-line"><span>${gl('Margin')}-Auslastung</span>${meter(usage, { label: 'Margin-Auslastung', cls: mcls })}<b class="num">${frac(usage, 0)}</b>
|
||
<span class="muted small">Long ${eur(p.longValue, 0)} · Short ${eur(p.shortValue, 0)} · Short-Kapazität ${eur(p.shortCapacity, 0)}</span></div>
|
||
${p.rules?.symbols ? `<p class="muted">Battle-Regel: nur ${esc(p.rules.symbols.join(', '))} handelbar.</p>` : ''}${p.rules?.noShort ? '<p class="muted">Battle-Regel: keine Leerverkäufe.</p>' : ''}
|
||
${comp && (comp.cases || comp.fines) ? `<p class="muted small">Börsenaufsicht: ${int(comp.cases)} Verfahren · ${int(comp.warnings)} Verwarnung(en) · ${int(comp.fines)} Bußgeld(er), gesamt ${eur(comp.finedTotal)}</p>` : ''}
|
||
</div></div>
|
||
<div class="card"><h2 class="card-h">Positionen <span class="muted small">${int(pos.length)}</span></h2><div class="body flush scroll-x">
|
||
${pos.length ? `<table><thead><tr><th>Wert</th><th class="num">Stück</th><th class="num">Ø Einstand</th><th class="num">Kurs</th><th class="num">Wert</th><th class="num">G/V</th><th class="num">Heute</th><th class="num">Leihzins</th><th><span class="sr">Aktionen</span></th></tr></thead><tbody>${posRows}</tbody></table>`
|
||
: '<p class="muted pad">Noch keine Positionen. Wähle im Markt eine Aktie und kaufe deine ersten Stücke.</p>'}
|
||
</div></div>
|
||
<div class="card"><h2 class="card-h">Offene Orders <span>${(p.orders?.length || p.cond?.length) ? '<button type="button" class="btn ghost small" data-act="cancelAll">Alle stornieren</button>' : ''}</span></h2><div class="body flush scroll-x">
|
||
${ordRows ? `<table><thead><tr><th>Wert</th><th>Seite</th><th>Typ</th><th class="num">Limit</th><th class="num">Ausgeführt</th><th>Gültig</th><th>Status</th><th><span class="sr">Aktion</span></th></tr></thead><tbody>${ordRows}</tbody></table>` : '<p class="muted pad">Keine offenen Orders.</p>'}
|
||
<h3 class="h4 pad">Bedingte Orders (Stop, Take-Profit, Trailing, OCO)</h3>
|
||
${condRows ? `<table><thead><tr><th>Wert</th><th>Seite</th><th>Typ</th><th class="num">Auslöser</th><th class="num">Limit</th><th class="num">Stück</th><th>Status</th><th><span class="sr">Aktion</span></th></tr></thead><tbody>${condRows}</tbody></table>` : '<p class="muted pad">Keine bedingten Orders.</p>'}
|
||
</div></div>
|
||
${p.kind === 'main' ? `<div class="card"><h2 class="card-h">Journal <button type="button" class="btn ghost small" data-act="journal" aria-expanded="${journalOpen}">${journalOpen ? 'Aktualisieren' : 'Anzeigen'}</button></h2><div class="body" id="journalBody">${journalOpen ? journalHtml() : '<p class="muted">Alle Ausführungen, Gebühren und Kennzahlen dieser Saison.</p>'}</div></div>` : ''}
|
||
</div>`);
|
||
}
|
||
|
||
function journalHtml() {
|
||
const j = S.journal;
|
||
if (!j) return '<p class="muted">Lade Journal …</p>';
|
||
const s = j.stats ?? {};
|
||
const KIND = { trade: 'Trade', dividend: 'Dividende', fine: 'Bußgeld', borrow: 'Leihgebühr', admin: 'Spielleitung', liquidation: 'Zwangsglattstellung', fund: 'Clan-Fonds', fundfee: 'Fondsgebühr', fundclose: 'Fondsauflösung' };
|
||
const SIDE = { buy: '▲ Kauf', sell: '▼ Verkauf', fee: 'Gebühr', deposit: 'Einzahlung', withdraw: 'Belastung', invest: 'Fonds-Einzahlung', redeem: 'Fonds-Rückgabe' };
|
||
return `<div class="kpis">
|
||
<div><small>Geschlossene Trades</small><b>${int(s.closedTrades)}</b></div>
|
||
<div><small>Trefferquote</small><b>${frac(s.winRate, 0)}</b></div>
|
||
<div><small>Ø Gewinn</small><b class="up">${eur(s.avgWin)}</b></div>
|
||
<div><small>Ø Verlust</small><b class="down">${eur(s.avgLoss)}</b></div>
|
||
<div><small>Bester</small><b>${chgEur(s.best ?? 0)}</b></div>
|
||
<div><small>Schlechtester</small><b>${chgEur(s.worst ?? 0)}</b></div>
|
||
<div><small>Profit-Faktor</small><b>${s.profitFactor === null || s.profitFactor === undefined ? '–' : num(s.profitFactor, 2)}</b></div>
|
||
</div>
|
||
${j.rows?.length ? `<div class="scroll-x"><table><thead><tr><th>Zeit</th><th>Art</th><th>Wert</th><th>Seite</th><th class="num">Stück</th><th class="num">Preis</th><th class="num">Gebühr</th><th class="num">Realisiert</th><th>Depot</th></tr></thead><tbody>
|
||
${j.rows.map((r) => `<tr><td>${when(r.ts)}</td><td>${esc(KIND[r.kind] ?? r.kind)}</td><td>${esc(r.symbol)}</td><td>${esc(SIDE[r.side] ?? r.side)}</td><td class="num">${r.qty ? int(r.qty) : ''}</td><td class="num">${r.price ? num(r.price) : ''}</td><td class="num">${num(r.fee)}</td><td class="num">${r.realized ? chgEur(r.realized) : ''}</td><td>${String(r.account).startsWith('b:') ? 'Battle' : String(r.account).startsWith('f:') || r.kind === 'fund' ? 'Fonds' : 'Haupt'}</td></tr>`).join('')}</tbody></table></div>`
|
||
: '<p class="muted">Noch keine Einträge in dieser Saison.</p>'}`;
|
||
}
|
||
|
||
async function loadJournal() {
|
||
try { S.journal = (await request('journal')).journal; } catch (e) { toast(e.message, 'err'); }
|
||
render();
|
||
}
|
||
|
||
export function initDepot() {
|
||
document.addEventListener('click', async (e) => {
|
||
const a = e.target.closest('[data-act]');
|
||
if (!a) return;
|
||
const act = a.dataset.act;
|
||
if (act === 'cancel') {
|
||
const id = a.dataset.id;
|
||
try { await request('cancel', { orderId: /^\d+$/.test(id) ? Number(id) : id }); toast('Order storniert.', 'ok'); } catch (err) { toast(err.message, 'err'); }
|
||
} else if (act === 'cancelAll') {
|
||
if (!(await ask({ title: 'Alle Orders stornieren?', text: `Alle offenen und bedingten Orders im Konto „${ACC_LABEL[depotAcc]}“ werden gelöscht.`, ok: 'Alle stornieren', danger: true }))) return;
|
||
try { await request('cancelAll', { account: depotAcc }); toast('Alle Orders storniert.', 'ok'); } catch (err) { toast(err.message, 'err'); }
|
||
} else if (act === 'depotAcc') { depotAcc = a.dataset.acc; render(); }
|
||
else if (act === 'posTrade') prefill({ symbol: a.dataset.sym, account: depotAcc });
|
||
else if (act === 'posClose') {
|
||
const q = Number(a.dataset.qty);
|
||
prefill({ symbol: a.dataset.sym, side: q > 0 ? 'sell' : 'buy', qty: Math.abs(q), type: 'limit', account: depotAcc });
|
||
toast('Ticket vorbelegt – Limit prüfen und absenden. Du wirst vor dem Senden noch einmal gefragt.', 'info');
|
||
} else if (act === 'journal') { journalOpen = true; S.journal = S.journal ?? null; render(); loadJournal(); }
|
||
});
|
||
sub('portfolio profile', () => { if (S.view === 'depot') render(); });
|
||
}
|
||
export const showDepot = render;
|