Files
stockautomtion/app/templates/index.html
gerd d3f3931c38 과거 거래 기록 조회 추가
좌측 사이드메뉴 추가
ggitignore 업데이트 : *.pyc
2026-07-17 13:03:35 +09:00

361 lines
19 KiB
HTML

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Stock Automation Dashboard</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #0f1117; color: #e1e4e8; display: flex; min-height: 100vh; }
.sidebar { width: 200px; background: #161b22; border-right: 1px solid #30363d; display: flex; flex-direction: column; flex-shrink: 0; }
.sidebar-header { padding: 16px; border-bottom: 1px solid #30363d; }
.sidebar-header h1 { font-size: 16px; color: #58a6ff; }
.sidebar-nav { flex: 1; padding: 8px 0; }
.sidebar-nav a { display: flex; align-items: center; gap: 10px; padding: 10px 16px; color: #8b949e; text-decoration: none; font-size: 14px; transition: background 0.15s; }
.sidebar-nav a:hover { background: #1c2128; color: #c9d1d9; }
.sidebar-nav a.active { background: #1c2128; color: #58a6ff; border-right: 2px solid #58a6ff; }
.sidebar-nav a .icon { width: 18px; text-align: center; font-size: 15px; }
.sidebar-footer { padding: 12px 16px; border-top: 1px solid #30363d; font-size: 12px; color: #484f58; }
.main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
.topbar { background: #161b22; padding: 12px 24px; border-bottom: 1px solid #30363d; display: flex; justify-content: space-between; align-items: center; }
.topbar .status { font-size: 13px; color: #8b949e; display: flex; align-items: center; gap: 6px; }
.content { flex: 1; padding: 24px; overflow-y: auto; }
.page { display: none; max-width: 1200px; margin: 0 auto; }
.page.active { display: block; }
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 16px; margin-bottom: 24px; }
.card { background: #161b22; border: 1px solid #30363d; border-radius: 8px; padding: 16px; }
.card h3 { font-size: 13px; color: #8b949e; margin-bottom: 8px; text-transform: uppercase; }
.card .value { font-size: 28px; font-weight: 700; }
.section { background: #161b22; border: 1px solid #30363d; border-radius: 8px; padding: 16px; margin-bottom: 20px; }
.section h2 { font-size: 16px; margin-bottom: 12px; color: #c9d1d9; }
table { width: 100%; border-collapse: collapse; font-size: 13px; }
th { text-align: left; padding: 8px 12px; color: #8b949e; border-bottom: 1px solid #30363d; }
td { padding: 8px 12px; border-bottom: 1px solid #21262d; }
tr:hover { background: #1c2128; }
.badge { padding: 2px 8px; border-radius: 12px; font-size: 11px; font-weight: 600; }
.badge.buy { background: #1a3a2a; color: #3fb950; }
.badge.sell { background: #3a1a1a; color: #f85149; }
.badge.pending { background: #3a3a1a; color: #d29922; }
.badge.filled { background: #1a2a3a; color: #58a6ff; }
.btn { padding: 8px 16px; border-radius: 6px; border: 1px solid #30363d; background: #21262d; color: #c9d1d9; cursor: pointer; font-size: 13px; }
.btn:hover { background: #30363d; }
.btn.primary { background: #238636; border-color: #2ea043; color: #fff; }
.btn.primary:hover { background: #2ea043; }
.form-row { display: flex; gap: 12px; align-items: end; margin-bottom: 12px; flex-wrap: wrap; }
.form-group { display: flex; flex-direction: column; gap: 4px; }
.form-group label { font-size: 12px; color: #8b949e; }
.form-group input, .form-group select { padding: 6px 10px; border-radius: 4px; border: 1px solid #30363d; background: #0d1117; color: #c9d1d9; font-size: 13px; }
#ws-status { display: inline-block; width: 8px; height: 8px; border-radius: 50%; }
#ws-status.connected { background: #3fb950; }
#ws-status.disconnected { background: #f85149; }
.alert { padding: 12px 16px; border-radius: 6px; margin-bottom: 16px; font-size: 13px; display: none; }
.alert.warning { background: #3a2a00; border: 1px solid #d29922; color: #e3b341; }
.alert.warning.show { display: block; }
.source-tag { font-size: 11px; padding: 2px 8px; border-radius: 10px; margin-left: 8px; }
.source-tag.kis { background: #1a2a3a; color: #58a6ff; }
.source-tag.local { background: #2a2a1a; color: #d29922; }
.filter-row { display: flex; gap: 12px; align-items: end; margin-bottom: 16px; flex-wrap: wrap; }
.positive { color: #3fb950; }
.negative { color: #f85149; }
</style>
</head>
<body>
<aside class="sidebar">
<div class="sidebar-header">
<h1>Stock Automation</h1>
</div>
<nav class="sidebar-nav">
<a href="#" class="active" data-page="trading">
<span class="icon">&#9881;</span> 실거래
</a>
<a href="#" data-page="history">
<span class="icon">&#128203;</span> 과거 기록 조회
</a>
</nav>
<div class="sidebar-footer">v0.1.0</div>
</aside>
<div class="main">
<div class="topbar">
<div style="font-size: 14px; color: #8b949e;" id="page-title">실거래</div>
<div class="status">
<span id="ws-status" class="disconnected"></span>
<span id="status-text">연결 중...</span>
</div>
</div>
<div class="content">
<!-- 실거래 페이지 -->
<div id="page-trading" class="page active">
<div id="auth-alert" class="alert warning">
API 키가 설정되지 않았거나 유효하지 않습니다. .env 파일에 KIS_APP_KEY와 KIS_APP_SECRET을 입력하세요.
현재 UI 표시만 가능하며, 시세 조회 및 매매 기능은 작동하지 않습니다.
</div>
<div class="grid">
<div class="card">
<h3>총 투자금</h3>
<div class="value" id="total-invested">-</div>
</div>
<div class="card">
<h3>평가금액</h3>
<div class="value" id="total-evaluated">-</div>
</div>
<div class="card">
<h3>총 수익</h3>
<div class="value" id="total-profit">-</div>
</div>
<div class="card">
<h3>수익률</h3>
<div class="value" id="profit-rate">-</div>
</div>
</div>
<div class="section">
<h2>보유 종목</h2>
<table>
<thead>
<tr>
<th>종목코드</th><th>종목명</th><th>수량</th>
<th>평균단가</th><th>현재가</th><th>수익</th><th>수익률</th>
</tr>
</thead>
<tbody id="holdings-table"></tbody>
</table>
</div>
<div class="section">
<h2>최근 매매 내역</h2>
<table>
<thead>
<tr>
<th>시간</th><th>종목코드</th><th>구분</th>
<th>수량</th><th>가격</th><th>상태</th>
</tr>
</thead>
<tbody id="trades-table"></tbody>
</table>
</div>
<div class="section">
<h2>매매 주문</h2>
<div class="form-row">
<div class="form-group">
<label>종목코드</label>
<input id="order-code" type="text" placeholder="005930" />
</div>
<div class="form-group">
<label>구분</label>
<select id="order-side">
<option value="buy">매수</option>
<option value="sell">매도</option>
</select>
</div>
<div class="form-group">
<label>수량</label>
<input id="order-qty" type="number" value="1" min="1" />
</div>
<div class="form-group">
<label>가격 (0=시장가)</label>
<input id="order-price" type="number" value="0" />
</div>
<button class="btn primary" onclick="placeOrder()">주문</button>
</div>
</div>
</div>
<!-- 과거 기록 조회 페이지 -->
<div id="page-history" class="page">
<div class="section">
<h2>과거 매매 기록 조회 <span id="history-source" class="source-tag"></span></h2>
<div class="filter-row">
<div class="form-group">
<label>시작일</label>
<input id="hist-start" type="date" />
</div>
<div class="form-group">
<label>종료일</label>
<input id="hist-end" type="date" />
</div>
<div class="form-group">
<label>종목코드 (선택)</label>
<input id="hist-code" type="text" placeholder="005930" />
</div>
<button class="btn primary" onclick="loadTradeHistory()">조회</button>
</div>
<table>
<thead>
<tr>
<th>시간</th><th>종목코드</th><th>종목명</th><th>구분</th>
<th>수량</th><th>체결가</th><th>주문금액</th><th>상태</th>
</tr>
</thead>
<tbody id="history-table"></tbody>
</table>
<div id="history-empty" style="display:none; text-align:center; padding:24px; color:#8b949e;">
조회된 매매 기록이 없습니다.
</div>
</div>
</div>
</div>
</div>
<script>
const API = '';
let ws;
let historyLoaded = false;
function formatPrice(n) { return n ? n.toLocaleString('ko-KR') + '원' : '-'; }
function formatRate(n) { return n >= 0 ? '+' + n.toFixed(2) + '%' : n.toFixed(2) + '%'; }
function formatDate(d) {
const dt = d ? new Date(d) : null;
if (!dt || isNaN(dt.getTime())) return '-';
return dt.toLocaleString('ko-KR');
}
document.querySelectorAll('.sidebar-nav a').forEach(link => {
link.addEventListener('click', (e) => {
e.preventDefault();
document.querySelectorAll('.sidebar-nav a').forEach(a => a.classList.remove('active'));
link.classList.add('active');
const page = link.dataset.page;
document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
document.getElementById('page-' + page).classList.add('active');
document.getElementById('page-title').textContent = link.textContent.trim();
if (page === 'trading') loadDashboard();
if (page === 'history' && !historyLoaded) { loadTradeHistory(); historyLoaded = true; }
});
});
async function loadDashboard() {
try {
const res = await fetch(API + '/api/dashboard/');
const data = await res.json();
if (!data.authenticated) document.getElementById('auth-alert').classList.add('show');
const s = data.summary;
document.getElementById('total-invested').textContent = formatPrice(s.total_invested);
document.getElementById('total-evaluated').textContent = formatPrice(s.total_evaluated);
const profitEl = document.getElementById('total-profit');
profitEl.textContent = formatPrice(s.total_profit);
profitEl.className = 'value ' + (s.total_profit >= 0 ? 'positive' : 'negative');
const rateEl = document.getElementById('profit-rate');
rateEl.textContent = formatRate(s.profit_rate);
rateEl.className = 'value ' + (s.profit_rate >= 0 ? 'positive' : 'negative');
document.getElementById('holdings-table').innerHTML = data.holdings.map(h => `
<tr>
<td>${h.stock_code}</td><td>${h.stock_name}</td><td>${h.qty}</td>
<td>${formatPrice(h.avg_price)}</td><td>${formatPrice(h.current_price)}</td>
<td class="${h.profit >= 0 ? 'positive' : 'negative'}">${formatPrice(h.profit)}</td>
<td class="${h.profit_rate >= 0 ? 'positive' : 'negative'}">${formatRate(h.profit_rate)}</td>
</tr>
`).join('');
document.getElementById('trades-table').innerHTML = data.recent_trades.map(t => `
<tr>
<td>${t.created_at ? new Date(t.created_at).toLocaleString('ko-KR') : '-'}</td>
<td>${t.stock_code}</td>
<td><span class="badge ${t.side}">${t.side === 'buy' ? '매수' : '매도'}</span></td>
<td>${t.qty}</td><td>${formatPrice(t.price)}</td>
<td><span class="badge ${t.status}">${t.status}</span></td>
</tr>
`).join('');
} catch (e) { console.error('대시보드 로드 실패:', e); }
}
async function placeOrder() {
const body = {
stock_code: document.getElementById('order-code').value,
side: document.getElementById('order-side').value,
qty: parseInt(document.getElementById('order-qty').value),
price: parseInt(document.getElementById('order-price').value),
};
try {
const res = await fetch(API + '/api/trading/order', {
method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body),
});
const data = await res.json();
alert(data.rt_cd === '0' ? '주문 성공: ' + data.order_no : '주문 실패: ' + data.msg);
loadDashboard();
} catch (e) { alert('주문 오류: ' + e.message); }
}
async function loadTradeHistory() {
const start = document.getElementById('hist-start').value.replace(/-/g, '');
const end = document.getElementById('hist-end').value.replace(/-/g, '');
const code = document.getElementById('hist-code').value.trim();
const params = new URLSearchParams();
if (start) params.set('start_date', start);
if (end) params.set('end_date', end);
if (code) params.set('stock_code', code);
params.set('limit', '200');
const sourceTag = document.getElementById('history-source');
const tbody = document.getElementById('history-table');
const emptyMsg = document.getElementById('history-empty');
try {
const res = await fetch(API + '/api/trading/history?' + params.toString());
const data = await res.json();
const trades = data.trades || [];
sourceTag.textContent = data.source === 'kis' ? 'KIS API' : '로컬 DB';
sourceTag.className = 'source-tag ' + data.source;
if (trades.length === 0) { tbody.innerHTML = ''; emptyMsg.style.display = 'block'; return; }
emptyMsg.style.display = 'none';
tbody.innerHTML = trades.map(t => {
const time = formatDate(t.created_at || t.filled_at || '');
const orderAmt = t.order_amount ? formatPrice(t.order_amount) : formatPrice(t.qty * t.price);
return `<tr>
<td>${time}</td>
<td>${t.stock_code}</td>
<td>${t.stock_name || '-'}</td>
<td><span class="badge ${t.side}">${t.side === 'buy' ? '매수' : '매도'}</span></td>
<td>${t.qty}</td>
<td>${formatPrice(t.price)}</td>
<td>${orderAmt}</td>
<td><span class="badge ${t.status}">${t.status === 'filled' ? '체결' : t.status}</span></td>
</tr>`;
}).join('');
} catch (e) {
console.error('매매 기록 조회 실패:', e);
tbody.innerHTML = '';
emptyMsg.style.display = 'block';
emptyMsg.textContent = '매매 기록을 불러오는 중 오류가 발생했습니다.';
}
}
function initHistoryDates() {
const today = new Date();
const monthAgo = new Date();
monthAgo.setDate(monthAgo.getDate() - 30);
document.getElementById('hist-end').value = today.toISOString().slice(0, 10);
document.getElementById('hist-start').value = monthAgo.toISOString().slice(0, 10);
}
function connectWS() {
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
ws = new WebSocket(`${proto}://${location.host}/ws/realtime`);
ws.onopen = () => {
document.getElementById('ws-status').className = 'connected';
document.getElementById('status-text').textContent = '실시간 연결됨';
};
ws.onclose = () => {
document.getElementById('ws-status').className = 'disconnected';
document.getElementById('status-text').textContent = '연결 끊김 - 재연결 중...';
setTimeout(connectWS, 3000);
};
ws.onmessage = (e) => {
const data = JSON.parse(e.data);
if (data.type === 'price') loadDashboard();
};
}
loadDashboard();
setInterval(loadDashboard, 10000);
connectWS();
initHistoryDates();
</script>
</body>
</html>