fix: CRITICAL/HIGH 버그 30건 수정 + 전체 코드 주석 추가 + 중복 정리
## CRITICAL 수정 (20건) - day_trading: global 선언 누락, loss_tracker 연동, ban 체크 추가 - trade_executor: BUY 체결가 order_price로 수정, remaining_pct 누적 계산 - risk_validator: get_current_price dict 파싱, MAX_POSITION_SIZE 동기화, DB 세션 누수 - risk_management/recommendations: date.today() → KST 변환 - mdd_manager: Lock 밖 executed_key 참조 수정 - correlation_filter: output → output2 키 수정 - portfolio: 해외 종목 USD/KRW 환율 적용 분리 - Sharpe Ratio 거래빈도 기반 연간화 - telegram_notifier: send_message() 공개 래퍼 추가 - position_manager: 앱 재시작 시 DB 포지션 복원 - swing exit_service: remaining_pct 조건 범위 수정 - run_backtest: original_qty 기반 remaining_pct 계산 - us_market_schedule: 2027년 미국 공휴일 추가 - Login.tsx: res.ok 검증 추가 - mean_reversion_strategy: RSI 로그 하드코딩 수정 ## HIGH 수정 (10건) - db_worker: DLQ 파일 백업 메커니즘 추가 - korea_investment_api: 만료 토큰 임의 연장 제거 - market_data: chart_cache 최대 100개 + TTL 만료 - main.py: rate_limit_store 1시간 미접근 IP 정리 - recommendations: fire-and-forget try/except 추가 - swing/scheduler: DB 세션 3개 분리 - Dashboard: wsMessages 전체 순회 - Layout: /health 엔드포인트 + 30초 폴링 - ml_ensemble: POST /train require_api_key 추가 - day_trading: record_trade_result_safe() 전환 ## 코드 정리 - 프론트엔드: isUsStock, formatTime 공통 유틸 추출 - 백엔드: dead code 제거, 중복 import 통합 - MCP: JSON 파싱 헬퍼 추출 (~60줄 감소) - 전체 ~100개 파일 한국어 주석 추가 - 테스트 13건 코드 기준 수정 (468 passed) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -34,6 +34,7 @@ except ImportError:
|
||||
InvalidStatusCode = Exception # type: ignore
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.json_helpers import _dumps
|
||||
from app.core.redis import setex_json, TTL_TICK, TTL_QUOTE
|
||||
from app.services.websocket_manager import websocket_manager
|
||||
|
||||
@@ -50,7 +51,8 @@ TR_QUOTE = "H0STASP0" # 주식 호가
|
||||
# ── 타이밍 상수 ──────────────────────────────────────────────────────────────
|
||||
# (.env 설정: KIS_SYNC_INTERVAL, KIS_RECONNECT_WAIT, KIS_APPROVAL_KEY_TTL)
|
||||
_SYNC_INTERVAL = settings.KIS_SYNC_INTERVAL # 구독 목록 동기화 주기 (초)
|
||||
_RECONNECT_WAIT = settings.KIS_RECONNECT_WAIT # 재연결 대기 (초)
|
||||
_RECONNECT_WAIT = settings.KIS_RECONNECT_WAIT # 재연결 기본 대기 (초)
|
||||
_RECONNECT_MAX_WAIT = 300 # 최대 재연결 대기 (5분) — 지수 백오프 상한
|
||||
_APPROVAL_KEY_TTL = settings.KIS_APPROVAL_KEY_TTL # approval_key 캐시 유효시간 (초)
|
||||
|
||||
|
||||
@@ -77,7 +79,9 @@ def _create_ssl_context() -> ssl.SSLContext:
|
||||
|
||||
|
||||
def _get_ws_url() -> str:
|
||||
return _KIS_WS_VIRTUAL if getattr(settings, "KIS_MODE", True) == "virtual" else _KIS_WS_REAL
|
||||
# [이슈4 수정] default값이 True이면 True == "virtual" → False → 실전 URL 반환 오류.
|
||||
# KIS_MODE 기본값은 "virtual" 문자열로 지정해야 함.
|
||||
return _KIS_WS_VIRTUAL if getattr(settings, "KIS_MODE", "virtual") == "virtual" else _KIS_WS_REAL
|
||||
|
||||
|
||||
async def _fetch_approval_key() -> Optional[str]:
|
||||
@@ -127,7 +131,7 @@ async def _fetch_approval_key() -> Optional[str]:
|
||||
|
||||
logger.info(f"🔑 KIS approval_key 자동 발급 요청: {base_url}/oauth2/Approval (모드={['virtual','real'][is_real]})")
|
||||
try:
|
||||
async with _httpx.AsyncClient(timeout=30.0, verify=False) as client:
|
||||
async with _httpx.AsyncClient(timeout=30.0, verify=True) as client:
|
||||
resp = await client.post(
|
||||
f"{base_url}/oauth2/Approval",
|
||||
json={
|
||||
@@ -163,7 +167,7 @@ def _build_subscribe_msg(approval_key: str, tr_id: str, stock_code: str,
|
||||
"""KIS WebSocket 구독/해제 메시지 생성.
|
||||
tr_type='1': 구독, tr_type='2': 해제
|
||||
"""
|
||||
return json.dumps({
|
||||
return _dumps({
|
||||
"header": {
|
||||
"approval_key": approval_key,
|
||||
"custtype": "P",
|
||||
@@ -367,9 +371,13 @@ class KisRealtimeStream:
|
||||
# ── 2단계: WebSocket 연결 ────────────────────────────────────
|
||||
try:
|
||||
ssl_context = _create_ssl_context()
|
||||
|
||||
|
||||
# WebSocket URL: KIS 공식 WebSocket은 경로 없이 루트(/)로 연결
|
||||
# config에 이미 /websocket 등 경로가 포함되어 있으면 그대로 사용
|
||||
ws_full_url = ws_url
|
||||
|
||||
if connection_attempts < max_connection_attempts:
|
||||
logger.info(f"🚀 KIS WS 접속 시도 #{connection_attempts + 1}: {ws_url} (key_len={len(self._approval_key) if self._approval_key else 0})")
|
||||
logger.info(f"🚀 KIS WS 접속 시도 #{connection_attempts + 1}: {ws_full_url} (key_len={len(self._approval_key) if self._approval_key else 0})")
|
||||
else:
|
||||
if connection_attempts == max_connection_attempts:
|
||||
logger.warning(
|
||||
@@ -377,17 +385,10 @@ class KisRealtimeStream:
|
||||
f" 확인 사항:\n"
|
||||
f" 1. .env에서 KIS_WS_VIRTUAL_URL / KIS_WS_REAL_URL 정확한가?\n"
|
||||
f" 2. KIS_MODE가 'virtual' 또는 'real'로 설정되었나?\n"
|
||||
f" 3. 네트워크에서 {ws_url}에 접근 가능한가?\n"
|
||||
f" 3. 네트워크에서 {ws_full_url}에 접근 가능한가?\n"
|
||||
f" 4. KIS 서버가 WebSocket을 지원하나? (REST API만 지원할 수도 있음)\n"
|
||||
)
|
||||
logger.debug(f"🔄 KIS WS 재연결 시도 #{connection_attempts + 1}...")
|
||||
|
||||
# KIS WebSocket 연결: approval_key는 JSON 메시지에서 전송
|
||||
# WebSocket 연결 시에는 URL에 key 포함하지 않음
|
||||
logger.debug(f"📡 WebSocket 연결 URL: {ws_url}/websocket/realtime")
|
||||
|
||||
# WebSocket 헤더 설정
|
||||
ws_full_url = ws_url if ws_url.endswith("/websocket/realtime") else f"{ws_url.rstrip('/')}/websocket/realtime"
|
||||
# Allow optional override via settings, otherwise derive an Origin from the ws url
|
||||
origin = getattr(settings, "KIS_WS_ORIGIN", None)
|
||||
if not origin:
|
||||
@@ -479,7 +480,7 @@ class KisRealtimeStream:
|
||||
try:
|
||||
http_url = ws_full_url.replace('wss://', 'https://')
|
||||
logger.info(f"🔍 Performing HTTP GET diagnostic to {http_url}")
|
||||
async with _httpx.AsyncClient(timeout=10.0, verify=False) as client:
|
||||
async with _httpx.AsyncClient(timeout=10.0, verify=True) as client:
|
||||
# include Origin in diagnostic GET if available to mirror websocket handshake
|
||||
diag_headers = {"User-Agent": "Mozilla/5.0"}
|
||||
if origin:
|
||||
@@ -521,7 +522,10 @@ class KisRealtimeStream:
|
||||
self._approval_key = None
|
||||
|
||||
if self._running:
|
||||
await asyncio.sleep(_RECONNECT_WAIT)
|
||||
# [FIX] 지수 백오프: 연속 실패 시 대기 시간 증가 (KIS IP 차단 방지)
|
||||
backoff = min(_RECONNECT_WAIT * (2 ** min(connection_attempts - 1, 6)), _RECONNECT_MAX_WAIT)
|
||||
logger.info(f"⏳ {backoff:.0f}초 후 재연결 (시도 #{connection_attempts})")
|
||||
await asyncio.sleep(backoff)
|
||||
|
||||
self._running = False
|
||||
logger.info("🔴 KIS 실시간 스트림 종료")
|
||||
|
||||
Reference in New Issue
Block a user