/** * 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 = `⚠️ ${timeStr}`; } else { timeCell.innerText = timeStr; timeCell.style.color = '#666'; } } }); } 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 = ` ${symbol} Loading... 0 0% 0 - `; tbody.appendChild(row); if (symbol === 'BTC/USD') insertPremiumRow(tbody, 'BTC_PREMIUM', '📊 BTC 프리미엄'); else if (symbol === 'XAU/KRW') insertPremiumRow(tbody, 'GOLD_PREMIUM', '✨ GOLD 프리미엄)'); }); document.querySelectorAll('#assets-tbody input[type="number"]').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'); // 사용자가 타이핑 중이 아닐 때만 업데이트 (포커스 체크) if (document.activeElement !== prevCloseInput) { prevCloseInput.value = currentPrices['KRX/GLD'].가격; } } const prevClose = parseFloat(row.querySelector('.prev-close').value) || 0; 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'); // 'price-up' 대신 선임님 클래스 사용 if (prevClose > 0) { if (change > 0) cell.classList.add('profit'); else if (change < 0) cell.classList.add('loss'); } }); const avgPrice = parseFloat(row.querySelector('.avg-price').value) || 0; 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 = `${label}-계산중...-`; 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 = parseFloat(row.querySelector('.avg-price').value) || 0; 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: parseFloat(r.querySelector('.prev-close').value)||0, average_price: parseFloat(r.querySelector('.avg-price').value)||0, 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(); });