웹소켓 적용중

This commit is contained in:
2026-02-24 23:20:42 +09:00
parent 153b1bed17
commit fc8c30b7e1
6 changed files with 467 additions and 116 deletions

View File

@@ -203,6 +203,50 @@ def _generate_sample_chart(stock_code: str, period: str, limit: int = 100) -> di
# 차트 데이터를 위한 간단한 인메모리 캐시 딕셔너리
chart_cache = {}
async def get_chart_data_cached(stock_code: str, period: str, limit: int) -> list:
"""캐시된 차트 데이터 반환 — REST endpoint와 WebSocket 핸들러가 공유.
캐시 미스 시 KIS API 호출 후 chart_cache에 저장.
realtime 보정 없음 (현재가는 WebSocket tick이 처리).
"""
if period not in ("D", "W", "M"):
period = "D"
limit = min(limit, 240)
cache_key = f"{stock_code}__{period}"
current_time = datetime.now()
cached = chart_cache.get(cache_key)
if cached and (current_time - cached["timestamp"]).total_seconds() < 600:
return list(cached["data"])
if not settings.KOREA_INVESTMENT_APP_KEY or not settings.KOREA_INVESTMENT_APP_SECRET:
return _generate_sample_chart(stock_code, period, limit).get("data", [])
data = await korea_investment_api.get_daily_chart(stock_code, period, limit=limit)
if "output2" not in data:
return []
chart_data = []
for item in data["output2"]:
try:
chart_data.append({
"date": item.get("stck_bsop_date"),
"open": float(str(item.get("stck_oprc", "0")).replace(",", "")),
"high": float(str(item.get("stck_hgpr", "0")).replace(",", "")),
"low": float(str(item.get("stck_lwpr", "0")).replace(",", "")),
"close": float(str(item.get("stck_clpr", "0")).replace(",", "")),
"volume": int(item.get("acml_vol", 0)),
})
except (ValueError, TypeError) as e:
logger.error(f"가격 파싱 오류: {item} - {e}")
continue
chart_cache[cache_key] = {"timestamp": current_time, "data": chart_data}
return chart_data
@router.get("/chart/{stock_code}")
async def get_stock_chart(
stock_code: str,