diff --git a/server/package-lock.json b/server/package-lock.json index 4fa8f31..3d325de 100644 --- a/server/package-lock.json +++ b/server/package-lock.json @@ -1,12 +1,12 @@ { "name": "wibosim-server", - "version": "0.23.1", + "version": "0.24.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "wibosim-server", - "version": "0.23.1", + "version": "0.24.0", "dependencies": { "express": "^5.1.0", "fast-xml-parser": "^5.2.0", diff --git a/server/package.json b/server/package.json index 697f242..f2e4ef4 100644 --- a/server/package.json +++ b/server/package.json @@ -1,6 +1,6 @@ { "name": "wibosim-server", - "version": "0.23.1", + "version": "0.24.0", "description": "WiBoSim – Wirtschafts- & Börsensimulation (Multiplayer)", "type": "module", "main": "src/index.js", diff --git a/server/public/app.js b/server/public/app.js index 49f1696..316f34e 100644 --- a/server/public/app.js +++ b/server/public/app.js @@ -26,6 +26,7 @@ import { initHelp, showHandbook, hintsForView, firstTime } from './js/help.js'; import { initInvite, inviteLanding } from './js/invite.js'; import { icon } from './js/icons.js'; import { setLogoNames } from './js/logos.js'; +import { initDerivs } from './js/derivs.js'; const PHASE_SHORT = { closed: 'Börse geschlossen', preopen: 'Vorbörse', opening: 'Eröffnungsauktion', continuous: 'Fortlaufender Handel', closing: 'Schlussauktion' }; const VIEWS = ['heute', 'markt', 'handeln', 'depot', 'termine', 'parlament', 'battles', 'clans', 'fortschritt', 'community', 'news', 'hilfe', 'mehr']; @@ -365,6 +366,7 @@ async function main() { initAccount({ authed: (isNew) => authWithToken(isNew), loggedOut }); initTrade(go); initDepot(); + initDerivs(); initInfo(); initPolitics(); initBattles(go); diff --git a/server/public/index.html b/server/public/index.html index 950cef1..7163e08 100644 --- a/server/public/index.html +++ b/server/public/index.html @@ -95,6 +95,7 @@ +
diff --git a/server/public/js/depot.js b/server/public/js/depot.js index ee57e9f..c6950ac 100644 --- a/server/public/js/depot.js +++ b/server/public/js/depot.js @@ -4,6 +4,7 @@ import { request } from './net.js'; import { toast, ask, gl } from './ui.js'; import { prefill } from './trade.js'; import { pendingFor, pendingRowDepot } from './pending.js'; +import { derivDepotHtml } from './derivs.js'; import { esc, $, int, num, eur, pct, chg, chgEur, frac, dirCls, countdown, now, when, dateY, time, patch, meter } from './util.js'; import { logo } from './logos.js'; @@ -79,6 +80,7 @@ function render() { : `

Noch keine Positionen. Wähle im Markt einen Wert und kaufe deine ersten Stücke – außerhalb der Handelszeit wird die Order für die nächste Auktion gesammelt.${p.kind === 'main' ? ` Für die Rangliste brauchst du mindestens ${int(S.leaderboard?.minTrades ?? 5)} Trades.` : ''}

`} + ${derivDepotHtml(p)}

Offene Orders ${(p.orders?.length || p.cond?.length) ? '' : ''}

${ordRows ? `${ordRows}
WertSeiteTypLimitAusgeführtGültigStatusAktion
` : '

Keine offenen Orders.

'}

Bedingte Orders (Stop, Take-Profit, Trailing, OCO)

@@ -92,7 +94,7 @@ function journalHtml() { const j = S.journal; if (!j) return '

Lade Journal …

'; const s = j.stats ?? {}; - const KIND = { trade: 'Trade', auction: 'Auktion', dividend: 'Dividende', fine: 'Bußgeld', borrow: 'Leihgebühr', admin: 'Spielleitung', liquidation: 'Zwangsglattstellung', fund: 'Clan-Fonds', fundfee: 'Fondsgebühr', fundclose: 'Fondsauflösung' }; + const KIND = { deriv: 'Hebelprodukt', derivExpiry: 'Fälligkeit', derivKO: 'Knock-out', derivSeason: 'Saisonende', trade: 'Trade', auction: 'Auktion', 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 `
Geschlossene Trades${int(s.closedTrades)}
diff --git a/server/public/js/derivs.js b/server/public/js/derivs.js new file mode 100644 index 0000000..a95b1b9 --- /dev/null +++ b/server/public/js/derivs.js @@ -0,0 +1,306 @@ +// Hebelprodukte (Optionsscheine und Turbos des Emittenten): Reiter „Hebelprodukte“ auf der Kursseite, Orderticket +// als Dialog, Depot-Gruppe und Meldungen zu Knock-out und Verfall. Gehandelt wird sofort zu Geld/Brief des Emittenten. +import { S, loggedIn } from './state.js'; +import { request, on } from './net.js'; +import { toast, ask, openModal, gl, browserNotify } from './ui.js'; +import { esc, num, int, eur, chg, chgEur, patch, store } from './util.js'; + +const KIND = { call: 'Call', put: 'Put', long: 'Turbo Long', short: 'Turbo Short' }; +const KIND_LONG = { call: 'Optionsschein (Call)', put: 'Optionsschein (Put)', long: 'Turbo-Zertifikat Long (Knock-out)', short: 'Turbo-Zertifikat Short (Knock-out)' }; +const IDX = 'WIBO10'; +export const RISK_TEXT = 'Totalverlust möglich, Zeitwert schmilzt täglich, Knock-out kann jederzeit eintreten.'; +const n3 = (x) => num(x, 3); +const isW = (k) => k === 'call' || k === 'put'; +const uName = (u) => (u === IDX ? 'WIBO-10' : u); + +// ---------------------------------------------------------------- Zustand des Reiters +let data = null; // Antwort von „derivs“ +let loadingKey = ''; +let lastLoad = 0; +let tabEl = null; +let useIndex = false; // Basiswert-Umschalter: Indexprodukte statt des gewählten Werts +let ack = false; // Risikohinweis bestätigt (Server merkt es sich) +const F = { kind: store.get('dKind', 'all'), tenor: 'all', lev: 'all', sort: store.get('dSort', ''), dir: 1 }; +let reveal = !!store.get('dReveal', false); // Einsteiger-Modus: Produkte erst nach Hinweis zeigen + +const curU = () => (useIndex ? IDX : S.symbol); + +async function load(force = false) { + const u = curU(); + const key = `${u}`; + if (!force && loadingKey === key && Date.now() - lastLoad < 1500) return; + loadingKey = key; lastLoad = Date.now(); + try { + const r = await request('derivs', { symbol: u }); + if (curU() !== u) return; + data = r.derivs; + if (data.ack) ack = true; + if (tabEl && document.contains(tabEl)) renderDerivTab(tabEl, { fetch: false }); + } catch (e) { if (!/Verbindung/.test(e.message)) toast(e.message, 'err'); } +} + +const fmtExp = (x) => `Tag ${int(x.expDay)}`; +const levBand = (l) => (!Number.isFinite(l) ? 'all' : l <= 5 ? 'lo' : l <= 10 ? 'mid' : 'hi'); + +function rowsOf(items) { + let list = items.filter((x) => (F.kind === 'all' || x.kind === F.kind) && (F.tenor === 'all' || x.tenor === F.tenor || (!isW(x.kind) && F.tenor === 'all')) && (F.lev === 'all' || levBand(x.lev) === F.lev)); + if (F.tenor !== 'all') list = list.filter((x) => isW(x.kind)); + const key = { + name: (x) => `${x.kind}|${String(x.strike).padStart(12, '0')}`, strike: (x) => x.strike, exp: (x) => (isW(x.kind) ? x.daysLeft : 1e9 - (x.dist ?? 0)), + lev: (x) => x.lev ?? 0, bid: (x) => x.bid, ask: (x) => x.ask, delta: (x) => x.delta, theta: (x) => x.theta ?? 0, + }[F.sort]; + if (key) list = [...list].sort((a, b) => (key(a) > key(b) ? 1 : key(a) < key(b) ? -1 : 0) * F.dir); + return list; +} + +const th = (k, label, cls = '') => ``; + +export function renderDerivTab(el, { fetch = true } = {}) { + tabEl = el; + const t = S.tickerMap.get(S.symbol); + if (fetch && (!data || data.u !== curU() || Date.now() - lastLoad > 3000)) load(); + const explain = `

Optionsscheine und Turbo-Zertifikate der Wiborischen Handelsbank. Du handelst direkt mit dem Emittenten zu Geld- und Briefkurs – sofort, ohne Orderbuch. Ein ${gl('Call')} gewinnt bei steigendem, ein ${gl('Put')} bei fallendem Kurs; ein ${gl('Turbo')} folgt dem Basiswert mit Hebel, verfällt aber sofort wertlos, wenn der Basiswert die ${gl('Knock-out')}-Schwelle berührt. Die Kurse der Scheine bewegen sich mit dem Basiswert – warum er sich bewegt, steht im ersten Reiter.

`; + if (S.simple && !reveal) { + patch(el, `${explain}`); + return; + } + const d = data && data.u === curU() ? data : null; + if (!d) { patch(el, `${explain}

Lade Hebelprodukte …

`); return; } + const idxSwitch = d.indexLink || useIndex ? `
+ +
` : ''; + if (!d.items.length) { + patch(el, `${idxSwitch}${explain}

Auf ${esc(d.uLabel)} gibt es keine Hebelprodukte. Optionsscheine und Turbos gibt es auf die zehn WIBO-10-Werte, den WIBO-10, Gold und Öl; Turbos zusätzlich auf Erdgas und WiboCoin.

+ `); + return; + } + const kinds = [['all', 'Alle'], ...(d.warrants ? [['call', 'Call'], ['put', 'Put']] : []), ...(d.turbos ? [['long', 'Turbo Long'], ['short', 'Turbo Short']] : [])]; + if (!kinds.some(([k]) => k === F.kind)) F.kind = 'all'; + const list = rowsOf(d.items); + const rows = list.map((x) => { + const w = isW(x.kind); + const term = w ? `${fmtExp(x)} ${esc(x.tenor ?? '')} · ${num(x.daysLeft, 1)} T` + : `KO ${num(x.ko)} ${num((x.dist ?? 0) * 100, 1)} % entfernt`; + return ` + ${x.held ? ` ${int(x.held)}` : ''}${esc(x.id)} · BV ${num(x.ratio, x.ratio < 0.01 ? 3 : 2)} + ${term} + ${x.lev ? num(x.lev, 1) : '–'} + ${n3(x.bid)}${n3(x.ask)} + ${w ? num(x.delta, 2) : (x.delta > 0 ? '1' : '−1')} + ${Number.isFinite(x.theta) ? n3(x.theta) : '–'}`; + }).join(''); + const tenorSel = d.warrants ? `` : ''; + patch(el, `
${idxSwitch}${esc(d.uLabel)} ${num(d.spot)}${d.u === IDX ? ' Punkte' : ' €'} · ${gl('Implizite Volatilität', 'Vola')} ${num(d.sigma * 100, 0)} % · Leitzins ${num(d.rate * 100, 2)} %
+ ${d.closed ? `` : ''} + ${S.simple ? `` : ''} +
+
${kinds.map(([k, l]) => ``).join('')}
+ ${tenorSel} + + ${int(list.length)} von ${int(d.items.length)} +
+
+ ${th('name', 'Produkt')}${th('exp', 'Fälligkeit / KO')}${th('lev', 'Hebel', 'num')}${th('bid', 'Geld', 'num')}${th('ask', 'Brief', 'num')}${th('delta', 'Delta', 'num')}${th('theta', 'Theta/Tag', 'num')} + ${rows || ''}
Keine Produkte für diesen Filter.
+ ${explain}

Emittent: ${esc(d.issuer)} · höchstens ${eur(d.limits.maxOrder, 0)} je Order und ${eur(d.limits.maxPerUnderlying, 0)} Einsatz je Basiswert · Gebühren wie bei Aktien · Bewertung im Depot zum Geldkurs.

`); +} + +// ---------------------------------------------------------------- Orderticket +let tk = null; // { el, close, prod, side, qty, account, timer, busy } +let unsure = null; // { key, cid, ts }: zuletzt gesendete Order ohne sichere Antwort + +function scenario(x, q) { + const u = esc(uName(x.u)); + const unit = x.u === IDX ? ' Punkte' : ' €'; + if (x.kind === 'call') return `Steigt ${u} bis zur Fälligkeit über ${num(q.breakEven)}${unit}, verdienst du – sonst Verlust bis zum Totalverlust.`; + if (x.kind === 'put') return `Fällt ${u} bis zur Fälligkeit unter ${num(q.breakEven)}${unit}, verdienst du – sonst Verlust bis zum Totalverlust.`; + const dir = x.kind === 'long' ? 'Fällt' : 'Steigt'; + return `${dir} ${u} auch nur kurz auf ${num(x.ko)}${unit} (Knock-out-Schwelle), verfällt der Turbo sofort wertlos. ${x.kind === 'long' ? 'Steigt' : 'Fällt'} ${u} um 1 %, gewinnt er etwa ${num(q.lev ?? 0, 1)} %.`; +} + +function kpis(x) { + const w = isW(x.kind); + const unit = x.u === IDX ? ' P.' : ' €'; + const items = w + ? [['Basispreis', `${num(x.strike)}${unit}`, 'Basispreis'], ['Fälligkeit', `${fmtExp(x)} · ${num(x.daysLeft, 1)} T`, null], ['Bezugsverhältnis', num(x.ratio, x.ratio < 0.01 ? 3 : 2), 'Bezugsverhältnis'], + ['Hebel (Omega)', num(x.lev, 1), 'Hebel'], ['Delta', num(x.delta, 2), 'Delta'], ['Aufgeld', `${num(x.premiumPct, 1)} %`, 'Aufgeld'], + ['Break-even', `${num(x.breakEven)}${unit}`, null], ['Theta je Tag', `${n3(x.theta)} €`, 'Theta'], ['Impl. Vola', `${num((x.sigma ?? 0) * 100, 0)} %`, 'Implizite Volatilität']] + : [['Knock-out', `${num(x.ko)}${unit}`, 'Knock-out'], ['Abstand', `${num((x.dist ?? 0) * 100, 1)} %`, null], ['Bezugsverhältnis', num(x.ratio, x.ratio < 0.01 ? 3 : 2), 'Bezugsverhältnis'], + ['Hebel', num(x.lev, 1), 'Hebel'], ['Basispreis', `${num(x.strike)}${unit}`, 'Basispreis'], ['Finanzierung je Tag', `${n3(x.theta)} €`, 'Finanzierungskosten'], + ['Aufgeld', `${num(x.premiumPct, 1)} %`, 'Aufgeld'], ['Break-even', `${num(x.breakEven)}${unit}`, null], ['Laufzeit', 'open end', null]]; + return `
${items.map(([k, v, g]) => `
${g ? gl(g, k) : esc(k)}
${v}
`).join('')}
`; +} + +function ticketBody() { + const x = tk.prod; + const held = x.held ?? 0; + const side = tk.side; + const px = side === 'buy' ? x.ask : x.bid; + const qty = tk.qty; + const notional = qty * px; + const fee = notional > 0 ? notional * (S.info?.fees?.taker ?? 0.0005) + (S.info?.fees?.fixed ?? 0.9) : 0; + const acc = tk.account === 'battle' ? S.battlePortfolio : S.portfolio; + const avail = acc?.available ?? 0; + const nn = (v) => `${v}`; + const rows = [ + [side === 'buy' ? 'Du kaufst' : 'Du verkaufst', `${nn(int(qty))} × ${esc(x.name)}`], + ['Ausführung', x.status !== 'active' ? 'nicht mehr handelbar' : x.closed ? 'ruht – Basiswert nicht im Handel' : `sofort beim Emittenten, ${nn(`${n3(px)} €`)} (${side === 'buy' ? 'Brief' : 'Geld'})`], + [side === 'buy' ? 'Kosten' : 'Erlös', qty > 0 && px > 0 ? `${nn(eur(side === 'buy' ? notional + fee : notional - fee))} inkl. Gebühr` : '–'], + side === 'buy' ? ['Max. Verlust', qty > 0 ? `${nn(eur(notional + fee))} (Totalverlust)` : '–'] : ['Danach', held - qty > 0 ? `${nn(int(held - qty))} Stück im Depot` : 'Position geschlossen'], + side === 'buy' ? ['Kaufkraft', `${nn(eur(Math.max(0, avail - notional - fee)))} danach`] : ['Bestand', `${nn(int(held))} Stück`], + ]; + const tooBig = side === 'buy' && notional > (data?.limits?.maxOrder ?? 25000); + const warn = tooBig ? `Höchstens ${eur(data?.limits?.maxOrder ?? 25000, 0)} je Order.` : side === 'buy' && notional + fee > avail ? 'Nicht genug Kaufkraft.' : side === 'sell' && qty > held ? 'So viele Stück hast du nicht – Leerverkauf ist nicht möglich.' : side === 'sell' && !(x.bid > 0) ? 'Der Schein ist praktisch wertlos: kein Geldkurs. Er wird bei Fälligkeit ausgebucht.' : (!isW(x.kind) && side === 'buy' && (x.dist ?? 1) < 0.005) ? 'Zu nah an der Knock-out-Schwelle – nur noch Verkauf.' : ''; + const accSeg = S.battlePortfolio ? `
` : ''; + return `
+
Geld${n3(x.bid)} €
Brief${n3(x.ask)} €
+
${esc(uName(x.u))}${num(x.spot)}
Spanne${num((x.spread ?? 0) * 100, 1)} %
+ ${kpis(x)} + ${accSeg} +
+
+
Schnell
${side === 'buy' ? [500, 1000, 5000].map((v) => ``).join('') : ``}
+
Klartext
${rows.map(([k, v]) => `
${k}
${v}
`).join('')}

${scenario(x, x)}

+

Risiko: ${esc(RISK_TEXT)}

+ +
${esc(warn || (x.closed ?? ''))}
`; +} + +function paintTicket() { + if (!tk) return; + const body = tk.el.querySelector('#dBody'); + patch(body, ticketBody()); +} + +async function refreshTicket() { + if (!tk || tk.busy) return; + try { + const r = await request('derivQuote', { id: tk.prod.id }); + if (!tk || r.deriv.id !== tk.prod.id) return; + tk.prod = r.deriv; + paintTicket(); + } catch { /* nächster Versuch */ } +} + +export async function openDerivTicket(id, { side = 'buy', qty = 0, account = null } = {}) { + if (!loggedIn()) { toast('Zum Handeln bitte anmelden.', 'info'); return; } + let prod; + try { prod = (await request('derivQuote', { id })).deriv; } catch (e) { toast(e.message, 'err'); return; } + tk?.close(); + const acct = account ?? (S.account === 'battle' && S.battlePortfolio ? 'battle' : 'main'); + if (S.account === 'fund') toast('Im Clan-Fonds sind Hebelprodukte nicht erlaubt – der Kauf läuft über dein Hauptdepot.', 'info'); + if (side === 'sell' && !prod.held) side = 'buy'; + const defQty = qty || (side === 'sell' ? prod.held : Math.max(1, Math.floor(1000 / Math.max(0.001, prod.ask)))); + const { el, close } = openModal(`

${esc(prod.name)}

+

${esc(KIND_LONG[prod.kind])} · Emittent Wiborische Handelsbank · ${esc(prod.id)}

+
`, + { label: `Orderticket ${prod.name}`, cls: 'd-modal', onClose: () => { clearInterval(tk?.timer); tk = null; } }); + tk = { el, close, prod, side, qty: defQty, account: acct, timer: setInterval(refreshTicket, 2000), busy: false }; + paintTicket(); + el.addEventListener('click', (e) => { + const s = e.target.closest('[data-dside]'); + if (s && !s.disabled) { tk.side = s.dataset.dside; tk.qty = tk.side === 'sell' ? (tk.prod.held ?? 0) : Math.max(1, Math.floor(1000 / Math.max(0.001, tk.prod.ask))); paintTicket(); return; } + const a = e.target.closest('[data-dacc]'); + if (a) { tk.account = a.dataset.dacc; paintTicket(); return; } + const q = e.target.closest('[data-dqe]'); + if (q) { tk.qty = q.dataset.dqe === 'all' ? (tk.prod.held ?? 0) : Math.max(1, Math.floor(Number(q.dataset.dqe) / Math.max(0.001, tk.prod.ask))); paintTicket(); } + }); + el.addEventListener('input', (e) => { if (e.target.id === 'dQty') { tk.qty = Math.max(0, Math.floor(Number(e.target.value) || 0)); paintTicket(); } }); + el.querySelector('#derivTicket').addEventListener('submit', (e) => { e.preventDefault(); submit(); }); +} + +async function submit() { + if (!tk || tk.busy) return; + const x = tk.prod; + if (!(tk.qty >= 1)) { toast('Bitte eine Stückzahl ≥ 1 eingeben', 'err'); return; } + let withAck = false; + if (tk.side === 'buy' && !ack && !S.profile?.derivAck) { + const ok = await ask({ title: 'Wichtiger Hinweis: Hebelprodukte', ok: 'Verstanden – weiter', + html: `

${esc(RISK_TEXT)}

  • Optionsscheine verlieren jeden Tag an Zeitwert und können wertlos verfallen.
  • Turbos verfallen sofort wertlos, sobald der Basiswert die Knock-out-Schwelle berührt – auch außerhalb deines Blicks.
  • Du kannst höchstens deinen Einsatz verlieren; ein Hebel von 10 macht aus 1 % Kursbewegung etwa 10 % Gewinn oder Verlust.
` }); + if (!ok) return; + withAck = true; + } + tk.busy = true; + // Wiederholung ohne sichere Antwort (Zeitüberschreitung, Verbindungsabbruch): dieselbe clientId → der Server kauft nicht doppelt + const key = `${x.id}|${tk.side}|${tk.qty}|${tk.account}`; + if (!(unsure && unsure.key === key && Date.now() - unsure.ts < 9 * 60_000)) unsure = { key, cid: `d-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`, ts: Date.now() }; + const cid = unsure.cid; + const body = { id: x.id, side: tk.side, qty: tk.qty, account: tk.account, clientId: cid, ack: withAck || undefined }; + const send = () => request('derivOrder', body); + try { + let r; + try { r = await send(); } catch (e) { + if (!e.needAck) throw e; + if (!(await ask({ title: 'Wichtiger Hinweis: Hebelprodukte', html: `

${esc(RISK_TEXT)}

`, ok: 'Verstanden – kaufen' }))) return; + body.ack = true; r = await send(); + } + unsure = null; + ack = ack || tk.side === 'buy'; + const o = r.order; + toast(`${o.side === 'buy' ? 'Kauf' : 'Verkauf'} ${int(o.qty)} × ${o.name} zu ${n3(o.price)} € · Gebühr ${eur(o.fee)}${o.realized ? ` · realisiert ${o.realized > 0 ? '+' : ''}${eur(o.realized)}` : ''}${o.duplicate ? ' (bereits ausgeführt)' : ''}`, 'ok', { title: 'Hebelprodukt ausgeführt' }); + tk?.close(); + load(true); + } catch (e) { + if (!/Zeitüberschreitung|Verbindung/.test(e.message)) unsure = null; + toast(e.message, 'err', { title: 'Nicht ausgeführt' }); refreshTicket(); + } + finally { if (tk) tk.busy = false; } +} + +// ---------------------------------------------------------------- Depot +export function derivDepotHtml(p) { + const list = p?.derivs ?? []; + if (!list.length) return ''; + const total = list.reduce((a, x) => a + x.value, 0), pnl = list.reduce((a, x) => a + x.pnl, 0); + const rows = list.map((x) => { + const w = isW(x.kind); + const risk = w ? `${fmtExp(x)}${num(x.daysLeft, 1)} Handelstage` : `KO ${num(x.ko)}${num((x.dist ?? 0) * 100, 1)} % Abstand`; + return `${esc(x.id)} + ${int(x.qty)}${n3(x.avgCost)}${n3(x.bid)}${eur(x.value)} + ${chgEur(x.pnl)}${chg(x.pnlPct)}${x.lev ? num(x.lev, 1) : '–'}${risk} +
`; + }).join(''); + return `

Hebelprodukte ${int(list.length)} · ${eur(total)} · G/V ${chgEur(pnl)}

+ ${rows}
ProduktStückØ EinstandGeldWertG/VHebelFälligkeit / Knock-outAktionen
+

Bewertet zum Geldkurs des Emittenten. Hebelprodukte belasten keine Margin – du kannst höchstens den Einsatz verlieren. Optionsscheine werden bei Fälligkeit bar abgerechnet, Turbos verfallen bei Knock-out sofort.

`; +} + +// ---------------------------------------------------------------- Ereignisse +export function initDerivs() { + document.addEventListener('click', (e) => { + const a = e.target.closest('[data-act]'); + if (!a) return; + const act = a.dataset.act; + if (act === 'derivOpen') openDerivTicket(a.dataset.id); + else if (act === 'derivSell') openDerivTicket(a.dataset.id, { side: 'sell', qty: Number(a.dataset.qty) }); + else if (act === 'dKind') { F.kind = a.dataset.kind; store.set('dKind', F.kind); if (tabEl) renderDerivTab(tabEl, { fetch: false }); } + else if (act === 'dUse') { useIndex = a.dataset.u === 'idx'; data = null; if (tabEl) renderDerivTab(tabEl); } + else if (act === 'dReveal') { reveal = true; store.set('dReveal', true); if (tabEl) renderDerivTab(tabEl); } + }); + document.addEventListener('click', (e) => { + const b = e.target.closest('[data-dsort]'); + if (!b) return; + const k = b.dataset.dsort; + if (F.sort === k) F.dir = -F.dir; else { F.sort = k; F.dir = 1; } + store.set('dSort', F.sort); + if (tabEl) renderDerivTab(tabEl, { fetch: false }); + }); + document.addEventListener('change', (e) => { + if (e.target.id === 'dTenor') { F.tenor = e.target.value; if (tabEl) renderDerivTab(tabEl, { fetch: false }); } + else if (e.target.id === 'dLev') { F.lev = e.target.value; if (tabEl) renderDerivTab(tabEl, { fetch: false }); } + }); + // Kurse im offenen Reiter laufend auffrischen + setInterval(() => { + if (!tabEl || !document.contains(tabEl) || tabEl.offsetParent === null || document.hidden) return; + if (S.simple && !reveal) return; + load(); + }, 3000); + on('derivKO', (m) => { + toast(`${uName(m.u)} hat die Schwelle ${num(m.strike)} berührt (${num(m.spot)}). ${int(m.qty)} Stück ${m.name} sind wertlos verfallen: −${eur(m.loss)}${m.account === 'battle' ? ' (Battle-Depot)' : ''}.`, 'err', { title: 'Knock-out', ms: 12_000 }); + browserNotify('Knock-out', `${m.name}: −${eur(m.loss)}`); + if (tk?.prod?.id === m.id) refreshTicket(); + load(true); + }); + on('derivExpiry', (m) => toast(`${m.name}: ${int(m.qty)} Stück abgerechnet zu ${n3(m.price)} € (${m.realized >= 0 ? '+' : ''}${eur(m.realized)}).`, m.price > 0 ? 'ok' : 'warn', { title: 'Optionsschein fällig' })); +} diff --git a/server/public/js/feedback.js b/server/public/js/feedback.js index 9dc1077..e8c8970 100644 --- a/server/public/js/feedback.js +++ b/server/public/js/feedback.js @@ -17,7 +17,7 @@ const WS_ACTS = ['cancel', 'cancelAll', 'vote', 'cosign', 'withdrawBill', 'elVot 'tender', 'watch', 'alert', 'anaLike', 'respond', 'queueLeave', 'queueBot', 'rematch', 'clanJoin', 'clanDecline', 'clanLeave', 'clanKick', 'clanOpen', 'fundOpen', 'fundRedeemAll', 'tourJoin', 'tourLeave', 'unfollow', 'readAll', 'readOne', 'todoClaim', 'todoHide', 'todoUnhide']; const WS_FORMS = ['#ticket', '#propForm', '#foundForm', '#donateForm', '#clanCreateForm', '#clanInviteForm', '#fundInvestForm', '#fundRedeemForm', - '#challengeForm', '#queueForm', '#followForm', '.agm-form', '.ipo-form', '.c-form', '.ana-form']; + '#challengeForm', '#queueForm', '#followForm', '.agm-form', '.ipo-form', '.c-form', '.ana-form', '#derivTicket']; export const WS_SEL = [...WS_ACTS.map((a) => `[data-act="${a}"]`), ...WS_FORMS.map((f) => `${f} [type="submit"]`), '[data-pf="follow"]', '[data-pf="unfollow"]', '[data-ws]'].join(','); /** Gleichen Button nach einem Neu-Rendern wiederfinden (id, sonst alle data-Attribute) */ diff --git a/server/public/js/helptext.js b/server/public/js/helptext.js index bcaf16d..18b1b25 100644 --- a/server/public/js/helptext.js +++ b/server/public/js/helptext.js @@ -249,6 +249,13 @@ export const CARD_HELP = { effect: 'Sobald ein eingeladener Spieler seinen ersten Handel macht, bekommt ihr beide XP; du erhältst den Erfolg „Netzwerker“ (Stufen bei 3 und 10 aktiven Freunden). Spielgeld gibt es dafür nicht.', tip: 'Keine Zweitkonten: Einladungen vom selben Anschluss (gleiche IP) bringen keine XP – die Freundschaft entsteht trotzdem.', }, + hebel: { + match: ['Hebelprodukte'], title: 'Hebelprodukte', chapter: 'hebel', terms: ['Optionsschein', 'Turbo', 'Knock-out', 'Hebel', 'Zeitwert', 'Finanzierungskosten'], + what: 'Optionsscheine (Call/Put) und Turbo-Zertifikate des fiktiven Emittenten Wiborische Handelsbank auf die zehn WIBO-10-Werte, den WIBO-10, Gold und Öl sowie Turbos auf Erdgas und WiboCoin.', + how: ['Auf der Kursseite eines Werts den Reiter „Hebelprodukte“ öffnen (bei Indexwerten ist auch der WIBO-10 wählbar).', 'Nach Art, Laufzeit und Hebel filtern, Spalten per Klick sortieren.', 'Produkt anklicken: Das Ticket zeigt die Kennzahlen und im Klartext, ab welchem Kurs du verdienst.', 'Gekauft und verkauft wird sofort beim Emittenten zu Brief bzw. Geld – ohne Orderbuch.'], + effect: 'Hebelprodukte bewegen den Basiswert nicht. Sie zählen zum Depotwert (zum Geldkurs), belasten keine Margin und können höchstens den Einsatz kosten. Am Saisonende werden sie zum Geldkurs ausgebucht.', + tip: 'Kleine Beträge, klare Idee, kurzer Zeitraum. Optionsscheine verlieren täglich Zeitwert, Turbos können jederzeit ausgeknockt werden – nie das ganze Depot einsetzen.', + }, social: { match: ['Freunde', 'Posteingang', 'Pinnwand', 'Gesendete Einladungen'], title: 'Community', chapter: 'wettbewerb', terms: [], what: 'Freunde, Nachrichten, Einladungen und Pinnwände.', @@ -328,6 +335,22 @@ export const TERMS = { Unternehmensanleihe: { short: 'Unternehmensanleihe: Anleihe eines Unternehmens – Rendite = Staatsrendite + Risikoaufschlag nach Rating.', long: 'Unternehmen leihen sich Geld über Anleihen mit festem Kupon und fester Laufzeit. Der Kurs folgt den Staatszinsen derselben Laufzeit und dem Risikoaufschlag, der vom Rating des Emittenten abhängt. Wie bei WIB2 und WIB10 laufen Stückzinsen auf, der Kupon wird vierteljährlich gezahlt, und die Restlaufzeit bleibt konstant. Hochzinsanleihen (BB+ und schlechter) zahlen hohe Kupons, tragen aber echtes Ausfallrisiko.', example: 'Anleihe mit 4,375 % Kupon, Rating BBB+: Staatsrendite 3,0 % + Aufschlag 1,4 Pp. = Rendite 4,4 % → Kurs knapp unter 100.', effect: 'Steigende Zinsen und Herabstufungen drücken den Kurs; Hochstufungen und sinkende Zinsen heben ihn. Market Maker stellen bei schlechterem Rating breitere Spreads.', see: ['Rating', 'Risikoaufschlag', 'Kupon', 'Ausfall'] }, Ausfall: { short: 'Ausfall: Ein Unternehmen kann seine Schulden nicht bedienen (Rating D). Anleihen werden zum Restwert abgewickelt.', long: 'Nur sehr schwache Unternehmen (CCC und schlechter) können ausfallen – das ist selten. Bei einem Ausfall werden alle Anleihen des Unternehmens zum Restwert von 20–50 % des Nennwerts ausbezahlt und aus den Depots ausgebucht; offene Orders darauf werden gestrichen. Die Aktie bricht ein: Die Gläubiger tauschen Forderungen in neue Aktien (starke Verwässerung), die Schulden sinken. Danach startet das Unternehmen mit einem neuen Rating im Hochzinsbereich und gibt eine neue Anleihe aus.', example: 'Rating CC, Zinsdeckung unter 1×: Zahlungsausfall. Die Anleihe wird zu 35 € je 100 € abgerechnet, die Aktie verliert rund 90 %.', effect: 'Wer Hochzinsanleihen hält, sollte Rating, Ausblick und Zinsdeckung im Blick behalten – vor einem Ausfall kommen meist mehrere Herabstufungen.', see: ['Rating', 'Unternehmensanleihe', 'Zinsdeckung'] }, Rückruf: { short: 'Rückruf: Der Verleiher fordert geliehene Aktien zurück – deine Short-Position muss eingedeckt werden.', long: 'Wird der Leihpool knapp, können Verleiher Aktien zurückrufen. Du bekommst eine Frist; danach wird zwangsweise eingedeckt.', example: 'Rückruf bei einer HTB-Aktie: Short muss innerhalb der Frist geschlossen werden.', effect: 'Erhöht das Risiko bei knappen Aktien.', see: ['HTB', 'Leerverkauf'] }, + Optionsschein: { short: 'Optionsschein: Wertpapier, das mit Hebel auf steigende (Call) oder fallende (Put) Kurse setzt – mit fester Laufzeit.', long: 'Ein Optionsschein verbrieft die Differenz zwischen dem Kurs des Basiswerts und dem Basispreis am Fälligkeitstag, umgerechnet mit dem Bezugsverhältnis. In WiBoSim gibt sie der fiktive Emittent Wiborische Handelsbank heraus; du kaufst und verkaufst direkt bei ihm zu Geld- und Briefkurs. Am Fälligkeitstag wird bar abgerechnet (zum Schlusskurs des Basiswerts), danach verschwindet der Schein aus dem Depot.', example: 'Call NVLT, Basispreis 150 €, Bezugsverhältnis 0,1. NVLT schließt am Fälligkeitstag bei 165 €: Gutschrift (165 − 150) × 0,1 = 1,50 € je Schein.', effect: 'Hoher Hebel nach oben und unten. Der Zeitwert schmilzt täglich – je näher die Fälligkeit, desto schneller. Totalverlust, wenn der Schein am Ende aus dem Geld ist.', see: ['Call', 'Put', 'Basispreis', 'Bezugsverhältnis', 'Zeitwert'] }, + Call: { short: 'Call: Optionsschein auf steigende Kurse. Lohnt sich, wenn der Basiswert bei Fälligkeit über Basispreis plus gezahltem Preis liegt.', long: 'Ein Call gewinnt, wenn der Basiswert steigt. Am Ende ist er (Kurs − Basispreis) × Bezugsverhältnis wert, mindestens null.', example: 'Basispreis 100 €, Bezugsverhältnis 0,1, Preis 0,80 €: Break-even bei 108 €.', effect: 'Calls sind bei gleichem Abstand meist etwas teurer als Puts, weil Geld bis zur Fälligkeit Zinsen bringen könnte.', see: ['Put', 'Optionsschein', 'Break-even'] }, + Put: { short: 'Put: Optionsschein auf fallende Kurse. Lohnt sich, wenn der Basiswert bei Fälligkeit unter Basispreis minus gezahltem Preis liegt.', long: 'Ein Put gewinnt, wenn der Basiswert fällt. Am Ende ist er (Basispreis − Kurs) × Bezugsverhältnis wert, mindestens null. So kannst du auf fallende Kurse setzen, ohne leerzuverkaufen – und ohne Nachschusspflicht.', example: 'Basispreis 40 €, Bezugsverhältnis 1, Preis 1,20 €, Aktie schließt bei 35 €: 5,00 € Gutschrift, also +317 %.', effect: 'Absicherung eines Aktienbestands oder Spekulation auf fallende Kurse. Erwartete Dividenden machen Puts etwas teurer.', see: ['Call', 'Leerverkauf'] }, + Basispreis: { short: 'Basispreis (Strike): Kurs des Basiswerts, ab dem ein Optionsschein am Ende etwas wert ist. Beim Turbo zugleich die Knock-out-Schwelle.', long: 'Beim Call zählt, wie weit der Basiswert über dem Basispreis liegt, beim Put, wie weit darunter. Liegt der Basispreis nahe am Kurs, heißt der Schein „am Geld“; Calls mit Basispreis über dem Kurs sind „aus dem Geld“, darunter „im Geld“.', example: 'Aktie 142,50 €: Call mit Basispreis 130 € ist im Geld, Call mit 160 € aus dem Geld.', effect: 'Je weiter aus dem Geld, desto billiger und hebelstärker – aber auch desto wahrscheinlicher der Totalverlust.', see: ['Innerer Wert (Optionsschein)', 'Turbo'] }, + Bezugsverhältnis: { short: 'Bezugsverhältnis: Wie viele Einheiten des Basiswerts ein Schein abbildet, z. B. 0,1 = ein Zehntel einer Aktie.', long: 'Damit Scheine handliche Preise haben, beziehen sie sich auf einen Bruchteil des Basiswerts. Bei Aktien meist 0,1 oder 1, beim WIBO-10 0,01.', example: 'Bezugsverhältnis 0,1: Steigt die Aktie um 1 €, steigt der innere Wert eines Calls um 0,10 €.', effect: 'Ändert nichts an Chance und Risiko – nur an der Stückzahl, die du für denselben Einsatz kaufst.', see: ['Optionsschein'] }, + 'Innerer Wert (Optionsschein)': { short: 'Innerer Wert eines Optionsscheins: was er bei sofortiger Fälligkeit wert wäre – (Kurs − Basispreis) × Bezugsverhältnis beim Call, umgekehrt beim Put, nie unter null.', long: 'Der innere Wert ist der Teil des Preises, der schon „sicher“ im Schein steckt. Der Emittent stellt nie einen Preis unter dem inneren Wert.', example: 'Aktie 150 €, Call-Basispreis 140 €, Bezugsverhältnis 0,1: innerer Wert 1,00 €.', effect: 'Preis = innerer Wert + Zeitwert.', see: ['Zeitwert', 'Aufgeld'] }, + Zeitwert: { short: 'Zeitwert: Teil des Optionsscheinpreises über dem inneren Wert – bezahlt die Chance bis zur Fälligkeit. Schmilzt täglich.', long: 'Solange Zeit bleibt, kann sich der Kurs noch günstig entwickeln; dafür zahlst du den Zeitwert. Er sinkt mit jedem Handelstag und am schnellsten in den letzten Tagen vor der Fälligkeit (Theta). Am Fälligkeitstag ist er null.', example: 'Call kostet 1,30 €, innerer Wert 1,00 €: Zeitwert 0,30 €.', effect: 'Wer lange hält und der Kurs bewegt sich nicht, verliert den Zeitwert.', see: ['Theta', 'Innerer Wert (Optionsschein)'] }, + Aufgeld: { short: 'Aufgeld: Um so viel Prozent muss sich der Basiswert bis zur Fälligkeit bewegen, damit du ohne Verlust bleibst.', long: 'Beim Call: (Basispreis + Preis ÷ Bezugsverhältnis) ÷ Kurs − 1, beim Put entsprechend nach unten. Beim Turbo ist das Aufgeld klein (Risiko eines Kurssprungs über die Schwelle trägt der Emittent).', example: 'Aktie 142,50 €, Call 150 € kostet 0,57 € bei Bezugsverhältnis 0,1: Break-even 155,70 €, Aufgeld 9,3 %.', effect: 'Hohes Aufgeld bei kurzer Restlaufzeit ist schwer aufzuholen.', see: ['Break-even', 'Zeitwert'] }, + 'Break-even': { short: 'Break-even: Kurs des Basiswerts bei Fälligkeit, ab dem du mit dem Schein Gewinn machst.', long: 'Call: Basispreis + Preis ÷ Bezugsverhältnis. Put: Basispreis − Preis ÷ Bezugsverhältnis. Gebühren kommen hinzu.', example: 'Put 40 € für 1,20 € (Bezugsverhältnis 1): Break-even 38,80 €.', effect: 'Steht im Ticket im Klartext.', see: ['Aufgeld'] }, + Hebel: { short: 'Hebel bzw. Omega: Um wie viel Prozent sich der Schein etwa bewegt, wenn der Basiswert sich um 1 % bewegt.', long: 'Beim Optionsschein heißt die Kennzahl Omega: Delta × Kurs × Bezugsverhältnis ÷ Preis des Scheins. Beim Turbo ist der Hebel Kurs × Bezugsverhältnis ÷ Preis – je näher die Knock-out-Schwelle, desto größer.', example: 'Hebel 10: Basiswert +2 % → Schein etwa +20 %; Basiswert −2 % → etwa −20 %.', effect: 'Hebel wirkt in beide Richtungen. Kleine Kursschwankungen werden zu großen Gewinnen oder Verlusten.', see: ['Delta', 'Turbo'] }, + Delta: { short: 'Delta: Um wie viel sich der Optionsschein (je Einheit des Basiswerts) bewegt, wenn der Basiswert um 1 € steigt. Call 0 bis 1, Put −1 bis 0.', long: 'Weit im Geld liegende Scheine haben ein Delta nahe ±1 und bewegen sich fast wie der Basiswert; weit aus dem Geld liegende kaum.', example: 'Delta 0,5, Bezugsverhältnis 0,1: Aktie +1 € → Call etwa +0,05 €.', effect: 'Auch eine grobe Schätzung dafür, wie wahrscheinlich der Schein im Geld endet.', see: ['Hebel', 'Theta'] }, + Theta: { short: 'Theta: Zeitwertverlust pro Handelstag bei unverändertem Kurs (in € je Schein).', long: 'Optionsscheine verlieren jeden Tag einen Teil ihres Zeitwerts. Das Spiel zeigt, um wie viel der Schein bis zum nächsten Handelstag billiger würde, wenn sich sonst nichts ändert. Bei Turbos steht hier die tägliche Finanzierung.', example: 'Theta −0,012 €, du hast 1.000 Scheine: etwa 12 € Wertverlust je Tag.', effect: 'In den letzten Tagen vor der Fälligkeit steigt Theta stark – kurz laufende Scheine sind teure Wetten auf schnelle Bewegungen.', see: ['Zeitwert'] }, + 'Implizite Volatilität': { short: 'Implizite Volatilität: Schwankungsannahme, mit der der Emittent Optionsscheine bewertet (in % pro Jahr).', long: 'Der Emittent bewertet mit dem Black-Scholes-Modell. Die Volatilität darin mischt die zuletzt tatsächlich beobachtete Schwankung des Basiswerts (Tagesrenditen) mit seiner üblichen Schwankung. Steigt die Unruhe am Markt, werden Optionsscheine teurer.', example: 'Vola 38 %: Der Emittent rechnet damit, dass die Aktie in einem Spieljahr typischerweise etwa ±38 % schwankt.', effect: 'Nach Kursstürzen steigt die implizite Volatilität – Calls und Puts werden teurer, auch ohne dass sich der Kurs weiter bewegt.', see: ['Optionsschein'] }, + Turbo: { short: 'Turbo (Knock-out-Zertifikat): folgt dem Basiswert mit festem Hebel, ohne Laufzeitende – verfällt aber sofort, wenn die Knock-out-Schwelle berührt wird.', long: 'Ein Turbo Long ist (Kurs − Basispreis) × Bezugsverhältnis wert, ein Turbo Short (Basispreis − Kurs) × Bezugsverhältnis, jeweils plus ein kleines Aufgeld. Basispreis und Knock-out-Schwelle sind gleich. Zeitwert und Volatilität spielen kaum eine Rolle, dafür steigen die Finanzierungskosten mit der Haltedauer.', example: 'NVLT 142,50 €, Turbo Long mit Schwelle 130,75 €, Bezugsverhältnis 0,1: Preis ≈ 1,19 €, Hebel ≈ 12.', effect: 'Fällt NVLT auf 130,75 €, ist der Turbo sofort wertlos – auch wenn der Kurs danach wieder steigt.', see: ['Knock-out', 'Finanzierungskosten', 'Hebel'] }, + 'Knock-out': { short: 'Knock-out: Berührt der Basiswert die Schwelle eines Turbos, verfällt dieser sofort wertlos.', long: 'Die Schwelle gilt jederzeit, solange der Basiswert gehandelt wird – auch in Auktionen, abends und (bei WiboCoin) am Wochenende. Schon ein einzelner Umsatz auf oder jenseits der Schwelle reicht. Du bekommst eine Benachrichtigung, einen Eintrag in „Mein Tag“ und eine Meldung im Spiel.', example: 'Turbo Short WIBC mit Schwelle 439: WiboCoin springt nachts kurz auf 440 – Knock-out, der Einsatz ist weg.', effect: 'Unter 3 % Abstand warnt „Mein Tag“. Unter 0,5 % Abstand verkauft der Emittent keine Turbos mehr.', see: ['Turbo'] }, + Finanzierungskosten: { short: 'Finanzierungskosten: Der Emittent verschiebt die Knock-out-Schwelle eines Turbos täglich (Long nach oben, Short nach unten).', long: 'Mit einem Turbo leihst du dir gewissermaßen den Großteil des Geldes beim Emittenten. Dafür steigt beim Long der Basispreis jeden Handelstag um (Leitzins + 3 %) ÷ Handelstage pro Jahr; beim Short sinkt er um (3 % − Leitzins) – nie zu deinen Gunsten. So rückt die Schwelle mit der Zeit näher an den Kurs.', example: 'Leitzins 2,5 %, Schwelle 130,75 €, 84 Handelstage pro Jahr: +0,086 € pro Tag.', effect: 'Turbos eignen sich für kurze Wetten; lange Haltedauer kostet und erhöht das Knock-out-Risiko.', see: ['Turbo', 'Leitzins'] }, }; // ================================================================ Handbuch @@ -461,4 +484,16 @@ export const MANUAL = [ 'Eigene Ranglisten gibt es für Battles (Elo), Clans, Prognose-Profis (Tippspiel) und Analysten. Am Saisonende werden Ligen gewertet, alle Depots starten neu; XP und Stufe bleiben.', ], }, + { + id: 'hebel', icon: 'bolt', title: 'Hebelprodukte: Optionsscheine & Turbos', + body: [ + 'Die fiktive Wiborische Handelsbank gibt laufend Optionsscheine und Turbo-Zertifikate heraus. Du handelst sie direkt mit ihr: Sie stellt einen Geldkurs (zu dem sie kauft) und einen Briefkurs (zu dem sie verkauft), solange der Basiswert gehandelt wird – auch im Abend- und Wochenendhandel, bei WiboCoin rund um die Uhr. In Auktionen und Volatilitätsunterbrechungen ruht der Handel. Gebühren wie bei Aktien, höchstens 25.000 € je Order und 50.000 € Einsatz je Basiswert.', + 'Optionsscheine gibt es als Call (steigende Kurse) und Put (fallende Kurse) mit Laufzeiten von etwa einem Monat, einem Quartal und einem Jahr (in Handelstagen des Spielkalenders). Am Fälligkeitstag wird zum Schlusskurs bar abgerechnet: innerer Wert × Bezugsverhältnis. Verfallene Serien ersetzt der Emittent durch neue mit Basispreisen um den aktuellen Kurs.', + 'Beispielrechnung Call: NVLT steht bei 142,50 €. Call mit Basispreis 150 €, Bezugsverhältnis 0,1, Laufzeit ein Quartal, Brief 0,57 €. Break-even: 150 + 0,57 ÷ 0,1 = 155,70 € (Aufgeld 9,3 %). Du kaufst 1.000 Stück für 570 € plus 1,19 € Gebühr. Schließt NVLT am Fälligkeitstag bei 165 €, bekommst du (165 − 150) × 0,1 = 1,50 € je Schein, also 1.500 € (+163 %). Schließt NVLT bei 150 € oder darunter, verfällt der Schein wertlos – Totalverlust von 571,19 €. Steigt NVLT nur langsam auf 152 €, bekommst du 0,20 € je Schein und verlierst trotz steigender Aktie 65 %.', + 'Kennzahlen im Ticket: Omega (Hebel) – so viele Prozent bewegt sich der Schein bei 1 % Kursbewegung; Delta – Preisänderung je 1 € Kursänderung; Aufgeld und Break-even; Theta – Wertverlust pro Handelstag; implizite Volatilität – Schwankungsannahme des Emittenten (Black-Scholes mit Leitzins und erwarteten Dividenden).', + 'Turbos (Knock-out-Zertifikate) haben keine Laufzeit. Ein Turbo Long ist (Kurs − Basispreis) × Bezugsverhältnis wert, ein Turbo Short umgekehrt, plus ein kleines Aufgeld. Beispielrechnung Turbo: Turbo Long NVLT mit Schwelle 130,75 €, Bezugsverhältnis 0,1, Preis ≈ 1,19 €, Hebel ≈ 12. Steigt NVLT um 2 % auf 145,35 €, ist der Turbo etwa 1,46 € wert (+23 %). Berührt NVLT 130,75 € – auch nur mit einem einzigen Umsatz –, verfällt der Turbo sofort wertlos. Jeden Handelstag steigt die Schwelle um die Finanzierungskosten: bei 2,5 % Leitzins und 3 % Aufschlag etwa 130,75 × 5,5 % ÷ 84 ≈ 0,09 €.', + 'Im Depot stehen Hebelprodukte in einer eigenen Gruppe mit Wert (zum Geldkurs), G/V, Hebel und Abstand zum Knock-out bzw. Fälligkeit. Sie zählen zum Depotwert und zur Rangliste, belasten aber keine Margin. Leerverkäufe von Scheinen gibt es nicht – du kannst höchstens deinen Einsatz verlieren. Am Saisonende wird alles zum Geldkurs ausgebucht. In Battles sind Hebelprodukte erlaubt (im Modus „Nur Long“ nur Call und Turbo Long, bei „3 Aktien“ nur auf die gezogenen Werte), im Clan-Fonds nicht: Dort verwaltet einer das Geld vieler, ein Totalverlust träfe alle.', + 'Mein Tag warnt, wenn ein Turbo weniger als 3 % von der Schwelle entfernt ist und wenn eigene Optionsscheine heute oder morgen fällig werden; die Fälligkeiten stehen auch im Kalender. Im Einsteiger-Modus zeigt der Reiter die Produkte erst nach einem Risikohinweis; vor dem ersten Kauf musst du den Hinweis bestätigen: Totalverlust möglich, Zeitwert schmilzt täglich, Knock-out kann jederzeit eintreten.', + ], + }, ]; diff --git a/server/public/js/info.js b/server/public/js/info.js index 8206937..ba35b4e 100644 --- a/server/public/js/info.js +++ b/server/public/js/info.js @@ -14,6 +14,7 @@ const KIND = { bill: ['parliament', 'Parlament'], law: ['doc', 'Gesetz'], auction: ['bell', 'Auktion'], season: ['flag', 'Saison'], corporate: ['handshake', 'Unternehmen'], election: ['ballot', 'Wahl'], agm: ['ballot', 'Hauptversammlung'], ipo: ['rocket', 'Börsengang'], rating: ['scales', 'Rating'], + expiry: ['hourglass', 'Fälligkeit Optionsschein'], }; let newsTab = 'news'; diff --git a/server/public/js/net.js b/server/public/js/net.js index 0602e1a..5d547f1 100644 --- a/server/public/js/net.js +++ b/server/public/js/net.js @@ -94,7 +94,7 @@ export function connect() { if (m.ok) p.resolve(m); else { if (m.humanCheck) emit('humanCheck', { nonce: m.humanCheck }); - p.reject(new Error(m.error || 'Fehler')); + p.reject(Object.assign(new Error(m.error || 'Fehler'), m.needAck ? { needAck: true } : {})); } return; } @@ -133,13 +133,13 @@ document.addEventListener('visibilitychange', () => { if (document.visibilitySta let humanInputs = 0; for (const t of ['pointerdown', 'keydown', 'touchstart']) addEventListener(t, (e) => { if (e.isTrusted) humanInputs++; }, { capture: true, passive: true }); const WATCHED = new Set(['order', 'cancel', 'cancelAll', 'tender', 'ipoSubscribe', 'agmVote', 'predictTip', 'vote', 'electionVote', - 'challenge', 'respond', 'rematch', 'queue', 'alertAdd', 'analysisPost', 'analysisLike', 'comment', 'follow', 'lobby']); + 'challenge', 'respond', 'rematch', 'queue', 'alertAdd', 'analysisPost', 'analysisLike', 'comment', 'follow', 'lobby', 'derivOrder']); // Reine Abfragen (wie READ_ONLY am Server) und Verbindungsverwaltung: binden sich nicht an Buttons const READS = new Set(['portfolio', 'journal', 'company', 'curve', 'candles', 'calendar', 'briefing', 'leaderboard', 'regulator', 'parliament', 'government', 'battles', 'liveBattles', 'quests', 'league', 'inbox', 'profile', 'friends', 'comments', 'clans', 'clan', - 'tournaments', 'me', 'ipoList', 'agmList', 'predictList', 'plan', 'analyses', 'population', 'todo', 'auth', 'logout', 'subscribe', 'humanCheck', 'clientEnv', 'ping']); -const ORDERISH = new Set(['order', 'cancel', 'cancelAll']); + 'tournaments', 'me', 'ipoList', 'agmList', 'predictList', 'plan', 'analyses', 'population', 'todo', 'derivs', 'derivQuote', 'auth', 'logout', 'subscribe', 'humanCheck', 'clientEnv', 'ping']); +const ORDERISH = new Set(['order', 'cancel', 'cancelAll', 'derivOrder']); /** * @param {string} type @param {object} [data] @param {{feedback?: boolean}} [opt] feedback: false → keine Button-Rückmeldung @@ -157,7 +157,7 @@ export function request(type, data = {}, opt = {}) { } const reqId = reqSeq++; const timer = setTimeout(() => { pending.delete(reqId); fb?.done(false); logTrail(label, false, 'Zeitüberschreitung', meta); reject(new Error('Zeitüberschreitung – bitte erneut versuchen')); }, 15_000); - const quiet = /^(company|calendar|briefing|.*List|plan|analyses|comments|book|candles|history|subscribe|ping|profile|leaderboard)$/.test(type); + const quiet = /^(company|calendar|briefing|.*List|plan|analyses|comments|book|candles|history|subscribe|ping|profile|leaderboard|derivs|derivQuote)$/.test(type); pending.set(reqId, { resolve: (v) => { fb?.done(true); if (!quiet) logTrail(label, true, '', meta); resolve(v); }, reject: (e) => { fb?.done(false); logTrail(label, false, e.message, meta); reject(e); }, diff --git a/server/public/js/today.js b/server/public/js/today.js index 6524f66..b7597a0 100644 --- a/server/public/js/today.js +++ b/server/public/js/today.js @@ -7,6 +7,7 @@ import { request, on } from './net.js'; import { toast } from './ui.js'; import { esc, $, $$, int, chg, countdown, now, when, patch } from './util.js'; import { selectSymbol } from './trade.js'; +import { openDerivTicket } from './derivs.js'; import { setPolTab } from './politics.js'; import { showRecap } from './progress.js'; import { icon } from './icons.js'; @@ -187,6 +188,7 @@ function openTarget(it) { if (t.symbol) { selectSymbol(t.symbol, { go: true }); if (t.stab) setTimeout(() => document.querySelector(`#sTabs [data-stab="${CSS.escape(t.stab)}"]`)?.click(), 0); + if (t.deriv) setTimeout(() => openDerivTicket(t.deriv), 60); } else if (t.view) { if (t.view === 'parlament' && t.tab) setPolTab(t.tab); go(t.view, t.tab ? { tab: t.tab } : {}); diff --git a/server/public/js/trade.js b/server/public/js/trade.js index d7fa7c5..2f9afa7 100644 --- a/server/public/js/trade.js +++ b/server/public/js/trade.js @@ -11,6 +11,7 @@ import { firstTime } from './help.js'; import { addPending, settlePending, pendingFor, pendingBadge } from './pending.js'; import { playConfirm } from './sound.js'; import { creditHtml, corpBondHtml, ratingBadge } from './credit.js'; +import { renderDerivTab } from './derivs.js'; const ORDER_TYPES = { limit: { label: 'Limit', simple: true }, @@ -403,6 +404,7 @@ function renderStabs() { const c = S.company; if (stab === 'comments') { renderAnalyses(el); return; } el._commentsTarget = null; el._anaSym = null; + if (stab === 'derivs') { renderDerivTab(el); return; } if (!c || c.symbol !== S.symbol) { patch(el, '

Lade Daten …

'); return; } if (stab === 'company') { if (c.kind && c.kind !== 'stock') { patch(el, causesHtml(c) + instrumentHtml(c)); paint($('#instCurve'), curveChart(c.curve)); paintGas(c.gas); } @@ -1353,7 +1355,7 @@ export function initTrade(nav) { const b = e.target.closest('[data-stab]'); if (!b) return; stab = b.dataset.stab; - if (stab !== 'comments' && !S.company) loadCompany(); + if (stab !== 'comments' && stab !== 'derivs' && !S.company) loadCompany(); renderStabs(); }); $('#sTabs').addEventListener('keydown', (e) => { diff --git a/server/public/style.css b/server/public/style.css index ea1179e..7e1bdc5 100644 --- a/server/public/style.css +++ b/server/public/style.css @@ -1430,3 +1430,45 @@ ul.events .ic { flex: none; } /* Hauptnavigation am Desktop bleibt beim Scrollen unter dem Kopf stehen; --top-h = Kopf + Navigation (gemessen in app.js) */ body:not(.admin) .mainnav { position: sticky; top: var(--hdr-h, 56px); z-index: 29; } + +/* ---------------------------------------------------------------- Hebelprodukte (Optionsscheine, Turbos) */ +.d-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin-bottom: 8px; } +.d-u { margin: 0; } +.d-filters { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin: 0 0 8px; } +.d-filters .seg { margin: 0; } +.d-f { display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--muted); } +.d-f select { padding: 3px 6px; min-height: 28px; } +.d-table { width: 100%; } +.d-table td { vertical-align: top; } +.d-table tr.d-held td { background: color-mix(in srgb, var(--up) 6%, transparent); } +.th-sort { background: none; border: 0; padding: 0; color: inherit; font: inherit; font-weight: 600; cursor: pointer; white-space: nowrap; } +.th-sort:hover { color: var(--text); } +.d-open { text-align: left; white-space: nowrap; } +.d-k { display: inline-block; font-size: 11px; font-weight: 700; padding: 0 6px; border-radius: 6px; line-height: 1.6; } +.d-k.d-call, .d-k.d-long { background: color-mix(in srgb, var(--up) 16%, transparent); color: var(--up); } +.d-k.d-put, .d-k.d-short { background: color-mix(in srgb, var(--down) 16%, transparent); color: var(--down-soft); } +.d-theta { color: var(--muted); } +.d-explain { margin: 10px 0 4px; } +.d-warn .btn-row { margin-top: 8px; } +.modal.d-modal { width: min(560px, 100%); } +.d-sub { margin: -6px 0 10px; } +.d-quote { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; margin: 0 0 10px; } +.d-quote > div { background: var(--panel2); border: 1px solid var(--line); border-radius: 8px; padding: 6px 8px; min-width: 0; } +.d-quote small { display: block; color: var(--muted); font-size: 11px; } +.d-quote b { font-size: 15px; } +.d-kpis { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 4px 12px; margin: 0 0 10px; font-size: 13px; } +.d-kpis > div { display: flex; justify-content: space-between; gap: 6px; border-bottom: 1px dashed var(--line); padding: 2px 0; min-width: 0; } +.d-kpis dt { color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.d-kpis dd { margin: 0; white-space: nowrap; } +.d-ticket .seg.mini { margin-bottom: 8px; } +.d-ticket .btn-row { display: flex; gap: 4px; flex-wrap: wrap; } +.lbl-s { display: block; color: var(--muted); font-size: 12px; margin-bottom: 3px; } +.klar-say { margin: 6px 0 0; min-height: 2.8em; line-height: 1.4; } +.d-risk { margin: 6px 0 8px; color: var(--down-soft); } +.d-ack { color: var(--down-soft); } +.d-depot td { vertical-align: top; } +@media (max-width: 760px) { + .d-quote { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .d-kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .d-filters .seg { overflow-x: auto; max-width: 100%; } +} diff --git a/server/src/achievements.js b/server/src/achievements.js index fcf7e65..0cdf8c2 100644 --- a/server/src/achievements.js +++ b/server/src/achievements.js @@ -24,6 +24,9 @@ export const ACHIEVEMENTS = { networker: { icon: 'handshake', title: 'Netzwerker', desc: 'Ein eingeladener Freund hat seinen ersten Handel gemacht' }, networker_3: { icon: 'network', title: 'Netzwerker II', desc: 'Drei eingeladene Freunde handeln aktiv' }, networker_10: { icon: 'globe', title: 'Netzwerker III', desc: 'Zehn eingeladene Freunde handeln aktiv' }, + lever_first: { icon: 'bolt', title: 'Hebel angesetzt', desc: 'Kaufe dein erstes Hebelprodukt (Optionsschein oder Turbo)' }, + lever_double: { icon: 'chart-up', title: 'Verdoppelt', desc: 'Verkaufe ein Hebelprodukt zum doppelten Einstandskurs oder mehr' }, + lever_ko: { icon: 'flame', title: 'Ausgeknockt', desc: 'Erlebe einen Knock-out – Hebel wirkt in beide Richtungen' }, }; import { SECTOR_OF } from './world.js'; diff --git a/server/src/botguard.js b/server/src/botguard.js index fca9077..166c028 100644 --- a/server/src/botguard.js +++ b/server/src/botguard.js @@ -30,7 +30,7 @@ export const BOT_ACTIONS = { melden: 'Nur melden', pruefen: 'Menschen-Bestätigu const SCRIPT_UA = /python|curl|wget|httpie|postman|insomnia|axios|node-fetch|undici|got\/|go-http|okhttp|java\/|libwww|scrapy|aiohttp|requests|headless|phantom|selenium|puppeteer|playwright|webdriver|bot\b|spider|crawler/i; /** Befehle, an denen Automatisierung gemessen wird (Handel und spielrelevante Klicks) */ export const WATCHED = new Set(['order', 'cancel', 'cancelAll', 'tender', 'ipoSubscribe', 'agmVote', 'predictTip', 'vote', 'electionVote', - 'challenge', 'respond', 'rematch', 'queue', 'alertAdd', 'analysisPost', 'analysisLike', 'comment', 'follow', 'lobby']); + 'challenge', 'respond', 'rematch', 'queue', 'alertAdd', 'analysisPost', 'analysisLike', 'comment', 'follow', 'lobby', 'derivOrder']); const HALF_LIFE_MS = 24 * 3_600_000; const HOUR = 3_600_000; diff --git a/server/src/changelog.js b/server/src/changelog.js index 0c52ea5..5f6819c 100644 --- a/server/src/changelog.js +++ b/server/src/changelog.js @@ -2,6 +2,17 @@ // Beim Veröffentlichen einer neuen Version: Eintrag oben ergänzen und package.json-Version anheben. // type: neu | besser | fix export const CHANGELOG = [ + { + version: '0.24.0', date: '2026-12-04', title: 'Hebelprodukte: Optionsscheine und Turbos', + items: [ + { type: 'neu', text: 'Neuer Reiter „Hebelprodukte“ auf der Wertpapierseite: Optionsscheine (Call/Put) und Turbo-Zertifikate (Long/Short) der (erfundenen) Wiborischen Handelsbank – auf liquide Aktien, den WIBO-10, Gold, Öl, Gas und WiboCoin. Du handelst direkt mit der Bank zu Geld- und Briefkurs.' }, + { type: 'neu', text: 'Optionsscheine mit Laufzeiten von einem Monat, einem Quartal und einem Jahr, fair bewertet nach Volatilität, Zins und Dividende. Das Ticket zeigt Hebel, Delta, Aufgeld, Break-even, Zeitwertverlust je Tag und erklärt im Klartext, ab wann du verdienst. Am Fälligkeitstag wird automatisch abgerechnet.' }, + { type: 'neu', text: 'Turbos ohne Laufzeitende mit Hebel 2 bis 20 und Knock-out-Schwelle: Berührt der Basiswert die Schwelle, ist der Turbo sofort wertlos – du bekommst sofort eine Meldung.' }, + { type: 'neu', text: 'Eigene Gruppe im Depot mit Hebel und Abstand zum Knock-out bzw. Restlaufzeit; „Mein Tag“ und Kalender warnen vor Fälligkeiten und nahem Knock-out. Drei neue Erfolge.' }, + { type: 'neu', text: 'Sicherheitsnetz: Im Einsteiger-Modus ausgeblendet, vor dem ersten Kauf musst du das Risiko bestätigen. Grenzen je Order und je Basiswert; im Clan-Fonds nicht erlaubt; zum Saisonende wird alles zum Geldkurs ausgebucht.' }, + { type: 'besser', text: 'Handbuch-Kapitel „Hebelprodukte“ mit Rechenbeispielen und 16 neuen Begriffen.' }, + ], + }, { version: '0.23.1', date: '2026-12-04', title: 'Navigation bleibt sichtbar', items: [ diff --git a/server/src/derivatives.js b/server/src/derivatives.js new file mode 100644 index 0000000..9bf2475 --- /dev/null +++ b/server/src/derivatives.js @@ -0,0 +1,719 @@ +// Hebelprodukte: Optionsscheine (Call/Put) und Turbo-Zertifikate mit Knock-out eines fiktiven Emittenten. +// +// Gehandelt wird nur mit dem Emittenten (kein Orderbuch zwischen Spielern, ähnlich dem Abendhandel mit dem Market Maker): +// Er stellt laufend Geld- und Briefkurse, solange der Basiswert gehandelt wird. Der Emittent sichert sich nicht ab – +// Käufe und Verkäufe von Scheinen bewegen den Basiswert nicht. +// +// – Optionsscheine: europäisch, Barausgleich (innerer Wert × Bezugsverhältnis) zum Schlusskurs am Fälligkeitstag. +// Preis nach Black-Scholes mit Leitzins, erwarteten Dividenden (bis zur Fälligkeit, vom Kurs abgezogen) und einer +// Volatilität aus realisierter Schwankung und Grundvolatilität des Basiswerts. Nie unter dem inneren Wert. +// Laufzeiten in Handelstagen des Spielkalenders (1M/1Q/1J nach daysPerYear), rollierend neu aufgelegt. +// – Turbos: open end, Basispreis = Knock-out-Schwelle, täglich um Finanzierungskosten angepasst. Berührt der +// Basiswert die Schwelle, verfällt der Turbo sofort wertlos (Benachrichtigung, „Mein Tag“, Toast). +// +// Bewertung im Depot zum Geldkurs. Hebelprodukte belasten keine Margin (Verlust höchstens der Einsatz) und dienen +// auch nicht als Sicherheit für Leerverkäufe. +import { applyFill } from './accounts.js'; +import { INDEX_SYMBOLS, COMPANIES } from './world.js'; +import { registerTodo } from './todo.js'; +import { clamp, fmt, normCdf } from './util.js'; + +export const ISSUER = 'Wiborische Handelsbank'; +export const IDX = 'WIBO10'; +export const KIND_LABEL = { call: 'Call', put: 'Put', long: 'Turbo Long', short: 'Turbo Short' }; +const INDEX_LIST = [...INDEX_SYMBOLS]; +/** Optionsscheine: die zehn Indexwerte (die liquidesten Aktien), der Index, Gold und Öl */ +export const WARRANT_UNDERLYINGS = [...INDEX_LIST, IDX, 'GOLD', 'OEL']; +/** Turbos zusätzlich auf Erdgas und WiboCoin */ +export const TURBO_UNDERLYINGS = [IDX, 'GOLD', 'OEL', 'GAS', 'WIBC', ...INDEX_LIST]; +const LEVERAGES = [2, 3, 5, 8, 12, 20]; // Ziel-Hebel der Turbos (Abstand zur Schwelle = 1/Hebel) +const STRIKE_SD = [-1, -0.5, 0, 0.5, 1]; // Basispreise in Standardabweichungen bis zur Fälligkeit +const MAX_STRIKES = 11; // je Serie (Basiswert + Fälligkeit) +const MAX_TURBOS = 14; // je Basiswert und Richtung +export const DERIV = { + tick: 0.001, // kleinste Preiseinheit + maxOrder: 25_000, // höchstens € je Order + maxQty: 1_000_000, // Stück je Order + maxPerUnderlying: 50_000, // Einsatz je Basiswert und Depot (Einstand) + perMinute: 20, // Orders je Minute und Spieler + perDay: 300, // Orders je Handelstag und Spieler + finSpread: 0.03, // Finanzierungsaufschlag der Turbos p. a. + turboPremium: 0.001, // Aufgeld der Turbos (Anteil des Basiswerts) + minKoDist: 0.005, // so nah an der Schwelle stellt der Emittent keinen Briefkurs mehr + koNear: 0.03, // „Mein Tag“: Knock-out-Nähe +}; +export const RISK_TEXT = 'Totalverlust möglich, Zeitwert schmilzt täglich, Knock-out kann jederzeit eintreten.'; + +const r3 = (x) => Math.round(x * 1000) / 1000; +const floor3 = (x) => Math.floor(x * 1000 + 1e-7) / 1000; +const ceil3 = (x) => Math.ceil(x * 1000 - 1e-7) / 1000; +const r4 = (x) => Math.round(x * 1e4) / 1e4; +const isWarrant = (k) => k === 'call' || k === 'put'; + +/** „Runde“ Schrittweite (1, 2, 2,5, 5 × 10^n) höchstens x */ +export function niceStep(x) { + const e = 10 ** Math.floor(Math.log10(Math.max(1e-9, x))); + for (const m of [5, 2.5, 2, 1]) if (m * e <= x) return m * e; + return e; +} +/** Bezugsverhältnis so, dass Basiswert × Verhältnis etwa 3–30 € ergibt (Index: 0,01) */ +export const ratioFor = (spot) => (spot >= 2000 ? 10 ** (2 - Math.floor(Math.log10(spot))) : 10 ** (1 - Math.round(Math.log10(Math.max(0.01, spot))))); + +/** + * Black-Scholes (europäisch) mit diskreten Dividenden: S wird um den Barwert der Dividenden bis zur Fälligkeit (div) + * gekürzt. T in Jahren, r und sigma als Anteil p. a. Liefert Preis und Delta je Einheit des Basiswerts. + */ +export function blackScholes({ type, S, K, T, r, sigma, div = 0 }) { + const Sx = Math.max(1e-9, S - div); + const call = type === 'call'; + if (!(T > 1e-9) || !(sigma > 1e-9)) { + const v = call ? Math.max(0, Sx - K) : Math.max(0, K - Sx); + return { price: v, delta: call ? (Sx > K ? 1 : 0) : (Sx < K ? -1 : 0) }; + } + const sq = sigma * Math.sqrt(T); + const d1 = (Math.log(Sx / K) + (r + 0.5 * sigma * sigma) * T) / sq; + const d2 = d1 - sq; + const df = Math.exp(-r * T); + if (call) return { price: Sx * normCdf(d1) - K * df * normCdf(d2), delta: normCdf(d1) }; + return { price: K * df * normCdf(-d2) - Sx * normCdf(-d1), delta: normCdf(d1) - 1 }; +} + +/** + * Untergrenze je Einheit: nie unter dem inneren Wert. Beim Put zusätzlich nicht unter K − (S − Dividenden): Im Spiel + * bringt Bargeld keine Zinsen – sonst ergäbe „Aktie + Put kaufen, Dividende kassieren“ einen sicheren Gewinn. + */ +export function floorValue(type, S, K, div = 0) { + return type === 'call' ? Math.max(0, S - K) : Math.max(0, K - S + Math.max(0, div)); +} + +/** + * Spanne (Brief − Geld) relativ zum Mittelkurs: breiter, je weiter aus dem Geld und je näher die Fälligkeit (1–15 %). + * otmSd: Abstand aus dem Geld in Standardabweichungen bis zur Fälligkeit · daysLeft: Handelstage bis zur Fälligkeit + */ +export function warrantSpread(otmSd, daysLeft) { + const near = clamp(1 - daysLeft / 3, 0, 1); + return clamp(0.01 + 0.035 * clamp(otmSd, 0, 2) + 0.05 * near, 0.01, 0.15); +} +/** Turbos: 1 % Grundspanne, bis 6 % kurz vor der Schwelle */ +export const turboSpread = (dist) => clamp(0.01 + 0.05 * clamp(1 - dist / 0.05, 0, 1), 0.01, 0.15); + +/** Geld/Brief aus Mittelkurs und relativer Spanne (Mindest-Geld 0,001 €; wertlos: Geld 0, Brief nicht) */ +export function quotePair(mid, spread, floor = 0) { + if (!(mid >= DERIV.tick)) return { bid: 0, ask: Math.max(DERIV.tick, ceil3(Math.max(mid, floor) * (1 + spread / 2))) }; + const bid = Math.max(DERIV.tick, floor3(mid * (1 - spread / 2))); + const ask = Math.max(bid + DERIV.tick, ceil3(mid * (1 + spread / 2)), ceil3(floor)); + return { bid: r3(bid), ask: r3(ask) }; +} + +export class Derivs { + constructor(g, saved) { + this.g = g; + this.products = new Map((saved?.products ?? []).map((x) => [x.id, x])); + this.seq = saved?.seq ?? 0; + this.vol = saved?.vol ?? {}; // Basiswert → { v: Varianz p. a. (EWMA), last: letzter Schluss } + this.lastFin = saved?.lastFin ?? null; // Spieltag der letzten Finanzierungsanpassung + this.lastKoTs = 0; + this.rate = new Map(); // Spieler → Zeitstempel der letzten Orders (Massenhandel) + } + get cfg() { return this.g.cfg; } + snapshot() { + return { products: [...this.products.values()], seq: this.seq, vol: this.vol, lastFin: this.lastFin }; + } + + // ================================================================ Basiswerte + uName(u) { return u === IDX ? 'WIBO-10' : u; } + uLabel(u) { return u === IDX ? 'WIBO-10' : this.g.stocks.get(u)?.name ?? u; } + /** Aktueller Kurs des Basiswerts (Index: berechneter Stand) */ + spot(u) { + if (u === IDX) return this.g.index().value; + return this.g.stocks.get(u)?.last ?? NaN; + } + /** Schlusskurs für den Barausgleich */ + closeOf(u) { + if (u === IDX) return this.g.index().value; // nach der Schlussauktion: Stand aus den Schlusskursen + const s = this.g.stocks.get(u); + return s?.close ?? s?.last ?? NaN; + } + #baseVol(u) { + const g = this.g; + if (u === IDX) { + const m = INDEX_LIST.map((x) => g.stocks.get(x)).filter(Boolean); + return 0.6 * (m.reduce((a, s) => a + g.econ.volNow(s), 0) / Math.max(1, m.length)); + } + const s = g.stocks.get(u); + return s ? g.econ.volNow(s) : 0.3; + } + /** Volatilität für die Bewertung: Mischung aus realisierter (EWMA der Tagesrenditen) und Grundvolatilität */ + sigma(u) { + const base = this.#baseVol(u); + const v = this.vol[u]?.v; + const mix = Number.isFinite(v) && v > 0 ? Math.sqrt(0.5 * v + 0.5 * base * base) : base; + return clamp(mix, 0.08, 1.6); + } + r() { return clamp((this.g.macro?.rate ?? 3) / 100, -0.02, 0.2); } + /** Erwartete Dividenden je Einheit des Basiswerts in den nächsten `days` Handelstagen */ + divUntil(u, days) { + const g = this.g; + const one = (s) => { + const f = s?.fund; + if (!f || days <= 0) return 0; + const qd = Math.max(1, this.cfg.quarterDays); + const pend = f.exDivDay && f.exDivDay > g.day && f.exDivDay <= g.day + days && f.pendingDividend > 0 ? f.pendingDividend : 0; + const rest = Math.max(0, days / qd - (pend ? 1 : 0)) * Math.max(0, f.lastDividend ?? 0); + return pend + rest; + }; + if (u === IDX) { + const base = COMPANIES.filter((c) => INDEX_SYMBOLS.has(c.symbol)).reduce((a, c) => a + c.price * c.shares, 0); + let d = 0; + for (const x of INDEX_LIST) { const s = g.stocks.get(x); if (s) d += one(s) * s.baseShares; } + return (d / base) * 10_000; + } + const s = g.stocks.get(u); + return s?.kind === 'stock' ? one(s) : 0; + } + /** Status des Basiswerts: null = handelbar, sonst Grund */ + closedReason(u) { + const g = this.g; + if (u === IDX) { + if (g.afterHours()) return null; + if (g.market.phase !== 'continuous') return 'Der WIBO-10 wird gerade nicht fortlaufend berechnet (Auktion oder Börse geschlossen)'; + if (INDEX_LIST.some((x) => g.stocks.get(x)?.volaEndsAt)) return 'Volatilitätsunterbrechung in einem Indexwert – der Emittent stellt keine Kurse'; + return null; + } + const s = g.stocks.get(u); + if (!s) return 'Basiswert unbekannt'; + const st = g.ex.status(s); + if (st === 'continuous') return null; + if (st === 'closed' && !s.allDay && g.ex.eveningQuote(s)) return null; // Abend-/Wochenendhandel + return st === 'vola' ? 'Volatilitätsunterbrechung im Basiswert – der Emittent stellt keine Kurse' + : st === 'call' ? 'Im Basiswert läuft eine Auktion – Handel mit Hebelprodukten ruht' : 'Der Basiswert wird gerade nicht gehandelt'; + } + + // ================================================================ Zeit + /** Anteil des laufenden Handelstags, der noch vor der Schlussauktion liegt (1 vor Eröffnung, 0 nach Schluss) */ + #todayLeft() { + const g = this.g; + const ph = g.market.phase; + if (ph === 'preopen' || ph === 'opening') return 1; + if (ph !== 'continuous') return 0; + const st = g.phaseInfo ?? g.clock.state(); + const len = st.closeAt - st.openAt; + return len > 0 ? clamp((st.closeAt - g.clock.now()) / len, 0, 1) : 0; + } + /** Restlaufzeit in Handelstagen (mit Bruchteil des laufenden Tags) */ + daysLeft(p) { return isWarrant(p.kind) ? Math.max(0, p.expDay - this.g.day) + this.#todayLeft() : null; } + /** Datum (Beginn) des Fälligkeitstags */ + expTs(p) { + const g = this.g, now = g.clock.now(); + const st = g.phaseInfo ?? g.clock.state(now); + const off = g.market.phase === 'closed' && g.market.date && st.date !== g.market.date ? 1 : 0; + return g.clock.tradingDayStart(Math.max(0, p.expDay - g.day - off), now); + } + + // ================================================================ Bewertung + /** + * Kurse und Kennzahlen eines Produkts. spot/days überschreibbar (Tests, Theta). + * @returns {{bid:number, ask:number, mid:number, spread:number, spot:number, intrinsic:number, lev:number|null, omega?:number, delta:number, + * theta?:number, premiumPct?:number, breakEven?:number, sigma?:number, daysLeft?:number, dist?:number}} + */ + quote(p, { spot = this.spot(p.u), days = this.daysLeft(p), sigma = this.sigma(p.u), r = this.r() } = {}) { + if (p.status !== 'active') return { bid: 0, ask: 0, mid: 0, spread: 0, spot, intrinsic: 0, lev: null, delta: 0, value: p.settle ?? 0 }; + const k = p.ratio; + if (isWarrant(p.kind)) { + const T = days / Math.max(1, this.cfg.daysPerYear); + const div = this.divUntil(p.u, days); + const bs = blackScholes({ type: p.kind, S: spot, K: p.strike, T, r, sigma, div }); + const floor = floorValue(p.kind, spot, p.strike, div); + const unit = Math.max(bs.price, floor); + const mid = unit * k; + const intrinsic = Math.max(0, p.kind === 'call' ? spot - p.strike : p.strike - spot) * k; + const sdT = Math.max(0.03, sigma * Math.sqrt(Math.max(T, 1e-6))); + const otm = Math.max(0, p.kind === 'call' ? Math.log(p.strike / Math.max(1e-9, spot - div)) : Math.log(Math.max(1e-9, spot - div) / p.strike)); + const spread = warrantSpread(otm / sdT, days); + const q = quotePair(mid, spread, floor * k); + // Zeitwertverlust: Wert morgen bei gleichem Kurs + const T1 = Math.max(0, days - 1) / Math.max(1, this.cfg.daysPerYear); + const div1 = this.divUntil(p.u, Math.max(0, days - 1)); + const next = Math.max(blackScholes({ type: p.kind, S: spot, K: p.strike, T: T1, r, sigma, div: div1 }).price, floorValue(p.kind, spot, p.strike, div1)) * k; + const delta = unit > floor + 1e-12 || floor === 0 ? bs.delta : (p.kind === 'call' ? 1 : -1); + const ref = q.ask || mid; + const omega = ref > 0 ? Math.abs(delta) * spot * k / ref : null; + const breakEven = p.kind === 'call' ? p.strike + q.ask / k : p.strike - q.ask / k; + const premiumPct = (p.kind === 'call' ? breakEven / spot - 1 : 1 - breakEven / spot) * 100; + return { bid: q.bid, ask: q.ask, mid, spread, spot, intrinsic, lev: omega, omega, delta, theta: next - mid, premiumPct, breakEven, sigma, daysLeft: days, div }; + } + const long = p.kind === 'long'; + const inner = (long ? spot - p.strike : p.strike - spot); + const dist = inner / spot; + if (inner <= 0) return { bid: 0, ask: 0, mid: 0, spread: 0, spot, intrinsic: 0, lev: null, delta: 0, dist: 0, ko: true }; + const mid = (inner + DERIV.turboPremium * spot) * k; + const spread = turboSpread(dist); + const q = quotePair(mid, spread, inner * k); + const lev = q.ask > 0 ? spot * k / q.ask : null; + const fin = this.finRate(p.kind); + return { + bid: q.bid, ask: q.ask, mid, spread, spot, intrinsic: inner * k, lev, delta: long ? 1 : -1, dist, ko: false, + theta: -(Math.abs(fin) * p.strike * k) / Math.max(1, this.cfg.daysPerYear), premiumPct: (DERIV.turboPremium * spot * k) / Math.max(1e-9, q.ask) * 100, + breakEven: long ? p.strike + q.ask / k : p.strike - q.ask / k, + }; + } + /** Finanzierungssatz p. a. für die tägliche Anpassung des Basispreises (Long: steigt, Short: sinkt – nie zugunsten des Inhabers) */ + finRate(kind) { return kind === 'long' ? Math.max(0, this.r() + DERIV.finSpread) : Math.min(0, this.r() - DERIV.finSpread); } + + name(p) { + const strike = p.strike >= 1000 ? fmt(p.strike).replace(/,00$/, '') : fmt(p.strike); + return `${KIND_LABEL[p.kind]} ${this.uName(p.u)} ${strike}`; + } + + /** Öffentliche Ansicht eines Produkts mit Kursen */ + view(p, q = this.quote(p)) { + const w = isWarrant(p.kind); + return { + id: p.id, name: this.name(p), kind: p.kind, u: p.u, uName: this.uName(p.u), strike: p.strike, ratio: p.ratio, status: p.status, + tenor: p.tenor ?? null, expDay: p.expDay ?? null, daysLeft: w ? q.daysLeft ?? this.daysLeft(p) : null, expTs: w ? this.expTs(p) : null, + ko: w ? null : p.strike, dist: w ? null : q.dist ?? null, + bid: q.bid, ask: q.ask, spread: q.spread, spot: q.spot, intrinsic: q.intrinsic, lev: q.lev, delta: q.delta, theta: q.theta ?? null, + premiumPct: q.premiumPct ?? null, breakEven: q.breakEven ?? null, sigma: q.sigma ?? null, issuedDay: p.issuedDay, + settle: p.settle ?? null, endedAt: p.endedAt ?? null, + }; + } + + // ================================================================ Emission (rollierend) + #newId() { this.seq += 1; return `WH${this.seq.toString(36).toUpperCase().padStart(4, '0')}`; } + #add(p) { this.products.set(p.id, p); this.g.metaDirty = true; return p; } + + tenors() { + const y = Math.max(8, this.cfg.daysPerYear); + return [{ key: '1M', d: Math.max(2, Math.round(y / 12)) }, { key: '1Q', d: Math.max(4, Math.round(y / 4)) }, { key: '1J', d: y }]; + } + + /** Fehlende Serien und Turbos auflegen (beim Laden, zu Handelsbeginn und regelmäßig) */ + issue({ warrants = true, turbos = true } = {}) { + const g = this.g; + const active = [...this.products.values()].filter((p) => p.status === 'active'); + if (warrants) { + for (const u of WARRANT_UNDERLYINGS) { + const S = this.spot(u); + if (!(S > 0)) continue; + const sigma = this.sigma(u); + for (const t of this.tenors()) { + const series = active.filter((p) => p.u === u && p.tenor === t.key && isWarrant(p.kind)); + const maxExp = Math.max(-1, ...series.map((p) => p.expDay)); + let expDay = maxExp; + if (!series.length || maxExp - g.day < t.d / 2) expDay = g.day + t.d; + // Basispreise um den aktuellen Kurs (fehlt ein Basispreis am Geld, wird nachgelegt) + const T = Math.max(1, expDay - g.day) / Math.max(1, this.cfg.daysPerYear); + const sd = Math.max(0.03, sigma * Math.sqrt(T)); + const step = niceStep(S * 0.02); + const have = series.filter((p) => p.expDay === expDay); + const nearAtm = have.some((p) => Math.abs(Math.log(p.strike / S)) < 0.3 * sd); + if (have.length && nearAtm) continue; + const strikes = new Set(have.map((p) => p.strike)); + let n = new Set(have.map((p) => p.strike)).size; + for (const z of STRIKE_SD) { + const K = Math.round((S * Math.exp(z * sd)) / step) * step; + const Kr = r4(K); + if (!(Kr > 0) || strikes.has(Kr) || n >= MAX_STRIKES) continue; + strikes.add(Kr); n++; + const ratio = ratioFor(S); + for (const kind of ['call', 'put']) this.#add({ id: this.#newId(), kind, u, strike: Kr, ratio, expDay, tenor: t.key, issuedDay: g.day, status: 'active' }); + } + } + } + } + if (turbos) { + for (const u of TURBO_UNDERLYINGS) { + const S = this.spot(u); + if (!(S > 0)) continue; + const step = niceStep(S * 0.002); + for (const kind of ['long', 'short']) { + const list = active.filter((p) => p.u === u && p.kind === kind && p.status === 'active'); + // weit entfernte, von niemandem gehaltene Turbos vom Markt nehmen + for (const p of list) { + const lev = S / Math.abs(S - p.strike); + if (lev < 1.6 && !this.#held(p.id)) { p.status = 'delisted'; p.endedAt = g.clock.now(); this.g.metaDirty = true; } + } + const live = list.filter((p) => p.status === 'active'); + for (const L of LEVERAGES) { + if (live.length >= MAX_TURBOS) break; + if (live.some((p) => { const lev = S / Math.abs(S - p.strike); return lev >= L * 0.8 && lev <= L * 1.25; })) continue; + const K = r4(Math.round((kind === 'long' ? S * (1 - 1 / L) : S * (1 + 1 / L)) / step) * step); + if (!(K > 0) || live.some((p) => p.strike === K)) continue; + live.push(this.#add({ id: this.#newId(), kind, u, strike: K, ratio: ratioFor(S), issuedDay: g.day, status: 'active' })); + } + } + } + } + } + + #held(id) { + for (const acc of this.g.allAccounts()) if (acc.derivs?.[id]?.qty > 0) return true; + return false; + } + + // ================================================================ Laden & Takt + /** Nach dem Laden: Produkte erzeugen (auch für alte Spielstände ohne Hebelprodukte), verwaiste Positionen erstatten */ + init() { + const g = this.g; + for (const u of new Set([...WARRANT_UNDERLYINGS, ...TURBO_UNDERLYINGS])) { + const S = this.spot(u); + if (!this.vol[u] && S > 0) this.vol[u] = { v: this.#baseVol(u) ** 2, last: S }; + } + this.issue(); + for (const acc of g.allAccounts()) { + for (const [id, pos] of Object.entries(acc.derivs ?? {})) { + if (this.products.has(id)) continue; + // Produkt fehlt (z. B. Spielstand ohne Emittentendaten): Einsatz zurück + acc.cash += pos.qty * pos.avgCost; + delete acc.derivs[id]; + g.markDirty(acc); + } + } + } + + /** Zu Beginn eines Handelstags: Finanzierungsanpassung der Turbos, Knock-outs prüfen, neue Serien auflegen */ + onNewDay() { + const g = this.g; + if (this.lastFin !== g.day) { + this.lastFin = g.day; + const dpy = Math.max(1, this.cfg.daysPerYear); + for (const p of this.products.values()) { + if (p.status !== 'active' || isWarrant(p.kind)) continue; + p.strike = r4(p.strike * (1 + this.finRate(p.kind) / dpy)); + } + g.metaDirty = true; + } + this.#checkKnockouts(true); + this.issue(); + this.#prune(); + } + + /** Nach der Schlussauktion: Verfall mit Barausgleich, realisierte Volatilität fortschreiben */ + onClose() { + const g = this.g; + for (const p of [...this.products.values()]) { + if (p.status === 'active' && isWarrant(p.kind) && p.expDay <= g.day) this.#expire(p, this.closeOf(p.u)); + } + for (const u of new Set([...WARRANT_UNDERLYINGS, ...TURBO_UNDERLYINGS])) { + const c = this.closeOf(u); + const st = this.vol[u]; + if (!(c > 0)) continue; + if (st?.last > 0) { + const ret = Math.log(c / st.last); + st.v = 0.92 * st.v + 0.08 * ret * ret * Math.max(1, this.cfg.daysPerYear); + st.last = c; + } else this.vol[u] = { v: this.#baseVol(u) ** 2, last: c }; + } + g.metaDirty = true; + } + + tick() { + const g = this.g; + this.#checkKnockouts(false); + // verpasster Verfall (z. B. Server war zum Handelsschluss aus) + for (const p of this.products.values()) if (p.status === 'active' && isWarrant(p.kind) && p.expDay < g.day) this.#expire(p, this.closeOf(p.u)); + if (g.tickCount % 30 === 0) this.issue({ warrants: false }); + } + + /** Tiefst-/Höchstkurs je Basiswert seit der letzten Prüfung (aus den Umsätzen) */ + #range(u, since) { + const S = this.spot(u); + let lo = S, hi = S; + if (u !== IDX) { + for (const t of this.g.stocks.get(u)?.tape ?? []) { + if (t.ts <= since) break; + if (t.price < lo) lo = t.price; + if (t.price > hi) hi = t.price; + } + } + return { lo, hi }; + } + + #checkKnockouts(spotOnly) { + const now = this.g.clock.now(); + const since = this.lastKoTs || now; + this.lastKoTs = now; + const ranges = new Map(); + for (const p of [...this.products.values()]) { + if (p.status !== 'active' || isWarrant(p.kind)) continue; + if (!ranges.has(p.u)) ranges.set(p.u, spotOnly ? { lo: this.spot(p.u), hi: this.spot(p.u) } : this.#range(p.u, since)); + const { lo, hi } = ranges.get(p.u); + if (p.kind === 'long' ? lo <= p.strike : hi >= p.strike) this.#knockout(p, p.kind === 'long' ? Math.min(lo, p.strike) : Math.max(hi, p.strike)); + } + } + + /** Einzelprodukt sofort prüfen (vor jeder Order) */ + checkKo(p) { + if (p.status !== 'active' || isWarrant(p.kind)) return false; + const S = this.spot(p.u); + if (p.kind === 'long' ? S <= p.strike : S >= p.strike) { this.#knockout(p, S); return true; } + return false; + } + + #prune() { + const g = this.g; + for (const [id, p] of this.products) { + if (p.status === 'active') continue; + if ((p.endDay ?? g.day) < g.day - 2) this.products.delete(id); + } + } + + /** Inhaber eines Produkts (alle Konten) */ + *#holders(id) { + for (const acc of this.g.allAccounts()) { + const pos = acc.derivs?.[id]; + if (pos?.qty > 0) yield [acc, pos]; + } + } + + /** Position ausbuchen (Verfall, Knock-out, Saisonende); liefert die Gutschrift */ + #bookOut(acc, p, px, kind) { + const g = this.g; + const pos = acc.derivs?.[p.id]; + if (!pos?.qty) return 0; + const qty = pos.qty; + const realized = qty * (px - pos.avgCost); + acc.cash += qty * px; + acc.realized = (acc.realized ?? 0) + realized; + delete acc.derivs[p.id]; + g.recordFill({ ts: g.clock.now(), owner: g.ownerOf(acc), account: acc.id, symbol: p.id, side: 'sell', qty, price: px, fee: 0, realized, kind }); + g.markDirty(acc); + g.todo?.touch(g.ownerOf(acc)); + return { qty, realized, amount: qty * px }; + } + + #knockout(p, at) { + const g = this.g; + p.status = 'ko'; + p.endedAt = g.clock.now(); + p.endDay = g.day; + p.koSpot = at; + p.settle = 0; + g.metaDirty = true; + for (const [acc] of [...this.#holders(p.id)]) { + const r = this.#bookOut(acc, p, 0, 'derivKO'); + const owner = g.ownerOf(acc); + const pl = g.players.get(owner); + const where = acc.kind === 'fund' ? ' (Clan-Fonds)' : acc.owner ? ' (Battle-Depot)' : ''; + const text = `${this.uName(p.u)} hat die Knock-out-Schwelle von ${fmt(p.strike)} berührt (${fmt(at)}). Deine ${r.qty} Stück verfallen wertlos – Verlust ${fmt(-r.realized)} €${where}.`; + g.notify(owner, { kind: 'deriv', title: `Knock-out: ${this.name(p)}`, text, action: { symbol: p.u === IDX ? INDEX_LIST[0] : p.u } }); + g.sendTo(owner, { type: 'derivKO', id: p.id, name: this.name(p), u: p.u, strike: p.strike, spot: at, qty: r.qty, loss: -r.realized, account: acc.kind === 'fund' ? 'fund' : acc.owner ? 'battle' : 'main' }); + if (pl) { + pl.derivHits = [...(pl.derivHits ?? []).filter((x) => x.day === g.day), { id: p.id, name: this.name(p), u: p.u, qty: r.qty, loss: -r.realized, day: g.day, kind: 'ko' }].slice(-10); + g.unlock(pl, 'lever_ko'); + } + } + } + + #expire(p, close) { + const g = this.g; + const unit = Math.max(0, p.kind === 'call' ? close - p.strike : p.strike - close); + const px = r4(unit * p.ratio); + p.status = 'expired'; + p.endedAt = g.clock.now(); + p.endDay = g.day; + p.settle = px; + p.settleSpot = close; + g.metaDirty = true; + for (const [acc] of [...this.#holders(p.id)]) { + const r = this.#bookOut(acc, p, px, 'derivExpiry'); + const owner = g.ownerOf(acc); + const pl = g.players.get(owner); + const text = px > 0 + ? `Barausgleich zum Schlusskurs ${fmt(close)}: ${fmt(px)} € je Schein, zusammen ${fmt(r.amount)} € gutgeschrieben (${r.realized >= 0 ? '+' : '−'}${fmt(Math.abs(r.realized))} €).` + : `Schlusskurs ${fmt(close)} – der Schein ist wertlos verfallen (Verlust ${fmt(-r.realized)} €).`; + g.notify(owner, { kind: 'deriv', title: `Fällig: ${this.name(p)}`, text }); + g.sendTo(owner, { type: 'derivExpiry', id: p.id, name: this.name(p), qty: r.qty, price: px, amount: r.amount, realized: r.realized }); + if (pl) pl.derivHits = [...(pl.derivHits ?? []).filter((x) => x.day === g.day), { id: p.id, name: this.name(p), u: p.u, qty: r.qty, pnl: r.realized, day: g.day, kind: 'expiry' }].slice(-10); + } + } + + /** Saisonende: alle Hebelprodukte aller Konten zum Geldkurs ausbuchen */ + liquidateAll(reason = 'season') { + for (const acc of this.g.allAccounts()) { + for (const id of Object.keys(acc.derivs ?? {})) { + const p = this.products.get(id); + if (!p) { delete acc.derivs[id]; continue; } + const q = this.quote(p); + this.#bookOut(acc, p, q.bid ?? 0, reason === 'season' ? 'derivSeason' : 'derivClose'); + } + } + } + + // ================================================================ Depot + /** Wert aller Hebelprodukte eines Kontos zum Geldkurs */ + value(acc) { + let v = 0; + for (const [id, pos] of Object.entries(acc.derivs ?? {})) { + const p = this.products.get(id); + if (!p || !(pos.qty > 0)) continue; + v += pos.qty * (this.quote(p).bid ?? 0); + } + return v; + } + + positions(acc) { + const out = []; + for (const [id, pos] of Object.entries(acc.derivs ?? {})) { + const p = this.products.get(id); + if (!p || !(pos.qty > 0)) continue; + const q = this.quote(p); + const v = this.view(p, q); + out.push({ ...v, qty: pos.qty, avgCost: pos.avgCost, value: pos.qty * q.bid, pnl: pos.qty * (q.bid - pos.avgCost), pnlPct: pos.avgCost > 0 ? (q.bid / pos.avgCost - 1) * 100 : 0, cost: pos.qty * pos.avgCost }); + } + return out.sort((a, b) => b.value - a.value); + } + + /** Produktliste für den Reiter „Hebelprodukte“ */ + list(u, p = null) { + const g = this.g; + u = u === 'WIBO-10' ? IDX : u; + if (u !== IDX && !g.stocks.has(u)) throw new Error('Unbekannter Basiswert'); + const held = p?.derivs ?? {}; + const items = [...this.products.values()].filter((x) => x.u === u && x.status === 'active').map((x) => ({ ...this.view(x), held: held[x.id]?.qty ?? 0 })); + const kindOrder = { call: 0, put: 1, long: 2, short: 3 }; + items.sort((a, b) => kindOrder[a.kind] - kindOrder[b.kind] || (a.expDay ?? 0) - (b.expDay ?? 0) || a.strike - b.strike); + const hasW = WARRANT_UNDERLYINGS.includes(u), hasT = TURBO_UNDERLYINGS.includes(u); + return { + u, uName: this.uName(u), uLabel: this.uLabel(u), spot: this.spot(u), sigma: this.sigma(u), rate: this.r(), issuer: ISSUER, + closed: hasW || hasT ? this.closedReason(u) : null, warrants: hasW, turbos: hasT, items, + indexLink: INDEX_SYMBOLS.has(u), tenors: this.tenors(), limits: { maxOrder: DERIV.maxOrder, maxPerUnderlying: DERIV.maxPerUnderlying }, + ack: !!p?.derivAck, day: g.day, + }; + } + + detail(id, p = null) { + const x = this.products.get(String(id ?? '')); + if (!x) throw new Error('Unbekanntes Produkt'); + if (x.status === 'active') this.checkKo(x); + return { ...this.view(x), held: p?.derivs?.[x.id]?.qty ?? 0, closed: x.status === 'active' ? this.closedReason(x.u) : 'Produkt ist nicht mehr handelbar' }; + } + + // ================================================================ Handel mit dem Emittenten + #rateCheck(p) { + const now = this.g.clock.now(); + const st = this.rate.get(p.id) ?? { times: [], day: this.g.day, n: 0 }; + if (st.day !== this.g.day) { st.day = this.g.day; st.n = 0; } + st.times = st.times.filter((t) => now - t < 60_000); + if (st.times.length >= DERIV.perMinute) throw new Error(`Höchstens ${DERIV.perMinute} Orders in Hebelprodukten pro Minute – bitte kurz warten`); + if (st.n >= DERIV.perDay) throw new Error(`Höchstens ${DERIV.perDay} Orders in Hebelprodukten pro Handelstag`); + st.times.push(now); st.n++; + this.rate.set(p.id, st); + if (this.rate.size > 5000) this.rate.clear(); + } + + /** + * Kauf oder Verkauf beim Emittenten – sofort oder gar nicht. o: { id, side, qty, account?, limit?, ack? } + * limit: schlechtester akzeptierter Preis (sonst gilt der aktuelle Geld- bzw. Briefkurs). + */ + order(pl, o = {}) { + const g = this.g, cfg = this.cfg; + const acc = g.resolveAccount(pl, o.account); + if (acc.kind === 'fund') throw new Error('Im Clan-Fonds sind Hebelprodukte nicht erlaubt – Fondsgeld der Mitglieder soll nicht mit Totalverlustrisiko gehebelt werden'); + const p = this.products.get(String(o.id ?? '')); + if (!p) throw new Error('Unbekanntes Produkt'); + const side = o.side; + if (side !== 'buy' && side !== 'sell') throw new Error('Ungültige Seite'); + const qty = Math.floor(Number(o.qty)); + if (!(qty >= 1 && qty <= DERIV.maxQty)) throw new Error('Ungültige Stückzahl'); + if (p.status === 'active') this.checkKo(p); + if (p.status !== 'active') throw new Error(p.status === 'ko' ? 'Knock-out: Der Turbo ist verfallen' : 'Dieses Produkt ist nicht mehr handelbar'); + if (side === 'buy') { + if (acc.locked) throw new Error('Depot gesperrt: Eigenkapital ist negativ – nur das Abbauen von Positionen ist erlaubt'); + if (acc.rules?.symbols && !acc.rules.symbols.includes(p.u)) throw new Error(`Im Battle nur erlaubt: ${acc.rules.symbols.join(', ')}`); + if (acc.rules?.noShort && (p.kind === 'put' || p.kind === 'short')) throw new Error('In diesem Battle-Modus sind nur steigende Wetten erlaubt (Call, Turbo Long)'); + } + const why = this.closedReason(p.u); + if (why) throw new Error(why); + const q = this.quote(p); + const owned = acc.derivs?.[p.id]?.qty ?? 0; + let px; + if (side === 'buy') { + if (!isWarrant(p.kind) && q.dist < DERIV.minKoDist) throw new Error('Zu nah an der Knock-out-Schwelle – der Emittent nimmt nur noch Verkäufe an'); + px = q.ask; + if (!(px > 0)) throw new Error('Der Emittent stellt gerade keinen Briefkurs'); + } else { + if (qty > owned) throw new Error(owned ? `Du hast nur ${owned} Stück – Leerverkauf von Hebelprodukten ist nicht möglich` : 'Nicht im Depot – Leerverkauf von Hebelprodukten ist nicht möglich'); + px = q.bid; + if (!(px > 0)) throw new Error('Der Schein ist praktisch wertlos – der Emittent stellt keinen Geldkurs (Ausbuchung bei Fälligkeit)'); + } + if (o.limit !== undefined && o.limit !== null && o.limit !== '') { + const lim = Number(o.limit); + if (!(lim > 0)) throw new Error('Ungültiges Limit'); + if (side === 'buy' ? px > lim + 1e-9 : px < lim - 1e-9) throw new Error(`Der Kurs hat sich bewegt: Der Emittent ${side === 'buy' ? 'verkauft' : 'kauft'} jetzt zu ${fmt3(px)} € – dein Limit ${fmt3(lim)} € wird nicht erreicht`); + } + const notional = qty * px; + if (side === 'buy' && notional > DERIV.maxOrder) throw new Error(`Höchstens ${fmt(DERIV.maxOrder)} € je Order – bei ${fmt3(px)} € also ${Math.floor(DERIV.maxOrder / px)} Stück`); + const fee = notional * cfg.feeRate + cfg.fixedFee; + if (side === 'buy') { + if (notional + fee > g.freeCash(acc) + 1e-6) throw new Error('Nicht genug Kaufkraft'); + const inU = Object.entries(acc.derivs ?? {}).reduce((a, [id, x]) => a + (this.products.get(id)?.u === p.u ? x.qty * x.avgCost : 0), 0); + if (inU + notional > DERIV.maxPerUnderlying) throw new Error(`Höchstens ${fmt(DERIV.maxPerUnderlying)} € Einsatz in Hebelprodukten je Basiswert und Depot (bisher ${fmt(inU)} €)`); + const owner = g.players.get(g.ownerOf(acc)); + if (owner && !owner.derivAck) { + if (o.ack !== true) { const e = new Error(`Bitte bestätige zuerst den Risikohinweis: ${RISK_TEXT}`); e.needAck = true; throw e; } + owner.derivAck = true; + g.markDirty(owner); + } + } else if (notional - fee < 0) throw new Error('Der Erlös deckt die Gebühr nicht'); + this.#rateCheck(pl); + // Buchung (Hebelprodukte liegen getrennt von Aktienpositionen in acc.derivs) + acc.derivs ??= {}; + const avgBefore = acc.derivs[p.id]?.avgCost ?? 0; + const book = { positions: acc.derivs, cash: acc.cash, fees: acc.fees, realized: acc.realized, trades: acc.trades }; + const gross = applyFill(book, p.id, side === 'buy' ? qty : -qty, px, fee); + Object.assign(acc, { cash: book.cash, fees: book.fees, realized: book.realized, trades: book.trades }); + if (acc.derivs[p.id]) acc.derivs[p.id].ts ??= g.clock.now(); + const realized = gross !== 0 ? gross - fee : 0; + const owner = g.ownerOf(acc); + g.recordFill({ ts: g.clock.now(), owner, account: acc.id, symbol: p.id, side, qty, price: px, fee, realized, kind: 'deriv' }); + g.markDirty(acc); + g.todo?.touch(owner); + const pp = g.players.get(owner); + if (pp) { + g.prog.event(pp, 'trade'); + if (side === 'buy') g.unlock(pp, 'lever_first'); + if (side === 'sell' && avgBefore > 0 && px >= 2 * avgBefore) g.unlock(pp, 'lever_double'); + } + return { id: `d${g.clock.now().toString(36)}`, product: p.id, name: this.name(p), side, qty, price: px, fee, realized, status: 'filled', notional }; + } +} +const fmt3 = (x) => x.toLocaleString('de-DE', { minimumFractionDigits: 3, maximumFractionDigits: 3 }); + +// ================================================================ „Mein Tag“ +registerTodo('derivs', (g, p, ctx) => { + const d = g.derivs; + if (!d) return []; + const out = []; + const accounts = [p, ...[...g.battleAccounts.values()].filter((a) => a.owner === p.id)]; + for (const acc of accounts) { + const where = acc === p ? '' : ' (Battle-Depot)'; + for (const [id, pos] of Object.entries(acc.derivs ?? {})) { + const x = d.products.get(id); + if (!x || x.status !== 'active' || !(pos.qty > 0)) continue; + const target = { view: 'handeln', symbol: x.u === IDX ? INDEX_LIST[0] : x.u, stab: 'derivs', deriv: x.id }; + if (isWarrant(x.kind)) { + const k = x.expDay - g.day; + if (k <= 0) { + out.push({ id: `dexp-${id}`, group: 'today', icon: 'hourglass', title: `${d.name(x)} wird heute fällig${where}`, + detail: `${pos.qty} Stück – Barausgleich zum Schlusskurs von ${d.uName(x.u)}. Bis zur Schlussauktion kannst du noch verkaufen.`, deadline: ctx.closeAt, target }); + } else if (k === 1) { + out.push({ id: `dexp-${id}`, group: 'watch', icon: 'hourglass', title: `${d.name(x)} wird morgen fällig${where}`, + detail: `${pos.qty} Stück – der Zeitwert schmilzt jetzt am schnellsten.`, deadline: ctx.dayStart(1), target }); + } + } else { + const q = d.quote(x); + if (q.dist < DERIV.koNear) { + out.push({ id: `dko-${id}`, group: 'urgent', icon: 'warn', title: `Knock-out nah: ${d.name(x)}${where}`, + detail: `${d.uName(x.u)} steht nur noch ${fmt(q.dist * 100)} % von der Schwelle ${fmt(x.strike)} entfernt – bei Berührung verfällt der Turbo wertlos.`, target }); + } + } + } + } + for (const h of (p.derivHits ?? []).filter((x) => x.day === g.day)) { + out.push(h.kind === 'ko' + ? { id: `dhit-${h.id}`, group: 'watch', icon: 'flame', title: `Knock-out: ${h.name}`, detail: `${h.qty} Stück wertlos verfallen (−${fmt(h.loss)} €).`, target: { view: 'depot' } } + : { id: `dhit-${h.id}`, group: 'watch', icon: 'doc', title: `Fällig: ${h.name}`, detail: `${h.qty} Stück abgerechnet (${h.pnl >= 0 ? '+' : '−'}${fmt(Math.abs(h.pnl))} €).`, target: { view: 'depot' } }); + } + return out; +}); diff --git a/server/src/derivatives.test.js b/server/src/derivatives.test.js new file mode 100644 index 0000000..a79df8c --- /dev/null +++ b/server/src/derivatives.test.js @@ -0,0 +1,369 @@ +// Hebelprodukte: Bewertung (Black-Scholes), Spannen, Arbitragefreiheit, Handel mit dem Emittenten, Knock-out, +// Verfall mit Barausgleich, Finanzierungsanpassung, Saisonende, Dedup über clientId und alte Spielstände. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import os from 'node:os'; +import fs from 'node:fs'; +import path from 'node:path'; + +process.env.NODE_ENV = 'test'; +process.env.TIME_MODE = 'turbo'; +process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-deriv-')); +const { settings } = await import('./settings.js'); +const { Store } = await import('./store.js'); +const { Game } = await import('./game.js'); +const { blackScholes, floorValue, quotePair, warrantSpread, DERIV, IDX, RISK_TEXT } = await import('./derivatives.js'); + +Object.assign(settings.game, { dayMs: 60_000, tickMs: 1000, rivalsEnabled: false, ipoEveryDays: 0, agmEnabled: false, staticCorridor: 0.5, dynamicCorridor: 0.3, marketHaltPct: 0.5, recallsEnabled: false }); +settings.news.enabled = false; + +function setup(dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-dv-'))) { + const clock = { t: Date.now() }; + const sent = []; + const store = new Store(dir); + const g = new Game({ store, now: () => clock.t, sendTo: (pid, m) => sent.push({ pid, ...m }) }); + return { g, clock, sent, dir, store }; +} +const step = ({ g, clock }, n = 1) => { for (let i = 0; i < n; i++) { clock.t += 1000; g.tick(); } }; +const until = (ctx, pred, max = 600) => { for (let i = 0; i < max && !pred(); i++) step(ctx); assert.ok(pred(), 'Bedingung nicht erreicht'); }; +const toContinuous = (ctx) => until(ctx, () => ctx.g.market.phase === 'continuous' && !ctx.g.stocks.get('NVLT').volaEndsAt); +const player = async (g, name) => (await g.register({ name, password: 'geheim123' })).player; +const near = (a, b, eps) => assert.ok(Math.abs(a - b) <= eps, `${a} ≉ ${b} (±${eps})`); +const prods = (g, u, kind) => [...g.derivs.products.values()].filter((x) => x.status === 'active' && (!u || x.u === u) && (!kind || x.kind === kind)); + +test('Black-Scholes gegen Referenzwerte', () => { + // Lehrbuchwerte (europäisch, ohne Dividende) + near(blackScholes({ type: 'call', S: 100, K: 100, T: 1, r: 0.05, sigma: 0.2 }).price, 10.4506, 1e-3); + near(blackScholes({ type: 'put', S: 100, K: 100, T: 1, r: 0.05, sigma: 0.2 }).price, 5.5735, 1e-3); + near(blackScholes({ type: 'call', S: 42, K: 40, T: 0.5, r: 0.1, sigma: 0.2 }).price, 4.7594, 1e-3); + near(blackScholes({ type: 'put', S: 42, K: 40, T: 0.5, r: 0.1, sigma: 0.2 }).price, 0.8086, 1e-3); + near(blackScholes({ type: 'call', S: 42, K: 40, T: 0.5, r: 0.1, sigma: 0.2 }).delta, 0.7791, 1e-3); + // Put-Call-Parität im Modell: C − P = (S − D) − K·e^(−rT) + for (const [S, K, T, r, sigma, div] of [[100, 90, 0.3, 0.03, 0.4, 1.2], [50, 60, 1, 0.01, 0.25, 0], [10000, 10400, 0.1, 0.04, 0.18, 30]]) { + const c = blackScholes({ type: 'call', S, K, T, r, sigma, div }).price, p = blackScholes({ type: 'put', S, K, T, r, sigma, div }).price; + near(c - p, S - div - K * Math.exp(-r * T), 1e-6 * S); + } + // Dividenden verbilligen Calls und verteuern Puts; ohne Restlaufzeit gilt der innere Wert + assert.ok(blackScholes({ type: 'call', S: 100, K: 100, T: 0.5, r: 0.03, sigma: 0.3, div: 2 }).price < blackScholes({ type: 'call', S: 100, K: 100, T: 0.5, r: 0.03, sigma: 0.3 }).price); + assert.equal(blackScholes({ type: 'put', S: 80, K: 100, T: 0, r: 0.03, sigma: 0.3 }).price, 20); +}); + +test('Spanne, Mindest-Geldkurs, wertlose Scheine', () => { + assert.equal(warrantSpread(0, 50), 0.01, 'am Geld, lange Laufzeit: 1 %'); + assert.ok(warrantSpread(2, 50) > warrantSpread(0.5, 50), 'weiter aus dem Geld → breiter'); + assert.ok(warrantSpread(0, 0.5) > warrantSpread(0, 10), 'kurz vor Fälligkeit → breiter'); + assert.ok(warrantSpread(5, 0) <= 0.15); + const q = quotePair(1.234, 0.02); + assert.ok(q.bid < 1.234 && q.ask > 1.234 && q.ask > q.bid); + const cheap = quotePair(0.0012, 0.15); + assert.equal(cheap.bid, 0.001, 'Mindest-Geldkurs 0,001 €'); + const worthless = quotePair(0.0001, 0.15); + assert.equal(worthless.bid, 0, 'wertlos: Geld 0'); + assert.ok(worthless.ask >= 0.001, 'Brief nicht 0'); +}); + +test('Produkte beim Start: Serien je Basiswert, Preis ≥ innerer Wert, Spanne 1–15 %, Calls etwas teurer', () => { + const { g } = setup(); + const all = prods(g); + assert.ok(all.length > 300, `${all.length} Produkte`); + for (const u of ['NVLT', IDX, 'GOLD', 'OEL']) { + assert.ok(prods(g, u, 'call').length >= 15 && prods(g, u, 'put').length >= 15, `Optionsscheine auf ${u}`); + assert.deepEqual([...new Set(prods(g, u, 'call').map((x) => x.tenor))].sort(), ['1J', '1M', '1Q']); + } + for (const u of [IDX, 'GOLD', 'OEL', 'GAS', 'WIBC', 'NVLT']) assert.ok(prods(g, u, 'long').length >= 5 && prods(g, u, 'short').length >= 5, `Turbos auf ${u}`); + assert.equal(prods(g, 'GAS', 'call').length, 0, 'keine Optionsscheine auf Gas'); + // Turbos mit Hebel 2–20 + const levs = prods(g, 'NVLT', 'long').map((x) => g.derivs.quote(x).lev); + assert.ok(Math.min(...levs) < 2.5 && Math.max(...levs) > 15, levs.join()); + // Bewertung bei verschiedenen Kursen + for (const shock of [0.6, 0.9, 1, 1.1, 1.6]) { + for (const x of all) { + const S = g.derivs.spot(x.u) * shock; + const q = g.derivs.quote(x, { spot: S }); + if (q.ko) continue; + assert.ok(q.mid + 1e-9 >= q.intrinsic, `${x.id}: Preis ≥ innerer Wert`); + assert.ok(q.ask + 1e-9 >= q.intrinsic, `${x.id}: Brief ≥ innerer Wert`); + assert.ok(q.ask > q.bid, `${x.id}: Brief > Geld`); + assert.ok(q.bid === 0 || q.bid >= DERIV.tick, `${x.id}: Mindest-Geldkurs`); + if (x.kind === 'call' || x.kind === 'put') assert.ok(q.spread >= 0.01 && q.spread <= 0.15, `${x.id}: Spanne ${q.spread}`); + } + } + // Calls vs. Puts mit gleichem Abstand: meist etwas teurer (Zins), nicht erzwungen + const S = g.derivs.spot('GOLD'); + const one = (kind, K) => g.derivs.quote({ kind, u: 'GOLD', strike: K, ratio: 0.1, expDay: g.day + 20, status: 'active' }).mid; + assert.ok(one('call', S * 1.1) > one('put', S / 1.1) * 0.95); +}); + +test('Arbitragefreiheit: Put-Call-Parität, Untergrenzen, Kauf/Verkauf, Zeitwert, Spanne bei Verfall', () => { + const { g } = setup(); + const d = g.derivs; + const r = d.r(); + for (const c of prods(g, null, 'call')) { + const p = [...d.products.values()].find((x) => x.kind === 'put' && x.u === c.u && x.strike === c.strike && x.expDay === c.expDay); + assert.ok(p, 'zu jedem Call gibt es den Put'); + const days = d.daysLeft(c), T = days / g.cfg.daysPerYear, S = d.spot(c.u), div = d.divUntil(c.u, days); + const qc = d.quote(c), qp = d.quote(p); + const parity = (S - div - c.strike * Math.exp(-r * T)) * c.ratio; + const tol = c.strike * c.ratio * (1 - Math.exp(-Math.abs(r) * T)) + (qc.ask - qc.bid) + (qp.ask - qp.bid) + 2 * DERIV.tick; + assert.ok(Math.abs(qc.mid - qp.mid - parity) <= tol, `${c.id}/${p.id}: Parität grob eingehalten`); + // Synthetik ohne Leerverkauf von Scheinen: Aktie + Put kaufen ≥ Basispreis + Dividenden (Bargeld bringt keine Zinsen) + assert.ok(qp.ask / p.ratio + 1e-9 >= Math.max(0, p.strike - S + div), `${p.id}: Put ≥ K − S + D`); + // Call + Aktie leerverkaufen: Call ≥ S − K + assert.ok(qc.ask / c.ratio + 1e-9 >= S - c.strike, `${c.id}: Call ≥ S − K`); + } + for (const x of prods(g)) { + const q0 = d.quote(x); + // sofort zurückverkaufen: nie Gewinn + assert.ok(q0.bid < q0.ask, `${x.id}: Kauf und Verkauf ohne Kursbewegung verliert`); + // einen Handelstag später bei unverändertem Kurs: Geld morgen < Brief heute + if (x.kind === 'call' || x.kind === 'put') { + const q1 = d.quote(x, { days: Math.max(0, d.daysLeft(x) - 1) }); + assert.ok(q1.bid < q0.ask, `${x.id}: Zeitwert macht Halten nicht risikolos`); + // Spanne bei Verfall: Barausgleich (innerer Wert) liegt nicht über dem Briefkurs + const qEnd = d.quote(x, { days: 0 }); + assert.ok(qEnd.ask + 1e-9 >= qEnd.intrinsic, `${x.id}: Brief ≥ Barausgleich`); + } + } +}); + +test('Handel mit dem Emittenten: Risikohinweis, Kauf, Bewertung zum Geldkurs, kein Leerverkauf, Grenzen', async () => { + const ctx = setup(); + const { g } = ctx; + const a = await player(g, 'Hebelfan'); + toContinuous(ctx); + const c = prods(g, 'NVLT', 'call').find((x) => x.tenor === '1Q'); + assert.throws(() => g.placeDeriv(a, { id: c.id, side: 'buy', qty: 100 }), (e) => e.needAck === true && e.message.includes(RISK_TEXT)); + const cash0 = a.cash; + const q = g.derivs.quote(c); + const o = g.placeDeriv(a, { id: c.id, side: 'buy', qty: 100, ack: true }); + assert.equal(o.status, 'filled'); + assert.equal(o.price, q.ask); + assert.ok(a.derivAck, 'Hinweis bestätigt und gemerkt'); + const fee = 100 * q.ask * g.cfg.feeRate + g.cfg.fixedFee; + near(a.cash, cash0 - 100 * q.ask - fee, 1e-6); + assert.equal(a.derivs[c.id].qty, 100); + assert.deepEqual(Object.keys(a.positions), [], 'keine Aktienposition'); + // Depot: eigene Gruppe, Wert zum Geldkurs, zählt zum Depotwert, belastet keine Margin + const pf = g.portfolio(a); + assert.equal(pf.derivs.length, 1); + near(pf.derivs[0].value, 100 * g.derivs.quote(c).bid, 1e-9); + near(g.equity(a), a.cash + 100 * g.derivs.quote(c).bid, 1e-6); + assert.equal(g.margin(a).usage, 0); + near(pf.equity, g.equity(a), 1e-6); + // ohne Basiswertbewegung: sofortiger Verkauf bringt weniger als der Kauf gekostet hat + assert.throws(() => g.placeDeriv(a, { id: c.id, side: 'sell', qty: 101 }), /Leerverkauf/); + const p2 = prods(g, 'NVLT', 'put')[0]; + assert.throws(() => g.placeDeriv(a, { id: p2.id, side: 'sell', qty: 1 }), /Leerverkauf/); + const sell = g.placeDeriv(a, { id: c.id, side: 'sell', qty: 100 }); + assert.ok(sell.realized < 0, 'Runde Kauf/Verkauf ist ein Verlust'); + assert.equal(a.derivs[c.id], undefined); + // Grenzen: Ordergröße, Limit, Basiswert gesperrt + const big = prods(g, IDX, 'long').sort((x, y) => g.derivs.quote(y).ask - g.derivs.quote(x).ask)[0]; + assert.throws(() => g.placeDeriv(a, { id: big.id, side: 'buy', qty: Math.ceil(DERIV.maxOrder / g.derivs.quote(big).ask) + 5 }), /je Order/); + assert.throws(() => g.placeDeriv(a, { id: c.id, side: 'buy', qty: 10, limit: g.derivs.quote(c).ask * 0.5 }), /Limit/); + // Basiswert wird nicht bewegt + const s = g.stocks.get('NVLT'); + const last = s.last; + g.placeDeriv(a, { id: c.id, side: 'buy', qty: 1000 }); + assert.equal(s.last, last, 'Basiswert unverändert'); + assert.equal(s.book.openOrdersOf(a.id).length, 0); + // Fills: im Journal als „deriv“ + assert.ok(g.pendingFills.some((f) => f.kind === 'deriv' && f.symbol === c.id)); +}); + +test('Dedup über clientId: Wiederholung kauft nicht doppelt', async () => { + const ctx = setup(); + const { g } = ctx; + const a = await player(g, 'Doppelt'); + toContinuous(ctx); + const t = prods(g, 'GOLD', 'long')[0]; + const first = g.placeDeriv(a, { id: t.id, side: 'buy', qty: 10, ack: true, clientId: 'abc-12345678' }); + const again = g.placeDeriv(a, { id: t.id, side: 'buy', qty: 10, ack: true, clientId: 'abc-12345678' }); + assert.equal(again.duplicate, true); + assert.equal(again.id, first.id); + assert.equal(a.derivs[t.id].qty, 10, 'nur einmal gekauft'); + // dieselbe clientId einer Aktienorder kollidiert nicht mit Hebelprodukten + const o = g.placeOrder(a, { symbol: 'NVLT', side: 'buy', type: 'limit', qty: 1, price: Math.round(g.stocks.get('NVLT').last * 0.9 * 100) / 100, clientId: 'abc-12345678' }); + assert.equal(o.duplicate, undefined); + g.placeDeriv(a, { id: t.id, side: 'buy', qty: 5, clientId: 'abc-87654321' }); + assert.equal(a.derivs[t.id].qty, 15); +}); + +test('Knock-out: sofortiger Verfall mit Benachrichtigung, Mein Tag, Toast; kein Kauf kurz davor', async () => { + const ctx = setup(); + const { g, sent } = ctx; + const a = await player(g, 'Ausgeknockt'); + toContinuous(ctx); + const s = g.stocks.get('NVLT'); + const t = prods(g, 'NVLT', 'long').sort((x, y) => y.strike - x.strike)[0]; // höchster Hebel + g.placeDeriv(a, { id: t.id, side: 'buy', qty: 200, ack: true }); + const cost = a.derivs[t.id].qty * a.derivs[t.id].avgCost; + // Knock-out-Nähe < 3 % → „Mein Tag“ + s.last = t.strike * 1.02; + assert.ok(g.todo.items(a).some((x) => x.id === `dko-${t.id}` && x.group === 'urgent')); + // Kauf zu nah an der Schwelle wird abgelehnt + s.last = t.strike * 1.003; + assert.throws(() => g.placeDeriv(a, { id: t.id, side: 'buy', qty: 10 }), /Knock-out-Schwelle/); + // Kurs berührt die Schwelle: vor dem nächsten Takt ist auch kein Kauf/Verkauf mehr möglich + s.last = t.strike * 0.999; + assert.throws(() => g.placeDeriv(a, { id: t.id, side: 'sell', qty: 10 }), /Knock-out/); + assert.equal(t.status, 'ko'); + assert.equal(a.derivs[t.id], undefined, 'Position ausgebucht'); + assert.ok(a.inbox.some((i) => i.kind === 'deriv' && i.title.includes('Knock-out')), 'Benachrichtigung'); + assert.ok(sent.some((m) => m.type === 'derivKO' && m.id === t.id && m.pid === a.id), 'Toast-Nachricht'); + assert.ok(g.todo.items(a).some((x) => x.id === `dhit-${t.id}`), 'Eintrag in Mein Tag'); + assert.ok(g.pendingFills.some((f) => f.kind === 'derivKO' && near2(f.realized, -cost))); + assert.ok(a.achievements.includes('lever_ko')); + // Knock-out im Takt (zwischenzeitliche Berührung über die Umsätze) + const t2 = prods(g, 'NVLT', 'long').sort((x, y) => y.strike - x.strike)[0]; + s.last = g.stocks.get('NVLT').fair; + g.placeDeriv(a, { id: t2.id, side: 'buy', qty: 10 }); + s.tape.unshift({ symbol: 'NVLT', price: t2.strike - 0.01, qty: 1, ts: g.clock.now() + 500 }); + ctx.clock.t += 1000; g.derivs.tick(); + assert.equal(t2.status, 'ko', 'Berührung zwischen zwei Takten zählt'); + // der Emittent legt neue Turbos auf + g.derivs.issue({ warrants: false }); + assert.ok(prods(g, 'NVLT', 'long').length >= 5); +}); +const near2 = (a, b) => Math.abs(a - b) < 1e-6; + +test('Verfall mit Barausgleich zum Schlusskurs, danach ausgebucht', async () => { + const ctx = setup(); + const { g, sent } = ctx; + const a = await player(g, 'Verfall'); + toContinuous(ctx); + const s = g.stocks.get('NVLT'); + const c = prods(g, 'NVLT', 'call').filter((x) => x.strike < s.last).sort((x, y) => x.strike - y.strike)[0]; // im Geld + const p = prods(g, 'NVLT', 'put').filter((x) => x.strike < s.last * 0.85)[0]; // weit aus dem Geld + g.placeDeriv(a, { id: c.id, side: 'buy', qty: 50, ack: true }); + if (p) g.placeDeriv(a, { id: p.id, side: 'buy', qty: 50 }); + c.expDay = g.day; if (p) p.expDay = g.day; // heute fällig + assert.ok(g.todo.items(a).some((x) => x.id === `dexp-${c.id}` && x.group === 'today'), 'Mein Tag: heute fällig'); + assert.ok(g.calendar(a).items.some((i) => i.kind === 'expiry' && i.title.includes(g.derivs.name(c))), 'Kalender: eigene Fälligkeit'); + const day = g.day; + until(ctx, () => g.day > day || g.market.phase === 'closed'); + assert.equal(c.status, 'expired'); + const expect = Math.round(Math.max(0, s.close - c.strike) * c.ratio * 1e4) / 1e4; + near(c.settle, expect, 1e-9); + assert.equal(a.derivs[c.id], undefined, 'ausgebucht'); + const f = g.pendingFills.find((x) => x.kind === 'derivExpiry' && x.symbol === c.id) ?? null; + const fromStore = f ?? g.store.journal(a.id, g.season.n).find((x) => x.kind === 'derivExpiry' && x.symbol === c.id); + assert.ok(fromStore, 'Abrechnung im Journal'); + near(fromStore.price, expect, 1e-9); + assert.ok(sent.some((m) => m.type === 'derivExpiry' && m.id === c.id)); + if (p) { assert.equal(p.status, 'expired'); assert.equal(p.settle, 0, 'aus dem Geld: wertlos'); } + // verfallene Serien werden ersetzt (rollierend) + g.derivs.issue(); + assert.ok(prods(g, 'NVLT', 'call').every((x) => x.expDay >= g.day)); + assert.ok(prods(g, 'NVLT', 'call').some((x) => x.tenor === '1M')); +}); + +test('Finanzierungsanpassung der Turbos: Basispreis wandert täglich, nie zugunsten des Inhabers', () => { + const { g } = setup(); + const d = g.derivs; + const L = prods(g, 'GOLD', 'long')[0], Sh = prods(g, 'GOLD', 'short')[0]; + const kL = L.strike, kS = Sh.strike; + const dpy = g.cfg.daysPerYear; + g.macro.rate = 2.5; + d.lastFin = null; + d.onNewDay(); + near(L.strike, kL * (1 + (0.025 + DERIV.finSpread) / dpy), 1e-3); + near(Sh.strike, kS * (1 + (0.025 - DERIV.finSpread) / dpy), 1e-3); + assert.ok(L.strike > kL && Sh.strike < kS); + // zweimal am selben Tag: keine doppelte Anpassung + const k2 = L.strike; d.onNewDay(); assert.equal(L.strike, k2); + // hoher Zins: Short-Basispreis steigt nicht (sonst risikoloser Zins mit Turbo Short + Aktie) + g.macro.rate = 9; d.lastFin = null; + const k3 = Sh.strike; d.onNewDay(); + assert.ok(Sh.strike <= k3); +}); + +test('Battles, Clan-Fonds, Massenhandel', async () => { + const ctx = setup(); + const { g } = ctx; + const a = await player(g, 'Regeltreu'); + toContinuous(ctx); + a.derivAck = true; + const call = prods(g, 'NVLT', 'call')[0], put = prods(g, 'NVLT', 'put')[0]; + // Clan-Fonds: nicht erlaubt + const fund = { id: 'f:test', owner: a.id, kind: 'fund', cash: 50_000, positions: {}, realized: 0, fees: 0, trades: 0, rules: { noShort: true } }; + g.battleAccounts.set(fund.id, fund); + g.clubs.managedFund = () => fund; + assert.throws(() => g.placeDeriv(a, { id: call.id, side: 'buy', qty: 1, account: 'fund' }), /Clan-Fonds/); + // Battle „Nur Long“: Call ja, Put nein + const bacc = { id: 'b:test', owner: a.id, cash: 50_000, positions: {}, realized: 0, fees: 0, trades: 0, rules: { noShort: true } }; + g.battleAccounts.set(bacc.id, bacc); + const orig = g.resolveAccount.bind(g); + g.resolveAccount = (p, w) => (w === 'battle' ? bacc : orig(p, w)); + assert.throws(() => g.placeDeriv(a, { id: put.id, side: 'buy', qty: 1, account: 'battle' }), /steigende/); + g.placeDeriv(a, { id: call.id, side: 'buy', qty: 5, account: 'battle' }); + assert.equal(bacc.derivs[call.id].qty, 5); + // Battle „3 Aktien“: Basiswert muss erlaubt sein + bacc.rules = { symbols: ['VOLT'] }; + assert.throws(() => g.placeDeriv(a, { id: call.id, side: 'buy', qty: 1, account: 'battle' }), /Battle nur erlaubt/); + // Massenhandel: höchstens DERIV.perMinute Orders je Minute + const t = prods(g, 'OEL', 'long')[0]; + let err = null; + for (let i = 0; i < DERIV.perMinute + 2 && !err; i++) { try { g.placeDeriv(a, { id: t.id, side: 'buy', qty: 1 }); } catch (e) { err = e; } } + assert.match(err?.message ?? '', /pro Minute/); + // Einsatzgrenze je Basiswert + g.derivs.rate.clear(); + a.cash = 1e6; + const gold = prods(g, 'GOLD', 'call'); + assert.throws(() => { for (const x of gold) g.placeDeriv(a, { id: x.id, side: 'buy', qty: Math.floor(20_000 / g.derivs.quote(x).ask) }); }, /je Basiswert/); +}); + +test('Saisonende: alles zum Geldkurs ausgebucht, danach leeres Depot', async () => { + const ctx = setup(); + const { g } = ctx; + const a = await player(g, 'Saisonschluss'); + toContinuous(ctx); + const c = prods(g, IDX, 'call')[3], t = prods(g, 'WIBC', 'short')[0]; + g.placeDeriv(a, { id: c.id, side: 'buy', qty: 300, ack: true }); + g.placeDeriv(a, { id: t.id, side: 'buy', qty: 100 }); + const expect = a.cash + 300 * g.derivs.quote(c).bid + 100 * g.derivs.quote(t).bid; + const eq = g.equity(a); + near(eq, expect, 1e-6); + g.derivs.liquidateAll('season'); + near(a.cash, expect, 1e-6); + assert.deepEqual(a.derivs, {}); + assert.ok(g.pendingFills.filter((f) => f.kind === 'derivSeason').length === 2); + g.placeDeriv(a, { id: c.id, side: 'buy', qty: 10 }); + g.endSeason(); + assert.deepEqual(a.derivs, {}, 'neue Saison: keine Hebelprodukte'); + assert.equal(a.cash, g.cfg.startCash); +}); + +test('Alter Spielstand ohne Hebelprodukte: Produkte werden beim Laden erzeugt, Positionen bleiben erhalten', async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-dv-old-')); + const ctx = setup(dir); + const a = await player(ctx.g, 'Altspieler'); + toContinuous(ctx); + const c = prods(ctx.g, 'NVLT', 'call')[2]; + ctx.g.placeDeriv(a, { id: c.id, side: 'buy', qty: 20, ack: true }); + a.derivs.WHZZZZ = { qty: 10, avgCost: 1.5 }; // Produkt, das es nicht mehr gibt + ctx.g.markDirty(a); + ctx.g.flush(true); + // Neustart mit Emittentendaten: Position bleibt + const g2 = new Game({ store: new Store(dir), now: () => ctx.clock.t }); + const a2 = g2.byName('Altspieler'); + assert.equal(a2.derivs[c.id].qty, 20); + assert.equal(g2.derivs.products.get(c.id).strike, c.strike); + assert.equal(a2.derivs.WHZZZZ, undefined, 'unbekanntes Produkt: Einsatz erstattet'); + near(a2.cash, a.cash + 15, 1e-6); + // Spielstand von vor den Hebelprodukten (keine Metadaten, Spieler ohne derivs) + const dir2 = fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-dv-old2-')); + const st = new Store(dir2); + const g3 = new Game({ store: st, now: () => ctx.clock.t }); + const b = await player(g3, 'Veteran'); + delete b.derivs; + g3.markDirty(b); + g3.flush(true); + st.db.prepare('DELETE FROM meta WHERE key = ?').run('derivs'); + const g4 = new Game({ store: new Store(dir2), now: () => ctx.clock.t }); + assert.ok(g4.derivs.products.size > 300, 'Produkte erzeugt'); + const b4 = g4.byName('Veteran'); + assert.equal(b4.derivs, undefined); + assert.equal(g4.portfolio(b4).derivs.length, 0); + near(g4.equity(b4), b4.cash, 1e-6); +}); diff --git a/server/src/game.js b/server/src/game.js index 7bcc527..69cf68e 100644 --- a/server/src/game.js +++ b/server/src/game.js @@ -39,6 +39,7 @@ import { Sessions, hashPw, checkPw } from './auth.js'; import { ACHIEVEMENTS, checkAchievements } from './achievements.js'; import * as reports from './reports.js'; import { Todos } from './todo.js'; +import { Derivs } from './derivatives.js'; import { rnd, clamp, fmt, uid, cleanText, safeUrl } from './util.js'; const DAY = 86_400_000; @@ -152,6 +153,9 @@ export class Game { if (!this.season.scenario) this.season.scenario = { id: 'normal', title: SCENARIOS.normal.title, desc: SCENARIOS.normal.desc, done: [] }; for (const p of this.players.values()) this.#migratePlayer(p); + // Hebelprodukte des Emittenten (alte Spielstände: werden beim Laden erzeugt) + this.derivs = new Derivs(this, meta.derivs); + this.derivs.init(); // Orders wiederherstellen (Buch + bedingte Orders) for (const o of data.orders) { @@ -228,7 +232,7 @@ export class Game { assets: { foreignRate: this.assets.foreignRate }, corp: this.corp.snapshot(), credit: this.credit.snapshot(), gov: this.gov.snapshot(), pol: this.pol.snapshot(), bat: this.bat.snapshot(), prog: this.prog.snapshot(), clubs: this.clubs.snapshot(), tour: this.tour.snapshot(), rivals: this.rivals.snapshot(), ipo: this.ipo.snapshot(), agm: this.agm.snapshot(), predict: this.predict.snapshot(), after: this.after.snapshot(), analyses: this.analyses.snapshot(), causes: this.causes.snapshot(), pop: this.pop.snapshot(), - ex: { nextCondId: this.ex.nextCondId, marketHaltLevel: this.ex.marketHaltLevel }, + ex: { nextCondId: this.ex.nextCondId, marketHaltLevel: this.ex.marketHaltLevel }, derivs: this.derivs.snapshot(), }; } @@ -281,7 +285,7 @@ export class Game { const c = this.cfg.startCash; return { cash: c, positions: {}, realized: 0, fees: 0, trades: 0, peakEquity: c, wasDown20: false, locked: false, - recalls: [], borrowAccrued: 0, dayStartEquity: c, weekStartEquity: c, eqHist: [], marginWarned: false, dayStats: null, + recalls: [], borrowAccrued: 0, derivs: {}, dayStartEquity: c, weekStartEquity: c, eqHist: [], marginWarned: false, dayStats: null, }; } @@ -445,8 +449,14 @@ export class Game { ownerOf(acc) { return acc.owner ?? acc.id; } allAccounts() { return [...this.players.values(), ...this.battleAccounts.values()]; } /** Depotwert; beim Hauptdepot zählen Clan-Fondsanteile mit (Ranglisten, Saisonrendite) – Margin nicht */ - equity(acc) { return equityOf(acc, this.priceOf) + (acc.owner ? 0 : this.clubs?.unitsValue(acc.id) ?? 0); } - margin(acc) { return marginInfo(acc, this.priceOf, this.cfg); } + equity(acc) { return equityOf(acc, this.priceOf) + (this.derivs?.value(acc) ?? 0) + (acc.owner ? 0 : this.clubs?.unitsValue(acc.id) ?? 0); } + /** Margin: Hebelprodukte zählen zum Eigenkapital (zum Geldkurs), aber nicht als Sicherheit für Leerverkäufe */ + margin(acc) { + const m = marginInfo(acc, this.priceOf, this.cfg); + const dv = acc.derivs && this.derivs ? this.derivs.value(acc) : 0; + if (dv) { m.equity += dv; m.derivValue = dv; } + return m; + } /** frei verfügbares Geld: Kaufkraft (ohne gebundene Leerverkaufserlöse) abzüglich offener Kauforders */ freeCash(acc) { return this.margin(acc).buyingPower - this.ex.reserved(acc).cash; } @@ -493,6 +503,7 @@ export class Game { positions, orders, cond, compliance: isMain ? acc.compliance : undefined, rank: isMain ? this.prog.rankOf(acc.id) : null, minTradesRanked: this.cfg.minTradesRanked, watch: isMain ? acc.watch ?? [] : undefined, alerts: isMain ? acc.alerts ?? [] : undefined, + derivs: this.derivs.positions(acc), derivValue: m.derivValue ?? 0, }; } @@ -501,17 +512,21 @@ export class Game { * z. B. nach Verbindungsabbruch ohne Antwort – erkannt: Statt erneut zu platzieren, kommt die gespeicherte * Antwort (mit `duplicate: true`) zurück. Abgelehnte Orders werden nicht gespeichert und dürfen erneut versucht werden. */ - placeOrder(p, o) { + placeOrder(p, o) { return this.#dedup(p, o, () => this.ex.place(p, o)); } + /** Hebelprodukt beim Emittenten kaufen/verkaufen – mit derselben clientId-Erkennung wie Orders */ + placeDeriv(p, o) { return this.#dedup(p, o, () => this.derivs.order(p, o), 'd:'); } + + #dedup(p, o, run, ns = '') { if (p.banned) throw new Error('Konto gesperrt'); - const cid = typeof o?.clientId === 'string' && CLIENT_ID_RE.test(o.clientId) ? o.clientId : null; - if (!cid) return this.ex.place(p, o); + const cid = typeof o?.clientId === 'string' && CLIENT_ID_RE.test(o.clientId) ? ns + o.clientId : null; + if (!cid) return run(); const t = this.clock.now(); let seen = this.orderClientIds.get(p.id); if (!seen) { seen = new Map(); this.orderClientIds.set(p.id, seen); } for (const [k, e] of seen) { if (t - e.ts > CLIENT_ID_TTL) seen.delete(k); else break; } // Einfügereihenfolge = zeitlich const hit = seen.get(cid); if (hit) return { ...hit.order, duplicate: true }; - const order = this.ex.place(p, o); + const order = run(); seen.set(cid, { ts: t, order }); while (seen.size > CLIENT_ID_KEEP) seen.delete(seen.keys().next().value); return order; @@ -558,6 +573,7 @@ export class Game { this.#phaseMachine(now); this.econ.step(dt, this.market.phase === 'continuous', this.afterHours()); this.ex.tick(dt); + try { this.derivs.tick(); } catch (e) { console.warn('[hebel]', e.message); } this.gov.tick(); this.pol.tick(); this.bat.tick(); @@ -648,6 +664,7 @@ export class Game { } this.ex.onNewDay(); this.econ.newDay(); + try { this.derivs.onNewDay(); } catch (e) { console.warn('[hebel]', e.message); } this.gov.newDay(); this.pol.newDay(); try { this.pop.newDay(); } catch (e) { console.warn('[bevoelkerung]', e.message); } @@ -685,6 +702,7 @@ export class Game { try { this.store.recordBar({ symbol: s.symbol, day: this.day, ts: now, o: s.open, h: s.high, l: s.low, c: s.close, v: s.volume }); } catch (e) { console.warn('[store]', e.message); } } this.ex.onDayClose(); + try { this.derivs.onClose(); } catch (e) { console.warn('[hebel]', e.message); } this.market.lastCloseAt = now; this.#setPhase('closed'); this.prog.dayClose(); @@ -701,6 +719,7 @@ export class Game { // ================================================================ Saison endSeason() { + this.derivs.liquidateAll('season'); // Hebelprodukte zum Geldkurs ausbuchen, bevor Depotwerte gewertet werden this.clubs.seasonEnd(); // Fonds auflösen und auszahlen, bevor Rückblicke erstellt und Depots zurückgesetzt werden const recaps = this.prog.seasonEnd(); this.bat.cancelAllRunning(); @@ -923,7 +942,7 @@ export class Game { } /** Ereigniskalender: Zahlen, Ex-Tage, Konjunkturdaten, Zinsentscheid, Abstimmungsende, Saisonende */ - calendar() { + calendar(p = null) { const now = this.clock.now(); const cfg = this.cfg; const items = []; @@ -972,6 +991,17 @@ export class Game { if (['preopen', 'opening'].includes(this.market.phase)) items.push({ ts: st.openAt, kind: 'auction', title: 'Eröffnungsauktion' }); if (['preopen', 'opening', 'continuous'].includes(this.market.phase)) items.push({ ts: st.closeAt, kind: 'auction', title: 'Schlussauktion' }); items.push({ ts: this.season.endsAt, kind: 'season', title: `Ende Saison ${this.season.n}` }); + if (p) { + // eigene Optionsscheine: Fälligkeit (Barausgleich zum Schlusskurs) + for (const acc of [p, ...[...this.battleAccounts.values()].filter((a) => a.owner === p.id)]) { + for (const [id, pos] of Object.entries(acc.derivs ?? {})) { + const d = this.derivs.products.get(id); + if (!d || d.status !== 'active' || !d.expDay || !(pos.qty > 0)) continue; + const k = d.expDay - this.day; + items.push({ ts: at(k), dayIn: k, kind: 'expiry', symbol: d.u === 'WIBO10' ? undefined : d.u, title: `Fälligkeit ${this.derivs.name(d)}`, detail: `${pos.qty} Stück${acc !== p ? ' (Battle-Depot)' : ''} · Barausgleich zum Schlusskurs` }); + } + } + } items.sort((a, b) => a.ts - b.ts); return { items: items.filter((i) => i.ts >= now - 3_600_000).slice(0, 60), day: this.day, reportingSeason: this.reportingSeason(), now }; } @@ -980,7 +1010,7 @@ export class Game { briefing(p) { const since = this.market.lastCloseAt || Date.now() - DAY; const news = this.news.filter((n) => n.ts >= since).sort((a, b) => Math.abs(b.sentiment ?? 0) - Math.abs(a.sentiment ?? 0)).slice(0, 10); - const cal = this.calendar(); + const cal = this.calendar(p); const today = cal.items.filter((i) => (i.dayIn ?? 0) <= 0 && i.ts < Date.now() + DAY); const holdings = p ? Object.entries(p.positions).filter(([, x]) => x.qty !== 0).map(([sym, x]) => { const s = this.stocks.get(sym); diff --git a/server/src/index.js b/server/src/index.js index 12b3d30..2f6bb02 100644 --- a/server/src/index.js +++ b/server/src/index.js @@ -211,7 +211,7 @@ setInterval(() => { const now = Date.now(); for (const [k, b] of playerBuckets) /** Nur lesende Aktionen – alle anderen sind gegen doppelte Zustellung derselben reqId geschützt */ const READ_ONLY = new Set(['portfolio', 'journal', 'company', 'chart', 'curve', 'candles', 'calendar', 'briefing', 'leaderboard', 'regulator', 'parliament', 'government', 'battles', 'liveBattles', 'quests', 'league', 'inbox', 'profile', 'friends', 'comments', 'clans', 'clan', - 'tournaments', 'me', 'ipoList', 'agmList', 'predictList', 'plan', 'analyses', 'population', 'todo']); + 'tournaments', 'me', 'ipoList', 'agmList', 'predictList', 'plan', 'analyses', 'population', 'todo', 'derivs', 'derivQuote']); const REPLAY_KEEP = 100; const MAX_CONN_PER_PLAYER = 10; /** @type {Record any>} */ @@ -230,7 +230,11 @@ const ACTIONS = { curve: () => ({ curve: game.assets.curve() }), tender: (p, m) => ({ offer: game.corp.tender(need(p), String(m.symbol), m.qty) }), candles: (p, m) => { const s = game.stocks.get(String(m.symbol)); if (!s) throw new Error('Unbekannt'); return { candles: s.candles }; }, - calendar: () => ({ calendar: game.calendar() }), + calendar: (p) => ({ calendar: game.calendar(p ?? null) }), + // Hebelprodukte (Optionsscheine, Turbos) – Handel nur mit dem Emittenten + derivs: (p, m) => ({ derivs: game.derivs.list(String(m.symbol ?? ''), p ?? null) }), + derivQuote: (p, m) => ({ deriv: game.derivs.detail(m.id, p ?? null) }), + derivOrder: (p, m) => ({ order: game.placeDeriv(need(p), { id: m.id, side: m.side, qty: m.qty, account: m.account, limit: m.limit, ack: m.ack === true, clientId: m.clientId }) }), briefing: (p) => ({ briefing: game.briefing(p) }), leaderboard: () => ({ leaderboard: game.prog.leaderboard() }), ipoList: (p) => ({ ipo: game.ipo.view(p) }), @@ -627,6 +631,7 @@ wss.on('connection', (ws, req) => { } } catch (e) { if (e.humanCheck) { if (p) sendTo(p.id, { type: 'humanCheck', nonce: e.humanCheck }); return reply(false, { error: e.message, humanCheck: e.humanCheck }); } + if (e.needAck) return reply(false, { error: e.message, needAck: true }); (replayKey ? remember : reply)(false, { error: e.message }); } });