Files
AssetPilot/asset_pilot_docker/static/js/app.js
2026-02-13 18:40:48 +09:00

370 lines
17 KiB
JavaScript

/**
* Asset Pilot - Frontend Logic (Integrated Watchdog Version)
*/
// 전역 변수 - 선임님 기존 변수명 유지
let currentPrices = {};
let userAssets = [];
let alertSettings = {};
let serverTimeOffset = 0;
const ASSET_SYMBOLS = [
'XAU/USD', 'XAU/CNY', 'XAU/GBP', 'USD/DXY', 'USD/KRW',
'BTC/KRW', 'BTC/USD', 'KRX/GLD', 'XAU/KRW'
];
function getInvestingUrl(symbol) {
const mapping = {
'XAU/USD': 'https://kr.investing.com/currencies/xau-usd',
'XAU/CNY': 'https://kr.investing.com/currencies/xau-cny',
'XAU/GBP': 'https://kr.investing.com/currencies/xau-gbp',
'USD/DXY': 'https://kr.investing.com/indices/usdollar',
'USD/KRW': 'https://kr.investing.com/currencies/usd-krw',
'BTC/USD': 'https://www.binance.com/en/trade/BTC_USD?type=spot',
'BTC/KRW': 'https://upbit.com/exchange?code=CRIX.UPBIT.KRW-BTC',
'KRX/GLD': 'https://m.stock.naver.com/marketindex/metals/M04020000',
'XAU/KRW': 'https://kr.investing.com/currencies/xau-krw'
};
return mapping[symbol] || '';
}
document.addEventListener('DOMContentLoaded', async () => {
await Promise.all([loadAssets(), loadInitialPrices()]);
loadAlertSettings();
startPriceStream();
document.getElementById('refresh-btn').addEventListener('click', refreshData);
document.getElementById('alert-settings-btn').addEventListener('click', openAlertModal);
document.querySelector('.close').addEventListener('click', closeAlertModal);
document.getElementById('save-alerts').addEventListener('click', saveAlertSettings);
document.getElementById('cancel-alerts').addEventListener('click', closeAlertModal);
setInterval(checkDataFreshness, 1000);
});
async function loadInitialPrices() {
try {
const response = await fetch('/api/prices');
if (response.ok) {
const result = await response.json();
processPriceData(result);
}
} catch (error) { console.error('초기 가격 로드 실패:', error); }
}
function processPriceData(result) {
currentPrices = result.prices || result;
if (result.fetch_status) {
updateSystemStatus(result.fetch_status, result.last_heartbeat, result.server_time);
}
updatePricesInTable();
calculatePnLRealtime();
}
function startPriceStream() {
const eventSource = new EventSource('/api/stream');
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
currentPrices = data;
updatePricesInTable();
calculatePnLRealtime();
document.getElementById('status-indicator').style.backgroundColor = '#10b981';
};
eventSource.onerror = () => {
document.getElementById('status-indicator').style.backgroundColor = '#ef4444';
};
}
function updateSystemStatus(status, lastHeartbeat, serverTimeStr) {
const dot = document.getElementById('status-dot');
const text = document.getElementById('status-text');
const syncTime = document.getElementById('last-sync-time');
if (dot && text) {
if (status === 'healthy') {
dot.className = "status-dot status-healthy";
text.innerText = "데이터 수집 엔진 정상";
} else {
dot.className = "status-dot status-stale";
text.innerText = "수집 지연 (Watchdog 감지)";
}
}
if (syncTime && lastHeartbeat) {
const hbTime = lastHeartbeat.split('T')[1].substring(0, 8);
syncTime.innerText = `Last Heartbeat: ${hbTime}`;
}
}
function checkDataFreshness() {
const now = new Date();
ASSET_SYMBOLS.forEach(symbol => {
const priceData = currentPrices[symbol];
if (!priceData || !priceData.업데이트) return;
const updateTime = new Date(priceData.업데이트);
const diffSeconds = Math.floor((now - updateTime) / 1000);
const row = document.querySelector(`tr[data-symbol="${symbol}"]`);
if (!row) return;
const timeCell = row.querySelector('.update-time-cell');
if (timeCell) {
const timeStr = priceData.업데이트.split('T')[1].substring(0, 8);
if (diffSeconds > 60) {
timeCell.innerHTML = `<span style="color: #ef4444; font-weight:bold;">⚠️ ${timeStr}</span>`;
} else {
timeCell.innerText = timeStr;
timeCell.style.color = '#666';
}
}
});
}
// ─── 천단위 표시 헬퍼 ────────────────────────────────────────
// 평상시: type="text" + 천단위 쉼표 표시
// 포커스 시: type="number" + 원본 숫자로 편집 가능
// blur 시: 다시 천단위 표시로 전환
function attachThousandFormat(input) {
// 초기 rawValue 저장 및 표시
input.dataset.rawValue = input.value;
_showFormatted(input);
input.addEventListener('focus', () => {
input.type = 'number';
input.value = input.dataset.rawValue || '';
});
input.addEventListener('blur', () => {
// blur 시점의 값을 rawValue에 저장
if (input.value !== '') {
input.dataset.rawValue = input.value;
}
_showFormatted(input);
});
// change 이벤트에서도 rawValue 동기화 (외부 change 핸들러가 읽기 전에)
input.addEventListener('change', () => {
input.dataset.rawValue = input.value;
});
}
function _showFormatted(input) {
const val = parseFloat(input.dataset.rawValue);
if (!isNaN(val)) {
input.type = 'text';
input.value = val.toLocaleString('ko-KR');
}
}
// rawValue에서 숫자를 안전하게 읽는 헬퍼
function getRawValue(input) {
return parseFloat(input.dataset.rawValue ?? input.value) || 0;
}
// 외부(updatePricesInTable)에서 프로그래밍 방식으로 값 갱신 시 사용
function setRawValue(input, num) {
input.dataset.rawValue = num;
// 현재 포커스 중이 아닐 때만 표시 갱신
if (document.activeElement !== input) {
_showFormatted(input);
}
}
function renderAssetsTable() {
const tbody = document.getElementById('assets-tbody');
tbody.innerHTML = '';
ASSET_SYMBOLS.forEach(symbol => {
const asset = userAssets.find(a => a.symbol === symbol) || {
symbol: symbol, previous_close: 0, average_price: 0, quantity: 0
};
const row = document.createElement('tr');
row.dataset.symbol = symbol;
row.innerHTML = `
<td><a href="${getInvestingUrl(symbol)}" target="_blank" class="investing-btn">${symbol}</a></td>
<td class="numeric input-cell"><input type="number" class="prev-close" value="${asset.previous_close}" step="0.01" data-symbol="${symbol}"></td>
<td class="numeric current-price">Loading...</td>
<td class="numeric change">0</td>
<td class="numeric change-percent">0%</td>
<td class="numeric input-cell"><input type="number" class="avg-price" value="${asset.average_price}" step="0.01" data-symbol="${symbol}"></td>
<td class="numeric input-cell"><input type="number" class="quantity" value="${asset.quantity}" step="${symbol.includes('BTC') ? '0.00000001' : '0.01'}" data-symbol="${symbol}"></td>
<td class="numeric buy-total">0</td>
<td class="numeric update-time-cell" style="font-size: 0.85em; color: #666;">-</td>
`;
tbody.appendChild(row);
// 전일종가, 평단가에만 천단위 포맷 적용
attachThousandFormat(row.querySelector('.prev-close'));
attachThousandFormat(row.querySelector('.avg-price'));
if (symbol === 'BTC/USD') insertPremiumRow(tbody, 'BTC_PREMIUM', '📊 BTC 프리미엄');
else if (symbol === 'XAU/KRW') insertPremiumRow(tbody, 'GOLD_PREMIUM', '✨ GOLD 프리미엄)');
});
document.querySelectorAll('#assets-tbody input').forEach(input => {
input.addEventListener('change', (e) => {
handleAssetChange(e);
updatePricesInTable();
});
});
}
function updatePricesInTable() {
const rows = document.querySelectorAll('#assets-tbody tr:not(.premium-row)');
const usdKrw = currentPrices['USD/KRW']?.가격 || 0;
rows.forEach(row => {
const symbol = row.dataset.symbol;
const priceData = currentPrices[symbol];
if (!priceData || !priceData.가격) return;
const currentPrice = priceData.가격;
const decimalPlaces = (symbol.includes('USD') || symbol.includes('DXY')) ? 2 : 0;
// XAU/KRW: KRX/GLD 가격을 전일종가 input에 실시간 주입
if (symbol === 'XAU/KRW' && currentPrices['KRX/GLD']) {
const prevCloseInput = row.querySelector('.prev-close');
setRawValue(prevCloseInput, currentPrices['KRX/GLD'].가격);
}
const prevCloseInput = row.querySelector('.prev-close');
const prevClose = getRawValue(prevCloseInput);
const currentPriceCell = row.querySelector('.current-price');
currentPriceCell.textContent = formatNumber(currentPrice, decimalPlaces);
const change = currentPrice - prevClose;
const changePercent = prevClose > 0 ? (change / prevClose * 100) : 0;
const changeCell = row.querySelector('.change');
const changePercentCell = row.querySelector('.change-percent');
changeCell.textContent = formatNumber(change, decimalPlaces);
changePercentCell.textContent = `${formatNumber(changePercent, 2)}%`;
// [교정] 선임님 기존 클래스명 profit/loss로 정확히 변경
const cellsToColor = [currentPriceCell, changeCell, changePercentCell];
cellsToColor.forEach(cell => {
cell.classList.remove('profit', 'loss');
if (prevClose > 0) {
if (change > 0) cell.classList.add('profit');
else if (change < 0) cell.classList.add('loss');
}
});
const avgPrice = getRawValue(row.querySelector('.avg-price'));
const quantity = parseFloat(row.querySelector('.quantity').value) || 0;
row.querySelector('.buy-total').textContent = formatNumber(avgPrice * quantity, 0);
});
if (usdKrw > 0) {
const btcKrw = currentPrices['BTC/KRW']?.가격;
const btcUsd = currentPrices['BTC/USD']?.가격;
if (btcKrw && btcUsd) {
const btcGlobalInKrw = btcUsd * usdKrw;
const btcPrem = btcKrw - btcGlobalInKrw;
const btcPremPct = (btcPrem / btcGlobalInKrw) * 100;
const btcRow = document.getElementById('BTC_PREMIUM');
const valCell = btcRow.querySelector('.premium-value');
const diffCell = btcRow.querySelector('.premium-diff');
valCell.textContent = formatNumber(btcPrem, 0);
diffCell.textContent = `(차이: ${formatNumber(btcPremPct, 2)}%)`;
[valCell, diffCell].forEach(c => {
c.classList.remove('profit', 'loss');
if (btcPrem > 0) c.classList.add('profit'); else if (btcPrem < 0) c.classList.add('loss');
});
}
const krxGold = currentPrices['KRX/GLD']?.가격;
const xauUsd = currentPrices['XAU/USD']?.가격;
if (krxGold && xauUsd) {
const goldGlobalInKrw = (xauUsd / 31.1035) * usdKrw;
const goldPrem = krxGold - goldGlobalInKrw;
const goldPremPct = (goldPrem / goldGlobalInKrw) * 100;
const goldRow = document.getElementById('GOLD_PREMIUM');
const valCell = goldRow.querySelector('.premium-value');
const diffCell = goldRow.querySelector('.premium-diff');
valCell.textContent = formatNumber(goldPrem, 0);
diffCell.textContent = `(차이: ${formatNumber(goldPremPct, 2)}%)`;
[valCell, diffCell].forEach(c => {
c.classList.remove('profit', 'loss');
if (goldPrem > 0) c.classList.add('profit'); else if (goldPrem < 0) c.classList.add('loss');
});
}
}
}
async function loadAssets() { try { const r = await fetch('/api/assets'); userAssets = await r.json(); renderAssetsTable(); } catch(e) { console.error(e); } }
async function loadAlertSettings() { try { const r = await fetch('/api/alerts/settings'); alertSettings = await r.json(); } catch(e) { console.error(e); } }
function insertPremiumRow(tbody, id, label) {
const row = document.createElement('tr');
row.id = id; row.className = 'premium-row';
row.innerHTML = `<td style="color:#6366f1;font-weight:bold;background:#f8fafc;">${label}</td><td class="numeric" style="background:#f8fafc;">-</td><td class="numeric premium-value" style="font-weight:bold;background:#f8fafc;">계산중...</td><td class="numeric premium-diff" colspan="2" style="background:#f8fafc;font-weight:bold;">-</td><td colspan="4" style="background:#f8fafc;"></td>`;
tbody.appendChild(row);
}
function calculatePnLRealtime() {
let totalBuy = 0, totalCurrentValue = 0;
let goldBuy = 0, goldCurrent = 0, btcBuy = 0, btcCurrent = 0;
const usdKrw = currentPrices['USD/KRW']?.가격 || 1400;
const rows = document.querySelectorAll('#assets-tbody tr:not(.premium-row)');
rows.forEach(row => {
const symbol = row.dataset.symbol;
const priceData = currentPrices[symbol];
if (!priceData) return;
const currentPrice = priceData.가격;
const avgPrice = getRawValue(row.querySelector('.avg-price'));
const quantity = parseFloat(row.querySelector('.quantity').value) || 0;
let buyValue = avgPrice * quantity;
let currentValue = currentPrice * quantity;
if (symbol.includes('USD') && symbol !== 'USD/KRW') { buyValue *= usdKrw; currentValue *= usdKrw; }
totalBuy += buyValue; totalCurrentValue += currentValue;
if (symbol.includes('XAU') || symbol.includes('GLD')) { goldBuy += buyValue; goldCurrent += currentValue; }
else if (symbol.includes('BTC')) { btcBuy += buyValue; btcCurrent += currentValue; }
});
updatePnLCard('total-pnl', 'total-percent', totalCurrentValue - totalBuy, totalBuy > 0 ? ((totalCurrentValue - totalBuy) / totalBuy * 100) : 0);
updatePnLCard('gold-pnl', 'gold-percent', goldCurrent - goldBuy, goldBuy > 0 ? ((goldCurrent - goldBuy) / goldBuy * 100) : 0);
updatePnLCard('btc-pnl', 'btc-percent', btcCurrent - btcBuy, btcBuy > 0 ? ((btcCurrent - btcBuy) / btcBuy * 100) : 0);
}
function updatePnLCard(vId, pId, v, p) {
const vE = document.getElementById(vId), pE = document.getElementById(pId);
if (!vE || !pE) return;
vE.textContent = formatNumber(v, 0) + ' 원'; pE.textContent = formatNumber(p, 2) + '%';
const sC = v > 0 ? 'profit' : v < 0 ? 'loss' : '';
vE.className = `pnl-value ${sC}`; pE.className = `pnl-percent ${sC}`;
}
async function handleAssetChange(e) {
const i = e.target; const s = i.dataset.symbol; const r = i.closest('tr');
const d = {
symbol: s,
previous_close: getRawValue(r.querySelector('.prev-close')),
average_price: getRawValue(r.querySelector('.avg-price')),
quantity: parseFloat(r.querySelector('.quantity').value) || 0
};
try { await fetch('/api/assets', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(d) }); calculatePnLRealtime(); } catch(err) { console.error(err); }
}
function openAlertModal() {
document.getElementById('급등락_감지').checked = alertSettings.급등락_감지 || false;
document.getElementById('급등락_임계값').value = alertSettings.급등락_임계값 || 3.0;
document.getElementById('목표수익률_감지').checked = alertSettings.목표수익률_감지 || false;
document.getElementById('목표수익률').value = alertSettings.목표수익률 || 10.0;
document.getElementById('특정가격_감지').checked = alertSettings.특정가격_감지 || false;
document.getElementById('금_목표가격').value = alertSettings._목표가격 || 100000;
document.getElementById('BTC_목표가격').value = alertSettings.BTC_목표가격 || 100000000;
document.getElementById('alert-modal').classList.add('active');
}
function closeAlertModal() { document.getElementById('alert-modal').classList.remove('active'); }
async function saveAlertSettings() {
const settings = { 급등락_감지: document.getElementById('급등락_감지').checked, 급등락_임계값: parseFloat(document.getElementById('급등락_임계값').value), 목표수익률_감지: document.getElementById('목표수익률_감지').checked, 목표수익률: parseFloat(document.getElementById('목표수익률').value), 특정가격_감지: document.getElementById('특정가격_감지').checked, _목표가격: parseInt(document.getElementById('금_목표가격').value), BTC_목표가격: parseInt(document.getElementById('BTC_목표가격').value) };
try { const r = await fetch('/api/alerts/settings', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ settings }) }); if (r.ok) { alertSettings = settings; closeAlertModal(); } } catch(err) { console.error(err); }
}
async function refreshData() { await Promise.all([loadAssets(), loadInitialPrices()]); }
function formatNumber(v, d = 0) { if (v === null || v === undefined || isNaN(v)) return 'N/A'; return v.toLocaleString('ko-KR', { minimumFractionDigits: d, maximumFractionDigits: d }); }
window.addEventListener('click', (e) => { if (e.target === document.getElementById('alert-modal')) closeAlertModal(); });