mirror of
https://github.com/db9979/wibosim.git
synced 2026-12-06 13:34:09 +01:00
- Farbschema System/Hell/Dunkel (Knopf in der Kopfleiste und in den Einstellungen), ohne Aufblitzen beim Laden - Alle Farben als Variablen, Diagramme lesen die Farben beim Zeichnen und folgen dem Schema - Nachrichten: Themen mit Pfeil, Eilmeldung, Folgemeldung, KI-Analyse und „Warum?“ mit bewegten Werten - Admin: Schlagzeile mit Regelwerk und Sprachmodell testen, Status der KI-Auswertung Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018i4GUhQVoPUusUzxgxLWkK
927 lines
58 KiB
JavaScript
927 lines
58 KiB
JavaScript
// Handel: Marktliste, Aktienansicht (Kopf, Chart, Detail-Tabs), Orderticket, Orderbuch und Umsätze.
|
||
import { S, sub, changed, loggedIn, activePortfolio } from './state.js';
|
||
import { request } from './net.js';
|
||
import { CandleChart, paint, curveChart } from './charts.js';
|
||
import { toast, ask, gl } from './ui.js';
|
||
import { esc, $, $$, num, int, eur, compact, pct, frac, chg, dirCls, arrow, countdown, now, when, time, timeS, ago, patch, player, meter, safeUrl, store } from './util.js';
|
||
import { renderComments } from './social.js';
|
||
|
||
const ORDER_TYPES = {
|
||
limit: { label: 'Limit', simple: true },
|
||
market: { label: 'Market (Bestens/Billigst)', simple: true },
|
||
stop: { label: 'Stop-Loss', simple: true },
|
||
stoplimit: { label: 'Stop-Limit' },
|
||
takeprofit: { label: 'Take-Profit' },
|
||
trailing: { label: 'Trailing-Stop' },
|
||
};
|
||
const COND = new Set(['stop', 'stoplimit', 'takeprofit', 'trailing']);
|
||
const TIF = { day: 'Tag (bis Handelsschluss)', gtc: 'GTC – bis auf Widerruf', gtd: 'GTD – bis Datum', ioc: 'IOC – sofort, Rest streichen', fok: 'FOK – ganz oder gar nicht' };
|
||
|
||
let chart = null;
|
||
let stab = 'company';
|
||
let side = 'buy';
|
||
let navigate = () => {};
|
||
let lastNewsId = null;
|
||
|
||
export const ticker = (sym = S.symbol) => S.tickerMap.get(sym);
|
||
|
||
// ================================================================ Marktliste
|
||
function statusBadges(t, { long = false } = {}) {
|
||
const b = [];
|
||
if (t.status === 'call') b.push(`<span class="badge-s auction" title="Auktion: Orders werden gesammelt">${gl('Auktion', 'Auktion')}</span>`);
|
||
if (t.status === 'vola') b.push(`<span class="badge-s halt" title="Volatilitätsunterbrechung">${long ? gl('Volatilitätsunterbrechung', 'Volatilitätsunterbrechung') : '<abbr title="Volatilitätsunterbrechung">VU</abbr>'} ${t.volaEndsAt ? `<span class="cd" data-until="${t.volaEndsAt}">${countdown(t.volaEndsAt - now())}</span>` : ''}</span>`);
|
||
if (t.htb) b.push(`<span class="badge-s short" title="Hard to borrow – Leihpool fast ausgeschöpft">HTB</span>`);
|
||
if (Number.isFinite(t.earningsIn) && t.earningsIn >= 0 && t.earningsIn <= 3) b.push(`<span class="badge-s earn" title="Quartalszahlen">${t.earningsIn === 0 ? 'Zahlen heute' : `Zahlen in ${t.earningsIn} T`}</span>`);
|
||
if (t.kind === 'bond' && Number.isFinite(t.exDivIn)) b.push(`<span class="badge-s div" title="Nächste Kuponzahlung (Handelstage)">${t.exDivIn <= 0 ? 'Kupon heute' : `Kupon in ${t.exDivIn} T`}</span>`);
|
||
else if (Number.isFinite(t.exDivIn) && t.exDivIn >= 0 && t.exDivIn <= 3) b.push(`<span class="badge-s div" title="Ex-Dividenden-Tag">${t.exDivIn === 0 ? 'Ex-Tag heute' : `Ex-Div. in ${t.exDivIn} T`}</span>`);
|
||
if (t.corp === 'offer') b.push(`<span class="badge-s offer" title="Laufendes Übernahmeangebot">${long ? gl('Übernahmeangebot', 'Übernahme') : 'Übernahme'}</span>`);
|
||
if (t.corp === 'trial') b.push('<span class="badge-s trial" title="Studienergebnis angekündigt">Studie</span>');
|
||
return b.join('');
|
||
}
|
||
|
||
// ================================================================ Anlageklassen & Einheiten
|
||
const CLASS_ORDER = ['stock', 'bond', 'commodity', 'fx'];
|
||
const CLASS_FALLBACK = { stock: 'Aktien', bond: 'Anleihen', commodity: 'Rohstoffe', fx: 'Devisen' };
|
||
export const kindOf = (t) => t?.kind ?? 'stock';
|
||
export const className = (k) => S.info?.assetClasses?.[k] ?? CLASS_FALLBACK[k] ?? k;
|
||
/** Preiseinheit eines Instruments */
|
||
export function unitOf(t) {
|
||
if (!t) return '';
|
||
if (kindOf(t) === 'bond') return 'je 100 € Nennwert';
|
||
return { OEL: 'je Barrel', GOLD: 'je 10 g', USD: 'je 100 $' }[t.symbol] ?? (kindOf(t) === 'stock' ? 'je Aktie' : 'je Stück');
|
||
}
|
||
/** Was treibt den Preis (Rohstoffe/Devisen) */
|
||
const DRIVERS = {
|
||
OEL: ['Weltkonjunktur (BIP-Wachstum über/unter Trend)', 'Marktstimmung', 'Förderentscheidungen des Petrolia-Kartells (Angebotsschocks, klingen über Wochen ab)', 'Wirkt zurück: teures Öl erhöht die Inflation und belastet Auto, Industrie und Handel – Energiewerte profitieren'],
|
||
GOLD: ['Realzins (Leitzins minus Inflation): fallende Realzinsen machen Gold attraktiver', 'Angst: schlechte Stimmung treibt den sicheren Hafen', 'Risikoaufschlag auf Wiborien-Anleihen (Zweifel an den Staatsfinanzen)'],
|
||
USD: ['Zinsdifferenz: Auslandszins minus Leitzins – sinkt der Leitzins relativ, wird der Dollar teurer', 'Risikoaufschlag Wiboriens (Kapitalflucht schwächt den Euro)', 'Wirkt zurück: teurer Dollar hilft Exporteuren und erhöht die Inflation'],
|
||
};
|
||
const groupClosed = new Set(store.get('mgrpClosed', []));
|
||
|
||
function renderMarketList() {
|
||
const rules = S.account === 'battle' ? S.battlePortfolio?.rules : null;
|
||
const visible = rules?.symbols ? S.tickers.filter((t) => rules.symbols.includes(t.symbol) || t.symbol === S.symbol) : S.tickers;
|
||
const hidden = S.tickers.length - visible.length;
|
||
const row = (t) => {
|
||
const prev = S.prevLast.get(t.symbol);
|
||
const flash = prev !== undefined && prev !== t.last ? (t.last > prev ? 'flash-up' : 'flash-down') : '';
|
||
const blocked = rules?.symbols && !rules.symbols.includes(t.symbol);
|
||
const ind = t.indicative && t.status !== 'continuous'
|
||
? `<small class="ind" title="Indikativer Auktionspreis und ausführbares Volumen">ind. ${num(t.indicative.price)} · ${compact(t.indicative.volume)} St.</small>` : '';
|
||
const extra = kindOf(t) === 'bond' ? `<small class="yl">Rendite ${num(t.yield, 2)} % · Dur. ${num(t.duration, 1)}</small>` : '';
|
||
return `<tr class="${t.symbol === S.symbol ? 'sel' : ''} ${blocked ? 'dim' : ''}" data-sym="${esc(t.symbol)}">
|
||
<td><button type="button" class="sym-btn" data-act="sym" data-sym="${esc(t.symbol)}" data-k="sym-${esc(t.symbol)}" aria-label="${esc(t.symbol)} ${esc(t.name)} anzeigen"><b>${esc(t.symbol)}</b>${rules?.symbols?.includes(t.symbol) ? ' <span class="badge-s battle" title="Im Battle handelbar">Battle</span>' : ''}<small>${esc(t.name)}</small>${extra}</button><div class="badges">${statusBadges(t)}</div></td>
|
||
<td class="num ${flash}">${num(t.last)}${ind}</td>
|
||
<td class="num">${chg(t.change)}</td></tr>`;
|
||
};
|
||
const kinds = [...new Set([...CLASS_ORDER, ...visible.map(kindOf)])];
|
||
const multi = kinds.filter((k) => visible.some((t) => kindOf(t) === k)).length > 1;
|
||
const rows = kinds.map((k) => {
|
||
const list = visible.filter((t) => kindOf(t) === k);
|
||
if (!list.length) return '';
|
||
if (!multi) return list.map(row).join('');
|
||
const closed = groupClosed.has(k);
|
||
const shown = closed ? list.filter((t) => t.symbol === S.symbol) : list;
|
||
return `<tr class="grp"><th colspan="3" scope="colgroup"><button type="button" class="grp-btn" data-act="mgrp" data-g="${esc(k)}" data-k="grp-${esc(k)}" aria-expanded="${!closed}"><span aria-hidden="true">${closed ? '▸' : '▾'}</span> ${esc(className(k))} <span class="muted">(${list.length})</span></button></th></tr>${shown.map(row).join('')}`;
|
||
}).join('') + (hidden ? `<tr class="dim"><td colspan="3"><small>${hidden} weitere Werte im Battle-Modus „3 Aktien“ ausgeblendet – für alle Werte auf das Hauptdepot wechseln.</small></td></tr>` : '');
|
||
patch($('#mlist'), rows);
|
||
const m = S.market;
|
||
if (m) $('#marketMeta').textContent = `Tag ${m.day}`;
|
||
}
|
||
|
||
// ================================================================ Aktie
|
||
export function selectSymbol(sym, { go = false } = {}) {
|
||
if (!S.tickerMap.has(sym)) return;
|
||
if (sym !== S.symbol) {
|
||
S.symbol = sym;
|
||
store.set('symbol', sym);
|
||
S.book = null; S.candles = []; S.company = null;
|
||
subscribe();
|
||
loadCompany();
|
||
renderMarketList();
|
||
renderStock();
|
||
renderBook();
|
||
syncTicketDefaults(true);
|
||
}
|
||
if (go) navigate('handeln');
|
||
}
|
||
|
||
export async function subscribe() {
|
||
try {
|
||
const r = await request('subscribe', { symbol: S.symbol });
|
||
if (r.symbol !== S.symbol) return;
|
||
S.candles = r.candles ?? [];
|
||
S.book = { ...(S.book ?? {}), depth: r.depth, tape: r.tape ?? [] };
|
||
drawChart();
|
||
renderBook();
|
||
} catch (e) { if (!/Verbindung/.test(e.message)) toast(e.message, 'err'); }
|
||
}
|
||
|
||
export async function loadCompany() {
|
||
const sym = S.symbol;
|
||
try {
|
||
const r = await request('company', { symbol: sym });
|
||
if (sym !== S.symbol) return;
|
||
S.company = r.company;
|
||
renderStabs();
|
||
if (S.chartMode === 'daily') drawChart();
|
||
} catch (e) { if (!/Verbindung/.test(e.message)) toast(e.message, 'err'); }
|
||
}
|
||
|
||
function onBook(m) {
|
||
if (m.symbol !== S.symbol) return;
|
||
S.book = { depth: m.depth, tape: m.tape, candle: m.candle, indicative: m.indicative, status: m.status };
|
||
if (m.candle) {
|
||
const c = S.candles;
|
||
const last = c[c.length - 1];
|
||
if (last && last.t === m.candle.t) c[c.length - 1] = m.candle;
|
||
else if (!last || m.candle.t > last.t) { c.push(m.candle); if (c.length > 500) c.shift(); }
|
||
}
|
||
renderBook();
|
||
if (S.chartMode === 'intraday') drawChart();
|
||
}
|
||
|
||
function drawChart() {
|
||
if (!chart) return;
|
||
const t = ticker();
|
||
const ind = t?.indicative && t.status !== 'continuous' ? t.indicative.price : null;
|
||
if (S.chartMode === 'daily') {
|
||
const bars = (S.company?.dailyBars ?? []).map((b) => ({ ...b, label: `T${b.day}` }));
|
||
chart.set(bars, { daily: true, empty: S.company ? 'Noch keine abgeschlossenen Handelstage' : 'Lade …' });
|
||
$('#chartNote').textContent = bars.length ? `${bars.length} Handelstage` : '';
|
||
} else {
|
||
chart.set(S.candles, { last: t?.last, indicative: ind, prevClose: t?.prevClose, empty: 'Noch keine Umsätze in diesem Zeitraum' });
|
||
$('#chartNote').textContent = S.candles.length ? `Kerzen seit ${time(S.candles[0].t)} · gestrichelt: Vortagesschluss` : '';
|
||
}
|
||
}
|
||
|
||
function renderStock() {
|
||
const t = ticker();
|
||
if (!t) return;
|
||
const spread = t.bid && t.ask ? t.ask - t.bid : null;
|
||
const kind = kindOf(t);
|
||
const common = `
|
||
<div><dt>Geld / Brief</dt><dd class="num">${num(t.bid)} / ${num(t.ask)}</dd></div>
|
||
<div><dt>${gl('Spread')}</dt><dd class="num">${spread !== null ? num(spread) : '–'}</dd></div>
|
||
<div><dt>Hoch / Tief</dt><dd class="num">${num(t.high)} / ${num(t.low)}</dd></div>
|
||
<div><dt>Eröffnung</dt><dd class="num">${num(t.open)}</dd></div>
|
||
<div><dt>Volumen</dt><dd class="num">${compact(t.volume)}</dd></div>`;
|
||
let kv;
|
||
if (kind === 'stock') {
|
||
const pe = t.pe ? num(t.pe, 1) : 'n. a.';
|
||
kv = `${common}
|
||
<div><dt>Börsenwert</dt><dd class="num">${compact(t.mcap)} €</dd></div>
|
||
<div><dt>${gl('KGV')}</dt><dd class="num">${pe}</dd></div>
|
||
<div><dt>${gl('Dividende', 'Div.-Rendite')}</dt><dd class="num">${frac(t.divYield, 2)}</dd></div>`;
|
||
} else if (kind === 'bond') {
|
||
kv = `${common}
|
||
<div><dt>${gl('Rendite')}</dt><dd class="num">${num(t.yield, 2)} %</dd></div>
|
||
<div><dt>${gl('Duration')}</dt><dd class="num">${num(t.duration, 1)} J.</dd></div>
|
||
<div><dt>${gl('Kupon')}</dt><dd class="num">${Number.isFinite(t.exDivIn) ? (t.exDivIn <= 0 ? 'heute' : `in ${int(t.exDivIn)} T`) : '–'}</dd></div>`;
|
||
} else {
|
||
kv = `${common}
|
||
<div><dt>Volatilität p. a.</dt><dd class="num">${frac(t.vol, 0)}</dd></div>`;
|
||
}
|
||
patch($('#sHead'), `
|
||
<div class="sh-top">
|
||
<div><h1 class="sym">${esc(t.symbol)}</h1><span class="muted">${esc(t.name)} · ${esc(kind === 'stock' ? (S.info?.sectors?.[t.sector]?.name ?? t.sector) : className(kind))}</span></div>
|
||
<div class="px-big"><span class="num">${num(t.last)} €</span> ${chg(t.change)}</div>
|
||
<div class="badges">${statusBadges(t, { long: true })}</div>
|
||
</div>
|
||
${kind !== 'stock' ? `<p class="muted small unit-line">Kurs in € ${esc(unitOf(t))} · gehandelt wie Aktien (Orderbuch, Auktionen, Leerverkauf möglich)</p>` : ''}
|
||
<dl class="kv-row">${kv}
|
||
<div><dt>Leihzins p. a.</dt><dd class="num">${frac(t.borrowRate, 1)}${t.htb ? ' <span class="badge-s short">HTB</span>' : ''}</dd></div>
|
||
</dl>`);
|
||
// Status-Hinweis (Auktion / Unterbrechung / geschlossen)
|
||
const ban = $('#sBanner');
|
||
let txt = '';
|
||
const ph = S.market?.phase;
|
||
if (t.status === 'vola') {
|
||
txt = `<b>${gl('Volatilitätsunterbrechung')}</b> – Auktion endet in ca. <span class="cd" data-until="${t.volaEndsAt}">${countdown(t.volaEndsAt - now())}</span> (zufälliges Ende). Orders werden gesammelt.`;
|
||
} else if (t.status === 'call') {
|
||
txt = `<b>${esc(S.market?.label ?? 'Auktion')}</b> – Orders werden gesammelt und zu einem Preis ausgeführt.`;
|
||
} else if (ph === 'closed' || ph === 'preopen') {
|
||
txt = `<b>${ph === 'preopen' ? 'Vorbörse' : 'Börse geschlossen'}</b> – Orders werden für die Eröffnungsauktion gesammelt.`;
|
||
}
|
||
if (t.indicative && t.status !== 'continuous') {
|
||
const s = t.indicative.surplus;
|
||
txt += ` <span class="ind-line">Indikativ: <b class="num">${num(t.indicative.price)} €</b> · ${int(t.indicative.volume)} St.${s ? ` · Überhang ${s > 0 ? 'Kauf' : 'Verkauf'} ${int(Math.abs(s))}` : ''}</span>`;
|
||
}
|
||
ban.hidden = !txt;
|
||
patch(ban, txt);
|
||
updateSticky();
|
||
}
|
||
|
||
// ---------------------------------------------------------------- Detail-Tabs
|
||
function renderStabs() {
|
||
for (const b of $$('#sTabs [data-stab]')) b.setAttribute('aria-selected', String(b.dataset.stab === stab));
|
||
const t0 = $('#sTabs [data-stab="company"]');
|
||
const k0 = kindOf(ticker());
|
||
const lbl = k0 === 'stock' ? 'Unternehmen' : k0 === 'bond' ? 'Anleihe' : k0 === 'fx' ? 'Devise' : 'Rohstoff';
|
||
if (t0 && t0.textContent !== lbl) t0.textContent = lbl;
|
||
const t1 = $('#sTabs [data-stab="holders"]');
|
||
if (t1) t1.textContent = k0 === 'stock' ? 'Aktionäre' : 'Halter';
|
||
const el = $('#sTabBody');
|
||
const c = S.company;
|
||
if (stab === 'comments') { renderComments(el, `stock:${S.symbol}`); return; }
|
||
el._commentsTarget = null;
|
||
if (!c || c.symbol !== S.symbol) { patch(el, '<p class="muted">Lade Daten …</p>'); return; }
|
||
if (stab === 'company') {
|
||
if (c.kind && c.kind !== 'stock') { patch(el, instrumentHtml(c)); paint($('#instCurve'), curveChart(c.curve)); }
|
||
else patch(el, companyHtml(c));
|
||
}
|
||
else if (stab === 'lending') patch(el, lendingHtml(c));
|
||
else if (stab === 'holders') patch(el, holdersHtml(c));
|
||
else if (stab === 'news') patch(el, newsList(c.news, c.kind && c.kind !== 'stock' ? 'Keine Meldungen zu diesem Wertpapier.' : 'Keine Meldungen zu diesem Unternehmen.'));
|
||
}
|
||
|
||
function companyHtml(c) {
|
||
const a = c.analysts;
|
||
const qs = c.quarters ?? [];
|
||
const maxEps = Math.max(0.01, ...qs.map((q) => Math.max(Math.abs(q.eps), Math.abs(q.est))), Math.abs(c.consensus ?? 0));
|
||
const bars = qs.map((q) => {
|
||
const beat = q.eps >= q.est;
|
||
return `<div class="b" title="${esc(q.label)}: Gewinn je Aktie ${num(q.eps)} € (Erwartung ${num(q.est)} €, ${pct(q.surprise * 100, 1)})">
|
||
<span class="v">${num(q.eps)}</span><i class="${beat ? '' : 'miss'}" style="height:${(Math.abs(q.eps) / maxEps) * 100}%"></i><span>${esc(q.label)}</span><span class="${dirCls(q.surprise)}">${arrow(q.surprise)}${num(Math.abs(q.surprise * 100), 1)}%</span></div>`;
|
||
}).join('') + (c.consensus ? `<div class="b" title="Konsens für das nächste Quartal"><span class="v">${num(c.consensus)}</span><i class="est" style="height:${(Math.abs(c.consensus) / maxEps) * 100}%"></i><span>nächstes</span><span class="muted">Konsens</span></div>` : '');
|
||
let range = '';
|
||
if (a) {
|
||
const lo = Math.min(a.low, c.last), hi = Math.max(a.high, c.last);
|
||
const pos = (v) => ((v - lo) / Math.max(1e-9, hi - lo)) * 100;
|
||
range = `
|
||
<div class="an-counts"><span class="up">Kaufen ${a.buy}</span> · <span class="gold-t">Halten ${a.hold}</span> · <span class="down">Verkaufen ${a.sell}</span></div>
|
||
<div class="range" aria-label="Spanne der Kursziele ${num(a.low)} bis ${num(a.high)} Euro, Median ${num(a.target)}, aktueller Kurs ${num(c.last)}">
|
||
<div class="range-bar" style="left:${pos(a.low)}%;width:${pos(a.high) - pos(a.low)}%"></div>
|
||
<div class="range-mark med" style="left:${pos(a.target)}%" title="Median-Kursziel"></div>
|
||
<div class="range-mark cur" style="left:${pos(c.last)}%" title="Aktueller Kurs"></div>
|
||
</div>
|
||
<div class="range-lbl"><span>Tief ${num(a.low)} €</span><span>Median ${num(a.target)} €</span><span>Hoch ${num(a.high)} €</span></div>
|
||
<details><summary>Einzelne Analysehäuser</summary><table class="mini-t"><tbody>${a.ratings.map((r) => `<tr><td>${esc(r.firm)}</td><td class="rating r-${esc(r.rating)}">${esc(r.rating)}</td><td class="num">${num(r.target)} €</td></tr>`).join('')}</tbody></table></details>`;
|
||
}
|
||
const sens = (x, what) => (Number.isFinite(x) && x !== 0 ? `<span class="${dirCls(x)}">${x > 0 ? '+' : '−'}${num(Math.abs(x), 2)}</span> <small class="muted">(${what} +10 % → Gewinn ${x > 0 ? '+' : '−'}${num(Math.abs(x) * 10, 1)} %)</small>` : '<span class="muted">kaum betroffen</span>');
|
||
const office = S.government?.me?.office ?? S.profile?.office;
|
||
const conflict = office?.sectors?.includes(c.sector);
|
||
const policy = (c.policy ?? []).length
|
||
? `<h3 class="h4">Wirkung beschlossener Gesetze</h3><ul class="plain">${c.policy.map((p) => `<li>${esc(p.bill)}: <span class="${dirCls(p.pct)}">${pct(p.pct, 1)}</span> auf den Gewinn ab Tag ${int(p.startDay)}</li>`).join('')}</ul>` : '';
|
||
return `
|
||
${corpHtml(c)}
|
||
<div class="grid3">
|
||
<div>
|
||
<h3 class="h4">Profil</h3>
|
||
<p>${esc(c.desc)}</p>
|
||
<dl class="kv">
|
||
<dt>Sektor</dt><dd>${esc(c.sectorName)}</dd><dt>Sitz</dt><dd>${esc(c.hq)}</dd>
|
||
<dt>Gegründet</dt><dd>${esc(c.founded)}</dd><dt>Mitarbeitende</dt><dd>${int(c.employees)}</dd>
|
||
<dt>Aktien</dt><dd>${compact(c.shares)}</dd><dt>Börsenwert</dt><dd>${compact(c.mcap)} €</dd>
|
||
<dt>Volatilität p. a.</dt><dd>${frac(c.vol, 0)}</dd>
|
||
</dl>
|
||
</div>
|
||
<div>
|
||
<h3 class="h4">Kennzahlen</h3>
|
||
<dl class="kv">
|
||
<dt>Gewinn je Aktie (12 M.)</dt><dd>${eur(c.epsTTM)}</dd>
|
||
<dt>${gl('KGV')} / Sektor</dt><dd>${c.pe ? num(c.pe, 1) : 'n. a.'} / ${num(c.sectorPe, 0)}</dd>
|
||
<dt>Erw. Wachstum</dt><dd>${frac(c.growth, 1)}</dd>
|
||
<dt>Ausschüttungsquote</dt><dd>${frac(c.payout, 0)}</dd>
|
||
<dt>Letzte ${gl('Dividende')}</dt><dd>${eur(c.lastDividend)} (${frac(c.divYield, 2)} p. a.)</dd>
|
||
${c.pendingDividend ? `<dt>Nächste Dividende</dt><dd>${eur(c.pendingDividend)} · ${gl('Ex-Tag')} ${c.exDivIn === 0 ? 'heute' : `in ${int(c.exDivIn)} Handelstagen`}</dd>` : ''}
|
||
<dt>Nächste Zahlen</dt><dd>${c.earningsIn <= 0 ? 'heute' : `in ${int(c.earningsIn)} Handelstagen`} · Konsens ${eur(c.consensus)}</dd>
|
||
${c.lastAuction?.price ? `<dt>Letzte Auktion</dt><dd>${eur(c.lastAuction.price)} · ${int(c.lastAuction.volume)} St.</dd>` : ''}
|
||
<dt>Zuständiges Ministerium</dt><dd>${esc(c.ministry ?? '–')}${conflict ? ' <span class="badge-s halt" title="Du leitest dieses Ressort">dein Ressort</span>' : ''}</dd>
|
||
<dt>Ölpreis-Empfindlichkeit</dt><dd>${sens(c.oilSens, 'Öl')}</dd>
|
||
<dt>Dollar-Empfindlichkeit</dt><dd>${sens(c.fxSens, 'Dollar')}</dd>
|
||
</dl>
|
||
</div>
|
||
<div>
|
||
<h3 class="h4">Analysten <span class="muted small">(kein „fairer Wert“ – nur Kursziele)</span></h3>
|
||
${range || '<p class="muted">Keine Einschätzungen.</p>'}
|
||
</div>
|
||
</div>
|
||
<h3 class="h4">Quartale: Gewinn je Aktie <span class="muted small">(Balken grün = Erwartung übertroffen, rot = verfehlt)</span></h3>
|
||
<div class="bars">${bars}</div>
|
||
${policy}
|
||
${c.corporate?.history?.length ? `<h3 class="h4">Unternehmensereignisse</h3><ul class="plain">${c.corporate.history.map((h) => `<li><span class="muted">Tag ${int(h.day)} ·</span> ${esc(h.title)}</li>`).join('')}</ul>` : ''}`;
|
||
}
|
||
|
||
const symLink = (sym, label = sym) => `<button type="button" class="linkish" data-act="sym" data-sym="${esc(sym)}">${esc(label)}</button>`;
|
||
|
||
/** Übernahmeangebot, Studie, Beherrschung – oben in der Unternehmensansicht */
|
||
function corpHtml(c) {
|
||
const k = c.corporate;
|
||
if (!k) return '';
|
||
const out = [];
|
||
const o = k.offer;
|
||
if (o) {
|
||
const target = o.role === 'target';
|
||
const own = Math.max(0, S.portfolio?.positions?.find((x) => x.symbol === c.symbol)?.qty ?? 0);
|
||
const mine = o.myTender ?? 0;
|
||
const tender = !target ? `<p class="muted small">${esc(c.name)} ist hier der Bieter. Bieter zahlen im Mittel zu viel – scheitert die Übernahme, erholt sich der Kurs meist etwas.</p>`
|
||
: loggedIn() ? `<div class="tender">
|
||
<p>Deine ${gl('Andienung')}: <b>${int(mine)} St.</b>${mine ? ` → bei Erfolg ${eur(mine * o.price)}` : ''} · Bestand im Hauptdepot: <b>${int(own)} St.</b></p>
|
||
${own > 0 || mine ? `<div class="inline-form"><label class="sr" for="tenderQty">Stückzahl andienen (0 = zurückziehen)</label>
|
||
<input id="tenderQty" data-k="tenderQty" type="number" inputmode="numeric" min="0" max="${own}" step="1" value="${mine || own}">
|
||
<button type="button" class="btn" data-act="tender" data-sym="${esc(c.symbol)}">Andienen</button>
|
||
${mine ? `<button type="button" class="btn ghost" data-act="tender" data-sym="${esc(c.symbol)}" data-zero="1">Zurückziehen</button>` : ''}</div>`
|
||
: '<p class="muted small">Du hältst keine Aktien dieses Unternehmens im Hauptdepot.</p>'}
|
||
<p class="muted small">Angedient wird aus dem Hauptdepot (höchstens dein Bestand, 0 = zurückziehen). Gelingt die Übernahme, werden die Aktien zum Angebotspreis gebührenfrei ausgebucht; scheitert sie, bleiben sie im Depot. Verkaufst du vorher, zählt nur der verbleibende Bestand.</p></div>`
|
||
: '<p class="muted small">Zum Andienen bitte <button type="button" class="linkish" data-act="login">anmelden</button>.</p>';
|
||
out.push(`<div class="corp-box offer">
|
||
<h3 class="h4">${gl('Übernahmeangebot')}${target ? '' : ' – als Bieter'}</h3>
|
||
<p>${target ? `<b>${esc(o.bidderName)}</b> (${symLink(o.bidder)}) bietet` : `<b>${esc(c.name)}</b> bietet für <b>${esc(o.targetName)}</b> (${symLink(o.target)})`} <b class="num">${eur(o.price)}</b> je Aktie.</p>
|
||
<div class="kpis">
|
||
<div><small>Angebotspreis</small><b>${eur(o.price)}</b></div>
|
||
<div><small>Aufschlag</small><b>${frac(o.premium, 0)}</b></div>
|
||
<div><small>Erfolgschance</small><b>${frac(o.probability, 0)}</b></div>
|
||
<div><small>Annahmefrist</small><b>${o.daysLeft <= 0 ? 'endet heute' : `${int(o.daysLeft)} Handelstage`}</b></div>
|
||
<div><small>Angedient (Spieler)</small><b>${int(o.tenderedTotal)} St.</b></div>
|
||
${target ? `<div><small>Kurs → Angebot</small><b>${pct((o.price / c.last - 1) * 100, 1)}</b></div>` : ''}
|
||
</div>
|
||
<p class="small">${o.authority ? `Prüfung durch das <b>${esc(o.authority)}</b> (gleiche Branche) – kann den Zusammenschluss untersagen.` : 'Keine kartellrechtliche Prüfung (verschiedene Branchen).'}</p>
|
||
${tender}</div>`);
|
||
}
|
||
const t = k.trial;
|
||
if (t) {
|
||
out.push(`<div class="corp-box">
|
||
<h3 class="h4">Studienergebnis erwartet</h3>
|
||
<div class="kpis">
|
||
<div><small>Wirkstoff</small><b>${esc(t.drug)}</b><small>Phase ${esc(t.phase)}</small></div>
|
||
<div><small>Ergebnis</small><b>${t.daysLeft <= 0 ? 'heute' : `in ${int(t.daysLeft)} T`}</b></div>
|
||
<div><small>Erfolgschance</small><b>${frac(t.probability, 0)}</b></div>
|
||
<div><small>bei Erfolg</small><b class="up">▲ ${pct(t.up * 100, 0)}</b></div>
|
||
<div><small>bei Misserfolg</small><b class="down">▼ ${pct(-t.down * 100, 0)}</b></div>
|
||
</div>
|
||
<p class="muted small">Wirkung auf den Unternehmenswert. Der Kurs preist die Erfolgschance schon ein – bei der Veröffentlichung bewegt er sich nur um die Überraschung.</p></div>`);
|
||
}
|
||
const ctl = k.control;
|
||
if (ctl) {
|
||
out.push(`<div class="corp-box">
|
||
<h3 class="h4">Beherrscht von ${symLink(ctl.by)}</h3>
|
||
<p>Abfindungsangebot für Minderheitsaktionäre: <b class="num">${eur(ctl.floor)}</b> je Aktie – noch ${int(ctl.daysLeft)} Handelstage. So lange dient es als Untergrenze für den Kurs.</p></div>`);
|
||
}
|
||
return out.join('');
|
||
}
|
||
|
||
/** Detailansicht für Anleihen, Rohstoffe und Devisen */
|
||
function instrumentHtml(c) {
|
||
const i = c.info ?? {};
|
||
const t = ticker(c.symbol);
|
||
const unit = unitOf(t ?? c);
|
||
const head = `<p>${esc(c.desc)}</p>`;
|
||
const auction = c.lastAuction?.price ? `<dt>Letzte Auktion</dt><dd>${eur(c.lastAuction.price)} · ${int(c.lastAuction.volume)} St.</dd>` : '';
|
||
if (c.kind === 'bond') {
|
||
const cv = c.curve ?? {};
|
||
const b = c.budget ?? {};
|
||
return `${head}
|
||
<div class="grid2">
|
||
<div>
|
||
<h3 class="h4">Anleihe</h3>
|
||
<dl class="kv">
|
||
<dt>Restlaufzeit</dt><dd>${int(i.maturity)} Jahre (konstant)</dd>
|
||
<dt>${gl('Kupon')}</dt><dd>${num(i.coupon, 2)} % p. a., vierteljährlich</dd>
|
||
<dt>${gl('Rendite')}</dt><dd><b>${num(i.yield, 2)} %</b></dd>
|
||
<dt>${gl('Duration')}</dt><dd>${num(i.duration, 2)} Jahre <small class="muted">(Rendite +1 Pp. ≈ Kurs −${num(i.duration, 1)} %)</small></dd>
|
||
<dt>Stückzinsen</dt><dd>${num(i.accrued, 3)} €</dd>
|
||
<dt>Kurs ohne Stückzinsen</dt><dd>${num(i.cleanPrice, 2)} € <small class="muted">(„clean“)</small></dd>
|
||
<dt>Kurs mit Stückzinsen</dt><dd>${num(c.last, 2)} € ${esc(unit)}</dd>
|
||
<dt>Nächster Kupon</dt><dd>${i.nextCouponIn <= 0 ? 'heute' : `in ${int(i.nextCouponIn)} Handelstagen`} · ${num(i.coupon / 4, 3)} € je 100 €</dd>
|
||
<dt>Volatilität p. a.</dt><dd>${frac(c.vol, 1)}</dd>
|
||
${auction}
|
||
</dl>
|
||
</div>
|
||
<div>
|
||
<h3 class="h4">${gl('Zinskurve')}</h3>
|
||
<div class="chart-wrap mini"><canvas id="instCurve" role="img" aria-label="Zinskurve: 2 Jahre ${num(cv.y2, 2)} Prozent, 10 Jahre ${num(cv.y10, 2)} Prozent"></canvas></div>
|
||
<p class="small">2 J. <b>${num(cv.y2, 2)} %</b> · 10 J. <b>${num(cv.y10, 2)} %</b> · Abstand <b>${num((cv.spread ?? 0) * 100, 0)} Bp.</b>
|
||
${cv.inverted ? '<span class="badge-s halt">invertiert</span>' : '<span class="badge-s div">normal</span>'}</p>
|
||
<p class="muted small">${cv.inverted ? 'Kurze Laufzeiten rentieren höher als lange – klassisches Rezessionssignal.' : 'Lange Laufzeiten rentieren höher als kurze.'} Leitzins ${num(c.rate, 2)} % · langfristiges Niveau ${num(cv.longNeutral, 2)} %.</p>
|
||
</div>
|
||
</div>
|
||
<h3 class="h4">Staatshaushalt Wiborien</h3>
|
||
<div class="kpis">
|
||
<div><small>Schulden</small><b>${num(b.debt, 1)} %</b><small>des BIP</small></div>
|
||
<div><small>Defizit</small><b>${num(b.deficit, 1)} %</b><small>des BIP</small></div>
|
||
<div><small>${gl('Rating')}</small><b>${esc(b.rating ?? '–')}</b></div>
|
||
<div><small>${gl('Risikoaufschlag')}</small><b>${num(b.riskPremium, 2)} Pp.</b></div>
|
||
</div>
|
||
<p class="muted small">Hohe Schulden und Defizite treiben den Risikoaufschlag – er wächst mit der Laufzeit und drückt besonders lange Anleihen. <button type="button" class="linkish" data-act="polTab" data-tab="haushalt">Haushalt & Politik ansehen</button></p>`;
|
||
}
|
||
const fx = c.kind === 'fx';
|
||
const diff = Number.isFinite(c.foreignRate) ? c.foreignRate - c.rate : null;
|
||
return `${head}
|
||
<div class="grid2">
|
||
<div>
|
||
<h3 class="h4">Kennzahlen</h3>
|
||
<dl class="kv">
|
||
<dt>Kurs</dt><dd>${eur(t?.last ?? c.last)} ${esc(unit)}</dd>
|
||
<dt>Basiskurs</dt><dd>${eur(i.base)}</dd>
|
||
<dt>Seit Spielstart</dt><dd>${chg(i.base ? ((t?.last ?? c.last) / i.base - 1) * 100 : i.changeFromStart)}</dd>
|
||
<dt>Vortag</dt><dd>${eur(c.prevClose)}</dd>
|
||
<dt>Volatilität p. a.</dt><dd>${frac(c.vol, 0)} <small class="muted">(normal ${frac(c.baseVol, 0)})</small></dd>
|
||
${fx ? `<dt>Zins im Ausland (USA)</dt><dd>${num(c.foreignRate, 2)} %</dd><dt>Leitzins Wiborien</dt><dd>${num(c.rate, 2)} %</dd>
|
||
<dt>Zinsdifferenz</dt><dd class="${dirCls(diff)}">${diff > 0 ? '+' : diff < 0 ? '−' : '±'}${num(Math.abs(diff), 2)} Pp. <small class="muted">${diff > 0 ? '(spricht für den Dollar)' : '(spricht für den Euro)'}</small></dd>` : ''}
|
||
${auction}
|
||
</dl>
|
||
</div>
|
||
<div>
|
||
<h3 class="h4">Was den Preis treibt</h3>
|
||
<ul class="plain">${(DRIVERS[c.symbol] ?? ['Angebot und Nachfrage im Orderbuch', 'Konjunktur und Marktstimmung']).map((d) => `<li>${esc(d)}</li>`).join('')}</ul>
|
||
${fx ? '<p class="muted small">Steigt der Kurs, bekommst du für 100 $ mehr Euro – der Euro ist schwächer geworden.</p>' : ''}
|
||
</div>
|
||
</div>`;
|
||
}
|
||
|
||
function lendingHtml(c) {
|
||
const l = c.lending;
|
||
const fp = c.flowPrev;
|
||
let flow = '<p class="muted">Noch kein abgeschlossener Handelstag.</p>';
|
||
if (fp) {
|
||
const rows = [...Object.values(fp.bots), { name: 'Spieler', desc: 'Alle menschlichen Spieler zusammen', ...fp.players }];
|
||
flow = rows.map((r) => `<div class="flow-row"><span title="${esc(r.desc ?? '')}">${esc(r.name)}</span>${meter(r.pct, { label: `${r.name} Anteil am Umsatz` })}<span class="num">${frac(r.pct, 0)}</span></div>`).join('');
|
||
}
|
||
return `<div class="grid2">
|
||
<div>
|
||
<h3 class="h4">Wertpapierleihe (für ${gl('Leerverkauf', 'Leerverkäufe')})</h3>
|
||
<dl class="kv">
|
||
<dt>Leihpool</dt><dd>${int(l.pool)} St.</dd>
|
||
<dt>Verliehen</dt><dd>${int(l.used)} St.</dd>
|
||
<dt>Auslastung</dt><dd>${frac(l.util, 0)}</dd>
|
||
<dt>Leihgebühr p. a.</dt><dd>${frac(l.rate, 2)}</dd>
|
||
<dt>Status</dt><dd>${l.hardToBorrow ? `<span class="badge-s short">${gl('HTB', 'Hard to borrow')}</span>` : 'leihbar'}${l.recalled ? ` · Rückruf ${frac(l.recalled, 0)} des Pools` : ''}</dd>
|
||
<dt>Short-Position der Spieler</dt><dd>${int(c.shortInterest)} St.</dd>
|
||
</dl>
|
||
${meter(l.util, { label: 'Auslastung des Leihpools', cls: l.util > 0.9 ? 'hi' : l.util > 0.6 ? 'mid' : '' })}
|
||
</div>
|
||
<div>
|
||
<h3 class="h4">Orderfluss Vortag${fp ? ` (Handelstag ${int(fp.day)})` : ''}</h3>
|
||
<p class="muted small">Anteile am Umsatz des Vortags – absichtlich kein Echtzeitsignal.</p>
|
||
${flow}
|
||
</div>
|
||
</div>`;
|
||
}
|
||
|
||
function holdersHtml(c) {
|
||
if (!c.holders?.length) return `<p class="muted">Kein Spieler hält ${c.kind && c.kind !== 'stock' ? 'dieses Wertpapier' : 'diese Aktie'}.</p>`;
|
||
return `<table><thead><tr><th>Spieler</th><th class="num">Stück</th><th class="num">Anteil</th></tr></thead><tbody>
|
||
${c.holders.map((h) => `<tr><td>${player(h.name)}</td><td class="num">${int(h.qty)}</td><td class="num">${Number.isFinite(h.pct) ? `${num(h.pct, 4)} %` : '–'}</td></tr>`).join('')}</tbody></table>`;
|
||
}
|
||
|
||
/** Nachrichtenliste (auch für andere Ansichten) */
|
||
const TOPIC_NAMES = { oil: 'Öl', rates: 'Zinsen', inflation: 'Inflation', usd: 'Dollar', gold: 'Gold', risk: 'Krisenrisiko', tariffs: 'Zölle', labor: 'Arbeitsmarkt', growth: 'Konjunktur' };
|
||
function newsAnalysisHtml(n) {
|
||
const a = n.analysis;
|
||
if (!a) return '';
|
||
const topics = Object.entries(a.topics ?? {}).filter(([, v]) => Math.abs(v) >= 0.1);
|
||
const chips = topics.map(([k, v]) => {
|
||
// für die Börse gut oder schlecht? (Farbe) – die Pfeilrichtung zeigt das Thema selbst
|
||
const good = { labor: 1, growth: 1 }[k] ? v > 0 : { usd: 1, gold: 1 }[k] ? null : v < 0;
|
||
return `<span class="ntopic ${good === null ? '' : good ? 'up' : 'down'}" title="${esc(TOPIC_NAMES[k])} ${v > 0 ? 'steigt' : 'sinkt'} (Stärke ${Math.round(Math.abs(v) * 100)} %)"><span aria-hidden="true">${v > 0 ? '▲' : '▼'}</span> ${esc(TOPIC_NAMES[k])}</span>`;
|
||
}).join('');
|
||
const by = a.by === 'llm' ? '<span class="chip" title="Bewertet von einem Sprachmodell">KI-Analyse</span>' : '';
|
||
const follow = a.followUp ? '<span class="chip" title="Dieselbe Geschichte wurde schon gemeldet – wirkt deutlich schwächer">Folgemeldung</span>' : '';
|
||
const reasons = (a.reasons ?? []).length
|
||
? `<details class="nwhy"><summary>Warum?</summary><ul>${a.reasons.map((r) => `<li>${esc(r)}</li>`).join('')}</ul>${n.affected?.length ? `<p class="muted small">Bewegt: ${n.affected.slice(0, 12).map(esc).join(', ')}${n.affected.length > 12 ? ' …' : ''}</p>` : ''}</details>` : '';
|
||
if (!chips && !by && !follow && !reasons) return '';
|
||
return `<div class="nana">${chips}${by}${follow}${reasons}</div>`;
|
||
}
|
||
|
||
export function newsList(list, empty = 'Keine Meldungen.') {
|
||
if (!list?.length) return `<p class="muted">${esc(empty)}</p>`;
|
||
return `<ul class="news">${list.map((n) => {
|
||
const url = safeUrl(n.url);
|
||
const s = n.sentiment ?? 0;
|
||
const title = url ? `<a href="${esc(url)}" target="_blank" rel="noopener noreferrer">${esc(n.title)}</a>` : esc(n.title);
|
||
const strong = Math.abs(s) >= 0.6 && (n.analysis?.strength ?? 0) >= 0.7 && !n.analysis?.followUp;
|
||
return `<li${strong ? ' class="nstrong"' : ''}><div class="meta"><span>${esc(n.source ?? '')}</span><span>${ago(n.ts)}</span>${n.real === false ? '<span class="chip">Spielwelt</span>' : ''}${strong ? '<span class="chip gold-t">Eilmeldung</span>' : ''}${Math.abs(s) >= 0.2 ? `<span class="${dirCls(s)}">${arrow(s)} Stimmung ${s > 0 ? 'positiv' : 'negativ'}</span>` : ''}</div><div>${title}</div>${newsAnalysisHtml(n)}</li>`;
|
||
}).join('')}</ul>`;
|
||
}
|
||
|
||
// ================================================================ Orderbuch & Umsätze
|
||
function renderBook() {
|
||
const t = ticker();
|
||
const d = S.book?.depth;
|
||
if (!d) { patch($('#book'), '<p class="muted pad">Lade Orderbuch …</p>'); patch($('#tape'), ''); return; }
|
||
const asks = (d.asks ?? []).slice(0, 8).reverse();
|
||
const bids = (d.bids ?? []).slice(0, 8);
|
||
const max = Math.max(1, ...asks.map((x) => x.qty), ...bids.map((x) => x.qty));
|
||
const row = (l, s) => `<tr class="${s}"><td class="num"><button type="button" class="px-btn" data-act="bookPx" data-px="${l.price}" aria-label="Limit ${num(l.price)} übernehmen">${num(l.price)}</button></td><td class="num">${int(l.qty)}</td><td class="num muted">${int(l.count)}</td><td class="barcell"><i style="width:${(l.qty / max) * 100}%"></i></td></tr>`;
|
||
const bb = bids[0]?.price, ba = d.asks?.[0]?.price;
|
||
const ind = S.book?.indicative ?? t?.indicative;
|
||
const st = S.book?.status ?? t?.status;
|
||
const mid = ind && st !== 'continuous'
|
||
? `<tr class="mid"><td colspan="4">Auktion · indikativ <b class="num">${num(ind.price)}</b> · ${int(ind.volume)} St.${ind.surplus ? ` · Überhang ${int(ind.surplus)}` : ''}</td></tr>`
|
||
: `<tr class="mid"><td colspan="4">${bb && ba ? `Spread ${num(ba - bb)} (${num(((ba - bb) / ((ba + bb) / 2)) * 100, 2)} %)` : 'kein Spread'}</td></tr>`;
|
||
patch($('#book'), `<table class="book" aria-label="Orderbuch"><thead><tr><th class="num">Preis</th><th class="num">Stück</th><th class="num">Ord.</th><th><span class="sr">Tiefe</span></th></tr></thead><tbody>
|
||
${asks.map((l) => row(l, 'ask')).join('') || '<tr class="ask"><td colspan="4" class="muted">keine Verkaufsorders</td></tr>'}${mid}${bids.map((l) => row(l, 'bid')).join('') || '<tr class="bid"><td colspan="4" class="muted">keine Kauforders</td></tr>'}</tbody></table>`);
|
||
$('#spread').textContent = bb && ba ? `Geld ${num(bb)} · Brief ${num(ba)}` : '';
|
||
const tape = (S.book.tape ?? []).slice(0, 25).map((x) => `<tr class="${x.player ? 'me' : ''}"><td class="muted">${timeS(x.ts)}</td><td class="num ${x.side === 'buy' ? 'up' : 'down'}"><span aria-hidden="true">${x.side === 'buy' ? '▲' : '▼'}</span> ${num(x.price)}</td><td class="num">${int(x.qty)}</td><td>${x.auction ? '<span class="badge-s auction" title="Auktionsumsatz">A</span>' : ''}${x.player ? '<span class="badge-s battle" title="Spieler beteiligt">S</span>' : ''}</td></tr>`).join('');
|
||
patch($('#tape'), tape || '<tr><td class="muted pad">Noch keine Umsätze</td></tr>');
|
||
}
|
||
|
||
// ================================================================ Orderticket
|
||
function ticketHtml() {
|
||
return `<form id="ticket" class="ticket" novalidate aria-label="Orderticket">
|
||
<div class="card-h"><h2 class="h-inline">Order <span id="tSym"></span></h2>
|
||
<label class="switch" title="Blendet fortgeschrittene Orderarten aus"><input type="checkbox" id="simpleToggle"><span>Einsteiger-Modus</span></label></div>
|
||
<div class="body">
|
||
<div class="seg" id="accSeg" role="group" aria-label="Konto" hidden>
|
||
<button type="button" data-acc="main" aria-pressed="true">Hauptdepot</button><button type="button" data-acc="battle" aria-pressed="false">Battle-Depot</button><button type="button" data-acc="fund" aria-pressed="false">Clan-Fonds</button></div>
|
||
<div class="seg side" role="group" aria-label="Richtung">
|
||
<button type="button" data-side="buy" aria-pressed="true">Kaufen</button><button type="button" data-side="sell" aria-pressed="false">Verkaufen</button></div>
|
||
<div class="row2">
|
||
<div class="field"><label for="oType">Ordertyp</label><select id="oType"></select></div>
|
||
<div class="field"><label for="oQty">Stück</label><input id="oQty" type="number" inputmode="numeric" min="1" step="1" value="10"></div>
|
||
</div>
|
||
<div class="row2">
|
||
<div class="field" id="fPrice"><label for="oPrice">${gl('Limit')} (€)</label><input id="oPrice" type="number" inputmode="decimal" step="0.01" min="0.01"></div>
|
||
<div class="field" id="fTrigger" hidden><label for="oTrigger">Auslösekurs (€)</label><input id="oTrigger" type="number" inputmode="decimal" step="0.01" min="0.01"></div>
|
||
<div class="field" id="fTrail" hidden><label for="oTrail">Abstand (%)</label><input id="oTrail" type="number" inputmode="decimal" step="0.5" min="0.5" max="30" value="5"></div>
|
||
</div>
|
||
<div class="qty-quick" role="group" aria-label="Schnellauswahl Menge">
|
||
<button type="button" class="btn ghost small" data-qf="0.1">10 %</button><button type="button" class="btn ghost small" data-qf="0.25">25 %</button><button type="button" class="btn ghost small" data-qf="0.5">50 %</button><button type="button" class="btn ghost small" data-qf="1">Max</button>
|
||
</div>
|
||
<details id="adv" class="adv"><summary>Erweitert: Gültigkeit, Iceberg, Bracket, OCO</summary>
|
||
<div class="row2">
|
||
<div class="field" id="fTif"><label for="oTif">${gl('TIF', 'Gültigkeit')}</label><select id="oTif">${Object.entries(TIF).map(([k, v]) => `<option value="${k}">${esc(v)}</option>`).join('')}</select></div>
|
||
<div class="field" id="fDate" hidden><label for="oDate">Gültig bis</label><input id="oDate" type="date"></div>
|
||
<div class="field" id="fPeak"><label for="oPeak">${gl('Iceberg')}: sichtbare Stück</label><input id="oPeak" type="number" min="1" step="1" placeholder="aus"></div>
|
||
</div>
|
||
<div id="fBracket">
|
||
<label class="check"><input type="checkbox" id="oBracket"> ${gl('Bracket')}: Stop & Take-Profit anhängen</label>
|
||
<div class="row3" id="bracketF" hidden>
|
||
<div class="field"><label for="oBKind">Absicherung</label><select id="oBKind"><option value="stop">Stop-Loss</option><option value="trailing">Trailing-Stop</option></select></div>
|
||
<div class="field"><label for="oBStop" id="oBStopLbl">Stop (€)</label><input id="oBStop" type="number" step="0.01" min="0"></div>
|
||
<div class="field"><label for="oBTp">Take-Profit (€)</label><input id="oBTp" type="number" step="0.01" min="0"></div>
|
||
</div>
|
||
</div>
|
||
<div id="fOco" hidden>
|
||
<label class="check"><input type="checkbox" id="oOco"> ${gl('OCO')}: Gegenstück anlegen</label>
|
||
<div class="field" id="ocoF" hidden><label for="oOcoTrig" id="oOcoLbl">Take-Profit (€)</label><input id="oOcoTrig" type="number" step="0.01" min="0"></div>
|
||
</div>
|
||
</details>
|
||
<div class="hint" id="oHint" aria-live="polite"></div>
|
||
<dl class="est">
|
||
<div><dt>Kurswert ca.</dt><dd id="eNotional">–</dd></div>
|
||
<div><dt>Gebühren ca. <span class="gl-i" tabindex="0" data-gl="Maker/Taker" aria-label="Erklärung Gebühren">ⓘ</span></dt><dd id="eFee">–</dd></div>
|
||
<div class="tot"><dt id="eTotalLbl">Gesamt ca.</dt><dd id="eTotal">–</dd></div>
|
||
<div><dt id="eAvailLbl">${gl('Kaufkraft')}</dt><dd id="eAvail">–</dd></div>
|
||
</dl>
|
||
<button type="submit" class="btn buy wide" id="oSubmit">Kaufen</button>
|
||
<p class="muted small" id="oLogin" hidden>Zum Handeln bitte <button type="button" class="linkish" data-act="login">anmelden</button>.</p>
|
||
</div></form>`;
|
||
}
|
||
|
||
const v = (id) => $(`#${id}`);
|
||
const val = (id) => { const x = Number(v(id).value); return Number.isFinite(x) && v(id).value !== '' ? x : null; };
|
||
|
||
function typeOptions() {
|
||
const sel = v('oType');
|
||
const cur = sel.value || 'limit';
|
||
sel.innerHTML = Object.entries(ORDER_TYPES).filter(([, t]) => !S.simple || t.simple).map(([k, t]) => `<option value="${k}">${esc(t.label)}</option>`).join('');
|
||
sel.value = [...sel.options].some((o) => o.value === cur) ? cur : 'limit';
|
||
}
|
||
|
||
function setSide(s) {
|
||
side = s;
|
||
for (const b of $$('#ticket [data-side]')) b.setAttribute('aria-pressed', String(b.dataset.side === s));
|
||
$('#ticket .seg.side').dataset.on = s;
|
||
syncTicketDefaults(false);
|
||
updateTicket();
|
||
}
|
||
|
||
/** Sinnvolle Vorbelegung von Limit/Trigger beim Symbol- oder Seitenwechsel */
|
||
function syncTicketDefaults(force) {
|
||
const t = ticker();
|
||
if (!t || !v('oPrice')) return;
|
||
const ref = side === 'buy' ? (t.ask ?? t.last) : (t.bid ?? t.last);
|
||
if (force || !v('oPrice').value) v('oPrice').value = ref.toFixed(2);
|
||
const type = v('oType').value;
|
||
const below = (side === 'sell') === (type !== 'takeprofit');
|
||
if (force || !v('oTrigger').value || v('oTrigger')._auto) {
|
||
v('oTrigger').value = (t.last * (below ? 0.95 : 1.05)).toFixed(2);
|
||
v('oTrigger')._auto = true;
|
||
}
|
||
$('#tSym').textContent = t.symbol;
|
||
}
|
||
|
||
function position(sym = S.symbol) {
|
||
const p = activePortfolio();
|
||
return p?.positions?.find((x) => x.symbol === sym)?.qty ?? 0;
|
||
}
|
||
|
||
/** Schätzpreis je Stück für die Kostenschätzung */
|
||
function estPrice(type) {
|
||
const t = ticker();
|
||
if (!t) return null;
|
||
const auction = t.status !== 'continuous';
|
||
const mkt = auction ? (t.indicative?.price ?? t.last) : side === 'buy' ? (t.ask ?? t.last) : (t.bid ?? t.last);
|
||
if (type === 'limit' || type === 'stoplimit') return val('oPrice');
|
||
if (type === 'market') return mkt;
|
||
if (type === 'trailing') { const tr = (val('oTrail') ?? 5) / 100; return t.last * (side === 'sell' ? 1 - tr : 1 + tr); }
|
||
return val('oTrigger');
|
||
}
|
||
|
||
function updateTicket() {
|
||
const form = v('ticket');
|
||
if (!form) return;
|
||
const t = ticker();
|
||
const type = v('oType').value;
|
||
const cond = COND.has(type);
|
||
v('fPrice').hidden = !(type === 'limit' || type === 'stoplimit');
|
||
v('fTrigger').hidden = !(type === 'stop' || type === 'stoplimit' || type === 'takeprofit');
|
||
v('fTrail').hidden = type !== 'trailing';
|
||
$('#fTrigger label').textContent = type === 'takeprofit' ? 'Zielkurs (€)' : 'Auslösekurs (€)';
|
||
v('adv').hidden = S.simple;
|
||
v('fTif').hidden = cond;
|
||
v('fDate').hidden = cond || v('oTif').value !== 'gtd';
|
||
v('fPeak').hidden = type !== 'limit';
|
||
v('fBracket').hidden = cond;
|
||
v('bracketF').hidden = !v('oBracket').checked;
|
||
v('oBStopLbl').textContent = v('oBKind').value === 'trailing' ? 'Abstand (%)' : 'Stop (€)';
|
||
v('fOco').hidden = !(type === 'stop' || type === 'takeprofit');
|
||
v('ocoF').hidden = !v('oOco').checked;
|
||
v('oOcoLbl').textContent = type === 'takeprofit' ? 'Stop-Loss (€)' : 'Take-Profit (€)';
|
||
v('simpleToggle').checked = S.simple;
|
||
const qLbl = $('label[for="oQty"]');
|
||
const qTxt = kindOf(t) === 'bond' ? 'Stück (à 100 € nominal)' : 'Stück';
|
||
if (qLbl && qLbl.textContent !== qTxt) qLbl.textContent = qTxt;
|
||
|
||
// Konto-Umschalter
|
||
const hasBattle = !!S.battlePortfolio, hasFund = !!S.fundPortfolio;
|
||
v('accSeg').hidden = !hasBattle && !hasFund;
|
||
if (!hasBattle && S.account === 'battle') S.account = 'main';
|
||
if (!hasFund && S.account === 'fund') S.account = 'main';
|
||
for (const b of $$('#accSeg [data-acc]')) {
|
||
b.hidden = (b.dataset.acc === 'battle' && !hasBattle) || (b.dataset.acc === 'fund' && !hasFund);
|
||
b.setAttribute('aria-pressed', String(b.dataset.acc === S.account));
|
||
}
|
||
|
||
const qty = Math.floor(val('oQty') ?? 0);
|
||
const px = estPrice(type);
|
||
const fees = S.info?.fees ?? { taker: 0.0005, maker: 0.0002, fixed: 0.9 };
|
||
const p = activePortfolio();
|
||
const hints = [];
|
||
let notional = null, fee = null;
|
||
if (qty > 0 && px > 0) {
|
||
notional = qty * px;
|
||
// Maker nur, wenn eine Limit-Order im fortlaufenden Handel nicht sofort ausführbar ist (Auktionen zählen als Taker)
|
||
const lim = val('oPrice');
|
||
const passive = type === 'limit' && lim > 0 && t?.status === 'continuous'
|
||
&& (side === 'buy' ? !(t.ask > 0 && lim >= t.ask) : !(t.bid > 0 && lim <= t.bid));
|
||
fee = notional * (passive ? fees.maker : fees.taker) + fees.fixed;
|
||
v('eFee').textContent = `${eur(fee)} (${passive ? 'Maker – liegt im Buch' : 'Taker'})`;
|
||
} else v('eFee').textContent = '–';
|
||
v('eNotional').textContent = notional ? eur(notional) : '–';
|
||
v('eTotalLbl').textContent = side === 'buy' ? 'Gesamt ca.' : 'Erlös ca.';
|
||
v('eTotal').textContent = notional ? eur(side === 'buy' ? notional + fee : notional - fee) : '–';
|
||
const pos = position();
|
||
if (side === 'buy') {
|
||
v('eAvailLbl').innerHTML = gl('Kaufkraft');
|
||
v('eAvail').textContent = p ? eur(p.available) : '–';
|
||
if (p && notional && pos >= 0 && notional + fee > p.available) hints.push('<span class="warn">Kaufkraft reicht voraussichtlich nicht.</span>');
|
||
if (pos < 0) hints.push(`Kauf deckt bis zu ${int(-pos)} St. deiner Short-Position ein.`);
|
||
} else {
|
||
v('eAvailLbl').textContent = 'Bestand';
|
||
v('eAvail').textContent = p ? `${int(pos)} St.` : '–';
|
||
const shortQty = Math.max(0, qty - Math.max(0, pos));
|
||
if (shortQty > 0 && qty > 0) {
|
||
hints.push(`<span class="warn">${gl('Leerverkauf')} von ${int(shortQty)} St.</span> Leihzins ${frac(t?.borrowRate, 1)} p. a.${t?.htb ? ' – <b>HTB</b>, Leihe knapp' : ''}. Short-Kapazität ${eur(p?.shortCapacity)}.`);
|
||
}
|
||
}
|
||
if (t && (type === 'limit' || type === 'stoplimit') && px && Math.abs(px / t.last - 1) > 0.2) hints.push('<span class="warn">Limit weicht mehr als 20 % vom Kurs ab – wird abgelehnt.</span>');
|
||
if (t && t.status !== 'continuous' && !cond) hints.push(`Orders werden derzeit <b>gesammelt (Auktion)</b>${['ioc', 'fok'].includes(v('oTif').value) ? ' – IOC/FOK sind jetzt nicht möglich' : ''}.`);
|
||
if (cond && t && t.status !== 'continuous') hints.push('Bedingte Order wird <b>vorgemerkt</b> – Auslöser werden erst im fortlaufenden Handel geprüft, nicht in der Auktion.');
|
||
if (cond) hints.push(`Bedingte Order: wird serverseitig überwacht und im fortlaufenden Handel ausgelöst${type === 'trailing' ? '' : ` (Auslöser muss ${(side === 'sell') === (type !== 'takeprofit') ? 'unter' : 'über'} dem Kurs liegen)`}.`);
|
||
if (S.account === 'battle') hints.push('Order für das <b>Battle-Depot</b>.');
|
||
if (S.account === 'fund') hints.push(`Order für den <b>Clan-Fonds</b> (Anlegergeld, nur Long) · NAV ${num(S.fundPortfolio?.nav)} €.`);
|
||
const rules = S.account === 'battle' ? S.battlePortfolio?.rules : null;
|
||
if (rules?.symbols && !rules.symbols.includes(S.symbol)) hints.push(`<span class="warn">Im Battle nur ${esc(rules.symbols.join(', '))} handelbar.</span>`);
|
||
if (p?.locked) hints.push('<span class="warn">Depot gesperrt: nur Positionsabbau möglich.</span>');
|
||
const kind = kindOf(t);
|
||
if (t && kind !== 'stock') hints.push(`Kurs in € ${esc(unitOf(t))}${kind === 'bond' && qty > 0 ? ` – ${int(qty)} St. = ${eur(qty * 100, 0)} Nennwert` : ''}.`);
|
||
const office = S.government?.me?.office ?? S.profile?.office;
|
||
if (t && kind === 'stock' && office?.sectors?.includes(t.sector) && ((side === 'buy' && pos >= 0) || (side === 'sell' && pos <= 0))) {
|
||
hints.push(`<span class="warn"><b>Interessenkonflikt:</b> Als ${esc(office.ministry)} darfst du ${esc(S.info?.sectors?.[t.sector]?.name ?? t.sector)}-Aktien nur abbauen – diese Order würde abgelehnt.</span>`);
|
||
}
|
||
patch(v('oHint'), hints.join('<br>'));
|
||
|
||
const btn = v('oSubmit');
|
||
btn.className = `btn wide ${side === 'buy' ? 'buy' : 'sell'}`;
|
||
const verb = side === 'buy' ? (pos < 0 ? 'Kaufen / Eindecken' : 'Kaufen') : (pos > 0 ? 'Verkaufen' : 'Leerverkaufen');
|
||
btn.textContent = `${verb}${qty > 0 ? ` ${int(qty)} × ${S.symbol}` : ''}`;
|
||
btn.disabled = !loggedIn();
|
||
v('oLogin').hidden = loggedIn();
|
||
}
|
||
|
||
function buildOrder() {
|
||
const type = v('oType').value;
|
||
const qty = Math.floor(val('oQty') ?? 0);
|
||
if (!(qty >= 1)) throw new Error('Bitte eine Stückzahl ≥ 1 eingeben');
|
||
const o = { symbol: S.symbol, side, orderType: type, qty, account: S.account };
|
||
if (type === 'limit' || type === 'stoplimit') { o.price = val('oPrice'); if (!(o.price > 0)) throw new Error('Bitte ein Limit eingeben'); }
|
||
if (type === 'stop' || type === 'stoplimit' || type === 'takeprofit') { o.trigger = val('oTrigger'); if (!(o.trigger > 0)) throw new Error('Bitte einen Auslösekurs eingeben'); }
|
||
if (type === 'trailing') o.trailPct = val('oTrail') ?? 5;
|
||
if (!S.simple) {
|
||
if (!COND.has(type)) {
|
||
o.tif = v('oTif').value;
|
||
if (o.tif === 'gtd') { o.expireAt = v('oDate').value; if (!o.expireAt) throw new Error('Bitte ein Datum für „Gültig bis“ wählen'); }
|
||
if (type === 'limit' && val('oPeak')) o.peak = Math.floor(val('oPeak'));
|
||
if (v('oBracket').checked) {
|
||
const b = {};
|
||
if (v('oBKind').value === 'trailing') { if (val('oBStop')) b.trailPct = val('oBStop'); } else if (val('oBStop')) b.stopTrigger = val('oBStop');
|
||
if (val('oBTp')) b.tpTrigger = val('oBTp');
|
||
if (!Object.keys(b).length) throw new Error('Bracket: Stop und/oder Take-Profit angeben');
|
||
o.bracket = b;
|
||
}
|
||
} else if ((type === 'stop' || type === 'takeprofit') && v('oOco').checked) {
|
||
const tr = val('oOcoTrig');
|
||
if (!(tr > 0)) throw new Error('OCO: zweiten Auslösekurs angeben');
|
||
o.oco = { trigger: tr };
|
||
}
|
||
}
|
||
return o;
|
||
}
|
||
|
||
function describe(o) {
|
||
const t = ticker();
|
||
const typ = ORDER_TYPES[o.orderType].label;
|
||
const parts = [`${o.side === 'buy' ? 'Kauf' : 'Verkauf'} ${int(o.qty)} × ${o.symbol}`, typ];
|
||
if (o.price) parts.push(`Limit ${eur(o.price)}`);
|
||
if (o.trigger) parts.push(`Auslöser ${eur(o.trigger)}`);
|
||
if (o.trailPct) parts.push(`Abstand ${num(o.trailPct, 1)} %`);
|
||
if (o.tif && o.tif !== 'day') parts.push(TIF[o.tif].split(' –')[0]);
|
||
if (o.peak) parts.push(`Iceberg ${int(o.peak)}`);
|
||
if (o.bracket) parts.push('mit Bracket');
|
||
if (o.oco) parts.push(`OCO ${eur(o.oco.trigger)}`);
|
||
if (o.account === 'battle') parts.push('Battle-Depot');
|
||
if (o.account === 'fund') parts.push('Clan-Fonds');
|
||
return parts.join(' · ') + (t && t.status !== 'continuous' && !COND.has(o.orderType) ? ' · wird für die Auktion gesammelt' : t && t.status !== 'continuous' ? ' · vorgemerkt bis zum fortlaufenden Handel' : '');
|
||
}
|
||
|
||
async function submitOrder(e) {
|
||
e?.preventDefault();
|
||
if (!loggedIn()) { navigate('login'); return; }
|
||
let o;
|
||
try { o = buildOrder(); } catch (err) { toast(err.message, 'err'); return; }
|
||
const p = activePortfolio();
|
||
const px = estPrice(o.orderType) ?? ticker()?.last ?? 0;
|
||
const notional = o.qty * px;
|
||
const pos = position();
|
||
const shortQty = o.side === 'sell' ? Math.max(0, o.qty - Math.max(0, pos)) : 0;
|
||
const large = p && notional > Math.max(1, p.equity) * 0.25;
|
||
if (o.side === 'sell' || large) {
|
||
const lines = [`<p>${esc(describe(o))}</p>`, `<p>Kurswert ca. <b>${eur(notional)}</b></p>`];
|
||
if (shortQty > 0) lines.push(`<p class="warn">Das ist ein <b>Leerverkauf</b> über ${int(shortQty)} Stück. Steigt der Kurs, ist der Verlust nach oben offen; es fallen Leihgebühren an (${frac(ticker()?.borrowRate, 1)} p. a.).</p>`);
|
||
else if (o.side === 'sell') lines.push(`<p>Du verkaufst ${int(o.qty)} von ${int(pos)} Stück.</p>`);
|
||
if (large) lines.push(`<p class="warn">Große Order: rund ${num((notional / Math.max(1, p.equity)) * 100, 0)} % deines Depotwerts.</p>`);
|
||
const ok = await ask({ title: o.side === 'sell' ? (shortQty > 0 ? 'Leerverkauf bestätigen' : 'Verkauf bestätigen') : 'Große Order bestätigen', html: lines.join(''), ok: 'Order senden', danger: o.side === 'sell' });
|
||
if (!ok) return;
|
||
}
|
||
const btn = v('oSubmit');
|
||
btn.disabled = true;
|
||
try {
|
||
const r = await request('order', o);
|
||
const ord = r.order ?? {};
|
||
if (COND.has(o.orderType)) toast(`${ORDER_TYPES[o.orderType].label} angelegt${ord.trigger ? ` – Auslöser ${eur(ord.trigger)}` : ''}${ord.legs > 1 ? ' (OCO)' : ''}.`, 'ok', { title: 'Bedingte Order aktiv' });
|
||
else if (ticker()?.status !== 'continuous' || S.market?.phase !== 'continuous') toast(`${describe(o)}.`, 'info', { title: 'Order gesammelt (Auktion)' });
|
||
else if (ord.status === 'filled') toast(`${o.side === 'buy' ? 'Gekauft' : 'Verkauft'}: ${int(ord.filled)} × ${o.symbol}`, 'ok', { title: 'Order ausgeführt' });
|
||
else if (ord.status === 'cancelled') toast(ord.filled ? `Teilweise ausgeführt (${int(ord.filled)} St.), Rest gestrichen.` : 'Nicht ausgeführt und gestrichen (IOC/FOK oder Preiskorridor).', 'warn', { title: 'Order beendet' });
|
||
else toast(`Order #${ord.id} liegt im Buch${ord.filled ? ` (${int(ord.filled)} St. ausgeführt)` : ''}.`, 'ok', { title: 'Order angenommen' });
|
||
} catch (err) {
|
||
const coi = /Interessenkonflikt/.test(err.message);
|
||
toast(err.message, 'err', { title: coi ? 'Interessenkonflikt – Order abgelehnt' : 'Order abgelehnt', ms: coi ? 10000 : undefined });
|
||
} finally { btn.disabled = !loggedIn(); }
|
||
}
|
||
|
||
/** Ticket von außen befüllen (z. B. „Position schließen“ im Depot) */
|
||
export function prefill({ symbol, side: sd, qty, type, price, account }) {
|
||
if (account) S.account = account;
|
||
if (symbol) selectSymbol(symbol);
|
||
if (type) { if (S.simple && !ORDER_TYPES[type]?.simple) { S.simple = false; store.set('simple', false); typeOptions(); } v('oType').value = type; }
|
||
if (qty) v('oQty').value = String(qty);
|
||
if (price) v('oPrice').value = Number(price).toFixed(2);
|
||
setSide(sd ?? side);
|
||
navigate('handeln');
|
||
setTimeout(() => { v('ticket')?.scrollIntoView({ block: 'nearest', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' }); v('oQty')?.focus(); }, 50);
|
||
}
|
||
|
||
function quickQty(f) {
|
||
const t = ticker();
|
||
const p = activePortfolio();
|
||
if (!t || !p) return;
|
||
const pos = position();
|
||
let q;
|
||
if (side === 'sell' && pos > 0) q = Math.floor(pos * f);
|
||
else {
|
||
const px = estPrice(v('oType').value) || t.last;
|
||
const fees = S.info?.fees ?? { taker: 0.0005, fixed: 0.9 };
|
||
q = Math.floor(((side === 'buy' ? p.available : p.shortCapacity) * f - fees.fixed) / (px * (1 + fees.taker) * (side === 'buy' ? 1.02 : 1)));
|
||
}
|
||
v('oQty').value = String(Math.max(1, q));
|
||
updateTicket();
|
||
}
|
||
|
||
async function tender(btn) {
|
||
const sym = btn.dataset.sym;
|
||
const qty = btn.dataset.zero ? 0 : Math.floor(Number($('#tenderQty')?.value ?? 0));
|
||
if (!Number.isFinite(qty) || qty < 0) { toast('Bitte eine gültige Stückzahl eingeben', 'err'); return; }
|
||
const o = S.company?.corporate?.offer;
|
||
if (qty > 0 && o) {
|
||
const ok = await ask({ title: 'Aktien andienen?', html: `<p>${int(qty)} × ${esc(sym)} zum Angebotspreis von <b>${eur(o.price)}</b> (zusammen ${eur(qty * o.price)}) andienen.</p><p class="muted small">Gelingt die Übernahme (Erfolgschance ${frac(o.probability, 0)}), werden die Aktien in ${int(Math.max(0, o.daysLeft))} Handelstag(en) ausgebucht. Bis dahin kannst du die Andienung ändern oder zurückziehen.</p>`, ok: 'Andienen' });
|
||
if (!ok) return;
|
||
}
|
||
btn.disabled = true;
|
||
try {
|
||
const r = await request('tender', { symbol: sym, qty });
|
||
toast(qty ? `${int(r.offer?.myTender ?? qty)} × ${sym} angedient.` : `Andienung für ${sym} zurückgezogen.`, 'ok', { title: 'Übernahmeangebot' });
|
||
await loadCompany();
|
||
} catch (err) { toast(err.message, 'err'); } finally { btn.disabled = false; }
|
||
}
|
||
|
||
function updateSticky() {
|
||
const t = ticker();
|
||
if (!t) return;
|
||
$('#stBuy').textContent = t.ask ? num(t.ask) : num(t.last);
|
||
$('#stSell').textContent = t.bid ? num(t.bid) : num(t.last);
|
||
}
|
||
|
||
// ================================================================ Init
|
||
export function initTrade(nav) {
|
||
navigate = nav;
|
||
$('#ticketCard').innerHTML = ticketHtml();
|
||
typeOptions();
|
||
chart = new CandleChart($('#chart'));
|
||
const form = v('ticket');
|
||
form.addEventListener('submit', submitOrder);
|
||
form.addEventListener('input', (e) => { if (e.target.id === 'oTrigger') e.target._auto = false; updateTicket(); });
|
||
form.addEventListener('change', (e) => {
|
||
if (e.target.id === 'simpleToggle') { S.simple = e.target.checked; store.set('simple', S.simple); typeOptions(); }
|
||
if (e.target.id === 'oType') { syncTicketDefaults(false); if (v('oTrigger')._auto) syncTicketDefaults(false); }
|
||
updateTicket();
|
||
});
|
||
form.addEventListener('click', (e) => {
|
||
const sd = e.target.closest('[data-side]');
|
||
if (sd) { setSide(sd.dataset.side); return; }
|
||
const acc = e.target.closest('[data-acc]');
|
||
if (acc) { S.account = acc.dataset.acc; changed('account'); return; }
|
||
const qf = e.target.closest('[data-qf]');
|
||
if (qf) quickQty(Number(qf.dataset.qf));
|
||
});
|
||
$('#sTabs').addEventListener('click', (e) => {
|
||
const b = e.target.closest('[data-stab]');
|
||
if (!b) return;
|
||
stab = b.dataset.stab;
|
||
if (stab !== 'comments' && !S.company) loadCompany();
|
||
renderStabs();
|
||
});
|
||
$('#sTabs').addEventListener('keydown', (e) => {
|
||
if (!['ArrowLeft', 'ArrowRight'].includes(e.key)) return;
|
||
const tabs = $$('#sTabs [data-stab]');
|
||
const i = tabs.indexOf(document.activeElement);
|
||
if (i < 0) return;
|
||
const n = tabs[(i + (e.key === 'ArrowRight' ? 1 : tabs.length - 1)) % tabs.length];
|
||
n.focus(); n.click();
|
||
});
|
||
$('#mlist').addEventListener('click', (e) => {
|
||
const tr = e.target.closest('tr[data-sym]');
|
||
if (tr && !e.target.closest('[data-gl]')) selectSymbol(tr.dataset.sym, { go: true });
|
||
});
|
||
document.addEventListener('click', (e) => {
|
||
const a = e.target.closest('[data-act]');
|
||
if (!a) return;
|
||
const act = a.dataset.act;
|
||
if (act === 'mgrp') {
|
||
const g = a.dataset.g;
|
||
if (groupClosed.has(g)) groupClosed.delete(g); else groupClosed.add(g);
|
||
store.set('mgrpClosed', [...groupClosed]);
|
||
renderMarketList();
|
||
return;
|
||
}
|
||
if (act === 'tender') { tender(a); return; }
|
||
if (act === 'bookPx') { if (v('oType').value !== 'limit' && v('oType').value !== 'stoplimit') v('oType').value = 'limit'; v('oPrice').value = Number(a.dataset.px).toFixed(2); updateTicket(); }
|
||
else if (act === 'chartMode') {
|
||
S.chartMode = a.dataset.mode;
|
||
for (const b of $$('[data-act="chartMode"]')) b.setAttribute('aria-pressed', String(b.dataset.mode === S.chartMode));
|
||
if (S.chartMode === 'daily' && !S.company) loadCompany();
|
||
drawChart();
|
||
} else if (act === 'quickSide') {
|
||
setSide(a.dataset.side);
|
||
v('ticket').scrollIntoView({ block: 'start', behavior: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth' });
|
||
v('oQty').focus({ preventScroll: true });
|
||
}
|
||
});
|
||
|
||
let lastDay = null;
|
||
sub('market', () => { if (S.market?.day !== lastDay) { if (lastDay !== null) loadCompany(); lastDay = S.market?.day; } });
|
||
sub('news', () => {
|
||
const n = S.news[0];
|
||
if (n && (n.symbol === S.symbol || n.affected?.includes(S.symbol)) && n.id !== lastNewsId) { lastNewsId = n.id; loadCompany(); }
|
||
});
|
||
sub('market', () => { if (stab === 'company' && S.company?.kind && S.company.kind !== 'stock' && S.company.symbol === S.symbol) renderStabs(); });
|
||
sub('market', () => { renderMarketList(); renderStock(); updateTicket(); if (S.chartMode === 'intraday') drawChart(); if (!v('oPrice').value) syncTicketDefaults(false); });
|
||
sub('portfolio account profile government', () => { updateTicket(); renderMarketList(); });
|
||
syncTicketDefaults(true);
|
||
setSide('buy');
|
||
}
|
||
|
||
export const tradeHooks = { onBook, renderMarketList, renderStock, renderBook, drawChart, renderStabs, updateTicket };
|