Files
wibosim/server/src/ipo.js
T
db9979andClaude Opus 5.5 654eb2c439 main (0.44.0) eingeführt; Abspaltung, Fusion und Aktiensplit in der Prüf-Simulation
Konflikte gelöst (Börsenneuling ins Index-Segment auch für Abspaltungen, Steuerarten, Rückzugsgründe, Journal, Admin, Stil). Prüf-Simulation: Buchungsarten spinoff, spinoffCash, merger, mergerCash und split im Hauptbuch (Barausgleich als Feld cash, Split skaliert Bots und Gegenbuchungen), Ereignisse Split, Zusammenlegung, Abspaltung und Fusion, Logo-Prüfung kennt reservierte Abspaltungen. Kein Split während einer laufenden Abspaltung oder Fusion. Erfolgs-Haken mit den vereinbarten Feldern.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018i4GUhQVoPUusUzxgxLWkK
2026-12-04 22:34:59 +00:00

355 lines
22 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;
/** Liquidität nach Börsenwert: kleine Werte haben ein dünneres Orderbuch (wie Small Caps) */
export const liqFor = (mcap) => r2(Math.min(1, Math.max(0.45, (mcap / 1e10) ** 0.3)));
// 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']],
realestate: [['Wohnhof', 'Stadtquartier Ost', 'Hausgrund', 'Ziegelwert', 'Campuswohnen'], ['Immobilien AG', 'SE', 'Wohnen AG']],
utilities: [['Stadtwerke Talheim', 'Quellwasser Nord', 'Wärmering', 'Netzwerk Süd'], ['AG', 'Versorgung AG']],
telecom: [['Funkturm Mitte', 'Faserland', 'Netzfunk', 'Signalwerk'], ['AG', 'Telekom AG', 'SE']],
logistics: [['Frachtkontor', 'Hafenring', 'Kurierwerk', 'Lagerblick', 'Schienenfracht'], ['AG', 'Logistik AG', 'SE']],
media: [['Bildfunk', 'Serienwerk', 'Klangkiste', 'Tagblatt-Verlag'], ['AG', 'Medien AG', 'SE']],
materials: [['Kunststoffwerk Lahn', 'Mineralis', 'Erzhütte', 'Polymerwerk'], ['AG', 'Chemie AG', 'SE']],
health: [['Praxisverbund', 'Reha-Kliniken Bergland', 'Pflegestift', 'Medilabor'], ['AG', 'SE', 'Gesundheit 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.',
realestate: 'Entwickelt und vermietet Wohnungen und Gewerbeflächen in wachsenden Städten.',
utilities: 'Regionaler Versorger für Wasser, Wärme und Strom mit regulierten Netzen.',
telecom: 'Junger Netzbetreiber, der Glasfaser und Funkmasten ausbaut.',
logistics: 'Wachsender Logistikdienstleister für Paket, Lager und Fracht.',
media: 'Medienhaus mit Streaming, Podcasts und Werbevermarktung.',
materials: 'Hersteller von Spezialchemie und Werkstoffen für Industrie und Bau.',
health: 'Betreibt Praxen, Labore und Reha-Kliniken.',
};
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],
realestate: [0.32, 0.06, 0.6], utilities: [0.22, 0.04, 0.6], telecom: [0.34, 0.12, 0.2], logistics: [0.38, 0.12, 0.2], media: [0.45, 0.16, 0.1],
materials: [0.36, 0.08, 0.3], health: [0.34, 0.12, 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 = this.listedCount() + 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 (this.nameTaken(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);
// Logo aus dem Pool der Branche schon zur Zeichnung reservieren (bei Absage sofort wieder frei)
g.marks?.assign(symbol, sector);
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;
}
/** gelistete Aktien (ohne von der Börse genommene) */
listedCount() { return [...this.g.stocks.values()].filter((s) => s.kind === 'stock' && !s.delisted).length; }
/**
* Abstand automatischer Börsengänge: normal cfg.ipoEveryDays. Liegt die Zahl gelisteter Aktien (plus laufende
* Zeichnungen) unter dem Ziel cfg.ipoTargetStocks – etwa nach Rückzügen von der Börse –, kommen sie häufiger:
* Abstand ÷ (1 + Fehlbestand), mindestens 1 Handelstag.
*/
everyDays() {
const cfg = this.cfg;
const short = (cfg.ipoTargetStocks ?? 0) - this.listedCount() - this.pending.filter((x) => x.status === 'signup').length;
return short > 0 ? Math.max(1, Math.round(cfg.ipoEveryDays / (1 + short))) : cfg.ipoEveryDays;
}
#quietSector() {
// Branchen mit wenigen Werten bevorzugt
const n = {};
for (const s of this.g.stocks.values()) if (s.kind === 'stock' && !s.delisted) 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), this.g.spinoff?.reservedNames?.() ?? []));
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), ...(this.g.spinoff?.reservedSymbols?.() ?? [])]);
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;
const every = this.everyDays();
this.state.nextDay ??= g.day + Math.round(every * rnd(0.5, 1.5));
if (every < cfg.ipoEveryDays) this.state.nextDay = Math.min(this.state.nextDay, g.day + every); // Markt dünn: früher
// 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.max(1, Math.round(this.everyDays() * 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';
g.marks?.release(x.symbol, { immediate: true });
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;
// Buchung wie ein Kauf: Journal, Steuer (Gebühr als Anschaffungsnebenkosten), Meldeschwellen
g.recordFill({ ts: g.clock.now(), owner: pid, account: acc.id, symbol: x.symbol, side: 'buy', qty: got, price: x.price, fee, realized: 0, kind: 'ipo' });
g.markDirty(acc);
x.allocated[pid] = got;
g.achievements?.onEvent?.(acc, 'ipoSubscribed', { id: x.id, symbol: x.symbol, qty: got, price: x.price });
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,
// Liquidität nach Börsenwert: kleine Neulinge haben ein dünneres Orderbuch (wie Small Caps)
liq: liqFor(x.fair * x.totalShares),
...(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 },
};
// Ausgabepreis als Referenz; der faire Wert liegt irgendwo drumherum (Erstnotiz klärt es)
this.listStock(def, { price: x.price });
x.status = 'listed';
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.chronicle?.add?.(x.symbol, { kind: 'ipo', title: `Börsengang zu ${fmt(x.price)} €`, text: `${x.ratio.toFixed(1).replace('.', ',')}-fach gezeichnet, Preisspanne ${fmt(x.lo)}–${fmt(x.hi)} €`, data: { price: x.price } });
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 });
}
/**
* Neue Aktie in den Handel aufnehmen – gemeinsamer Weg für Börsengänge und Abspaltungen (spinoff.js).
* def: Stammdaten (werden in state.listed gespeichert, damit die Aktie nach einem Neustart wieder angelegt wird).
* opts: price = erster Kurs (Referenz der Eröffnungsauktion); fund = fertige Unternehmenszahlen (sonst aus dem Kurs
* erzeugt); fair = fairer Kurs (sonst zwischen Kurs und innerem Wert); hDay = Schwankungsfaktor der ersten Tage.
*/
listStock(def, { price, fund = null, fair = null, hDay = 2.5 } = {}) {
const g = this.g;
const s = g.makeStock({ kind: 'stock', ...def });
g.marks?.assign(def.symbol, def.sector); // Logo-Pool: Marke der Branche (meist schon bei der Ankündigung reserviert)
s.fund = fund ?? g.econ.init(s, g.stocks.size);
Object.assign(s, { last: price, prevClose: price, close: price, open: price, high: price, low: price, refAuction: price, seeded: true });
g.stocks.set(s.symbol, s);
SECTOR_OF[s.symbol] = s.sector;
g.indices?.onListed?.(s.symbol);
s.fv = g.econ.fv(s);
s.fair = fair ??price * Math.exp(Math.log(s.fv / price) * 0.6);
s.hDay = hDay; // erste Handelstage schwanken stärker
updateAnalysts(s, s.fv);
this.state.listed.push(def);
return s;
}
/** Freies Börsenkürzel für einen Namen (berücksichtigt laufende Börsengänge und angekündigte Abspaltungen) */
symbolFor(name) { return this.#symbol(name); }
/** Name schon vergeben (gelistet, Zeichnung oder angekündigte Abspaltung)? */
nameTaken(name) {
const n = String(name ?? '').toLowerCase();
return [...this.g.stocks.values()].some((s) => s.name.toLowerCase() === n) || this.pending.some((x) => x.name.toLowerCase() === n)
|| (this.g.spinoff?.reservedNames?.() ?? []).some((x) => x.toLowerCase() === n);
}
/** Zufälliger fiktiver Firmenname der Branche (wie bei Börsengängen) */
nameFor(sector) { return this.#name(sector); }
#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, mark: this.g.marks?.of(x.symbol) ?? null,
};
}
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,
};
}
}