Files
wibosim/server/src/game.js
T
db9979andClaude Opus 5.5 0e2219246f 0.15.0: Die Bevölkerung reagiert – Stimmung, Konsumklima, Proteste, Bürgerstimmen
- population.js: fünf Bevölkerungsgruppen reagieren auf Wirtschaftslage und Gesetze (Gewöhnung, spiegelbildliche Aufhebung)
- Stimmung wirkt auf Umfragen, Konsumklima (Konsum/Auto) und löst Proteste, Streiks und Zugeständnisse aus
- optional Sprachmodell: Einschätzung von Spielervorlagen (gemischt mit Regeln, begrenzt) und Bürgerstimmen
- Politik → Bevölkerung, „Wer gewinnt, wer verliert?“, Hilfe, Glossar, Handbuch, Tests, Doku

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

1072 lines
57 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.
// 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 } 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 { Corporate } from './corporate.js';
import { TOPICS, analyze as analyzeNews, fingerprint, similarity } from './newsanalysis.js';
import { Government } from './government.js';
import { SCENARIOS, applyScenario, pickScenario } from './scenarios.js';
import { Ipo } from './ipo.js';
import { Agm } from './agm.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 { 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 { Clubs } from './clubs.js';
import { Tournaments } from './tournaments.js';
import { Rivals } from './rivals.js';
import { Sessions, hashPw, checkPw } from './auth.js';
import { ACHIEVEMENTS, checkAchievements } from './achievements.js';
import * as reports from './reports.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 = () => {};
/** 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);
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();
this.tickCount = 0;
// 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, ...(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);
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.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.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);
this.agm = new Agm(this, meta.agm);
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.stocks.values()].forEach((s, idx) => {
if (s.kind === 'stock') { if (!s.fund) s.fund = this.econ.init(s, idx); } else s.asset ??= initAsset(s, this.day);
});
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);
// 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 })) 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 });
}
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.candles.slice(-300), refAuction: s.refAuction, lastAuction: s.lastAuction, lend: s.lend, flowPrev: s.flowPrev,
shares: s.shares, asset: s.asset, control: s.control,
};
}
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(), gov: this.gov.snapshot(),
pol: this.pol.snapshot(), bat: this.bat.snapshot(), prog: this.prog.snapshot(),
clubs: this.clubs.snapshot(), tour: this.tour.snapshot(), rivals: this.rivals.snapshot(), ipo: this.ipo.snapshot(), agm: this.agm.snapshot(), predict: this.predict.snapshot(), after: this.after.snapshot(), analyses: this.analyses.snapshot(), causes: this.causes.snapshot(), pop: this.pop.snapshot(),
ex: { nextCondId: this.ex.nextCondId, marketHaltLevel: this.ex.marketHaltLevel },
};
}
/** 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];
const now = Date.now();
const withMeta = force || this.metaDirty || 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.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, dayStartEquity: c, weekStartEquity: c, eqHist: [], marginWarned: false, dayStats: null,
};
}
async register({ name, password, email } = {}, 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');
const pw = await hashPw(String(password));
if (this.byName(name)) throw new Error('Name ist bereits vergeben');
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 } });
return { player: p, token: this.sessions.create(p.id) };
}
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;
return {
...c,
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, asset: sv?.asset ?? null, control: sv?.control ?? null, seeded: !!sv,
};
}
/** 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);
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) + (acc.owner ? 0 : this.clubs?.unitsValue(acc.id) ?? 0); }
margin(acc) { return marginInfo(acc, this.priceOf, this.cfg); }
/** 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,
};
});
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,
};
}
placeOrder(p, o) {
if (p.banned) throw new Error('Konto gesperrt');
return this.ex.place(p, o);
}
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, 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());
this.ex.tick(dt);
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();
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);
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;
}
this.ex.onNewDay();
this.econ.newDay();
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.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) continue; // Krypto handelt durchgehend, keine Auktion
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.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();
this.market.lastCloseAt = now;
this.#setPhase('closed');
this.prog.dayClose();
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.clubs.seasonEnd(); // Fonds auflösen und auszahlen, bevor Rückblicke erstellt und Depots zurückgesetzt werden
const recaps = this.prog.seasonEnd();
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;
p.recap = rc ?? 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 },
});
}
}
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();
for (const p of this.players.values()) { p.alerts = []; p.weekRecap = null; }
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 });
}
// ================================================================ 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) {
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;
}
const topical = Object.keys(n.analysis.topics ?? {}).length > 0;
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);
}
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 = COMPANIES.filter((c) => INDEX_SYMBOLS.has(c.symbol)).reduce((a, c) => a + c.price * c.shares, 0);
let now = 0, prev = 0;
for (const s of this.stocks.values()) { if (s.kind !== 'stock' || !INDEX_SYMBOLS.has(s.symbol)) continue; now += s.last * s.baseShares; prev += s.prevClose * s.baseShares; }
return { value: (now / base) * 10_000, change: (now / prev - 1) * 100 };
}
/** 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.stocks.values()].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: (s.last / s.prevClose - 1) * 100, high: s.high, low: s.low, volume: s.volume,
bid: s.book.bestBid(), ask: s.book.bestAsk(), mcap: null, vol: this.econ.volNow(s), pe: null,
divYield: s.kind === 'bond' ? s.coupon / 100 / (s.last / 100) : null, yield: info.yield ?? null, duration: info.duration ?? null,
status: st, volaEndsAt: s.volaEndsAt || 0, indicative: s.indicative ?? null,
htb: this.ex.lendUtil(s) > 0.9, borrowRate: this.ex.lendRate(s), earningsIn: null, exDivIn: s.kind === 'bond' ? info.nextCouponIn : null,
allDay: !!s.allDay, noShort: !!s.noShort, close: s.close ?? null, eve: this.ex.eveningQuote(s),
};
}
const eps = epsTTM(s.fund);
const corp = this.corp.offers.find((o) => o.target === s.symbol) ? 'offer' : 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: (s.last / s.prevClose - 1) * 100, high: s.high, low: s.low, volume: s.volume,
bid: s.book.bestBid(), ask: s.book.bestAsk(), mcap: s.last * s.shares, vol: this.econ.volNow(s),
pe: eps > 0 ? s.last / eps : null, divYield: (s.fund.lastDividend * 4) / s.last,
status: st, volaEndsAt: s.volaEndsAt || 0, indicative: s.indicative ?? null,
htb: this.ex.lendUtil(s) > 0.9, borrowRate: this.ex.lendRate(s),
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),
};
});
}
reportingSeason() {
return [...this.stocks.values()].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(), 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(),
};
}
company(symbol, pid = null) {
const s = this.stocks.get(symbol);
if (!s) throw new Error('Unbekanntes Wertpapier');
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, 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),
oilSens: SECTORS[s.sector].oil, fxSens: SECTORS[s.sector].fx,
ministry: MINISTRIES.find((m) => m.sectors.includes(s.sector))?.name ?? null,
};
}
/** 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,
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),
};
}
/** Ereigniskalender: Zahlen, Ex-Tage, Konjunkturdaten, Zinsentscheid, Abstimmungsende, Saisonende */
calendar() {
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.stocks.values()) {
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;
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` });
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' });
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.agm.calendarItems());
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}` });
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();
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').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,
};
}
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: 0, fee: 0, realized: 0, kind: 'admin' });
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);
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 '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 '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 '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;
}
}