327 lines
14 KiB
Plaintext
327 lines
14 KiB
Plaintext
// 전역 변수
|
|
let currentPrices = {};
|
|
let userAssets = [];
|
|
let alertSettings = {};
|
|
|
|
// 자산 목록 (고정 리스트)
|
|
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', () => {
|
|
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);
|
|
});
|
|
|
|
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();
|
|
calculatePnLRealtime();
|
|
updateLastUpdateTime();
|
|
document.getElementById('status-indicator').style.backgroundColor = '#10b981';
|
|
};
|
|
eventSource.onerror = () => {
|
|
document.getElementById('status-indicator').style.backgroundColor = '#ef4444';
|
|
};
|
|
}
|
|
|
|
// 테이블 뼈대 생성
|
|
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 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 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 class="numeric buy-total">0</td>
|
|
`;
|
|
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 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-color: #f8fafc;">${label}</td>
|
|
<td class="numeric" style="background-color: #f8fafc;">-</td>
|
|
<td class="numeric premium-value" style="font-weight: bold; background-color: #f8fafc;">계산중...</td>
|
|
<td class="numeric premium-diff" colspan="2" style="background-color: #f8fafc; font-weight: bold;">-</td>
|
|
<td colspan="3" style="background-color: #f8fafc;"></td>
|
|
`;
|
|
tbody.appendChild(row);
|
|
}
|
|
|
|
// 실시간 가격 및 색상 업데이트 핵심 로직
|
|
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;
|
|
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)}%`;
|
|
|
|
const cellsToColor = [currentPriceCell, changeCell, changePercentCell];
|
|
cellsToColor.forEach(cell => {
|
|
cell.classList.remove('price-up', 'price-down');
|
|
if (prevClose > 0) {
|
|
if (change > 0) cell.classList.add('price-up');
|
|
else if (change < 0) cell.classList.add('price-down');
|
|
}
|
|
});
|
|
|
|
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) {
|
|
// 1. BTC 프리미엄
|
|
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(cell => {
|
|
cell.classList.remove('price-up', 'price-down');
|
|
if (btcPrem > 0) cell.classList.add('price-up');
|
|
else if (btcPrem < 0) cell.classList.add('price-down');
|
|
});
|
|
}
|
|
|
|
// 2. GOLD 프리미엄
|
|
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(cell => {
|
|
cell.classList.remove('price-up', 'price-down');
|
|
if (goldPrem > 0) cell.classList.add('price-up');
|
|
else if (goldPrem < 0) cell.classList.add('price-down');
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
function calculatePnLRealtime() {
|
|
let totalBuy = 0, totalCurrentValue = 0;
|
|
let goldBuy = 0, goldCurrent = 0;
|
|
let 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(valueId, percentId, value, percent) {
|
|
const valueElem = document.getElementById(valueId);
|
|
const percentElem = document.getElementById(percentId);
|
|
if (!valueElem || !percentElem) return;
|
|
valueElem.textContent = formatNumber(value, 0) + ' 원';
|
|
percentElem.textContent = formatNumber(percent, 2) + '%';
|
|
const stateClass = value > 0 ? 'profit' : value < 0 ? 'loss' : '';
|
|
valueElem.className = `pnl-value ${stateClass}`;
|
|
percentElem.className = `pnl-percent ${stateClass}`;
|
|
}
|
|
|
|
async function handleAssetChange(event) {
|
|
const input = event.target;
|
|
const symbol = input.dataset.symbol;
|
|
const row = input.closest('tr');
|
|
const data = {
|
|
symbol,
|
|
previous_close: parseFloat(row.querySelector('.prev-close').value) || 0,
|
|
average_price: parseFloat(row.querySelector('.avg-price').value) || 0,
|
|
quantity: parseFloat(row.querySelector('.quantity').value) || 0
|
|
};
|
|
try {
|
|
await fetch('/api/assets', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(data)
|
|
});
|
|
calculatePnLRealtime();
|
|
} 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; closeAlertModal(); }
|
|
} catch (error) { console.error('알림 설정 저장 실패:', error); }
|
|
}
|
|
|
|
async function refreshData() { await loadAssets(); }
|
|
|
|
function updateLastUpdateTime() {
|
|
document.getElementById('last-update').textContent = `마지막 업데이트: ${new Date().toLocaleTimeString('ko-KR')}`;
|
|
}
|
|
|
|
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', (e) => { if (e.target === document.getElementById('alert-modal')) closeAlertModal(); }); |