Files
wibosim/server/src/ipo.js
T
db9979andClaude Opus 5.5 915f0d37cb 0.13.0: Feierabend – Abendhandel, Hauptversammlungen, Tippspiel, Plan & Analysen
- Abend- und Wochenendhandel über einen Market Maker (Spread, Größenlimit, Abendkurs als Eröffnungstendenz)
- Hauptversammlungen mit Abstimmungen über Dividende, Rückkauf, Kapitalerhöhung und Vergütung
- Prognose-Tippspiel für den nächsten Handelstag mit Rangliste
- Plan für den nächsten Handelstag, Watchlist, Kursalarme, Wochenrückblick
- Analysen mit Likes, Auswertung und Analysten-Rangliste
- Parlamentsabstimmungen enden abends, Wahlkampf am Wochenende, TV-Duell
- Clan-Wochenziel, Krypto-Wochenende, Börsengänge bevorzugt Do/Fr
- Fixes: Aktien-Links, Speicherung von Trailing-Stops und Dividendenanpassungen

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUhQVoPUusUzxgxLWkK
2026-12-03 21:37:08 +00:00

287 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Börsengänge (IPOs): neue, fiktive Unternehmen kommen während der Saison an die Börse.
// – Auslöser: Zufall (etwa alle paar Handelstage), Admin-Menü, oder eine echte Meldung über einen Börsengang
// („… plant Börsengang“, „IPO“, „Börsendebüt“). Dann geht in Wiborien ein fiktives Unternehmen derselben Branche
// an die Börse – nie das echte Unternehmen aus der Meldung.
// – Zeichnungsfrist über einige Handelstage mit Preisspanne. Spieler (und Rivalen) zeichnen eine Stückzahl; der
// Höchstbetrag (oberes Ende der Spanne) wird so lange als Kaufkraft reserviert.
// – Preisfindung nach Nachfrage (Spieler, Rivalen, Institutionelle): hohe Überzeichnung → oberes Ende der Spanne.
// Zu wenig Nachfrage → der Börsengang wird abgesagt. Bei Überzeichnung wird anteilig zugeteilt.
// – Erstnotiz in der Eröffnungsauktion des Listing-Tags. Der „faire“ Wert des Unternehmens ist nicht bekannt –
// erste Kurse können deutlich über oder unter dem Ausgabepreis liegen.
import { SECTORS, SECTOR_OF } from './world.js';
import { updateAnalysts } from './fundamentals.js';
import { analyze } from './newsanalysis.js';
import { rnd, clamp, uid, gauss, fmt, cleanText } from './util.js';
const pick = (a) => a[Math.floor(Math.random() * a.length)];
const r2 = (x) => Math.round(x * 100) / 100;
// Namensbausteine je Branche (fiktiv)
const NAMES = {
tech: [['Datalux', 'Cloudberg', 'Quantor', 'Bitwerk', 'Synapta', 'Neuronix', 'Codehain', 'Lumetra'], ['AG', 'SE', 'Systems AG', 'Technologies SE']],
energy: [['Solaris Nord', 'Gezeitenkraft', 'Erdwärme Süd', 'Batteriewerk Lausitz', 'Sonnenfeld', 'Netzbau Mitte'], ['AG', 'Energie AG', 'SE']],
auto: [['Elektra Mobil', 'Akkuwerk', 'Fahrwerk Hessen', 'Ladepunkt', 'Autonova'], ['AG', 'SE', 'Motoren AG']],
banks: [['Neobank Wiborien', 'Zinshaus', 'Kreditwerk', 'Depotfix', 'Versicherungsring'], ['AG', 'SE', 'Holding']],
pharma: [['Genovia', 'Zellkraft', 'Medicura', 'Immunexa', 'Pharmalind'], ['Therapeutics', 'AG', 'Biotech SE']],
consumer: [['Feinkost Lindner', 'Modehaus Weber', 'Frischkiste', 'Spielwaren Kranich', 'Kaffeerösterei Ahorn'], ['AG', 'SE', 'Gruppe AG']],
industry: [['Präzisionswerk', 'Drohnenbau Ost', 'Lasertechnik Rhein', 'Kranbau Nord', 'Pumpenwerk Saar'], ['AG', 'SE', 'Industrie AG']],
defense: [['Schutzsysteme Nord', 'Satcom Alpen', 'Radarwerk', 'Cyberwehr'], ['AG', 'SE', 'Defence AG']],
};
const DESC = {
tech: 'Junges Technologieunternehmen mit Software und Hardware für Industrie und Verbraucher.',
energy: 'Baut und betreibt Anlagen für erneuerbare Energie und Speicher.',
auto: 'Entwickelt Antriebe, Batterien und Mobilitätsdienste.',
banks: 'Digitaler Finanzdienstleister mit Konten, Krediten und Versicherungen.',
pharma: 'Forscht an neuen Wirkstoffen; die Zulassung der wichtigsten Mittel steht noch aus.',
consumer: 'Markenhersteller und Händler mit treuer Kundschaft.',
industry: 'Mittelständischer Maschinen- und Anlagenbauer mit Exportgeschäft.',
defense: 'Zulieferer für Verteidigung, Satelliten und Sicherheitstechnik.',
};
const HQ = ['Kassel', 'Rostock', 'Potsdam', 'Würzburg', 'Regensburg', 'Kiel', 'Magdeburg', 'Erfurt', 'Saarbrücken', 'Osnabrück', 'Heilbronn', 'Paderborn'];
// Kennzahlen je Branche: [Volatilität, Wachstum, Ausschüttung]
const PROFILE = {
tech: [0.5, 0.25, 0], energy: [0.38, 0.12, 0.2], auto: [0.45, 0.18, 0], banks: [0.4, 0.15, 0.2],
pharma: [0.55, 0.28, 0], consumer: [0.28, 0.06, 0.4], industry: [0.33, 0.08, 0.3], defense: [0.36, 0.14, 0.2],
};
// Meldung über einen Börsengang (echte Nachrichten)
const IPO_RE = /\b(börsengang|börsengänge|börsengangs|ipo|börsendebüt|erstnotiz|börsenneuling|geht an die börse|gang an die börse|an die börse gehen|aufs parkett)\b/i;
export class Ipo {
constructor(g, saved) {
this.g = g;
this.state = { pending: [], listed: [], history: [], lastNewsAt: 0, nextDay: null, ...(saved ?? {}) };
}
get cfg() { return this.g.cfg; }
snapshot() { return this.state; }
get pending() { return this.state.pending; }
// ================================================================ Ankündigen
/**
* Neuen Börsengang ankündigen. opts: {sector, name, source: 'auto'|'admin'|'news', news: Schlagzeile}
* Liefert die Ankündigung oder wirft, wenn gerade nicht möglich.
*/
announce(opts = {}) {
const g = this.g, cfg = this.cfg;
if (this.pending.filter((x) => x.status === 'signup').length >= 2) throw new Error('Es laufen bereits zwei Börsengänge');
const stocks = [...g.stocks.values()].filter((s) => s.kind === 'stock').length + this.pending.filter((x) => x.status === 'signup').length;
if (stocks >= cfg.ipoMaxStocks) throw new Error(`Höchstzahl von ${cfg.ipoMaxStocks} Aktien erreicht`);
const sector = Object.hasOwn(SECTORS, opts.sector ?? '') ? opts.sector : this.#quietSector();
const name = opts.name ? cleanText(opts.name, 40) : this.#name(sector);
if (!name || name.length < 3) throw new Error('Ungültiger Name');
if ([...g.stocks.values()].some((s) => s.name.toLowerCase() === name.toLowerCase()) || this.pending.some((x) => x.name === name)) throw new Error('Name ist bereits vergeben');
const symbol = this.#symbol(name);
const [vol, growth, payout] = PROFILE[sector];
const mid = r2(rnd(12, 90));
const ipo = {
id: uid(4), symbol, name, sector, source: opts.source ?? 'auto', news: opts.news ? cleanText(opts.news, 200) : null,
desc: DESC[sector], hq: pick(HQ), founded: 1990 + Math.floor(rnd(0, 34)), employees: Math.round(rnd(300, 9000) / 10) * 10,
vol: r2(vol * rnd(0.85, 1.2)), growth: r2(growth * rnd(0.7, 1.3)), payout,
lo: r2(mid * 0.9), hi: r2(mid * 1.1), totalShares: Math.round(rnd(0.6, 3) * 1e8 / 1e6) * 1e6,
// wahrer Wert: niemand kennt ihn – liegt um die Mitte der Spanne
fair: r2(mid * Math.exp(0.04 + gauss() * 0.15)),
announcedDay: g.day, closeDay: g.day + Math.max(1, cfg.ipoSignupDays), status: 'signup', orders: {}, ts: Date.now(),
};
ipo.offered = Math.round(ipo.totalShares * 0.25);
this.pending.push(ipo);
this.g.metaDirty = true;
const txt = ipo.source === 'news'
? `Börsengang in Wiborien: ${name} (${SECTORS[sector].name}) will an die Börse – Zeichnung bis Handelstag ${ipo.closeDay}`
: `${name} (${SECTORS[sector].name}) kündigt Börsengang an – Preisspanne ${fmt(ipo.lo)}–${fmt(ipo.hi)} €, Zeichnung bis Handelstag ${ipo.closeDay}`;
g.addNews({ id: `ipo-${ipo.id}`, title: txt, source: 'Börse', real: false, sentiment: 0, sectors: [sector], ts: Date.now(), ipo: ipo.id }, false);
g.log('market', txt);
g.broadcast({ type: 'ipo', ipo: this.publicView(ipo) });
return ipo;
}
#quietSector() {
// Branchen mit wenigen Werten bevorzugt
const n = {};
for (const s of this.g.stocks.values()) if (s.kind === 'stock') n[s.sector] = (n[s.sector] ?? 0) + 1;
const keys = Object.keys(SECTORS);
const w = keys.map((k) => 1 / (1 + (n[k] ?? 0)));
let r = Math.random() * w.reduce((a, b) => a + b, 0);
return keys.find((k, i) => (r -= w[i]) <= 0) ?? pick(keys);
}
#name(sector) {
const [a, b] = NAMES[sector];
const taken = new Set([...this.g.stocks.values()].map((s) => s.name).concat(this.pending.map((x) => x.name)));
for (let i = 0; i < 30; i++) { const n = `${pick(a)} ${pick(b)}`; if (!taken.has(n)) return n; }
return `${pick(a)} ${Math.floor(rnd(2, 99))} AG`;
}
#symbol(name) {
const letters = name.normalize('NFD').replace(/[^A-Za-z]/g, '').toUpperCase();
const used = new Set([...this.g.stocks.keys(), ...this.pending.map((x) => x.symbol)]);
const tries = [letters.slice(0, 4), letters.slice(0, 3) + letters.slice(-1), letters[0] + letters.slice(2, 5)];
for (const t of tries) if (t.length === 4 && !used.has(t)) return t;
for (let i = 0; i < 100; i++) { const t = letters.slice(0, 2) + String.fromCharCode(65 + Math.floor(Math.random() * 26), 65 + Math.floor(Math.random() * 26)); if (!used.has(t)) return t; }
return `I${uid(2).toUpperCase().slice(0, 3)}`;
}
/** echte Meldung über einen Börsengang? → fiktiver Börsengang derselben Branche (höchstens einer je 12 Stunden) */
onNews(n) {
if (!this.cfg.ipoFromNews || !n?.real) return;
const text = `${n.title} ${n.desc ?? ''}`;
if (!IPO_RE.test(text)) return;
if (Date.now() - this.state.lastNewsAt < 12 * 3_600_000) return;
const sector = n.sectors?.[0] ?? analyze(n.title, n.desc ?? '').sectors?.[0];
try {
this.announce({ sector, source: 'news', news: n.title });
this.state.lastNewsAt = Date.now();
} catch { /* gerade nicht möglich */ }
}
// ================================================================ Zeichnen
/** Kaufkraft, die für Zeichnungen reserviert ist (Höchstpreis inkl. Gebühr) */
hold(acc) {
let sum = 0;
for (const x of this.pending) if (x.status === 'signup' && x.orders[acc.id]) sum += x.orders[acc.id] * x.hi * (1 + this.cfg.feeRate);
return sum;
}
subscribe(p, id, qty) {
const x = this.pending.find((i) => i.id === String(id ?? ''));
if (!x || x.status !== 'signup') throw new Error('Diese Zeichnung ist nicht (mehr) offen');
qty = Math.floor(Number(qty));
if (!(qty >= 0 && qty <= x.offered)) throw new Error('Ungültige Stückzahl');
const prev = x.orders[p.id] ?? 0;
if (qty > prev) {
const extra = (qty - prev) * x.hi * (1 + this.cfg.feeRate);
if (extra > this.g.freeCash(p) + 1e-6) throw new Error(`Nicht genug Kaufkraft: reserviert wird der Höchstpreis ${fmt(x.hi)} € je Aktie`);
}
if (qty === 0) delete x.orders[p.id]; else x.orders[p.id] = qty;
this.g.markDirty(p);
this.g.metaDirty = true;
return this.publicView(x, p);
}
// ================================================================ Takt
/** Vorbörse eines neuen Handelstags: Zeichnungsschluss, Zuteilung, Erstnotiz; ggf. neuer Börsengang */
newDay() {
const g = this.g, cfg = this.cfg;
for (const x of this.pending) if (x.status === 'signup' && g.day >= x.closeDay) this.#close(x);
this.state.pending = this.pending.filter((x) => x.status === 'signup');
if (!cfg.ipoEnabled || cfg.ipoEveryDays <= 0) return;
this.state.nextDay ??= g.day + Math.round(cfg.ipoEveryDays * rnd(0.5, 1.5));
// Echtzeit: automatische Börsengänge bevorzugt Do/Fr ankündigen – die Zeichnungsfrist läuft dann übers Wochenende
const wd = g.clock.turbo ? null : (new Date(Date.UTC(...g.clock.localDay().day.split('-').map((x, i) => Number(x) - (i === 1 ? 1 : 0)))).getUTCDay() + 6) % 7;
if (g.day >= this.state.nextDay && (wd === null || wd >= 3 || g.day >= this.state.nextDay + 3)) {
this.state.nextDay = g.day + Math.round(cfg.ipoEveryDays * rnd(0.6, 1.4));
try { this.announce({ source: 'auto' }); } catch { /* Höchstzahl erreicht o. ä. */ }
}
}
/** Rivalen zeichnen (aus rivals.js) */
rivalOrders() {
for (const x of this.pending) {
if (x.status !== 'signup') continue;
for (const p of this.g.rivals?.active() ?? []) {
if (p.id in x.orders || p.rival.mem[`ipo:${x.id}`]) continue;
p.rival.mem[`ipo:${x.id}`] = true;
const c = this.g.rivals.character(p);
const like = { momentum: 0.8, news: 0.6, politics: 0.5, value: 0.4, contra: 0.3, macro: 0.25, income: x.payout > 0.2 ? 0.4 : 0.1, index: 0.15 }[c.style] ?? 0.3;
if (Math.random() > like) continue;
const qty = Math.floor((this.g.freeCash(p) * rnd(0.03, 0.1)) / (x.hi * 1.01));
if (qty > 0) { try { this.subscribe(p, x.id, Math.min(qty, Math.floor(x.offered * 0.05))); } catch { /* egal */ } }
}
}
}
#close(x) {
const g = this.g, cfg = this.cfg;
// Nachfrage: Spieler (nur, was sie noch bezahlen können) + Institutionelle (abhängig von Branchenstimmung und Markt)
const want = {};
for (const [pid, q] of Object.entries(x.orders)) {
const acc = g.players.get(pid);
if (!acc) continue;
want[pid] = Math.min(q, Math.floor(Math.max(0, acc.cash) / (x.lo * (1 + cfg.feeRate))));
}
const retail = Object.values(want).reduce((a, b) => a + b, 0);
const mood = (g.macro.sectorMood[x.sector] ?? 0) * 0.6 + g.macro.sentiment * 0.4;
const inst = x.offered * Math.max(0, rnd(0.4, 2.2) * Math.exp(mood) * Math.exp(Math.log(x.fair / ((x.lo + x.hi) / 2)) * 2));
const ratio = (retail + inst) / x.offered;
x.ratio = r2(ratio);
x.orders = {}; // Reservierungen freigeben (vor der Zuteilung)
if (ratio < 0.6) {
x.status = 'cancelled';
const txt = `Börsengang von ${x.name} abgesagt – zu wenig Nachfrage (${Math.round(ratio * 100)} % des Angebots gezeichnet)`;
g.addNews({ id: `ipo-c-${x.id}`, title: txt, source: 'Börse', real: false, sentiment: -0.1, sectors: [x.sector], ts: Date.now() }, false);
g.log('market', txt);
for (const pid of Object.keys(want)) g.notify(pid, { kind: 'ipo', title: `Börsengang ${x.name} abgesagt`, text: 'Deine Zeichnung ist hinfällig, die reservierte Kaufkraft ist wieder frei.' });
this.state.history.unshift({ ...this.#summary(x), ts: Date.now() });
this.state.history = this.state.history.slice(0, 20);
g.broadcast({ type: 'ipo', ipo: this.publicView(x) });
return;
}
x.price = r2(x.lo + (x.hi - x.lo) * clamp((ratio - 0.8) / 1.7, 0, 1));
// Kleinanleger-Tranche: höchstens 30 % des Angebots; bei Überzeichnung anteilig (mind. 1 Stück)
const tranche = Math.floor(x.offered * 0.3);
const quota = retail > tranche ? tranche / retail : 1;
x.allocated = {};
for (const [pid, q] of Object.entries(want)) {
const acc = g.players.get(pid);
let got = Math.floor(q * quota);
if (q > 0 && got === 0) got = 1;
got = Math.min(got, Math.floor(Math.max(0, acc.cash) / (x.price * (1 + cfg.feeRate))));
if (got <= 0) continue;
const cost = got * x.price, fee = cost * cfg.feeRate;
acc.cash -= cost + fee;
acc.fees = (acc.fees ?? 0) + fee;
const pos = (acc.positions[x.symbol] ??= { qty: 0, avgCost: 0 });
pos.avgCost = (pos.avgCost * pos.qty + cost) / (pos.qty + got);
pos.qty += got;
acc.trades = (acc.trades ?? 0) + 1;
g.markDirty(acc);
x.allocated[pid] = got;
g.notify(pid, { kind: 'ipo', title: `Zuteilung ${x.name}: ${got} Aktien`, text: `${got} von ${q} gezeichneten Aktien zu ${fmt(x.price)} € (${Math.round(quota * 100)} %). Erster Handel heute in der Eröffnungsauktion.` });
}
for (const pid of Object.keys(want)) if (!x.allocated[pid]) g.notify(pid, { kind: 'ipo', title: `Keine Zuteilung bei ${x.name}`, text: 'Der Börsengang war stark überzeichnet oder dein Guthaben reichte nicht.' });
this.#list(x);
}
#list(x) {
const g = this.g;
const def = {
symbol: x.symbol, name: x.name, sector: x.sector, price: x.fair, shares: x.totalShares, vol: x.vol, growth: x.growth,
...(x.payout === 0 ? { payout: 0 } : {}), desc: x.desc, founded: x.founded, hq: x.hq, employees: x.employees,
ipo: { day: g.day, price: x.price, ratio: x.ratio, news: x.news },
};
const s = g.makeStock({ kind: 'stock', ...def });
s.fund = g.econ.init(s, g.stocks.size);
// Ausgabepreis als Referenz; der faire Wert liegt irgendwo drumherum (Erstnotiz klärt es)
Object.assign(s, { last: x.price, prevClose: x.price, close: x.price, open: x.price, high: x.price, low: x.price, refAuction: x.price, seeded: true });
g.stocks.set(s.symbol, s);
SECTOR_OF[s.symbol] = s.sector;
s.fv = g.econ.fv(s);
s.fair = x.price * Math.exp(Math.log(s.fv / x.price) * 0.6);
s.hDay = 2.5; // erste Handelstage schwanken stärker
updateAnalysts(s, s.fv);
x.status = 'listed';
this.state.listed.push(def);
this.state.history.unshift({ ...this.#summary(x), ts: Date.now() });
this.state.history = this.state.history.slice(0, 20);
const txt = `Erstnotiz: ${x.name} (${x.symbol}) startet heute an der Börse – Ausgabepreis ${fmt(x.price)} €, ${x.ratio.toFixed(1).replace('.', ',')}-fach gezeichnet`;
g.addNews({ id: `ipo-l-${x.id}`, title: txt, source: 'Börse', real: false, sentiment: 0.05, sectors: [x.sector], symbol: x.symbol, ts: Date.now() }, false);
g.log('market', txt);
g.metaDirty = true;
g.broadcast({ type: 'ipo', ipo: this.publicView(x), listed: true });
}
#summary(x) { return { id: x.id, name: x.name, symbol: x.symbol, sector: x.sector, status: x.status, price: x.price ?? null, lo: x.lo, hi: x.hi, ratio: x.ratio ?? null, source: x.source }; }
// ================================================================ Ansichten
publicView(x, viewer = null) {
return {
id: x.id, symbol: x.symbol, name: x.name, sector: x.sector, sectorName: SECTORS[x.sector]?.name, desc: x.desc, hq: x.hq, founded: x.founded, employees: x.employees,
lo: x.lo, hi: x.hi, offered: x.offered, totalShares: x.totalShares, growth: x.growth, payout: x.payout, closeDay: x.closeDay, announcedDay: x.announcedDay,
status: x.status, price: x.price ?? null, ratio: x.ratio ?? null, source: x.source, news: x.news,
subscribers: Object.keys(x.orders ?? {}).length, mine: viewer ? x.orders?.[viewer.id] ?? 0 : undefined,
};
}
view(viewer) {
return {
pending: this.pending.filter((x) => x.status === 'signup').map((x) => this.publicView(x, viewer)),
history: this.state.history.slice(0, 10), day: this.g.day,
};
}
}