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,3 +1,7 @@
/* Asset Pilot - Redesigned CSS */
@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=Noto+Sans+KR:wght@400;500;600;700&display=swap');
* {
margin: 0;
padding: 0;
@@ -5,349 +9,709 @@
}
:root {
/* 핵심 색상 변수 - app.js profit/loss 연동 보존 */
--primary-color: #2563eb;
--success-color: #10b981;
--danger-color: #ef4444;
--warning-color: #f59e0b;
--bg-color: #f8fafc;
--card-bg: #ffffff;
--text-primary: #1e293b;
--text-secondary: #64748b;
--border-color: #e2e8f0;
--success-color: #10b981;
/* 테마 */
--bg-color: #161c2a;
--bg-secondary: #1e2636;
--card-bg: #222d42;
--card-border: rgba(255,255,255,0.1);
--text-primary: #f0f4ff;
--text-secondary: #9aa3ba;
--text-muted: #5e6880;
--border-color: rgba(255,255,255,0.08);
--accent-gold: #f59e0b;
--accent-blue: #3b82f6;
--font-body: 'Noto Sans KR', sans-serif;
--font-mono: 'IBM Plex Mono', monospace;
}
/* ─── 기본 ─────────────────────────────────────────── */
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
font-family: var(--font-body);
background-color: var(--bg-color);
color: var(--text-primary);
line-height: 1.6;
min-height: 100vh;
}
/* 미묘한 배경 그리드 텍스처 */
body::before {
content: '';
position: fixed;
inset: 0;
background-image:
linear-gradient(rgba(37,99,235,0.03) 1px, transparent 1px),
linear-gradient(90deg, rgba(37,99,235,0.03) 1px, transparent 1px);
background-size: 40px 40px;
pointer-events: none;
z-index: 0;
}
.container {
max-width: 1400px;
margin: 0 auto;
padding: 20px;
padding: 20px 24px;
position: relative;
z-index: 1;
}
/* 헤더 */
header {
background: var(--card-bg);
border-radius: 12px;
padding: 24px;
margin-bottom: 24px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
header h1 {
font-size: 32px;
margin-bottom: 8px;
}
.subtitle {
color: var(--text-secondary);
font-size: 14px;
margin-bottom: 12px;
}
/* ─── 손익 색상 (app.js profit/loss 연동 - 절대 수정 금지) ─ */
.profit { color: var(--danger-color) !important; }
.loss { color: var(--primary-color) !important; }
.numeric.profit, .numeric.loss { font-weight: 600; }
/* ─── 상태바 ─────────────────────────────────────────── */
.status-bar {
display: flex;
align-items: center;
gap: 8px;
font-size: 14px;
color: var(--text-secondary);
background: #111827;
color: #8892aa;
padding: 7px 20px;
font-size: 0.8em;
font-family: var(--font-mono);
border-bottom: 1px solid rgba(37,99,235,0.25);
letter-spacing: 0.02em;
position: sticky;
top: 0;
z-index: 100;
}
.status-dot {
width: 10px;
height: 10px;
.status-bar .status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background-color: var(--success-color);
margin-right: 10px;
flex-shrink: 0;
}
.status-healthy {
background-color: var(--success-color) !important;
box-shadow: 0 0 8px var(--success-color);
animation: pulse 2s infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
.status-stale {
background-color: var(--danger-color) !important;
box-shadow: 0 0 8px var(--danger-color);
}
/* 손익 요약 */
@keyframes pulse {
0%, 100% { opacity: 1; box-shadow: 0 0 8px var(--success-color); }
50% { opacity: 0.6; box-shadow: 0 0 3px var(--success-color); }
}
#status-indicator {
width: 10px; height: 10px; border-radius: 50%;
display: inline-block; vertical-align: middle; margin-right: 5px;
}
/* ─── 헤더 ─────────────────────────────────────────── */
header {
background: var(--card-bg);
border: 1px solid var(--card-border);
border-radius: 16px;
padding: 20px 28px;
margin-bottom: 20px;
position: relative;
overflow: hidden;
}
header::after {
content: '';
position: absolute;
top: 0; left: 0; right: 0;
height: 2px;
background: linear-gradient(90deg, var(--primary-color), #8b5cf6, var(--accent-gold));
}
header h1 {
font-size: clamp(22px, 4vw, 30px);
font-weight: 700;
letter-spacing: -0.02em;
color: var(--text-primary);
margin-bottom: 2px;
}
header .subtitle {
color: var(--text-secondary);
font-size: 13px;
}
.header-actions {
display: flex;
gap: 10px;
flex-shrink: 0;
}
/* ─── 아이콘 버튼 ─────────────────────────────────── */
.icon-btn {
padding: 8px 14px;
background: var(--bg-secondary);
border: 1px solid var(--card-border);
border-radius: 8px;
color: var(--text-secondary);
font-size: 13px;
font-family: var(--font-body);
cursor: pointer;
transition: all 0.2s;
white-space: nowrap;
}
.icon-btn:hover {
background: var(--primary-color);
color: white;
border-color: var(--primary-color);
transform: translateY(-1px);
}
/* ─── 손익 요약 카드 ───────────────────────────────── */
.pnl-summary {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 16px;
margin-bottom: 24px;
grid-template-columns: repeat(3, 1fr);
gap: 14px;
margin-bottom: 20px;
}
.pnl-card {
background: var(--card-bg);
border-radius: 12px;
padding: 20px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
border: 1px solid var(--card-border);
border-radius: 14px;
padding: 18px 22px;
position: relative;
overflow: hidden;
transition: transform 0.2s, box-shadow 0.2s;
}
.pnl-card.total {
background: linear-gradient(135deg, var(--primary-color) 0%, #1e40af 100%);
color: white;
.pnl-card:hover {
transform: translateY(-2px);
box-shadow: 0 8px 30px rgba(0,0,0,0.3);
}
.pnl-card h3 {
font-size: 14px;
font-size: 12px;
font-weight: 500;
margin-bottom: 12px;
opacity: 0.9;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.08em;
margin-bottom: 10px;
}
.pnl-value {
font-size: 28px;
font-weight: 700;
font-family: var(--font-mono);
font-size: clamp(18px, 3vw, 26px);
font-weight: 600;
margin-bottom: 4px;
color: var(--text-primary);
letter-spacing: -0.02em;
}
.pnl-percent {
font-size: 16px;
font-weight: 500;
font-family: var(--font-mono);
font-size: 13px;
color: var(--text-secondary);
}
.pnl-value.profit {
color: var(--danger-color);
/* 총 손익 카드 */
.pnl-card.total {
background: linear-gradient(135deg, #1e3a8a 0%, #1e40af 60%, #2563eb 100%);
border-color: rgba(59,130,246,0.3);
}
.pnl-value.loss {
color: var(--primary-color);
}
.pnl-card.total h3 { color: rgba(255,255,255,0.6); }
.pnl-card.total .pnl-value,
.pnl-card.total .pnl-percent {
color: white;
.pnl-card.total .pnl-percent,
.pnl-card.total .profit,
.pnl-card.total .loss {
color: #ffffff !important;
}
/* 자산 섹션 */
.assets-section {
/* 장식 원형 */
.pnl-card::before {
content: '';
position: absolute;
right: -20px; top: -20px;
width: 80px; height: 80px;
border-radius: 50%;
background: rgba(255,255,255,0.03);
}
/* ─── 테이블 섹션 ──────────────────────────────────── */
.table-section, .assets-section {
background: var(--card-bg);
border-radius: 12px;
padding: 24px;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
margin-bottom: 24px;
}
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
border: 1px solid var(--card-border);
border-radius: 16px;
overflow: hidden;
margin-bottom: 20px;
}
.section-header h2 {
font-size: 20px;
.table-section-header {
padding: 16px 22px;
border-bottom: 1px solid var(--border-color);
font-size: 13px;
font-weight: 600;
color: var(--text-secondary);
text-transform: uppercase;
letter-spacing: 0.06em;
}
/* 테이블 */
.table-container {
/* 테이블 가로 스크롤 래퍼 */
.table-wrapper {
width: 100%;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
table {
width: 100%;
border-collapse: collapse;
min-width: 720px; /* 가로 스크롤 기준점 */
}
th, td {
padding: 12px 16px;
text-align: left;
border-bottom: 1px solid var(--border-color);
thead tr {
background: rgba(0,0,0,0.2);
}
th {
background-color: var(--bg-color);
padding: 11px 16px;
font-size: 11px;
font-weight: 600;
font-size: 14px;
color: var(--text-secondary);
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.06em;
text-align: left;
white-space: nowrap;
border-bottom: 1px solid var(--border-color);
}
td {
padding: 13px 16px;
font-size: 14px;
border-bottom: 1px solid var(--border-color);
vertical-align: middle;
color: var(--text-primary);
white-space: nowrap;
}
tbody tr:last-child td { border-bottom: none; }
tbody tr {
transition: background 0.15s;
}
tbody tr:hover td {
background: rgba(37,99,235,0.06);
}
.numeric {
text-align: right;
font-family: var(--font-mono);
font-size: 13px;
}
/* 입력창 컬럼: 내용에 맞게 최소 너비 고정 */
td.input-cell {
width: 1%; /* shrink-to-fit */
white-space: nowrap;
}
td input {
width: 100%;
padding: 6px 8px;
width: clamp(72px, 8vw, 120px); /* 화면 너비 비례, 최소 72 최대 120 */
padding: 4px 8px;
background: var(--bg-secondary);
border: 1px solid var(--border-color);
border-radius: 4px;
font-size: 14px;
border-radius: 5px;
color: var(--text-primary);
font-size: 12px;
font-family: var(--font-mono);
text-align: right;
display: block;
}
td input:focus {
outline: none;
border-color: var(--primary-color);
box-shadow: 0 0 0 2px rgba(37,99,235,0.2);
}
.price-up {
color: var(--danger-color);
}
.premium-row td { background-color: rgba(245, 158, 11, 0.04) !important; }
.price-down {
color: var(--primary-color);
}
/* 버튼 */
/* ─── 버튼 ────────────────────────────────────────── */
.btn {
padding: 10px 20px;
padding: 9px 18px;
border: none;
border-radius: 6px;
font-size: 14px;
border-radius: 7px;
font-size: 13px;
font-weight: 500;
font-family: var(--font-body);
cursor: pointer;
transition: all 0.2s;
}
.btn-primary {
background-color: var(--primary-color);
background: var(--primary-color);
color: white;
}
.btn-primary:hover {
background-color: #1e40af;
}
.btn-primary:hover { background: #1e40af; transform: translateY(-1px); }
.btn-secondary {
background-color: var(--border-color);
color: var(--text-primary);
background: var(--bg-secondary);
color: var(--text-secondary);
border: 1px solid var(--border-color);
}
.btn-secondary:hover {
background-color: #cbd5e1;
.btn-secondary:hover { background: var(--border-color); }
.investing-btn {
display: inline-block;
padding: 4px 10px;
font-size: 11px;
font-weight: 600;
color: var(--text-secondary);
background: var(--bg-secondary);
border: 1px solid var(--border-color);
border-radius: 5px;
text-decoration: none;
min-width: 80px;
text-align: center;
font-family: var(--font-body);
transition: all 0.2s;
}
/* 모달 */
.investing-btn:hover {
background: var(--primary-color);
color: white !important;
border-color: var(--primary-color);
box-shadow: 0 2px 8px rgba(37,99,235,0.4);
}
/* ─── 모달 ────────────────────────────────────────── */
.modal {
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.5);
}
.modal.active {
display: flex;
z-index: 9999;
left: 0; top: 0;
width: 100vw; height: 100vh;
background-color: rgba(0, 0, 0, 0.75);
backdrop-filter: blur(4px);
justify-content: center;
align-items: center;
}
.modal-content {
background-color: var(--card-bg);
border-radius: 12px;
width: 90%;
max-width: 600px;
.modal.active { display: flex !important; }
.modal .modal-content, .modal-content.card {
background: var(--card-bg) !important;
border: 1px solid var(--card-border) !important;
border-radius: 16px !important;
width: 90% !important;
max-width: 460px !important;
max-height: 90vh;
overflow-y: auto;
box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1);
box-shadow: 0 30px 60px rgba(0,0,0,0.6) !important;
animation: modalFade 0.25s ease-out;
position: relative;
}
.modal-header {
/* 모달 상단 컬러 라인 */
.modal .modal-content::before,
.modal-content.card::before {
content: '';
position: absolute;
top: 0; left: 0; right: 0;
height: 2px;
background: linear-gradient(90deg, var(--primary-color), #8b5cf6);
border-radius: 16px 16px 0 0;
}
@keyframes modalFade {
from { opacity: 0; transform: translateY(-16px) scale(0.97); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
.modal .modal-header {
padding: 20px 24px !important;
border-bottom: 1px solid var(--border-color) !important;
display: flex;
justify-content: space-between;
align-items: center;
padding: 20px 24px;
}
.modal .modal-header h2,
.modal-content.card h2 {
font-size: 17px !important;
font-weight: 700 !important;
color: var(--text-primary) !important;
}
.modal .modal-body {
padding: 22px 28px !important;
display: flex;
flex-direction: column;
align-items: stretch;
}
.modal .setting-group {
width: 100% !important;
margin: 0 0 14px 0 !important;
padding-bottom: 14px;
border-bottom: 1px solid var(--border-color) !important;
}
.modal .setting-group:last-child { border-bottom: none !important; }
.modal .setting-group h3 {
font-size: 12px !important;
font-weight: 600 !important;
color: var(--text-muted) !important;
text-transform: uppercase;
letter-spacing: 0.06em;
margin-bottom: 10px !important;
}
.modal .setting-group label {
display: flex;
align-items: center;
gap: 10px;
width: 100%;
font-size: 14px !important;
color: var(--text-primary) !important;
margin-bottom: 8px !important;
cursor: pointer;
}
.modal .setting-group label:last-child { margin-bottom: 0 !important; }
.modal .setting-group input[type="checkbox"] {
width: 16px; height: 16px;
flex-shrink: 0;
accent-color: var(--primary-color);
}
.modal .setting-group input[type="number"] {
width: 100px !important;
height: 32px !important;
text-align: right !important;
padding: 0 8px !important;
font-size: 14px !important;
font-family: var(--font-mono);
background: var(--bg-secondary);
border: 1px solid var(--border-color);
border-radius: 6px;
color: var(--text-primary);
margin-left: auto;
}
.modal .setting-group input[type="number"]:focus {
outline: none;
border-color: var(--primary-color);
}
.modal .setting-group input[type="number"]::-webkit-inner-spin-button,
.modal .setting-group input[type="number"]::-webkit-outer-spin-button {
margin: 0;
}
/* 기존 모달 비(非)구조 지원 (card 클래스만 있을 때) */
.modal-content.card > hr {
border: none;
border-top: 1px solid var(--border-color);
margin: 0;
}
.modal-content.card > .setting-group {
padding: 14px 24px;
border-bottom: 1px solid var(--border-color);
}
.modal-header h2 {
font-size: 20px;
.modal-content.card > .setting-group label {
display: flex;
align-items: center;
gap: 10px;
font-size: 14px;
color: var(--text-primary);
margin-bottom: 8px;
cursor: pointer;
}
.modal-content.card > .setting-group input[type="number"] {
display: block;
margin-top: 8px;
width: 120px;
padding: 6px 10px;
background: var(--bg-secondary);
border: 1px solid var(--border-color);
border-radius: 6px;
color: var(--text-primary);
font-family: var(--font-mono);
font-size: 13px;
text-align: right;
}
.modal .sub-setting {
margin-top: 8px;
font-size: 13px;
color: var(--text-secondary);
display: flex;
align-items: center;
gap: 8px;
}
.modal .sub-setting input[type="number"] {
flex: 1;
max-width: 130px;
}
.modal .modal-footer {
padding: 14px 24px !important;
border-top: 1px solid var(--border-color) !important;
background: rgba(0,0,0,0.15) !important;
display: flex;
justify-content: flex-end;
gap: 10px;
border-radius: 0 0 16px 16px;
}
.modal-content.card > .modal-footer {
padding: 14px 24px;
border-top: 1px solid var(--border-color);
background: rgba(0,0,0,0.15);
display: flex;
justify-content: flex-end;
gap: 10px;
}
.close {
font-size: 28px;
font-weight: 300;
font-size: 24px;
cursor: pointer;
color: var(--text-secondary);
color: var(--text-muted);
line-height: 1;
padding: 2px 6px;
border-radius: 4px;
transition: all 0.15s;
}
.close:hover {
color: var(--text-primary);
background: rgba(255,255,255,0.08);
}
.modal-body {
padding: 24px;
}
.setting-group {
margin-bottom: 24px;
padding-bottom: 24px;
border-bottom: 1px solid var(--border-color);
}
.setting-group:last-child {
border-bottom: none;
}
.setting-group h3 {
font-size: 16px;
margin-bottom: 16px;
}
.setting-group label {
display: block;
margin-bottom: 12px;
}
.setting-group input[type="checkbox"] {
margin-right: 8px;
}
.setting-group input[type="number"] {
width: 120px;
padding: 8px;
border: 1px solid var(--border-color);
border-radius: 4px;
margin-left: 8px;
}
.modal-footer {
display: flex;
justify-content: flex-end;
gap: 12px;
padding: 20px 24px;
border-top: 1px solid var(--border-color);
}
/* 푸터 */
/* ─── 푸터 ────────────────────────────────────────── */
footer {
text-align: center;
padding: 24px;
color: var(--text-secondary);
padding: 28px;
color: var(--text-muted);
font-size: 12px;
}
footer p {
margin-top: 12px;
font-size: 14px;
}
/* ─── 반응형 ───────────────────────────────────────── */
/* 반응형 */
@media (max-width: 768px) {
.container {
padding: 12px;
}
header h1 {
font-size: 24px;
}
/* 태블릿 (768px ~ 1024px) */
@media (max-width: 1024px) {
.container { padding: 16px; }
.pnl-summary {
grid-template-columns: 1fr;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
}
table {
.pnl-value { font-size: 20px; }
header { padding: 16px 20px; }
header h1 { font-size: 24px; }
}
/* 모바일 (최대 767px) */
@media (max-width: 767px) {
.container { padding: 12px; }
/* 헤더 스택 레이아웃 */
header {
padding: 14px 16px;
margin-bottom: 14px;
}
header > div {
flex-direction: column !important;
align-items: flex-start !important;
gap: 12px;
}
header h1 { font-size: 20px; }
header .subtitle { font-size: 12px; }
.header-actions {
width: 100%;
justify-content: flex-end;
}
.icon-btn {
padding: 7px 11px;
font-size: 12px;
}
th, td {
padding: 8px;
/* 손익 카드: 모바일 2+1 레이아웃 */
.pnl-summary {
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.pnl-card.total {
grid-column: 1 / -1; /* 총 손익은 전체 폭 */
}
.pnl-card { padding: 14px 16px; }
.pnl-card h3 { font-size: 11px; margin-bottom: 6px; }
.pnl-value { font-size: 18px; }
.pnl-percent { font-size: 12px; }
/* 테이블: 가로 스크롤 + 폰트 축소 */
.table-section, .assets-section {
border-radius: 12px;
}
th { font-size: 10px; padding: 9px 10px; }
td { font-size: 12px; padding: 10px 10px; }
/* 모바일: 입력창 더 작게 */
td input { width: clamp(60px, 14vw, 90px); font-size: 11px; padding: 3px 5px; }
/* 상태바 텍스트 압축 */
.status-bar { font-size: 0.72em; padding: 6px 12px; }
/* 모달 */
.modal .modal-content,
.modal-content.card {
width: 95% !important;
max-width: none !important;
}
.modal .modal-body { padding: 16px 18px !important; }
.modal .modal-header { padding: 14px 18px !important; }
.modal .modal-footer { padding: 12px 18px !important; }
}
/* 초소형 (최대 400px) */
@media (max-width: 400px) {
.pnl-summary { grid-template-columns: 1fr; }
.pnl-card.total { grid-column: auto; }
header h1 { font-size: 18px; }
}
/* ─── 스크롤바 스타일 ──────────────────────────────── */
::-webkit-scrollbar { width: 5px; height: 5px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: var(--text-muted); border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: var(--text-secondary); }
/* ─── 포커스 접근성 ───────────────────────────────── */
:focus-visible {
outline: 2px solid var(--primary-color);
outline-offset: 2px;
}

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(); });