// 전역 변수
let currentPrices = {};
let userAssets = [];
let alertSettings = {};
// 초기화
document.addEventListener('DOMContentLoaded', () => {
loadAssets();
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);
});
// 자산 데이터 로드
async function loadAssets() {
try {
const response = await fetch('/api/assets');
userAssets = await response.json();
renderAssetsTable();
} 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 startPriceStream() {
const eventSource = new EventSource('/api/stream');
eventSource.onmessage = (event) => {
currentPrices = JSON.parse(event.data);
updatePricesInTable();
updateLastUpdateTime();
};
eventSource.onerror = () => {
console.error('SSE 연결 오류');
document.getElementById('status-indicator').style.backgroundColor = '#ef4444';
};
}
// 테이블 렌더링
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;
const row = document.createElement('tr');
row.dataset.symbol = symbol;
const decimalPlaces = symbol.includes('BTC') ? 8 : 2;
row.innerHTML = `
${symbol} |
|
N/A |
N/A |
N/A |
|
|
0 |
`;
tbody.appendChild(row);
});
// 입력 필드 이벤트 리스너
document.querySelectorAll('input[type="number"]').forEach(input => {
input.addEventListener('change', handleAssetChange);
input.addEventListener('blur', handleAssetChange);
});
}
// 테이블에 가격 업데이트
function updatePricesInTable() {
const rows = document.querySelectorAll('#assets-tbody tr');
rows.forEach(row => {
const symbol = row.dataset.symbol;
const priceData = currentPrices[symbol];
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;
row.querySelector('.current-price').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)}%`;
// 색상 적용
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
})
});
if (response.ok) {
console.log(`✅ ${symbol} 업데이트 완료`);
// 매입액 즉시 업데이트
const buyTotal = averagePrice * quantity;
row.querySelector('.buy-total').textContent = formatNumber(buyTotal, 0);
}
} catch (error) {
console.error('업데이트 실패:', error);
}
}
// 알림 설정 모달 열기
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 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);
}
}
// 데이터 새로고침
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();
}
});