feat: 자동매매 신뢰성 개선 — 시세 실서버 라우팅·일일 한도 전역화·수동 매수 API
- korea_investment_api: KIS_QUOTES_VIA_REAL — 모의투자 모드에서 시세/차트/호가 조회를 실계좌 시세 서버(20/s)로 위임, 주문·잔고는 모의서버 유지 (EGW00201 대응) - recommendations: execute_auto_trade_background asyncio.Lock 중복 실행 방지 + MAX_DAILY_TRADES를 당일 BUY 건수 차감 전역 기준으로 적용 (11종목 동시 매수 재발 방지) - manual_buy.py 신규: POST /api/v1/portfolio/buy (리스크 가드 + safe_place_order + db_worker) - mcp-server: claude_code_client(claude -p 헤드리스 모드) 추가, trade_monitor 부분매도 시 active 유지·remaining_pct 갱신, API 키 헤더·/api/v1 경로 수정, ODNO 주문ID 수정 - config: MCP_REQUEST_TIMEOUT, MCP_RISK_CACHE_TTL, BATCH_ANALYSIS_INTERVAL, SWING_INDEX_BREAKER_ENABLED(OFF), API_TRIGGERED_AUTO_TRADE(OFF) 추가 - docker-compose: 포트 충돌 해소 (postgres 15433, frontend 3001) - frontend: 추천 패널 매수 버튼, 차트/호가/저널 패널 개선 - CLAUDE.md 압축 최적화 (규칙 변경 없음), _sweep_single_axis.py 백테스트 단일축 스윕 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -14,6 +14,7 @@ from typing import Dict, Any, Optional, Tuple
|
||||
from pydantic import BaseModel
|
||||
import httpx
|
||||
import logging
|
||||
import time
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
@@ -66,6 +67,20 @@ def get_http_client() -> httpx.AsyncClient:
|
||||
_fail_open_count: int = 0
|
||||
_FAIL_OPEN_WARN_THRESHOLD: int = 5 # 연속 N회 초과 시 경고 로그
|
||||
|
||||
# ─── RISK_ASSESSMENT 결과 캐시 (MCP_RISK_CACHE_TTL>0 일 때만) ────────────
|
||||
# 스케줄러가 매 사이클(60s/30s) 같은 종목셋으로 재요청하는 AI 호출을 줄인다.
|
||||
_risk_cache: Dict[str, Tuple[float, bool, str]] = {} # key → (expires_at, approve, reason)
|
||||
|
||||
|
||||
def _risk_cache_key(trade_plan: Dict[str, Any]) -> str:
|
||||
stocks = trade_plan.get("top_stocks") or []
|
||||
codes = sorted(
|
||||
str(s.get("stock_code", s) if isinstance(s, dict) else s) for s in stocks
|
||||
)
|
||||
if not codes and trade_plan.get("stock_code"):
|
||||
codes = [str(trade_plan["stock_code"])]
|
||||
return f"{trade_plan.get('strategy', '')}:{trade_plan.get('action', '')}:{','.join(codes)}"
|
||||
|
||||
|
||||
# ─── 공통 리스크 평가 함수 ────────────────────────────────────────────
|
||||
async def request_mcp_risk_assessment(
|
||||
@@ -91,6 +106,13 @@ async def request_mcp_risk_assessment(
|
||||
if not settings.MCP_VALIDATION_ENABLED:
|
||||
return True, "mcp_disabled"
|
||||
|
||||
_ttl = settings.MCP_RISK_CACHE_TTL
|
||||
_ckey = _risk_cache_key(trade_plan) if _ttl > 0 else None
|
||||
if _ckey:
|
||||
_hit = _risk_cache.get(_ckey)
|
||||
if _hit and _hit[0] > time.monotonic():
|
||||
return _hit[1], f"{_hit[2]} (cached)"
|
||||
|
||||
try:
|
||||
client = get_http_client()
|
||||
except RuntimeError:
|
||||
@@ -116,7 +138,7 @@ async def request_mcp_risk_assessment(
|
||||
"signals": signals,
|
||||
},
|
||||
},
|
||||
timeout=15.0,
|
||||
timeout=settings.MCP_REQUEST_TIMEOUT,
|
||||
)
|
||||
if resp.status_code == 200:
|
||||
result = resp.json()
|
||||
@@ -124,11 +146,11 @@ async def request_mcp_risk_assessment(
|
||||
payload = result.get("result", result)
|
||||
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
|
||||
approve = not ("deny" in decision or "reject" in decision)
|
||||
if _ckey:
|
||||
_risk_cache[_ckey] = (time.monotonic() + _ttl, approve, reason)
|
||||
return approve, reason
|
||||
else:
|
||||
_fail_open_count += 1
|
||||
logger.warning(
|
||||
|
||||
Reference in New Issue
Block a user