- Reorder init(): loadTrades() runs first, charts second - Wrap chart init in try-catch so UI survives CDN issues - Update start.sh to detect changes in embedded .html/.js/.css
626 lines
22 KiB
JavaScript
626 lines
22 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 class="trade-row" data-id="${t.ID}" onclick="openTradeDetail(${t.ID})">
|
|
<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>';
|
|
}
|
|
}
|
|
|
|
// ---- Trade Detail Modal ----
|
|
function openTradeDetail(id) {
|
|
const modal = document.getElementById('trade-modal');
|
|
const body = document.getElementById('trade-detail-body');
|
|
modal.style.display = 'flex';
|
|
body.innerHTML = '<div class="loading">加载中...</div>';
|
|
|
|
fetch('/api/trade/' + id)
|
|
.then(r => r.json())
|
|
.then(data => {
|
|
const t = data.trade;
|
|
if (!t || !t.ID) {
|
|
body.innerHTML = '<div class="loading text-red">交易数据加载失败</div>';
|
|
return;
|
|
}
|
|
|
|
const opened = new Date(t.OpenedAt);
|
|
const closed = t.ClosedAt ? new Date(t.ClosedAt) : null;
|
|
const dur = closed ? Math.round((closed - opened) / 1000) + 's' : '-';
|
|
const pnlCls = t.NetPnl > 0 ? 'text-green' : t.NetPnl < 0 ? 'text-red' : '';
|
|
|
|
const feeEntry = t.FeeEntry != null ? t.FeeEntry.toFixed(3) + '%' : '-';
|
|
const feeExit = t.FeeExit != null ? t.FeeExit.toFixed(3) + '%' : '-';
|
|
const totalFee = t.FeeEntry != null && t.FeeExit != null
|
|
? (t.FeeEntry + t.FeeExit).toFixed(3) + '%' : '-';
|
|
|
|
const le = t.LongEntry != null ? t.LongEntry.toFixed(6) : '-';
|
|
const lx = t.LongExit != null ? t.LongExit.toFixed(6) : '-';
|
|
const se = t.ShortEntry != null ? t.ShortEntry.toFixed(6) : '-';
|
|
const sx = t.ShortExit != null ? t.ShortExit.toFixed(6) : '-';
|
|
const lpnl = t.LongPnl != null ? t.LongPnl.toFixed(4) + '%' : '-';
|
|
const spnl = t.ShortPnl != null ? t.ShortPnl.toFixed(4) + '%' : '-';
|
|
|
|
body.innerHTML = `<div class="detail-grid">
|
|
<div class="detail-section">
|
|
<h3>概览</h3>
|
|
<div class="detail-row"><span class="label">币种</span><span class="value"><strong>${t.Coin}</strong>/USDT</span></div>
|
|
<div class="detail-row"><span class="label">方向</span><span class="value">${t.Direction || '-'}</span></div>
|
|
<div class="detail-row"><span class="label">状态</span><span class="value">${t.Status === 'closed' ? '已平仓' : t.Status}</span></div>
|
|
<div class="detail-row"><span class="label">加仓次数</span><span class="value">${t.ScaleCount || 0} 次</span></div>
|
|
<div class="detail-row"><span class="label">总规模</span><span class="value">$${(t.AmountUSD || 0).toFixed(0)}</span></div>
|
|
</div>
|
|
<div class="detail-section">
|
|
<h3>时间</h3>
|
|
<div class="detail-row"><span class="label">开仓</span><span class="value">${opened.toLocaleString('zh-CN', { hour12: false })}</span></div>
|
|
<div class="detail-row"><span class="label">平仓</span><span class="value">${closed ? closed.toLocaleString('zh-CN', { hour12: false }) : '-'}</span></div>
|
|
<div class="detail-row"><span class="label">持仓时长</span><span class="value">${dur}</span></div>
|
|
</div>
|
|
<div class="detail-section">
|
|
<h3>价差</h3>
|
|
<div class="detail-row"><span class="label">入场价差</span><span class="value">${t.EntrySpread != null ? t.EntrySpread.toFixed(4) + '%' : '-'}</span></div>
|
|
<div class="detail-row"><span class="label">出场价差</span><span class="value">${t.ExitSpread != null ? t.ExitSpread.toFixed(4) + '%' : '-'}</span></div>
|
|
<div class="detail-row"><span class="label">收敛情况</span><span class="value ${t.Convergence === '价差收敛' ? 'text-green' : t.Convergence === '价差发散' ? 'text-red' : ''}">${t.Convergence || '-'}</span></div>
|
|
<div class="detail-row"><span class="label">平仓原因</span><span class="value">${t.ExitReason || '-'}</span></div>
|
|
</div>
|
|
<div class="detail-section">
|
|
<h3>手续费</h3>
|
|
<div class="detail-row"><span class="label">开仓费</span><span class="value">${feeEntry}</span></div>
|
|
<div class="detail-row"><span class="label">平仓费</span><span class="value">${feeExit}</span></div>
|
|
<div class="detail-row"><span class="label">总手续费</span><span class="value">${totalFee}</span></div>
|
|
</div>
|
|
<div class="detail-section">
|
|
<h3>多仓 ${t.LongExchange || '-'}</h3>
|
|
<div class="detail-row"><span class="label">入场价</span><span class="value">$${le}</span></div>
|
|
<div class="detail-row"><span class="label">出场价</span><span class="value">$${lx}</span></div>
|
|
<div class="detail-row"><span class="label">盈亏</span><span class="value ${t.LongPnl > 0 ? 'text-green' : t.LongPnl < 0 ? 'text-red' : ''}">${lpnl}</span></div>
|
|
</div>
|
|
<div class="detail-section">
|
|
<h3>空仓 ${t.ShortExchange || '-'}</h3>
|
|
<div class="detail-row"><span class="label">入场价</span><span class="value">$${se}</span></div>
|
|
<div class="detail-row"><span class="label">出场价</span><span class="value">$${sx}</span></div>
|
|
<div class="detail-row"><span class="label">盈亏</span><span class="value ${t.ShortPnl > 0 ? 'text-green' : t.ShortPnl < 0 ? 'text-red' : ''}">${spnl}</span></div>
|
|
</div>
|
|
<div class="detail-section detail-section-full">
|
|
<h3>净收益</h3>
|
|
<div class="detail-row" style="font-size:16px"><span class="label">总计</span><span class="value ${pnlCls}" style="font-weight:700">${t.NetPnl != null ? t.NetPnl.toFixed(4) + '%' : '-'}</span></div>
|
|
</div>
|
|
</div>`;
|
|
|
|
// Append orders table if available
|
|
if (data.orders && data.orders.length > 0) {
|
|
const ordersHtml = data.orders.map(o => {
|
|
const typeLabel = o.Type === 'entry' ? '开仓' : o.Type === 'exit' ? '平仓' : o.Type === 'scale' ? '加仓' : o.Type;
|
|
return `<tr><td>${typeLabel}</td><td>${o.Side === 'buy' ? '买' : '卖'}</td><td>${o.Exchange}</td><td>$${o.Price ? o.Price.toFixed(6) : '-'}</td><td>${o.Size || '-'}</td><td>${o.Fee ? o.Fee.toFixed(4) + '%' : '-'}</td><td>${o.OrderID ? o.OrderID.substring(0, 12) + '...' : '-'}</td></tr>`;
|
|
}).join('');
|
|
body.innerHTML += `<div class="detail-section detail-section-full" style="border-top:1px solid var(--border)">
|
|
<h3>订单明细 (${data.orders.length})</h3>
|
|
<table class="detail-orders">
|
|
<thead><tr><th>类型</th><th>方向</th><th>交易所</th><th>价格</th><th>数量</th><th>手续费</th><th>订单ID</th></tr></thead>
|
|
<tbody>${ordersHtml}</tbody>
|
|
</table>
|
|
</div>`;
|
|
}
|
|
})
|
|
.catch(err => {
|
|
body.innerHTML = '<div class="loading text-red">加载失败: ' + err.message + '</div>';
|
|
});
|
|
}
|
|
|
|
function closeTradeDetail() {
|
|
document.getElementById('trade-modal').style.display = 'none';
|
|
}
|
|
|
|
// Close modal on overlay click
|
|
document.addEventListener('click', function(e) {
|
|
const modal = document.getElementById('trade-modal');
|
|
if (e.target === modal) closeTradeDetail();
|
|
});
|
|
|
|
// Close on Escape
|
|
document.addEventListener('keydown', function(e) {
|
|
if (e.key === 'Escape') closeTradeDetail();
|
|
});
|
|
|
|
// Expose modal functions to global scope for HTML onclick handlers
|
|
window.openTradeDetail = openTradeDetail;
|
|
window.closeTradeDetail = closeTradeDetail;
|
|
|
|
// ---- Init ----
|
|
function init() {
|
|
connectSSE();
|
|
loadTrades(); // run before charts in case Chart CDN is slow
|
|
setInterval(loadTrades, 10000);
|
|
try { initPriceChart(); } catch(e) { console.warn('Price chart init failed:', e); }
|
|
try { initSpreadChart(); } catch(e) { console.warn('Spread chart init failed:', e); }
|
|
}
|
|
|
|
if (document.readyState === 'loading') {
|
|
document.addEventListener('DOMContentLoaded', init);
|
|
} else {
|
|
init();
|
|
}
|
|
|
|
})();
|