mirror of
https://github.com/db9979/wibosim.git
synced 2026-12-06 13:34:09 +01:00
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
1431 lines
81 KiB
JavaScript
1431 lines
81 KiB
JavaScript
// Spielkern: hält den Zustand, verbindet die Module (Börse, Ökonomie, Politik, Aufsicht, Battles, Fortschritt,
|
||
// Soziales), steuert den Handelstag (Vorbörse → Eröffnungsauktion → fortlaufender Handel → Schlussauktion)
|
||
// und schreibt geänderte Daten pro Takt in EINER Transaktion in die Datenbank.
|
||
import { createHash, timingSafeEqual } from 'node:crypto';
|
||
import { settings } from './settings.js';
|
||
import { Clock, PHASE_LABELS, isTradingDate } from './calendar.js';
|
||
import { OrderBook, bumpOrderId } from './orderbook.js';
|
||
import { COMPANIES, SECTORS, MINISTRIES, INDEX_SYMBOLS, SECTOR_OF, createMacro } from './world.js';
|
||
import { INSTRUMENTS, ASSET_CLASSES, Assets, initAsset } from './assets.js';
|
||
import { Credit } from './credit.js';
|
||
import { streakText } from './fundamentals.js';
|
||
import { Corporate } from './corporate.js';
|
||
import { TOPICS, analyze as analyzeNews, fingerprint, similarity } from './newsanalysis.js';
|
||
import { NewsBudget, echoFactor } from './newsbudget.js';
|
||
import { Government } from './government.js';
|
||
import { SCENARIOS, applyScenario, pickScenario } from './scenarios.js';
|
||
import { Ipo } from './ipo.js';
|
||
import { MarkPool } from './markpool.js';
|
||
import { Agm } from './agm.js';
|
||
import { SeasonReview } from './seasonreview.js';
|
||
import { Predict } from './predict.js';
|
||
import { AfterHours } from './afterhours.js';
|
||
import { Analyses } from './analyses.js';
|
||
import { Causes } from './causes.js';
|
||
import { Population } from './population.js';
|
||
import { Energy } from './energy.js';
|
||
import { buildRange, rangeDays } from './chartrange.js';
|
||
import { epsTTM, payoutOf, updateAnalysts } from './fundamentals.js';
|
||
import { ARCHETYPES } from './bots.js';
|
||
import { equityOf, marginInfo } from './accounts.js';
|
||
import { Exchange, publicOrder, COND_LABEL } from './exchange.js';
|
||
import { Economy } from './economy.js';
|
||
import { Politics } from './politics.js';
|
||
import { Regulator, VIOLATIONS } from './regulator.js';
|
||
import { Battles } from './battles.js';
|
||
import { Progress, levelOf, TIERS } from './progress.js';
|
||
import { Social } from './social.js';
|
||
import { Messages } from './messages.js';
|
||
import { Invites } from './invites.js';
|
||
import { Clubs } from './clubs.js';
|
||
import { Tournaments } from './tournaments.js';
|
||
import { Rivals } from './rivals.js';
|
||
import { Sessions, hashPw, checkPw } from './auth.js';
|
||
import { ACHIEVEMENTS, checkAchievements, AchievementHooks } from './achievements.js';
|
||
import * as reports from './reports.js';
|
||
import { Todos } from './todo.js';
|
||
import { Derivs } from './derivatives.js';
|
||
import { Indices } from './indices.js';
|
||
import { ETFS, Etfs } from './etf.js';
|
||
import { Tax, freshTax } from './tax.js';
|
||
import { Holdings } from './holdings.js';
|
||
import { Delist } from './delist.js';
|
||
import { Spinoff } from './spinoff.js';
|
||
import { Merger } from './merger.js';
|
||
import { Splits, parseRatio, splitRatioFor, reverseRatioFor } from './splits.js';
|
||
import { Chronicle } from './chronicle.js';
|
||
import { rnd, clamp, fmt, uid, cleanText, safeUrl } from './util.js';
|
||
|
||
const DAY = 86_400_000;
|
||
const OPEN_CALL_MS = 10 * 60_000; // Aufrufphase der Eröffnungsauktion (Echtzeit)
|
||
const NAME_RE = /^[\p{L}\p{N} _.-]{3,20}$/u;
|
||
const MAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
|
||
const IP_SALT = uid(8);
|
||
const noop = () => {};
|
||
/** Zahl für die Marktdaten runden (jeder Takt an alle Clients – lange Nachkommastellen kosten nur Bandbreite) */
|
||
const rd = (x, d) => (typeof x === 'number' && Number.isFinite(x) ? Math.round(x * 10 ** d) / 10 ** d : x);
|
||
const CLIENT_ID_RE = /^[A-Za-z0-9_-]{8,64}$/;
|
||
const CLIENT_ID_TTL = 10 * 60_000; // so lange erkennt der Server eine wiederholte Order (gleiche clientId) wieder
|
||
const CLIENT_ID_KEEP = 50; // höchstens so viele clientIds je Spieler
|
||
const EQ_HIST_SEND = 120; // so viele Punkte Depotwert-Verlauf gehen mit dem Depot an den Client
|
||
|
||
/** Auswertung einer Meldung bereinigen (kommt teils von außen bzw. aus dem Sprachmodell) */
|
||
function cleanAnalysis(a) {
|
||
const out = { by: a?.by === 'llm' ? 'llm' : 'regeln', topics: {}, sectorImpact: {}, strength: 0.6, reasons: [] };
|
||
if (!a) return out;
|
||
const n1 = (x) => Math.max(-1, Math.min(1, Number(x) || 0));
|
||
for (const k of Object.keys(TOPICS)) if (a.topics?.[k]) out.topics[k] = n1(a.topics[k]);
|
||
for (const [k, v] of Object.entries(a.sectorImpact ?? {})) if (SECTORS[k]) out.sectorImpact[k] = n1(v);
|
||
if (Number.isFinite(Number(a.strength))) out.strength = Math.max(0, Math.min(1, Number(a.strength)));
|
||
out.reasons = [].concat(a.reasons ?? []).slice(0, 6).map((r) => cleanText(r, 160));
|
||
if (a.relevant === false) out.relevant = false;
|
||
return out;
|
||
}
|
||
|
||
export class Game {
|
||
/**
|
||
* @param {{store: import('./store.js').Store, broadcast?: Function, sendTo?: Function, isOnline?: Function, kick?: Function, now?: () => number}} opt
|
||
*/
|
||
constructor({ store, broadcast, sendTo, isOnline, kick, now } = {}) {
|
||
this.store = store;
|
||
this.broadcast = broadcast ?? noop;
|
||
this.sendTo = sendTo ?? noop;
|
||
this.isOnline = isOnline ?? (() => false);
|
||
this.kick = kick ?? noop;
|
||
this.clock = new Clock(() => settings.game, now ?? Date.now);
|
||
/** Wartung (Neuaufsetzen der Börse, prehistory.js): {text, since} – solange gesetzt, nimmt der Server keine Aufträge an */
|
||
this.maintenance = null;
|
||
this.#load();
|
||
}
|
||
|
||
/**
|
||
* Spielstand nach dem Neuaufsetzen oder Wiederherstellen einer Sicherung neu aus der Datenbank laden. Das Objekt
|
||
* bleibt dasselbe (Gateway, Aktionen und Bot-Erkennung halten Verweise darauf), alle Module werden neu erzeugt.
|
||
*/
|
||
reload() {
|
||
this.#load();
|
||
this.phaseInfo = null;
|
||
}
|
||
|
||
#load() {
|
||
const store = this.store;
|
||
const data = store.load();
|
||
const meta = data.meta;
|
||
const core = meta.core ?? {};
|
||
if (core.turboEpoch && this.clock.turbo) this.clock.turboEpoch = core.turboEpoch;
|
||
this.day = core.day ?? 1;
|
||
this.season = core.season ?? { n: 1, startedAt: Date.now(), endsAt: Date.now() + this.cfg.seasonDays * DAY };
|
||
this.events = core.events ?? [];
|
||
this.news = core.news ?? [];
|
||
this.cases = core.cases ?? [];
|
||
this.market = core.market ?? { phase: 'closed', date: null, openUncrossAt: 0, closeUncrossAt: 0, lastCloseAt: 0 };
|
||
this.macro = meta.macro ?? createMacro();
|
||
// ältere Spielstände: neue Branchen (ab 0.25) bekommen eine neutrale Stimmung
|
||
for (const k of Object.keys(SECTORS)) { this.macro.sectorMood[k] ??= 0; if (this.macro.moodAvg) this.macro.moodAvg[k] ??= 0; }
|
||
this.tickCount = 0;
|
||
/** @type {Map<string, Map<string, {ts: number, order: any}>>} clientId → Antwort je Spieler (nur im Speicher) */
|
||
this.orderClientIds = new Map();
|
||
|
||
// Dirty-Tracking für die Persistenz
|
||
this.dirtyPlayers = new Set();
|
||
this.dirtyAccounts = new Set();
|
||
this.deletedPlayers = new Set();
|
||
this.deletedAccounts = new Set();
|
||
this.pendingFills = [];
|
||
this.changedOwners = new Set(); // für das Gateway: wessen Depot hat sich geändert
|
||
this.metaDirty = false;
|
||
this.lastMetaAt = 0;
|
||
|
||
this.players = new Map(data.players.map((p) => [p.id, p]));
|
||
this.battleAccounts = new Map(data.accounts.map((a) => [a.id, a]));
|
||
|
||
this.stocks = new Map();
|
||
// Börsengänge früherer Saisons/Tage (ipo.js) kommen nach den festen Werten
|
||
for (const c of [...COMPANIES.map((x) => ({ kind: 'stock', ...x })), ...INSTRUMENTS, ...ETFS, ...(meta.ipo?.listed ?? []).map((x) => ({ kind: 'stock', ...x }))]) {
|
||
if (this.stocks.has(c.symbol)) continue;
|
||
if (c.kind === 'stock') SECTOR_OF[c.symbol] = c.sector;
|
||
this.stocks.set(c.symbol, this.makeStock(c, meta.stocks?.[c.symbol]));
|
||
}
|
||
|
||
this.ex = new Exchange(this);
|
||
this.ex.nextCondId = meta.ex?.nextCondId ?? 1;
|
||
this.ex.marketHaltLevel = meta.ex?.marketHaltLevel ?? 0;
|
||
this.assets = new Assets(this);
|
||
if (meta.assets?.foreignRate) this.assets.foreignRate = meta.assets.foreignRate;
|
||
this.econ = new Economy(this);
|
||
// Energielage aus echten Strom- und Gasdaten (energy.js); vor dem Bewerten anlegen – der innere Wert enthält ihre Wirkung
|
||
this.energy = new Energy(this, meta.energy);
|
||
this.newsBudget = new NewsBudget(); // Bündelung und Sättigung echter Meldungen (nur im Speicher, 6–12 h Gedächtnis)
|
||
Object.assign(this.econ, { cbExpect: meta.econ?.cbExpect ?? null, cbAt: meta.econ?.cbAt ?? 0, lastDecision: meta.econ?.lastDecision ?? null, cascades: meta.econ?.cascades ?? [] });
|
||
this.corp = new Corporate(this, meta.corp);
|
||
this.credit = new Credit(this, meta.credit);
|
||
this.gov = new Government(this, meta.gov);
|
||
this.pol = new Politics(this, meta.pol);
|
||
this.reg = new Regulator();
|
||
this.bat = new Battles(this, meta.bat);
|
||
this.prog = new Progress(this, meta.prog);
|
||
this.social = new Social(this);
|
||
this.msgs = new Messages(this);
|
||
this.invites = new Invites(this);
|
||
this.clubs = new Clubs(this, meta.clubs);
|
||
this.tour = new Tournaments(this, meta.tour);
|
||
this.rivals = new Rivals(this, meta.rivals);
|
||
this.ipo = new Ipo(this, meta.ipo);
|
||
// Abspaltungen und Fusionen (vor dem Logo-Pool: angekündigte Töchter halten ihre Marke über einen Neustart)
|
||
this.spinoff = new Spinoff(this, meta.spinoff);
|
||
this.merger = new Merger(this, meta.merger);
|
||
// Logo-Pool für Börsenneulinge (alte Spielstände: gelistete Neulinge bekommen beim Laden einmalig eine Marke)
|
||
this.marks = new MarkPool(this, meta.marks);
|
||
this.marks.migrate();
|
||
this.delist = new Delist(this, meta.delist);
|
||
this.chronicle = new Chronicle(this, meta.chronicle); // Firmenchronik (chronicle.js)
|
||
this.splits = new Splits(this, meta.splits); // Aktiensplit / Zusammenlegung (splits.js)
|
||
this.pendingBarScales = []; // Tagesbalken, die mit dem nächsten Speichern bereinigt werden (Split)
|
||
this.agm = new Agm(this, meta.agm);
|
||
this.review = new SeasonReview(this, meta.review);
|
||
this.predict = new Predict(this, meta.predict);
|
||
this.after = new AfterHours(this, meta.after);
|
||
this.analyses = new Analyses(this, meta.analyses);
|
||
this.causes = new Causes(this, meta.causes);
|
||
this.pop = new Population(this, meta.pop);
|
||
this.sessions = new Sessions(data.sessions);
|
||
this.todo = new Todos(this);
|
||
// Ereignis-Haken für Erfolge aus dem Firmenleben (Börsengang, Split, Abspaltung, Fusion, Rückzug, Insolvenz)
|
||
this.achievements = new AchievementHooks(this);
|
||
|
||
[...this.stocks.values()].forEach((s, idx) => {
|
||
// ältere Spielstände: Bilanz und Rating werden beim Laden erzeugt (credit.js)
|
||
if (s.kind === 'stock') { if (!s.fund) s.fund = this.econ.init(s, idx); else this.credit.ensure(s); } else s.asset ??= initAsset(s, this.day);
|
||
});
|
||
this.econ.initOutlook();
|
||
this.econ.refreshFv();
|
||
this.assets.seed();
|
||
for (const s of this.stocks.values()) if (s.kind === 'stock' && !s.fund.analysts) updateAnalysts(s, s.fv);
|
||
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);
|
||
// Indizes vor den Hebelprodukten anlegen: stellt die WIBO-10-Zusammensetzung (Nachrücker nach Börsenrückzügen) wieder her
|
||
this.indices = new Indices(this, meta.indices);
|
||
// Hebelprodukte des Emittenten (alte Spielstände: werden beim Laden erzeugt)
|
||
this.derivs = new Derivs(this, meta.derivs);
|
||
this.derivs.init();
|
||
// Marktsegmente und Indizes (alte Spielstände: werden beim Laden eingeteilt, Historie aus Tageskerzen zurückgerechnet)
|
||
this.indices.init();
|
||
// Indexfonds (Korb aus den Indizes), Abgeltungsteuer, Meldeschwellen & Pflichtangebot (etf.js, tax.js, holdings.js)
|
||
this.etfs = new Etfs(this);
|
||
this.etfs.init();
|
||
this.tax = new Tax(this);
|
||
this.holdings = new Holdings(this);
|
||
// alte Spielstände: Firmenchronik einmalig aus vorhandenen Daten zurückfüllen
|
||
try { this.chronicle.backfill(); } catch (e) { console.warn('[chronik]', e.message); }
|
||
|
||
// Orders wiederherstellen (Buch + bedingte Orders)
|
||
for (const o of data.orders) {
|
||
const { kind, ...rest } = o;
|
||
if (kind === 'book') {
|
||
const s = this.stocks.get(rest.symbol);
|
||
if (!s || !this.account(rest.ownerId)) continue;
|
||
s.book.addResting(rest);
|
||
bumpOrderId(Number(rest.id));
|
||
} else if (kind === 'cond' && this.account(rest.accountId)) {
|
||
this.ex.condOrders.push(rest);
|
||
const n = Number(String(rest.id).replace(/\D/g, ''));
|
||
if (n >= this.ex.nextCondId) this.ex.nextCondId = n + 1;
|
||
}
|
||
}
|
||
|
||
// Admin-Einrichtung: solange es keinen Admin gibt, gilt ein Einrichtungscode aus dem Server-Log
|
||
this.setupCode = null;
|
||
if (![...this.players.values()].some((p) => p.isAdmin)) {
|
||
this.setupCode = process.env.ADMIN_SETUP_CODE || uid(4);
|
||
if (process.env.NODE_ENV !== 'test') console.log(`[admin] Noch kein Admin. Einrichtungscode: ${this.setupCode} (im Spiel unter Profil → „Admin einrichten“ eingeben)`);
|
||
}
|
||
this.prog.refresh();
|
||
}
|
||
|
||
get cfg() { return settings.game; }
|
||
|
||
#migratePlayer(p) {
|
||
p.compliance ??= { cases: 0, warnings: 0, fines: 0, finedTotal: 0 };
|
||
p.dividendCount ??= 0;
|
||
p.votes ??= 0;
|
||
p.notify ??= {};
|
||
for (const [k, v] of Object.entries({ battle: true, season: true, achievements: false, margin: true, morning: false, daily: false, messages: true })) p.notify[k] ??= v;
|
||
p.battleStats ??= { w: 0, l: 0, d: 0 };
|
||
p.achievements ??= [];
|
||
p.elo ??= 1000;
|
||
p.inbox ??= [];
|
||
p.follows ??= [];
|
||
p.ips ??= [];
|
||
p.novice ??= true;
|
||
p.party ??= null;
|
||
delete p.token;
|
||
this.prog.initPlayer(p);
|
||
}
|
||
|
||
// ================================================================ Persistenz
|
||
markDirty(obj) {
|
||
if (!obj) return;
|
||
if (this.players.get(obj.id) === obj) { this.dirtyPlayers.add(obj.id); this.changedOwners.add(obj.id); }
|
||
else if (this.battleAccounts.get(obj.id) === obj) { this.dirtyAccounts.add(obj.id); this.changedOwners.add(obj.owner); }
|
||
}
|
||
|
||
recordFill(f) {
|
||
this.pendingFills.push({ ...f, season: this.season.n });
|
||
this.tax?.onFill(f); // Abgeltungsteuer einbehalten/erstatten (setzt f.tax)
|
||
this.holdings?.noteFill(f); // Meldeschwellen am Ende des Takts prüfen
|
||
}
|
||
|
||
metaSnapshot() {
|
||
const stocks = {};
|
||
for (const s of this.stocks.values()) {
|
||
stocks[s.symbol] = {
|
||
fair: s.fair, last: s.last, prevClose: s.prevClose, close: s.close, open: s.open, high: s.high, low: s.low,
|
||
volume: s.volume, turnover: s.turnover, turnoverAvg: s.turnoverAvg, hDay: s.hDay, mis: s.mis, imp: s.imp, mmInv: s.mmInv,
|
||
fund: s.fund, candles: s.delisted ? [] : s.candles.slice(-300), // eingestellte Werte: Intraday-Kerzen nicht mehr mitschleppen (Tageskerzen liegen in der DB) refAuction: s.refAuction, lastAuction: s.lastAuction, lend: s.lend, flowPrev: s.flowPrev,
|
||
shares: s.shares, asset: s.asset, control: s.control, delisted: s.delisted ?? null,
|
||
...(s.splitF && s.splitF !== 1 ? { splitF: s.splitF } : {}),
|
||
};
|
||
}
|
||
return {
|
||
core: {
|
||
day: this.day, season: this.season, events: this.events.slice(0, 100), news: this.news.slice(0, 60),
|
||
cases: this.cases.slice(0, 300), market: this.market, turboEpoch: this.clock.turboEpoch,
|
||
},
|
||
macro: this.macro, stocks,
|
||
econ: { cbExpect: this.econ.cbExpect, cbAt: this.econ.cbAt, lastDecision: this.econ.lastDecision, cascades: this.econ.cascades },
|
||
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(), delist: this.delist.snapshot(), splits: this.splits.snapshot(), chronicle: this.chronicle.snapshot(), spinoff: this.spinoff.snapshot(), merger: this.merger.snapshot(), marks: this.marks.snapshot(), agm: this.agm.snapshot(), review: this.review.snapshot(), predict: this.predict.snapshot(), after: this.after.snapshot(), analyses: this.analyses.snapshot(), causes: this.causes.snapshot(), pop: this.pop.snapshot(), energy: this.energy.snapshot(),
|
||
ex: { nextCondId: this.ex.nextCondId, marketHaltLevel: this.ex.marketHaltLevel }, derivs: this.derivs.snapshot(), indices: this.indices.snapshot(),
|
||
};
|
||
}
|
||
|
||
/** Eine Transaktion mit allen Änderungen seit dem letzten Takt */
|
||
flush(force = false) {
|
||
const w = this.sessions.drain();
|
||
for (const id of this.deletedAccounts) this.dirtyAccounts.delete(id);
|
||
for (const id of this.deletedPlayers) this.dirtyPlayers.delete(id);
|
||
w.players = [...this.dirtyPlayers].map((id) => this.players.get(id)).filter(Boolean);
|
||
w.accounts = [...this.dirtyAccounts].map((id) => this.battleAccounts.get(id)).filter(Boolean);
|
||
w.orders = new Map([...this.dirtyPlayers, ...this.dirtyAccounts].map((id) => [id, this.ex.ordersOf(id)]));
|
||
w.fills = this.pendingFills.splice(0);
|
||
w.deletedPlayers = [...this.deletedPlayers];
|
||
w.deletedAccounts = [...this.deletedAccounts];
|
||
w.barScales = this.pendingBarScales.splice(0); // Split: Tagesbalken bereinigen – in derselben Transaktion wie der Meta-Stand
|
||
const now = Date.now();
|
||
const withMeta = force || this.metaDirty || w.barScales.length > 0 || now - this.lastMetaAt > 60_000;
|
||
if (withMeta) w.meta = this.metaSnapshot();
|
||
try {
|
||
this.store.write(w);
|
||
} catch (e) {
|
||
// Transaktion zurückgerollt: nichts verwerfen, der nächste Takt schreibt alles erneut
|
||
this.pendingFills.unshift(...w.fills);
|
||
this.pendingBarScales.unshift(...w.barScales);
|
||
this.sessions.pendingSet.unshift(...w.sessions); this.sessions.pendingDel.unshift(...w.deletedSessions); this.sessions.pendingDelPlayers.unshift(...w.deletedSessionsOf);
|
||
if (withMeta) this.metaDirty = true;
|
||
throw e;
|
||
}
|
||
if (withMeta) { this.metaDirty = false; this.lastMetaAt = now; }
|
||
this.dirtyPlayers.clear(); this.dirtyAccounts.clear(); this.deletedPlayers.clear(); this.deletedAccounts.clear();
|
||
}
|
||
|
||
drainChanged() { const out = [...this.changedOwners]; this.changedOwners.clear(); return out; }
|
||
|
||
// ================================================================ Spieler & Anmeldung
|
||
#ipHash(ip) { return createHash('sha256').update(`${IP_SALT}|${ip}`).digest('hex').slice(0, 16); }
|
||
|
||
noteIp(p, ip) {
|
||
if (!ip) return;
|
||
const h = this.#ipHash(ip);
|
||
p.ips = [h, ...(p.ips ?? []).filter((x) => x !== h)].slice(0, 5);
|
||
p.lastSeen = Date.now();
|
||
this.markDirty(p);
|
||
}
|
||
|
||
sharedIp(a, b) {
|
||
const pa = this.players.get(a), pb = this.players.get(b);
|
||
return !!pa && !!pb && (pa.ips ?? []).some((h) => (pb.ips ?? []).includes(h));
|
||
}
|
||
|
||
#freshAccount() {
|
||
const c = this.cfg.startCash;
|
||
return {
|
||
cash: c, positions: {}, realized: 0, fees: 0, trades: 0, peakEquity: c, wasDown20: false, locked: false,
|
||
recalls: [], borrowAccrued: 0, derivs: {}, dayStartEquity: c, weekStartEquity: c, eqHist: [], marginWarned: false, dayStats: null,
|
||
tax: freshTax(), stakes: {}, seasonOrders: 0, seasonTrack: null, seasonAch: null, // Steuerjahr = Saison; gemeldete Beteiligungsschwellen
|
||
};
|
||
}
|
||
|
||
async register({ name, password, email, invite } = {}, ip = null) {
|
||
if (!this.cfg.registrationOpen) throw new Error('Registrierung ist derzeit geschlossen');
|
||
name = cleanText(name, 20);
|
||
if (!NAME_RE.test(name)) throw new Error('Name: 3–20 Zeichen (Buchstaben, Ziffern, Leerzeichen, _ . -)');
|
||
if (String(password ?? '').length < 8) throw new Error('Passwort: mindestens 8 Zeichen');
|
||
email = cleanText(email, 120);
|
||
if (email && !MAIL_RE.test(email)) throw new Error('Ungültige E-Mail-Adresse');
|
||
if (this.byName(name)) throw new Error('Name ist bereits vergeben');
|
||
this.invites.beforeRegister(invite); // „nur mit Einladung“: ohne gültigen Code abgelehnt
|
||
const pw = await hashPw(String(password));
|
||
if (this.byName(name)) throw new Error('Name ist bereits vergeben');
|
||
const inv = this.invites.beforeRegister(invite); // nach dem Hashen erneut (Code kann inzwischen aufgebraucht sein)
|
||
const p = {
|
||
id: `p:${uid(6)}`, name, pw, email, isAdmin: false, banned: false, joined: Date.now(), lastSeen: Date.now(),
|
||
elo: 1000, battleStats: { w: 0, l: 0, d: 0 }, achievements: [], seasonsPlayed: 1, bestReturn: 0,
|
||
...this.#freshAccount(),
|
||
};
|
||
this.players.set(p.id, p);
|
||
this.#migratePlayer(p);
|
||
this.noteIp(p, ip);
|
||
this.markDirty(p);
|
||
this.log('player', `${name} ist dem Markt beigetreten`);
|
||
this.social.notify(p.id, { kind: 'welcome', title: 'Willkommen bei WiBoSim!', text: `Du startest mit ${fmt(this.cfg.startCash)} €. Die Einführung zeigt dir in zwei Minuten das Wichtigste.`, action: { tutorial: true } });
|
||
const invited = this.invites.afterRegister(p, inv);
|
||
return { player: p, token: this.sessions.create(p.id), invite: invited };
|
||
}
|
||
|
||
async login(name, password, ip = null) {
|
||
if (this.sessions.locked(name)) throw new Error('Zu viele Fehlversuche – bitte 15 Minuten warten');
|
||
const p = this.byName(name);
|
||
const ok = p ? await checkPw(password, p.pw) : await checkPw(password, 'x:00').catch(() => false);
|
||
if (p?.rival) { this.sessions.failed(name); throw new Error('Name oder Passwort falsch'); }
|
||
if (!p || !ok) { this.sessions.failed(name); throw new Error('Name oder Passwort falsch'); }
|
||
if (p.banned) throw new Error('Dieses Konto ist gesperrt');
|
||
this.sessions.succeeded(name);
|
||
this.noteIp(p, ip);
|
||
return { player: p, token: this.sessions.create(p.id) };
|
||
}
|
||
|
||
/** Laufzeitobjekt eines Wertpapiers (feste Werte, Börsengänge); sv = gespeicherter Stand */
|
||
makeStock(c, sv = null) {
|
||
const price = sv?.last ?? c.price;
|
||
// Aktiensplits (splits.js): Gesamtfaktor seit der Erstnotiz – Ausgangskurs, Ausgangszahl und Ausgabepreis bereinigen
|
||
const F = sv?.splitF > 0 ? sv.splitF : 1;
|
||
return {
|
||
...c,
|
||
...(F !== 1 ? { price: c.price / F, ...(c.ipo ? { ipo: { ...c.ipo, price: c.ipo.price / F, rawPrice: c.ipo.price } } : {}) } : {}),
|
||
splitF: F,
|
||
fair: sv?.fair ?? price, last: price, prevClose: sv?.prevClose ?? price, close: sv?.close ?? price,
|
||
open: sv?.open ?? price, high: sv?.high ?? price, low: sv?.low ?? price,
|
||
volume: sv?.volume ?? 0, turnover: sv?.turnover ?? 0, turnoverAvg: sv?.turnoverAvg ?? 1e6,
|
||
candles: sv?.candles ?? [], book: new OrderBook(c.symbol), tape: [],
|
||
flow: Object.fromEntries(Object.keys(ARCHETYPES).map((k) => [k, 0])), playerFlow: 0, flowPrev: sv?.flowPrev ?? null,
|
||
instJob: null, mmInv: sv?.mmInv ?? 0, imp: sv?.imp ?? 0, toxic: 0, hDay: sv?.hDay ?? 1, mis: sv?.mis ?? 0,
|
||
fv: null, fund: sv?.fund ?? null, refAuction: sv?.refAuction ?? price, volaEndsAt: 0, indicative: null,
|
||
lastAuction: sv?.lastAuction ?? null, lend: sv?.lend ?? { recalled: 0 }, shortUsed: 0,
|
||
shares: sv?.shares ?? c.shares, baseShares: c.shares * F, asset: sv?.asset ?? null, control: sv?.control ?? null, seeded: !!sv,
|
||
delisted: sv?.delisted ?? null, // von der Börse genommen (delist.js): bleibt für Journal und Historie auflösbar
|
||
};
|
||
}
|
||
|
||
/** computergesteuerten Rivalen anlegen (rivals.js) – gleiches Startkapital, gleiche Regeln */
|
||
createRival({ name, pw, rival }) {
|
||
const p = {
|
||
id: `r:${rival.char}:${uid(3)}`, name, pw, email: '', isAdmin: false, banned: false, joined: Date.now(), lastSeen: Date.now(),
|
||
elo: 1000, battleStats: { w: 0, l: 0, d: 0 }, achievements: [], seasonsPlayed: 1, bestReturn: 0, rival,
|
||
...this.#freshAccount(),
|
||
};
|
||
this.players.set(p.id, p);
|
||
this.#migratePlayer(p);
|
||
p.notify = Object.fromEntries(Object.keys(p.notify).map((k) => [k, false]));
|
||
this.markDirty(p);
|
||
return p;
|
||
}
|
||
|
||
logout(token) { this.sessions.revoke(token); }
|
||
|
||
byName(name) {
|
||
const n = String(name ?? '').trim().toLowerCase();
|
||
if (!n) return null;
|
||
for (const p of this.players.values()) if (p.name.toLowerCase() === n) return p;
|
||
return null;
|
||
}
|
||
|
||
byToken(token) {
|
||
const id = this.sessions.resolve(token);
|
||
const p = id && this.players.get(id);
|
||
return p && !p.banned ? p : null;
|
||
}
|
||
|
||
async updateProfile(p, { email, notify: nt, password, oldPassword, novice } = {}) {
|
||
let token = null;
|
||
if (email !== undefined) {
|
||
const e = cleanText(email, 120);
|
||
if (e && !MAIL_RE.test(e)) throw new Error('Ungültige E-Mail-Adresse');
|
||
p.email = e;
|
||
}
|
||
if (nt && typeof nt === 'object') for (const k of Object.keys(p.notify)) if (k in nt) p.notify[k] = !!nt[k];
|
||
if (novice !== undefined) p.novice = !!novice;
|
||
if (password) {
|
||
if (!(await checkPw(oldPassword, p.pw))) throw new Error('Altes Passwort falsch');
|
||
if (String(password).length < 8) throw new Error('Passwort: mindestens 8 Zeichen');
|
||
p.pw = await hashPw(String(password));
|
||
this.sessions.revokeAll(p.id); // alle anderen Sitzungen abmelden
|
||
token = this.sessions.create(p.id);
|
||
}
|
||
this.markDirty(p);
|
||
return { profile: this.profile(p), token };
|
||
}
|
||
|
||
claimAdmin(p, code) {
|
||
if (!this.setupCode) throw new Error('Es gibt bereits einen Admin');
|
||
// Raten erschweren: höchstens 5 Fehlversuche je Spieler in 15 Minuten
|
||
this.claimFails ??= new Map();
|
||
const f = this.claimFails.get(p.id);
|
||
if (f && f.n >= 5 && Date.now() - f.ts < 15 * 60_000) throw new Error('Zu viele Fehlversuche – bitte 15 Minuten warten');
|
||
const a = Buffer.from(String(code ?? '').trim()), b = Buffer.from(this.setupCode);
|
||
if (a.length !== b.length || !timingSafeEqual(a, b)) {
|
||
const n = f && Date.now() - f.ts < 15 * 60_000 ? f.n + 1 : 1;
|
||
this.claimFails.set(p.id, { n, ts: Date.now() });
|
||
throw new Error('Einrichtungscode falsch');
|
||
}
|
||
this.claimFails.delete(p.id);
|
||
p.isAdmin = true;
|
||
this.setupCode = null;
|
||
this.markDirty(p);
|
||
this.store.audit(p.name, 'claimAdmin', 'Admin per Einrichtungscode');
|
||
this.log('admin', `${p.name} ist jetzt Admin`);
|
||
return this.profile(p);
|
||
}
|
||
|
||
profile(p) {
|
||
const lvl = levelOf(p.xp ?? 0);
|
||
return {
|
||
id: p.id, name: p.name, email: p.email, notify: p.notify, isAdmin: p.isAdmin, elo: Math.round(p.elo),
|
||
battleStats: p.battleStats, achievements: p.achievements.map((id) => ({ id, ...ACHIEVEMENTS[id] })),
|
||
allAchievements: Object.entries(ACHIEVEMENTS).map(([id, a]) => ({ id, ...a, unlocked: p.achievements.includes(id) })),
|
||
joined: p.joined, seasonsPlayed: p.seasonsPlayed, bestReturn: p.bestReturn, compliance: p.compliance,
|
||
xp: p.xp ?? 0, level: lvl, tier: TIERS[p.league?.tier ?? 0], league: p.league, novice: p.novice,
|
||
unread: this.social.unread(p), recap: p.recap ?? null, mutedUntil: p.mutedUntil ?? 0,
|
||
adminSetupOpen: !!this.setupCode,
|
||
party: p.party ?? null, office: this.gov.officeOf(p.id),
|
||
};
|
||
}
|
||
|
||
unlock(p, id) {
|
||
if (!p || !this.players.has(p.id) || p.achievements.includes(id) || !ACHIEVEMENTS[id]) return;
|
||
p.achievements.push(id);
|
||
if (p.seasonAch?.n !== this.season.n) p.seasonAch = { n: this.season.n, ids: [] };
|
||
p.seasonAch.ids.push(id); // Erfolge dieser Saison (Saisonrückblick)
|
||
if (!p.rival) (p.achNew ??= []).push(id); // für „Mein Tag“ (Abholen), bis der Spieler ihn quittiert
|
||
const a = ACHIEVEMENTS[id];
|
||
this.markDirty(p);
|
||
this.sendTo(p.id, { type: 'achievement', achievement: { id, ...a } });
|
||
this.log('achievement', `${p.name} erhält „${a.title}“`);
|
||
this.prog.addXp(p, 25);
|
||
this.social.notify(p.id, { kind: 'achievement', title: `Erfolg: ${a.title}`, text: a.desc, email: 'achievements' });
|
||
}
|
||
|
||
notify(pid, n) { this.social.notify(pid, n); }
|
||
|
||
// ================================================================ Konten
|
||
priceOf = (sym) => this.stocks.get(sym).last;
|
||
account(id) { return this.players.get(id) ?? this.battleAccounts.get(id) ?? null; }
|
||
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) + (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; }
|
||
|
||
/** 'main' oder 'battle' → Kontoobjekt des Spielers */
|
||
resolveAccount(p, which) {
|
||
if (!which || which === 'main') return p;
|
||
if (which === 'fund') return this.clubs.managedFund(p);
|
||
const bt = this.bat.active(p.id);
|
||
const accId = bt && (bt.a === p.id ? bt.aAcc : bt.bAcc);
|
||
const acc = accId && this.battleAccounts.get(accId);
|
||
if (!acc) throw new Error('Kein aktives Battle-Depot');
|
||
return acc;
|
||
}
|
||
|
||
portfolio(acc) {
|
||
const res = this.ex.reserved(acc);
|
||
const m = this.margin(acc);
|
||
const fundValue = acc.owner ? 0 : this.clubs?.unitsValue(acc.id) ?? 0; // Fondsanteile (nur Hauptdepot)
|
||
const eqAll = m.equity + fundValue;
|
||
const positions = Object.entries(acc.positions).filter(([, pos]) => pos.qty !== 0).map(([sym, pos]) => {
|
||
const s = this.stocks.get(sym);
|
||
return {
|
||
symbol: sym, qty: pos.qty, avgCost: pos.avgCost, last: s.last, value: pos.qty * s.last,
|
||
pnl: (s.last - pos.avgCost) * pos.qty, pnlPct: pos.avgCost ? (s.last / pos.avgCost - 1) * 100 * Math.sign(pos.qty) : 0,
|
||
dayChange: (s.last / s.prevClose - 1) * 100, short: pos.qty < 0, borrowRate: pos.qty < 0 ? this.ex.lendRate(s) : null,
|
||
...(this.splits.recent(sym) ? { split: this.splits.recent(sym) } : {}),
|
||
};
|
||
});
|
||
const orders = [];
|
||
for (const s of this.stocks.values()) {
|
||
const queued = !this.ex.isContinuous(s);
|
||
for (const o of s.book.openOrdersOf(acc.id)) orders.push({ ...publicOrder(o), status: queued ? 'queued' : o.status, bracket: !!o.meta?.bracket });
|
||
}
|
||
const cond = this.ex.condOrders.filter((c) => c.accountId === acc.id).map((c) => ({ ...c, trigger: this.ex.condTrigger(c), label: COND_LABEL[c.type] }));
|
||
const start = acc.startCash ?? this.cfg.startCash;
|
||
const isMain = !acc.owner;
|
||
const dayStart = acc.dayStartEquity ?? start;
|
||
return {
|
||
accountId: acc.id, kind: acc.kind ?? (isMain ? 'main' : 'battle'), rules: acc.rules ?? null, name: acc.name ?? acc.name,
|
||
cash: acc.cash, available: m.buyingPower - res.cash, equity: eqAll, fundValue, startCash: start,
|
||
returnPct: (eqAll / start - 1) * 100, realized: acc.realized, fees: acc.fees, trades: acc.trades ?? 0,
|
||
dayPnL: eqAll - dayStart, dayPnLPct: (eqAll / Math.max(1, dayStart) - 1) * 100,
|
||
longValue: m.long, shortValue: m.short, shortCapacity: m.shortCapacity, marginUsage: m.usage,
|
||
locked: !!acc.locked, recalls: acc.recalls ?? [], borrowAccrued: acc.borrowAccrued ?? 0,
|
||
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, tax: this.tax.view(acc),
|
||
// Depotwert-Verlauf (ein Punkt je Handelsschluss) für die Kurve im Depot – nur Hauptdepot, gekürzt und auf Euro gerundet
|
||
eqHist: isMain ? (acc.eqHist ?? []).slice(-EQ_HIST_SEND).map((v) => Math.round(v)) : undefined,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Order platzieren. Mit `clientId` (vom Client je Order erzeugt) wird eine Wiederholung derselben Order –
|
||
* 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) { 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');
|
||
if (this.maintenance) throw new Error(this.maintenance.text);
|
||
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 = run();
|
||
seen.set(cid, { ts: t, order });
|
||
while (seen.size > CLIENT_ID_KEEP) seen.delete(seen.keys().next().value);
|
||
return order;
|
||
}
|
||
|
||
cancelOrder(p, id) { return this.ex.cancel(p, id); }
|
||
|
||
// ================================================================ Aufsicht
|
||
findings(list) {
|
||
if (!this.cfg.regulatorEnabled) return;
|
||
for (const f of list ?? []) {
|
||
const p = this.players.get(f.owner);
|
||
if (!p) continue;
|
||
if (this.cases.find((c) => c.owner === p.id && c.kind === f.kind && Date.now() - c.ts < 60_000)) continue;
|
||
p.compliance.cases++;
|
||
let fine = 0;
|
||
if (p.compliance.cases === 1) p.compliance.warnings++;
|
||
else {
|
||
fine = Math.round(Math.max(0, this.equity(p)) * this.cfg.fineRate * Math.min(5, p.compliance.cases - 1));
|
||
p.cash -= fine; p.realized -= fine;
|
||
p.compliance.fines++; p.compliance.finedTotal += fine;
|
||
if (fine) this.recordFill({ ts: Date.now(), owner: p.id, account: p.id, symbol: '-', side: 'fee', qty: 0, price: 0, fee: fine, realized: -fine, kind: 'fine' });
|
||
}
|
||
const c = { id: uid(4), ts: Date.now(), owner: p.id, name: p.name, kind: f.kind, text: VIOLATIONS[f.kind], detail: f.detail, fine };
|
||
this.cases.unshift(c);
|
||
if (this.cases.length > 300) this.cases.pop();
|
||
this.markDirty(p);
|
||
this.metaDirty = true;
|
||
const txt = `Aufsicht: ${fine ? `Bußgeld ${fmt(fine)} € gegen` : 'Verwarnung für'} ${p.name} – ${VIOLATIONS[f.kind]}`;
|
||
this.log('regulator', txt);
|
||
this.sendTo(p.id, { type: 'regulator', case: c, text: txt });
|
||
this.social.notify(p.id, { kind: 'regulator', title: fine ? `Bußgeld ${fmt(fine)} €` : 'Verwarnung der Börsenaufsicht', text: `${VIOLATIONS[f.kind]}: ${f.detail}` });
|
||
if (f.kind === 'battle') this.bat.annul(this.bat.active(p.id), 'Handel zwischen den Gegnern');
|
||
}
|
||
}
|
||
|
||
// ================================================================ Takt & Handelstag
|
||
tick() {
|
||
const now = this.clock.now();
|
||
const dt = this.lastTickAt ? clamp(now - this.lastTickAt, 0, this.maxTickDtMs ?? 60_000) : this.cfg.tickMs;
|
||
this.lastTickAt = now;
|
||
this.tickCount++;
|
||
this.causes.set(null);
|
||
this.#phaseMachine(now);
|
||
this.econ.step(dt, this.market.phase === 'continuous', this.afterHours());
|
||
try { this.energy.tick(dt, this.market.phase === 'continuous'); } catch (e) { console.warn('[energie]', e.message); }
|
||
try { this.merger.tick(); } catch (e) { console.warn('[fusion]', e.message); }
|
||
this.ex.tick(dt);
|
||
try { this.derivs.tick(); } catch (e) { console.warn('[hebel]', e.message); }
|
||
this.gov.tick();
|
||
this.pol.tick();
|
||
this.bat.tick();
|
||
this.agm.tick();
|
||
this.predict.tick();
|
||
this.after.tick(dt);
|
||
this.clubs.tick();
|
||
this.tour.tick();
|
||
this.rivals.tick();
|
||
if (this.tickCount % 10 === 0) this.#periodic();
|
||
if (this.tickCount % 5 === 0) this.prog.refresh();
|
||
if (this.tickCount % 30 === 0) this.reg.cleanup();
|
||
this.holdings.flush();
|
||
if (this.market.phase === 'closed' && now >= this.season.endsAt) this.endSeason();
|
||
this.flush();
|
||
}
|
||
|
||
#periodic() {
|
||
for (const p of this.players.values()) {
|
||
if (p.banned) continue;
|
||
const eq = this.equity(p);
|
||
for (const id of checkAchievements(p, eq, this.cfg.startCash)) this.unlock(p, id);
|
||
try { this.achievements.periodic(p); } catch (e) { console.warn('[erfolge]', e.message); }
|
||
if (eq > (p.peakEquity ?? 0)) p.peakEquity = eq;
|
||
}
|
||
this.prog.periodic();
|
||
}
|
||
|
||
#setPhase(phase) {
|
||
if (this.market.phase === phase) return;
|
||
this.market.phase = phase;
|
||
this.metaDirty = true;
|
||
if (phase === 'closing') for (const s of this.stocks.values()) if (!s.allDay) s.volaEndsAt = 0; // Volatilitätsauktion geht in der Schlussauktion auf
|
||
this.broadcast({ type: 'phase', phase: this.phaseView() });
|
||
}
|
||
|
||
#phaseMachine(now) {
|
||
const st = this.clock.state(now);
|
||
this.phaseInfo = st;
|
||
const m = this.market;
|
||
const active = ['preopen', 'opening', 'continuous', 'closing'].includes(m.phase);
|
||
// Handelstag ist vorbei (oder Server war während des Schlusses aus) → Schlussauktion nachholen
|
||
if (active && m.date && (st.date !== m.date || st.phase === 'closed')) {
|
||
if (m.phase === 'preopen' || m.phase === 'opening') this.#openMarket();
|
||
this.#closeDay();
|
||
}
|
||
if (st.phase === 'closed') {
|
||
this.#setPhase('closed');
|
||
const after = this.afterHours();
|
||
if ((m.after ?? null) !== after) {
|
||
const was = m.after;
|
||
m.after = after;
|
||
this.metaDirty = true;
|
||
if (after) {
|
||
for (const s of this.stocks.values()) s.eveImp = 0;
|
||
this.log('market', after === 'weekend' ? 'Wochenendhandel geöffnet – der Market Maker stellt Kurse (breitere Spannen, begrenzte Stückzahl)' : 'Abendhandel geöffnet – bis zum Ende handelst du direkt mit dem Market Maker');
|
||
} else if (was) this.log('market', was === 'weekend' ? 'Wochenendhandel beendet' : 'Abendhandel beendet – Orders werden für die Eröffnungsauktion gesammelt');
|
||
this.broadcast({ type: 'phase', phase: this.phaseView() });
|
||
}
|
||
return;
|
||
}
|
||
if (this.market.after) { this.market.after = null; }
|
||
if (m.date !== st.date) this.#newDay(st);
|
||
if (st.phase === 'preopen') {
|
||
this.#setPhase(this.clock.turbo || now >= st.openAt - OPEN_CALL_MS ? 'opening' : 'preopen');
|
||
} else if (st.phase === 'continuous') {
|
||
if (m.phase === 'preopen') this.#setPhase('opening');
|
||
if (m.phase === 'opening' && now >= m.openUncrossAt) this.#openMarket();
|
||
} else if (st.phase === 'closing') {
|
||
if (m.phase === 'preopen' || m.phase === 'opening') this.#openMarket();
|
||
if (m.phase === 'continuous') {
|
||
const dur = st.phaseEndsAt - st.closeAt;
|
||
m.closeUncrossAt = st.phaseEndsAt - rnd(0, Math.min(30_000, dur * 0.25)); // zufälliges Auktionsende
|
||
this.#setPhase('closing');
|
||
}
|
||
if (m.phase === 'closing' && now >= m.closeUncrossAt) this.#closeDay();
|
||
}
|
||
}
|
||
|
||
#newDay(st) {
|
||
const m = this.market;
|
||
if (m.date) this.day++;
|
||
m.date = st.date;
|
||
m.openUncrossAt = st.openAt + rnd(0, this.clock.turbo ? 3000 : 30_000);
|
||
for (const s of this.stocks.values()) {
|
||
s.prevClose = s.close ?? s.last;
|
||
s.open = s.high = s.low = s.last;
|
||
s.volume = 0; s.turnover = 0; s.playerFlow = 0;
|
||
for (const k of Object.keys(s.flow)) s.flow[k] = 0;
|
||
}
|
||
// fällige Aktiensplits zum Handelsbeginn (vor Orders, Fundamentaldaten und Hebelprodukten des Tages)
|
||
try { this.splits.newDay(); } catch (e) { console.warn('[split]', e.message); }
|
||
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); }
|
||
this.prog.newDay();
|
||
try { this.ipo.newDay(); } catch (e) { console.warn('[ipo]', e.message); }
|
||
try { this.spinoff.newDay(); } catch (e) { console.warn('[abspaltung]', e.message); }
|
||
try { this.merger.newDay(); } catch (e) { console.warn('[fusion]', e.message); }
|
||
try { this.agm.newDay(); } catch (e) { console.warn('[hv]', e.message); }
|
||
try { this.after.onNewDay(); } catch (e) { console.warn('[feierabend]', e.message); }
|
||
this.metaDirty = true;
|
||
this.#setPhase('preopen');
|
||
this.log('market', `Handelstag ${this.day} beginnt – Vorbörse, Eröffnungsauktion um ${new Date(st.openAt).toLocaleTimeString('de-DE', { timeZone: this.cfg.timezone, hour: '2-digit', minute: '2-digit' })}`);
|
||
try { reports.morning(this); } catch (e) { console.warn('[report]', e.message); }
|
||
}
|
||
|
||
#openMarket() {
|
||
let vol = 0;
|
||
for (const s of this.stocks.values()) {
|
||
if (s.allDay || s.delisted) continue; // Krypto handelt durchgehend, keine Auktion; eingestellte Werte gar nicht
|
||
const r = this.ex.uncross(s, 'open');
|
||
vol += r.volume ?? 0;
|
||
s.open = s.high = s.low = s.last;
|
||
}
|
||
this.#setPhase('continuous');
|
||
try { this.predict.onOpen(); } catch (e) { console.warn('[tipps]', e.message); }
|
||
this.log('market', `Eröffnungsauktion beendet – fortlaufender Handel (${vol.toLocaleString('de-DE')} Stück in der Auktion)`);
|
||
}
|
||
|
||
#closeDay() {
|
||
const now = this.clock.now();
|
||
if (this.market.phase !== 'closing') this.#setPhase('closing');
|
||
for (const s of this.stocks.values()) {
|
||
if (s.delisted) continue;
|
||
if (!s.allDay) this.ex.uncross(s, 'close');
|
||
s.close = s.last;
|
||
s.turnoverAvg = 0.8 * (s.turnoverAvg ?? s.turnover) + 0.2 * s.turnover;
|
||
s.flowPrev = { ...s.flow, players: s.playerFlow, day: this.day };
|
||
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.indices.onClose(); } catch (e) { console.warn('[indizes]', e.message); }
|
||
try { this.splits.onClose(); } catch (e) { console.warn('[split]', e.message); }
|
||
try { this.derivs.onClose(); } catch (e) { console.warn('[hebel]', e.message); }
|
||
this.market.lastCloseAt = now;
|
||
this.#setPhase('closed');
|
||
this.prog.dayClose();
|
||
try { this.review.dayClose(); } catch (e) { console.warn('[saisonrückblick]', e.message); }
|
||
try { this.predict.onClose(); } catch (e) { console.warn('[tipps]', e.message); }
|
||
try { this.analyses.onClose(); } catch (e) { console.warn('[analysen]', e.message); }
|
||
try { this.after.onClose(); } catch (e) { console.warn('[wochenrückblick]', e.message); }
|
||
const idx = this.index();
|
||
this.log('market', `Handelsschluss Tag ${this.day}: WIBO-10 ${fmt(idx.value)} (${idx.change >= 0 ? '+' : ''}${idx.change.toFixed(2)} %)`);
|
||
try { reports.daily(this); } catch (e) { console.warn('[report]', e.message); }
|
||
this.flush(true);
|
||
try { this.store.backup(); } catch (e) { console.warn('[backup]', e.message); }
|
||
if (now >= this.season.endsAt) this.endSeason();
|
||
}
|
||
|
||
// ================================================================ Saison
|
||
endSeason() {
|
||
this.#closeSeasonAccounts(true);
|
||
const now = Date.now();
|
||
this.season = { n: this.season.n + 1, startedAt: now, endsAt: now + this.cfg.seasonDays * DAY };
|
||
this.agm.onSeason();
|
||
this.analyses.onSeason();
|
||
this.causes.onSeason();
|
||
this.review.onSeasonStart();
|
||
this.metaDirty = true;
|
||
this.log('season', `Saison ${this.season.n} gestartet – alle Depots zurückgesetzt`);
|
||
try { applyScenario(this, pickScenario(this.cfg.scenario)); } catch (e) { console.warn('[szenario]', e.message); }
|
||
this.prog.refresh();
|
||
this.broadcast({ type: 'season', season: this.season });
|
||
}
|
||
|
||
/**
|
||
* Neuaufsetzen der Börse (prehistory.js): alle Depots wie zu einem Saisonstart zurücksetzen – Hebelprodukte und
|
||
* Clan-Fonds ausbuchen, Orders und Battles beenden –, aber ohne Rückblick und Ligawertung der abgebrochenen Saison.
|
||
*/
|
||
resetAccountsForRestart() {
|
||
this.#closeSeasonAccounts(false, 'Neuaufsetzen der Börse');
|
||
}
|
||
|
||
/** Depots aller Spieler auf Startkapital; ranked = Saisonwertung (Rückblick, Ligen, Ruhmeshalle) */
|
||
#closeSeasonAccounts(ranked, reason = null) {
|
||
this.derivs.liquidateAll('season'); // Hebelprodukte zum Geldkurs ausbuchen, bevor Depotwerte gewertet werden
|
||
this.clubs.seasonEnd(reason); // Fonds auflösen und auszahlen, bevor Rückblicke erstellt und Depots zurückgesetzt werden
|
||
const recaps = ranked ? this.prog.seasonEnd() : new Map();
|
||
if (ranked) this.review.seasonEnd(recaps); // Saisonrückblick-Snapshots: nach der Wertung, vor dem Zurücksetzen
|
||
this.bat.cancelAllRunning();
|
||
for (const p of this.players.values()) {
|
||
this.ex.cancelAll(p.id);
|
||
const rc = recaps.get(p.id);
|
||
if (rc) p.bestReturn = Math.max(p.bestReturn ?? 0, rc.returnPct);
|
||
Object.assign(p, this.#freshAccount());
|
||
p.seasonsPlayed = (p.seasonsPlayed ?? 1) + 1;
|
||
if (ranked) p.recap = rc ?? null;
|
||
p.alerts = []; p.weekRecap = null;
|
||
this.markDirty(p);
|
||
if (rc) {
|
||
this.sendTo(p.id, { type: 'seasonRecap', recap: rc });
|
||
this.social.notify(p.id, {
|
||
kind: 'season', title: `Saison ${rc.season} beendet: ${rc.returnPct >= 0 ? '+' : ''}${rc.returnPct.toFixed(2)} %`,
|
||
text: `${rc.rank ? `Rang ${rc.rank} von ${rc.of} (besser als ${Math.max(0, rc.percentile - 1)} %)` : 'Nicht in der Wertung'} · Liga: ${rc.leagueChange ?? '–'} (${rc.newTier ?? rc.tier}). Neue Saison: alle starten mit ${fmt(this.cfg.startCash)} €.`,
|
||
email: 'season', action: { recap: true },
|
||
});
|
||
}
|
||
}
|
||
return recaps;
|
||
}
|
||
|
||
// ================================================================ Nachrichten & Ereignisse
|
||
addNews(n, applyImpact = true) {
|
||
if (this.news.some((x) => x.id === n.id)) return;
|
||
n.title = cleanText(n.title, 300);
|
||
n.source = cleanText(n.source, 80);
|
||
n.url = safeUrl(n.url);
|
||
n.sectors = (n.sectors ?? []).filter((x) => SECTORS[x]);
|
||
n.analysis = cleanAnalysis(n.analysis);
|
||
// Dieselbe Geschichte aus mehreren Quellen: Folgemeldungen wirken deutlich schwächer
|
||
if (n.real) {
|
||
n.weight = Math.max(0.3, Math.min(1, Number(n.weight) || 1));
|
||
if (this.cfg.newsBudget) {
|
||
const st = this.newsBudget.story(n, Date.now());
|
||
if (st.echo > 0) { n.analysis.followUp = true; n.analysis.echo = st.echo; n.analysis.sources = st.sources; }
|
||
} else {
|
||
const fp = fingerprint(n.title);
|
||
const since = Date.now() - 12 * 3_600_000;
|
||
if (this.news.some((x) => x.real && x.ts >= since && similarity(fp, fingerprint(x.title)) >= 0.45)) n.analysis.followUp = true;
|
||
}
|
||
} else delete n.weight;
|
||
const topical = Object.keys(n.analysis.topics ?? {}).length > 0;
|
||
// Wirkungsbudget: je Thema, Branche und Börsenstimmung sättigt die Wirkung über 6 h (mehr Quellen ≠ mehr Ausschläge)
|
||
if (applyImpact && n.real && this.cfg.newsBudget && (n.sentiment || topical)) n.analysis.damp = this.#newsDamp(n);
|
||
if (applyImpact && (n.sentiment || topical)) n.affected = this.causes.with(`Nachricht: ${n.title}`, () => this.econ.newsImpact(n));
|
||
if (n.real) this.pol.noteNews(n.title);
|
||
this.news.unshift(n);
|
||
if (this.news.length > 100) this.news.pop();
|
||
this.metaDirty = true;
|
||
this.broadcast({ type: 'news', news: n });
|
||
this.rivals.onNews(n);
|
||
this.ipo?.onNews(n);
|
||
}
|
||
|
||
/** Last einer echten Meldung je Kanal buchen und Dämpfung bestimmen (newsbudget.js) */
|
||
#newsDamp(n) {
|
||
const a = n.analysis;
|
||
const base = (0.5 + 0.5 * (a.strength ?? 0.6)) * echoFactor(a.echo ?? (a.followUp ? 1 : 0)) * n.weight;
|
||
const loads = { mood: (n.sentiment ?? 0) * base };
|
||
for (const [k, v] of Object.entries(a.topics ?? {})) loads[`topic:${k}`] = v * base;
|
||
for (const sec of n.sectors) loads[`sector:${sec}`] = (a.sectorImpact?.[sec] ?? n.sentiment ?? 0) * base;
|
||
const f = this.newsBudget.take(loads, Date.now());
|
||
const r2 = (x) => Math.round(x * 100) / 100;
|
||
const damp = { mood: r2(f.mood ?? 1), topics: {}, sectors: {}, min: 1 };
|
||
for (const [key, v] of Object.entries(f)) {
|
||
if (key.startsWith('topic:')) damp.topics[key.slice(6)] = r2(v);
|
||
else if (key.startsWith('sector:')) damp.sectors[key.slice(7)] = r2(v);
|
||
if (loads[key]) damp.min = Math.min(damp.min, r2(v));
|
||
}
|
||
return damp;
|
||
}
|
||
|
||
log(kind, text, extra = {}) {
|
||
this.events.unshift({ kind, text, ts: Date.now(), ...extra });
|
||
if (this.events.length > 200) this.events.pop();
|
||
this.broadcast({ type: 'event', event: this.events[0] });
|
||
}
|
||
|
||
// ================================================================ Ansichten
|
||
index() {
|
||
// Gewichte fest nach Ausgangszahl der Aktien (Kapitalmaßnahmen verschieben den Index nicht)
|
||
const base = this.indexBase();
|
||
let now = 0, prev = 0;
|
||
for (const sym of INDEX_SYMBOLS) { const s = this.stocks.get(sym); if (!s || s.kind !== 'stock') continue; now += s.last * s.baseShares; prev += s.prevClose * s.baseShares; }
|
||
return { value: (now / base) * 10_000, change: (now / prev - 1) * 100 };
|
||
}
|
||
|
||
/** Basis des WIBO-10: Ausgangswert, nach einem Nachrücker (Börsenrückzug) verkettet (indices.js) */
|
||
indexBase() { return this.indices?.w10Base() ?? COMPANIES.filter((c) => INDEX_SYMBOLS.has(c.symbol)).reduce((a, c) => a + c.price * c.shares, 0); }
|
||
|
||
/** gelistete (handelbare) Wertpapiere – von der Börse genommene bleiben in this.stocks, zählen hier aber nicht */
|
||
listed() { return [...this.stocks.values()].filter((s) => !s.delisted); }
|
||
|
||
/** Abend- oder Wochenendhandel gerade offen? → 'evening' | 'weekend' | null */
|
||
afterHours() {
|
||
if (this.market.phase !== 'closed') return null;
|
||
const a = (this.phaseInfo ?? this.clock.state()).after;
|
||
return (a === 'evening' && this.cfg.eveningTrading) || (a === 'weekend' && this.cfg.weekendTrading) ? a : null;
|
||
}
|
||
|
||
phaseView() {
|
||
const st = this.phaseInfo ?? this.clock.state();
|
||
const ph = this.market.phase;
|
||
const after = this.afterHours();
|
||
const endsAt = { preopen: st.openAt - OPEN_CALL_MS, opening: this.market.openUncrossAt || st.openAt, continuous: st.closeAt, closing: st.phaseEndsAt, closed: st.nextPreOpen }[ph];
|
||
return {
|
||
phase: ph, label: after ? (after === 'weekend' ? 'Wochenendhandel' : 'Abendhandel') : PHASE_LABELS[ph], endsAt: after ? st.afterEndsAt : endsAt,
|
||
after, afterEndsAt: after ? st.afterEndsAt : null, randomEnd: ph === 'opening' || ph === 'closing',
|
||
openAt: st.openAt, closeAt: st.closeAt, nextPreOpen: st.nextPreOpen, date: this.market.date,
|
||
timeMode: this.cfg.timeMode, turbo: this.clock.turbo, timezone: this.cfg.timezone, serverTime: this.clock.now(),
|
||
};
|
||
}
|
||
|
||
tickers() {
|
||
return this.listed().map((s) => {
|
||
const st = this.ex.status(s);
|
||
if (s.kind !== 'stock') {
|
||
const info = this.assets.info(s);
|
||
return {
|
||
symbol: s.symbol, name: s.name, kind: s.kind, sector: s.kind, last: s.last, prevClose: s.prevClose, open: s.open,
|
||
change: rd((s.last / s.prevClose - 1) * 100, 3), high: s.high, low: s.low, volume: s.volume,
|
||
bid: s.book.bestBid(), ask: s.book.bestAsk(), mcap: null, vol: rd(this.econ.volNow(s), 3), pe: null,
|
||
divYield: s.kind === 'bond' ? rd(s.coupon / 100 / (s.last / 100), 5) : null, yield: rd(info.yield ?? null, 3), duration: rd(info.duration ?? null, 2),
|
||
status: st, volaEndsAt: s.volaEndsAt || 0, indicative: s.indicative ?? null,
|
||
htb: this.ex.lendUtil(s) > 0.9, borrowRate: rd(this.ex.lendRate(s), 4), earningsIn: null, exDivIn: s.kind === 'bond' ? info.nextCouponIn : null,
|
||
allDay: !!s.allDay, noShort: !!s.noShort, close: s.close ?? null, eve: this.ex.eveningQuote(s),
|
||
issuer: s.issuer ?? null, rating: s.issuer ? this.credit.ratingOf(s.issuer) : null,
|
||
...(s.kind === 'etf' ? { nav: rd(info.nav, 3), premium: rd(info.premium, 5), ter: info.ter, divYield: rd(info.distYield, 5), exDivIn: info.nextDistIn } : {}),
|
||
};
|
||
}
|
||
const eps = epsTTM(s.fund);
|
||
const corp = this.corp.offers.find((o) => o.target === s.symbol) ? 'offer' : this.merger.badge(s.symbol) ?? this.spinoff.badge(s.symbol) ?? (this.corp.trials.find((t) => t.symbol === s.symbol) ? 'trial' : null);
|
||
return {
|
||
kind: 'stock', corp,
|
||
symbol: s.symbol, name: s.name, sector: s.sector, last: s.last, prevClose: s.prevClose, open: s.open,
|
||
change: rd((s.last / s.prevClose - 1) * 100, 3), high: s.high, low: s.low, volume: s.volume,
|
||
bid: s.book.bestBid(), ask: s.book.bestAsk(), mcap: Math.round(s.last * s.shares), vol: rd(this.econ.volNow(s), 3),
|
||
pe: eps > 0 ? rd(s.last / eps, 2) : null, divYield: rd((s.fund.lastDividend * 4) / s.last, 5),
|
||
status: st, volaEndsAt: s.volaEndsAt || 0, indicative: s.indicative ?? null,
|
||
htb: this.ex.lendUtil(s) > 0.9, borrowRate: rd(this.ex.lendRate(s), 4),
|
||
earningsIn: s.fund.nextEarningsDay - this.day, exDivIn: s.fund.exDivDay ? s.fund.exDivDay - this.day : null,
|
||
ipoDay: s.ipo?.day ?? null, close: s.close ?? null, eve: this.ex.eveningQuote(s), rating: this.credit.ratingOf(s.symbol),
|
||
seg: this.indices.segOf(s.symbol), turnover: Math.round(s.turnover ?? 0),
|
||
...(this.marks.of(s.symbol) ? { mark: this.marks.of(s.symbol) } : {}),
|
||
};
|
||
});
|
||
}
|
||
|
||
reportingSeason() {
|
||
return this.listed().filter((s) => { if (s.kind !== 'stock') return false; const k = s.fund.nextEarningsDay - this.day; return k >= 0 && k <= 3; }).length >= 3;
|
||
}
|
||
|
||
marketView() {
|
||
return {
|
||
day: this.day, ...this.phaseView(), index: this.index(), indices: this.indices.view(), tickers: this.tickers(), macro: this.econ.publicMacro(),
|
||
marketHaltLevel: this.ex.marketHaltLevel, season: { n: this.season.n, endsAt: this.season.endsAt, scenario: this.season.scenario ? { id: this.season.scenario.id, title: this.season.scenario.title, desc: this.season.scenario.desc } : null },
|
||
politics: { coalition: this.gov.coalition ? this.gov.coalition.parties.map((id) => this.gov.party(id)?.short) : [], rating: this.gov.budget.rating, electionAt: this.gov.election?.done ? null : this.gov.election?.at ?? null, noConfidence: !!this.gov.noConf },
|
||
reportingSeason: this.reportingSeason(),
|
||
};
|
||
}
|
||
|
||
/** Kursverlauf eines Wertpapiers für einen Zeitraum (1T · 1W · 1M · 1Q · 1J · Max), siehe chartrange.js */
|
||
chartRange(symbol, range = '1M') {
|
||
const s = this.stocks.get(symbol);
|
||
if (!s) throw new Error('Unbekanntes Wertpapier');
|
||
const n = rangeDays(range, this.cfg);
|
||
const stored = this.store.dailyBarsFrom(symbol, n === null ? 0 : Math.max(0, this.day - Math.max(n, 1) - 2));
|
||
return { symbol, ...buildRange({ range, cfg: this.cfg, day: this.day, phase: this.market.phase, stock: s, stored, now: this.clock.now() }) };
|
||
}
|
||
|
||
company(symbol, pid = null) {
|
||
const s = this.stocks.get(symbol);
|
||
if (!s) throw new Error('Unbekanntes Wertpapier');
|
||
if (s.delisted) return this.#delistedView(s);
|
||
if (s.kind !== 'stock') return this.#instrument(s);
|
||
const f = s.fund;
|
||
const eps = epsTTM(f);
|
||
const holders = [];
|
||
let shortInterest = 0;
|
||
for (const p of this.players.values()) {
|
||
if (p.banned) continue;
|
||
const q = p.positions[symbol]?.qty ?? 0;
|
||
if (q > 0) holders.push({ name: p.name, qty: q, pct: (q / s.shares) * 100 });
|
||
if (q < 0) shortInterest += -q;
|
||
}
|
||
holders.sort((a, b) => b.qty - a.qty);
|
||
// Orderfluss nur vom Vortag (T+1) – kein Echtzeit-Signal
|
||
const fp = s.flowPrev;
|
||
const total = fp ? Object.entries(fp).filter(([k]) => k !== 'day').reduce((a, [, v]) => a + v, 0) : 0;
|
||
return {
|
||
symbol, name: s.name, sector: s.sector, sectorName: SECTORS[s.sector].name, mark: this.marks.of(symbol), desc: s.desc, founded: s.founded, hq: s.hq, employees: s.employees,
|
||
last: s.last, prevClose: s.prevClose, shares: s.shares, mcap: s.last * s.shares, vol: this.econ.volNow(s), baseVol: s.vol, growth: f.g ?? s.growth,
|
||
epsTTM: eps, pe: eps > 0 ? s.last / eps : null, sectorPe: SECTORS[s.sector].pe,
|
||
payout: payoutOf(s), lastDividend: f.lastDividend, divYield: (f.lastDividend * 4) / s.last,
|
||
pendingDividend: f.pendingDividend, exDivDay: f.exDivDay, exDivIn: f.exDivDay ? f.exDivDay - this.day : null,
|
||
consensus: f.consensus, nextEarningsDay: f.nextEarningsDay, earningsIn: f.nextEarningsDay - this.day, day: this.day, quarters: f.quarters.slice(-8),
|
||
analysts: f.analysts ? { buy: f.analysts.buy, hold: f.analysts.hold, sell: f.analysts.sell, target: f.analysts.target, low: f.analysts.low, high: f.analysts.high, ratings: f.analysts.ratings } : null,
|
||
policy: (f.policy ?? []).map((x) => ({ bill: x.bill, pct: (Math.exp(x.log) - 1) * 100, startDay: x.startDay })),
|
||
holders: holders.slice(0, 10), shortInterest, lending: this.ex.lendInfo(s),
|
||
flowPrev: fp ? {
|
||
day: fp.day,
|
||
bots: Object.fromEntries(Object.keys(ARCHETYPES).map((k) => [k, { ...ARCHETYPES[k], qty: fp[k] ?? 0, pct: total ? (fp[k] ?? 0) / total : 0 }])),
|
||
players: { qty: fp.players ?? 0, pct: total ? (fp.players ?? 0) / total : 0 },
|
||
} : null,
|
||
status: this.ex.status(s), volaEndsAt: s.volaEndsAt || 0, indicative: s.indicative, lastAuction: s.lastAuction,
|
||
news: this.news.filter((n) => n.symbol === symbol || n.affected?.includes(symbol) || n.sectors?.includes(s.sector)).slice(0, 15),
|
||
dailyBars: this.store.dailyBars(symbol, 120),
|
||
kind: 'stock', corporate: { ...this.corp.view(symbol, pid), spinoff: this.spinoff.view(symbol, pid), merger: this.merger.view(symbol, pid) },
|
||
oilSens: SECTORS[s.sector].oil, gasSens: s.gasSens ?? SECTORS[s.sector].gas ?? 0, fxSens: SECTORS[s.sector].fx,
|
||
ministry: MINISTRIES.find((m) => m.sectors.includes(s.sector))?.name ?? null,
|
||
seg: this.indices.segOf(symbol), liq: s.liq ?? 1, indexWeights: this.indices.weightsOf(symbol),
|
||
structure: this.holdings.structure(s), stake: this.holdings.stakeView(pid, s),
|
||
split: this.splits.view(symbol), chronicle: this.chronicle.view(symbol),
|
||
credit: this.credit.companyView(s), outlook: this.econ.outlookView()?.find((o) => o.sector === s.sector) ?? null,
|
||
};
|
||
}
|
||
|
||
/** Eingestellte Aktie/Anleihe (alter Link, Journal): Hinweis statt Handelsmaske */
|
||
#delistedView(s) {
|
||
return {
|
||
symbol: s.symbol, name: s.name, kind: s.kind, sector: s.sector ?? null, sectorName: SECTORS[s.sector]?.name ?? null, desc: s.desc ?? '',
|
||
founded: s.founded ?? null, hq: s.hq ?? null, last: s.last, prevClose: s.prevClose, shares: s.shares ?? null, day: this.day,
|
||
delisted: this.delist.info(s),
|
||
news: this.news.filter((n) => n.symbol === s.symbol || n.affected?.includes(s.symbol)).slice(0, 10),
|
||
dailyBars: this.store.dailyBars(s.symbol, 120),
|
||
corporate: s.kind === 'stock' ? { history: this.corp.history.filter((h) => h.symbol === s.symbol).slice(0, 8) } : null,
|
||
chronicle: this.chronicle.view(s.symbol), mark: this.marks.of(s.symbol) ?? null,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* „Ehemalige Firmen“: alle von der Börse genommenen Aktien (neueste zuerst) mit Grund, Abfindung, letztem Kurs,
|
||
* Kurs beim Börsengang bzw. Ausgangskurs (beide splitbereinigt) und einer kleinen Verlaufslinie der letzten Tagesschlüsse.
|
||
*/
|
||
formerCompanies() {
|
||
const list = [];
|
||
for (const s of this.stocks.values()) {
|
||
if (s.kind !== 'stock' || !s.delisted) continue;
|
||
const d = this.delist.info(s);
|
||
let bars = [];
|
||
try { bars = this.store.dailyBars(s.symbol, 40); } catch { /* ohne Speicher */ }
|
||
const ipo = s.ipo?.price ?? null;
|
||
list.push({
|
||
symbol: s.symbol, name: s.name, sector: s.sector, sectorName: SECTORS[s.sector]?.name ?? s.sector, mark: this.marks.of(s.symbol) ?? null,
|
||
founded: s.founded ?? null, hq: s.hq ?? null, desc: s.desc ?? '',
|
||
day: d.day, ts: d.ts, reason: d.reason, reasonText: d.reasonText, why: d.why, price: d.price, last: d.last, byName: d.byName,
|
||
startPrice: ipo ?? s.price ?? null, startKind: ipo ? 'ipo' : 'start', ipoDay: s.ipo?.day ?? null,
|
||
spark: bars.map((b) => b.c).filter((x) => Number.isFinite(x)),
|
||
events: this.chronicle.count(s.symbol),
|
||
});
|
||
}
|
||
list.sort((a, b) => (b.ts ?? 0) - (a.ts ?? 0) || (b.day ?? 0) - (a.day ?? 0));
|
||
return { list, day: this.day };
|
||
}
|
||
|
||
/** Detailansicht für Anleihen, Rohstoffe, Devisen */
|
||
#instrument(s) {
|
||
const holders = [];
|
||
let shortInterest = 0;
|
||
for (const p of this.players.values()) {
|
||
if (p.banned) continue;
|
||
const q = p.positions[s.symbol]?.qty ?? 0;
|
||
if (q > 0) holders.push({ name: p.name, qty: q, pct: null });
|
||
if (q < 0) shortInterest += -q;
|
||
}
|
||
holders.sort((a, b) => b.qty - a.qty);
|
||
const fp = s.flowPrev;
|
||
const total = fp ? Object.entries(fp).filter(([k]) => k !== 'day').reduce((a, [, v]) => a + v, 0) : 0;
|
||
return {
|
||
symbol: s.symbol, name: s.name, kind: s.kind, kindName: ASSET_CLASSES[s.kind], desc: s.desc, last: s.last, prevClose: s.prevClose,
|
||
vol: this.econ.volNow(s), baseVol: s.vol, info: this.assets.info(s), curve: s.kind === 'bond' ? this.assets.curve() : null,
|
||
budget: s.kind === 'bond' ? { debt: this.gov.budget.debt, deficit: this.gov.budget.deficit, rating: this.gov.budget.rating, riskPremium: this.gov.riskPremium() } : null,
|
||
foreignRate: s.kind === 'fx' ? this.assets.foreignRate : null, rate: this.macro.rate,
|
||
gas: s.symbol === 'GAS' ? this.assets.gasInfo() : null, credit: s.issuer ? this.credit.bondView(s) : null,
|
||
etf: s.kind === 'etf' ? this.etfs.detail(s) : null,
|
||
holders: holders.slice(0, 10), shortInterest, lending: this.ex.lendInfo(s),
|
||
flowPrev: fp ? {
|
||
day: fp.day,
|
||
bots: Object.fromEntries(Object.keys(ARCHETYPES).map((k) => [k, { ...ARCHETYPES[k], qty: fp[k] ?? 0, pct: total ? (fp[k] ?? 0) / total : 0 }])),
|
||
players: { qty: fp.players ?? 0, pct: total ? (fp.players ?? 0) / total : 0 },
|
||
} : null,
|
||
status: this.ex.status(s), volaEndsAt: s.volaEndsAt || 0, indicative: s.indicative, lastAuction: s.lastAuction,
|
||
news: this.news.filter((n) => n.symbol === s.symbol || n.affected?.includes(s.symbol)).slice(0, 15),
|
||
dailyBars: this.store.dailyBars(s.symbol, 120),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Datum je Handelstag (für Achsen und Listen statt „Tag 123“): vergangene Tage aus den gespeicherten Tagesbalken,
|
||
* Lücken rückwärts über den Börsenkalender, künftige Tage aus dem Kalender. Im Turbo-Modus gibt es keine Daten.
|
||
* Zwischengespeichert je Handelstag und Phase.
|
||
*/
|
||
dayDates() {
|
||
if (this.clock.turbo) return { dated: false, day: this.day, map: {} };
|
||
const key = `${this.day}:${this.market.phase}`;
|
||
if (this._dayDates?.key === key) return this._dayDates.v;
|
||
const now = this.clock.now();
|
||
const st = this.phaseInfo ?? this.clock.state(now);
|
||
// geschlossen: die Uhr zeigt schon auf die nächste Sitzung, der Spieltag zählt erst zur Vorbörse hoch
|
||
const off = this.market.phase === 'closed' && (!this.market.date || st.date !== this.market.date) ? 1 : 0;
|
||
const map = {};
|
||
try { for (const r of this.store.dayTimes()) if (r.day <= this.day) map[r.day] = r.ts; } catch { /* ohne Speicher */ }
|
||
map[this.day] ??= now;
|
||
for (let k = 1; k <= 400; k++) map[this.day + k] = this.clock.tradingDayStart(Math.max(0, k - off), now);
|
||
// Lücken in der Vergangenheit: Handelstage rückwärts zählen (Wochenenden und Feiertage überspringen)
|
||
for (let d = this.day - 1; d >= 0; d--) {
|
||
if (map[d]) continue;
|
||
let t = map[d + 1] - 86_400_000;
|
||
for (let i = 0; i < 10; i++) { const x = new Date(t); if (isTradingDate(x.getUTCFullYear(), x.getUTCMonth() + 1, x.getUTCDate())) break; t -= 86_400_000; }
|
||
map[d] = t;
|
||
}
|
||
const v = { dated: true, day: this.day, map };
|
||
this._dayDates = { key, v };
|
||
return v;
|
||
}
|
||
|
||
/** Ereigniskalender: Zahlen, Ex-Tage, Konjunkturdaten, Zinsentscheid, Abstimmungsende, Saisonende */
|
||
calendar(p = null) {
|
||
const now = this.clock.now();
|
||
const cfg = this.cfg;
|
||
const items = [];
|
||
const st = this.phaseInfo ?? this.clock.state(now);
|
||
// nach Handelsschluss zeigt die Uhr schon auf den nächsten Handelstag, der Spieltag zählt aber erst zur Vorbörse hoch
|
||
const off = this.market.phase === 'closed' && this.market.date && st.date !== this.market.date ? 1 : 0;
|
||
const at = (k) => this.clock.tradingDayStart(Math.max(0, k - off), now);
|
||
for (const s of this.listed()) {
|
||
if (s.kind === 'bond') {
|
||
const kc = Math.max(0, cfg.quarterDays - (this.day - (s.asset?.couponStart ?? this.day)));
|
||
items.push({ ts: at(kc), dayIn: kc, kind: 'exdiv', symbol: s.symbol, title: `${s.symbol} Kuponzahlung`, detail: `${fmt(s.coupon / 4)} € je 100 € Nennwert` });
|
||
}
|
||
if (s.kind !== 'stock') continue;
|
||
const k = s.fund.nextEarningsDay - this.day;
|
||
const streak = streakText(s.fund);
|
||
if (k >= 0 && k <= cfg.quarterDays) items.push({ ts: at(k), dayIn: k, kind: 'earnings', symbol: s.symbol, title: `Quartalszahlen ${s.name}`, detail: `Konsens ${fmt(s.fund.consensus)} € je Aktie${streak ? ` · ${streak}` : ''}` });
|
||
if (s.fund.exDivDay) {
|
||
const kd = s.fund.exDivDay - this.day;
|
||
items.push({ ts: at(kd), dayIn: kd, kind: 'exdiv', symbol: s.symbol, title: `${s.symbol} ex Dividende`, detail: `${fmt(s.fund.pendingDividend)} € je Aktie` });
|
||
}
|
||
}
|
||
const km = cfg.macroEveryDays - (this.day % cfg.macroEveryDays);
|
||
items.push({ ts: at(km), dayIn: km, kind: 'macro', title: 'Konjunkturdaten (Inflation, Wachstum, Arbeitslosigkeit)', detail: 'Statistikamt, zur Vorbörse' });
|
||
items.push({ ts: at(km), dayIn: km, kind: 'macro', symbol: 'GAS', title: 'Gasspeicher-Bericht (Füllstand)', detail: 'Netzagentur Wiborien, zur Vorbörse' });
|
||
const cbDay = this.econ.nextCbDay();
|
||
const kc = cbDay - this.day;
|
||
const hm = (t) => { const [h, m] = t.split(':').map(Number); return (h * 60 + m) * 60_000; };
|
||
const cbOffset = this.clock.turbo ? cfg.dayMs * 0.5 : hm(cfg.openTime) - hm(cfg.preOpenTime) + (hm(cfg.closeTime) - hm(cfg.openTime)) * 0.6;
|
||
const cbTs = kc === 0 && this.econ.cbAt ? this.econ.cbAt : at(kc) + cbOffset;
|
||
const e = this.econ.cbExpect;
|
||
items.push({ ts: cbTs, dayIn: kc, kind: 'cb', title: 'Zinsentscheid der Zentralbank', detail: e ? `Markt erwartet ${e.mean >= 0 ? '+' : ''}${Math.round(e.mean * 100)} Bp.` : '' });
|
||
items.push(...this.pol.calendarItems());
|
||
items.push(...this.corp.calendarItems(at));
|
||
items.push(...this.spinoff.calendarItems(at), ...this.merger.calendarItems(at));
|
||
items.push(...this.credit.calendarItems(at));
|
||
items.push(...this.agm.calendarItems());
|
||
items.push(...this.splits.calendarItems(at));
|
||
if (cfg.macroEveryDays >= 2) {
|
||
const half = Math.floor(cfg.macroEveryDays / 2);
|
||
let ki = (half - (this.day % cfg.macroEveryDays) + cfg.macroEveryDays) % cfg.macroEveryDays;
|
||
if (ki === 0 && this.market.phase !== 'closed') ki = cfg.macroEveryDays;
|
||
items.push({ ts: at(ki), dayIn: ki, kind: 'macro', title: 'Frühindikatoren (Einkaufsmanagerindex, Klimaindex)', detail: 'zur Vorbörse' });
|
||
}
|
||
const el = this.gov.election;
|
||
if (el && !el.done) items.push({ ts: el.at, kind: 'election', title: 'Parlamentswahl in Wiborien', detail: `${Object.keys(el.votes).length} Spielerstimmen abgegeben` });
|
||
if (this.gov.noConf) items.push({ ts: this.gov.noConf.endsAt, kind: 'bill', title: 'Abstimmung über das Misstrauensvotum' });
|
||
for (const l of this.pol.laws.filter((x) => !x.applied)) items.push({ ts: at(Math.max(0, l.inForceDay - this.day)), dayIn: l.inForceDay - this.day, kind: 'law', title: `Inkrafttreten: ${l.title}` });
|
||
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 };
|
||
}
|
||
|
||
/** Morgenbriefing: Nachrichten seit Handelsschluss, Termine des Tages, Lage der eigenen Positionen */
|
||
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(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);
|
||
return { symbol: sym, qty: x.qty, last: s.last, prevClose: s.prevClose, indicative: s.indicative?.price ?? null, change: (s.last / s.prevClose - 1) * 100 };
|
||
}) : [];
|
||
const ph = this.phaseView();
|
||
return {
|
||
phase: ph, phaseText: ph.label, news, today, holdings, macro: this.econ.publicMacro(),
|
||
parliament: this.pol.view(p?.id), index: this.index(), reportingSeason: cal.reportingSeason,
|
||
curve: this.assets.curve(), assets: this.tickers().filter((t) => t.kind !== 'stock' && !t.issuer).map((t) => ({ symbol: t.symbol, name: t.name, kind: t.kind, last: t.last, change: t.change, yield: t.yield })),
|
||
government: { coalition: this.gov.view().coalition, rating: this.gov.budget.rating, election: this.gov.election?.done ? null : this.gov.election?.at },
|
||
scenario: this.season.scenario ?? null,
|
||
ratingChanges: this.credit.history.filter((h) => h.ts >= since).slice(0, 8).map((h) => ({ ...h, name: this.stocks.get(h.symbol)?.name ?? h.symbol })),
|
||
};
|
||
}
|
||
|
||
seasonReview(p, season) { return this.review.view(p, season); }
|
||
journal(p) { return { rows: this.store.journal(p.id, this.season.n), stats: this.store.journalStats(p.id, this.season.n) }; }
|
||
|
||
// ================================================================ Admin
|
||
adminPlayers() {
|
||
return [...this.players.values()].map((p) => ({
|
||
id: p.id, name: p.name, email: p.email, isAdmin: p.isAdmin, banned: p.banned, joined: p.joined, lastSeen: p.lastSeen,
|
||
equity: this.equity(p), trades: p.trades, elo: Math.round(p.elo), achievements: p.achievements.length, level: levelOf(p.xp ?? 0),
|
||
shortValue: this.margin(p).short, compliance: p.compliance, locked: !!p.locked, mutedUntil: p.mutedUntil ?? 0, online: this.isOnline(p.id),
|
||
rival: p.rival ? { char: p.rival.char, active: !!p.rival.active } : undefined,
|
||
}));
|
||
}
|
||
|
||
adminAction(actor, action, { id, value } = {}) {
|
||
const p = id ? this.players.get(id) : null;
|
||
const needs = ['reset', 'ban', 'unban', 'admin', 'delete', 'cash', 'clearCompliance', 'mute', 'unmute'];
|
||
if (needs.includes(action) && !p) throw new Error('Spieler nicht gefunden');
|
||
if (p?.rival && ['admin', 'mute', 'unmute'].includes(action)) throw new Error('Nicht möglich für computergesteuerte Rivalen');
|
||
if (p && p.id === actor.id && ['ban', 'delete', 'admin'].includes(action)) throw new Error('Diese Aktion ist am eigenen Konto nicht möglich');
|
||
let detail = p ? { player: p.name } : {};
|
||
switch (action) {
|
||
case 'reset': this.ex.cancelAll(p.id); this.bat.cancelFor(p.id, 'Depot zurückgesetzt'); Object.assign(p, this.#freshAccount()); break;
|
||
case 'ban':
|
||
p.banned = true; this.ex.cancelAll(p.id); this.bat.cancelFor(p.id, 'Spieler gesperrt');
|
||
this.sessions.revokeAll(p.id); this.kick(p.id, 'Dein Konto wurde gesperrt.');
|
||
break;
|
||
case 'unban': p.banned = false; break;
|
||
case 'admin': p.isAdmin = !!value; detail.value = !!value; break;
|
||
case 'cash': {
|
||
const v = Number(value);
|
||
if (!Number.isFinite(v) || Math.abs(v) > 1e9) throw new Error('Ungültiger Betrag');
|
||
p.cash += v; detail.value = v;
|
||
this.recordFill({ ts: Date.now(), owner: p.id, account: p.id, symbol: '-', side: v >= 0 ? 'deposit' : 'withdraw', qty: 0, price: Math.abs(v), fee: 0, realized: 0, kind: 'admin' }); // Betrag im Feld price (Journal, Prüf-Simulation)
|
||
this.social.notify(p.id, { kind: 'admin', title: v >= 0 ? 'Nachschuss gutgeschrieben' : 'Belastung durch die Spielleitung', text: `${fmt(v)} €` });
|
||
break;
|
||
}
|
||
case 'clearCompliance': p.compliance = { cases: 0, warnings: 0, fines: 0, finedTotal: 0 }; break;
|
||
case 'mute': {
|
||
const min = clamp(Number(value) || 60, 1, 60 * 24 * 30);
|
||
p.mutedUntil = Date.now() + min * 60_000; detail.minutes = min; break;
|
||
}
|
||
case 'unmute': p.mutedUntil = 0; break;
|
||
case 'delete':
|
||
if (p.rival) this.rivals.removed(p);
|
||
this.ex.cancelAll(p.id); this.bat.cancelFor(p.id, 'Spieler gelöscht'); this.sessions.revokeAll(p.id);
|
||
this.kick(p.id, 'Dein Konto wurde gelöscht.');
|
||
this.gov.dropPlayer(p.id); this.pol.dropPlayer(p.id); this.corp.dropPlayer(p.id);
|
||
this.players.delete(p.id); this.deletedPlayers.add(p.id); this.orderClientIds.delete(p.id);
|
||
for (const q of this.players.values()) if (q.follows?.includes(p.id)) { q.follows = q.follows.filter((x) => x !== p.id); this.markDirty(q); }
|
||
break;
|
||
case 'deleteAnalysis': this.analyses.remove(value); detail = { analysis: String(value) }; break;
|
||
case 'deleteComment': this.store.deleteComment(value); this.broadcast({ type: 'commentDeleted', id: Number(value) }); detail = { comment: Number(value) }; break;
|
||
case 'endSeason': this.endSeason(); break;
|
||
case 'rivalsRestore': this.rivals.restoreAll(); this.rivals.ensure().catch(() => {}); break;
|
||
case 'centralBank': this.econ.cbAt = this.clock.now(); break;
|
||
case 'nextBill': this.pol.close(); break;
|
||
case 'earnings': {
|
||
const s = this.stocks.get(value);
|
||
if (!s) throw new Error('Unbekanntes Symbol');
|
||
s.fund.nextEarningsDay = this.day + 1; detail = { symbol: value, note: 'Zahlen zum nächsten Handelstag' };
|
||
break;
|
||
}
|
||
case 'news': {
|
||
const v = value ?? {};
|
||
const title = cleanText(v.title, 200);
|
||
if (title.length < 5) throw new Error('Titel zu kurz');
|
||
const an = analyzeNews(title); // Themen (Öl, Zinsen, …) aus dem Text; Stimmung und Branchen bestimmt der Admin
|
||
this.addNews({ id: `admin-${Date.now()}`, title, source: 'Redaktion (Admin)', real: false, sentiment: clamp(Number(v.sentiment) || 0, -1, 1), sectors: [].concat(v.sectors ?? []), ts: Date.now(),
|
||
analysis: { by: 'regeln', topics: an.topics, strength: 0.8, reasons: an.reasons } });
|
||
detail = { title };
|
||
break;
|
||
}
|
||
case 'broadcast': {
|
||
const text = cleanText(value, 300);
|
||
this.broadcast({ type: 'announcement', text });
|
||
detail = { text };
|
||
break;
|
||
}
|
||
case 'tournament': detail = this.tour.admin(actor, value ?? {}); break;
|
||
case 'scenario': {
|
||
if (typeof value !== 'string' || !Object.hasOwn(SCENARIOS, value)) throw new Error('Unbekanntes Szenario');
|
||
applyScenario(this, value); detail = { scenario: value }; break;
|
||
}
|
||
case 'takeover': {
|
||
const o = this.corp.takeover(value?.target ?? value, value?.bidder);
|
||
if (!o) throw new Error('Kein passender Bieter gefunden');
|
||
detail = { target: o.target, bidder: o.bidder, price: o.price }; break;
|
||
}
|
||
case 'capitalIncrease': case 'buyback': case 'trial': {
|
||
const s = this.stocks.get(value);
|
||
if (!s || s.kind !== 'stock') throw new Error('Unbekannte Aktie');
|
||
if (action === 'capitalIncrease') this.corp.capitalIncrease(s);
|
||
else if (action === 'buyback') this.corp.buyback(s);
|
||
else this.corp.announceTrial(s);
|
||
detail = { symbol: value }; break;
|
||
}
|
||
case 'oilShock': {
|
||
const v = clamp(Number(value) || 0.15, -0.5, 0.5);
|
||
this.assets.oilShock(v); detail = { size: v }; break;
|
||
}
|
||
case 'gasEvent': {
|
||
const ev = this.assets.gasEvent();
|
||
if (!ev) throw new Error('Erdgas nicht vorhanden');
|
||
detail = { event: ev.title }; break;
|
||
}
|
||
case 'agm': {
|
||
const m = this.agm.announce(this.stocks.get(String(value ?? '')));
|
||
detail = { agm: m.id, symbol: m.symbol }; break;
|
||
}
|
||
case 'cryptoEvent': {
|
||
const ev = this.assets.cryptoEvent();
|
||
if (!ev) throw new Error('WiboCoin nicht vorhanden');
|
||
detail = { event: ev.title ?? ev.text ?? 'Krypto' }; break;
|
||
}
|
||
case 'delist': {
|
||
// Spielleitung nimmt eine Aktie von der Börse: Abfindung zum letzten Kurs (oder angegebenem Preis)
|
||
const v = typeof value === 'object' && value ? value : { symbol: value };
|
||
const s = this.stocks.get(String(v.symbol ?? ''));
|
||
if (!s || s.kind !== 'stock') throw new Error('Unbekannte Aktie');
|
||
const px = v.price === undefined || v.price === null || v.price === '' ? s.last : Number(v.price);
|
||
if (!(px >= 0) || px > s.last * 3) throw new Error('Ungültiger Abfindungspreis');
|
||
const r = this.delist.delist(s, { reason: 'admin', price: px, why: cleanText(v.why ?? '', 120) || 'durch die Spielleitung' });
|
||
detail = { symbol: s.symbol, price: r.price, accounts: r.accounts, replacement: r.replacement }; break;
|
||
}
|
||
case 'spinoff': {
|
||
// Abspaltung ankündigen (Stichtag nach cfg.spinoffNoticeDays)
|
||
const v = typeof value === 'object' && value ? value : { symbol: value };
|
||
const x = this.spinoff.announce({ symbol: v.symbol || undefined, name: v.name || undefined, ratio: v.ratio, alpha: v.alpha, source: 'admin' });
|
||
detail = { parent: x.parent, child: x.symbol, name: x.name, ratio: x.ratio, alpha: x.alpha, recordDay: x.recordDay }; break;
|
||
}
|
||
case 'merger': {
|
||
// Fusion per Aktientausch ankündigen (Hauptversammlung, Kartellprüfung, Vollzug)
|
||
const v = typeof value === 'object' && value ? value : { target: value };
|
||
const d = this.merger.announce({ target: v.target || undefined, buyer: v.buyer || undefined, source: 'admin' });
|
||
detail = { target: d.target, buyer: d.buyer, ratio: d.ratio, premium: d.premium, endDay: d.endDay }; break;
|
||
}
|
||
case 'split': {
|
||
// Aktiensplit/Zusammenlegung: „jetzt“ = sofort, wenn gerade nicht fortlaufend gehandelt wird (Vorbörse, geschlossen),
|
||
// sonst zum Beginn des nächsten Handelstags; „ankündigen“ = mit der eingestellten Vorlaufzeit
|
||
const v = typeof value === 'object' && value ? value : { symbol: value };
|
||
const s = this.stocks.get(String(v.symbol ?? ''));
|
||
if (!s || s.kind !== 'stock') throw new Error('Unbekannte Aktie');
|
||
if (s.delisted) throw new Error(this.delist.error(s));
|
||
let r = v.ratio && v.ratio !== 'auto' ? parseRatio(v.ratio) : null;
|
||
if (v.ratio && v.ratio !== 'auto' && !r) throw new Error('Ungültiges Verhältnis (erlaubt: 2:1, 3:1, 4:1, 5:1, 10:1 oder 1:5, 1:10, 1:20)');
|
||
if (!r) r = s.last < (this.cfg.reverseSplitBelow || 1) ? { num: 1, den: reverseRatioFor(s.last) } : { num: splitRatioFor(s.last, this.cfg.splitThreshold || 400), den: 1 };
|
||
const quiet = ['closed', 'preopen'].includes(this.market.phase);
|
||
if (v.mode === 'announce') {
|
||
const x = this.splits.announce(s, { ...r, lead: v.lead, by: 'admin' });
|
||
detail = { symbol: s.symbol, ratio: `${x.num}:${x.den}`, effectiveDay: x.day, applied: false }; break;
|
||
}
|
||
if (this.splits.pendingOf(s.symbol)) throw new Error(`Für ${s.symbol} ist bereits ein Split angekündigt`);
|
||
if (quiet) {
|
||
const x = this.splits.apply(s, { ...r, by: 'admin' });
|
||
this.flush(true); // Tagesbalken sofort bereinigen
|
||
detail = { symbol: s.symbol, ratio: `${x.num}:${x.den}`, applied: true, price: x.price };
|
||
} else {
|
||
const x = this.splits.announce(s, { ...r, lead: 1, by: 'admin' });
|
||
detail = { symbol: s.symbol, ratio: `${x.num}:${x.den}`, effectiveDay: x.day, applied: false };
|
||
}
|
||
break;
|
||
}
|
||
case 'ipo': {
|
||
const v = typeof value === 'object' && value ? value : {};
|
||
const x = this.ipo.announce({ sector: v.sector, name: v.name, source: 'admin' });
|
||
detail = { ipo: x.id, name: x.name, symbol: x.symbol }; break;
|
||
}
|
||
case 'mark': {
|
||
// Logo-Pool: einem Börsenneuling eine andere freie Marke geben
|
||
const v = typeof value === 'object' && value ? value : {};
|
||
const sym = String(v.symbol ?? ''), key = String(v.key ?? '');
|
||
const old = this.marks.of(sym);
|
||
this.marks.reassign(sym, key);
|
||
detail = { symbol: sym, mark: key, before: old }; break;
|
||
}
|
||
case 'election': this.gov.holdNow(); detail = { seats: this.gov.seats }; break;
|
||
case 'backup': detail = { file: this.store.backup(`manuell-${new Date().toISOString().slice(0, 16).replace(/[:T]/g, '-')}`) }; break;
|
||
default: throw new Error('Unbekannte Aktion');
|
||
}
|
||
if (p && this.players.has(p.id)) this.markDirty(p);
|
||
this.metaDirty = true;
|
||
this.store.audit(actor.name, action, detail);
|
||
return detail;
|
||
}
|
||
}
|