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:
2026-03-26 16:05:41 +09:00
parent 739a8a2e5d
commit de7921d270
149 changed files with 133353 additions and 3338 deletions

View File

@@ -25,14 +25,23 @@ router = APIRouter()
_http_client: Optional[httpx.AsyncClient] = None
def _mcp_default_headers() -> dict:
"""MCP 서버 인증용 기본 헤더. MCP_API_KEY가 설정되어 있으면 X-API-Key 포함."""
headers: dict = {}
if settings.MCP_API_KEY:
headers["X-API-Key"] = settings.MCP_API_KEY
return headers
async def init_http_client() -> None:
"""lifespan 시작 시 한 번만 호출. keepalive 연결 풀 설정."""
global _http_client
_http_client = httpx.AsyncClient(
timeout=httpx.Timeout(connect=5.0, read=60.0, write=10.0, pool=5.0),
limits=httpx.Limits(max_keepalive_connections=5, max_connections=10),
headers=_mcp_default_headers(),
)
logger.info("✅ MCP httpx.AsyncClient initialized")
logger.info("MCP httpx.AsyncClient initialized (api_key=%s)", "set" if settings.MCP_API_KEY else "none")
async def close_http_client() -> None:
@@ -53,6 +62,11 @@ def get_http_client() -> httpx.AsyncClient:
return _http_client
# ─── fail-open 카운터 ─────────────────────────────────────────────────
_fail_open_count: int = 0
_FAIL_OPEN_WARN_THRESHOLD: int = 5 # 연속 N회 초과 시 경고 로그
# ─── 공통 리스크 평가 함수 ────────────────────────────────────────────
async def request_mcp_risk_assessment(
trade_plan: Dict[str, Any],
@@ -72,13 +86,23 @@ async def request_mcp_risk_assessment(
- approve=False → 주문 스킵
- MCP 장애 / 타임아웃 → fail-open (approve=True, 매매 중단 방지)
"""
global _fail_open_count
if not settings.MCP_VALIDATION_ENABLED:
return True, "mcp_disabled"
try:
client = get_http_client()
except RuntimeError:
logger.warning("⚠️ http_client 미초기화 — fail-open")
_fail_open_count += 1
logger.warning(
"MCP http_client 미초기화 — fail-open (누적 %d회)", _fail_open_count
)
if _fail_open_count > _FAIL_OPEN_WARN_THRESHOLD:
logger.error(
"MCP fail-open 연속 %d회 초과: MCP 서버 연결 상태를 점검하세요",
_fail_open_count,
)
return True, "client_not_initialized_fail_open"
try:
@@ -101,16 +125,42 @@ async def request_mcp_risk_assessment(
decision = str(payload.get("decision", "approve")).lower()
reason = str(payload.get("reason", ""))
if "deny" in decision or "reject" in decision:
_fail_open_count = 0 # 정상 응답 수신 시 카운터 리셋
return False, reason
_fail_open_count = 0 # 정상 응답 수신 시 카운터 리셋
return True, reason
else:
logger.warning(f"⚠️ MCP RISK_ASSESSMENT HTTP {resp.status_code} — fail-open")
_fail_open_count += 1
logger.warning(
"MCP RISK_ASSESSMENT HTTP %d — fail-open (누적 %d회)",
resp.status_code, _fail_open_count,
)
if _fail_open_count > _FAIL_OPEN_WARN_THRESHOLD:
logger.error(
"MCP fail-open 연속 %d회 초과: MCP 서버 응답 오류가 지속됩니다",
_fail_open_count,
)
return True, f"mcp_http_{resp.status_code}_fail_open"
except httpx.TimeoutException:
logger.warning("⚠️ MCP RISK_ASSESSMENT 타임아웃 — fail-open")
_fail_open_count += 1
logger.warning(
"MCP RISK_ASSESSMENT 타임아웃 — fail-open (누적 %d회)", _fail_open_count
)
if _fail_open_count > _FAIL_OPEN_WARN_THRESHOLD:
logger.error(
"MCP fail-open 연속 %d회 초과: MCP 서버 타임아웃이 지속됩니다",
_fail_open_count,
)
return True, "mcp_timeout_fail_open"
except Exception as e:
logger.warning(f"⚠️ MCP RISK_ASSESSMENT 오류: {e} — fail-open")
_fail_open_count += 1
logger.warning(
"MCP RISK_ASSESSMENT 오류: %s — fail-open (누적 %d회)", e, _fail_open_count
)
if _fail_open_count > _FAIL_OPEN_WARN_THRESHOLD:
logger.error(
"MCP fail-open 연속 %d회 초과: 오류=%s", _fail_open_count, e
)
return True, f"mcp_error_fail_open: {e}"