Very Good Web Server Work

This commit is contained in:
Wind
2026-02-13 18:40:48 +09:00
parent 18fa480c84
commit d4f1ca87ab
12 changed files with 1369 additions and 1352 deletions

View File

@@ -1,140 +1,245 @@
// 전역 변수
/**
* Asset Pilot - Frontend Logic (Integrated Watchdog Version)
*/
// 전역 변수 - 선임님 기존 변수명 유지
let currentPrices = {};
let userAssets = [];
let alertSettings = {};
let serverTimeOffset = 0;
// 초기화
document.addEventListener('DOMContentLoaded', () => {
loadAssets();
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);
// 주기적 PnL 업데이트
setInterval(updatePnL, 1000);
setInterval(checkDataFreshness, 1000);
});
// 자산 데이터 로드
async function loadAssets() {
async function loadInitialPrices() {
try {
const response = await fetch('/api/assets');
userAssets = await response.json();
renderAssetsTable();
} catch (error) {
console.error('자산 로드 실패:', error);
}
const response = await fetch('/api/prices');
if (response.ok) {
const result = await response.json();
processPriceData(result);
}
} catch (error) { console.error('초기 가격 로드 실패:', error); }
}
// 알림 설정 로드
async function loadAlertSettings() {
try {
const response = await fetch('/api/alerts/settings');
alertSettings = await response.json();
} 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) => {
currentPrices = JSON.parse(event.data);
const data = JSON.parse(event.data);
currentPrices = data;
updatePricesInTable();
updateLastUpdateTime();
calculatePnLRealtime();
document.getElementById('status-indicator').style.backgroundColor = '#10b981';
};
eventSource.onerror = () => {
console.error('SSE 연결 오류');
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 = '';
const assets = [
'XAU/USD', 'XAU/CNY', 'XAU/GBP', 'USD/DXY', 'USD/KRW',
'BTC/USD', 'BTC/KRW', 'KRX/GLD', 'XAU/KRW'
];
assets.forEach(symbol => {
const asset = userAssets.find(a => a.symbol === symbol);
if (!asset) return;
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;
const decimalPlaces = symbol.includes('BTC') ? 8 : 2;
row.innerHTML = `
<td><strong>${symbol}</strong></td>
<td class="numeric">
<input type="number"
class="prev-close"
value="${asset.previous_close}"
step="0.01"
data-symbol="${symbol}">
</td>
<td class="numeric current-price">N/A</td>
<td class="numeric change">N/A</td>
<td class="numeric change-percent">N/A</td>
<td class="numeric">
<input type="number"
class="avg-price"
value="${asset.average_price}"
step="0.01"
data-symbol="${symbol}">
</td>
<td class="numeric">
<input type="number"
class="quantity"
value="${asset.quantity}"
step="${symbol.includes('BTC') ? '0.00000001' : '0.01'}"
data-symbol="${symbol}">
</td>
<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('input[type="number"]').forEach(input => {
input.addEventListener('change', handleAssetChange);
input.addEventListener('blur', handleAssetChange);
document.querySelectorAll('#assets-tbody input').forEach(input => {
input.addEventListener('change', (e) => {
handleAssetChange(e);
updatePricesInTable();
});
});
}
// 테이블에 가격 업데이트
function updatePricesInTable() {
const rows = document.querySelectorAll('#assets-tbody tr');
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;
}
if (!priceData || !priceData.가격) return;
const currentPrice = priceData.가격;
const prevClose = parseFloat(row.querySelector('.prev-close').value) || 0;
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 decimalPlaces = symbol.includes('USD') || symbol.includes('DXY') ? 2 : 0;
row.querySelector('.current-price').textContent = formatNumber(currentPrice, decimalPlaces);
const currentPriceCell = row.querySelector('.current-price');
currentPriceCell.textContent = formatNumber(currentPrice, decimalPlaces);
// 변동 계산
const change = currentPrice - prevClose;
const changePercent = prevClose > 0 ? (change / prevClose * 100) : 0;
@@ -143,91 +248,107 @@ function updatePricesInTable() {
changeCell.textContent = formatNumber(change, decimalPlaces);
changePercentCell.textContent = `${formatNumber(changePercent, 2)}%`;
// 색상 적용
const colorClass = change > 0 ? 'price-up' : change < 0 ? 'price-down' : '';
changeCell.className = `numeric ${colorClass}`;
changePercentCell.className = `numeric ${colorClass}`;
// 매입액 계산
const avgPrice = parseFloat(row.querySelector('.avg-price').value) || 0;
const quantity = parseFloat(row.querySelector('.quantity').value) || 0;
const buyTotal = avgPrice * quantity;
row.querySelector('.buy-total').textContent = formatNumber(buyTotal, 0);
});
}
// 손익 업데이트
async function updatePnL() {
try {
const response = await fetch('/api/pnl');
const pnl = await response.json();
// 금 손익
updatePnLCard('gold-pnl', 'gold-percent', pnl.금손익, pnl['금손익%']);
// BTC 손익
updatePnLCard('btc-pnl', 'btc-percent', pnl.BTC손익, pnl['BTC손익%']);
// 총 손익
updatePnLCard('total-pnl', 'total-percent', pnl.총손익, pnl['총손익%']);
} catch (error) {
console.error('PnL 업데이트 실패:', error);
}
}
// PnL 카드 업데이트
function updatePnLCard(valueId, percentId, value, percent) {
const valueElem = document.getElementById(valueId);
const percentElem = document.getElementById(percentId);
valueElem.textContent = formatNumber(value, 0) + ' 원';
percentElem.textContent = formatNumber(percent, 2) + '%';
// 총손익이 아닌 경우만 색상 적용
if (valueId !== 'total-pnl') {
valueElem.className = `pnl-value ${value > 0 ? 'profit' : value < 0 ? 'loss' : ''}`;
percentElem.className = `pnl-percent ${value > 0 ? 'profit' : value < 0 ? 'loss' : ''}`;
}
}
// 자산 변경 처리
async function handleAssetChange(event) {
const input = event.target;
const symbol = input.dataset.symbol;
const row = input.closest('tr');
const previousClose = parseFloat(row.querySelector('.prev-close').value) || 0;
const averagePrice = parseFloat(row.querySelector('.avg-price').value) || 0;
const quantity = parseFloat(row.querySelector('.quantity').value) || 0;
try {
const response = await fetch('/api/assets', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
symbol,
previous_close: previousClose,
average_price: averagePrice,
quantity: quantity
})
// [교정] 선임님 기존 클래스명 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');
}
});
if (response.ok) {
console.log(`${symbol} 업데이트 완료`);
// 매입액 즉시 업데이트
const buyTotal = averagePrice * quantity;
row.querySelector('.buy-total').textContent = formatNumber(buyTotal, 0);
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');
});
}
} catch (error) {
console.error('업데이트 실패:', error);
}
}
// 알림 설정 모달 열기
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;
@@ -236,74 +357,13 @@ function openAlertModal() {
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');
}
// 알림 설정 저장
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 response = await fetch('/api/alerts/settings', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ settings })
});
if (response.ok) {
alertSettings = settings;
console.log('✅ 알림 설정 저장 완료');
closeAlertModal();
}
} catch (error) {
console.error('알림 설정 저장 실패:', error);
}
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 loadAssets();
console.log('🔄 데이터 새로고침 완료');
}
// 마지막 업데이트 시간 표시
function updateLastUpdateTime() {
const now = new Date();
const timeString = now.toLocaleTimeString('ko-KR');
document.getElementById('last-update').textContent = `마지막 업데이트: ${timeString}`;
}
// 숫자 포맷팅
function formatNumber(value, decimals = 0) {
if (value === null || value === undefined || isNaN(value)) {
return 'N/A';
}
return value.toLocaleString('ko-KR', {
minimumFractionDigits: decimals,
maximumFractionDigits: decimals
});
}
// 외부 클릭 시 모달 닫기
window.addEventListener('click', (event) => {
const modal = document.getElementById('alert-modal');
if (event.target === modal) {
closeAlertModal();
}
});
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(); });