Files
wibosim/server/src/rivals.js
T
db9979andClaude Opus 5.5 fe68dfd3d9 Erdgas (GAS) als neuer Rohstoff mit Saison und Gasspeicher
- Instrument GAS (Erdgas, 1 MWh): Heizsaison, Speicherfüllstand als Makrogröße, Gasmarkt-Ereignisse, schwache Ölkopplung
- Nachrichtenthema gas (Regeln und LLM-Schema), Gaspreis nicht mehr beim Öl
- Wirkung auf Inflation, BIP, Branchen und Bevölkerung (Heizkosten)
- Gesetze Gaspreisbremse und Gasspeicherpflicht, Szenario Energiekrise mit Gas
- Client: Kurs- und Makroansicht, Hilfe, Glossar, Handbuchkapitel Energie, Admin-Ereignis
- Alte Spielstände laden ohne GAS sauber, Tests in gas.test.js
- Balancing-Bericht mit GAS und Saisonkurve, Doku in BALANCING.md, API.md, README

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

723 lines
39 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.
// Rivalen: computergesteuerte Mitspieler mit eigenem Charakter.
// Sie haben ein echtes Spielerkonto (gekennzeichnet als Bot), handeln über dasselbe Orderbuch mit denselben Regeln
// (Gebühren, Margin, Aufsicht), stehen in den Ranglisten, machen Politik, nehmen Battles an, treten in Turnieren an
// und kommentieren ab und zu. Sie sehen nur, was auch Spieler sehen: Kurse, Nachrichten (mit Auswertung),
// veröffentlichte Konjunkturdaten, Analystenziele, Gesetzgebung – nie den inneren Wert.
//
// Wie viele Rivalen mitspielen, regelt das Admin-Menü: Auffüllen bis zu einer Teilnehmerzahl (Menschen + Rivalen),
// mit Mindest- und Höchstzahl. Nicht benötigte Rivalen pausieren (handeln nicht, erscheinen nicht in Ranglisten).
import { roundTick } from './orderbook.js';
import { BILL_TEMPLATES, SECTORS, NPC_PARTIES, INFL_TARGET, TREND_GDP } from './world.js';
import { hashPw } from './auth.js';
import { rnd, clamp, uid } from './util.js';
import { RivalMind } from './rivalmind.js';
const MIN = 60_000, HOUR = 3_600_000, DAY = 86_400_000;
const pick = (a) => a[Math.floor(Math.random() * a.length)];
/**
* Charaktere. every: Sekunden zwischen zwei Entscheidungen · weight: Anteil des Vermögens je Position ·
* maxPos: höchstens so viele Positionen · short: darf leerverkaufen · stop/take: Verlustbegrenzung/Gewinnmitnahme ·
* politics/chat: wie aktiv (0…1) · pos: politische Haltung (markt, staat, oeko) ·
* battle: {accept, challenge (relativ), mode}
*/
export const CHARACTERS = {
max: {
name: 'Max Momentum', title: 'Der Zocker', style: 'momentum',
desc: 'Springt auf jeden Trend auf, setzt konzentriert und scheut auch Leerverkäufe nicht. Hohe Gewinne, hohe Verluste.',
every: [25, 70], weight: 0.28, maxPos: 4, short: true, stop: 0.07, take: 0.12, politics: 0.15, chat: 0.6,
pos: { markt: 0.8, staat: -0.6, oeko: -0.4 }, battle: { accept: 0.9, challenge: 1.6, mode: 'arena' },
say: {
buy: ['{s} läuft. Ich bin dabei! 🚀', 'Trend ist dein Freund – {s} gekauft.', 'Wer zögert, verliert. Rein in {s}.'],
sell: ['{s} verliert an Schwung – raus und weiter.', 'Gewinne laufen lassen? Nicht bei {s}. Verkauft.'],
short: ['{s} geht runter, und ich verdiene mit. Short.', 'Der Trend bei {s} zeigt nach unten. Leerverkauf läuft.'],
battleWin: ['Zu langsam! 😎', 'Nächstes Mal mehr Risiko wagen.'], battleLose: ['Glück gehabt. Revanche?', 'Der Markt war heute gegen mich.'],
},
},
doris: {
name: 'Doris Dividende', title: 'Die Vorsichtige', style: 'income',
desc: 'Sammelt solide Dividendenwerte und Staatsanleihen, hält eine Bargeldreserve und verkauft nur, wenn es sich lohnt.',
every: [120, 300], weight: 0.14, maxPos: 6, short: false, stop: 0.2, take: 0.18, politics: 0.45, chat: 0.25,
pos: { markt: 0.2, staat: 0.1, oeko: 0.1 }, battle: { accept: 0.45, challenge: 0.3, mode: 'longonly' },
say: {
buy: ['{s} zahlt verlässlich Dividende. Ein Stück mehr für die Sammlung.', 'Ruhig bleiben, Qualität kaufen: {s}.'],
sell: ['Bei {s} nehme ich einen Teil des Gewinns mit. Vorsicht ist die Mutter der Porzellankiste.'],
battleWin: ['Langsam, aber sicher. ☕'], battleLose: ['Hektik ist nichts für mich. Gut gespielt!'],
},
},
nina: {
name: 'Nina Newsflash', title: 'Die Nachrichtenhändlerin', style: 'news',
desc: 'Liest jede Eilmeldung zuerst und handelt sofort – Öl, Gold, Zinsen, Branchen. Hält Positionen nur kurz.',
every: [20, 60], weight: 0.16, maxPos: 5, short: true, stop: 0.05, take: 0.06, politics: 0.3, chat: 0.55,
pos: { markt: 0.3, staat: 0.2, oeko: 0.4 }, battle: { accept: 0.75, challenge: 1, mode: 'arena' },
say: {
buy: ['„{n}“ – das ist gut für {s}. Gekauft!', 'Eilmeldung gelesen, {s} gekauft, bevor die anderen aufwachen.'],
sell: ['„{n}“ – das schadet {s}. Raus bzw. short.', 'Schlechte Nachrichten für {s}. Ich bin auf der anderen Seite.'],
short: ['„{n}“ – {s} wird leiden. Leerverkauf.'],
battleWin: ['Information ist alles. 📰'], battleLose: ['Die Nachrichtenlage war heute zäh.'],
},
},
kurt: {
name: 'Kurt Kontra', title: 'Der Querdenker', style: 'contra',
desc: 'Kauft, wenn alle verkaufen, und verkauft, wenn alle kaufen. Wettet auf Übertreibungen.',
every: [60, 150], weight: 0.15, maxPos: 5, short: true, stop: 0.08, take: 0.05, politics: 0.25, chat: 0.5,
pos: { markt: -0.2, staat: -0.3, oeko: -0.3 }, battle: { accept: 0.6, challenge: 0.8, mode: 'classic' },
say: {
buy: ['Alle verkaufen {s}? Dann kaufe ich. Übertreibung!', 'Panik bei {s} – meine Lieblingszeit zum Kaufen.'],
short: ['{s} ist heiß gelaufen. Ich halte dagegen.', 'Zu viel Euphorie bei {s}. Short.'],
sell: ['{s} ist wieder normal bewertet. Danke, Herde.'],
battleWin: ['Gegen den Strom zu schwimmen zahlt sich aus.'], battleLose: ['Der Markt bleibt länger irrational, als man denkt.'],
},
},
rita: {
name: 'Rita Rohstoff', title: 'Die Makro-Strategin', style: 'macro',
desc: 'Denkt in Zinsen, Inflation und Rohstoffen: Anleihen bei sinkender Inflation, Gold bei Angst, Öl und Gas nach Nachrichtenlage.',
every: [90, 240], weight: 0.2, maxPos: 5, short: true, stop: 0.1, take: 0.15, politics: 0.4, chat: 0.35,
pos: { markt: 0.1, staat: 0.3, oeko: 0.5 }, battle: { accept: 0.5, challenge: 0.6, mode: 'arena' },
say: {
buy: ['Makrolage spricht für {s}. Position aufgebaut.', 'Mein Modell sagt: {s} kaufen.'],
sell: ['Bei {s} hat sich das Bild gedreht. Reduziert.'], short: ['{s} ist aus Makrosicht zu teuer. Short.'],
battleWin: ['Das große Bild schlägt das Rauschen.'], battleLose: ['Kurzfristig regiert der Zufall.'],
},
},
stefan: {
name: 'Stefan Strippe', title: 'Der Strippenzieher', style: 'politics',
desc: 'Mischt in der Politik mit: gründet eine Partei, spendet ins Lobbyregister, bringt Vorlagen ein – und kauft vorher die Branchen, die profitieren.',
every: [90, 200], weight: 0.17, maxPos: 5, short: true, stop: 0.1, take: 0.14, politics: 1, chat: 0.45,
pos: { markt: 0.6, staat: 0.1, oeko: -0.2 }, battle: { accept: 0.5, challenge: 0.5, mode: 'classic' },
say: {
buy: ['Das Parlament wird {s} helfen. Ich bin vorbereitet.', 'Politik bewegt Märkte – {s} gekauft.'],
sell: ['Bei {s} weht politisch Gegenwind. Verkauft.'], short: ['Das neue Gesetz trifft {s}. Ich wette dagegen.'],
bill: ['Diese Vorlage ist gut für Wiborien – und für die Börse. Bitte mitzeichnen!'],
battleWin: ['Gute Beziehungen zahlen sich aus.'], battleLose: ['Auch in der Politik verliert man mal eine Abstimmung.'],
},
},
viktor: {
name: 'Viktor Value', title: 'Der Bewerter', style: 'value',
desc: 'Vergleicht Kurs und Kursziele der Analysten. Kauft mit Abschlag, verkauft mit Aufschlag – geduldig.',
every: [150, 360], weight: 0.16, maxPos: 5, short: true, stop: 0.15, take: 0.2, politics: 0.35, chat: 0.3,
pos: { markt: 0.5, staat: -0.2, oeko: 0 }, battle: { accept: 0.4, challenge: 0.3, mode: 'classic' },
say: {
buy: ['{s} notiert deutlich unter dem Kursziel. Schnäppchen.', 'Geduld wird belohnt: {s} gekauft.'],
sell: ['{s} hat das Kursziel erreicht. Verkauft.'], short: ['{s} ist klar überbewertet. Short.'],
battleWin: ['Bewertung schlägt Bauchgefühl.'], battleLose: ['Kurzfristig ist die Börse eine Abstimmungsmaschine …'],
},
},
ingrid: {
name: 'Ingrid Index', title: 'Die Gelassene', style: 'index',
desc: 'Kauft breit gestreut den ganzen Markt plus etwas Anleihen und rebalanciert gelegentlich. Sonst: nichts tun.',
every: [300, 720], weight: 0.085, maxPos: 12, short: false, stop: 1, take: 1, politics: 0.2, chat: 0.15,
pos: { markt: 0.3, staat: 0.2, oeko: 0.3 }, battle: { accept: 0.35, challenge: 0.2, mode: 'classic' },
say: {
buy: ['Breit streuen, ruhig schlafen. Nachgekauft.'], sell: ['Kleines Rebalancing. Mehr passiert hier nicht.'],
battleWin: ['Nichts tun ist manchmal die beste Strategie.'], battleLose: ['Langfristig gewinnt der Markt.'],
},
},
};
// Reihenfolge beim Auffüllen: abwechslungsreiche Mischung zuerst
export const RIVAL_ORDER = ['max', 'doris', 'nina', 'kurt', 'stefan', 'rita', 'viktor', 'ingrid'];
const PARTY = { name: 'Bündnis für Wohlstand', short: 'BFW' };
export class Rivals {
constructor(g, saved) {
this.g = g;
this.state = { lastChallenge: {}, lastComment: 0, removed: [], ...(saved ?? {}) };
this.newsQueue = []; // [{n, at}] – Nina reagiert mit kurzer Verzögerung
this.mind = new RivalMind(this); // optional: Sprachmodell für Lagebild, Kommentare, Politik
}
character(p) { return CHARACTERS[p?.rival?.char]; }
get cfg() { return this.g.cfg; }
snapshot() { return this.state; }
now() { return this.g.clock.now(); }
/** alle Rivalen (auch pausierte) */
all() { return [...this.g.players.values()].filter((p) => p.rival); }
active() { return this.all().filter((p) => p.rival.active && !p.banned); }
isRival(pid) { return !!this.g.players.get(pid)?.rival; }
/** Namen der Rivalen für den Client (Kennzeichnung) */
names() { return this.all().map((p) => p.name); }
info(p) {
const c = CHARACTERS[p?.rival?.char];
if (!c) return null;
const v = this.mind.view(p);
return { char: p.rival.char, title: c.title, desc: c.desc, style: c.style, active: !!p.rival.active, view: v ? { note: v.note, mood: v.mood, at: v.at } : null };
}
humans() {
const since = Date.now() - 7 * DAY;
return [...this.g.players.values()].filter((p) => !p.rival && !p.banned && ((p.lastSeen ?? p.joined ?? 0) >= since || this.g.isOnline(p.id))).length;
}
desired() {
const c = this.cfg;
if (!c.rivalsEnabled) return 0;
return clamp(c.rivalsTarget - this.humans(), c.rivalsMin, Math.min(c.rivalsMax, RIVAL_ORDER.length));
}
// ================================================================ Auffüllen
ensure() {
// läuft schon ein Durchgang (Passwort-Hash ist asynchron), auf diesen warten
this.pending ??= this.#ensure().finally(() => { this.pending = null; });
return this.pending;
}
async #ensure() {
{
const want = this.desired();
const byChar = new Map(this.all().map((p) => [p.rival.char, p]));
const keys = RIVAL_ORDER.filter((k) => !this.state.removed.includes(k)).slice(0, want);
for (const k of keys) {
let p = byChar.get(k);
if (!p) p = await this.#create(k);
if (p && !p.rival.active) {
p.rival.active = true;
p.rival.nextAt = this.now() + rnd(5, 40) * 1000;
this.g.markDirty(p);
this.g.log('player', `${p.name} (${CHARACTERS[k].title}, computergesteuert) mischt jetzt mit`);
}
}
for (const p of this.all()) {
if (p.rival.active && !keys.includes(p.rival.char)) {
p.rival.active = false;
this.g.ex.cancelAll(p.id);
this.g.bat.queueLeave(p);
this.g.markDirty(p);
this.g.log('player', `${p.name} pausiert – genug menschliche Mitspieler`);
}
}
}
}
async #create(k) {
const c = CHARACTERS[k];
let name = c.name;
for (let i = 2; this.g.byName(name); i++) name = `${c.name} ${i}`;
const pw = await hashPw(uid(16)); // nicht anmeldbar: niemand kennt das Passwort
if (this.all().some((p) => p.rival.char === k)) return null;
return this.g.createRival({ name, pw, rival: { char: k, active: false, mem: {} } });
}
/** Admin hat einen Rivalen gelöscht: nicht wieder anlegen */
removed(p) {
if (p?.rival && !this.state.removed.includes(p.rival.char)) this.state.removed.push(p.rival.char);
this.g.metaDirty = true;
}
/** Admin: gelöschte Rivalen wieder zulassen */
restoreAll() { this.state.removed = []; this.g.metaDirty = true; }
// ================================================================ Takt
tick() {
const g = this.g;
if (g.tickCount % 15 === 1) this.ensure().catch((e) => console.warn('[rivalen]', e.message));
if (!this.cfg.rivalsEnabled) return;
const now = this.now();
const act = this.active();
if (!act.length) return;
if (g.tickCount % 3 === 0) this.#invites(act);
if (g.tickCount % 30 === 7) this.#maybeChallenge(act);
if (g.tickCount % 60 === 11) this.#tournaments(act);
if (g.tickCount % 20 === 13) g.ipo?.rivalOrders();
if (g.tickCount % 20 === 17) g.agm?.rivalVotes();
if (g.tickCount % 20 === 19) g.predict?.rivalTips();
this.mind.tick();
const mult = Math.max(0.1, this.cfg.rivalsActivity || 1);
for (const p of act) {
const r = p.rival;
if (now < (r.nextAt ?? 0)) continue;
const c = CHARACTERS[r.char];
r.nextAt = now + (rnd(c.every[0], c.every[1]) * 1000) / mult / (g.clock.turbo ? 3 : 1);
try { this.#act(p, c); } catch (e) { if (process.env.RIVALS_DEBUG) console.warn('[rivale]', p.name, e.message); }
}
// Nachrichtenhändlerin: verzögerte Reaktion
if (this.newsQueue.length) {
const due = this.newsQueue.filter((x) => x.at <= now);
this.newsQueue = this.newsQueue.filter((x) => x.at > now);
for (const { n, pid } of due) {
const p = g.players.get(pid);
if (p?.rival?.active) { this.eveOk = true; try { this.#reactNews(p, n); } catch { /* egal */ } finally { this.eveOk = false; } }
}
}
}
/** neue Meldung (aus game.addNews): wer reagiert darauf? */
onNews(n) {
if (!this.cfg.rivalsEnabled || !n?.analysis || n.analysis.followUp) return;
const strong = Math.abs(n.sentiment ?? 0) >= 0.3 || Object.values(n.analysis.topics ?? {}).some((v) => Math.abs(v) >= 0.4);
if (!strong) return;
for (const p of this.active()) {
if (CHARACTERS[p.rival.char].style !== 'news') continue;
this.newsQueue.push({ n, pid: p.id, at: this.now() + rnd(4, 25) * 1000 / (this.g.clock.turbo ? 2 : 1) });
}
// mit Sprachmodell: ein gesprächiger Rivale kommentiert die Meldung beim am stärksten betroffenen Wert
if (this.mind.on && this.cfg.rivalsChat && this.#commentFree()) {
const sym = (n.affected ?? []).find((x) => this.g.stocks.has(x));
const pool = this.active().filter((p) => Math.random() < CHARACTERS[p.rival.char].chat);
const p = pool[Math.floor(Math.random() * pool.length)];
if (sym && p) {
const s = this.g.stocks.get(sym);
this.#reserveComment();
this.mind.say(p, `Eilmeldung: „${String(n.title).slice(0, 200)}“. Betroffen ist u. a. ${s.name} (${s.symbol}), Kurs ${s.last.toFixed(2)} €. Kommentiere die Meldung aus deiner Sicht als Anleger.`,
(t) => this.#post(p, `stock:${sym}`, t)).catch(() => {});
}
}
}
// ================================================================ Handeln
/** Konto, mit dem gerade gehandelt wird: im Battle (außer „Hauptdepot“-Modus) das Battle-Depot */
#account(p) {
const bt = this.g.bat.active(p.id);
if (bt && bt.mode !== 'classic') {
const acc = this.g.battleAccounts.get(bt.a === p.id ? bt.aAcc : bt.bAcc);
if (acc) return { acc, which: 'battle', rules: bt.rules ?? acc.rules ?? {} };
}
return { acc: p, which: 'main', rules: {} };
}
#act(p, c) {
const g = this.g;
if (this.cfg.rivalsPolitics && Math.random() < c.politics * 0.5) this.#politics(p, c);
if (g.market.phase !== 'continuous') return;
const ctx = this.#account(p);
this.#riskExits(p, c, ctx);
const style = { momentum: this.#momentum, income: this.#income, news: this.#newsExits, contra: this.#contra, macro: this.#macro, politics: this.#politicsTrades, value: this.#value, index: this.#index }[c.style];
style.call(this, p, c, ctx);
if (c.style !== 'index' && Math.random() < 0.35) this.#conviction(p, c, ctx);
}
/** Lagebild (Sprachmodell): bei klarer Überzeugung eine Position im stärksten Thema eröffnen */
#conviction(p, c, ctx) {
const v = this.mind.view(p);
if (!v || this.#nOpen(ctx) >= c.maxPos) return;
const ideas = [
...Object.entries(v.sectors).map(([sec, x]) => [this.#universe(ctx).filter((s) => s.sector === sec).sort((a, b) => b.last * b.shares - a.last * a.shares)[0], x]),
...Object.entries(v.assets).map(([sym, x]) => [this.#universe(ctx, ['bond', 'commodity', 'fx', 'crypto']).find((s) => s.symbol === sym), x]),
].filter(([s, x]) => s && Math.abs(x) >= 0.6 && (x > 0 || c.short) && !this.#posQty(ctx, s.symbol)).sort((a, b) => Math.abs(b[1]) - Math.abs(a[1]));
const [s, x] = ideas[0] ?? [];
if (s) this.#target(p, c, ctx, s, Math.sign(x) * this.#sizeFor(ctx, s, c.weight * Math.abs(x)), 'Lagebild');
}
/** handelbare Instrumente (im Battle ggf. eingeschränkt) */
#universe(ctx, kinds = ['stock']) {
return [...this.g.stocks.values()].filter((s) => kinds.includes(s.kind) && (this.g.ex.isContinuous(s) || (this.eveOk && this.g.ex.eveningQuote(s))) && (!ctx.rules.symbols || ctx.rules.symbols.includes(s.symbol)));
}
#posQty(ctx, sym) { return ctx.acc.positions?.[sym]?.qty ?? 0; }
#equity(ctx) { return Math.max(1, this.g.equity(ctx.acc)); }
#nOpen(ctx) { return Object.values(ctx.acc.positions ?? {}).filter((x) => x.qty !== 0).length; }
/** Kursveränderung über die letzten n Kerzen */
#ret(s, n = 20) {
const cs = s.candles ?? [];
if (cs.length < 3) return (s.last / s.prevClose) - 1;
const old = cs[Math.max(0, cs.length - n)]?.c ?? s.prevClose;
return s.last / old - 1;
}
/**
* Zielposition (Stück, negativ = short) ansteuern – mit marketable Limit (IOC) wie ein schneller Spieler.
* Kleine Abweichungen werden ignoriert, damit nicht ständig nachgehandelt wird.
*/
#target(p, c, ctx, s, targetQty, reason = '', news = null) {
if (!c.short || ctx.rules.noShort) targetQty = Math.max(0, targetQty);
const cur = this.#posQty(ctx, s.symbol);
// Lagebild (falls vorhanden): gegen die eigene Einschätzung nichts aufbauen, mit ihr etwas mehr
const flip = cur && targetQty && Math.sign(cur) !== Math.sign(targetQty);
if (targetQty && c.style !== 'index' && (flip || Math.abs(targetQty) > Math.abs(cur))) {
const v = this.mind.view(p);
if (v) {
const b = this.mind.bias(p, s) * Math.sign(targetQty);
if (b <= -0.5) { if (!flip) return false; targetQty = 0; } // nur glattstellen, nicht drehen
else targetQty *= clamp(1 + 0.5 * b, 0.5, 1.5) * (0.6 + 0.8 * v.risk);
}
}
targetQty = Math.trunc(targetQty);
let diff = targetQty - cur;
if (Math.abs(diff) < Math.max(1, Math.abs(targetQty) * 0.15) && targetQty !== 0) return false;
if (!diff) return false;
// Wer gerade über eine Vorlage abgestimmt hat, handelt die betroffenen Branchen nicht (Aufsicht!)
const cur2 = this.g.pol.cur;
if (cur2?.votes?.[p.id] && cur2.bill.effects?.[s.sector]) return false;
const eve = this.g.ex.isContinuous(s) ? null : this.g.ex.eveningQuote(s);
if (!this.g.ex.isContinuous(s) && !eve) return false; // Volatilitätsunterbrechung: abwarten
const side = diff > 0 ? 'buy' : 'sell';
// nicht mehr kaufen, als die Kaufkraft hergibt (beim Eindecken von Shorts wird Sicherheit frei)
if (side === 'buy' && cur >= 0) {
const afford = Math.floor((this.g.freeCash(ctx.acc) * 0.97) / (s.last * 1.004));
if (afford < 1) return false;
diff = Math.min(diff, afford);
}
const qty = Math.min(Math.abs(diff), eve ? eve.maxQty : 1_000_000);
const price = roundTick(s.last * (side === 'buy' ? 1.004 : 0.996));
if (eve) this.g.placeOrder(p, { symbol: s.symbol, side, qty, type: 'market', venue: 'evening', account: ctx.which === 'battle' ? 'battle' : undefined });
else this.g.placeOrder(p, { symbol: s.symbol, side, qty, type: 'limit', price, tif: 'ioc', account: ctx.which === 'battle' ? 'battle' : undefined });
p.rival.mem.entry ??= {};
if (targetQty === 0) delete p.rival.mem.entry[s.symbol];
else if (cur === 0 || Math.sign(cur) !== Math.sign(targetQty)) p.rival.mem.entry[s.symbol] = { px: s.last, ts: this.now() };
this.g.markDirty(p);
const kind = targetQty < 0 && side === 'sell' ? 'short' : side === 'buy' ? 'buy' : 'sell';
if (Math.abs(diff) * s.last > this.#equity(ctx) * 0.05) this.#say(p, c, kind, s, news);
return true;
}
#sizeFor(ctx, s, w) { return Math.floor((this.#equity(ctx) * w) / Math.max(0.01, s.last)); }
/** Stop-Loss und Gewinnmitnahme für alle Stile */
#riskExits(p, c, ctx) {
for (const [sym, pos] of Object.entries(ctx.acc.positions ?? {})) {
if (!pos.qty) continue;
const s = this.g.stocks.get(sym);
const entry = p.rival.mem.entry?.[sym]?.px ?? pos.avg ?? s.last;
const pnl = (s.last / entry - 1) * Math.sign(pos.qty);
if (pnl <= -c.stop) this.#target(p, c, ctx, s, 0, 'Stop');
else if (pnl >= c.take) this.#target(p, c, ctx, s, Math.trunc(pos.qty * (c.style === 'income' ? 0.66 : 0)), 'Gewinn');
}
}
#momentum(p, c, ctx) {
const list = this.#universe(ctx, ['stock', 'commodity', 'crypto']).map((s) => ({ s, r: this.#ret(s, 25) + rnd(-0.003, 0.003) })).sort((a, b) => b.r - a.r);
// laufende Positionen: drehen sie, raus
for (const [sym, pos] of Object.entries(ctx.acc.positions ?? {})) {
if (!pos.qty) continue;
const s = this.g.stocks.get(sym);
const r = this.#ret(s, 10);
if ((pos.qty > 0 && r < -0.015) || (pos.qty < 0 && r > 0.015)) this.#target(p, c, ctx, s, 0);
}
if (this.#nOpen(ctx) >= c.maxPos) return;
const top = list.filter((x) => x.r > 0.02).slice(0, 2);
const bottom = list.filter((x) => x.r < -0.025).slice(-1);
for (const { s } of top) if (!this.#posQty(ctx, s.symbol)) { this.#target(p, c, ctx, s, this.#sizeFor(ctx, s, c.weight)); return; }
for (const { s } of bottom) if (!this.#posQty(ctx, s.symbol)) { this.#target(p, c, ctx, s, -this.#sizeFor(ctx, s, c.weight * 0.7)); return; }
}
#income(p, c, ctx) {
const stocks = this.#universe(ctx).filter((s) => ['pharma', 'consumer', 'banks', 'energy', 'industry'].includes(s.sector))
.map((s) => ({ s, y: ((s.fund?.lastDividend ?? 0) * 4) / s.last })).sort((a, b) => b.y - a.y);
const want = stocks.slice(0, 4);
for (const { s } of want) if (!this.#posQty(ctx, s.symbol)) { this.#target(p, c, ctx, s, this.#sizeFor(ctx, s, c.weight)); return; }
// Anleihen als Ruhepol, etwas Gold
const bonds = this.#universe(ctx, ['bond']);
for (const b of bonds) if (!this.#posQty(ctx, b.symbol)) { this.#target(p, c, ctx, b, this.#sizeFor(ctx, b, 0.12)); return; }
const gold = this.g.stocks.get('GOLD');
if (gold && !ctx.rules.symbols && !this.#posQty(ctx, 'GOLD')) this.#target(p, c, ctx, gold, this.#sizeFor(ctx, gold, 0.05));
}
#newsExits(p, c, ctx) {
// Positionen aus Nachrichten nach Haltedauer schließen
const hold = (this.g.clock.turbo ? 6 : 40) * MIN;
for (const [sym, e] of Object.entries(p.rival.mem.entry ?? {})) {
if (this.now() - e.ts > hold && this.#posQty(ctx, sym)) this.#target(p, c, ctx, this.g.stocks.get(sym), 0);
}
}
#reactNews(p, n) {
const c = CHARACTERS[p.rival.char];
if (this.g.market.phase !== 'continuous' && !this.g.afterHours()) return; // abends über den Market Maker
const ctx = this.#account(p);
if (this.#nOpen(ctx) >= c.maxPos) return;
const t = n.analysis?.topics ?? {};
const moves = [];
if (Math.abs(t.oil ?? 0) >= 0.3) moves.push(['OEL', Math.sign(t.oil)]);
if (Math.abs(t.gas ?? 0) >= 0.3) moves.push(['GAS', Math.sign(t.gas)]);
if ((t.risk ?? 0) >= 0.3 || (t.gold ?? 0) >= 0.3) moves.push(['GOLD', 1]);
if (Math.abs(t.rates ?? 0) >= 0.3) moves.push(['WIB10', -Math.sign(t.rates)]);
if (Math.abs(t.usd ?? 0) >= 0.3) moves.push(['USD', Math.sign(t.usd)]);
for (const sec of n.sectors ?? []) {
const v = n.analysis?.sectorImpact?.[sec] ?? n.sentiment;
if (Math.abs(v) < 0.3) continue;
const best = this.#universe(ctx).filter((s) => s.sector === sec).sort((a, b) => b.last * b.shares - a.last * a.shares)[0];
if (best) moves.push([best.symbol, Math.sign(v)]);
}
const [sym, dir] = moves.find(([sym]) => this.g.stocks.has(sym) && (!ctx.rules.symbols || ctx.rules.symbols.includes(sym)) && !this.#posQty(ctx, sym)) ?? [];
if (!sym) return;
const s = this.g.stocks.get(sym);
this.#target(p, c, ctx, s, dir * this.#sizeFor(ctx, s, c.weight), 'Nachricht', n);
}
#contra(p, c, ctx) {
for (const [sym, pos] of Object.entries(ctx.acc.positions ?? {})) {
if (!pos.qty) continue;
const s = this.g.stocks.get(sym);
const day = s.last / s.prevClose - 1;
if (Math.abs(day) < 0.01 || (this.now() - (p.rival.mem.entry?.[sym]?.ts ?? 0)) > (this.g.clock.turbo ? 0.5 : 1.5) * DAY) this.#target(p, c, ctx, s, 0);
}
if (this.#nOpen(ctx) >= c.maxPos) return;
const list = this.#universe(ctx, ['stock', 'commodity']).map((s) => ({ s, d: s.last / s.prevClose - 1 }));
const fallen = list.filter((x) => x.d < -0.03).sort((a, b) => a.d - b.d)[0];
const risen = list.filter((x) => x.d > 0.04).sort((a, b) => b.d - a.d)[0];
if (fallen && !this.#posQty(ctx, fallen.s.symbol)) this.#target(p, c, ctx, fallen.s, this.#sizeFor(ctx, fallen.s, c.weight));
else if (risen && !this.#posQty(ctx, risen.s.symbol)) this.#target(p, c, ctx, risen.s, -this.#sizeFor(ctx, risen.s, c.weight * 0.8));
}
#macro(p, c, ctx) {
const m = this.g.econ.publicMacro();
const recent = this.g.news.filter((n) => n.ts > Date.now() - (this.g.clock.turbo ? 2 : 24) * HOUR);
const topic = (k) => recent.reduce((a, n) => a + (n.analysis?.topics?.[k] ?? 0) * (n.analysis?.followUp ? 0.3 : 1), 0);
const infl = m.inflation ?? INFL_TARGET, gdp = m.gdp ?? TREND_GDP;
const targets = {
WIB10: infl < INFL_TARGET + 0.4 && gdp < TREND_GDP + 0.3 ? 0.3 : infl > INFL_TARGET + 1.2 ? -0.12 : 0.1,
GOLD: 0.06 + (m.sentiment < -0.25 ? 0.08 : 0) + clamp(topic('risk') * 0.04, 0, 0.08),
OEL: clamp(topic('oil') * 0.06, -0.15, 0.15),
GAS: clamp(topic('gas') * 0.05, -0.12, 0.12),
USD: clamp(topic('usd') * 0.05 + ((m.rate ?? 2.5) < 3 ? 0.04 : -0.04), -0.1, 0.1),
};
const sym = pick(Object.keys(targets));
const s = this.g.stocks.get(sym);
if (!s || (ctx.rules.symbols && !ctx.rules.symbols.includes(sym))) {
// im Battle mit Aktienauswahl: einfach dem Trend der erlaubten Werte folgen
return this.#momentum(p, c, ctx);
}
this.#target(p, c, ctx, s, this.#sizeFor(ctx, s, targets[sym]));
}
#politicsTrades(p, c, ctx) {
const pipe = this.g.pol.pipeline ?? [];
const score = {};
for (const e of pipe) {
const prob = e.p ?? 0.5;
if (prob < 0.55) continue;
for (const [sec, eff] of Object.entries(e.bill.effects ?? {})) score[sec] = (score[sec] ?? 0) + eff * prob;
}
const best = Object.entries(score).sort((a, b) => Math.abs(b[1]) - Math.abs(a[1]))[0];
if (!best || Math.abs(best[1]) < 0.015) return this.#value(p, c, ctx);
const [sec, v] = best;
const s = this.#universe(ctx).filter((x) => x.sector === sec).sort((a, b) => b.last * b.shares - a.last * a.shares)[0];
if (s && !this.#posQty(ctx, s.symbol) && this.#nOpen(ctx) < c.maxPos) this.#target(p, c, ctx, s, Math.sign(v) * this.#sizeFor(ctx, s, c.weight * (v > 0 ? 1 : 0.6)));
}
#value(p, c, ctx) {
for (const [sym, pos] of Object.entries(ctx.acc.positions ?? {})) {
if (!pos.qty) continue;
const s = this.g.stocks.get(sym);
const tgt = s.fund?.analysts?.target;
if (!tgt) continue;
const up = tgt / s.last - 1;
if ((pos.qty > 0 && up < 0.03) || (pos.qty < 0 && up > -0.03)) this.#target(p, c, ctx, s, 0);
}
if (this.#nOpen(ctx) >= c.maxPos) return;
const list = this.#universe(ctx).filter((s) => s.fund?.analysts?.target).map((s) => ({ s, up: s.fund.analysts.target / s.last - 1 })).sort((a, b) => b.up - a.up);
const cheap = list.find((x) => x.up > 0.15 && !this.#posQty(ctx, x.s.symbol));
const dear = [...list].reverse().find((x) => x.up < -0.12 && !this.#posQty(ctx, x.s.symbol));
if (cheap) this.#target(p, c, ctx, cheap.s, this.#sizeFor(ctx, cheap.s, c.weight));
else if (dear) this.#target(p, c, ctx, dear.s, -this.#sizeFor(ctx, dear.s, c.weight * 0.6));
}
#index(p, c, ctx) {
const stocks = this.#universe(ctx);
const bonds = ctx.rules.symbols ? [] : this.#universe(ctx, ['bond']).slice(-1);
const w = (0.85 / Math.max(1, stocks.length));
// eine Abweichung pro Entscheidung ausgleichen – das reicht
const all = [...stocks.map((s) => [s, w]), ...bonds.map((s) => [s, 0.1])];
const off = all.map(([s, wt]) => ({ s, want: this.#sizeFor(ctx, s, wt), have: this.#posQty(ctx, s.symbol) }))
.filter((x) => Math.abs(x.want - x.have) > Math.max(1, x.want * 0.25)).sort(() => Math.random() - 0.5)[0];
if (off) this.#target(p, c, ctx, off.s, off.want);
}
// ================================================================ Politik
#politics(p, c) {
const g = this.g, gov = g.gov, pol = g.pol;
if (!gov || !pol) return;
// Partei: Stefan gründet eine, andere politische Rivalen treten bei (sonst der nächstgelegenen Volkspartei)
const own0 = gov.parties.find((x) => x.short === PARTY.short);
if (p.party && own0 && p.party !== own0.id && c.politics >= 0.4 && NPC_PARTIES.some((x) => x.id === p.party) && Math.random() < 0.1) {
gov.leave(p); gov.join(p, own0.id);
return;
}
if (!p.party) {
const own = gov.parties.find((x) => x.short === PARTY.short);
if (c.style === 'politics' && !own && g.freeCash(p) > 30_000) {
gov.found(p, { name: PARTY.name, short: PARTY.short, pos: c.pos });
} else if (own && c.politics >= 0.3 && Math.random() < 0.6) gov.join(p, own.id);
else {
gov.join(p, this.#nearestNpc(c).id);
}
return;
}
// Wahl
const e = gov.election;
if (e && !e.done && !(p.id in (e.votes ?? {}))) {
try { gov.vote(p, p.party); } catch { gov.vote(p, this.#nearestNpc(c).id); }
return;
}
// Abstimmung: eigenes Depot zuerst, sonst Haltung
const cur = pol.cur;
if (cur?.id && !cur.votes?.[p.id]) {
let expo = 0;
for (const [sym, pos] of Object.entries(p.positions)) {
const s = g.stocks.get(sym);
expo += (cur.bill.effects?.[s?.sector] ?? 0) * pos.qty * (s?.last ?? 0);
}
const yes = Math.abs(expo) > 100 ? expo > 0 : (c.pos[cur.bill.axis] ?? 0) + rnd(-0.4, 0.4) > 0;
if (!this.mind.on) { pol.vote(p, cur.id, yes); return; }
if (p.rival.mem.voting === cur.id) return; // Entscheidung läuft schon
p.rival.mem.voting = cur.id;
const bySec = {};
for (const [sym, pos] of Object.entries(p.positions)) {
const s = g.stocks.get(sym);
if (s?.kind === 'stock' && cur.bill.effects?.[s.sector] && pos.qty) bySec[s.sector] = (bySec[s.sector] ?? 0) + pos.qty * s.last;
}
this.mind.decideVote(p, cur, yes, bySec, (y, reason) => {
const e = pol.cur;
if (!e || e.id !== cur.id || e.votes?.[p.id] || !this.g.players.has(p.id)) return;
try { pol.vote(p, e.id, y); } catch { return; }
if (reason && this.cfg.rivalsChat && this.mind.speechAllowed() && this.#post(p, `bill:${e.id}`, reason)) this.mind.spoke();
}, () => { delete p.rival.mem.voting; }).catch(() => { delete p.rival.mem.voting; });
return;
}
// Vorlagen mitzeichnen (eigene Partei oder passende Richtung)
for (const x of pol.proposals ?? []) {
if (x.by === p.id || x.cosigners.includes(p.id)) continue;
const author = g.players.get(x.by);
if ((author?.party && author.party === p.party) || (c.pos[x.bill?.axis] ?? 0) > 0.3) {
pol.cosign(p, x.id);
if (Math.random() < c.chat * 0.3) this.#comment(p, `bill:${x.id}`, pick(CHARACTERS[p.rival.char].say.bill ?? ['Sinnvolle Vorlage – unterschrieben.']));
return;
}
}
// Misstrauensvotum
if (gov.noConf && !(p.id in gov.noConf.votes)) {
gov.voteNoConfidence(p, !gov.coalition?.parties?.includes(p.party));
return;
}
if (c.style !== 'politics') return;
// Strippenzieher: Vorlage für die eigene größte Branche und Lobbyspende
if (!(pol.proposals ?? []).some((x) => x.by === p.id) && Math.random() < 0.3) {
const sec = this.#topSector(p) ?? pick(Object.keys(SECTORS));
// nur Vorlagen, die nicht schon gelten oder vorliegen (sonst lehnt das Parlament sie ab)
const tpl = pick(Object.entries(BILL_TEMPLATES).filter(([k, t]) => t.eff > 0 && !pol.inForceKey?.(`pp:${k}:${sec}`)).map(([k]) => k));
if (tpl) { try { pol.propose(p, { template: tpl, sector: sec }); } catch { /* gleichartige Vorlage liegt vor */ } }
return;
}
const lastLobby = p.rival.mem.lastLobby ?? 0;
if (this.now() - lastLobby > (g.clock.turbo ? 6 : 72) * HOUR && g.freeCash(p) > 50_000) {
const sec = this.#topSector(p);
if (sec) {
gov.lobbyDonate(p, { partyId: p.party, amount: 5000, sector: sec, direction: 'plus' });
p.rival.mem.lastLobby = this.now();
}
}
}
#nearestNpc(c) {
const dist = (a) => Object.keys(c.pos).reduce((s, k) => s + ((a.pos?.[k] ?? 0) - c.pos[k]) ** 2, 0);
return [...NPC_PARTIES].sort((a, b) => dist(a) - dist(b))[0];
}
#topSector(p) {
const by = {};
for (const [sym, pos] of Object.entries(p.positions)) {
const s = this.g.stocks.get(sym);
if (s?.kind === 'stock' && pos.qty > 0) by[s.sector] = (by[s.sector] ?? 0) + pos.qty * s.last;
}
return Object.entries(by).sort((a, b) => b[1] - a[1])[0]?.[0] ?? null;
}
// ================================================================ Battles & Turniere
/** Einladungen an Rivalen beantworten (mit etwas Bedenkzeit) */
#invites(act) {
if (!this.cfg.rivalsBattles) return;
const bat = this.g.bat;
for (const inv of [...bat.invites.values()]) {
const p = act.find((x) => x.id === inv.to);
if (!p) continue;
const wait = (this.g.clock.turbo ? 5 : 20) * 1000;
if (Date.now() - inv.ts < wait) continue;
const c = CHARACTERS[p.rival.char];
const yes = !bat.active(p.id) && !bat.active(inv.from) && Math.random() < c.battle.accept;
try { bat.respond(p, inv.id, yes); } catch { /* inzwischen ungültig */ }
}
}
/** Gegner für die Schnell-Battle-Warteschlange (statt Index-Bot), falls frei */
opponentFor(q) {
if (!this.cfg.rivalsEnabled || !this.cfg.rivalsBattles) return null;
const free = this.active().filter((p) => !this.g.bat.active(p.id));
if (!free.length) return null;
return free.sort((a, b) => Math.abs(a.elo - q.elo) - Math.abs(b.elo - q.elo) + rnd(-50, 50))[0];
}
/** Ab und zu fordert ein Rivale einen Spieler heraus, der gerade online ist */
#maybeChallenge(act) {
if (!this.cfg.rivalsBattles || this.g.market.phase !== 'continuous') return;
const g = this.g, bat = g.bat;
const gap = (g.clock.turbo ? 1 : 12) * HOUR;
const humans = [...g.players.values()].filter((h) => !h.rival && !h.banned && g.isOnline(h.id) && !bat.active(h.id)
&& Date.now() - (this.state.lastChallenge[h.id] ?? 0) > gap && h.notify?.rivalChallenges !== false);
if (!humans.length || Math.random() > 0.25) return;
const h = pick(humans);
const weights = act.filter((p) => !bat.active(p.id)).map((p) => [p, CHARACTERS[p.rival.char].battle.challenge]);
const total = weights.reduce((a, [, w]) => a + w, 0);
if (!total) return;
let r = Math.random() * total;
const [p] = weights.find(([, w]) => (r -= w) <= 0) ?? weights[0];
const c = CHARACTERS[p.rival.char];
const durations = bat.durations();
try {
bat.challenge(p, h.name, durations[Math.min(1, durations.length - 1)], c.battle.mode);
this.state.lastChallenge[h.id] = Date.now();
g.metaDirty = true;
} catch { /* z. B. inzwischen im Battle */ }
}
/** offene Turniere: Rivalen melden sich an, solange Plätze frei sind (höchstens die Hälfte des Feldes) */
#tournaments(act) {
if (!this.cfg.rivalsBattles) return;
for (const t of this.g.tour.list) {
if (t.status !== 'signup') continue;
const rivalsIn = t.players.filter((x) => this.isRival(x.id ?? x)).length;
if (rivalsIn >= Math.floor(t.size / 2) || t.players.length >= t.size) continue;
const p = act.find((x) => !t.players.some((y) => (y.id ?? y) === x.id));
if (p && Math.random() < 0.5) { try { this.g.tour.join(p, t.id); } catch { /* egal */ } }
}
}
/** Battle vorbei (Hook aus battles.js) – kurzer Spruch */
onBattleEnd(bt) {
if (!this.cfg.rivalsChat) return;
for (const side of ['a', 'b']) {
const p = this.g.players.get(bt[side]);
if (!p?.rival || !bt.winner) continue;
const c = CHARACTERS[p.rival.char];
const won = bt.winner === p.name;
const other = bt[side === 'a' ? 'b' : 'a'];
if (!this.g.players.get(other) || this.g.players.get(other).rival) continue;
const fallback = pick(won ? c.say.battleWin : c.say.battleLose);
const send = (t) => this.g.notify?.(other, { kind: 'battle', title: `${p.name}: „${t}“`, text: 'Nachricht deines Battle-Gegners.' });
if (!this.mind.on) { send(fallback); continue; }
const mine = side === 'a' ? bt.aReturn : bt.bReturn, theirs = side === 'a' ? bt.bReturn : bt.aReturn;
this.mind.say(p, `Dein Battle (${bt.modeName}, ${bt.durationMin} Minuten) gegen ${this.g.players.get(other).name} ist vorbei: Du hast ${won ? 'gewonnen' : 'verloren'}, ${Number(mine ?? 0).toFixed(2)} % gegen ${Number(theirs ?? 0).toFixed(2)} %. Schick deinem Gegner einen kurzen, fairen Spruch.`, send, fallback).catch(() => {});
}
}
// ================================================================ Kommentare
#say(p, c, kind, s, n) {
if (!this.cfg.rivalsChat || Math.random() > c.chat * 0.35 || !this.#commentFree()) return;
const lines = c.say[kind] ?? c.say.buy;
if (!lines?.length) return;
const txt = pick(lines).replace('{s}', s.name ?? s.symbol).replace('{n}', String(n?.title ?? '').slice(0, 70));
this.#reserveComment();
if (!this.mind.on) { this.#post(p, `stock:${s.symbol}`, txt); return; }
const what = { buy: 'gekauft', sell: 'verkauft', short: 'leerverkauft (short)' }[kind] ?? 'gehandelt';
const v = this.mind.view(p);
this.mind.say(p, `Du hast gerade ${s.name} (${s.symbol}) ${what}, Kurs ${s.last.toFixed(2)} €, heute ${((s.last / s.prevClose - 1) * 100).toFixed(1)} %.${n ? ` Anlass: die Meldung „${String(n.title).slice(0, 160)}“.` : ''}${v?.note ? ` Dein Lagebild: ${v.note}` : ''}`,
(t) => this.#post(p, `stock:${s.symbol}`, t), txt).catch(() => {});
}
#comment(p, target, text) {
if (!this.#commentFree()) return;
this.#reserveComment();
this.#post(p, target, text);
}
/** höchstens ein Rivalen-Kommentar alle paar Minuten (alle zusammen) */
#commentFree() { return Date.now() - this.state.lastComment >= (this.g.clock.turbo ? 1 : 5) * MIN; }
#reserveComment() { this.state.lastComment = Date.now(); }
#post(p, target, text) {
try { this.g.social.postComment(p, target, text); return true; } catch (e) { if (process.env.RIVALS_DEBUG) console.warn("[rivale] Kommentar", p.name, target, e.message); return false; }
}
// ================================================================ Ansicht (Admin)
view() {
return {
desired: this.desired(), humans: this.humans(),
list: this.all().map((p) => ({
name: p.name, char: p.rival.char, title: CHARACTERS[p.rival.char]?.title, active: !!p.rival.active,
equity: this.g.equity(p), returnPct: (this.g.equity(p) / this.g.cfg.startCash - 1) * 100, trades: p.trades ?? 0,
party: p.party ? (this.g.gov.party(p.party)?.short ?? p.party) : null, inBattle: !!this.g.bat.active(p.id),
view: (() => { const v = this.mind.view(p); return v ? { note: v.note, mood: v.mood, risk: v.risk, sectors: v.sectors, assets: v.assets, at: v.at } : null; })(),
})),
removed: this.state.removed, mind: this.mind.status(),
};
}
}