Files
wibosim/server/public/js/candlechart.js
T

532 lines
28 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.
// Interaktiver Kurschart (Canvas, ohne Bibliotheken): Kerzen, Linie oder Fläche, Volumen, Fadenkreuz mit Infozeile,
// Zoom und Verschieben (chartzoom.js), gleitende Durchschnitte und Bollinger-Bänder, eigene Trades und Order-Linien.
// Gezeichnet wird nur der sichtbare Ausschnitt, gebündelt in einem requestAnimationFrame.
import { num, time, date, compact } from './util.js';
import { ZoomCtl } from './chartzoom.js';
import {
visibleRange, indexAt, xOf, aggregate, bucketSize, priceRange, scaleRange, niceStep, stepDecimals,
timeTicks, tickEvery, smaInto, bollingerInto, recalcFrom, headKeys, droppedFront, isFull,
} from './chartview.js';
// ---------------------------------------------------------------- Farben (aus CSS-Variablen, je Farbschema einmal aufgelöst)
let colCache = null;
const COLS = {
up: ['--up', '#22c55e'], down: ['--down', '#ef4444'], text: ['--muted', '#8b97ad'], line: ['--line', '#222c42'],
accent: ['--accent', '#3b82f6'], gold: ['--gold', '#f5b942'], fg: ['--text', '#dfe6f3'], bg: ['--panel', '#121826'],
onSignal: ['--on-signal', '#0b0f17'], tip: ['--tip-bg', '#0d1422'],
grid: ['--cc-grid', 'rgba(127,127,127,.14)'], ma1: ['--cc-ma1', '#3b82f6'], ma2: ['--cc-ma2', '#f5b942'], bb: ['--cc-bb', '#a78bfa'],
crossBg: ['--cc-cross-bg', '#dfe6f3'], crossFg: ['--cc-cross-fg', '#121826'],
};
function colors() {
if (colCache) return colCache;
const probe = document.createElement('span');
probe.style.display = 'none';
document.body.appendChild(probe);
const out = {};
for (const [k, [v, fb]] of Object.entries(COLS)) {
probe.style.color = fb;
probe.style.color = `var(${v}, ${fb})`;
out[k] = getComputedStyle(probe).color || fb;
}
probe.remove();
return (colCache = out);
}
/** Farbe mit Deckkraft (rgb(), rgba(), color(srgb …), #rrggbb) */
function alpha(c, a) {
const s = String(c).trim();
let m = /^rgba?\(([^)]+)\)$/i.exec(s);
if (m) { const p = m[1].split(/[\s,/]+/).filter(Boolean).slice(0, 3); return `rgba(${p.join(',')},${a})`; }
m = /^color\((\S+)\s+([^/)]+?)(?:\s*\/\s*[^)]+)?\)$/i.exec(s);
if (m) return `color(${m[1]} ${m[2].trim()} / ${a})`;
m = /^#([0-9a-f]{6})$/i.exec(s);
if (m) return `rgba(${[0, 2, 4].map((i) => parseInt(m[1].slice(i, i + 2), 16)).join(',')},${a})`;
return s;
}
const charts = new Set();
if (typeof document !== 'undefined') {
document.addEventListener('wibo:theme', () => {
colCache = null;
for (const ch of charts) { if (!ch.c.isConnected) continue; ch.redraw(); }
});
}
const FONT = '11px system-ui, -apple-system, "Segoe UI", Roboto, sans-serif';
const MONO = 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace';
function wrapText(ctx, text, maxW) {
const lines = [];
let cur = '';
for (const w of String(text).split(/\s+/)) {
const t = cur ? `${cur} ${w}` : w;
if (cur && ctx.measureText(t).width > maxW) { lines.push(cur); cur = w; } else cur = t;
}
if (cur) lines.push(cur);
return lines;
}
function roundRect(ctx, x, y, w, h, r) {
ctx.beginPath();
if (ctx.roundRect) ctx.roundRect(x, y, w, h, r); else ctx.rect(x, y, w, h);
}
/**
* Kurschart. set(bars, opt) mit bars [{t?|ts?|day?, o, h, l, c, v}] und
* opt: {style: 'candle'|'line'|'area', fit (Standardansicht: alles), viewKey (andere Daten → Ausschnitt zurücksetzen),
* last, indicative, prevClose (gestrichelt), base (Zeitraumbeginn → Farbe), xLabel(b), tipTitle(b), empty,
* daily (ohne Kursmarke, Beschriftung b.label), ind {ma20, ma50, bb},
* marks [{i (Index in bars), buy {qty, px}|null, sell {qty, px}|null, tip [Text]}] eigene Trades (chartmarks.js),
* levels [{p, kind: 'stop'|'tp'|'limit', side, label, tip}] aktive eigene Orders als Linien}
*/
export class CandleChart {
/** @param {HTMLCanvasElement} canvas */
constructor(canvas) {
this.c = canvas;
this.ctx = canvas.getContext('2d');
this.bars = []; this.opt = {};
this.key = null; this.n0 = 0; this.head = [];
this.hoverPt = null;
this.yk = 1; // senkrechte Streckung (Ziehen an der Preisachse)
this.raf = 0;
this.layout = { w: 100, axis: 60 };
this.ind = { ma20: { a: [], from: 0 }, ma50: { a: [], from: 0 }, bb: { a: { mid: [], up: [], lo: [] }, from: 0 } };
charts.add(this);
canvas.ccChart = this; // für Prüfungen im Browser (Ausschnitt lesen)
this.zoom = new ZoomCtl(canvas, {
count: () => this.bars.length,
plot: () => this.layout,
redraw: () => this.redraw(),
hover: (p) => { this.hoverPt = p; this.redraw(); },
yScale: (f) => { this.yk = Math.max(0.25, Math.min(8, this.yk * f)); this.redraw(); },
yReset: () => { this.yk = 1; this.redraw(); },
announce: (msg) => this.announce(msg),
});
// Tastatur und Screenreader: fokussierbar, Bedienhinweis und Ansage nach Tastaturbedienung
const wrap = canvas.parentElement;
if (!canvas.hasAttribute('tabindex')) canvas.tabIndex = 0;
canvas.setAttribute('aria-roledescription', 'Kurschart');
if (wrap && !wrap.querySelector('.cc-help')) {
const id = `${canvas.id || 'cc'}Help`;
wrap.insertAdjacentHTML('beforeend', `<p class="sr cc-help" id="${id}">Pfeiltasten links und rechts verschieben den Ausschnitt, Plus und Minus zoomen, 0 zeigt den ganzen Zeitraum, Pos1 und Ende springen zum Anfang bzw. zu den neuesten Kursen.</p><p class="sr cc-live" aria-live="polite"></p>
<div class="cc-ctl" role="group" aria-label="Zoom">
<button type="button" class="cc-b" data-cc="out" aria-label="Verkleinern" title="Verkleinern (Minus)"><svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M6 12h12"/></svg></button>
<button type="button" class="cc-b" data-cc="in" aria-label="Vergrößern" title="Vergrößern (Plus)"><svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M6 12h12M12 6v12"/></svg></button>
<button type="button" class="cc-b cc-reset" data-cc="reset" title="Ganzen Zeitraum zeigen (0 oder Doppeltippen)">Alles</button>
</div>`);
canvas.setAttribute('aria-describedby', id);
wrap.querySelector('.cc-ctl').addEventListener('click', (e) => {
const b = e.target.closest('[data-cc]');
if (!b) return;
const z = this.zoom, n = this.bars.length, v = z.get();
if (b.dataset.cc === 'reset') z.reset();
else z.set({ ...v, ...zoomed(v, b.dataset.cc === 'in' ? 0.7 : 1 / 0.7, n) });
});
}
this.ro = new ResizeObserver(() => this.redraw());
this.ro.observe(wrap ?? canvas);
}
/** @param {object[]} bars @param {object} opt */
set(bars, opt = {}) {
bars = bars ?? [];
const key = opt.viewKey ?? '';
const n = bars.length;
const fit = !!(opt.fit || opt.style !== 'candle');
let rf;
if (key !== this.key) {
this.key = key; this.yk = 1; this.zoom.restart(fit); rf = 0;
} else {
const dropped = this.n0 ? droppedFront(this.head, bars) : -1;
this.zoom.fit = fit;
this.zoom.data(this.n0, n, dropped);
rf = recalcFrom(dropped >= 0, this.n0, dropped);
}
for (const k of Object.keys(this.ind)) this.ind[k].from = Math.min(this.ind[k].from, rf);
this.bars = bars; this.opt = opt; this.n0 = n; this.head = headKeys(bars);
this.redraw();
}
redraw() {
if (this.raf) return;
this.raf = requestAnimationFrame(() => { this.raf = 0; try { this.draw(); } catch (e) { console.error('[chart]', e); } });
}
announce(msg) {
const live = this.c.parentElement?.querySelector('.cc-live');
if (!live || !this.bars.length) return;
const { from, to } = visibleRange(this.zoom.get(), this.bars.length);
const xl = this.xLabel();
clearTimeout(this.annT);
this.annT = setTimeout(() => { live.textContent = `${msg}: ${xl(this.bars[from])} bis ${xl(this.bars[to - 1])}, ${to - from} von ${this.bars.length} Balken`; }, 250);
}
xLabel() { const o = this.opt; return o.xLabel ?? ((b) => (o.daily ? (b.label ?? date(b.t)) : time(b.t))); }
/** Indikatoren bei Bedarf fortschreiben (nur ab dem ersten geänderten Balken) */
indicators() {
const on = this.opt.ind ?? {}, bars = this.bars, n = bars.length, I = this.ind;
if (on.ma20 && I.ma20.from < n) { smaInto(bars, 20, I.ma20.a, I.ma20.from); I.ma20.from = n; }
if (on.ma50 && I.ma50.from < n) { smaInto(bars, 50, I.ma50.a, I.ma50.from); I.ma50.from = n; }
if (on.bb && I.bb.from < n) { bollingerInto(bars, 20, 2, I.bb.a, I.bb.from); I.bb.from = n; }
}
draw() {
const c = this.c;
if (!c.isConnected) { this.ro.disconnect(); this.zoom.destroy(); charts.delete(this); return; }
const r = c.getBoundingClientRect();
if (r.width < 2 || r.height < 2) return; // ausgeblendet – ResizeObserver zeichnet beim Einblenden
const dpr = Math.min(3, window.devicePixelRatio || 1);
const w = Math.round(r.width), h = Math.round(r.height);
if (c.width !== Math.round(w * dpr) || c.height !== Math.round(h * dpr)) { c.width = Math.round(w * dpr); c.height = Math.round(h * dpr); }
const ctx = this.ctx;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, w, h);
ctx.font = FONT; ctx.setLineDash([]); ctx.lineWidth = 1;
const col = colors(), o = this.opt, all = this.bars, n = all.length;
// scharfe Haarlinien: auf Gerätepixel ausrichten
const hair = Math.max(1, Math.round(dpr)) / dpr;
const snap = (v) => (Math.round(v * dpr) + (Math.max(1, Math.round(dpr)) % 2) / 2) / dpr;
const wrap = c.parentElement;
if (!n) {
this.layout = { w: w - 56, axis: w - 56 };
wrap?.classList.remove('cc-zoomed');
ctx.fillStyle = col.text; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
const lines = wrapText(ctx, o.empty ?? 'Noch keine Kursdaten', Math.max(120, Math.min(460, w - 40)));
lines.forEach((l, i) => ctx.fillText(l, w / 2, h / 2 + (i - (lines.length - 1) / 2) * 17));
return;
}
const style = o.style === 'line' || o.style === 'area' ? (n > 1 ? o.style : 'candle') : 'candle';
const line = style !== 'candle';
this.indicators();
const on = o.ind ?? {}, I = this.ind;
// Ausschnitt und Preisbereich (Achsenbreite hängt von der Größe der Zahlen ab → zuerst schätzen)
const est = Math.max(...[all[n - 1].h, o.last, o.indicative].filter(Number.isFinite));
const axisW = Math.max(54, Math.ceil(ctx.measureText(num(est * 1.05, 2)).width) + 18);
const timeH = 22;
const plotW = Math.max(20, w - axisW), plotH = h - timeH;
this.layout = { w: plotW, axis: plotW };
const v = this.zoom.get();
wrap?.classList.toggle('cc-zoomed', !isFull(v, n));
const { from, to } = visibleRange(v, n);
const span = v.b - v.a, slot = plotW / span;
const k = bucketSize(slot, line ? 1 : 2);
const groups = aggregate(all, from, to, k);
const extras = [];
const rightEdge = v.b >= n - 0.5;
if (line && rightEdge && Number.isFinite(o.last)) extras.push(o.last);
for (const m of o.marks ?? []) if (m.i >= from && m.i < to) for (const x of [m.buy?.px, m.sell?.px]) if (Number.isFinite(x)) extras.push(x);
const pushInd = (arr) => { for (let i = from; i < to; i += k) if (Number.isFinite(arr[i])) extras.push(arr[i]); };
if (on.ma20) pushInd(I.ma20.a);
if (on.ma50) pushInd(I.ma50.a);
if (on.bb) { pushInd(I.bb.a.up); pushInd(I.bb.a.lo); }
const levels = (o.levels ?? []).filter((l) => Number.isFinite(l.p) && l.p > 0);
const near = [...levels.map((l) => l.p), o.indicative, rightEdge ? o.prevClose : NaN, rightEdge && !line ? o.last : NaN];
const pr = scaleRange(priceRange(all, from, to, { line, extras, near, pad: 0.08 }), this.yk);
const { lo, hi, vmax } = pr;
const infoRows = plotW < 430 ? 2 : 1;
const padT = 8 + infoRows * 15 + (on.ma20 || on.ma50 || on.bb ? 15 : 0);
const volH = Math.max(24, Math.round(plotH * 0.18));
const priceBot = plotH - Math.round(volH * 0.55) - 6;
const y = (p) => padT + ((hi - p) / (hi - lo)) * (priceBot - padT);
const pAt = (yy) => hi - ((yy - padT) / (priceBot - padT)) * (hi - lo);
const X = (i) => xOf(v, i, plotW);
const xl = this.xLabel();
const first = all[0], lastBar = all[n - 1];
const base = Number.isFinite(o.base) && o.base > 0 ? o.base : first.o;
const trend = (o.last ?? lastBar.c) >= base ? col.up : col.down;
// ---- Gitter und Preisachse
const step = niceStep(hi - lo, Math.max(3, Math.round((priceBot - padT) / 52)));
const dec = stepDecimals(step);
ctx.lineWidth = hair; ctx.strokeStyle = col.grid;
const yTicks = [];
for (let p = Math.ceil(lo / step) * step; p <= hi; p += step) { const yy = y(p); if (yy > 4 && yy < plotH - 4) yTicks.push([p, yy]); }
for (const [, yy] of yTicks) { ctx.beginPath(); ctx.moveTo(0, snap(yy)); ctx.lineTo(plotW, snap(yy)); ctx.stroke(); }
// Zeitachse: Abstand nach Breite der Beschriftung, immer Vielfache → ruhig beim Verschieben
const lw = ctx.measureText(xl(lastBar)).width;
const every = tickEvery(slot, lw + 22);
const xTicks = timeTicks(from, to, every);
for (const i of xTicks) { const xx = snap(X(i)); if (xx < 0 || xx > plotW) continue; ctx.beginPath(); ctx.moveTo(xx, 0); ctx.lineTo(xx, plotH); ctx.stroke(); }
ctx.save();
ctx.beginPath(); ctx.rect(0, 0, plotW, plotH); ctx.clip();
// ---- Volumen (unten, halbtransparent in Kerzenfarbe)
const bw = Math.max(1, Math.min(slot * k * 0.72, 28));
for (const g of groups) {
const vh = ((g.v ?? 0) / (vmax * k)) * volH;
if (vh <= 0) continue;
const cx = X(g.i + (g.k - 1) / 2);
ctx.fillStyle = g.c >= g.o ? col.up : col.down;
ctx.globalAlpha = 0.28;
ctx.fillRect(Math.round((cx - bw / 2) * dpr) / dpr, plotH - vh, Math.max(hair, Math.round(bw * dpr) / dpr), vh);
}
ctx.globalAlpha = 1;
// ---- Bollinger-Band (Fläche hinter dem Kurs)
const indPath = (arr, stroke, width = 1.25, dash = []) => {
ctx.beginPath();
let started = false;
for (let i = Math.max(0, from - k); i < Math.min(n, to + k); i += k) {
const val = arr[i];
if (!Number.isFinite(val)) { started = false; continue; }
const xx = X(i), yy = y(val);
if (started) ctx.lineTo(xx, yy); else { ctx.moveTo(xx, yy); started = true; }
}
if (stroke) { ctx.strokeStyle = stroke; ctx.lineWidth = width; ctx.setLineDash(dash); ctx.stroke(); ctx.setLineDash([]); ctx.lineWidth = 1; }
};
if (on.bb) {
const B = I.bb.a;
ctx.beginPath();
const idx = [];
for (let i = Math.max(0, from - k); i < Math.min(n, to + k); i += k) if (Number.isFinite(B.up[i])) idx.push(i);
if (idx.length > 1) {
idx.forEach((i, j) => (j ? ctx.lineTo(X(i), y(B.up[i])) : ctx.moveTo(X(i), y(B.up[i]))));
for (let j = idx.length - 1; j >= 0; j--) ctx.lineTo(X(idx[j]), y(B.lo[idx[j]]));
ctx.closePath(); ctx.fillStyle = alpha(col.bb, 0.08); ctx.fill();
}
indPath(B.up, alpha(col.bb, 0.75), 1);
indPath(B.lo, alpha(col.bb, 0.75), 1);
indPath(B.mid, alpha(col.bb, 0.6), 1, [4, 3]);
}
// ---- Kurs: Linie / Fläche / Kerzen
if (line) {
const pts = groups.map((g) => [X(g.i + g.k - 1), y(g.c)]);
// Linie bis an die Ränder fortsetzen (Balken links/rechts außerhalb des Ausschnitts)
if (from > 0) pts.unshift([X(from - 1), y(all[from - 1].c)]);
if (to < n) pts.push([X(to), y(all[to].c)]);
ctx.beginPath();
pts.forEach(([px, py], i) => (i ? ctx.lineTo(px, py) : ctx.moveTo(px, py)));
ctx.strokeStyle = trend; ctx.lineWidth = 2; ctx.lineJoin = 'round'; ctx.stroke(); ctx.lineWidth = 1;
if (style === 'area') {
ctx.lineTo(pts[pts.length - 1][0], priceBot + 6); ctx.lineTo(pts[0][0], priceBot + 6); ctx.closePath();
const gr = ctx.createLinearGradient(0, padT, 0, priceBot);
gr.addColorStop(0, alpha(trend, 0.26)); gr.addColorStop(1, alpha(trend, 0.02));
ctx.fillStyle = gr; ctx.fill();
}
if (to - from <= 14) { ctx.fillStyle = trend; for (let i = from; i < to; i++) { ctx.beginPath(); ctx.arc(X(i), y(all[i].c), 2.5, 0, 7); ctx.fill(); } }
} else {
for (const g of groups) {
const cx = X(g.i + (g.k - 1) / 2);
const up = g.c >= g.o;
const cc = up ? col.up : col.down;
ctx.strokeStyle = ctx.fillStyle = cc;
ctx.lineWidth = hair;
const sx = snap(cx);
ctx.beginPath(); ctx.moveTo(sx, y(g.h)); ctx.lineTo(sx, y(g.l)); ctx.stroke();
const top = y(Math.max(g.o, g.c)), bh = Math.max(hair, Math.abs(y(g.o) - y(g.c)));
const bx = Math.round((cx - bw / 2) * dpr) / dpr, bwp = Math.max(hair, Math.round(bw * dpr) / dpr);
ctx.fillRect(bx, top, bwp, bh);
}
}
if (on.ma50) indPath(I.ma50.a, col.ma2, 1.5);
if (on.ma20) indPath(I.ma20.a, col.ma1, 1.5);
ctx.restore();
// ---- Vortagesschluss (gestrichelt, beschriftet)
if (Number.isFinite(o.prevClose) && !o.daily) {
const yy = y(o.prevClose);
if (yy > padT - 4 && yy < priceBot + 4) {
ctx.setLineDash([2, 4]); ctx.strokeStyle = col.text; ctx.lineWidth = hair;
ctx.beginPath(); ctx.moveTo(0, snap(yy)); ctx.lineTo(plotW, snap(yy)); ctx.stroke(); ctx.setLineDash([]);
ctx.font = `600 ${FONT}`; ctx.textAlign = 'right'; ctx.textBaseline = 'bottom';
const t = `Vortag ${num(o.prevClose, 2)}`, tw = ctx.measureText(t).width;
ctx.fillStyle = alpha(col.bg, 0.8); ctx.fillRect(plotW - tw - 10, yy - 15, tw + 8, 14);
ctx.fillStyle = col.text; ctx.fillText(t, plotW - 6, yy - 2);
ctx.font = FONT;
}
}
// ---- Order-Linien (gestrichelt, Beschriftung links)
const lvColor = (l) => (l.kind === 'stop' ? col.down : l.kind === 'tp' ? col.up : l.side === 'buy' ? col.accent : col.gold);
const lvY = [];
if (levels.length) {
ctx.font = `600 ${FONT}`; ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
let prevY = -Infinity;
for (const l of levels) { // absteigend nach Kurs sortiert → Beschriftungen von oben nach unten
const out = l.p > hi ? 1 : l.p < lo ? -1 : 0;
const yy = snap(out > 0 ? padT + 1 : out < 0 ? priceBot - 1 : y(l.p));
const lc = lvColor(l);
lvY.push({ l, yy });
if (!out) { ctx.strokeStyle = lc; ctx.lineWidth = 1.25; ctx.setLineDash([6, 3]); ctx.beginPath(); ctx.moveTo(0, yy); ctx.lineTo(plotW, yy); ctx.stroke(); ctx.setLineDash([]); ctx.lineWidth = 1; }
const txt = `${l.label} ${num(l.p, 2)}${out > 0 ? ' ↑' : out < 0 ? ' ↓' : ''}`;
const tw = ctx.measureText(txt).width + 10;
const ty = Math.min(priceBot - 8, Math.max(padT + 8, Math.max(yy - 9, prevY + 16)));
prevY = ty;
ctx.fillStyle = alpha(col.bg, 0.92); ctx.fillRect(4, ty - 8, tw, 16);
ctx.strokeStyle = lc; ctx.lineWidth = hair; ctx.strokeRect(snap(4), snap(ty - 8), tw - 1, 15);
ctx.fillStyle = lc; ctx.fillText(txt, 9, ty + 0.5);
}
ctx.font = FONT;
}
// ---- eigene Trades (Dreiecke am Ausführungskurs)
const marks = (o.marks ?? []).filter((m) => m.i >= from && m.i < to);
for (const m of marks) {
const cx = X(m.i);
for (const [kk, d] of [['buy', 1], ['sell', -1]]) {
if (!m[kk]) continue;
const py = Math.max(padT, Math.min(priceBot, y(m[kk].px)));
ctx.beginPath(); ctx.moveTo(cx, py + 2 * d); ctx.lineTo(cx - 6, py + 12 * d); ctx.lineTo(cx + 6, py + 12 * d); ctx.closePath();
ctx.fillStyle = kk === 'buy' ? col.up : col.down; ctx.strokeStyle = col.bg; ctx.lineWidth = 1.5; ctx.fill(); ctx.stroke(); ctx.lineWidth = 1;
}
}
// ---- Achsen: Trennlinie, Preisbeschriftung, Zeitbeschriftung
ctx.strokeStyle = col.line; ctx.lineWidth = hair;
ctx.beginPath(); ctx.moveTo(snap(plotW), 0); ctx.lineTo(snap(plotW), plotH); ctx.moveTo(0, snap(plotH)); ctx.lineTo(w, snap(plotH)); ctx.stroke();
// Achsenwerte nicht unter den farbigen Marken (letzter Kurs, Vortag, indikativ) zeigen
const tagY = [o.daily ? NaN : (o.last ?? lastBar.c), o.daily ? NaN : o.prevClose, o.indicative].filter(Number.isFinite).map((p) => Math.max(padT - 2, Math.min(priceBot + 2, y(p))));
ctx.fillStyle = col.text; ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
for (const [p, yy] of yTicks) if (!tagY.some((t) => Math.abs(t - yy) < 15)) ctx.fillText(num(p, dec), plotW + 7, yy);
ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
for (const i of xTicks) {
const xx = X(i), s = xl(all[i]), tw = ctx.measureText(s).width;
if (xx - tw / 2 < 2 || xx + tw / 2 > plotW - 2) continue;
ctx.fillText(s, xx, plotH + timeH / 2 + 1);
}
// ---- Marken rechts: letzter Kurs (farbig), indikativer Preis, Vortagesschluss
const tag = (p, bg, fg, label, outline = false) => {
if (!Number.isFinite(p)) return;
const yy = Math.max(padT - 2, Math.min(priceBot + 2, y(p)));
ctx.font = `600 ${FONT}`;
roundRect(ctx, plotW + 1, yy - 9, axisW - 2, 18, 3);
if (outline) { ctx.fillStyle = col.bg; ctx.fill(); ctx.strokeStyle = bg; ctx.lineWidth = 1; ctx.stroke(); ctx.fillStyle = bg; } else { ctx.fillStyle = bg; ctx.fill(); ctx.fillStyle = fg; }
ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
ctx.fillText(label ?? num(p, 2), plotW + 6, yy + 0.5);
ctx.font = FONT;
};
const lastP = o.last ?? lastBar.c;
if (!o.daily && Number.isFinite(lastP)) {
const yy = y(lastP);
if (yy > 0 && yy < plotH) { ctx.strokeStyle = trend; ctx.lineWidth = hair; ctx.setLineDash([1, 3]); ctx.beginPath(); ctx.moveTo(0, snap(yy)); ctx.lineTo(plotW, snap(yy)); ctx.stroke(); ctx.setLineDash([]); }
}
if (Number.isFinite(o.prevClose) && !o.daily) { const yy = y(o.prevClose); if (yy > padT - 4 && yy < priceBot + 4) tag(o.prevClose, col.text, col.bg, undefined, true); }
if (Number.isFinite(o.indicative)) tag(o.indicative, col.gold, col.onSignal, `≈${num(o.indicative, 2)}`);
if (!o.daily) tag(lastP, trend, col.onSignal);
// ---- Fadenkreuz mit Preis- und Zeitmarke
const hp = this.hoverPt;
let hi_ = to - 1;
if (hp && hp.x >= 0 && hp.x < plotW) {
const i = indexAt(v, hp.x, plotW, n);
hi_ = Math.max(from, Math.min(to - 1, i));
const b = all[hi_];
const cx = snap(X(hi_));
const yy = Math.max(0, Math.min(plotH, line ? y(b.c) : hp.y));
ctx.strokeStyle = col.text; ctx.lineWidth = hair; ctx.setLineDash([4, 4]);
ctx.beginPath(); ctx.moveTo(cx, 0); ctx.lineTo(cx, plotH); ctx.stroke();
ctx.beginPath(); ctx.moveTo(0, snap(yy)); ctx.lineTo(plotW, snap(yy)); ctx.stroke();
ctx.setLineDash([]);
if (line) { ctx.fillStyle = trend; ctx.strokeStyle = col.bg; ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(cx, y(b.c), 4, 0, 7); ctx.fill(); ctx.stroke(); ctx.lineWidth = 1; }
tag(line ? b.c : pAt(yy), col.crossBg, col.crossFg, num(line ? b.c : pAt(yy), Math.max(2, dec)));
const tt = o.tipTitle ? o.tipTitle(b) : xl(b);
ctx.font = `600 ${FONT}`;
const tw = ctx.measureText(tt).width + 14;
const bx = Math.max(0, Math.min(plotW - tw, cx - tw / 2));
roundRect(ctx, bx, plotH + 2, tw, timeH - 4, 3); ctx.fillStyle = col.crossBg; ctx.fill();
ctx.fillStyle = col.crossFg; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.fillText(tt, bx + tw / 2, plotH + timeH / 2 + 1);
ctx.font = FONT;
// eigene Trades bzw. Order unter dem Fadenkreuz
const rows = [
...((o.marks ?? []).find((m) => m.i === hi_)?.tip ?? []).map((t) => ({ t, color: t.startsWith('Dein Kauf') ? col.up : t.startsWith('Dein Verkauf') ? col.down : col.fg })),
...lvY.filter((z) => Math.abs(z.yy - hp.y) <= 8).map((z) => ({ t: z.l.tip, color: lvColor(z.l) })),
];
if (rows.length) {
ctx.font = `600 12px ${MONO}`;
const tw2 = Math.max(...rows.map((rr) => ctx.measureText(rr.t).width)) + 16, th = rows.length * 16 + 8;
let bx2 = cx + 12;
if (bx2 + tw2 > plotW) bx2 = cx - 12 - tw2;
bx2 = Math.max(2, bx2);
const by2 = Math.min(priceBot - th, Math.max(padT, yy + 12));
roundRect(ctx, bx2, by2, tw2, th, 4); ctx.fillStyle = alpha(col.tip, 0.96); ctx.fill(); ctx.strokeStyle = col.line; ctx.lineWidth = 1; ctx.stroke();
ctx.textAlign = 'left'; ctx.textBaseline = 'middle';
rows.forEach((rr, j) => { ctx.fillStyle = rr.color; ctx.fillText(rr.t, bx2 + 8, by2 + 12 + j * 16); });
ctx.font = FONT;
}
}
// ---- Infozeile oben links: E/H/T/S, Änderung, Volumen der Kerze (bzw. der neuesten sichtbaren) und Indikatoren
if (hi_ >= 0) {
const b = all[hi_];
const prev = hi_ > 0 ? all[hi_ - 1].c : (Number.isFinite(o.base) ? o.base : b.o);
const d = prev ? (b.c / prev - 1) * 100 : 0;
const dc = b.c >= b.o ? col.up : col.down;
const pd = Math.max(2, dec);
const seg = [];
const add = (lbl, val, color) => seg.push({ lbl, val, color });
if (line) add('Kurs', num(b.c, pd), dc);
else { add('E', num(b.o, pd), dc); add('H', num(b.h, pd), dc); add('T', num(b.l, pd), dc); add('S', num(b.c, pd), dc); }
const row2 = [];
row2.push({ lbl: '', val: `${d > 0 ? '+' : d < 0 ? '−' : '±'}${num(Math.abs(d), 2)} %`, color: d >= 0 ? col.up : col.down });
row2.push({ lbl: 'Vol', val: compact(b.v ?? 0), color: col.fg });
const rows = infoRows === 1 ? [[...seg, ...row2]] : [seg, row2];
const indRow = [];
if (on.ma20) indRow.push({ lbl: 'MA 20', val: num(I.ma20.a[hi_], pd), color: col.ma1 });
if (on.ma50) indRow.push({ lbl: 'MA 50', val: num(I.ma50.a[hi_], pd), color: col.ma2 });
if (on.bb) indRow.push({ lbl: 'BB 20', val: `${num(I.bb.a.lo[hi_], pd)} – ${num(I.bb.a.up[hi_], pd)}`, color: col.bb });
if (indRow.length) rows.push(indRow);
ctx.font = `11px ${MONO}`; ctx.textBaseline = 'middle'; ctx.textAlign = 'left';
const widths = rows.map((rw) => rw.reduce((s, z) => s + (z.lbl ? ctx.measureText(`${z.lbl} `).width : 0) + ctx.measureText(z.val).width + 10, 0));
const boxW = Math.min(plotW - 8, Math.max(...widths) + 8);
roundRect(ctx, 4, 4, boxW, rows.length * 15 + 5, 4); ctx.fillStyle = alpha(col.bg, 0.78); ctx.fill();
rows.forEach((rw, j) => {
let x = 9;
const yy = 12 + j * 15;
for (const z of rw) {
if (z.lbl) { ctx.fillStyle = col.text; ctx.fillText(`${z.lbl} `, x, yy); x += ctx.measureText(`${z.lbl} `).width; }
ctx.fillStyle = z.color; ctx.fillText(z.val, x, yy); x += ctx.measureText(z.val).width + 10;
}
});
ctx.font = FONT;
}
}
}
/** Zoomstufe um die Mitte (für die Knöpfe) */
function zoomed(v, f, n) {
const span = v.b - v.a, m = (v.a + v.b) / 2;
const next = Math.max(Math.min(5, n), Math.min(n, span * f));
return { a: m - next / 2, b: m + next / 2 };
}
// ---------------------------------------------------------------- Vollbild
/**
* Element als Vollbild-Ansicht zeigen (fest über der Seite; wo möglich echtes Vollbild und Querformat).
* Escape, der Knopf oder „Zurück“ schließen. Liefert {open, close, toggle, isOpen}.
*/
export function fullscreen(el, { onChange } = {}) {
let open = false, pushed = false, skipPop = false;
const doc = document.documentElement;
const set = (on) => {
if (open === on) return;
open = on;
el.classList.toggle('cc-fs', on);
doc.classList.toggle('cc-fs-open', on);
onChange?.(on);
};
const close = ({ fromPop = false } = {}) => {
if (!open) return;
set(false);
if (document.fullscreenElement) document.exitFullscreen?.().catch(() => {});
if (pushed && !fromPop && history.state?.ccFs) { skipPop = true; history.back(); }
pushed = false;
};
const show = () => {
if (open) return;
set(true);
try { history.pushState({ ...(history.state ?? {}), ccFs: true }, ''); pushed = true; } catch { /* egal */ }
// echtes Vollbild nur auf Geräten, die es für beliebige Elemente können; Querformat ist ein Wunsch, kein Muss
if (el.requestFullscreen && matchMedia('(pointer: coarse)').matches) {
el.requestFullscreen({ navigationUI: 'hide' }).then(() => screen.orientation?.lock?.('landscape')).catch(() => {});
}
};
// vor den Verlaufs-Handlern der App: „Zurück“ schließt nur die Vollbild-Ansicht
window.addEventListener('popstate', (e) => {
if (skipPop) { skipPop = false; e.stopImmediatePropagation(); return; }
if (open && !history.state?.ccFs) { pushed = false; close({ fromPop: true }); e.stopImmediatePropagation(); }
}, true);
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && open && !e.defaultPrevented && !document.querySelector('.modal-bg')) { e.preventDefault(); close(); }
});
document.addEventListener('fullscreenchange', () => { if (!document.fullscreenElement && open && el.requestFullscreen && matchMedia('(pointer: coarse)').matches) close(); });
return { open: show, close, toggle: () => (open ? close() : show()), isOpen: () => open };
}