Very Good till Now !
This commit is contained in:
369
.TemporaryDocument/app.js.good2
Normal file
369
.TemporaryDocument/app.js.good2
Normal file
@@ -0,0 +1,369 @@
|
||||
/**
|
||||
* Asset Pilot - Frontend Logic
|
||||
* 최적화: 초기 DB 로드 + 실시간 SSE 스트림 결합
|
||||
*/
|
||||
|
||||
// 전역 변수
|
||||
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] || '';
|
||||
}
|
||||
|
||||
// 초기화: DOM 로드 시 실행
|
||||
document.addEventListener('DOMContentLoaded', async () => {
|
||||
// 1. 자산 구조와 DB에 저장된 최신 가격을 동시에 먼저 가져옴 (Zero-Loading 핵심)
|
||||
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);
|
||||
});
|
||||
|
||||
// [추가] DB에 저장된 최신 가격을 즉시 로드
|
||||
async function loadInitialPrices() {
|
||||
try {
|
||||
const response = await fetch('/api/prices');
|
||||
if (response.ok) {
|
||||
currentPrices = await response.json();
|
||||
updatePricesInTable();
|
||||
calculatePnLRealtime();
|
||||
updateLastUpdateTime();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('초기 가격 로드 실패:', error);
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
// 프리미엄 행 삽입 (BTC, GOLD 아래에 특수 행 추가)
|
||||
if (symbol === 'BTC/USD') {
|
||||
insertPremiumRow(tbody, 'BTC_PREMIUM', '📊 BTC 프리미엄 (김프)');
|
||||
} else if (symbol === 'XAU/KRW') {
|
||||
insertPremiumRow(tbody, 'GOLD_PREMIUM', '✨ GOLD 프리미엄 (국내외차)');
|
||||
}
|
||||
});
|
||||
|
||||
// 입력값 변경 시 자동 저장 및 UI 갱신
|
||||
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 usdKrwData = currentPrices['USD/KRW'] || currentPrices['usd/krw'];
|
||||
const usdKrw = usdKrwData?.가격 || 0;
|
||||
|
||||
// 만약 여전히 안나온다면 디버깅을 위해 콘솔에 찍어보세요
|
||||
if (usdKrw === 0) {
|
||||
console.log("현재 수신된 전체 가격 데이터:", currentPrices);
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
// USD 자산은 한화로 환산
|
||||
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 Promise.all([loadAssets(), loadInitialPrices()]);
|
||||
}
|
||||
|
||||
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();
|
||||
});
|
||||
Reference in New Issue
Block a user