Files
exchange-monitor-go/web/static/app.js
T
jackyu66git beb3611778 Phase 3: Real-time enhancements
P3-1: Scan optimization — only BG↔HL (50+ pair combos → 2)
P3-2: Real-time spread chart — spreadHistory ring buffer +
      /api/spread-history endpoint + Chart.js spread chart
P3-3: Live position PnL — positions SSE now includes
      estimated current profit/loss + current spread
P3-4: Real-time trade events — trader.OnTradeEvent callback
      fires SSE 'trade_open' / 'trade_close' immediately
P3-5: Connection status monitoring — tracks last update time
      per exchange, broadcast via stats.connections + /api/connections

Frontend: spread chart card, PnL column in positions,
          connection status dots in stats bar,
          green/red border flash on trade events
2026-05-03 18:05:19 +08:00

508 lines
15 KiB
JavaScript

/* ============================================================
Exchange Monitor Dashboard — Frontend Logic v3 (P3)
============================================================ */
(function() {
'use strict';
// ---- DOM refs ----
const $ = id => document.getElementById(id);
const els = {
clock: $('clock'),
connStatus: $('conn-status'),
connDetail: $('conn-detail'),
pricesAge: $('prices-age'),
priceBody: $('price-body'),
arbBody: $('arb-body'),
posBody: $('positions-body'),
tradesBody: $('trades-body'),
statTotal: $('stat-total'),
statConv: $('stat-converged'),
statDiv: $('stat-diverged'),
statFlat: $('stat-flat'),
statPos: $('stat-positions'),
statCoins: $('stat-coins'),
chartCoin: $('chart-coin'),
chartExch: $('chart-exchange'),
chartCanvas: $('priceChart'),
spreadCoin: $('spread-coin'),
spreadCanvas: $('spreadChart'),
};
// ---- Clock ----
function updateClock() {
const now = new Date();
els.clock.textContent = now.toLocaleTimeString('zh-CN', { hour12: false });
}
setInterval(updateClock, 1000);
updateClock();
const EXCHANGES = ['Binance', 'HyperLiquid', 'Bitget', 'dYdX'];
const COINS = ['DOGE', 'LINK', 'ONDO', 'OP', 'WIF', 'ARB'];
function formatPrice(p) {
if (p == null || p <= 0) return '-';
if (p >= 100) return p.toFixed(2);
if (p >= 1) return p.toFixed(4);
return p.toFixed(6);
}
function priceClass(last, cur) {
if (last == null || cur == null) return '';
return cur > last ? 'text-green' : cur < last ? 'text-red' : '';
}
function pnlClass(val) {
if (val == null) return '';
return val > 0 ? 'text-green' : val < 0 ? 'text-red' : '';
}
// ---- Price cache for chart data ----
const priceCache = {};
// ---- SSE Connection ----
let eventSource = null;
function connectSSE() {
if (eventSource) eventSource.close();
eventSource = new EventSource('/events');
eventSource.addEventListener('connected', () => {
els.connStatus.textContent = '● 已连接';
els.connStatus.className = 'status-online';
});
eventSource.onerror = () => {
els.connStatus.textContent = '● 已断开 (重连中...)';
els.connStatus.className = 'status-offline';
setTimeout(connectSSE, 3000);
};
eventSource.onmessage = (e) => {
try {
const msg = JSON.parse(e.data);
const handler = eventHandlers[msg.event];
if (handler) handler(msg.data);
} catch(err) {
// ignore parse errors
}
};
}
// ---- Event Handlers ----
const eventHandlers = {};
eventHandlers.prices = (prices) => {
if (!prices || prices.length === 0) return;
let html = '';
let coinsOnline = 0;
for (const coin of COINS) {
const row = prices.find(p => p.coin === coin);
if (!row) {
html += `<tr><td>${coin}</td>${EXCHANGES.map(() => '<td class="text-dim">-</td>').join('')}<td class="text-dim">-</td></tr>`;
continue;
}
coinsOnline++;
const cells = EXCHANGES.map(ex => {
const p = row[ex];
const sp = row[ex + '_spread'];
const key = coin + '.' + ex;
const prev = priceCache[key];
const curP = p || 0;
const cls = prev ? priceClass(prev.last, curP) : '';
if (prev) {
prev.last = curP;
} else {
priceCache[key] = { last: curP, points: [] };
}
if (p > 0) {
if (!priceCache[key]) priceCache[key] = { last: p, points: [] };
priceCache[key].points.push({ t: Date.now(), p: p });
if (priceCache[key].points.length > 500) {
priceCache[key].points = priceCache[key].points.slice(-500);
}
}
let display = formatPrice(p);
if (sp && sp > 0.01) {
display += `<span class="text-dim" style="font-size:10px"> (${sp.toFixed(3)}%)</span>`;
}
return `<td class="${cls}">${display}</td>`;
});
// P3-2: Add spread column
const spread = row['bg_hl_spread'];
const spreadCls = spread > 0.1 ? 'text-green' : spread < -0.1 ? 'text-red' : '';
const spreadStr = spread != null ? spread.toFixed(4) + '%' : '-';
html += `<tr><td><strong>${coin}</strong></td>${cells.join('')}<td class="${spreadCls}">${spreadStr}</td></tr>`;
}
els.priceBody.innerHTML = html;
els.pricesAge.textContent = new Date().toLocaleTimeString('zh-CN', { hour12: false });
updateChartSelectors(prices);
};
eventHandlers.arb = (opps) => {
if (!opps || opps.length === 0) {
els.arbBody.innerHTML = '<tr><td colspan="5" class="text-dim">暂无套利机会</td></tr>';
return;
}
const html = opps.slice(0, 10).map(opp => {
const cls = opp.net_profit > 0.1 ? 'text-green' : opp.net_profit > 0.05 ? 'text-yellow' : '';
return `<tr>
<td>${opp.coin}</td>
<td>${opp.direction}</td>
<td class="text-right">${formatPrice(opp.buy_price)}</td>
<td class="text-right">${formatPrice(opp.sell_price)}</td>
<td class="text-right ${cls}"><strong>${opp.net_profit.toFixed(4)}</strong></td>
</tr>`;
}).join('');
els.arbBody.innerHTML = html;
};
// P3-3: Positions with live PnL
eventHandlers.positions = (positions) => {
if (!positions || positions.length === 0) {
els.posBody.innerHTML = '<tr><td colspan="8" class="text-dim">无持仓</td></tr>';
return;
}
const html = positions.map(p => {
const pnl = p.pnl_est;
const pnlStr = pnl != null ? pnl.toFixed(4) + '%' : '-';
const curSpread = p.current_spread != null ? p.current_spread.toFixed(4) + '%' : '-';
return `<tr>
<td><strong>${p.coin}</strong></td>
<td>${p.direction}</td>
<td class="text-right">$${p.amount_usd.toFixed(0)}</td>
<td class="text-right">${p.entry_spread.toFixed(4)}%</td>
<td class="text-right">${curSpread}</td>
<td class="text-right ${pnlClass(pnl)}"><strong>${pnlStr}</strong></td>
<td class="text-right">${p.scales}</td>
<td>${p.duration}</td>
</tr>`;
}).join('');
els.posBody.innerHTML = html;
};
// P3-5: Connection status in stats
eventHandlers.stats = (stats) => {
els.statTotal.textContent = stats.total_trades || 0;
els.statConv.textContent = stats.converged || 0;
els.statDiv.textContent = stats.diverged || 0;
els.statFlat.textContent = stats.flat || 0;
els.statPos.textContent = stats.open_positions || 0;
els.statCoins.textContent = stats.coins || 0;
// Connection status dots
if (stats.connections) {
const dots = Object.entries(stats.connections).map(([ex, status]) => {
const color = status === 'online' ? '#3fb950' : status === 'stale' ? '#d29922' : '#f85149';
return `<span style="color:${color}">●</span> ${ex}`;
}).join(' ');
els.connDetail.innerHTML = dots;
}
};
// P3-4: Real-time trade events
eventHandlers.trade_open = (trade) => {
// Flash the positions card to draw attention
const card = $('positions-card');
card.style.transition = 'border-color 0.3s';
card.style.borderColor = '#3fb950';
setTimeout(() => { card.style.borderColor = ''; }, 2000);
// Refresh trades table
setTimeout(loadTrades, 500);
};
eventHandlers.trade_close = (trade) => {
const card = $('trades-card');
card.style.transition = 'border-color 0.3s';
card.style.borderColor = trade.pnl_pct > 0 ? '#3fb950' : '#f85149';
setTimeout(() => { card.style.borderColor = ''; }, 2000);
setTimeout(loadTrades, 500);
};
// ---- Price Chart ----
let priceChart = null;
function initPriceChart() {
const ctx = els.chartCanvas.getContext('2d');
priceChart = new Chart(ctx, {
type: 'line',
data: { datasets: [{
label: 'Price',
data: [],
borderColor: '#58a6ff',
backgroundColor: 'rgba(88, 166, 255, 0.1)',
borderWidth: 2,
pointRadius: 0,
fill: true,
tension: 0.2,
}] },
options: {
responsive: true,
maintainAspectRatio: false,
animation: { duration: 0 },
plugins: {
legend: { display: false },
tooltip: {
mode: 'index', intersect: false,
callbacks: {
title: (items) => items.length ? new Date(items[0].parsed.x).toLocaleTimeString('zh-CN', { hour12: false }) : '',
label: (item) => item.parsed.y.toFixed(4),
},
},
},
scales: {
x: {
type: 'linear',
ticks: {
color: '#8b949e', maxTicksLimit: 10,
callback: (v) => new Date(v).toLocaleTimeString('zh-CN', { hour12: false, hour: '2-digit', minute: '2-digit' }),
},
grid: { color: 'rgba(48,54,61,0.5)' },
},
y: {
ticks: { color: '#8b949e', callback: (v) => v.toFixed(4) },
grid: { color: 'rgba(48,54,61,0.3)' },
},
},
},
});
}
// ---- P3-2: Spread Chart ----
let spreadChart = null;
function initSpreadChart() {
const ctx = els.spreadCanvas.getContext('2d');
spreadChart = new Chart(ctx, {
type: 'line',
data: { datasets: [{
label: 'BG↔HL Spread %',
data: [],
borderColor: '#d29922',
backgroundColor: 'rgba(210, 153, 34, 0.1)',
borderWidth: 2,
pointRadius: 0,
fill: true,
tension: 0.2,
}] },
options: {
responsive: true,
maintainAspectRatio: false,
animation: { duration: 0 },
plugins: {
legend: { display: false },
tooltip: {
mode: 'index', intersect: false,
callbacks: {
title: (items) => items.length ? new Date(items[0].parsed.x).toLocaleTimeString('zh-CN', { hour12: false }) : '',
label: (item) => item.parsed.y.toFixed(4) + '%',
},
},
},
scales: {
x: {
type: 'linear',
ticks: {
color: '#8b949e', maxTicksLimit: 10,
callback: (v) => new Date(v).toLocaleTimeString('zh-CN', { hour12: false, hour: '2-digit', minute: '2-digit' }),
},
grid: { color: 'rgba(48,54,61,0.5)' },
},
y: {
ticks: { color: '#8b949e', callback: (v) => v.toFixed(3) + '%' },
grid: { color: 'rgba(48,54,61,0.3)' },
},
},
},
});
}
// ---- Chart Selectors ----
function updateChartSelectors(prices) {
const coinSel = els.chartCoin;
const exSel = els.chartExch;
const spreadSel = els.spreadCoin;
// Price chart coin selector
if (coinSel.options.length <= 1) {
const cur = coinSel.value;
coinSel.innerHTML = '<option value="">-- 选择币种 --</option>';
for (const row of prices) {
const opt = document.createElement('option');
opt.value = row.coin; opt.textContent = row.coin;
coinSel.appendChild(opt);
}
if (cur) coinSel.value = cur;
else if (prices.length > 0) coinSel.value = prices[0].coin;
}
// Price chart exchange selector
if (exSel.options.length <= 1) {
exSel.innerHTML = '<option value="">-- 选择交易所 --</option>';
for (const ex of EXCHANGES) {
const opt = document.createElement('option');
opt.value = ex; opt.textContent = ex;
exSel.appendChild(opt);
}
exSel.value = 'HyperLiquid';
}
// Spread chart coin selector
if (spreadSel.options.length <= 1) {
const cur = spreadSel.value;
spreadSel.innerHTML = '<option value="">-- 选择币种 --</option>';
for (const row of prices) {
const opt = document.createElement('option');
opt.value = row.coin; opt.textContent = row.coin;
spreadSel.appendChild(opt);
}
if (cur) spreadSel.value = cur;
else if (prices.length > 0) spreadSel.value = prices[0].coin;
}
// Update charts on selection change
const selCoin = coinSel.value, selEx = exSel.value;
if (selCoin && selEx) updatePriceChart(selCoin, selEx);
const spCoin = spreadSel.value;
if (spCoin) updateSpreadChart(spCoin);
}
function updatePriceChart(coin, exchange) {
const key = coin + '.' + exchange;
const cache = priceCache[key];
if (!cache || !cache.points || cache.points.length < 2) {
if (priceChart) {
priceChart.data.datasets[0].data = [];
priceChart.data.datasets[0].label = `${coin} @ ${exchange}`;
priceChart.update('none');
}
return;
}
const data = cache.points.map(p => ({ x: p.t, y: p.p }));
if (priceChart) {
priceChart.data.datasets[0].data = data;
priceChart.data.datasets[0].label = `${coin} @ ${exchange}`;
priceChart.update('none');
}
}
async function updateSpreadChart(coin) {
try {
const resp = await fetch(`/api/spread-history?coin=${coin}`);
const data = await resp.json();
const pts = data.points || [];
if (pts.length < 2) {
if (spreadChart) {
spreadChart.data.datasets[0].data = [];
spreadChart.data.datasets[0].label = `${coin} BG↔HL`;
spreadChart.update('none');
}
return;
}
const chartData = pts.map(p => ({ x: p.t, y: p.s }));
if (spreadChart) {
spreadChart.data.datasets[0].data = chartData;
spreadChart.data.datasets[0].label = `${coin} BG↔HL`;
spreadChart.update('none');
}
} catch (err) {
// ignore
}
}
// ---- Chart controls ----
els.chartCoin.addEventListener('change', () => {
const coin = els.chartCoin.value;
const ex = els.chartExch.value;
if (coin && ex) updatePriceChart(coin, ex);
});
els.chartExch.addEventListener('change', () => {
const coin = els.chartCoin.value;
const ex = els.chartExch.value;
if (coin && ex) updatePriceChart(coin, ex);
});
els.spreadCoin.addEventListener('change', () => {
if (els.spreadCoin.value) updateSpreadChart(els.spreadCoin.value);
});
// ---- Auto-refresh charts ----
setInterval(() => {
const coin = els.chartCoin.value;
const ex = els.chartExch.value;
if (coin && ex) updatePriceChart(coin, ex);
}, 2000);
setInterval(() => {
if (els.spreadCoin.value) updateSpreadChart(els.spreadCoin.value);
}, 3000);
// ---- Trades from API ----
async function loadTrades() {
try {
const resp = await fetch('/api/trades');
const data = await resp.json();
const trades = data.trades || [];
if (trades.length === 0) {
els.tradesBody.innerHTML = '<tr><td colspan="8" class="text-dim">暂无交易记录</td></tr>';
return;
}
const html = trades.slice(0, 20).map(t => {
const pnlCls = t.NetPnl > 0 ? 'text-green' : t.NetPnl < 0 ? 'text-red' : '';
const convCls = t.Convergence === '价差收敛' ? 'text-green' :
t.Convergence === '价差发散' ? 'text-red' : 'text-yellow';
return `<tr>
<td class="text-dim">${t.ClosedAt ? new Date(t.ClosedAt).toLocaleTimeString('zh-CN', { hour12: false }) : '-'}</td>
<td><strong>${t.Coin}</strong></td>
<td>${t.Direction}</td>
<td class="text-right">${t.EntrySpread != null ? t.EntrySpread.toFixed(4) : '-'}</td>
<td class="text-right">${t.ExitSpread != null ? t.ExitSpread.toFixed(4) : '-'}</td>
<td class="text-right ${pnlCls}"><strong>${t.NetPnl != null ? t.NetPnl.toFixed(4) : '-'}</strong></td>
<td class="${convCls}">${t.Convergence || '-'}</td>
<td>${t.ExitReason || '-'}</td>
</tr>`;
}).join('');
els.tradesBody.innerHTML = html;
} catch (err) {
els.tradesBody.innerHTML = '<tr><td colspan="8" class="text-red">加载失败</td></tr>';
}
}
// ---- Init ----
function init() {
connectSSE();
initPriceChart();
initSpreadChart();
loadTrades();
setInterval(loadTrades, 10000);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();