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.` : ''}
| Wert | Seite | Typ | Limit | Ausgeführt | Gültig | Status | Aktion |
|---|
Keine offenen Orders.
'}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 `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 ? `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 `| Keine Produkte für diesen Filter. |
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 `${scenario(x, x)}
Risiko: ${esc(RISK_TEXT)}
+ +${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)}
${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 `| Produkt | Stück | Ø Einstand | Geld | Wert | G/V | Hebel | Fälligkeit / Knock-out | Aktionen |
|---|
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.
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