Spaces:
Paused
Paused
Download bubbles.html from leisudev/crypto-vol-live: direct link, hf CLI and curl.
- Browser
- Download file 131 kB
-
https://huggingface.co/spaces/leisudev/crypto-vol-live/resolve/main/bubbles.html
- Command line
-
hf download hf://spaces/leisudev/crypto-vol-live/bubbles.html
-
curl -L -o bubbles.html https://huggingface.co/spaces/leisudev/crypto-vol-live/resolve/main/bubbles.html
131 kB
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>Timestral 泡泡图 · 波动率预测</title>
<!-- bubble-ui: multi-ind seawater sentiment ice-peak v3.8 prefs-sync-all -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=ZCOOL+KuaiLe&display=swap" rel="stylesheet" />
<style>
:root {
--coral: #F18D8D;
--sky: #4DBBEB;
--orange: #F7941D;
--magenta: #E91E63;
--yellow: #FFD500;
--bg: #FFF8F0;
--bg-elev: #FFFFFF;
--bg-card: #FFFFFF;
--bg-hover: #FFF1E6;
--border: #F0D9C8;
--text: #1F1520;
--text-muted: #6B5A62;
--text-dim: #9A8790;
--accent: var(--sky);
--radius: 14px;
--font: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
--cartoon: "ZCOOL KuaiLe", "Ma Shan Zheng", "Comic Sans MS", "PingFang SC", cursive, sans-serif;
--shadow: 0 8px 24px rgba(233, 30, 99, 0.08), 0 2px 8px rgba(31, 21, 32, 0.06);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body {
height: 100%; overflow: hidden;
font-family: var(--cartoon); background: var(--bg); color: var(--text);
line-height: 1.45; font-size: 14px; overscroll-behavior: none; touch-action: manipulation;
}
body::before {
content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;
background: repeating-linear-gradient(
180deg,
var(--coral) 0px, var(--coral) 28px,
var(--sky) 28px, var(--sky) 56px,
var(--orange) 56px, var(--orange) 84px,
var(--magenta) 84px, var(--magenta) 112px,
var(--yellow) 112px, var(--yellow) 140px
);
opacity: 0.09;
mask-image: linear-gradient(180deg, rgba(0,0,0,0.5), rgba(0,0,0,0.1) 45%, transparent 80%);
-webkit-mask-image: linear-gradient(180deg, rgba(0,0,0,0.5), rgba(0,0,0,0.1) 45%, transparent 80%);
}
.paper-strip {
height: 10px; width: 100%; flex-shrink: 0;
background:
radial-gradient(circle at 10px 0, transparent 9px, var(--coral) 9.5px) 0 0 / 20px 10px,
radial-gradient(circle at 10px 0, transparent 9px, var(--sky) 9.5px) 20px 0 / 20px 10px,
radial-gradient(circle at 10px 0, transparent 9px, var(--orange) 9.5px) 40px 0 / 20px 10px,
radial-gradient(circle at 10px 0, transparent 9px, var(--magenta) 9.5px) 60px 0 / 20px 10px,
radial-gradient(circle at 10px 0, transparent 9px, var(--yellow) 9.5px) 80px 0 / 20px 10px;
background-color: var(--coral);
}
.app-shell { display: flex; flex-direction: column; height: 100%; max-height: 100dvh; }
header.topbar {
flex-shrink: 0; padding: 8px 12px 6px;
background: rgba(255,252,248,0.92);
border-bottom: 1px solid var(--border);
backdrop-filter: blur(8px);
position: relative; z-index: 30; overflow: visible;
}
.topbar-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.topbar-row + .topbar-row { margin-top: 6px; }
.brand {
font-family: var(--cartoon); font-size: 18px; font-weight: 700;
letter-spacing: 0.02em; color: var(--text);
}
.brand small {
display: block; font-family: var(--font); font-size: 11px;
font-weight: 500; color: var(--text-muted); margin-top: 1px;
}
.seg {
display: flex; gap: 4px; flex-wrap: wrap;
background: rgba(255,255,255,0.7); border: 1px solid var(--border);
border-radius: 999px; padding: 3px;
}
.seg button {
appearance: none; border: none; background: transparent;
color: var(--text-muted); font-weight: 650; font-size: 12px;
padding: 6px 12px; border-radius: 999px; cursor: pointer; font-family: inherit;
transition: background .15s, color .15s;
white-space: nowrap;
}
.seg button.on {
background: linear-gradient(135deg, var(--magenta), var(--orange));
color: #fff; box-shadow: 0 2px 8px rgba(233,30,99,0.25);
}
/* Horizon / candle prediction row: full-width, never wrap mid-button */
.horizon-row {
display: flex; align-items: center; gap: 8px;
flex-wrap: nowrap; width: 100%; min-width: 0;
}
#horizon-seg, #candle-seg {
flex: 1 1 auto; min-width: 0;
flex-wrap: nowrap; overflow-x: auto; -webkit-overflow-scrolling: touch;
}
#horizon-seg button, #candle-seg button {
flex: 1 1 0; min-width: max-content; text-align: center;
}
.horizon-row .axis-hint { flex-shrink: 0; white-space: nowrap; }
.btn {
appearance: none; border: 1px solid var(--border); background: var(--bg-card);
color: var(--text); padding: 6px 10px; border-radius: 8px; font-size: 12px;
font-weight: 600; cursor: pointer; font-family: inherit;
}
.btn:hover { background: var(--bg-hover); }
.btn.on { background: linear-gradient(135deg, rgba(233,30,99,0.12), rgba(247,148,29,0.12)); border-color: #f0b8a0; }
.btn-rsi {
appearance: none; border: 2px solid #5ec8e8; cursor: pointer; font-family: inherit;
display: inline-flex; align-items: center; gap: 5px;
padding: 5px 12px 5px 8px; border-radius: 999px;
background: linear-gradient(160deg, #e8f8fd 0%, #b8e8f5 55%, #8ad4ec 100%);
color: #0a5f7a; font-weight: 800; font-size: 12px; letter-spacing: 0.04em;
box-shadow: 0 2px 10px rgba(77,187,235,0.35), inset 0 1px 0 rgba(255,255,255,0.7);
transition: transform .12s, box-shadow .15s, background .15s, border-color .15s;
flex-shrink: 0;
}
.btn-rsi:hover { transform: translateY(-1px); box-shadow: 0 4px 14px rgba(77,187,235,0.45); }
.btn-rsi .rsi-ico {
width: 22px; height: 22px; border-radius: 50%;
background: radial-gradient(circle at 35% 30%, #fff 0%, #7fd4f0 45%, #2a9fc4 100%);
display: inline-flex; align-items: center; justify-content: center;
box-shadow: inset 0 -1px 2px rgba(10,95,122,0.25);
}
.btn-rsi .rsi-ico svg { width: 14px; height: 14px; display: block; }
.btn-rsi.on {
border-color: #1a8fb8;
background: linear-gradient(160deg, #7fd4f0 0%, #3db4d8 50%, #1a8fb8 100%);
color: #fff;
box-shadow: 0 3px 14px rgba(26,143,184,0.5), inset 0 1px 0 rgba(255,255,255,0.35);
}
.btn-rsi.on .rsi-ico {
background: radial-gradient(circle at 35% 30%, #e8f8fd 0%, #fff 40%, #b8e8f5 100%);
}
.btn-vol {
appearance: none; border: none; cursor: pointer; font-family: inherit;
display: inline-flex; align-items: center; gap: 5px;
padding: 5px 12px 5px 8px; border-radius: 999px; font-size: 12px; font-weight: 800;
color: #fff; letter-spacing: 0.02em;
background: linear-gradient(135deg, #E91E63, #F7941D);
box-shadow: 0 3px 12px rgba(233,30,99,0.35);
flex-shrink: 0;
}
.btn-vol[hidden] { display: none !important; }
.btn-vol:hover { transform: translateY(-1px); box-shadow: 0 4px 14px rgba(233,30,99,0.45); }
.btn-vol .vol-ico {
width: 22px; height: 22px; border-radius: 50%;
display: inline-flex; align-items: center; justify-content: center;
background: rgba(255,255,255,0.95);
box-shadow: 0 1px 4px rgba(31,21,32,0.12);
}
.btn-vol .vol-ico svg { width: 14px; height: 14px; display: block; }
.mode-toolbar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; flex: 1; min-width: 0; }
#rsi-seg { display: none; }
.axis-hint { font-size: 11px; color: var(--text-dim); }
.crack-help {
margin-top: 6px; padding: 7px 10px; border-radius: 10px;
background: linear-gradient(90deg, rgba(241,141,141,0.18), rgba(77,187,235,0.14));
border: 1px solid var(--border); font-size: 11px; color: var(--text-muted); line-height: 1.45;
}
.crack-help strong { color: var(--magenta); font-weight: 700; }
.coin-panel {
position: relative; margin-top: 6px; border: 1px solid var(--border); border-radius: 12px;
background: rgba(255,255,255,0.78); z-index: 40;
}
.coin-panel-hd {
display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
padding: 6px 10px; cursor: pointer; user-select: none;
}
.coin-panel-hd .lab { font-size: 12px; font-weight: 700; color: var(--text); }
.coin-panel-hd .meta { font-size: 11px; color: var(--text-dim); margin-left: auto; }
/* Floating dropdown — does NOT change stage height */
.coin-panel-bd {
display: none; position: absolute; left: 0; right: 0; top: calc(100% + 4px);
z-index: 50; padding: 8px 10px 12px;
border: 1px solid var(--border); border-radius: 12px;
background: rgba(255,252,248,0.98);
box-shadow: 0 12px 28px rgba(31,21,32,0.14);
max-height: min(220px, 36vh); overflow: auto;
}
.coin-panel.open .coin-panel-bd { display: block; }
.coin-grid {
display: grid; grid-template-columns: repeat(auto-fill, minmax(92px, 1fr)); gap: 4px 6px;
}
.coin-item {
display: flex; align-items: center; gap: 5px; font-size: 11px; font-weight: 600;
color: var(--text-muted); padding: 3px 4px; border-radius: 6px; cursor: pointer;
}
.coin-item:hover { background: var(--bg-hover); color: var(--text); }
.coin-item input { accent-color: var(--magenta); width: 14px; height: 14px; }
.coin-item .has-data { color: #2e7d32; font-size: 9px; }
.coin-item .no-data { color: #b45309; font-size: 9px; }
.coin-actions { display: flex; gap: 6px; margin-top: 6px; flex-wrap: wrap; }
.coin-actions .btn { padding: 4px 8px; font-size: 11px; }
.stage { flex: 1; min-height: 0; position: relative; display: flex; flex-direction: column; z-index: 1; }
.canvas-frame {
flex: 1; min-height: 0; margin: 8px 10px; position: relative;
background: rgba(255,252,248,0.72); border: 1px solid var(--border);
border-radius: 16px; box-shadow: var(--shadow); overflow: hidden; touch-action: none;
/* height comes only from flex remainder of fixed chrome (topbar/dock/status) */
}
.canvas-frame::before {
content: ""; position: absolute; inset: 0; pointer-events: none; z-index: 0;
background:
linear-gradient(180deg, rgba(233,30,99,0.04) 0%, transparent 30%, transparent 70%, rgba(77,187,235,0.05) 100%),
radial-gradient(ellipse 55% 50% at 50% 48%, rgba(255,255,255,0.55) 0%, transparent 70%);
}
.y-rail {
position: absolute; left: 0; top: 0; bottom: 0; width: 56px; z-index: 2;
display: flex; flex-direction: column; justify-content: space-between;
padding: 14px 4px; pointer-events: none;
background: linear-gradient(90deg, rgba(255,248,240,0.95), transparent);
}
.y-rail span {
font-size: 10px; font-weight: 700; color: var(--text-dim);
writing-mode: vertical-rl; text-orientation: mixed; letter-spacing: 0.06em;
}
.y-rail .hi { color: var(--orange); }
.y-rail .mid { color: var(--text-muted); opacity: 0.7; }
.y-rail .lo { color: var(--sky); }
.lane-guides {
position: absolute; inset: 0 8px 0 56px; pointer-events: none; z-index: 1;
}
.lane-guides i {
position: absolute; left: 8px; right: 12px; height: 0;
border-top: 1px dashed rgba(240, 217, 200, 0.55);
}
.lane-guides i:nth-child(1) { top: 8%; }
.lane-guides i:nth-child(3) { top: 92%; }
.lane-guides i.center-line {
top: 50%;
border-top: 1.5px solid rgba(31, 21, 32, 0.34);
box-shadow: 0 0.5px 0 rgba(255, 255, 255, 0.65);
}
.bubble-layer {
position: absolute; inset: 0 8px 0 56px; z-index: 3;
}
@keyframes soap-float {
0%, 100% { transform: translate(0, 0); }
25% { transform: translate(var(--fx, 4px), calc(var(--fy, 6px) * -1)); }
50% { transform: translate(calc(var(--fx, 4px) * -0.6), var(--fy, 6px)); }
75% { transform: translate(calc(var(--fx, 4px) * 0.35), calc(var(--fy, 6px) * -0.45)); }
}
.bubble {
position: absolute; border-radius: 50%;
display: block;
color: var(--text); font-weight: 700; cursor: grab;
user-select: none; -webkit-user-select: none;
background: rgba(var(--bubble-rgb), 0.12);
border: 1.5px solid rgba(255,255,255,0.72);
box-shadow:
inset 0 -10px 18px rgba(var(--bubble-rgb), 0.12),
inset 0 2px 6px rgba(255,255,255,0.55),
0 8px 22px rgba(31,21,32,0.10),
0 0 0 1px rgba(var(--bubble-rgb), 0.28);
transition: top .4s ease, box-shadow .15s;
touch-action: none; will-change: left, top, transform;
overflow: hidden;
}
.bubble.floating:not(.dragging) {
animation: soap-float var(--fdur, 5.5s) ease-in-out var(--fdelay, 0s) infinite;
}
.bubble:active, .bubble.dragging {
cursor: grabbing; z-index: 20 !important; animation: none !important;
transform: scale(1.07);
box-shadow:
inset 0 -10px 18px rgba(var(--bubble-rgb), 0.16),
inset 0 2px 8px rgba(255,255,255,0.65),
0 14px 32px rgba(233,30,99,0.22),
0 0 0 2px rgba(255,255,255,0.95);
}
.bubble.selected {
z-index: 15;
box-shadow:
inset 0 -10px 18px rgba(var(--bubble-rgb), 0.14),
inset 0 2px 6px rgba(255,255,255,0.6),
0 10px 26px rgba(233,30,99,0.22),
0 0 0 2.5px var(--yellow);
}
.bubble.no-band {
opacity: 0.72;
filter: grayscale(0.15);
}
/* Icon fills entire bubble */
.bubble .b-av-wrap {
position: absolute; inset: 0; z-index: 0;
border-radius: 50%; overflow: hidden; pointer-events: none;
}
.bubble .b-av-wrap img, .bubble .b-av-wrap .b-init {
width: 100%; height: 100%; display: block; object-fit: cover;
}
.bubble .b-av-wrap .b-init {
display: grid; place-items: center; font-size: clamp(16px, 38%, 28px);
font-weight: 750; color: #fff; text-shadow: 0 1px 2px rgba(0,0,0,0.35);
background: linear-gradient(135deg, rgba(var(--bubble-rgb),0.95), rgba(var(--bubble-rgb),0.55));
}
/* Soap gloss over icon */
.bubble .b-gloss {
position: absolute; inset: 0; border-radius: 50%; pointer-events: none; z-index: 2;
background:
radial-gradient(circle at 32% 26%, rgba(255,255,255,0.82) 0%, rgba(255,255,255,0.22) 26%, transparent 48%),
radial-gradient(circle at 70% 78%, rgba(var(--bubble-rgb), 0.18) 0%, transparent 50%),
linear-gradient(160deg, rgba(255,255,255,0.18) 0%, transparent 42%, rgba(var(--bubble-rgb),0.08) 100%);
box-shadow:
inset 0 -12px 20px rgba(var(--bubble-rgb), 0.10),
inset 0 2px 8px rgba(255,255,255,0.45);
}
.bubble .b-gloss::before {
content: ""; position: absolute; top: 10%; left: 16%; width: 48%; height: 30%;
border-radius: 50%;
background: linear-gradient(160deg, rgba(255,255,255,0.92) 0%, rgba(255,255,255,0.22) 55%, transparent 80%);
}
.bubble .b-gloss::after {
content: ""; position: absolute; bottom: 14%; right: 18%; width: 22%; height: 14%;
border-radius: 50%; background: rgba(255,255,255,0.38);
}
.bubble .b-name {
position: absolute; left: 6%; right: 6%; bottom: 10%; z-index: 3;
font-size: clamp(9px, 16%, 11px); font-weight: 800;
text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
color: #1f1520; text-shadow: 0 1px 0 rgba(255,255,255,0.85), 0 0 6px rgba(255,255,255,0.7);
line-height: 1.1; pointer-events: none;
}
.bubble .b-na {
position: absolute; left: 50%; top: 42%; transform: translate(-50%, -50%);
z-index: 3; font-size: 10px; font-weight: 800; color: #b45309;
background: rgba(255,255,255,0.75); padding: 2px 6px; border-radius: 999px;
pointer-events: none; text-shadow: none;
}
/* Irregular stone-fissure cracks (SVG) */
.bubble .crack {
position: absolute; inset: 0; border-radius: 50%; pointer-events: none; z-index: 4;
opacity: 0; transition: opacity .28s;
overflow: hidden;
/* opacity only via .near-edge / .at-edge — never sticky inline */
}
.bubble .crack svg {
width: 100%; height: 100%; display: block;
}
.bubble .crack path {
fill: none;
stroke: rgba(28, 16, 20, 0.72);
stroke-linecap: round;
stroke-linejoin: round;
mix-blend-mode: multiply;
}
.bubble .crack path.micro {
stroke: rgba(40, 22, 28, 0.42);
}
.bubble.near-edge .crack { opacity: var(--crack, 0.4); }
.bubble.at-edge .crack {
opacity: var(--crack, 0.92);
filter: contrast(1.15);
}
.bubble.at-edge {
box-shadow:
inset 0 -10px 18px rgba(var(--bubble-rgb), 0.14),
inset 0 2px 6px rgba(255,255,255,0.55),
0 8px 22px rgba(31,21,32,0.12),
0 0 0 1.5px rgba(233,30,99,0.4);
}
/* Bottom dock always visible — fixed height so canvas never jumps */
.detail-sheet {
flex-shrink: 0; height: 200px; max-height: 200px; overflow-y: auto;
background: var(--bg-elev); border-top: 1px solid var(--border);
}
.detail-sheet.empty .detail-inner { opacity: 0.55; }
.detail-placeholder {
grid-column: 1 / -1; font-size: 12px; color: var(--text-dim); padding: 4px 0;
}
.detail-inner {
padding: 10px 14px 14px;
display: grid; grid-template-columns: auto 1fr auto; gap: 10px; align-items: start;
}
.detail-av {
width: 48px; height: 48px; border-radius: 50%; overflow: hidden; flex-shrink: 0;
box-shadow: 0 2px 8px rgba(31,21,32,0.12); border: 2px solid #fff;
background: rgba(var(--bubble-rgb, 77,187,235), 0.3);
display: grid; place-items: center;
}
.detail-av img { width: 100%; height: 100%; object-fit: cover; display: block; }
.detail-name { font-weight: 700; font-size: 15px; }
.detail-handle { color: var(--text-muted); font-size: 12px; }
.detail-close {
appearance: none; border: none; background: var(--bg-hover); color: var(--text-muted);
width: 28px; height: 28px; border-radius: 8px; cursor: pointer; font-size: 16px; line-height: 1;
}
.detail-body { grid-column: 1 / -1; margin-top: 2px; }
.band-row { font-size: 13px; margin: 4px 0 8px; }
.band-row b { font-variant-numeric: tabular-nums; font-size: 15px; }
.pos-bar {
position: relative; height: 10px; border-radius: 999px; margin: 8px 0 4px;
background: linear-gradient(90deg, #b91c1c, #e5e7eb 50%, #15803d);
box-shadow: inset 0 0 0 1px rgba(31,59,99,.06);
}
.pos-bar .dot {
position: absolute; top: 50%; width: 14px; height: 14px; margin: -7px 0 0 -7px;
border-radius: 50%; background: #fff;
box-shadow: 0 0 0 2px rgba(var(--bubble-rgb),0.9), 0 2px 6px rgba(0,0,0,.2);
transition: left .4s ease;
}
.pos-labs {
display: flex; justify-content: space-between; font-size: 11px; color: var(--text-dim);
font-variant-numeric: tabular-nums;
}
.chk-table { width: 100%; border-collapse: collapse; font-size: 12px; margin-top: 8px; }
.chk-table td { padding: 4px 2px; border-top: 1px solid #f0e6dc; vertical-align: top; }
.chk-table .ok { color: #2e7d32; font-weight: 700; }
.chk-table .ng { color: #c62828; font-weight: 700; }
.marks { letter-spacing: 2px; }
.grid-marks { display: flex; flex-wrap: wrap; gap: 2px; margin-top: 2px; }
.grid-marks span {
width: 14px; height: 14px; font-size: 9px; line-height: 14px; text-align: center;
border-radius: 3px; color: #fff;
}
.grid-marks .g { background: #2e7d32; }
.grid-marks .r { background: #c62828; }
.tg { font-size: 10px; color: #9a6700; font-weight: 600; }
.tg.lv { color: #2e7d32; }
.disc { font-size: 11px; color: #c62828; margin-top: 8px; font-weight: 600; }
.legend { font-size: 11px; color: var(--text-dim); margin-top: 4px; }
.status-line {
flex-shrink: 0; font-size: 11px; color: var(--text-dim); padding: 4px 12px 8px;
background: rgba(255,252,248,0.92); border-top: 1px solid var(--border);
}
.status-line.warn { color: #b45309; }
@media (max-width: 768px) {
/* Tiny bubbles: icon-only; hide name labels that would overflow */
.bubble .b-name { display: none; }
.bubble .b-na { font-size: 6px; padding: 0 3px; }
.bubble .b-av-wrap .b-init { font-size: clamp(8px, 42%, 14px); }
.bubble .b-gloss::before { width: 44%; height: 26%; }
.bubble .b-gloss::after { width: 18%; height: 12%; }
}
@media (max-width: 480px) {
.bubble .b-na { font-size: 5px; padding: 0 2px; }
.bubble .b-av-wrap .b-init { font-size: clamp(7px, 44%, 12px); }
}
@media (max-width: 520px) {
.y-rail { width: 28px; }
.bubble-layer, .lane-guides { inset: 0 4px 0 28px; }
.brand { font-size: 15px; }
.auth-wrap { max-width: min(132px, 46vw); }
.auth-pill { padding: 3px 8px; font-size: 10px; }
.auth-pill.x-login { max-width: 96px; }
#btn-x-label { max-width: 64px; }
.auth-wrap.is-x #btn-x-label { max-width: 76px; }
.auth-note { font-size: 9px; }
.seg button { padding: 5px 8px; font-size: 11px; }
.btn-rsi, .btn-vol { padding: 4px 9px 4px 6px; font-size: 11px; }
.btn-rsi .rsi-ico, .btn-vol .vol-ico { width: 18px; height: 18px; }
.btn-rsi .rsi-ico svg, .btn-vol .vol-ico svg { width: 12px; height: 12px; }
.coin-panel-bd { max-height: min(180px, 32vh); }
.detail-sheet { height: 168px; max-height: 168px; }
.stage-frame { margin: 6px 6px; border-radius: 12px; }
}
@media (prefers-reduced-motion: reduce) {
.bubble.floating:not(.dragging) { animation: none; }
.bubble { transition: none; }
}
/* === Multi-indicator overhaul === */
html, body { font-family: var(--cartoon); }
.brand small, .seg button, .btn, .btn-ind, .axis-hint, .crack-help,
.coin-panel, .coin-item, .detail-sheet, .status-line, .y-rail span,
.drawer, .auth-row, .ind-check, input, label, .alarm-btn, .gear-btn {
font-family: var(--cartoon) !important;
}
.brand small { font-weight: 500; opacity: 0.85; }
/* Always seawater canvas (was RSI-only) */
.canvas-frame {
background: linear-gradient(180deg, rgba(186,232,245,0.88) 0%, rgba(168,224,238,0.82) 40%, rgba(145,210,230,0.78) 100%);
border-color: #9ad0e4;
box-shadow: 0 8px 24px rgba(42,159,196,0.14), 0 2px 8px rgba(31,21,32,0.05);
transition: background 1.2s ease, box-shadow 1.2s ease, border-color 1.2s ease;
}
.canvas-frame::before {
background:
linear-gradient(180deg, rgba(255,255,255,0.35) 0%, transparent 28%, transparent 72%, rgba(42,159,196,0.12) 100%),
radial-gradient(ellipse 60% 45% at 50% 40%, rgba(255,255,255,0.45) 0%, transparent 70%),
repeating-linear-gradient(95deg, transparent 0 18px, rgba(255,255,255,0.06) 18px 19px);
}
/* Sentiment tint: --heat 0=ice blue → 1=hot red */
.canvas-frame::after {
content: ""; position: absolute; inset: 0; pointer-events: none; z-index: 0;
background: linear-gradient(180deg,
rgba(198,40,40, calc(var(--heat, 0.35) * 0.28)) 0%,
transparent 45%,
rgba(21,101,192, calc((1 - var(--heat, 0.35)) * 0.32)) 100%);
transition: background 1.4s ease, opacity 1.4s ease;
mix-blend-mode: soft-light;
opacity: 0.95;
}
.y-rail {
background: linear-gradient(90deg, rgba(186,232,245,0.95), transparent);
}
.lane-guides i { border-top-color: rgba(42, 159, 196, 0.28); }
/* Indicator peer toggles: blue idle, orange-red selected */
.toolbar-stack { display: flex; flex-direction: column; gap: 6px; width: 100%; }
.ind-row {
display: flex; align-items: center; gap: 8px;
flex-wrap: nowrap; justify-content: flex-start;
width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch;
padding-bottom: 2px;
}
.ind-item { display: inline-flex; align-items: center; gap: 3px; flex-shrink: 0; }
.btn-ind {
appearance: none; border: 2px solid #5ec8e8; cursor: pointer;
display: inline-flex; align-items: center; gap: 5px;
padding: 5px 11px 5px 7px; border-radius: 999px;
background: linear-gradient(160deg, #e8f8fd 0%, #b8e8f5 55%, #8ad4ec 100%);
color: #0a5f7a; font-weight: 800; font-size: 12px; letter-spacing: 0.03em;
box-shadow: 0 2px 10px rgba(77,187,235,0.35), inset 0 1px 0 rgba(255,255,255,0.7);
transition: transform .12s, box-shadow .15s, background .2s, border-color .2s, color .2s;
flex-shrink: 0;
}
.btn-ind:hover { transform: translateY(-1px); }
.btn-ind .ind-ico {
width: 20px; height: 20px; border-radius: 50%;
background: radial-gradient(circle at 35% 30%, #fff 0%, #7fd4f0 45%, #2a9fc4 100%);
display: inline-flex; align-items: center; justify-content: center;
font-size: 9px; font-weight: 900; color: #0a5f7a;
}
.btn-ind.on {
border-color: #e65100;
background: linear-gradient(160deg, #ffcc80 0%, #ff8a50 45%, #e64a19 100%);
color: #fff;
box-shadow: 0 3px 14px rgba(230,74,25,0.45), inset 0 1px 0 rgba(255,255,255,0.35);
}
.btn-ind.on .ind-ico {
background: radial-gradient(circle at 35% 30%, #fff8e1 0%, #ffe0b2 40%, #ffcc80 100%);
color: #bf360c;
}
.ind-check {
width: 16px; height: 16px; accent-color: #2e7d32; cursor: pointer;
flex-shrink: 0; margin: 0;
}
.ind-check:disabled { opacity: 0.35; cursor: default; }
#candle-seg { display: none; }
body.ind-candle #horizon-seg { display: none !important; }
body.ind-candle #candle-seg { display: flex; }
body:not(.ind-candle) #candle-seg { display: none; }
body.ind-vol .bubble .crack { display: block; }
body:not(.ind-vol) .bubble .crack { display: none; }
/* Tools row under indicators (right-aligned); drawers anchor here */
.tools-row {
position: relative; z-index: 35;
display: flex; align-items: center; justify-content: flex-end; gap: 8px;
width: 100%;
}
.gear-btn, .alarm-btn {
appearance: none; border: 2px solid #5ec8e8; cursor: pointer;
width: 40px; height: 40px; border-radius: 12px;
background: linear-gradient(160deg, #e8f8fd, #8ad4ec);
color: #0a5f7a; font-size: 18px; font-weight: 800;
box-shadow: 0 3px 12px rgba(77,187,235,0.35);
display: grid; place-items: center;
}
.alarm-btn { border-color: #ff8a65; background: linear-gradient(160deg, #ffe0b2, #ffab91); color: #bf360c; }
.gear-btn:hover, .alarm-btn:hover { transform: translateY(-1px); }
.drawer {
display: none; position: absolute; right: 0; top: calc(100% + 6px); width: min(280px, 78vw);
max-height: min(70vh, 420px); overflow: auto;
background: rgba(255,252,248,0.98); border: 1px solid #9ad0e4;
border-radius: 14px; padding: 12px; box-shadow: 0 12px 28px rgba(31,21,32,0.16);
z-index: 40;
}
.drawer.open { display: block; }
.drawer h3 { font-size: 14px; margin-bottom: 8px; color: #0a5f7a; }
.drawer .row { margin: 8px 0; }
.drawer label { display: flex; justify-content: space-between; font-size: 12px; color: var(--text-muted); margin-bottom: 2px; }
.drawer input[type=range] { width: 100%; accent-color: #e64a19; }
.drawer .val { color: #e64a19; font-weight: 800; }
.auth-wrap {
margin-left: auto;
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 4px;
flex: 0 0 auto;
max-width: min(168px, 42vw);
min-width: 0;
}
.auth-row {
display: flex; align-items: center; gap: 6px; flex-wrap: nowrap;
justify-content: flex-end; margin: 0;
max-width: 100%;
}
.auth-pill {
appearance: none; border: 1px solid var(--border); background: #fff;
padding: 4px 10px; border-radius: 999px; font-size: 11px; font-weight: 700;
cursor: pointer; color: var(--text-muted); white-space: nowrap;
flex: 0 0 auto;
}
.auth-pill.on { background: #e8f8fd; border-color: #5ec8e8; color: #0a5f7a; }
.auth-pill.x-login {
background: #000; color: #fff; border-color: #000;
display: inline-flex; align-items: center; gap: 4px;
max-width: 108px;
min-width: 0;
overflow: hidden;
}
.auth-pill.x-login.on {
background: #111; border-color: #333;
}
.auth-pill.x-login svg { flex: 0 0 auto; }
#btn-x-label {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
min-width: 0;
max-width: 72px;
}
.auth-note {
font-size: 10px; color: var(--text-dim);
text-align: right; line-height: 1.3;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Logged-in: hide Guest to keep the corner compact */
.auth-wrap.is-x #btn-guest { display: none; }
.auth-wrap.is-x .auth-pill.x-login { max-width: 120px; }
.auth-wrap.is-x #btn-x-label { max-width: 88px; }
/* Resonance aura: fireball (animated bottom burn) / ice-seal (static) */
.bubble .aura {
position: absolute; inset: -28%; border-radius: 50%;
pointer-events: none; z-index: 6; opacity: 0;
transition: opacity .3s;
overflow: visible;
}
.bubble.aura-hot .aura,
.bubble.aura-cold .aura { opacity: 1; }
.bubble .aura svg { width: 100%; height: 100%; display: block; overflow: visible; }
.bubble.aura-hot {
box-shadow:
inset 0 0 18px 4px rgba(255, 236, 179, 0.55),
inset 0 -14px 22px rgba(255, 87, 34, 0.35),
0 0 22px 6px rgba(255, 140, 0, 0.65),
0 0 48px 14px rgba(255, 60, 0, 0.35);
}
.bubble.aura-cold {
box-shadow:
inset 0 0 16px 6px rgba(227, 242, 253, 0.7),
inset 0 -10px 18px rgba(3, 169, 244, 0.35),
0 0 18px 5px rgba(129, 212, 250, 0.7),
0 0 36px 10px rgba(2, 119, 189, 0.3);
}
/* Flame tongues rise & flicker — strongest at bottom */
.bubble.aura-hot .aura .flame-tongues { transform-origin: 50% 78%; }
.bubble.aura-hot .aura .ft1 { animation: flame-burn 0.55s ease-in-out infinite alternate; }
.bubble.aura-hot .aura .ft2 { animation: flame-burn 0.42s ease-in-out infinite alternate-reverse; animation-delay: -0.12s; }
.bubble.aura-hot .aura .ft3 { animation: flame-burn 0.68s ease-in-out infinite alternate; animation-delay: -0.28s; }
.bubble.aura-hot .aura .embers { animation: ember-drift 1.4s linear infinite; }
@keyframes flame-burn {
0% { transform: translateY(4%) scaleY(0.92) scaleX(1.02); opacity: 0.82; }
100% { transform: translateY(-6%) scaleY(1.12) scaleX(0.96); opacity: 1; }
}
@keyframes ember-drift {
0% { transform: translateY(0); opacity: 0.9; }
100% { transform: translateY(-10%); opacity: 0.35; }
}
.bubble { transition: top .55s cubic-bezier(.22,.61,.36,1), box-shadow .15s; }
.brand-line {
display: inline-flex; align-items: center; gap: 6px; flex-wrap: wrap;
}
.help-q {
appearance: none; border: 1.5px solid #5ec8e8; background: #e8f8fd;
color: #0a5f7a; width: 20px; height: 20px; border-radius: 50%;
font-size: 12px; font-weight: 900; line-height: 1; cursor: pointer;
display: inline-grid; place-items: center; padding: 0; flex-shrink: 0;
font-family: var(--cartoon);
}
.help-q[aria-expanded="true"] {
background: #ff8a50; border-color: #e65100; color: #fff;
}
.model-help {
margin-top: 8px; padding: 10px 12px; border-radius: 12px;
background: rgba(255,252,248,0.98); border: 1px solid #9ad0e4;
box-shadow: 0 8px 20px rgba(31,21,32,0.12);
font-size: 12px; line-height: 1.55; color: var(--text-muted);
max-width: min(520px, 92vw); position: relative; z-index: 40;
}
.model-help[hidden] { display: none !important; }
.model-help strong { color: #0a5f7a; }
.model-help .mh-close {
appearance: none; border: none; background: transparent;
color: var(--text-dim); font-size: 16px; font-weight: 800;
position: absolute; right: 8px; top: 4px; cursor: pointer;
}
.ind-check.spacer {
width: 16px; height: 16px; visibility: hidden; pointer-events: none;
flex-shrink: 0; display: inline-block;
}
.heat-badge {
position: absolute; left: 62px; top: 8px; z-index: 4; pointer-events: none;
font-size: 10px; font-weight: 800; padding: 3px 8px; border-radius: 999px;
background: rgba(255,255,255,0.75); color: #0a5f7a;
border: 1px solid rgba(154,208,228,0.8);
}
@media (max-width: 520px) {
/* 5 equal columns so MACD is never clipped */
.ind-row {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 4px;
overflow: visible;
width: 100%;
}
.ind-item {
flex-direction: column;
align-items: center;
gap: 2px;
min-width: 0;
width: 100%;
}
.ind-check { width: 14px; height: 14px; order: -1; }
.ind-check.spacer { width: 14px; height: 14px; }
.btn-ind {
width: 100%;
justify-content: center;
padding: 4px 2px;
font-size: 10px;
gap: 2px;
min-width: 0;
}
.btn-ind .ind-ico { width: 14px; height: 14px; font-size: 7px; flex-shrink: 0; }
.btn-ind span:not(.ind-ico) {
overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 100%;
}
.gear-btn, .alarm-btn { width: 34px; height: 34px; font-size: 15px; }
.crack-help { font-size: 11px; max-height: 3.2em; overflow: hidden; }
.horizon-row .seg { width: 100%; }
.horizon-row .seg button { flex: 1; min-width: 0; padding: 6px 4px; font-size: 12px; }
}
</style>
</head>
<body>
<div class="app-shell">
<div class="paper-strip" aria-hidden="true"></div>
<header class="topbar">
<div class="topbar-row">
<div class="brand" id="brand-title">
<div class="brand-line">
<span id="brand-name">Timestral时序模型波动预测</span>
<button type="button" class="help-q" id="btn-model-help" aria-expanded="false" aria-controls="model-help" title="模型原理">?</button>
</div>
<small id="brand-sub">纵轴 = 现价在预测区间中的位置 · 横轴可拖</small>
<div class="model-help" id="model-help" hidden></div>
</div>
<div class="auth-wrap">
<button type="button" class="btn" id="btn-lang">English</button>
<div class="auth-row" id="auth-row">
<button type="button" class="auth-pill on" id="btn-guest" data-auth="guest">游客</button>
<button type="button" class="auth-pill x-login" id="btn-x-login" title="X login">
<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>
<span id="btn-x-label">X登录</span>
</button>
</div>
<div class="auth-note" id="auth-note">X登录偏好存在本机</div>
</div>
</div>
<div class="coin-panel" id="coin-panel">
<div class="coin-panel-hd" id="coin-panel-hd" role="button" tabindex="0" aria-expanded="false">
<span class="lab" id="coin-panel-lab">币种列表</span>
<span class="meta" id="coin-panel-meta">已选 0</span>
<button type="button" class="btn" id="btn-coin-toggle" style="margin-left:0">展开</button>
</div>
<div class="coin-panel-bd" id="coin-panel-bd">
<div class="coin-grid" id="coin-grid"></div>
<div class="coin-actions">
<button type="button" class="btn" id="btn-coin-default">默认样例</button>
<button type="button" class="btn" id="btn-coin-all">全选前50</button>
<button type="button" class="btn" id="btn-coin-clear">清空</button>
</div>
</div>
</div>
<div class="topbar-row horizon-row">
<div class="seg" id="horizon-seg" role="tablist">
<button type="button" data-h="h1">1小时</button>
<button type="button" data-h="h24" class="on">24小时</button>
<button type="button" data-h="h7">一周</button>
</div>
<div class="seg" id="candle-seg" role="tablist" aria-label="Candle timeframe">
<button type="button" data-tf="15m">15 分钟</button>
<button type="button" data-tf="1h" class="on">1 小时</button>
<button type="button" data-tf="4h">4 小时</button>
</div>
<span class="axis-hint" id="axis-hint">上沿 ↑ · 下沿 ↓ · 触边裂痕</span>
</div>
<div class="topbar-row toolbar-stack">
<div class="ind-row" id="ind-bar">
<div class="ind-item">
<span class="ind-check spacer" aria-hidden="true"></span>
<button type="button" class="btn-ind on" data-ind="vol" id="btn-ind-vol" aria-pressed="true" title="VOL">
<span class="ind-ico">V</span><span data-i18n-ind="vol">波动</span>
</button>
</div>
<div class="ind-item">
<input type="checkbox" class="ind-check" data-res="rsi" id="chk-rsi" title="共振" />
<button type="button" class="btn-ind" data-ind="rsi" id="btn-ind-rsi" aria-pressed="false" title="RSI">
<span class="ind-ico">R</span><span>RSI</span>
</button>
</div>
<div class="ind-item">
<input type="checkbox" class="ind-check" data-res="ema" id="chk-ema" title="共振" />
<button type="button" class="btn-ind" data-ind="ema" id="btn-ind-ema" aria-pressed="false" title="EMA">
<span class="ind-ico">E</span><span>EMA</span>
</button>
</div>
<div class="ind-item">
<input type="checkbox" class="ind-check" data-res="bb" id="chk-bb" title="共振" />
<button type="button" class="btn-ind" data-ind="bb" id="btn-ind-bb" aria-pressed="false" title="BB">
<span class="ind-ico">B</span><span data-i18n-ind="bb">布林</span>
</button>
</div>
<div class="ind-item">
<input type="checkbox" class="ind-check" data-res="macd" id="chk-macd" title="共振" />
<button type="button" class="btn-ind" data-ind="macd" id="btn-ind-macd" aria-pressed="false" title="MACD">
<span class="ind-ico">M</span><span>MACD</span>
</button>
</div>
</div>
<div class="tools-row" id="tools-row">
<button type="button" class="alarm-btn" id="btn-alarms" title="报警阀值">🔔</button>
<button type="button" class="gear-btn" id="btn-settings" title="设置">⚙</button>
<div class="drawer" id="drawer-alarms">
<h3 id="alarm-title">报警阈值</h3>
<div class="row"><label>RSI 超买 <span class="val" id="v-a-ob">70</span></label>
<input type="range" id="a-ob" min="55" max="90" step="1" value="70" /></div>
<div class="row"><label>RSI 超卖 <span class="val" id="v-a-os">30</span></label>
<input type="range" id="a-os" min="10" max="45" step="1" value="30" /></div>
<div class="row"><label>EMA 偏离% <span class="val" id="v-a-ema">3.0</span></label>
<input type="range" id="a-ema" min="5" max="150" step="5" value="30" /></div>
<div class="row"><label>MACD 柱阈值 <span class="val" id="v-a-macd">0</span></label>
<input type="range" id="a-macd" min="0" max="50" step="1" value="0" /></div>
<div class="row" style="font-size:11px;color:var(--text-dim)" id="alarm-hint">布林:收盘突破上下轨即触发。勾选指标后重合信号触发冰峰。</div>
</div>
<div class="drawer" id="drawer-settings">
<h3 id="set-title">指标参数</h3>
<div class="row"><label>RSI <span class="val" id="v-rsi">14</span></label>
<input type="range" id="p-rsi" min="5" max="48" step="1" value="14" /></div>
<div class="row"><label>EMA <span class="val" id="v-ema">20</span></label>
<input type="range" id="p-ema" min="5" max="100" step="1" value="20" /></div>
<div class="row"><label>BB 周期 <span class="val" id="v-bbp">20</span></label>
<input type="range" id="p-bbp" min="5" max="50" step="1" value="20" /></div>
<div class="row"><label>BB 倍数 <span class="val" id="v-bbm">2.0</span></label>
<input type="range" id="p-bbm" min="10" max="40" step="1" value="20" /></div>
<div class="row"><label>MACD 快 <span class="val" id="v-mf">12</span></label>
<input type="range" id="p-mf" min="5" max="30" step="1" value="12" /></div>
<div class="row"><label>MACD 慢 <span class="val" id="v-ms">26</span></label>
<input type="range" id="p-ms" min="10" max="50" step="1" value="26" /></div>
<div class="row"><label>MACD 信号 <span class="val" id="v-msig">9</span></label>
<input type="range" id="p-msig" min="3" max="20" step="1" value="9" /></div>
</div>
</div>
</div>
<div class="crack-help" id="crack-help"></div>
</header>
<div class="stage">
<div class="canvas-frame" id="canvas-frame" style="--heat:0.35">
<div class="heat-badge" id="heat-badge">情绪 · —</div>
<div class="y-rail" aria-hidden="true">
<span class="hi" id="ylab-hi">预测上沿</span>
<span class="mid" id="ylab-mid">中心</span>
<span class="lo" id="ylab-lo">预测下沿</span>
</div>
<div class="lane-guides" id="lane-guides" aria-hidden="true"><i class="rsi-ob"></i><i class="center-line"></i><i class="rsi-os"></i></div>
<div class="bubble-layer" id="bubble-layer"></div>
</div>
<div class="detail-sheet" id="detail-sheet">
<div class="detail-inner">
<div class="detail-av" id="d-av"></div>
<div>
<div class="detail-name" id="d-name">—</div>
<div class="detail-handle" id="d-handle"></div>
</div>
<button type="button" class="detail-close" id="d-close" aria-label="关闭">×</button>
<div class="detail-body" id="d-body"></div>
</div>
</div>
</div>
<div class="status-line" id="status">加载中…</div>
</div>
<script>
(function () {
// Top ~50 by typical market cap; exclude USDT/USDC. XAU optional at end.
const COINS = [
{ id: 'BTC', inst: 'BTC-USDT', rgb: '247,147,26', icon: 'btc' },
{ id: 'ETH', inst: 'ETH-USDT', rgb: '98,126,234', icon: 'eth' },
{ id: 'BNB', inst: 'BNB-USDT', rgb: '243,186,47', icon: 'bnb' },
{ id: 'XRP', inst: 'XRP-USDT', rgb: '35,41,47', icon: 'xrp' },
{ id: 'SOL', inst: 'SOL-USDT', rgb: '153,69,255', icon: 'sol' },
{ id: 'DOGE', inst: 'DOGE-USDT', rgb: '195,166,54', icon: 'doge' },
{ id: 'ADA', inst: 'ADA-USDT', rgb: '0,51,173', icon: 'ada' },
{ id: 'TRX', inst: 'TRX-USDT', rgb: '255,0,27', icon: 'trx' },
{ id: 'AVAX', inst: 'AVAX-USDT', rgb: '232,65,66', icon: 'avax' },
{ id: 'LINK', inst: 'LINK-USDT', rgb: '43,90,217', icon: 'link' },
{ id: 'TON', inst: 'TON-USDT', rgb: '0,136,204', icon: 'ton' },
{ id: 'SHIB', inst: 'SHIB-USDT', rgb: '255,160,61', icon: 'shib' },
{ id: 'DOT', inst: 'DOT-USDT', rgb: '230,0,122', icon: 'dot' },
{ id: 'BCH', inst: 'BCH-USDT', rgb: '141,208,98', icon: 'bch' },
{ id: 'NEAR', inst: 'NEAR-USDT', rgb: '0,0,0', icon: 'near' },
{ id: 'LTC', inst: 'LTC-USDT', rgb: '191,191,191', icon: 'ltc' },
{ id: 'POL', inst: 'POL-USDT', rgb: '130,71,229', icon: 'matic' },
{ id: 'UNI', inst: 'UNI-USDT', rgb: '255,0,122', icon: 'uni' },
{ id: 'ICP', inst: 'ICP-USDT', rgb: '41,170,226', icon: 'icp' },
{ id: 'APT', inst: 'APT-USDT', rgb: '0,0,0', icon: 'apt' },
{ id: 'ATOM', inst: 'ATOM-USDT', rgb: '46,49,72', icon: 'atom' },
{ id: 'XLM', inst: 'XLM-USDT', rgb: '0,0,0', icon: 'xlm' },
{ id: 'FIL', inst: 'FIL-USDT', rgb: '0,145,234', icon: 'fil' },
{ id: 'ARB', inst: 'ARB-USDT', rgb: '40,160,240', icon: 'arb' },
{ id: 'OP', inst: 'OP-USDT', rgb: '255,4,32', icon: 'op' },
{ id: 'HBAR', inst: 'HBAR-USDT', rgb: '0,0,0', icon: 'hbar' },
{ id: 'VET', inst: 'VET-USDT', rgb: '21,183,183', icon: 'vet' },
{ id: 'INJ', inst: 'INJ-USDT', rgb: '0,240,200', icon: 'inj' },
{ id: 'IMX', inst: 'IMX-USDT', rgb: '0,0,0', icon: 'imx' },
{ id: 'AAVE', inst: 'AAVE-USDT', rgb: '183,104,255', icon: 'aave' },
{ id: 'GRT', inst: 'GRT-USDT', rgb: '103,68,204', icon: 'grt' },
{ id: 'ALGO', inst: 'ALGO-USDT', rgb: '0,0,0', icon: 'algo' },
{ id: 'SAND', inst: 'SAND-USDT', rgb: '0,174,239', icon: 'sand' },
{ id: 'MANA', inst: 'MANA-USDT', rgb: '255,43,142', icon: 'mana' },
{ id: 'AXS', inst: 'AXS-USDT', rgb: '0,81,255', icon: 'axs' },
{ id: 'THETA', inst: 'THETA-USDT', rgb: '46,217,193', icon: 'theta' },
{ id: 'EOS', inst: 'EOS-USDT', rgb: '0,0,0', icon: 'eos' },
{ id: 'XTZ', inst: 'XTZ-USDT', rgb: '44,125,247', icon: 'xtz' },
{ id: 'FLOW', inst: 'FLOW-USDT', rgb: '0,239,139', icon: 'flow' },
{ id: 'EGLD', inst: 'EGLD-USDT', rgb: '0,0,0', icon: 'egld' },
{ id: 'SUI', inst: 'SUI-USDT', rgb: '76,162,255', icon: 'sui' },
{ id: 'PEPE', inst: 'PEPE-USDT', rgb: '62,168,62', icon: 'pepe' },
{ id: 'WLD', inst: 'WLD-USDT', rgb: '0,0,0', icon: 'wld' },
{ id: 'FET', inst: 'FET-USDT', rgb: '28,48,112', icon: 'fet' },
{ id: 'RNDR', inst: 'RENDER-USDT', rgb: '0,0,0', icon: 'rndr' },
{ id: 'STX', inst: 'STX-USDT', rgb: '85,70,237', icon: 'stx' },
{ id: 'RUNE', inst: 'RUNE-USDT', rgb: '35,212,185', icon: 'rune' },
{ id: 'KAS', inst: 'KAS-USDT', rgb: '112,199,152', icon: 'kas' },
{ id: 'MKR', inst: 'MKR-USDT', rgb: '26,171,155', icon: 'mkr' },
{ id: 'XAU', inst: 'XAU-USDT-SWAP', rgb: '212,175,55', icon: 'gold', label: { zh: '黄金', en: 'Gold' } },
];
const DEFAULT_SELECTED = ['BTC','ETH','BNB','XRP','SOL','TRX','NEAR','DOGE','LINK','ADA','XAU'];
const ICON_CDN = 'https://cdn.jsdelivr.net/gh/spothq/cryptocurrency-icons@master/128/color/';
const SQRT7 = Math.sqrt(7);
const EDGE = 0.08;
const LS_SEL = 'vol-bubble-coins';
const I18N = {
zh: {
title: 'Timestral时序模型波动预测',
modelHelpTitle: '模型原理',
modelHelp: '<button type="button" class="mh-close" id="btn-model-help-close" aria-label="关闭">×</button><strong>Timestral 时序模型波动预测</strong><br>用 Timestral-5M 学习每根 1 小时 K 线的「高低振幅」(log(high/low)),再把未来 24 根小时的振幅期望合成为一段波动率。页面上的泡泡纵轴 = 现价落在该预测价格带里的位置:靠上沿 / 下沿越近裂痕越满。<br>• <b>1 小时 / 24 小时</b>:模型直接给出的价格带<br>• <b>一周</b>:由 24 小时半宽按 √t 时间尺度外推(不是另训一周模型)<br>• 命中勾选区展示历史「实际高低是否落在预测带内」;裂痕与火球 / 冰封仅作风险视觉提示,不是买卖信号。',
sub: '纵轴 = 现价在预测区间中的位置 · 横轴可拖',
h1: '1小时', h24: '24小时', h7: '一周',
hi: '预测上沿', lo: '预测下沿', hint: '上沿 ↑ · 下沿 ↓ · 触边裂痕',
band: '预测区间', pos: '现价在区间位置', until: '有效至',
chk: '预测准不准', rH: '上一个小时', rY: '昨天全天', r24: '最近 24 小时', r7: '最近 7 天', r30: '最近一个月',
inN: (h,n) => `${h}/${n} 落在区间内`,
mk: '✓ 都在区间内 ↑ 破上沿 ↓ 破下沿 ↕ 两边都破',
disc: '只预测晃多大,不预测涨跌;一周 = 24h 半宽 × √7(时间外推,非单独模型)。不构成投资建议。',
loading: '加载中…', loaded: n => `已加载 ${n} 个有数据币种 · 价格约 20s 刷新 · 静态样例数据`,
loadedReady: (n, m) => `已就绪 ${n} / 已选 ${m} · 其余热身中`,
warming: '热身中',
stale: '样例数据较旧;部署后接实时 API。',
lang: 'English', center: '中心价', method7: '一周区间由 √t 从 24h 外推',
bt: '(回测)', lv: '(实盘)',
mUp: '突破上沿', mDn: '跌破下沿', mBoth: '两边都破',
noData: '暂无该币预测区间(无 state 样例)',
coinLab: '币种列表', coinMeta: n => `已选 ${n} / ${COINS.length}`,
coinOpen: '展开', coinClose: '收起',
detailEmptyTitle: '点选气泡查看详情',
detailEmptySub: '底部栏固定 · 画布高度不变',
detailEmptyBody: '选择上方气泡后,这里显示预测区间、现价位置与历史命中。关闭仅取消选中,不会收起本栏。',
coinDef: '默认样例', coinAll: '全选前50', coinClear: '清空',
hasData: '有区间', noBand: '无区间',
crackHelp: '<strong>泡泡裂痕是什么:</strong>裂痕表示现价逼近该时段(1h / 24h / 1周)预测波动区间的上下沿;裂得越满,越接近或触及边界,突破该预测区间的可能性越高。中间无裂 = 仍在区间中部。石头缝式不规则裂纹仅作视觉提示,不是买卖信号。',
na: 'N/A',
rsiBtn: 'RSI',
volBack: '回预测',
rsiTf15: '15 分钟', rsiTf1h: '1 小时', rsiTf4h: '4 小时',
rsiHi: '超买 70+', rsiMid: '50', rsiLo: '超卖 30-',
rsiHint: '上 = 超买 · 中 = 50 · 下 = 超卖',
rsiSub: '纵轴 = RSI(14) · 横轴可拖 · 海水底色',
rsiTitle: 'RSI 泡泡图 · 相对强弱',
rsiCrackHelp: '<strong>RSI 泡泡:</strong>竖直位置 = Wilder RSI(14)。越靠上越接近超买(70+),越靠下越接近超卖(30-)。中间约 50 为中性。不构成投资建议。',
rsiDisc: 'RSI 由 OKX K 线在浏览器本地计算(Wilder 14),不经过 Timestral 预测。仅供参考,不构成投资建议。',
rsiLoaded: n => `RSI 模式 · ${n} 个币已算好 · K 线约 60s 刷新`,
rsiVal: 'RSI(14)',
rsiMeaning: '解读',
rsiOb: '超买区(≥70)——短期偏热,回撤概率升高',
rsiOs: '超卖区(≤30)——短期偏冷,反弹概率升高',
rsiNeu: '中性区(30–70)——动能不极端',
rsiNoData: '暂无 RSI(K 线拉取失败或样本不足)',
rsiDetailEmpty: '选择上方气泡后,这里显示 RSI(14)、周期与超买/超卖解读。',
volBtn: '波动', bbBtn: '布林',
guest: '游客', loginReg: 'X登录',
authLocalNote: 'X登录偏好存在本机',
authXNeed: 'X登录未就绪(Space 密钥)',
authXOk: '偏好已云同步',
authXUser: '偏好已云同步',
setTitle: '指标参数', alarmTitle: '报警阈值',
alarmHint: '布林:收盘突破上下轨即触发。勾选指标后重合信号触发冰峰。',
heatLab: h => `情绪 · ${h}`,
heatCold: '冰点', heatHot: '火热', heatMid: '中性',
emaHi: '远高于 EMA', emaMid: '贴近 EMA', emaLo: '远低于 EMA',
emaHint: '上 = 价远高于均线 · 下 = 远低于',
emaSub: '纵轴 = 价格相对 EMA 偏离 · 横轴可拖',
emaTitle: 'EMA 泡泡图 · 移动平均',
emaCrackHelp: '<strong>EMA 泡泡:</strong>竖直位置 = 现价相对 EMA 的偏离(裁剪后映射)。越上越贵于均线,越下越便宜。不构成投资建议。',
emaDisc: 'EMA 由 OKX K 线在浏览器本地计算,不经过 Timestral。仅供参考。',
emaVal: '相对 EMA',
emaLoaded: n => `EMA 模式 · ${n} 个币已算好 · K 线约 60s`,
emaDetailEmpty: '选择气泡查看价格相对 EMA 的偏离。',
bbHi: '上轨外', bbMid: '带内中轨', bbLo: '下轨外',
bbHint: '上 = 突破上轨 · 下 = 跌破下轨',
bbSub: '纵轴 = 布林带内相对位置 · 横轴可拖',
bbTitle: '布林带泡泡图',
bbCrackHelp: '<strong>布林带泡泡:</strong>竖直位置 = (收盘−下轨)/(上轨−下轨)。越上越贴近/突破上轨,越下越贴近/突破下轨。不构成投资建议。',
bbDisc: '布林带由 OKX K 线本地计算。仅供参考,不构成投资建议。',
bbVal: '布林位置',
bbLoaded: n => `布林模式 · ${n} 个币已算好 · K 线约 60s`,
bbDetailEmpty: '选择气泡查看布林带位置与突破状态。',
macdHi: '柱线偏多', macdMid: '零轴', macdLo: '柱线偏空',
macdHint: '上 = 多头柱 · 下 = 空头柱',
macdSub: '纵轴 = MACD 柱线归一化 · 横轴可拖',
macdTitle: 'MACD 泡泡图',
macdCrackHelp: '<strong>MACD 泡泡:</strong>竖直位置 = 柱线相对近期幅度归一化。上偏多、下偏空。不构成投资建议。',
macdDisc: 'MACD 由 OKX K 线本地计算。仅供参考,不构成投资建议。',
macdVal: 'MACD 柱',
macdLoaded: n => `MACD 模式 · ${n} 个币已算好 · K 线约 60s`,
macdDetailEmpty: '选择气泡查看 MACD 柱线与交叉。',
indLoaded: (name, n) => `${name} · ${n} 个币就绪`,
resonateOn: '共振开',
warnMany: '已选较多币种,布局可能拥挤。',
},
en: {
title: 'Timestral volatility forecast',
modelHelpTitle: 'How it works',
modelHelp: '<button type="button" class="mh-close" id="btn-model-help-close" aria-label="Close">×</button><strong>Timestral volatility forecast</strong><br>Timestral-5M models each 1H bar\'s log(high/low) range, then aggregates the next 24 hourly expectations into a volatility band. Bubble Y = where spot sits inside that band; nearer the rim → fuller cracks.<br>• <b>1h / 24h</b>: model price bands<br>• <b>1 week</b>: 24h half-width scaled by √t (not a separate weekly model)<br>• Hit marks show whether actual high/low stayed inside the band. Cracks and fire/ice auras are visual risk cues, not trade signals.',
sub: 'Y = price in forecast band · drag horizontally',
h1: '1h', h24: '24h', h7: '1w',
hi: 'Upper band', lo: 'Lower band', hint: 'Top = hi · Bottom = lo · Edge cracks',
band: 'Forecast band', pos: 'Price in band', until: 'Valid until',
chk: 'How past bands did', rH: 'Last hour', rY: 'Yesterday', r24: 'Last 24 hours', r7: 'Last 7 days', r30: 'Last month',
inN: (h,n) => `${h}/${n} inside`,
mk: '✓ inside ↑ broke above ↓ broke below ↕ both',
disc: 'Forecasts swing size, not direction. Week = 24h half-width × √7 (time-scaling, not a separate model). Not investment advice.',
loading: 'Loading…', loaded: n => `${n} coins with band data · price ~20s · sample static data`,
loadedReady: (n, m) => `Ready ${n} / selected ${m} · others warming`,
warming: 'Warming',
stale: 'Sample data is stale; live API after Docker Space deploy.',
lang: '中文', center: 'Center', method7: 'Week band = √t from 24h',
bt: ' (backtest)', lv: ' (live)',
mUp: 'broke above', mDn: 'broke below', mBoth: 'broke both',
noData: 'No forecast band for this coin (no state sample)',
coinLab: 'Coins', coinMeta: n => `${n} / ${COINS.length} selected`,
coinOpen: 'Expand', coinClose: 'Collapse',
detailEmptyTitle: 'Tap a bubble for details',
detailEmptySub: 'Bottom dock fixed · canvas height locked',
detailEmptyBody: 'After you select a bubble, this dock shows the forecast band, price position, and hit history. Close only clears selection — it does not hide this bar.',
coinDef: 'Default sample', coinAll: 'Select all ~50', coinClear: 'Clear',
hasData: 'has band', noBand: 'no band',
crackHelp: '<strong>What cracks mean:</strong> Cracks appear when price nears the predicted volatility band edge for the selected horizon (1h / 24h / 1w). Fuller rupture ≈ closer to or at the edge — higher chance of breaking out of that forecast range. No crack in the middle = still mid-band. Irregular stone-fissure look is a visual cue only, not a trade signal.',
na: 'N/A',
rsiBtn: 'RSI',
volBack: 'Back',
rsiTf15: '15m', rsiTf1h: '1h', rsiTf4h: '4h',
rsiHi: 'Overbought 70+', rsiMid: '50', rsiLo: 'Oversold 30-',
rsiHint: 'Top = OB · Mid = 50 · Bottom = OS',
rsiSub: 'Y = RSI(14) · drag X · seawater canvas',
rsiTitle: 'RSI bubbles · relative strength',
rsiCrackHelp: '<strong>RSI bubbles:</strong> Vertical position = Wilder RSI(14). Higher ≈ overbought (70+); lower ≈ oversold (30-); mid ≈ 50 neutral. Not investment advice.',
rsiDisc: 'RSI is computed in-browser from OKX candles (Wilder 14), not from Timestral forecasts. For reference only — not investment advice.',
rsiLoaded: n => `RSI mode · ${n} coins ready · candles ~60s`,
rsiVal: 'RSI(14)',
rsiMeaning: 'Reading',
rsiOb: 'Overbought (≥70) — heat elevated; pullback risk up',
rsiOs: 'Oversold (≤30) — cold stretch; bounce risk up',
rsiNeu: 'Neutral (30–70) — momentum not extreme',
rsiNoData: 'No RSI yet (candle fetch failed or too few bars)',
rsiDetailEmpty: 'Select a bubble to see RSI(14), timeframe, and overbought/oversold reading.',
volBtn: 'Vol', bbBtn: 'BB',
guest: 'Guest', loginReg: 'X login',
authLocalNote: 'X login prefs stay on this device',
authXNeed: 'X login not ready (Space secrets)',
authXOk: 'Prefs synced',
authXUser: 'Prefs synced',
setTitle: 'Indicator params', alarmTitle: 'Alarm thresholds',
alarmHint: 'Bollinger: close outside bands triggers. Checked indicators with aligned signals → ice peak.',
heatLab: h => `Heat · ${h}`,
heatCold: 'Ice', heatHot: 'Hot', heatMid: 'Neutral',
emaHi: 'Far above EMA', emaMid: 'Near EMA', emaLo: 'Far below EMA',
emaHint: 'Top = price ≫ EMA · Bottom = ≪ EMA',
emaSub: 'Y = % distance to EMA · drag X',
emaTitle: 'EMA bubbles · moving average',
emaCrackHelp: '<strong>EMA bubbles:</strong> Y = clipped % distance of price vs EMA. Higher = above MA. Not investment advice.',
emaDisc: 'EMA is computed in-browser from OKX candles. For reference only.',
emaVal: 'vs EMA',
emaLoaded: n => `EMA · ${n} coins · candles ~60s`,
emaDetailEmpty: 'Select a bubble to see price vs EMA.',
bbHi: 'Above upper', bbMid: 'Mid band', bbLo: 'Below lower',
bbHint: 'Top = upper break · Bottom = lower break',
bbSub: 'Y = position in Bollinger band · drag X',
bbTitle: 'Bollinger bubbles',
bbCrackHelp: '<strong>Bollinger bubbles:</strong> Y = (close−lower)/(upper−lower). Not investment advice.',
bbDisc: 'Bollinger Bands from OKX candles in-browser. For reference only.',
bbVal: 'BB position',
bbLoaded: n => `BB · ${n} coins · candles ~60s`,
bbDetailEmpty: 'Select a bubble for Bollinger position.',
macdHi: 'Hist bullish', macdMid: 'Zero', macdLo: 'Hist bearish',
macdHint: 'Top = bull hist · Bottom = bear hist',
macdSub: 'Y = normalized MACD histogram · drag X',
macdTitle: 'MACD bubbles',
macdCrackHelp: '<strong>MACD bubbles:</strong> Y = histogram normalized to recent range. Not investment advice.',
macdDisc: 'MACD from OKX candles in-browser. For reference only.',
macdVal: 'MACD hist',
macdLoaded: n => `MACD · ${n} coins · candles ~60s`,
macdDetailEmpty: 'Select a bubble for MACD histogram.',
indLoaded: (name, n) => `${name} · ${n} coins ready`,
resonateOn: 'Resonance on',
warnMany: 'Many coins selected; layout may be crowded.',
},
};
let lang = localStorage.getItem('vol-bubble-lang') || 'zh';
let horizon = localStorage.getItem('vol-bubble-h') || 'h24';
// Peer indicators — switching only moves bubble Y on the same seawater canvas
let indicator = localStorage.getItem('vol-bubble-ind') || (
localStorage.getItem('vol-bubble-mode') === 'rsi' ? 'rsi' : 'vol'
); // vol|rsi|ema|bb|macd
let candleTf = localStorage.getItem('vol-bubble-candle-tf')
|| localStorage.getItem('vol-bubble-rsi-tf') || '1h';
const CANDLE_BAR = { '15m': '15m', '1h': '1H', '4h': '4H' };
function loadJSON(k, fallback) {
try { const v = JSON.parse(localStorage.getItem(k)); return v && typeof v === 'object' ? { ...fallback, ...v } : { ...fallback }; }
catch (_) { return { ...fallback }; }
}
function saveJSON(k, obj) { localStorage.setItem(k, JSON.stringify(obj)); }
let params = loadJSON('vol-bubble-params', {
rsi: 14, ema: 20, bbPeriod: 20, bbMult: 2, macdFast: 12, macdSlow: 26, macdSignal: 9,
});
let alarms = loadJSON('vol-bubble-alarms', {
rsiOb: 70, rsiOs: 30, emaPct: 3, macdHist: 0,
});
let resonate = loadJSON('vol-bubble-resonate', { rsi: false, ema: false, bb: false, macd: false });
let authMode = localStorage.getItem('vol-bubble-auth') || 'guest'; // guest | x
let authUser = localStorage.getItem('vol-bubble-x-user') || '';
let prefsCloud = loadJSON('vol-bubble-prefs', {});
let states = {};
let livePrice = {};
const warming = {}; // inst id -> warming (503 or null bands)
// Candle cache: key id|tf -> { closes, highs, lows, ts }
let candleCache = {};
// Derived per-coin metrics for current params: id -> { rsi, ema, bbY, bbUpper, bbLower, macdHist, signals }
let metrics = {};
let selected = null;
let positions = {};
let drag = null;
let zTop = 10;
let selectedIds = loadSelectedIds();
const isCandleInd = () => indicator !== 'vol';
const $ = id => document.getElementById(id);
const t = k => I18N[lang][k];
const xm = m => m === 'up' ? '↑' : m === 'down' ? '↓' : '↕';
const pdg = p => !(p > 0) ? 2 : p >= 1000 ? 0 : p >= 10 ? 2 : p >= 1 ? 4 : Math.min(8, 4 - Math.floor(Math.log10(p)));
const pf = (x, p) => {
if (x == null || !isFinite(x)) return '—';
const d = pdg(p);
return x.toLocaleString('en-US', { maximumFractionDigits: d, minimumFractionDigits: d });
};
function loadSelectedIds() {
try {
const raw = localStorage.getItem(LS_SEL);
if (raw) {
const arr = JSON.parse(raw);
if (Array.isArray(arr) && arr.length) {
const allow = new Set(COINS.map(c => c.id));
const filtered = arr.filter(id => allow.has(id)).slice(0, 50);
if (filtered.length) return new Set(filtered);
}
}
} catch (_) {}
return new Set(DEFAULT_SELECTED);
}
function saveSelectedIds() {
localStorage.setItem(LS_SEL, JSON.stringify([...selectedIds]));
persistPrefs();
}
function activeCoins() {
return COINS.filter(c => selectedIds.has(c.id));
}
function hashStr(s) {
let h = 2166136261;
for (let i = 0; i < s.length; i++) {
h ^= s.charCodeAt(i);
h = Math.imul(h, 16777619);
}
return h >>> 0;
}
function seededRng(seed) {
let s = seed >>> 0;
return () => {
s = (Math.imul(s, 1664525) + 1013904223) >>> 0;
return s / 4294967296;
};
}
/** Irregular stone-fissure polylines; seed stable per coin. */
function buildCrackSvg(coinId, intensity) {
const rnd = seededRng(hashStr(coinId + ':fissure'));
const W = 100, H = 100, cx = 50, cy = 50;
const mainN = 2 + Math.floor(rnd() * 2); // 2–3 main cracks
const paths = [];
function jagLine(x0, y0, x1, y1, segs, amp) {
const pts = [[x0, y0]];
for (let i = 1; i < segs; i++) {
const t = i / segs;
const bx = x0 + (x1 - x0) * t;
const by = y0 + (y1 - y0) * t;
const nx = -(y1 - y0), ny = (x1 - x0);
const len = Math.hypot(nx, ny) || 1;
const j = (rnd() - 0.5) * 2 * amp * (0.4 + 0.6 * Math.sin(t * Math.PI));
pts.push([bx + (nx / len) * j, by + (ny / len) * j]);
}
pts.push([x1, y1]);
return pts;
}
function toPath(pts) {
return pts.map((p, i) => (i === 0 ? `M${p[0].toFixed(1)} ${p[1].toFixed(1)}` : `L${p[0].toFixed(1)} ${p[1].toFixed(1)}`)).join(' ');
}
function edgePoint(ang) {
// slightly inside circle rim
const r = 46 + rnd() * 2;
return [cx + Math.cos(ang) * r, cy + Math.sin(ang) * r];
}
for (let m = 0; m < mainN; m++) {
const a0 = rnd() * Math.PI * 2;
const span = Math.PI * (0.55 + rnd() * 0.7);
const a1 = a0 + span * (rnd() > 0.5 ? 1 : -1);
// start near mid, not perfect center
const sx = cx + (rnd() - 0.5) * 18;
const sy = cy + (rnd() - 0.5) * 18;
const [ex, ey] = edgePoint(a1);
const segs = 6 + Math.floor(rnd() * 5);
const amp = 3.5 + rnd() * 5 + intensity * 2;
const pts = jagLine(sx, sy, ex, ey, segs, amp);
const sw = (0.7 + intensity * 1.4 + rnd() * 0.5).toFixed(2);
paths.push(`<path d="${toPath(pts)}" stroke-width="${sw}" />`);
// branching micro-cracks near outer third
const branchCount = intensity > 0.35 ? 1 + Math.floor(rnd() * 2) : (rnd() > 0.5 ? 1 : 0);
for (let b = 0; b < branchCount; b++) {
const bi = Math.floor(pts.length * (0.55 + rnd() * 0.35));
const bp = pts[Math.min(bi, pts.length - 1)];
const bang = Math.atan2(bp[1] - cy, bp[0] - cx) + (rnd() - 0.5) * 1.4;
const br = 8 + rnd() * 14;
const bx1 = bp[0] + Math.cos(bang) * br;
const by1 = bp[1] + Math.sin(bang) * br;
const bpts = jagLine(bp[0], bp[1], bx1, by1, 3 + Math.floor(rnd() * 2), 2 + rnd() * 2);
const bsw = (0.35 + intensity * 0.55).toFixed(2);
paths.push(`<path class="micro" d="${toPath(bpts)}" stroke-width="${bsw}" />`);
}
}
// faint rim chips when near rupture
if (intensity > 0.55) {
for (let i = 0; i < 2 + Math.floor(rnd() * 2); i++) {
const ang = rnd() * Math.PI * 2;
const [e0x, e0y] = edgePoint(ang);
const inward = 6 + rnd() * 8;
const ix = e0x - Math.cos(ang) * inward + (rnd() - 0.5) * 3;
const iy = e0y - Math.sin(ang) * inward + (rnd() - 0.5) * 3;
const cpts = jagLine(e0x, e0y, ix, iy, 3, 1.5 + rnd());
paths.push(`<path class="micro" d="${toPath(cpts)}" stroke-width="${(0.4 + intensity * 0.4).toFixed(2)}" />`);
}
}
return `<svg viewBox="0 0 ${W} ${H}" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">${paths.join('')}</svg>`;
}
function ensureH7(now) {
if (!now) return null;
if (now.h7 && now.h7.lo != null && now.h7.hi != null) return now.h7;
const P = now.center, lo24 = now.h24 && now.h24.lo, hi24 = now.h24 && now.h24.hi;
if (!(P > 0) || !(lo24 > 0) || !(hi24 > 0)) return null;
const until = now.h24.until
? (() => {
const d = new Date(now.h24.until.replace(' ', 'T') + '+08:00');
if (isNaN(d)) return now.h24.until;
d.setTime(d.getTime() + 6 * 24 * 3600 * 1000);
const p = n => String(n).padStart(2, '0');
const bj = new Date(d.getTime());
return `${bj.getFullYear()}-${p(bj.getMonth()+1)}-${p(bj.getDate())} ${p(bj.getHours())}:${p(bj.getMinutes())}`;
})()
: null;
return {
lo: P * Math.pow(lo24 / P, SQRT7),
hi: P * Math.pow(hi24 / P, SQRT7),
until,
method: 'sqrt_t',
client: true,
};
}
/** Wilder RSI(period) from chronological closes (oldest → newest). */
function calcRsi(closes, period) {
period = period || params.rsi;
if (!closes || closes.length < period + 1) return null;
let avgGain = 0, avgLoss = 0;
for (let i = 1; i <= period; i++) {
const d = closes[i] - closes[i - 1];
if (d >= 0) avgGain += d; else avgLoss -= d;
}
avgGain /= period;
avgLoss /= period;
for (let i = period + 1; i < closes.length; i++) {
const d = closes[i] - closes[i - 1];
const gain = d > 0 ? d : 0;
const loss = d < 0 ? -d : 0;
avgGain = (avgGain * (period - 1) + gain) / period;
avgLoss = (avgLoss * (period - 1) + loss) / period;
}
if (avgLoss === 0) return avgGain === 0 ? 50 : 100;
const rs = avgGain / avgLoss;
return 100 - (100 / (1 + rs));
}
function calcEmaSeries(closes, period) {
if (!closes || closes.length < period) return null;
const k = 2 / (period + 1);
let ema = 0;
for (let i = 0; i < period; i++) ema += closes[i];
ema /= period;
const out = new Array(closes.length).fill(null);
out[period - 1] = ema;
for (let i = period; i < closes.length; i++) {
ema = closes[i] * k + ema * (1 - k);
out[i] = ema;
}
return out;
}
function lastEma(closes, period) {
const s = calcEmaSeries(closes, period);
if (!s) return null;
return s[s.length - 1];
}
// Y = clipped % distance of price vs EMA (±clipPct maps to 0..1, 0.5 = on EMA)
function yFracEma(price, ema, clipPct) {
if (!(price > 0) || !(ema > 0)) return 0.5;
clipPct = clipPct || 8;
const pct = ((price - ema) / ema) * 100;
const clipped = Math.max(-clipPct, Math.min(clipPct, pct));
return (clipped / clipPct + 1) / 2;
}
function calcBollinger(closes, period, mult) {
period = period || params.bbPeriod;
mult = mult != null ? mult : params.bbMult;
if (!closes || closes.length < period) return null;
const slice = closes.slice(-period);
const mean = slice.reduce((a, b) => a + b, 0) / period;
let varSum = 0;
for (const x of slice) varSum += (x - mean) * (x - mean);
const std = Math.sqrt(varSum / period);
const upper = mean + mult * std;
const lower = mean - mult * std;
const close = closes[closes.length - 1];
const width = upper - lower;
const y = width > 0 ? Math.max(0, Math.min(1, (close - lower) / width)) : 0.5;
return { mid: mean, upper, lower, close, y, breakUpper: close > upper, breakLower: close < lower };
}
function calcMacd(closes, fast, slow, signal) {
fast = fast || params.macdFast;
slow = slow || params.macdSlow;
signal = signal || params.macdSignal;
if (!closes || closes.length < slow + signal) return null;
const ef = calcEmaSeries(closes, fast);
const es = calcEmaSeries(closes, slow);
if (!ef || !es) return null;
const macdLine = [];
for (let i = 0; i < closes.length; i++) {
if (ef[i] == null || es[i] == null) macdLine.push(null);
else macdLine.push(ef[i] - es[i]);
}
const valid = macdLine.filter(x => x != null);
if (valid.length < signal) return null;
// Signal EMA on macd line values (skip nulls by building dense then map back)
const dense = [];
const idxMap = [];
for (let i = 0; i < macdLine.length; i++) {
if (macdLine[i] != null) { dense.push(macdLine[i]); idxMap.push(i); }
}
const sigSeries = calcEmaSeries(dense, signal);
if (!sigSeries) return null;
const last = dense.length - 1;
const macd = dense[last];
const sig = sigSeries[last];
const prevMacd = dense[last - 1];
const prevSig = sigSeries[last - 1];
if (macd == null || sig == null) return null;
const hist = macd - sig;
// Normalize hist vs recent abs max for Y mapping
let maxAbs = 1e-12;
for (let i = Math.max(0, dense.length - 40); i < dense.length; i++) {
const h = dense[i] - (sigSeries[i] != null ? sigSeries[i] : dense[i]);
maxAbs = Math.max(maxAbs, Math.abs(h));
}
const y = Math.max(0, Math.min(1, (hist / maxAbs + 1) / 2));
const crossUp = prevMacd != null && prevSig != null && prevMacd <= prevSig && macd > sig;
const crossDn = prevMacd != null && prevSig != null && prevMacd >= prevSig && macd < sig;
return { macd, signal: sig, hist, y, crossUp, crossDn };
}
function candleKey(id, tf) { return id + '|' + (tf || candleTf); }
async function fetchCandles(c, tf) {
tf = tf || candleTf;
const bar = CANDLE_BAR[tf] || '1H';
const key = candleKey(c.id, tf);
const cached = candleCache[key];
if (cached && cached.ts && (Date.now() - cached.ts) < 55000 && cached.closes && cached.closes.length > 30) {
return cached;
}
try {
const url = `https://www.okx.com/api/v5/market/candles?instId=${encodeURIComponent(c.inst)}&bar=${encodeURIComponent(bar)}&limit=100`;
const r = await fetch(url, { cache: 'no-store' });
if (!r.ok) return cached || null;
const j = await r.json();
const rows = (j && j.data) || [];
// OKX newest-first: [ts, o, h, l, c, ...]
const chrono = rows.slice().reverse();
const closes = chrono.map(row => parseFloat(row[4])).filter(x => x > 0);
const highs = chrono.map(row => parseFloat(row[2]));
const lows = chrono.map(row => parseFloat(row[3]));
const entry = { closes, highs, lows, ts: Date.now() };
candleCache[key] = entry;
return entry;
} catch (_) {
return cached || null;
}
}
function computeMetricsFor(c, candle) {
const closes = candle && candle.closes;
if (!closes || closes.length < 5) {
metrics[c.id] = null;
return null;
}
const rsi = calcRsi(closes, params.rsi);
const ema = lastEma(closes, params.ema);
const price = closes[closes.length - 1];
const emaPct = (ema > 0 && price > 0) ? ((price - ema) / ema) * 100 : null;
const bb = calcBollinger(closes, params.bbPeriod, params.bbMult);
const macd = calcMacd(closes, params.macdFast, params.macdSlow, params.macdSignal);
const sig = {};
if (rsi != null) {
if (rsi >= alarms.rsiOb) sig.rsi = 'hot';
else if (rsi <= alarms.rsiOs) sig.rsi = 'cold';
else sig.rsi = null;
}
if (emaPct != null) {
if (emaPct >= alarms.emaPct) sig.ema = 'hot';
else if (emaPct <= -alarms.emaPct) sig.ema = 'cold';
else sig.ema = null;
}
if (bb) {
if (bb.breakUpper) sig.bb = 'hot';
else if (bb.breakLower) sig.bb = 'cold';
else sig.bb = null;
}
if (macd) {
if (macd.crossUp) sig.macd = 'hot';
else if (macd.crossDn) sig.macd = 'cold';
else if (alarms.macdHist > 0) {
if (macd.hist >= alarms.macdHist) sig.macd = 'hot';
else if (macd.hist <= -alarms.macdHist) sig.macd = 'cold';
else sig.macd = null;
} else {
sig.macd = null;
}
}
const m = { rsi, ema, emaPct, price, bb, macd, sig };
metrics[c.id] = m;
return m;
}
function resonanceFor(id) {
const m = metrics[id];
if (!m || !m.sig) return null;
const checked = ['rsi', 'ema', 'bb', 'macd'].filter(k => resonate[k]);
if (checked.length < 2) return null;
const hot = checked.filter(k => m.sig[k] === 'hot');
const cold = checked.filter(k => m.sig[k] === 'cold');
if (hot.length >= 2) return 'hot';
if (cold.length >= 2) return 'cold';
return null;
}
function auraWrapSvg(kind, uid) {
uid = uid || 'g';
if (kind === 'hot') {
// Fireball: bright core + glass rim + bottom-heavy licking flames (CSS animates .ft*)
return `<svg viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<defs>
<radialGradient id="${uid}-core" cx="45%" cy="40%" r="55%">
<stop offset="0%" stop-color="#fffde7" stop-opacity="0.95"/>
<stop offset="35%" stop-color="#ffeb3b" stop-opacity="0.75"/>
<stop offset="70%" stop-color="#ff9100" stop-opacity="0.45"/>
<stop offset="100%" stop-color="#e65100" stop-opacity="0"/>
</radialGradient>
<radialGradient id="${uid}-halo" cx="50%" cy="50%" r="50%">
<stop offset="60%" stop-color="#ff5722" stop-opacity="0"/>
<stop offset="85%" stop-color="#ff6d00" stop-opacity="0.45"/>
<stop offset="100%" stop-color="#ffab00" stop-opacity="0.2"/>
</radialGradient>
</defs>
<circle cx="60" cy="60" r="58" fill="url(#${uid}-halo)"/>
<circle cx="60" cy="60" r="40" fill="url(#${uid}-core)"/>
<g class="flame-tongues ft1">
<path d="M38 95 C42 78 48 70 52 78 C54 68 58 62 60 72 C62 62 68 66 70 78 C74 70 82 78 78 95 C70 108 48 108 38 95Z" fill="#ff6d00" opacity="0.95"/>
<path d="M44 98 C48 86 52 80 55 88 C58 78 62 76 64 86 C68 80 74 88 70 100 C62 110 50 110 44 98Z" fill="#ffeb3b" opacity="0.9"/>
</g>
<g class="flame-tongues ft2">
<path d="M22 78 C28 62 36 58 40 68 C44 56 50 54 48 70 C52 64 56 74 50 86 C40 96 24 92 22 78Z" fill="#ff9100" opacity="0.92"/>
<path d="M78 78 C72 62 68 56 64 68 C60 54 56 58 58 72 C54 66 50 76 58 88 C68 96 84 92 78 78Z" fill="#ff9100" opacity="0.92"/>
<path d="M30 88 C34 76 40 74 42 82 C46 72 50 78 48 88 C44 96 32 98 30 88Z" fill="#fff59d" opacity="0.85"/>
<path d="M90 88 C86 76 80 74 78 82 C74 72 70 78 72 88 C76 96 88 98 90 88Z" fill="#fff59d" opacity="0.85"/>
</g>
<g class="flame-tongues ft3">
<path d="M48 28 C52 18 58 14 60 24 C62 14 70 18 66 30 C72 26 74 36 66 40 C60 34 54 36 48 28Z" fill="#ffab00" opacity="0.75"/>
<path d="M18 52 C24 44 32 46 30 56 C36 50 38 60 30 66 C22 70 12 62 18 52Z" fill="#ff5722" opacity="0.8"/>
<path d="M102 52 C96 44 88 46 90 56 C84 50 82 60 90 66 C98 70 108 62 102 52Z" fill="#ff5722" opacity="0.8"/>
</g>
<g class="embers" fill="#ffecb3">
<circle cx="34" cy="34" r="1.6" opacity="0.9"/><circle cx="86" cy="30" r="1.3" opacity="0.8"/>
<circle cx="24" cy="64" r="1.2" opacity="0.85"/><circle cx="96" cy="60" r="1.4" opacity="0.8"/>
<circle cx="50" cy="16" r="1.1" opacity="0.7"/><circle cx="70" cy="20" r="1.2" opacity="0.75"/>
<circle cx="42" cy="104" r="1.5" opacity="0.9"/><circle cx="78" cy="102" r="1.3" opacity="0.85"/>
</g>
<ellipse cx="72" cy="42" rx="9" ry="5" fill="#fff" opacity="0.35"/>
<circle cx="60" cy="60" r="36" fill="none" stroke="#ffe082" stroke-width="1.6" opacity="0.45"/>
</svg>`;
}
// Ice-seal: frosted glass sphere fully encased in static ice shell + crystals
return `<svg viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<defs>
<radialGradient id="${uid}-ice" cx="38%" cy="32%" r="68%">
<stop offset="0%" stop-color="#ffffff" stop-opacity="0.75"/>
<stop offset="40%" stop-color="#e1f5fe" stop-opacity="0.55"/>
<stop offset="75%" stop-color="#4fc3f7" stop-opacity="0.5"/>
<stop offset="100%" stop-color="#01579b" stop-opacity="0.45"/>
</radialGradient>
<linearGradient id="${uid}-rim" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#e3f2fd" stop-opacity="1"/>
<stop offset="55%" stop-color="#29b6f6" stop-opacity="0.85"/>
<stop offset="100%" stop-color="#01579b" stop-opacity="0.95"/>
</linearGradient>
</defs>
<circle cx="60" cy="60" r="56" fill="url(#${uid}-ice)" opacity="0.55"/>
<circle cx="60" cy="60" r="42" fill="url(#${uid}-ice)"/>
<circle cx="60" cy="60" r="44" fill="none" stroke="url(#${uid}-rim)" stroke-width="7" opacity="0.95"/>
<circle cx="60" cy="60" r="39" fill="none" stroke="#e1f5fe" stroke-width="1.8" opacity="0.8"/>
<!-- jagged ice seal shards around rim -->
<path d="M60 14 L68 28 L52 30 Z" fill="#e3f2fd" stroke="#fff" stroke-width="0.7" opacity="0.95"/>
<path d="M88 28 L98 40 L82 44 Z" fill="#b3e5fc" stroke="#fff" stroke-width="0.7" opacity="0.9"/>
<path d="M104 60 L96 74 L86 62 Z" fill="#e1f5fe" stroke="#fff" stroke-width="0.7" opacity="0.9"/>
<path d="M90 92 L78 100 L76 84 Z" fill="#81d4fa" stroke="#fff" stroke-width="0.7" opacity="0.88"/>
<path d="M60 106 L48 94 L72 94 Z" fill="#e3f2fd" stroke="#fff" stroke-width="0.7" opacity="0.92"/>
<path d="M30 92 L22 78 L40 80 Z" fill="#b3e5fc" stroke="#fff" stroke-width="0.7" opacity="0.9"/>
<path d="M16 60 L24 46 L34 58 Z" fill="#e1f5fe" stroke="#fff" stroke-width="0.7" opacity="0.9"/>
<path d="M32 28 L44 18 L48 34 Z" fill="#fff" stroke="#b3e5fc" stroke-width="0.6" opacity="0.95"/>
<path d="M42 48 L54 40 L56 56 L44 58 Z" fill="#e1f5fe" opacity="0.55"/>
<path d="M70 52 L84 48 L82 64 L68 62 Z" fill="#b3e5fc" opacity="0.45"/>
<ellipse cx="48" cy="44" rx="12" ry="7" fill="#fff" opacity="0.4"/>
<circle cx="74" cy="40" r="3" fill="#fff" opacity="0.55"/>
<circle cx="40" cy="70" r="2.2" fill="#e3f2fd" opacity="0.7"/>
</svg>`;
}
function applyIcePeak(el, id) {
const kind = resonanceFor(id);
el.classList.remove('aura-hot', 'aura-cold', 'ice-peak-hot', 'ice-peak-cold');
let aura = el.querySelector('.aura') || el.querySelector('.ice-peak');
if (!kind) {
if (aura) aura.remove();
return;
}
el.classList.add(kind === 'hot' ? 'aura-hot' : 'aura-cold');
if (!aura) {
aura = document.createElement('div');
el.appendChild(aura);
}
aura.className = 'aura';
const uid = 'a' + hashStr(id + ':' + kind).toString(36);
aura.innerHTML = auraWrapSvg(kind, uid);
}
function yForIndicator(c) {
const m = metrics[c.id];
if (indicator === 'rsi') {
if (!m || m.rsi == null) return null;
return Math.max(0, Math.min(1, m.rsi / 100));
}
if (indicator === 'ema') {
if (!m || m.ema == null || !(m.price > 0)) return null;
return yFracEma(m.price, m.ema, 8);
}
if (indicator === 'bb') {
if (!m || !m.bb) return null;
return m.bb.y;
}
if (indicator === 'macd') {
if (!m || !m.macd) return null;
return m.macd.y;
}
return null;
}
function updateSentiment() {
const coins = activeCoins();
let vals = [];
coins.forEach(c => {
const m = metrics[c.id];
if (m && m.rsi != null) vals.push(m.rsi / 100);
else {
const y = yForIndicator(c);
if (y != null) vals.push(y);
}
});
// Also blend current indicator Y if no RSI
if (!vals.length) {
coins.forEach(c => {
if (indicator === 'vol') {
const st = states[c.id];
const band = st ? bandFor(st) : null;
const price = st ? (livePrice[c.id] != null ? livePrice[c.id] : st.price) : null;
if (band && price > 0) vals.push(yFrac(price, band));
}
});
}
const heat = vals.length ? vals.reduce((a, b) => a + b, 0) / vals.length : 0.35;
const frame = $('canvas-frame');
if (frame) frame.style.setProperty('--heat', heat.toFixed(3));
const badge = $('heat-badge');
if (badge) {
const lab = heat >= 0.62 ? t('heatHot') : heat <= 0.38 ? t('heatCold') : t('heatMid');
badge.textContent = t('heatLab')(lab + ' ' + Math.round(heat * 100));
badge.style.color = heat >= 0.62 ? '#c62828' : heat <= 0.38 ? '#1565c0' : '#0a5f7a';
}
}
async function refreshCandlesAndMetrics() {
if (!isCandleInd() && !Object.values(resonate).some(Boolean)) {
// still refresh RSI-ish for sentiment if any resonate checked
}
const needCandles = isCandleInd() || Object.values(resonate).some(Boolean);
if (!needCandles && indicator === 'vol') {
updateSentiment();
return;
}
const targets = activeCoins();
await Promise.all(targets.map(async c => {
const candle = await fetchCandles(c, candleTf);
computeMetricsFor(c, candle);
}));
layoutAll();
updateSentiment();
updateStatusLine();
if (selected) selectCoin(selected);
}
async function refreshAllRsi() { return refreshCandlesAndMetrics(); }
function bandValid(band) {
if (!band) return false;
const lo = Number(band.lo), hi = Number(band.hi);
return Number.isFinite(lo) && Number.isFinite(hi) && hi > lo;
}
function bandFor(state) {
const now = state && state.bands && state.bands.now;
if (!now) return null;
const band = horizon === 'h7' ? ensureH7(now) : (now[horizon] || null);
return bandValid(band) ? band : null;
}
function yFrac(price, band) {
if (!band || !(band.hi > band.lo)) return 0.5;
return Math.max(0, Math.min(1, (price - band.lo) / (band.hi - band.lo)));
}
function applyI18n() {
const candle = isCandleInd();
document.body.classList.toggle('ind-candle', candle);
document.body.classList.toggle('ind-vol', indicator === 'vol');
document.body.classList.remove('rsi-mode'); // legacy class unused
const titleMap = { vol: 'title', rsi: 'rsiTitle', ema: 'emaTitle', bb: 'bbTitle', macd: 'macdTitle' };
const subMap = { vol: 'sub', rsi: 'rsiSub', ema: 'emaSub', bb: 'bbSub', macd: 'macdSub' };
const helpMap = { vol: 'crackHelp', rsi: 'rsiCrackHelp', ema: 'emaCrackHelp', bb: 'bbCrackHelp', macd: 'macdCrackHelp' };
const hiMap = { vol: 'hi', rsi: 'rsiHi', ema: 'emaHi', bb: 'bbHi', macd: 'macdHi' };
const midMap = { vol: null, rsi: 'rsiMid', ema: 'emaMid', bb: 'bbMid', macd: 'macdMid' };
const loMap = { vol: 'lo', rsi: 'rsiLo', ema: 'emaLo', bb: 'bbLo', macd: 'macdLo' };
const hintMap = { vol: 'hint', rsi: 'rsiHint', ema: 'emaHint', bb: 'bbHint', macd: 'macdHint' };
const brandName = $('brand-name');
if (brandName) {
// Product name stays stable; indicator only changes subtitle/rails
brandName.textContent = t('title');
}
const mh = $('model-help');
if (mh && !mh.hidden) mh.innerHTML = t('modelHelp');
$('brand-sub').textContent = t(subMap[indicator] || 'sub');
$('ylab-hi').textContent = t(hiMap[indicator] || 'hi');
$('ylab-mid').textContent = midMap[indicator] ? t(midMap[indicator]) : (lang === 'zh' ? '中心' : 'Mid');
$('ylab-lo').textContent = t(loMap[indicator] || 'lo');
$('axis-hint').textContent = t(hintMap[indicator] || 'hint');
$('btn-lang').textContent = t('lang');
$('crack-help').innerHTML = t(helpMap[indicator] || 'crackHelp');
$('coin-panel-lab').textContent = t('coinLab');
$('coin-panel-meta').textContent = t('coinMeta')(selectedIds.size);
const open = $('coin-panel').classList.contains('open');
$('btn-coin-toggle').textContent = open ? t('coinClose') : t('coinOpen');
$('btn-coin-default').textContent = t('coinDef');
$('btn-coin-all').textContent = t('coinAll');
$('btn-coin-clear').textContent = t('coinClear');
document.querySelectorAll('#horizon-seg button').forEach(b => {
b.textContent = t(b.dataset.h);
b.classList.toggle('on', !candle && b.dataset.h === horizon);
});
document.querySelectorAll('#candle-seg button').forEach(b => {
const k = b.dataset.tf === '15m' ? 'rsiTf15' : b.dataset.tf === '4h' ? 'rsiTf4h' : 'rsiTf1h';
b.textContent = t(k);
b.classList.toggle('on', candle && b.dataset.tf === candleTf);
});
document.querySelectorAll('.btn-ind').forEach(b => {
const on = b.dataset.ind === indicator;
b.classList.toggle('on', on);
b.setAttribute('aria-pressed', on ? 'true' : 'false');
});
const volLab = document.querySelector('[data-i18n-ind="vol"]');
if (volLab) volLab.textContent = t('volBtn');
const bbLab = document.querySelector('[data-i18n-ind="bb"]');
if (bbLab) bbLab.textContent = t('bbBtn');
['rsi','ema','bb','macd'].forEach(k => {
const chk = document.getElementById('chk-' + k);
if (chk) chk.checked = !!resonate[k];
});
$('btn-guest').textContent = t('guest');
const xLabel = $('btn-x-label');
const xBtn = $('btn-x-login');
const wrap = document.querySelector('.auth-wrap');
if (authMode === 'x' && authUser) {
const full = '@' + authUser;
xLabel.textContent = full.length > 12 ? (full.slice(0, 11) + '…') : full;
if (xBtn) xBtn.title = full;
} else {
xLabel.textContent = t('loginReg');
if (xBtn) xBtn.title = 'X login';
}
$('btn-guest').classList.toggle('on', authMode === 'guest');
xBtn.classList.toggle('on', authMode === 'x');
if (wrap) wrap.classList.toggle('is-x', authMode === 'x');
$('auth-note').textContent = authMode === 'x' ? t('authXOk') : t('authLocalNote');
if ($('set-title')) $('set-title').textContent = t('setTitle');
if ($('alarm-title')) $('alarm-title').textContent = t('alarmTitle');
if ($('alarm-hint')) $('alarm-hint').textContent = t('alarmHint');
const g = $('lane-guides');
if (g) {
const kids = g.children;
const guideCandle = candle;
if (kids[0]) kids[0].style.top = guideCandle ? '30%' : '8%';
if (kids[2]) kids[2].style.top = guideCandle ? '70%' : '92%';
}
document.documentElement.lang = lang === 'zh' ? 'zh-CN' : 'en';
const titles = {
vol: lang === 'zh' ? 'Timestral 泡泡图 · 波动率预测' : 'Timestral Bubbles · Vol Forecast',
rsi: lang === 'zh' ? 'Timestral 泡泡图 · RSI' : 'Timestral Bubbles · RSI',
ema: lang === 'zh' ? 'Timestral 泡泡图 · EMA' : 'Timestral Bubbles · EMA',
bb: lang === 'zh' ? 'Timestral 泡泡图 · 布林带' : 'Timestral Bubbles · Bollinger',
macd: lang === 'zh' ? 'Timestral 泡泡图 · MACD' : 'Timestral Bubbles · MACD',
};
document.title = titles[indicator] || titles.vol;
syncParamSliders();
renderCoinPicker();
updateSentiment();
}
function syncParamSliders() {
const set = (id, v, fmt) => {
const el = $(id); if (!el) return;
el.value = v;
const lab = $('v-' + id.slice(2));
// ids: p-rsi -> v-rsi
};
const map = [
['p-rsi', params.rsi, v => String(v)],
['p-ema', params.ema, v => String(v)],
['p-bbp', params.bbPeriod, v => String(v)],
['p-bbm', Math.round(params.bbMult * 10), v => (v/10).toFixed(1)],
['p-mf', params.macdFast, v => String(v)],
['p-ms', params.macdSlow, v => String(v)],
['p-msig', params.macdSignal, v => String(v)],
['a-ob', alarms.rsiOb, v => String(v)],
['a-os', alarms.rsiOs, v => String(v)],
['a-ema', Math.round(alarms.emaPct * 10), v => (v/10).toFixed(1)],
['a-macd', alarms.macdHist, v => String(v)],
];
map.forEach(([id, val, fmt]) => {
const el = $(id); if (!el) return;
el.value = val;
});
if ($('v-rsi')) $('v-rsi').textContent = params.rsi;
if ($('v-ema')) $('v-ema').textContent = params.ema;
if ($('v-bbp')) $('v-bbp').textContent = params.bbPeriod;
if ($('v-bbm')) $('v-bbm').textContent = params.bbMult.toFixed(1);
if ($('v-mf')) $('v-mf').textContent = params.macdFast;
if ($('v-ms')) $('v-ms').textContent = params.macdSlow;
if ($('v-msig')) $('v-msig').textContent = params.macdSignal;
if ($('v-a-ob')) $('v-a-ob').textContent = alarms.rsiOb;
if ($('v-a-os')) $('v-a-os').textContent = alarms.rsiOs;
if ($('v-a-ema')) $('v-a-ema').textContent = alarms.emaPct.toFixed(1);
if ($('v-a-macd')) $('v-a-macd').textContent = alarms.macdHist;
}
function iconUrl(c) {
if (c.icon === 'gold') return null;
return ICON_CDN + c.icon + '.png';
}
function coinLabel(c) {
if (c.label) return c.label[lang] || c.id;
return c.id;
}
function makeBubble(c) {
const el = document.createElement('div');
el.className = 'bubble floating';
el.dataset.id = c.id;
el.style.setProperty('--bubble-rgb', c.rgb);
const rnd = seededRng(hashStr(c.id + ':float'));
el.style.setProperty('--fx', (3 + rnd() * 5).toFixed(1) + 'px');
el.style.setProperty('--fy', (4 + rnd() * 6).toFixed(1) + 'px');
el.style.setProperty('--fdur', (4.5 + rnd() * 2.5).toFixed(1) + 's');
el.style.setProperty('--fdelay', (-rnd() * 4).toFixed(1) + 's');
const size = bubbleSizeFor(c);
el.style.width = size + 'px';
el.style.height = size + 'px';
const av = document.createElement('div');
av.className = 'b-av-wrap';
const url = iconUrl(c);
if (url) {
const img = document.createElement('img');
img.alt = c.id;
img.src = url;
img.onerror = () => {
img.remove();
const init = document.createElement('div');
init.className = 'b-init';
init.textContent = c.id.slice(0, 2);
av.appendChild(init);
};
av.appendChild(img);
} else {
const init = document.createElement('div');
init.className = 'b-init';
init.textContent = c.id.slice(0, 2);
av.appendChild(init);
}
const gloss = document.createElement('div');
gloss.className = 'b-gloss';
const name = document.createElement('div');
name.className = 'b-name';
name.textContent = coinLabel(c);
const crack = document.createElement('div');
crack.className = 'crack';
crack.innerHTML = buildCrackSvg(c.id, 0.5);
el.appendChild(av);
el.appendChild(gloss);
el.appendChild(name);
el.appendChild(crack);
el.addEventListener('pointerdown', onPointerDown);
return el;
}
function layerSize() {
const layer = $('bubble-layer');
return { w: layer.clientWidth, h: layer.clientHeight };
}
function viewportW() {
return window.innerWidth || document.documentElement.clientWidth || 1024;
}
/** Diameter: desktop ~64–78; tablet ~24–34; phone ~20–30 (shrinks with coin count). */
function bubbleSizeFor(c, nOpt) {
const rnd = seededRng(hashStr(c.id + ':float'));
const n = nOpt != null ? nOpt : (activeCoins().length || 1);
const vw = viewportW();
let base, span, floor;
if (vw <= 480) {
// phone: ~half prior size so many coins fit without stacking
base = Math.max(20, Math.min(28, 30 - n * 0.28));
span = 4;
floor = 18;
} else if (vw <= 768) {
base = Math.max(24, Math.min(32, 34 - n * 0.22));
span = 4;
floor = 22;
} else {
base = 64;
span = 14;
floor = 56;
}
return Math.max(floor, base + rnd() * span);
}
function applyBubbleSize(el, c) {
const size = bubbleSizeFor(c);
el.style.width = size + 'px';
el.style.height = size + 'px';
return size;
}
/** Even horizontal slots + light jitter; keep user-dragged X. */
function ensureSpreadPositions() {
const coins = activeCoins();
const n = coins.length;
if (!n) return;
coins.forEach((c, i) => {
const prev = positions[c.id];
if (prev && prev.user) return;
const jitter = ((hashStr(c.id) % 1000) / 1000 - 0.5) * Math.min(0.12, 0.85 / Math.max(n, 1));
// stagger odd/even slightly toward edges for denser packing feel
const stagger = (i % 2 === 0 ? -0.015 : 0.015) * Math.min(1, 8 / n);
let xFrac = (i + 0.5) / n + jitter + stagger;
positions[c.id] = { xFrac: Math.max(0, Math.min(1, xFrac)), user: false };
});
}
/** Push apart bubbles that overlap too much (same-ish Y), clamp inside frame. */
function resolveOverlaps() {
const coins = activeCoins();
const { w } = layerSize();
if (w <= 0 || coins.length < 2) return;
const items = coins.map(c => {
const el = document.querySelector(`.bubble[data-id="${c.id}"]`);
if (!el || el.style.display === 'none') return null;
const size = parseFloat(el.style.width) || 48;
const left = parseFloat(el.style.left) || 0;
const top = parseFloat(el.style.top) || 0;
return { id: c.id, el, size, cx: left + size / 2, cy: top + size / 2, left, top };
}).filter(Boolean);
for (let iter = 0; iter < 5; iter++) {
for (let i = 0; i < items.length; i++) {
for (let j = i + 1; j < items.length; j++) {
const a = items[i], b = items[j];
const dx = b.cx - a.cx;
const dy = b.cy - a.cy;
const minDist = (a.size + b.size) * 0.56; // tighter packing for small mobile diameters
const dist = Math.hypot(dx, dy) || 0.01;
if (dist >= minDist) continue;
// mostly separate on X (Y is price-driven)
const push = (minDist - dist) * 0.55;
const ux = Math.abs(dx) < 1 ? (a.id < b.id ? -1 : 1) : dx / dist;
const shift = push * Math.sign(ux || 1);
// weight: non-user moves more
const aUser = !!(positions[a.id] && positions[a.id].user);
const bUser = !!(positions[b.id] && positions[b.id].user);
let da = shift, db = -shift;
if (aUser && !bUser) { da = 0; db = -push * Math.sign(ux || 1) * 2; }
else if (!aUser && bUser) { da = push * Math.sign(ux || 1) * 2; db = 0; }
else if (aUser && bUser) { da *= 0.35; db *= 0.35; }
a.cx += da; b.cx += db;
}
}
// clamp + write back
items.forEach(it => {
let left = it.cx - it.size / 2;
left = Math.max(0, Math.min(Math.max(0, w - it.size), left));
it.left = left;
it.cx = left + it.size / 2;
it.el.style.left = left + 'px';
const prev = positions[it.id] || {};
positions[it.id] = {
xFrac: w > it.size ? left / (w - it.size) : 0,
user: !!prev.user,
};
});
}
}
function placeBubble(el, c) {
const st = states[c.id];
const { w, h } = layerSize();
const size = applyBubbleSize(el, c);
if (positions[c.id] == null) {
// temporary; ensureSpreadPositions fills properly on layoutAll
let hsh = hashStr(c.id);
positions[c.id] = { xFrac: (hsh % 1000) / 1000, user: false };
}
let x = positions[c.id].xFrac * Math.max(0, w - size);
x = Math.max(0, Math.min(Math.max(0, w - size), x));
el.style.left = x + 'px';
el.style.display = '';
el.classList.remove('near-edge', 'at-edge', 'no-band');
const crackEl = el.querySelector('.crack');
let na = el.querySelector('.b-na');
if (isCandleInd()) {
el.style.removeProperty('--crack');
if (crackEl) {
crackEl.style.removeProperty('opacity');
crackEl.innerHTML = '';
}
const y = yForIndicator(c);
if (y == null || !isFinite(y)) {
el.classList.add('no-band');
el.style.top = Math.max(0, Math.min(Math.max(0, h - size), (h - size) * 0.5)) + 'px';
if (!na) {
na = document.createElement('div');
na.className = 'b-na';
el.appendChild(na);
}
na.textContent = t('na');
applyIcePeak(el, c.id);
return;
}
if (na) na.remove();
const top = Math.max(0, Math.min(Math.max(0, h - size), (1 - y) * Math.max(0, h - size)));
el.style.top = top + 'px';
applyIcePeak(el, c.id);
return;
}
const band = st ? bandFor(st) : null;
const price = st
? (livePrice[c.id] != null ? livePrice[c.id] : st.price)
: null;
if (!band || !(price > 0)) {
el.classList.add('no-band');
el.style.top = Math.max(0, Math.min(Math.max(0, h - size), (h - size) * 0.5)) + 'px';
el.style.removeProperty('--crack');
if (crackEl) {
crackEl.style.removeProperty('opacity');
crackEl.innerHTML = buildCrackSvg(c.id, 0);
}
if (!na) {
na = document.createElement('div');
na.className = 'b-na';
el.appendChild(na);
}
// Warming: 503 / state without usable bands. N/A only for hard miss.
const warm = !!warming[c.id] || !!(st && !band);
na.textContent = warm ? t('warming') : t('na');
return;
}
if (na) na.remove();
const y = yFrac(price, band);
const top = Math.max(0, Math.min(Math.max(0, h - size), (1 - y) * Math.max(0, h - size)));
el.style.top = top + 'px';
// Crack intensity always from SELECTED horizon band (recomputed every layout)
const dist = Math.min(y, 1 - y);
if (crackEl) crackEl.style.removeProperty('opacity'); // clear any legacy inline override
if (dist <= EDGE) {
const intensity = 1 - dist / EDGE;
el.style.setProperty('--crack', (0.28 + 0.72 * intensity).toFixed(2));
el.classList.add(dist <= EDGE * 0.35 ? 'at-edge' : 'near-edge');
if (crackEl) crackEl.innerHTML = buildCrackSvg(c.id, intensity);
} else {
el.style.removeProperty('--crack');
if (crackEl) crackEl.innerHTML = buildCrackSvg(c.id, 0);
}
applyIcePeak(el, c.id);
}
function rebuildBubbles() {
const layer = $('bubble-layer');
const keepX = { ...positions };
layer.innerHTML = '';
activeCoins().forEach(c => {
layer.appendChild(makeBubble(c));
});
positions = keepX;
ensureSpreadPositions();
layoutAll();
if (selected && !selectedIds.has(selected)) {
selected = null;
showDetailEmpty();
} else if (selected) {
selectCoin(selected);
} else {
showDetailEmpty();
}
}
function layoutAll() {
ensureSpreadPositions();
activeCoins().forEach(c => {
const el = document.querySelector(`.bubble[data-id="${c.id}"]`);
if (el) placeBubble(el, c);
});
resolveOverlaps();
}
function onPointerDown(e) {
if (e.button != null && e.button !== 0) return;
const el = e.currentTarget;
const id = el.dataset.id;
el.setPointerCapture(e.pointerId);
el.classList.add('dragging');
el.style.zIndex = ++zTop;
const rect = el.getBoundingClientRect();
drag = {
id, el,
ox: e.clientX - rect.left,
oy: e.clientY - rect.top,
moved: false,
startX: e.clientX, startY: e.clientY,
};
e.preventDefault();
}
function onPointerMove(e) {
if (!drag) return;
const { w } = layerSize();
const size = parseFloat(drag.el.style.width) || 72;
let x = e.clientX - $('bubble-layer').getBoundingClientRect().left - drag.ox;
x = Math.max(0, Math.min(w - size, x));
drag.el.style.left = x + 'px';
positions[drag.id] = { xFrac: w > size ? x / (w - size) : 0, user: true };
if (Math.hypot(e.clientX - drag.startX, e.clientY - drag.startY) > 6) drag.moved = true;
}
function onPointerUp(e) {
if (!drag) return;
const { id, el, moved } = drag;
el.classList.remove('dragging');
try { el.releasePointerCapture(e.pointerId); } catch (_) {}
drag = null;
if (!moved) selectCoin(id);
}
window.addEventListener('pointermove', onPointerMove);
window.addEventListener('pointerup', onPointerUp);
window.addEventListener('pointercancel', onPointerUp);
function showDetailEmpty() {
const sheet = $('detail-sheet');
sheet.classList.add('empty');
$('d-name').textContent = t('detailEmptyTitle');
$('d-handle').textContent = t('detailEmptySub');
$('d-av').innerHTML = '';
$('d-av').textContent = '·';
const emptyMap = { vol: 'detailEmptyBody', rsi: 'rsiDetailEmpty', ema: 'emaDetailEmpty', bb: 'bbDetailEmpty', macd: 'macdDetailEmpty' };
const emptyBody = t(emptyMap[indicator] || 'detailEmptyBody');
$('d-body').innerHTML = `<div class="detail-placeholder">${emptyBody}</div>`;
document.querySelectorAll('.bubble.selected').forEach(b => b.classList.remove('selected'));
}
function selectCoin(id) {
selected = id;
document.querySelectorAll('.bubble').forEach(b => b.classList.toggle('selected', b.dataset.id === id));
const c = COINS.find(x => x.id === id);
const st = states[id];
const sheet = $('detail-sheet');
if (!c) {
showDetailEmpty();
return;
}
sheet.classList.remove('empty');
$('d-name').textContent = coinLabel(c);
$('d-handle').textContent = c.inst;
const av = $('d-av');
av.style.setProperty('--bubble-rgb', c.rgb);
av.innerHTML = '';
const url = iconUrl(c);
if (url) {
const img = document.createElement('img');
img.src = url; img.alt = c.id;
img.onerror = () => { av.textContent = c.id.slice(0, 2); };
av.appendChild(img);
} else {
av.textContent = c.id.slice(0, 2);
}
if (isCandleInd()) {
renderIndDetail(c);
return;
}
if (!st) {
$('d-body').innerHTML = `<div>${t('noData')}</div><div class="disc">${t('disc')}</div>`;
return;
}
renderDetail(c, st);
}
function renderIndDetail(c) {
const m = metrics[c.id];
const body = $('d-body');
const tfLab = candleTf === '15m' ? t('rsiTf15') : candleTf === '4h' ? t('rsiTf4h') : t('rsiTf1h');
const price = (m && m.price) || livePrice[c.id];
const res = resonanceFor(c.id);
const resHtml = res ? `<div class="band-row" style="color:${res==='hot'?'#c62828':'#1565c0'}">❄ ${t('resonateOn')} · ${res}</div>` : '';
if (!m) {
const discMap = { rsi: 'rsiDisc', ema: 'emaDisc', bb: 'bbDisc', macd: 'macdDisc' };
body.innerHTML = `<div>${t('rsiNoData')}</div><div class="disc">${t(discMap[indicator]||'rsiDisc')}</div>`;
return;
}
if (indicator === 'rsi') {
if (m.rsi == null) { body.innerHTML = `<div>${t('rsiNoData')}</div><div class="disc">${t('rsiDisc')}</div>`; return; }
const meaning = m.rsi >= alarms.rsiOb ? t('rsiOb') : m.rsi <= alarms.rsiOs ? t('rsiOs') : t('rsiNeu');
const y = m.rsi / 100;
body.innerHTML = `
<div class="band-row">${t('rsiVal')}(${params.rsi}) · ${tfLab}
<b style="font-size:18px;color:rgba(${c.rgb},1)">${m.rsi.toFixed(1)}</b></div>
<div class="pos-bar" style="--bubble-rgb:${c.rgb}"><span class="dot" style="left:${(y*100).toFixed(1)}%"></span></div>
<div class="pos-labs"><span>0</span><span>50</span><span>100</span></div>
<div style="font-weight:700;margin-top:10px;font-size:12px;color:var(--text-muted)">${t('rsiMeaning')}</div>
<div class="band-row" style="margin-top:4px">${meaning}</div>
${resHtml}
${price > 0 ? `<div class="band-row" style="margin-top:8px">${lang==='zh'?'现价':'Price'} <b style="color:rgba(${c.rgb},1)">${pf(price,price)}</b></div>` : ''}
<div class="disc">${t('rsiDisc')}</div>`;
return;
}
if (indicator === 'ema') {
if (m.ema == null) { body.innerHTML = `<div>${t('rsiNoData')}</div><div class="disc">${t('emaDisc')}</div>`; return; }
const y = yFracEma(m.price, m.ema, 8);
body.innerHTML = `
<div class="band-row">${t('emaVal')}(${params.ema}) · ${tfLab}
<b style="font-size:18px;color:rgba(${c.rgb},1)">${m.emaPct!=null?m.emaPct.toFixed(2)+'%':'—'}</b></div>
<div class="pos-bar" style="--bubble-rgb:${c.rgb}"><span class="dot" style="left:${(y*100).toFixed(1)}%"></span></div>
<div class="pos-labs"><span>-8%</span><span>0</span><span>+8%</span></div>
<div class="band-row">EMA <b>${pf(m.ema,m.ema)}</b> · ${lang==='zh'?'现价':'Price'} <b>${pf(m.price,m.price)}</b></div>
${resHtml}<div class="disc">${t('emaDisc')}</div>`;
return;
}
if (indicator === 'bb') {
if (!m.bb) { body.innerHTML = `<div>${t('rsiNoData')}</div><div class="disc">${t('bbDisc')}</div>`; return; }
const b = m.bb;
body.innerHTML = `
<div class="band-row">${t('bbVal')}(${params.bbPeriod},${params.bbMult}) · ${tfLab}
<b style="font-size:18px;color:rgba(${c.rgb},1)">${(b.y*100).toFixed(0)}%</b></div>
<div class="pos-bar" style="--bubble-rgb:${c.rgb}"><span class="dot" style="left:${(b.y*100).toFixed(1)}%"></span></div>
<div class="pos-labs"><span>${pf(b.lower,b.close)}</span><span>${pf(b.mid,b.close)}</span><span>${pf(b.upper,b.close)}</span></div>
<div class="band-row">${b.breakUpper ? '↑ break upper' : b.breakLower ? '↓ break lower' : 'in band'}</div>
${resHtml}<div class="disc">${t('bbDisc')}</div>`;
return;
}
if (indicator === 'macd') {
if (!m.macd) { body.innerHTML = `<div>${t('rsiNoData')}</div><div class="disc">${t('macdDisc')}</div>`; return; }
const d = m.macd;
body.innerHTML = `
<div class="band-row">${t('macdVal')}(${params.macdFast},${params.macdSlow},${params.macdSignal}) · ${tfLab}
<b style="font-size:18px;color:rgba(${c.rgb},1)">${d.hist.toPrecision(4)}</b></div>
<div class="pos-bar" style="--bubble-rgb:${c.rgb}"><span class="dot" style="left:${(d.y*100).toFixed(1)}%"></span></div>
<div class="pos-labs"><span>bear</span><span>0</span><span>bull</span></div>
<div class="band-row">MACD ${d.macd.toPrecision(4)} · Signal ${d.signal.toPrecision(4)}
${d.crossUp?'· cross↑':''}${d.crossDn?'· cross↓':''}</div>
${resHtml}<div class="disc">${t('macdDisc')}</div>`;
}
}
function renderDetail(c, st) {
const B = st.bands || {};
const now = B.now || {};
const band = bandFor(st);
const price = livePrice[c.id] != null ? livePrice[c.id] : st.price;
const P = now.center || price;
const y = yFrac(price, band);
const body = $('d-body');
if (!band) {
body.innerHTML = `<div>${t('noData')}</div><div class="disc">${t('disc')}</div>`;
return;
}
const tg = src => `<span class="tg ${src === 'live' ? 'lv' : ''}">${src === 'live' ? t('lv') : t('bt')}</span>`;
const chkLine = (label, r) => {
if (!r) return `<tr><td>${label}</td><td colspan="2">—</td></tr>`;
const res = r.hit
? `<span class="ok">✓</span>`
: `<span class="ng">${xm(r.miss)} ${t(r.miss === 'up' ? 'mUp' : r.miss === 'down' ? 'mDn' : 'mBoth')}</span>`;
return `<tr><td>${label}<br>${tg(r.source)}</td>
<td>${t('band')} ${pf(r.lo, P)} – ${pf(r.hi, P)}<br><span style="color:var(--text-dim)">${pf(r.act_lo, P)} – ${pf(r.act_hi, P)}</span></td>
<td>${res}</td></tr>`;
};
const h24m = B.last24 || { marks: [], hits: 0, hours: 0 };
const w7 = B.last7 || { marks: [], hits: 0, days: 0, source: 'backtest' };
const m30 = B.last30 || { marks: [], hits: 0, days: 0, source: 'backtest' };
const marks24 = (h24m.marks || []).map(m =>
`<span class="${m.hit ? 'g' : 'r'}" title="${m.t}">${m.hit ? '✓' : xm(m.miss)}</span>`).join('');
const marks30 = (m30.marks || []).map(m =>
`<span class="${m.hit ? 'g' : 'r'}" title="${m.t}">${m.hit ? '✓' : xm(m.miss)}</span>`).join('');
const marks7 = (w7.marks || []).map(m =>
m.hit ? '<span class="ok">✓</span>' : `<span class="ng">${xm(m.miss)}</span>`).join(' ');
body.innerHTML = `
<div class="band-row">${t('band')} <b>${pf(band.lo, P)} – ${pf(band.hi, P)}</b>
${horizon === 'h7' ? `<div class="legend">${t('method7')}</div>` : ''}
<div class="legend">${t('until')} ${band.until || '—'} · ${t('center')} ${pf(P, P)}</div>
</div>
<div class="pos-bar" style="--bubble-rgb:${c.rgb}"><span class="dot" style="left:${(y * 100).toFixed(1)}%"></span></div>
<div class="pos-labs"><span>${pf(band.lo, P)}</span><span>${t('pos')} ${(y * 100).toFixed(0)}%</span><span>${pf(band.hi, P)}</span></div>
<div class="band-row" style="margin-top:8px"><b style="color:rgba(${c.rgb},1)">${pf(price, P)}</b></div>
<div style="font-weight:700;margin-top:10px;font-size:12px;color:var(--text-muted)">${t('chk')}</div>
<table class="chk-table">
${chkLine(t('rH'), B.last_hour)}
${chkLine(t('rY'), B.yesterday)}
<tr><td>${t('r24')}</td><td colspan="2"><div class="grid-marks">${marks24}</div>${t('inN')(h24m.hits, h24m.hours)}</td></tr>
<tr><td>${t('r7')}</td><td colspan="2"><span class="marks">${marks7}</span> ${t('inN')(w7.hits, w7.days)}${tg(w7.source)}</td></tr>
<tr><td>${t('r30')}</td><td colspan="2"><div class="grid-marks">${marks30}</div>${t('inN')(m30.hits, m30.days)}${tg(m30.source)}</td></tr>
</table>
<div class="legend">${t('mk')}</div>
<div class="disc">${t('disc')}</div>
`;
}
function renderCoinPicker() {
const grid = $('coin-grid');
grid.innerHTML = '';
COINS.forEach(c => {
const lab = document.createElement('label');
lab.className = 'coin-item';
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.value = c.id;
cb.checked = selectedIds.has(c.id);
cb.addEventListener('change', () => {
if (cb.checked) {
if (selectedIds.size >= 50) {
cb.checked = false;
return;
}
selectedIds.add(c.id);
} else {
selectedIds.delete(c.id);
if (selectedIds.size === 0) {
// keep at least one default
selectedIds.add(DEFAULT_SELECTED[0]);
cb.checked = c.id === DEFAULT_SELECTED[0];
}
}
saveSelectedIds();
$('coin-panel-meta').textContent = t('coinMeta')(selectedIds.size);
updateStatusLine();
rebuildBubbles();
// lazy-load missing state / price for newly checked
ensureCoinData(c).then(() => layoutAll());
});
const span = document.createElement('span');
span.textContent = coinLabel(c);
const mark = document.createElement('span');
let has;
if (isCandleInd()) {
has = yForIndicator(c) != null;
} else {
has = !!(states[c.id] && bandFor(states[c.id]));
}
mark.className = has ? 'has-data' : 'no-data';
mark.textContent = has ? t('hasData') : t('noBand');
lab.appendChild(cb);
lab.appendChild(span);
lab.appendChild(mark);
grid.appendChild(lab);
});
}
function setCoinPanelOpen(open) {
$('coin-panel').classList.toggle('open', open);
$('coin-panel-hd').setAttribute('aria-expanded', open ? 'true' : 'false');
$('btn-coin-toggle').textContent = open ? t('coinClose') : t('coinOpen');
}
async function fetchState(c) {
// Prefer live API; mark warming on 503 or null-band payloads.
try {
const r = await fetch(`/api/vol/state?inst=${encodeURIComponent(c.inst)}`, { cache: 'no-store' });
if (r.status === 503) {
warming[c.id] = true;
return null;
}
if (r.ok) {
const j = await r.json();
if (j && (j.bands || j.price != null)) {
const h24 = j.bands && j.bands.now && j.bands.now.h24;
warming[c.id] = j.warming === true || j.bands_ready === false || !bandValid(h24);
return j;
}
}
} catch (_) {}
try {
const r = await fetch(`data/state_${c.id}.json?t=${Date.now()}`, { cache: 'no-store' });
if (r.ok) {
const j = await r.json();
if (j && (j.bands || j.price != null)) {
const h24 = j.bands && j.bands.now && j.bands.now.h24;
warming[c.id] = !bandValid(h24);
return j;
}
}
} catch (_) {}
return null;
}
async function mapPool(items, limit, fn) {
const out = new Array(items.length);
let i = 0;
async function worker() {
while (i < items.length) {
const idx = i++;
out[idx] = await fn(items[idx], idx);
}
}
const n = Math.max(1, Math.min(limit, items.length));
await Promise.all(Array.from({ length: n }, () => worker()));
return out;
}
async function ensureCoinData(c) {
if (!states[c.id]) {
const j = await fetchState(c);
if (j) {
states[c.id] = j;
if (j.price != null) livePrice[c.id] = j.price;
}
}
// try live ticker even without band
try {
const url = `https://www.okx.com/api/v5/market/ticker?instId=${encodeURIComponent(c.inst)}`;
const r = await fetch(url, { cache: 'no-store' });
if (r.ok) {
const j = await r.json();
const last = j && j.data && j.data[0] && parseFloat(j.data[0].last);
if (last > 0) livePrice[c.id] = last;
}
} catch (_) {}
if (isCandleInd() || Object.values(resonate).some(Boolean)) {
try {
const candle = await fetchCandles(c, candleTf);
computeMetricsFor(c, candle);
} catch (_) {}
}
}
function updateStatusLine() {
if (isCandleInd()) {
const n = activeCoins().filter(c => yForIndicator(c) != null).length;
const loadMap = { rsi: 'rsiLoaded', ema: 'emaLoaded', bb: 'bbLoaded', macd: 'macdLoaded' };
let msg = t(loadMap[indicator] || 'rsiLoaded')(n);
if (selectedIds.size > 18) msg += ' · ' + t('warnMany');
$('status').textContent = msg;
$('status').classList.add('warn');
return;
}
const active = activeCoins();
const n = active.filter(c => states[c.id] && bandFor(states[c.id])).length;
const m = active.length;
let msg = t('loadedReady')(n, m);
if (selectedIds.size > 18) msg += ' · ' + t('warnMany');
$('status').textContent = msg;
$('status').classList.add('warn');
const btc = states.BTC;
if (btc && btc.published_utc) {
const ageH = (Date.now() - Date.parse(btc.published_utc)) / 3600000;
if (ageH > 6) $('status').textContent += ' · ' + t('stale');
}
}
async function loadStates() {
$('status').textContent = t('loading');
let targets = activeCoins().slice();
// Prioritize currently selected bubble, then coins still missing usable bands.
targets.sort((a, b) => {
const as = (a.id === selected ? 0 : 1);
const bs = (b.id === selected ? 0 : 1);
if (as !== bs) return as - bs;
const ar = (states[a.id] && bandFor(states[a.id])) ? 1 : 0;
const br = (states[b.id] && bandFor(states[b.id])) ? 1 : 0;
return ar - br;
});
const results = await mapPool(targets, 6, async c => {
const j = await fetchState(c);
return { id: c.id, state: j };
});
results.forEach(r => {
if (!r.state) return;
states[r.id] = r.state;
if (r.state.price != null) livePrice[r.id] = r.state.price;
});
rebuildBubbles();
renderCoinPicker();
updateStatusLine();
}
async function pollPrices() {
await Promise.all(activeCoins().map(async c => {
try {
const url = `https://www.okx.com/api/v5/market/ticker?instId=${encodeURIComponent(c.inst)}`;
const r = await fetch(url, { cache: 'no-store' });
if (!r.ok) return;
const j = await r.json();
const last = j && j.data && j.data[0] && parseFloat(j.data[0].last);
if (last > 0) livePrice[c.id] = last;
} catch (_) {}
}));
layoutAll();
if (selected) {
const c = COINS.find(x => x.id === selected);
if (!c) return;
if (isCandleInd()) renderIndDetail(c);
else if (states[selected]) renderDetail(c, states[selected]);
}
}
function setIndicator(next) {
if (!next || next === indicator) {
applyI18n();
layoutAll();
return;
}
indicator = next;
localStorage.setItem('vol-bubble-ind', indicator);
// migrate legacy key
localStorage.setItem('vol-bubble-mode', indicator === 'vol' ? 'vol' : 'rsi');
persistPrefs();
applyI18n();
if (isCandleInd()) {
$('status').textContent = t('loading');
refreshCandlesAndMetrics();
} else {
layoutAll();
updateSentiment();
updateStatusLine();
if (selected) selectCoin(selected);
else showDetailEmpty();
// still compute metrics if resonate checks on
if (Object.values(resonate).some(Boolean)) refreshCandlesAndMetrics();
}
}
let _prefsTimer = null;
function persistPrefs() {
saveJSON('vol-bubble-params', params);
saveJSON('vol-bubble-alarms', alarms);
saveJSON('vol-bubble-resonate', resonate);
const blob = {
indicator, candleTf, horizon, lang, params, alarms, resonate,
coins: [...selectedIds], authMode, updatedAt: Date.now(),
};
saveJSON('vol-bubble-prefs', blob);
if (authMode !== 'x') return;
clearTimeout(_prefsTimer);
_prefsTimer = setTimeout(() => {
fetch('/api/prefs', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify(blob),
}).catch(() => {});
}, 250);
}
$('horizon-seg').addEventListener('click', e => {
const b = e.target.closest('button[data-h]');
if (!b) return;
horizon = b.dataset.h;
localStorage.setItem('vol-bubble-h', horizon);
persistPrefs();
if (indicator !== 'vol') {
setIndicator('vol');
return;
}
applyI18n();
layoutAll();
if (selected) selectCoin(selected);
});
$('candle-seg').addEventListener('click', e => {
const b = e.target.closest('button[data-tf]');
if (!b) return;
candleTf = b.dataset.tf;
localStorage.setItem('vol-bubble-candle-tf', candleTf);
persistPrefs();
applyI18n();
$('status').textContent = t('loading');
refreshCandlesAndMetrics();
});
document.querySelectorAll('.btn-ind').forEach(btn => {
btn.addEventListener('click', () => setIndicator(btn.dataset.ind));
});
document.querySelectorAll('.ind-check').forEach(chk => {
chk.addEventListener('change', () => {
resonate[chk.dataset.res] = chk.checked;
persistPrefs();
refreshCandlesAndMetrics();
});
});
function closeDrawers(except) {
['drawer-settings','drawer-alarms'].forEach(id => {
if (id !== except) $(id).classList.remove('open');
});
}
$('btn-settings').addEventListener('click', e => {
e.stopPropagation();
const d = $('drawer-settings');
const open = !d.classList.contains('open');
closeDrawers(open ? 'drawer-settings' : null);
d.classList.toggle('open', open);
});
$('btn-alarms').addEventListener('click', e => {
e.stopPropagation();
const d = $('drawer-alarms');
const open = !d.classList.contains('open');
closeDrawers(open ? 'drawer-alarms' : null);
d.classList.toggle('open', open);
});
document.addEventListener('click', e => {
if (!e.target.closest('.tools-row')) closeDrawers(null);
});
function onParamInput() {
params.rsi = +$('p-rsi').value;
params.ema = +$('p-ema').value;
params.bbPeriod = +$('p-bbp').value;
params.bbMult = +$('p-bbm').value / 10;
params.macdFast = +$('p-mf').value;
params.macdSlow = +$('p-ms').value;
params.macdSignal = +$('p-msig').value;
if (params.macdSlow <= params.macdFast) params.macdSlow = params.macdFast + 1;
syncParamSliders();
persistPrefs();
// recompute from cached candles (no refetch)
activeCoins().forEach(c => {
const candle = candleCache[candleKey(c.id, candleTf)];
if (candle) computeMetricsFor(c, candle);
});
layoutAll();
updateSentiment();
if (selected && isCandleInd()) selectCoin(selected);
}
function onAlarmInput() {
alarms.rsiOb = +$('a-ob').value;
alarms.rsiOs = +$('a-os').value;
alarms.emaPct = +$('a-ema').value / 10;
alarms.macdHist = +$('a-macd').value;
syncParamSliders();
persistPrefs();
activeCoins().forEach(c => {
const candle = candleCache[candleKey(c.id, candleTf)];
if (candle) computeMetricsFor(c, candle);
});
layoutAll();
if (selected) selectCoin(selected);
}
['p-rsi','p-ema','p-bbp','p-bbm','p-mf','p-ms','p-msig'].forEach(id => {
const el = $(id); if (el) el.addEventListener('input', onParamInput);
});
['a-ob','a-os','a-ema','a-macd'].forEach(id => {
const el = $(id); if (el) el.addEventListener('input', onAlarmInput);
});
function applyCloudPrefs(prefs) {
if (!prefs || typeof prefs !== 'object') return;
if (prefs.lang === 'zh' || prefs.lang === 'en') {
lang = prefs.lang;
localStorage.setItem('vol-bubble-lang', lang);
}
if (prefs.horizon && ['h1','h24','h7'].includes(prefs.horizon)) {
horizon = prefs.horizon;
localStorage.setItem('vol-bubble-h', horizon);
}
if (prefs.candleTf && ['15m','1h','4h'].includes(prefs.candleTf)) {
candleTf = prefs.candleTf;
localStorage.setItem('vol-bubble-candle-tf', candleTf);
}
if (prefs.params && typeof prefs.params === 'object') {
params = { ...params, ...prefs.params };
saveJSON('vol-bubble-params', params);
}
if (prefs.alarms && typeof prefs.alarms === 'object') {
alarms = { ...alarms, ...prefs.alarms };
saveJSON('vol-bubble-alarms', alarms);
}
if (prefs.resonate && typeof prefs.resonate === 'object') {
resonate = { ...resonate, ...prefs.resonate };
saveJSON('vol-bubble-resonate', resonate);
}
if (Array.isArray(prefs.coins) && prefs.coins.length) {
selectedIds = new Set(prefs.coins.filter(id => COINS.some(c => c.id === id)));
if (!selectedIds.size) selectedIds = new Set(COINS.slice(0, 8).map(c => c.id));
localStorage.setItem(LS_SEL, JSON.stringify([...selectedIds]));
}
if (prefs.indicator && ['vol','rsi','ema','bb','macd'].includes(prefs.indicator)) {
indicator = prefs.indicator;
localStorage.setItem('vol-bubble-ind', indicator);
}
prefsCloud = prefs;
saveJSON('vol-bubble-prefs', prefs);
}
async function refreshAuthFromServer() {
try {
const r = await fetch('/api/auth/status', { credentials: 'same-origin' });
const j = await r.json();
if (j.auth === 'x') {
authMode = 'x';
authUser = (j.user && j.user.username) || '';
localStorage.setItem('vol-bubble-auth', 'x');
if (authUser) localStorage.setItem('vol-bubble-x-user', authUser);
const pr = await fetch('/api/prefs', { credentials: 'same-origin' });
const pj = await pr.json();
if (pj && pj.prefs && Object.keys(pj.prefs).length) applyCloudPrefs(pj.prefs);
} else {
// Keep local guest mode unless URL says we just finished OAuth
if (new URLSearchParams(location.search).get('auth') === 'x') {
// cookie missing → treat as guest
authMode = 'guest';
authUser = '';
}
}
if (!j.x_configured && authMode !== 'x') {
// leave note for later click
}
} catch (_) {}
applyI18n();
syncParamSliders();
document.querySelectorAll('.ind-check').forEach(chk => {
if (chk.classList.contains('spacer')) return;
chk.checked = !!resonate[chk.dataset.res];
});
}
$('btn-guest').addEventListener('click', async () => {
if (authMode === 'x') {
try { await fetch('/api/auth/logout', { method: 'POST', credentials: 'same-origin' }); } catch (_) {}
}
authMode = 'guest';
authUser = '';
localStorage.setItem('vol-bubble-auth', 'guest');
localStorage.removeItem('vol-bubble-x-user');
applyI18n();
});
$('btn-x-login').addEventListener('click', async () => {
if (authMode === 'x') return; // already signed in
try {
const st = await fetch('/api/auth/status', { credentials: 'same-origin' }).then(r => r.json());
if (!st.x_configured) {
$('auth-note').textContent = t('authXNeed');
return;
}
} catch (_) {
$('auth-note').textContent = t('authXNeed');
return;
}
window.location.href = '/api/auth/x/start';
});
// After OAuth redirect (?auth=x), sync session + cloud prefs once
refreshAuthFromServer();
function setModelHelpOpen(open) {
const panel = $('model-help');
const btn = $('btn-model-help');
if (!panel || !btn) return;
panel.hidden = !open;
btn.setAttribute('aria-expanded', open ? 'true' : 'false');
if (open) {
panel.innerHTML = t('modelHelp');
const close = $('btn-model-help-close');
if (close) close.onclick = () => setModelHelpOpen(false);
}
}
$('btn-model-help').addEventListener('click', () => {
const open = $('btn-model-help').getAttribute('aria-expanded') !== 'true';
setModelHelpOpen(open);
});
document.addEventListener('click', e => {
const panel = $('model-help');
const btn = $('btn-model-help');
if (!panel || panel.hidden) return;
if (panel.contains(e.target) || (btn && btn.contains(e.target))) return;
setModelHelpOpen(false);
});
$('btn-lang').addEventListener('click', () => {
lang = lang === 'zh' ? 'en' : 'zh';
localStorage.setItem('vol-bubble-lang', lang);
persistPrefs();
applyI18n();
document.querySelectorAll('.bubble .b-name').forEach(el => {
const id = el.parentElement.dataset.id;
const c = COINS.find(x => x.id === id);
if (c) el.textContent = coinLabel(c);
});
document.querySelectorAll('.bubble .b-na').forEach(el => {
const id = el.parentElement && el.parentElement.dataset.id;
const st = id ? states[id] : null;
const warm = !!(id && (warming[id] || (st && !bandFor(st))));
el.textContent = warm ? t('warming') : t('na');
});
if (selected) selectCoin(selected);
updateStatusLine();
});
$('d-close').addEventListener('click', () => {
selected = null;
showDetailEmpty(); // dock stays open; stage height unchanged
});
window.addEventListener('resize', () => { ensureSpreadPositions(); layoutAll(); });
function togglePanel(e) {
if (e.target.closest && e.target.closest('#btn-coin-toggle')) {
// handled below
}
setCoinPanelOpen(!$('coin-panel').classList.contains('open'));
}
$('btn-coin-toggle').addEventListener('click', e => {
e.stopPropagation();
setCoinPanelOpen(!$('coin-panel').classList.contains('open'));
});
$('coin-panel-hd').addEventListener('click', e => {
if (e.target.closest('button')) return;
setCoinPanelOpen(!$('coin-panel').classList.contains('open'));
});
$('coin-panel-hd').addEventListener('keydown', e => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
setCoinPanelOpen(!$('coin-panel').classList.contains('open'));
}
});
document.addEventListener('click', e => {
const panel = $('coin-panel');
if (panel.classList.contains('open') && !panel.contains(e.target)) {
setCoinPanelOpen(false);
}
});
$('btn-coin-default').addEventListener('click', () => {
selectedIds = new Set(DEFAULT_SELECTED);
saveSelectedIds();
applyI18n();
loadStates();
});
$('btn-coin-all').addEventListener('click', () => {
selectedIds = new Set(COINS.map(c => c.id).slice(0, 50));
saveSelectedIds();
applyI18n();
loadStates();
});
$('btn-coin-clear').addEventListener('click', () => {
selectedIds = new Set([DEFAULT_SELECTED[0]]);
saveSelectedIds();
applyI18n();
rebuildBubbles();
});
applyI18n();
showDetailEmpty();
loadStates().then(() => {
pollPrices();
setInterval(pollPrices, 20000);
setInterval(loadStates, 5 * 60 * 1000);
setInterval(() => {
if (isCandleInd() || Object.values(resonate).some(Boolean)) refreshCandlesAndMetrics();
}, 60000);
if (isCandleInd() || Object.values(resonate).some(Boolean)) refreshCandlesAndMetrics();
});
})();
</script>
</body>
</html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<title>Timestral 泡泡图 · 波动率预测</title>
<!-- bubble-ui: multi-ind seawater sentiment ice-peak v3.8 prefs-sync-all -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=ZCOOL+KuaiLe&display=swap" rel="stylesheet" />
<style>
:root {
--coral: #F18D8D;
--sky: #4DBBEB;
--orange: #F7941D;
--magenta: #E91E63;
--yellow: #FFD500;
--bg: #FFF8F0;
--bg-elev: #FFFFFF;
--bg-card: #FFFFFF;
--bg-hover: #FFF1E6;
--border: #F0D9C8;
--text: #1F1520;
--text-muted: #6B5A62;
--text-dim: #9A8790;
--accent: var(--sky);
--radius: 14px;
--font: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
--cartoon: "ZCOOL KuaiLe", "Ma Shan Zheng", "Comic Sans MS", "PingFang SC", cursive, sans-serif;
--shadow: 0 8px 24px rgba(233, 30, 99, 0.08), 0 2px 8px rgba(31, 21, 32, 0.06);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
html, body {
height: 100%; overflow: hidden;
font-family: var(--cartoon); background: var(--bg); color: var(--text);
line-height: 1.45; font-size: 14px; overscroll-behavior: none; touch-action: manipulation;
}
body::before {
content: ""; position: fixed; inset: 0; z-index: -1; pointer-events: none;
background: repeating-linear-gradient(
180deg,
var(--coral) 0px, var(--coral) 28px,
var(--sky) 28px, var(--sky) 56px,
var(--orange) 56px, var(--orange) 84px,
var(--magenta) 84px, var(--magenta) 112px,
var(--yellow) 112px, var(--yellow) 140px
);
opacity: 0.09;
mask-image: linear-gradient(180deg, rgba(0,0,0,0.5), rgba(0,0,0,0.1) 45%, transparent 80%);
-webkit-mask-image: linear-gradient(180deg, rgba(0,0,0,0.5), rgba(0,0,0,0.1) 45%, transparent 80%);
}
.paper-strip {
height: 10px; width: 100%; flex-shrink: 0;
background:
radial-gradient(circle at 10px 0, transparent 9px, var(--coral) 9.5px) 0 0 / 20px 10px,
radial-gradient(circle at 10px 0, transparent 9px, var(--sky) 9.5px) 20px 0 / 20px 10px,
radial-gradient(circle at 10px 0, transparent 9px, var(--orange) 9.5px) 40px 0 / 20px 10px,
radial-gradient(circle at 10px 0, transparent 9px, var(--magenta) 9.5px) 60px 0 / 20px 10px,
radial-gradient(circle at 10px 0, transparent 9px, var(--yellow) 9.5px) 80px 0 / 20px 10px;
background-color: var(--coral);
}
.app-shell { display: flex; flex-direction: column; height: 100%; max-height: 100dvh; }
header.topbar {
flex-shrink: 0; padding: 8px 12px 6px;
background: rgba(255,252,248,0.92);
border-bottom: 1px solid var(--border);
backdrop-filter: blur(8px);
position: relative; z-index: 30; overflow: visible;
}
.topbar-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.topbar-row + .topbar-row { margin-top: 6px; }
.brand {
font-family: var(--cartoon); font-size: 18px; font-weight: 700;
letter-spacing: 0.02em; color: var(--text);
}
.brand small {
display: block; font-family: var(--font); font-size: 11px;
font-weight: 500; color: var(--text-muted); margin-top: 1px;
}
.seg {
display: flex; gap: 4px; flex-wrap: wrap;
background: rgba(255,255,255,0.7); border: 1px solid var(--border);
border-radius: 999px; padding: 3px;
}
.seg button {
appearance: none; border: none; background: transparent;
color: var(--text-muted); font-weight: 650; font-size: 12px;
padding: 6px 12px; border-radius: 999px; cursor: pointer; font-family: inherit;
transition: background .15s, color .15s;
white-space: nowrap;
}
.seg button.on {
background: linear-gradient(135deg, var(--magenta), var(--orange));
color: #fff; box-shadow: 0 2px 8px rgba(233,30,99,0.25);
}
/* Horizon / candle prediction row: full-width, never wrap mid-button */
.horizon-row {
display: flex; align-items: center; gap: 8px;
flex-wrap: nowrap; width: 100%; min-width: 0;