Files
wibosim/server/scripts/cryptovol.mjs
T
db9979andClaude Opus 5.5 22559b2127 Kerzenchart ruhiger: Bündeln zu 2/5-Min-Kerzen, breitere Körper; WiboCoin-Minutenkerzen ohne Impuls-Rauschen
- 1T-Kerzenchart (alle Werte): Körper rund 74 % des Platzes, mindestens 1 px Abstand; bei mehr als 120 Kerzen im
  Bild Bündeln zu 2- bzw. 5-Minuten-Kerzen (OHLC, Umsatz summiert), beim Hineinzoomen wieder feiner; Hinweis
  „2-Min-Kerzen“ im Chart-Kopf (am Handy in der Kennzahlenzeile)
- WiboCoin: Market Impact × 0,45 (cryptoImpactScale) und halbe Market-Maker-Spanne (cryptoSpreadScale);
  realisierte Vola aus Minutenkerzen 306 % → 192 % p. a., Spanne je Kerze 82 → 38 Bp., Tage über ±15 % 3,3 → 1,1 %
- scripts/cryptovol.mjs (Messlauf), Tests chartbundle.test.js und cryptovol.test.js, BALANCING.md Abschnitt 27

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

178 lines
10 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.
// Messlauf WiboCoin-Volatilität (docs/BALANCING.md, Abschnitt 27): spielt mit künstlicher Uhr und festem Zufall einige
// Kalendertage im Echtzeit-Kalender durch (Handelszeit im 2-s-Takt, sonst im 10-s-Takt wie der Server) und wertet die
// Minutenkerzen aus: realisierte Volatilität p. a. (Summe der quadrierten Minutenrenditen, je Kalendertag × 365),
// Anteil der Tage mit mehr als ±15 % (Mitternacht zu Mitternacht), mittleres Verhältnis Docht/Körper je Minute und die
// ausgewiesene Volatilität (Kennzahl „Volatilität p. a.“) im Mittel.
//
// node scripts/cryptovol.mjs [--days 30] [--seed 1] [--seeds 1] [--syms WIBC,BRAU,VITA] [--set '{"cryptoHypeVol":4}'] [--test]
//
// --test rechnet mit den Testwerten (NODE_ENV=test), sonst mit den Standardwerten des Servers. Jeder Seed läuft in
// einem eigenen Kindprozess.
import { fork } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const SELF = fileURLToPath(import.meta.url);
const DAY = 86_400_000;
// Standardwerte des Servers, die NODE_ENV=test sonst abschaltet (wie scripts/balance.mjs --server)
export const SERVER_DEFAULTS = { fundIdioSd: 0.15, growthAccrual: true, smallCapImpact: 0.5, cryptoEventScale: 0.5, cryptoHypeCap: 0.12, cryptoHypeVol: 4, cryptoDriftSd: 0.2, creditDefaultScale: 1, splitProb: 0.3, delistInsolvencyProb: 0.15, spinoffEnabled: true, mergerEnabled: true, delistTakeover: true, panicDayDepth: 1, cryptoImpactScale: 0.45, cryptoSpreadScale: 0.5 };
function mulberry32(a) {
return function () {
a |= 0; a = (a + 0x6d2b79f5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
/**
* Kennzahlen aus Minutenkerzen [{t, o, h, l, c}] (aufsteigend). dayKey(t) ordnet einer Kerze ihren Kalendertag zu.
* vol: Wurzel aus (Summe der quadrierten log. Minutenrenditen je Kalendertag × 365); big: Anteil der Tage mit |Δ| > 15 %;
* range: mittlere Spanne Hoch–Tief je Kerze (Anteil vom Kurs); wick: Summe aller Dochte (oben + unten) / Summe aller Körper; wickMed: Median je Kerze (Körper mindestens 1 Kursschritt).
*/
export function candleStats(bars, dayKey, { tick = 0.01, minBars = 600 } = {}) {
let sq = 0;
const days = new Map();
const ratios = [];
let wSum = 0, bSum = 0, rSum = 0;
for (let i = 0; i < bars.length; i++) {
const b = bars[i];
if (i > 0) { const r = Math.log(b.c / bars[i - 1].c); if (Number.isFinite(r)) sq += r * r; }
const k = dayKey(b.t);
const d = days.get(k) ?? { o: i > 0 ? bars[i - 1].c : b.o, c: b.c, n: 0 };
d.c = b.c; d.n++;
days.set(k, d);
const body = Math.abs(b.c - b.o), wick = b.h - Math.max(b.o, b.c) + Math.min(b.o, b.c) - b.l;
ratios.push(wick / Math.max(body, tick));
wSum += wick; bSum += body; rSum += (b.h - b.l) / b.c;
}
const full = [...days.values()].filter((d) => d.n >= minBars); // nur (fast) volle Tage
const moves = full.map((d) => d.c / d.o - 1);
const nDays = Math.max(1, bars.length / 1440);
ratios.sort((a, b) => a - b);
return {
vol: Math.sqrt((sq / nDays) * 365),
days: moves.length,
big: moves.length ? moves.filter((m) => Math.abs(m) > 0.15).length / moves.length : NaN,
worst: moves.length ? Math.min(...moves) : NaN,
best: moves.length ? Math.max(...moves) : NaN,
daySd: moves.length > 1 ? Math.sqrt(moves.reduce((a, m) => a + Math.log(1 + m) ** 2, 0) / moves.length) : NaN,
wickMed: ratios.length ? ratios[Math.floor(ratios.length / 2)] : NaN,
wickMean: ratios.length ? ratios.reduce((a, b) => a + b, 0) / ratios.length : NaN,
wick: bSum > 0 ? wSum / bSum : NaN,
range: bars.length ? rSum / bars.length : NaN, // mittlere Spanne Hoch–Tief einer Kerze (Anteil vom Kurs) // Summe der Dochte / Summe der Körper (robust gegen Kerzen ohne Körper)
};
}
// ====================================================================== Kindprozess: ein Lauf
async function child(job) {
Math.random = mulberry32(job.seed * 7919 + 17);
process.env.TIME_MODE = 'realtime';
process.env.NODE_ENV = 'test';
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-cvol-'));
const clock = { t: job.t0 };
Date.now = () => clock.t;
const { settings } = await import('../src/settings.js');
settings.news.enabled = false;
for (const [k, v] of Object.entries(job.overrides ?? {})) settings.game[k] = v;
const { Store } = await import('../src/store.js');
const { Game } = await import('../src/game.js');
const { simulatedNews } = await import('../src/news.js');
const { zonedParts } = await import('../src/calendar.js').catch(() => ({}));
const store = new Store(process.env.DATA_DIR);
store.backup = () => null;
const g = new Game({ store, now: () => clock.t });
const cfg = settings.game;
const tz = cfg.timezone;
const fmt = new Intl.DateTimeFormat('en-CA', { timeZone: tz, year: 'numeric', month: '2-digit', day: '2-digit' });
const dayKey = (t) => fmt.format(t);
void zonedParts;
const syms = job.syms;
const bars = Object.fromEntries(syms.map((s) => [s, new Map()]));
const shown = Object.fromEntries(syms.map((s) => [s, []]));
const simEvery = settings.news.simulatedEveryMin * 60_000;
const fairPath = Object.fromEntries(syms.map((s) => [s, []])); // je Minute: fairer Kurs und Mitte des Market Makers
let lastSim = clock.t, nextShow = 0, nextMin = 0, events = 0;
const origAdd = g.addNews.bind(g);
g.addNews = (n, apply = true) => { if (n?.source === 'Kryptomarkt') events++; return origAdd(n, apply); };
const end = job.t0 + job.days * DAY;
while (clock.t < end) {
const open = g.market.phase !== 'closed';
clock.t += open ? cfg.tickMs : (cfg.tickClosedMs ?? 10_000);
if (simEvery > 0 && clock.t - lastSim >= simEvery) { lastSim = clock.t; g.addNews(simulatedNews()); }
g.tick();
g.ex.pendingTrades.length = 0;
g.drainChanged();
for (const sym of syms) {
const s = g.stocks.get(sym);
const c = s?.candles[s.candles.length - 1];
if (c) bars[sym].set(c.t, { ...c });
}
if (clock.t >= nextMin) {
nextMin = Math.floor(clock.t / 60_000) * 60_000 + 60_000;
for (const sym of syms) { const s = g.stocks.get(sym); if (s && (s.allDay || g.market.phase === 'continuous')) fairPath[sym].push([s.fair, s.fair * Math.exp(s.imp ?? 0)]); }
}
if (clock.t >= nextShow) {
nextShow = clock.t + 3_600_000;
for (const sym of syms) { const s = g.stocks.get(sym); if (s) shown[sym].push(g.econ.volNow(s)); }
}
}
const out = {};
for (const sym of syms) {
const s = g.stocks.get(sym);
let list = [...bars[sym].values()].sort((a, b) => a.t - b.t);
// Aktien: nur Handelszeit (der Abendhandel hat eigene, gedämpfte Kerzen); Krypto rund um die Uhr
const st = candleStats(list, dayKey, { tick: s.last >= 50 ? 0.01 : s.last >= 10 ? 0.005 : 0.001, minBars: s.allDay ? 600 : 300 });
if (!s.allDay) {
// Aktien: Vol aus den Minutenrenditen der Handelszeit, je Handelstag × 252
let sq = 0; const perDay = new Map();
for (let i = 1; i < list.length; i++) {
const k = dayKey(list[i].t);
if (k !== dayKey(list[i - 1].t)) continue; // Übernachtlücke gehört zur Tagesrendite, nicht zur Minutenvola
sq += Math.log(list[i].c / list[i - 1].c) ** 2;
perDay.set(k, 1);
}
st.vol = Math.sqrt((sq / Math.max(1, perDay.size)) * 252);
list = null;
}
const sh = shown[sym];
// Anteil des fairen Kurses und der Market-Maker-Mitte an der Minutenvola (Rest: Geld/Brief-Sprünge, Orderbuch)
const fp = fairPath[sym], perYear = s.allDay ? 365 * 1440 : 252 * 510;
const rv = (k) => { let q = 0; for (let i = 1; i < fp.length; i++) q += Math.log(fp[i][k] / fp[i - 1][k]) ** 2; return Math.sqrt((q / Math.max(1, fp.length - 1)) * perYear); };
st.volFair = rv(0); st.volMid = rv(1);
out[sym] = { ...st, shown: sh.reduce((a, b) => a + b, 0) / Math.max(1, sh.length), base: s.vol };
}
process.send({ seed: job.seed, out, events });
process.exit(0);
}
// ====================================================================== Hauptprozess
if (process.env.CVOL_JOB) await child(JSON.parse(process.env.CVOL_JOB));
else if (process.argv[1] === SELF) {
const a = process.argv.slice(2);
const get = (k, d) => { const i = a.indexOf(k); return i >= 0 ? a[i + 1] : d; };
const days = Number(get('--days', 30)), seed0 = Number(get('--seed', 1)), seeds = Number(get('--seeds', 1));
const syms = get('--syms', 'WIBC').split(',');
const overrides = { ...(a.includes('--test') ? {} : SERVER_DEFAULTS), ...JSON.parse(get('--set', '{}')) };
const t0 = Date.UTC(2027, 0, 4, 0, 0) - 3_600_000; // Montag 00:00 Berlin
const jobs = Array.from({ length: seeds }, (_, i) => ({ seed: seed0 + i, days, syms, overrides, t0 }));
const res = await Promise.all(jobs.map((job) => new Promise((resolve) => {
const c = fork(SELF, [], { env: { ...process.env, CVOL_JOB: JSON.stringify(job) }, execArgv: ['--disable-warning=ExperimentalWarning'], stdio: ['ignore', 'ignore', 'inherit', 'ipc'] });
let got = null;
c.on('message', (m) => { got = m; });
c.on('exit', () => resolve(got ?? { seed: job.seed, failed: true }));
})));
const pct = (x, d = 0) => (Number.isFinite(x) ? `${(x * 100).toFixed(d)} %` : '–');
for (const r of res) {
if (r.failed) { console.log(`Seed ${r.seed}: fehlgeschlagen`); continue; }
for (const [sym, s] of Object.entries(r.out)) {
console.log(`Seed ${r.seed} ${sym.padEnd(5)} Vol p. a. ${pct(s.vol)} (ausgewiesen Ø ${pct(s.shown)}, Basis ${pct(s.base)}) · Tage ${s.days}, > ±15 % ${pct(s.big)} (fair ${pct(s.volFair)}, MM-Mitte ${pct(s.volMid)}) · Tages-SD ${pct(s.daySd, 1)} · schlechtester/bester Tag ${pct(s.worst, 1)} / ${pct(s.best, 1)} · Spanne je Kerze ${(s.range * 1e4).toFixed(1)} Bp. · Docht/Körper ${s.wick.toFixed(2)} (Median je Kerze ${s.wickMed.toFixed(2)})${sym === 'WIBC' ? ` · Krypto-Ereignisse ${r.events}` : ''}`);
}
}
if (a.includes('--json')) fs.writeFileSync(get('--json'), JSON.stringify(res, null, 1));
}