mirror of
https://github.com/db9979/wibosim.git
synced 2026-12-05 21:14:09 +01:00
- Hebelprodukte: Nach eigenem Handel im Basiswert quotiert der Emittent der Person für eine Schutzfrist vorsichtig aus aktuellem Kurs und Kurs vor dem Handel (Kauf und Verkauf jeweils zum ungünstigeren). Zusätzlich ist das Basiswert-Volumen je Spieler und Basiswert begrenzt (Vielfaches der Markttiefe). Beides lässt sich im Admin einstellen. - Saisonende/Neuaufsetzen: Offene IPO-Zeichnungen werden verworfen, die Kaufkraft wird frei und die Zeichner werden benachrichtigt. - Konto löschen: Fondsanteile werden sofort zurückgenommen (Auszahlung, Verfall zugunsten der übrigen Anleger oder Auflösung, wenn der Spieler einziger Anleger ist). Eine Auflösung zahlt nicht mehr an gelöschte Konten. - Ausführungsprüfung: Das Eindecken eines Leerverkaufs verbraucht keine Kaufkraft mehr doppelt. Eine nicht mehr gedeckte Order verfällt mit dem Rest, statt gekreuzt im Buch zu liegen. - simkit: Invariante, dass Fondsanteile nur bestehenden Konten gehören. Regressionstests in review-kern.test.js. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUhQVoPUusUzxgxLWkK
267 lines
12 KiB
JavaScript
267 lines
12 KiB
JavaScript
// @ts-check
|
||
// Orderbuch mit Preis-Zeit-Priorität (Xetra-Vorbild).
|
||
// - fortlaufender Handel: Limit/Market, Gültigkeit IOC/FOK, Iceberg-Orders, Preiskorridor (Volatilitätsunterbrechung)
|
||
// - Auktionen: Orders werden während der Aufrufphase ohne Ausführung gesammelt (das Buch darf sich kreuzen),
|
||
// anschließend wird zum meistausführbaren Preis „ausgeglichen“ (uncross).
|
||
|
||
let nextOrderId = 1;
|
||
let nextTradeId = 1;
|
||
|
||
export const TICK = 0.01;
|
||
/** @param {number} p */
|
||
export const roundTick = (p) => Math.round(Math.round(p / TICK) * TICK * 100) / 100;
|
||
/** IDs nach einem Neustart oberhalb der gespeicherten weiterzählen @param {number} n */
|
||
export const bumpOrderId = (n) => { if (n >= nextOrderId) nextOrderId = n + 1; };
|
||
|
||
/**
|
||
* @typedef {{id:number, symbol:string, ownerId:string, group:string, side:'buy'|'sell', type:'limit'|'market',
|
||
* price:number|null, qty:number, filled:number, ts:number, status:string, tif?:string, expireAt?:number|null,
|
||
* peak?:number|null, show?:number, meta?:any}} Order
|
||
* @typedef {{id:number, symbol:string, price:number, qty:number, buyOrderId:number, sellOrderId:number, buyerId:string,
|
||
* sellerId:string, aggressor:'buy'|'sell'|null, ts:number, bo:Order, so:Order, auction?:boolean}} Trade
|
||
* @typedef {(taker:Order, maker:Order, qty:number, px:number, dry?:boolean) => true|'buy'|'sell'} CanFill
|
||
* Risikoprüfung je Teilausführung; mit dry = true nur prüfen, ohne die Menge als ausgeführt vorzumerken (Fill-or-Kill)
|
||
*/
|
||
|
||
export class OrderBook {
|
||
/** @param {string} symbol */
|
||
constructor(symbol) {
|
||
this.symbol = symbol;
|
||
/** @type {Order[]} */ this.bids = []; // Market zuerst, dann Preis absteigend, dann Zeit
|
||
/** @type {Order[]} */ this.asks = []; // Market zuerst, dann Preis aufsteigend, dann Zeit
|
||
/** @type {Map<number, Order>} */ this.orders = new Map();
|
||
/** @type {Map<string, Set<Order>>} */ this.byOwner = new Map();
|
||
}
|
||
|
||
bestBid() { const o = this.bids.find((x) => x.type === 'limit'); return o ? o.price : null; }
|
||
bestAsk() { const o = this.asks.find((x) => x.type === 'limit'); return o ? o.price : null; }
|
||
mid() { const b = this.bestBid(), a = this.bestAsk(); return b && a && a > b ? (a + b) / 2 : null; }
|
||
|
||
/** Neue Order-Struktur */
|
||
static make(o) {
|
||
const isLimit = o.type === 'limit';
|
||
const qty = Math.floor(o.qty);
|
||
const peak = o.peak ? Math.min(qty, Math.max(1, Math.floor(o.peak))) : null;
|
||
return {
|
||
id: o.id ?? nextOrderId++, symbol: o.symbol, ownerId: o.ownerId, group: o.group ?? o.ownerId,
|
||
side: o.side, type: isLimit ? 'limit' : 'market', price: isLimit ? roundTick(o.price) : null,
|
||
qty, filled: o.filled ?? 0, ts: o.ts ?? Date.now(), status: 'open', tif: o.tif ?? 'gtc',
|
||
expireAt: o.expireAt ?? null, peak, show: peak ? Math.min(peak, qty - (o.filled ?? 0)) : undefined, meta: o.meta,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Fortlaufender Handel.
|
||
* @param {any} o
|
||
* @param {{canFill?: CanFill, lo?: number, hi?: number}} [opt] lo/hi: Preiskorridor – außerhalb wird nicht gehandelt
|
||
* @returns {{order: Order, trades: Trade[], stopped: boolean}}
|
||
*/
|
||
submit(o, { canFill = () => true, lo = 0, hi = Infinity } = {}) {
|
||
const order = OrderBook.make({ ...o, symbol: this.symbol });
|
||
const trades = [];
|
||
let stopped = false, uncovered = false;
|
||
const book = order.side === 'buy' ? this.asks : this.bids;
|
||
const crosses = (r) => r.type === 'limit' && (order.type === 'market' || (order.side === 'buy' ? r.price <= order.price : r.price >= order.price));
|
||
|
||
if (order.tif === 'fok') {
|
||
let avail = 0;
|
||
for (const r of book) {
|
||
if (!crosses(r) || r.price < lo || r.price > hi) break;
|
||
// nur, was auch ausgeführt würde: eigene Orders (Selbsthandel) und nicht mehr gedeckte ruhende Orders zählen nicht
|
||
if (r.group === order.group) continue;
|
||
const q = Math.min(r.qty - r.filled, order.qty - avail);
|
||
const ok = canFill(order, r, q, r.price, true);
|
||
if (ok === order.side) break;
|
||
if (ok === true) avail += q;
|
||
if (avail >= order.qty) break;
|
||
}
|
||
if (avail < order.qty) { order.status = 'cancelled'; return { order, trades, stopped: false }; }
|
||
}
|
||
|
||
while (order.filled < order.qty && book.length && crosses(book[0])) {
|
||
const resting = book[0];
|
||
if (resting.price < lo || resting.price > hi) { stopped = true; break; }
|
||
if (resting.group === order.group) { this.#remove(resting, 'cancelled'); continue; } // Self-Trade-Prevention
|
||
const avail = resting.peak ? resting.show : resting.qty - resting.filled;
|
||
const qty = Math.min(order.qty - order.filled, avail);
|
||
const ok = canFill(order, resting, qty, resting.price);
|
||
if (ok !== true) {
|
||
if (ok === resting.side) { this.#remove(resting, 'cancelled'); continue; } // ruhende Order nicht mehr gedeckt
|
||
uncovered = true; // eigene Order nicht (mehr) gedeckt: Rest verfällt, sonst läge sie gekreuzt im Buch
|
||
break;
|
||
}
|
||
trades.push(this.#fill(order, resting, qty, resting.price, order.side));
|
||
if (resting.filled >= resting.qty) this.#remove(resting, 'filled');
|
||
else if (resting.peak && resting.show <= 0) this.#reloadIceberg(resting);
|
||
}
|
||
|
||
if (order.filled >= order.qty) order.status = 'filled';
|
||
else if (order.type === 'market' || order.tif === 'ioc' || order.tif === 'fok' || uncovered) order.status = order.filled ? 'partial-cancelled' : 'cancelled';
|
||
else this.#rest(order);
|
||
return { order, trades, stopped };
|
||
}
|
||
|
||
/** Order ohne Ausführung ins Buch legen (Auktions-Aufrufphase, Wiederherstellung nach Neustart) */
|
||
addResting(o) {
|
||
const order = OrderBook.make({ ...o, symbol: this.symbol });
|
||
this.#rest(order);
|
||
return order;
|
||
}
|
||
|
||
/**
|
||
* Indikativer Auktionspreis: maximales ausführbares Volumen, dann kleinster Überhang,
|
||
* dann Marktdruck, dann Nähe zum Referenzpreis.
|
||
* @param {number} ref
|
||
*/
|
||
indicative(ref) {
|
||
const prices = [...new Set([...this.bids, ...this.asks].filter((o) => o.type === 'limit').map((o) => o.price))];
|
||
if (!prices.length) {
|
||
const hasB = this.bids.length, hasA = this.asks.length;
|
||
return hasB && hasA ? { price: roundTick(ref), volume: Math.min(this.#vol(this.bids), this.#vol(this.asks)), surplus: 0 } : null;
|
||
}
|
||
let best = null;
|
||
for (const p of prices) {
|
||
let buy = 0, sell = 0;
|
||
for (const o of this.bids) if (o.type === 'market' || o.price >= p - 1e-9) buy += o.qty - o.filled;
|
||
for (const o of this.asks) if (o.type === 'market' || o.price <= p + 1e-9) sell += o.qty - o.filled;
|
||
const vol = Math.min(buy, sell);
|
||
const cand = { price: p, volume: vol, surplus: buy - sell };
|
||
if (!best || vol > best.volume || (vol === best.volume && (Math.abs(cand.surplus) < Math.abs(best.surplus)
|
||
|| (Math.abs(cand.surplus) === Math.abs(best.surplus) && Math.abs(p - ref) < Math.abs(best.price - ref))))) best = cand;
|
||
}
|
||
if (!best || best.volume <= 0) return null;
|
||
// gleiches Volumen und gleicher Überhang über eine Preisspanne → Referenzpreis, falls innerhalb
|
||
return best;
|
||
}
|
||
|
||
#vol(side) { return side.reduce((a, o) => a + o.qty - o.filled, 0); }
|
||
|
||
/**
|
||
* Auktion ausgleichen: alle kreuzenden Orders zum Einheitspreis ausführen.
|
||
* Danach ist das Buch nicht mehr gekreuzt; nicht ausgeführte Market-Orders verfallen.
|
||
* @param {number} ref Referenzpreis @param {CanFill} [canFill]
|
||
* @returns {{price:number|null, volume:number, trades: Trade[]}}
|
||
*/
|
||
uncross(ref, canFill = () => true) {
|
||
const ind = this.indicative(ref);
|
||
const trades = [];
|
||
if (ind) {
|
||
const p = ind.price;
|
||
const eligible = (o) => o.type === 'market' || (o.side === 'buy' ? o.price >= p - 1e-9 : o.price <= p + 1e-9);
|
||
while (this.bids.length && this.asks.length) {
|
||
const b = this.bids[0], a = this.asks[0];
|
||
if (!eligible(b) || !eligible(a)) break;
|
||
if (b.group === a.group) { // Self-Trade-Prevention: jüngere Order verfällt
|
||
this.#remove(b.ts >= a.ts ? b : a, 'cancelled');
|
||
continue;
|
||
}
|
||
const qty = Math.min(b.qty - b.filled, a.qty - a.filled);
|
||
const ok = canFill(b, a, qty, p);
|
||
if (ok !== true) { this.#remove(ok === 'buy' ? b : a, 'cancelled'); continue; }
|
||
const t = this.#fill(b, a, qty, p, null);
|
||
t.auction = true;
|
||
trades.push(t);
|
||
if (b.filled >= b.qty) this.#remove(b, 'filled');
|
||
if (a.filled >= a.qty) this.#remove(a, 'filled');
|
||
}
|
||
}
|
||
// Market-Reste verfallen, Icebergs neu einreihen
|
||
for (const o of [...this.bids, ...this.asks]) {
|
||
if (o.type === 'market') this.#remove(o, o.filled ? 'partial-cancelled' : 'cancelled');
|
||
else if (o.peak) o.show = Math.min(o.peak, o.qty - o.filled);
|
||
}
|
||
const volume = trades.reduce((x, t) => x + t.qty, 0);
|
||
return { price: trades.length ? ind.price : null, volume, trades };
|
||
}
|
||
|
||
/** Storno; group (Spieler) muss passen, falls angegeben */
|
||
cancel(orderId, group) {
|
||
const o = this.orders.get(Number(orderId));
|
||
if (!o || (group && o.group !== group)) return null;
|
||
this.#remove(o, 'cancelled');
|
||
return o;
|
||
}
|
||
|
||
cancelAllOf(ownerId) {
|
||
const set = this.byOwner.get(ownerId);
|
||
if (!set) return [];
|
||
const list = [...set];
|
||
for (const o of list) this.#remove(o, 'cancelled');
|
||
return list;
|
||
}
|
||
|
||
/** Orders entfernen, die eine Bedingung erfüllen (z. B. abgelaufene Tagesorders) */
|
||
removeWhere(pred, status = 'expired') {
|
||
const out = [];
|
||
for (const o of [...this.orders.values()]) if (pred(o)) { this.#remove(o, status); out.push(o); }
|
||
return out;
|
||
}
|
||
|
||
openOrdersOf(ownerId) { return [...(this.byOwner.get(ownerId) ?? [])]; }
|
||
countOf(ownerId) { return this.byOwner.get(ownerId)?.size ?? 0; }
|
||
|
||
/** Aggregierte Markttiefe (Level 2); Icebergs zeigen nur die sichtbare Spitze */
|
||
depth(levels = 10) {
|
||
const agg = (side) => {
|
||
const out = [];
|
||
for (const o of side) {
|
||
if (o.type !== 'limit') continue;
|
||
const rest = o.peak ? o.show : o.qty - o.filled;
|
||
const last = out[out.length - 1];
|
||
if (last && Math.abs(last.price - o.price) < TICK / 2) { last.qty += rest; last.count++; }
|
||
else if (out.length < levels) out.push({ price: o.price, qty: rest, count: 1 });
|
||
else break;
|
||
}
|
||
return out;
|
||
};
|
||
return { bids: agg(this.bids), asks: agg(this.asks) };
|
||
}
|
||
|
||
#fill(a, b, qty, price, aggressor) {
|
||
const buyer = a.side === 'buy' ? a : b;
|
||
const seller = a.side === 'buy' ? b : a;
|
||
a.filled += qty; b.filled += qty;
|
||
for (const o of [a, b]) if (o.peak && this.orders.has(o.id)) o.show -= qty;
|
||
return {
|
||
id: nextTradeId++, symbol: this.symbol, price, qty, buyOrderId: buyer.id, sellOrderId: seller.id,
|
||
buyerId: buyer.ownerId, sellerId: seller.ownerId, aggressor, ts: Date.now(), bo: buyer, so: seller,
|
||
};
|
||
}
|
||
|
||
#reloadIceberg(o) {
|
||
const side = o.side === 'buy' ? this.bids : this.asks;
|
||
side.splice(side.indexOf(o), 1);
|
||
o.show = Math.min(o.peak, o.qty - o.filled);
|
||
o.ts = Date.now(); // neue Spitze verliert die Zeitpriorität
|
||
this.#insert(side, o);
|
||
}
|
||
|
||
#insert(side, order) {
|
||
const key = (o) => (o.type === 'market' ? (order.side === 'buy' ? Infinity : -Infinity) : o.price);
|
||
const better = order.side === 'buy' ? (x, y) => x > y : (x, y) => x < y;
|
||
let i = side.findIndex((o) => better(key(order), key(o)) || (key(order) === key(o) && order.ts < o.ts));
|
||
if (i === -1) i = side.length;
|
||
side.splice(i, 0, order);
|
||
}
|
||
|
||
#rest(order) {
|
||
order.status = order.filled ? 'partial' : 'open';
|
||
if (order.peak) order.show = Math.min(order.peak, order.qty - order.filled);
|
||
this.#insert(order.side === 'buy' ? this.bids : this.asks, order);
|
||
this.orders.set(order.id, order);
|
||
let set = this.byOwner.get(order.ownerId);
|
||
if (!set) this.byOwner.set(order.ownerId, (set = new Set()));
|
||
set.add(order);
|
||
}
|
||
|
||
#remove(order, status) {
|
||
const side = order.side === 'buy' ? this.bids : this.asks;
|
||
const i = side.indexOf(order);
|
||
if (i !== -1) side.splice(i, 1);
|
||
this.orders.delete(order.id);
|
||
const set = this.byOwner.get(order.ownerId);
|
||
if (set) { set.delete(order); if (!set.size) this.byOwner.delete(order.ownerId); }
|
||
order.status = status;
|
||
}
|
||
}
|