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

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

467 lines
29 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.
// Prüf-Simulation (Invarianten) für WiBoSim: unabhängiges Hauptbuch, Invarianten-Prüfungen, Neustart-Vergleich und
// eine Liste von Ereignis-Auslösern. Genutzt von src/invariants.test.js (Belastungstest Orders), src/soak.test.js
// (schneller Lauf in `npm test`) und scripts/soak.mjs (`npm run soak -- --days 60 --seed 7`).
//
// ---------------------------------------------------------------------------------------------------------------
// Geldmenge – erlaubte Quellen und Senken
// ---------------------------------------------------------------------------------------------------------------
// Die Summe aller Kontostände (Hauptdepots inkl. Rivalen, Battle-Depots, Clan-Fonds) ändert sich NUR durch Buchungen
// (game.recordFill) oder durch das Anlegen/Löschen von Konten. Jede Buchungsart hat genau eine Geldwirkung (MONEY):
// Gegenpartei außerhalb der Spielerkonten (Quelle/Senke):
// trade, auction, evening – Ausführung gegen Bots/Market Maker (Spieler-gegen-Spieler hebt sich auf)
// ipo – Zuteilung bei einem Börsengang (Geld geht an das Unternehmen)
// tender – Andienung an einen Bieter (Firma: Quelle; Pflichtangebot eines Spielers: neutral)
// delist, default – Abfindung bei Rückzug von der Börse / Restwert einer ausgefallenen Anleihe
// fundclose – Fondsauflösung: Positionen zum letzten Kurs (Gegenpartei: Markt)
// deriv, derivExpiry, derivKO, derivSeason, derivClose, derivDelist – Emittent der Hebelprodukte
// dividend, coupon – Ausschüttungen (Quelle)
// tax – Abgeltungsteuer (Senke) bzw. Erstattung (Quelle)
// cancel, borrow, fine, party, lobby – Gebühren, Leihgebühr, Bußgeld, Parteigründung, Lobby (Senken)
// admin – Nachschuss/Belastung der Spielleitung (Betrag im Feld price)
// split – Spitzenausgleich bei einer Zusammenlegung (Betrag im Feld cash, sonst 0)
// spinoffCash, mergerCash – Barausgleich für Bruchteile bei Abspaltung/Fusion (Betrag im Feld cash)
// Ohne Geldwirkung: spinoff (Einbuchung der Tochter), merger (Ausbuchung des Ziels, Einbuchung des Käufers)
// Überträge zwischen Konten (neutral): fund (Fonds-Ein-/Auszahlung), fundfee (Verwaltungsgebühr an den Manager)
// Konten anlegen (Registrierung, Rivale, Battle-Depot, Fonds) ist eine Quelle in Höhe des Startguthabens; Konten
// löschen (Battle-Ende, Fondsauflösung, Spieler löschen) eine Senke in Höhe des Restguthabens. Saisonende und
// Depot-Reset setzen alle Depots neu auf (geprüft wird dann: Startkapital, keine Positionen/Orders/Hebelprodukte).
// Unbekannte Buchungsarten lassen die Prüfung scheitern – neue Arten müssen hier eingetragen werden.
//
// Stückzahlen: Für jedes Wertpapier gilt Σ Bestände aller Konten (long − short) + Netto der Bots/Market Maker im
// Orderbuch + Netto aller Gegenbuchungen außerhalb des Orderbuchs (Börsengang, Andienung, Abfindung, Abendhandel,
// Fondsauflösung, gelöschte Konten, Abspaltung, Fusion) = 0. Ein Aktiensplit skaliert alle drei Größen des Symbols
// (Konten aus den split-Buchungen: qty = neuer Bestand, before = alter Bestand; Bots und Gegenbuchungen × Verhältnis). Zusätzlich: Long-Bestände der Spieler ≤ ausgegebene Aktien (s.shares).
import assert from 'node:assert/strict';
/** reproduzierbarer Zufall (mulberry32) */
export function rng(seed) { let s = seed >>> 0; return () => { s = (s + 0x6D2B79F5) >>> 0; let t = s; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
const sgnOf = (f) => (f.side === 'buy' ? 1 : f.side === 'sell' ? -1 : 0);
const xfer = (f) => -sgnOf(f) * f.qty * f.price - (f.fee ?? 0);
/** Geldwirkung je Buchungsart (siehe Kopfkommentar) */
export const MONEY = {
trade: xfer, auction: xfer, evening: xfer, ipo: xfer, tender: xfer, fundclose: xfer, delist: xfer, default: xfer,
deriv: xfer, derivExpiry: xfer, derivKO: xfer, derivSeason: xfer, derivClose: xfer, derivDelist: xfer,
dividend: (f) => f.realized, coupon: (f) => f.realized, tax: (f) => f.realized,
cancel: (f) => -f.fee, borrow: (f) => -f.fee, fine: (f) => -f.fee, party: (f) => -f.fee, lobby: (f) => -f.fee,
fund: () => 0, fundfee: () => 0,
admin: (f) => (f.side === 'deposit' ? 1 : -1) * (f.price ?? 0),
split: (f) => f.cash ?? 0,
spinoff: () => 0, merger: () => 0, spinoffCash: (f) => f.cash, mergerCash: (f) => f.cash,
};
/** Buchungen, die Aktien-/Anleihebestände (acc.positions) bewegen */
export const POS_KINDS = new Set(['trade', 'auction', 'evening', 'ipo', 'tender', 'fundclose', 'delist', 'default', 'spinoff', 'merger']);
/** davon ohne Orderbuch (Gegenbuchung außerhalb: Unternehmen, Market Maker, Abfindung) */
export const EXT_KINDS = new Set(['evening', 'ipo', 'tender', 'fundclose', 'delist', 'default', 'spinoff', 'merger']);
/** Buchungen, die Hebelprodukt-Bestände (acc.derivs) bewegen */
export const DERIV_KINDS = new Set(['deriv', 'derivExpiry', 'derivKO', 'derivSeason', 'derivClose', 'derivDelist']);
/** Buchungen, deren Gebühr in acc.fees landet */
export const FEE_KINDS = new Set(['trade', 'auction', 'evening', 'ipo', 'cancel', 'borrow', 'fundfee', 'deriv']);
const isBotId = (id) => String(id).startsWith('bot:');
const BOOK_TAG = Symbol('simkit.book');
/**
* Beobachter: zählt jede Buchung mit und führt ein unabhängiges Hauptbuch. Nach einem Neustart (neues Game-Objekt)
* mit L.attach(g) neu anhängen – die Zähler bleiben erhalten.
*/
export function instrument(g, { debug = false } = {}) {
const L = {
pos: new Map(), // accId -> {sym: qty} aus den Fills
dpos: new Map(), // accId -> {productId: qty} aus den Hebelprodukt-Buchungen
fees: new Map(), // accId -> Summe Gebühren aus den Fills
botNet: {}, // sym -> Nettobestand der Bots (aus den Trades des Orderbuchs)
sink: {}, // sym -> Gegenbuchungen außerhalb des Orderbuchs und gelöschte Konten
money: 0, // erwartete Summe aller Kontostände
flows: {}, // Geldwirkung je Buchungsart bzw. Kontoereignis (Bericht)
unknown: [], // Buchungsarten ohne Eintrag in MONEY
splitAcc: {}, // sym -> [{was, now}] Kontobestände eines laufenden Splits
fills: [], nFills: 0,
trades: [],
kinds: {},
debug,
g: null,
};
const flow = (k, v) => { L.flows[k] = (L.flows[k] ?? 0) + v; L.money += v; };
const pos = (m, id) => { if (!m.has(id)) m.set(id, {}); return m.get(id); };
L.flow = flow;
const onFill = (f) => {
L.nFills++;
L.kinds[f.kind] = (L.kinds[f.kind] ?? 0) + 1;
if (debug) L.fills.push(f); else if (L.fills.length < 400) L.fills.push(f);
const sgn = sgnOf(f);
if (POS_KINDS.has(f.kind)) {
const p = pos(L.pos, f.account);
p[f.symbol] = (p[f.symbol] ?? 0) + sgn * f.qty;
if (!p[f.symbol]) delete p[f.symbol];
if (EXT_KINDS.has(f.kind)) L.sink[f.symbol] = (L.sink[f.symbol] ?? 0) - sgn * f.qty;
}
if (f.kind === 'split') {
// Bestand neu aus der Buchung (Vorzeichen vom alten Bestand); Bots und Gegenbuchungen werden in L.splitDone skaliert
const p = pos(L.pos, f.account);
const was = p[f.symbol] ?? 0;
if (Number.isFinite(f.before)) assert.equal(was, f.before, `Split ${f.symbol}: Hauptbuch ${was} ≠ Bestand vor dem Split ${f.before} (${f.account})`);
const now = Math.sign(was) * f.qty;
(L.splitAcc[f.symbol] ??= []).push({ was, now });
p[f.symbol] = now;
if (!p[f.symbol]) delete p[f.symbol];
}
if (DERIV_KINDS.has(f.kind)) {
const p = pos(L.dpos, f.account);
p[f.symbol] = (p[f.symbol] ?? 0) + sgn * f.qty;
if (!p[f.symbol]) delete p[f.symbol];
}
if (FEE_KINDS.has(f.kind) && (f.side === 'buy' || f.side === 'sell' || f.side === 'fee')) L.fees.set(f.account, (L.fees.get(f.account) ?? 0) + f.fee);
const m = MONEY[f.kind];
if (!m) { L.unknown.push(f.kind); return; }
const v = m(f);
if (!Number.isFinite(v)) L.unknown.push(`${f.kind}(NaN)`);
else flow(f.kind, v);
};
const wrapBook = (s) => {
const book = s.book;
if (!book || book[BOOK_TAG]) return;
book[BOOK_TAG] = true;
const tally = (r) => {
for (const t of r?.trades ?? []) {
if (debug && (!isBotId(t.buyerId) || !isBotId(t.sellerId))) L.trades.push({ symbol: s.symbol, id: t.id, buyerId: t.buyerId, sellerId: t.sellerId, qty: t.qty, price: t.price, auction: t.auction, n: L.nFills });
if (isBotId(t.buyerId)) L.botNet[s.symbol] = (L.botNet[s.symbol] ?? 0) + t.qty;
if (isBotId(t.sellerId)) L.botNet[s.symbol] = (L.botNet[s.symbol] ?? 0) - t.qty;
}
return r;
};
const sub = book.submit.bind(book), unc = book.uncross.bind(book);
book.submit = (...a) => tally(sub(...a));
book.uncross = (...a) => tally(unc(...a));
};
L.wrapBooks = () => { for (const s of L.g.stocks.values()) wrapBook(s); };
/** Konto verlässt das System: Restbestände und Restgeld sind eine Senke */
const dropAcc = (acc, why) => {
for (const [sym, p] of Object.entries(acc.positions ?? {})) L.sink[sym] = (L.sink[sym] ?? 0) + p.qty;
flow(why, -acc.cash);
L.pos.delete(acc.id); L.dpos.delete(acc.id); L.fees.delete(acc.id);
};
const addAcc = (acc, why) => {
flow(why, acc.cash);
for (const [sym, p] of Object.entries(acc.positions ?? {})) { pos(L.pos, acc.id)[sym] = p.qty; L.sink[sym] = (L.sink[sym] ?? 0) - p.qty; }
if (acc.fees) L.fees.set(acc.id, acc.fees);
};
/** an ein (neues) Game-Objekt anhängen */
L.attach = (gg) => {
L.g = gg;
const orig = gg.recordFill.bind(gg);
gg.recordFill = (f) => { onFill(f); return orig(f); };
const mk = gg.makeStock.bind(gg);
gg.makeStock = (...a) => { const s = mk(...a); wrapBook(s); return s; };
L.wrapBooks();
const bd = gg.battleAccounts.delete.bind(gg.battleAccounts), bs = gg.battleAccounts.set.bind(gg.battleAccounts);
gg.battleAccounts.delete = (id) => { const acc = gg.battleAccounts.get(id); if (acc) dropAcc(acc, 'kontoGeloescht'); return bd(id); };
gg.battleAccounts.set = (id, acc) => { if (!gg.battleAccounts.has(id)) addAcc(acc, 'kontoAngelegt'); return bs(id, acc); };
const pd = gg.players.delete.bind(gg.players), ps = gg.players.set.bind(gg.players);
gg.players.delete = (id) => { const p = gg.players.get(id); if (p) dropAcc(p, 'spielerGeloescht'); return pd(id); };
gg.players.set = (id, p) => { if (!gg.players.has(id)) addAcc(p, 'spielerAngelegt'); return ps(id, p); };
// Saisonende / Depot-Reset: neue Basis (die Liquidationen davor sind normale Buchungen)
const es = gg.endSeason.bind(gg);
gg.endSeason = (...a) => { const r = es(...a); L.rebase('saisonende'); L.afterSeason = gg.day; return r; };
// Aktiensplit: Bots und Gegenbuchungen des Symbols mit dem Verhältnis skalieren. Die Konten kommen aus den
// split-Buchungen; Spitzen (Zusammenlegung) gehen bar weg. Ganzzahlig: Bots gerundet, Rest außerhalb des Buchs.
const sa = gg.splits.apply.bind(gg.splits);
gg.splits.apply = (s, opts) => {
L.splitAcc[s.symbol] = [];
const r = sa(s, opts);
const f = (opts?.num ?? 1) / (opts?.den ?? 1);
const accs = L.splitAcc[s.symbol]; delete L.splitAcc[s.symbol];
const heldOld = accs.reduce((a, x) => a + x.was, 0), heldNew = accs.reduce((a, x) => a + x.now, 0);
const ledOther = [...L.pos.values()].reduce((a, p) => a + (p[s.symbol] ?? 0), 0) - heldNew; // Konten ohne Buchung (sollte 0 sein)
assert.equal(ledOther, 0, `Split ${s.symbol}: Konten mit Bestand ohne split-Buchung`);
const bot = L.botNet[s.symbol] ?? 0, sink = L.sink[s.symbol] ?? 0;
assert.equal(heldOld + bot + sink, 0, `Split ${s.symbol}: Stückzahl schon vor dem Split nicht erhalten`);
L.botNet[s.symbol] = Math.round(bot * f);
L.sink[s.symbol] = -heldNew - L.botNet[s.symbol];
return r;
};
const aa = gg.adminAction.bind(gg);
gg.adminAction = (actor, action, opts) => {
if (action !== 'reset') return aa(actor, action, opts);
const p = gg.players.get(opts?.id);
if (p) dropAcc(p, 'depotReset');
const r = aa(actor, action, opts);
if (p) addAcc(p, 'depotReset');
return r;
};
return L;
};
/** Ledger an den Ist-Stand anlegen (Saisonende): Geld- und Bestandsdifferenz als benannte Quelle/Senke */
L.rebase = (why) => {
const accs = L.g.allAccounts();
const money = accs.reduce((a, x) => a + x.cash, 0);
flow(why, money - L.money);
for (const acc of accs) {
const led = L.pos.get(acc.id) ?? {};
for (const sym of new Set([...Object.keys(led), ...Object.keys(acc.positions)])) {
const d = (acc.positions[sym]?.qty ?? 0) - (led[sym] ?? 0);
if (d) L.sink[sym] = (L.sink[sym] ?? 0) - d;
}
L.pos.set(acc.id, Object.fromEntries(Object.entries(acc.positions).map(([k, p]) => [k, p.qty])));
L.dpos.set(acc.id, Object.fromEntries(Object.entries(acc.derivs ?? {}).map(([k, p]) => [k, p.qty])));
L.fees.set(acc.id, acc.fees ?? 0);
}
};
L.attach(g);
L.money = g.allAccounts().reduce((a, x) => a + x.cash, 0);
L.flows.start = L.money;
for (const acc of g.allAccounts()) addAcc({ ...acc, cash: 0 }, 'start');
return L;
}
const fin = (x, what) => assert.ok(Number.isFinite(x), `${what} ist nicht endlich: ${x}`);
/** alle Zahlen eines (kleinen) Objekts auf NaN/Infinity prüfen */
export function finiteDeep(obj, what, depth = 0, seen = new Set()) {
if (obj === null || obj === undefined || depth > 6) return;
if (typeof obj === 'number') { fin(obj, what); return; }
if (typeof obj !== 'object' || seen.has(obj)) return;
seen.add(obj);
if (Array.isArray(obj)) { for (let i = 0; i < obj.length; i++) finiteDeep(obj[i], `${what}[${i}]`, depth + 1, seen); return; }
for (const [k, v] of Object.entries(obj)) finiteDeep(v, `${what}.${k}`, depth + 1, seen);
}
// ---------------------------------------------------------------------------------------------------------------
// Invarianten: Liste benannter Prüfungen; neue Ereignisarten (Split, Abspaltung, Fusion) ergänzen hier eigene Einträge
// ---------------------------------------------------------------------------------------------------------------
export const CHECKS = [
{
name: 'Konten endlich, Bestände ganzzahlig',
run(g, L, where) {
for (const a of g.allAccounts()) {
fin(a.cash, `${where}: Cash ${a.id}`); fin(a.fees ?? 0, `${where}: Gebühren ${a.id}`); fin(a.realized ?? 0, `${where}: realisiert ${a.id}`);
fin(a.borrowAccrued ?? 0, `${where}: Leihgebühr ${a.id}`);
for (const [sym, p] of Object.entries(a.positions)) {
assert.ok(Number.isInteger(p.qty) && p.qty !== 0, `${where}: Bestand ${a.id} ${sym} = ${p.qty}`);
fin(p.avgCost, `${where}: Einstand ${a.id} ${sym}`);
if (a.rules?.noShort) assert.ok(p.qty > 0, `${where}: Short im Long-only-Konto ${a.id} ${sym} ${p.qty}`);
assert.ok(g.stocks.has(sym), `${where}: unbekanntes Symbol ${sym}`);
assert.ok(!g.stocks.get(sym).delisted, `${where}: ${a.id} hält eingestellte Aktie ${sym}`);
}
for (const [id, p] of Object.entries(a.derivs ?? {})) {
assert.ok(Number.isInteger(p.qty) && p.qty > 0, `${where}: Hebelprodukt ${a.id} ${id} = ${p.qty}`);
fin(p.avgCost, `${where}: Einstand Hebel ${a.id} ${id}`);
const pr = g.derivs.products.get(id);
assert.ok(pr, `${where}: ${a.id} hält unbekanntes Hebelprodukt ${id}`);
assert.equal(pr.status, 'active', `${where}: ${a.id} hält beendetes Hebelprodukt ${id} (${pr.status})`);
}
if (a.kind === 'fund') {
fin(a.totalUnits, `${where}: Fondsanteile`);
const sum = Object.values(a.units).reduce((x, u) => x + u, 0);
assert.ok(Math.abs(sum - a.totalUnits) < 1e-3, `${where}: Anteile ${sum} ≠ ${a.totalUnits}`);
for (const u of Object.values(a.units)) assert.ok(u > 0 && Number.isFinite(u), `${where}: Anteil ${u}`);
}
}
},
},
{
name: 'Bestände und Gebühren = Summe der Buchungen',
run(g, L, where) {
for (const a of g.allAccounts()) {
const led = L.pos.get(a.id) ?? {};
for (const sym of new Set([...Object.keys(led), ...Object.keys(a.positions)])) {
assert.equal(a.positions[sym]?.qty ?? 0, led[sym] ?? 0, `${where}: Bestand ${a.id} ${sym} passt nicht zu den Buchungen`);
}
const dled = L.dpos.get(a.id) ?? {};
for (const id of new Set([...Object.keys(dled), ...Object.keys(a.derivs ?? {})])) {
assert.equal(a.derivs?.[id]?.qty ?? 0, dled[id] ?? 0, `${where}: Hebelbestand ${a.id} ${id} passt nicht zu den Buchungen`);
}
const fees = L.fees.get(a.id) ?? 0;
assert.ok(Math.abs((a.fees ?? 0) - fees) < 1e-6 * Math.max(1, fees), `${where}: Gebühren ${a.id} ${a.fees} ≠ ${fees}`);
}
},
},
{
name: 'Geldmenge',
run(g, L, where) {
assert.deepEqual(L.unknown, [], `${where}: Buchungsarten ohne Geldregel: ${[...new Set(L.unknown)].join(', ')}`);
const money = g.allAccounts().reduce((a, x) => a + x.cash, 0);
assert.ok(Math.abs(money - L.money) < 1e-6 * Math.max(1, Math.abs(L.money)) + 0.01, `${where}: Geldmenge ${money} ≠ ${L.money} (Differenz ${money - L.money})`);
},
},
{
name: 'Stückzahlen je Wertpapier',
run(g, L, where) {
const held = {}, long = {};
for (const a of g.allAccounts()) for (const [sym, p] of Object.entries(a.positions)) { held[sym] = (held[sym] ?? 0) + p.qty; if (p.qty > 0) long[sym] = (long[sym] ?? 0) + p.qty; }
for (const s of g.stocks.values()) {
const sum = (held[s.symbol] ?? 0) + (L.botNet[s.symbol] ?? 0) + (L.sink[s.symbol] ?? 0);
if (sum !== 0 && L.debug) {
console.log('STUECK', where, s.symbol, held[s.symbol], L.botNet[s.symbol], L.sink[s.symbol]);
for (const t of L.trades.filter((t) => t.symbol === s.symbol).slice(-8)) console.log(' T', t);
for (const f of L.fills.filter((f) => f.symbol === s.symbol).slice(-8)) console.log(' F', f.account, f.side, f.qty, f.price, f.kind);
}
assert.equal(sum, 0, `${where}: Stückzahl ${s.symbol} nicht erhalten (Konten ${held[s.symbol] ?? 0}, Bots ${L.botNet[s.symbol] ?? 0}, außerhalb ${L.sink[s.symbol] ?? 0})`);
if (s.kind === 'stock') {
assert.ok(Number.isInteger(s.shares) && s.shares > 0, `${where}: ausgegebene Aktien ${s.symbol} = ${s.shares}`);
assert.ok((long[s.symbol] ?? 0) <= s.shares, `${where}: Spieler halten mehr ${s.symbol} (${long[s.symbol]}) als ausgegeben (${s.shares})`);
}
}
},
},
{
name: 'Orderbuch und bedingte Orders',
run(g, L, where) {
for (const s of g.stocks.values()) {
const b = s.book;
const listed = [...b.bids, ...b.asks];
assert.equal(listed.length, b.orders.size, `${where}: ${s.symbol} Buch/Index`);
let owned = 0;
for (const set of b.byOwner.values()) owned += set.size;
assert.equal(owned, b.orders.size, `${where}: ${s.symbol} Besitzerindex`);
if (s.delisted) assert.equal(b.orders.size, 0, `${where}: Orders im Buch der eingestellten Aktie ${s.symbol}`);
for (const o of listed) {
assert.equal(b.orders.get(o.id), o, `${where}: Order ${o.id} fehlt im Index`);
assert.ok(['open', 'partial'].includes(o.status), `${where}: Order ${o.id} im Buch mit Status ${o.status}`);
assert.ok(Number.isInteger(o.qty) && o.qty > 0 && Number.isFinite(o.filled) && o.filled >= 0 && o.filled < o.qty, `${where}: Order ${o.id} Menge ${o.qty}/${o.filled}`);
if (o.type === 'limit') assert.ok(Number.isFinite(o.price) && o.price > 0, `${where}: Order ${o.id} Limit ${o.price}`);
if (!isBotId(o.ownerId)) assert.ok(g.account(o.ownerId), `${where}: Order ${o.id} ohne Konto`);
}
for (let i = 1; i < b.bids.length; i++) if (b.bids[i].type === 'limit' && b.bids[i - 1].type === 'limit') assert.ok(b.bids[i - 1].price >= b.bids[i].price, `${where}: Bids unsortiert`);
for (let i = 1; i < b.asks.length; i++) if (b.asks[i].type === 'limit' && b.asks[i - 1].type === 'limit') assert.ok(b.asks[i - 1].price <= b.asks[i].price, `${where}: Asks unsortiert`);
if (!s.delisted && g.ex.isContinuous(s)) {
const bb = b.bestBid(), ba = b.bestAsk();
if (bb && ba) assert.ok(bb < ba, `${where}: ${s.symbol} Buch gekreuzt ${bb} ≥ ${ba}`);
}
}
for (const c of g.ex.condOrders) {
assert.ok(g.account(c.accountId), `${where}: bedingte Order ${c.id} ohne Konto`);
const s = g.stocks.get(c.symbol);
assert.ok(s && !s.delisted, `${where}: bedingte Order ${c.id} auf ${s ? 'eingestellte' : 'unbekannte'} Aktie ${c.symbol}`);
// Bracket-Beine warten mit der bisher ausgeführten Menge (anfangs 0) auf ihre Mutter-Order
if (c.status === 'pending') {
assert.ok(Number.isInteger(c.qty) && c.qty >= 0, `${where}: wartende bedingte Order ${c.id} Menge ${c.qty}`);
assert.ok(s?.book.orders.has(c.parent), `${where}: wartende bedingte Order ${c.id} ohne Mutter-Order ${c.parent}`);
} else assert.ok(Number.isInteger(c.qty) && c.qty > 0, `${where}: bedingte Order ${c.id} (${c.status}) Menge ${c.qty}`);
}
},
},
{
name: 'Kurse, Fundamentaldaten, Indizes endlich',
run(g, L, where) {
for (const s of g.stocks.values()) {
for (const k of ['last', 'fair', 'prevClose', 'open', 'high', 'low']) if (s[k] !== undefined && s[k] !== null) fin(s[k], `${where}: ${s.symbol}.${k}`);
if (s.delisted) assert.ok(s.last >= 0, `${where}: Kurs ${s.symbol} < 0`);
else assert.ok(s.last > 0, `${where}: Kurs ${s.symbol} ≤ 0`);
if (s.kind === 'stock' && !s.delisted) { fin(s.fv, `${where}: ${s.symbol}.fv`); finiteDeep(s.fund, `${where}: ${s.symbol}.fund`); }
}
for (const id of Object.keys(g.indices.st.idx).concat('WIBO10')) { const v = g.indices.value(id); fin(v, `${where}: Index ${id}`); assert.ok(v > 0, `${where}: Index ${id} ≤ 0`); }
for (const e of g.etfs.list()) fin(g.etfs.nav(e), `${where}: NAV ${e.symbol}`);
finiteDeep(g.macro, `${where}: macro`);
},
},
{
name: 'Keine Verweise auf eingestellte Aktien',
run(g, L, where) {
const dead = new Set([...g.stocks.values()].filter((s) => s.delisted).map((s) => s.symbol));
if (!dead.size) return;
for (const p of g.players.values()) {
for (const a of p.alerts ?? []) assert.ok(!dead.has(a.symbol), `${where}: Kursalarm von ${p.name} auf eingestellte Aktie ${a.symbol}`);
for (const w of p.watch ?? []) assert.ok(!dead.has(w), `${where}: Merkliste von ${p.name} enthält eingestellte Aktie ${w}`);
}
for (const pr of g.derivs.products.values()) if (pr.status === 'active') assert.ok(!dead.has(pr.u), `${where}: aktives Hebelprodukt ${pr.id} auf eingestellte Aktie ${pr.u}`);
for (const o of g.corp.offers) assert.ok(!dead.has(o.target) && !dead.has(o.bidder), `${where}: Angebot ${o.target}/${o.bidder} mit eingestellter Aktie`);
for (const t of g.corp.trials) assert.ok(!dead.has(t.symbol), `${where}: Studie auf eingestellte Aktie ${t.symbol}`);
for (const m of g.agm.state.meetings) if (m.status === 'open') assert.ok(!dead.has(m.symbol), `${where}: Hauptversammlung ${m.symbol} offen`);
for (const [id, d] of Object.entries(g.indices.st.idx)) for (const sym of Object.keys(d.units ?? {})) assert.ok(!dead.has(sym), `${where}: Index ${id} enthält eingestellte Aktie ${sym}`);
for (const e of g.etfs.list()) for (const sym of Object.keys(e.asset?.basket ?? {})) assert.ok(!dead.has(sym), `${where}: ETF ${e.symbol} enthält eingestellte Aktie ${sym}`);
for (const sym of dead) assert.ok(!g.indices.st.seg[sym], `${where}: Segment für eingestellte Aktie ${sym}`);
for (const pr of g.predict?.qs ?? []) if (pr.symbol && dead.has(pr.symbol)) assert.ok(pr.status === 'done', `${where}: offene Tippfrage auf ${pr.symbol}`);
},
},
{
name: 'Logo-Pool',
run(g, L, where) {
const seen = new Map();
const pendingSyms = new Set([...(g.ipo.pending ?? []).filter((x) => x.status === 'signup').map((x) => x.symbol), ...(g.spinoff?.reservedSymbols?.() ?? [])]);
for (const [sym, key] of Object.entries(g.marks.bySym)) {
const s = g.stocks.get(sym);
assert.ok((s && !s.delisted) || pendingSyms.has(sym), `${where}: Marke ${key} hängt an ${s ? 'eingestellter' : 'unbekannter'} Firma ${sym}`);
assert.ok(!seen.has(key), `${where}: Marke ${key} doppelt vergeben (${seen.get(key)}, ${sym})`);
seen.set(key, sym);
}
},
},
];
/** alle Invarianten prüfen; extra: weitere {name, run}-Einträge */
export function checkAll(g, L, where, extra = []) {
L.wrapBooks();
for (const c of [...CHECKS, ...extra]) c.run(g, L, where);
}
// ---------------------------------------------------------------------------------------------------------------
// Neustart: Zustand vor dem Speichern == Zustand nach dem Laden
// ---------------------------------------------------------------------------------------------------------------
const norm = (x) => JSON.parse(JSON.stringify(x ?? null));
const r6 = (x) => (Number.isFinite(x) ? Math.round(x * 1e6) / 1e6 : x);
/** Konten (Salden, Bestände, Orders) – auch nach einem Absturz ohne Meta-Speicherung identisch */
export function accountsState(g) {
const accs = {};
for (const a of g.allAccounts()) {
accs[a.id] = norm({
cash: a.cash, fees: a.fees, realized: a.realized, locked: !!a.locked, units: a.units ?? null, totalUnits: a.totalUnits ?? null,
positions: Object.fromEntries(Object.entries(a.positions).map(([k, p]) => [k, { qty: p.qty, avgCost: p.avgCost }])),
derivs: Object.fromEntries(Object.entries(a.derivs ?? {}).map(([k, p]) => [k, { qty: p.qty, avgCost: p.avgCost }])),
alerts: (a.alerts ?? []).map((x) => `${x.symbol}:${x.price}:${x.dir}`).sort(), watch: [...(a.watch ?? [])].sort(),
orders: g.ex.ordersOf(a.id).map((o) => `${o.kind}:${o.id}:${o.symbol}:${o.side}:${o.qty}:${o.filled ?? ''}:${o.price ?? o.trigger ?? ''}`).sort(),
tax: a.tax ?? null,
});
}
return accs;
}
/** relevante Teile des Spielstands (für den Neustart-Vergleich nach geordnetem Speichern) */
export function gameState(g) {
const stocks = {};
for (const s of g.stocks.values()) stocks[s.symbol] = { kind: s.kind, last: r6(s.last), shares: s.shares ?? null, delisted: s.delisted ?? null, fair: r6(s.fair), control: s.control ?? null };
return norm({
day: g.day, season: g.season.n, phase: g.market.phase,
accounts: accountsState(g),
stocks,
indices: { seg: g.indices.st.seg, idx: g.indices.st.idx, w10: g.indices.st.w10, values: Object.fromEntries(Object.keys(g.indices.st.idx).concat('WIBO10').map((id) => [id, r6(g.indices.value(id))])) },
marks: { bySym: g.marks.bySym, locked: g.marks.locked },
// Hebelprodukte: gehaltene müssen identisch sein; beim Laden darf der Emittent fehlende Serien neu auflegen
// (derivs.init → issue, wie alle 30 Takte) – daher nur „kein Produkt verschwindet“ (derivIds, siehe sameState)
derivs: [...g.derivs.products.values()].filter((p) => g.allAccounts().some((a) => a.derivs?.[p.id])).map((p) => `${p.id}:${p.u}:${p.kind}:${p.status}:${p.strike ?? ''}`).sort(),
derivIds: [...g.derivs.products.keys()].sort(),
cond: g.ex.condOrders.map((c) => `${c.id}:${c.symbol}:${c.qty}`).sort(),
offers: g.corp.offers.map((o) => ({ ...o, tenders: o.tenders })),
ipo: g.ipo.pending.map((x) => ({ id: x.id, symbol: x.symbol, status: x.status, orders: x.orders })),
listed: g.ipo.state.listed.map((x) => x.symbol),
clubs: [...g.clubs.clubs.values()].map((c) => ({ id: c.id, members: c.members.map((m) => m.id), fundId: c.fundId ?? null })),
etfs: Object.fromEntries(g.etfs.list().map((e) => [e.symbol, Object.fromEntries(Object.entries(e.asset?.basket ?? {}).map(([k, v]) => [k, r6(v)]))])),
delisted: g.delist.history.map((h) => h.symbol),
histories: { corp: g.corp.history.length, credit: g.credit.history.length, defaults: g.credit.defaults.length },
});
}
/** erste Abweichung zweier Zustände (Pfad) – für lesbare Fehlermeldungen */
export function firstDiff(a, b, path = '') {
if (a === b) return null;
if (typeof a !== typeof b || a === null || b === null || typeof a !== 'object') return `${path || '/'}: ${JSON.stringify(a)?.slice(0, 120)} ≠ ${JSON.stringify(b)?.slice(0, 120)}`;
const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
for (const k of keys) { const d = firstDiff(a[k], b[k], `${path}/${k}`); if (d) return d; }
return null;
}
/** Neustart-Vergleich: null oder die erste Abweichung (neu aufgelegte Hebelprodukte beim Laden sind erlaubt) */
export function sameState(before, after) {
const { derivIds: a = [], ...b0 } = before, { derivIds: b = [], ...a0 } = after;
const gone = a.filter((id) => !b.includes(id));
if (gone.length) return `Hebelprodukte nach dem Laden verschwunden: ${gone.slice(0, 5).join(', ')}`;
return firstDiff(b0, a0);
}