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

@@ -15,7 +15,9 @@ import logging
import time
import pytz
from fastapi import Depends
from app.core.config import settings
from app.core.security import require_api_key as _require_admin_key
from app.api import api_router
from app.services.websocket_manager import websocket_manager
from app.core.json_helpers import _dumps
@@ -48,541 +50,25 @@ logging.basicConfig(level=_log_level, handlers=_handlers)
logger = logging.getLogger(__name__)
def _normalize_recommendations(rec: dict) -> dict:
"""서로 다른 포맷의 추천 결과를 recommendations_by_rule 포맷으로 정규화.
- get_rule_based_recommendations_realtime() → {"recommendations": [...], ...}
- get_rule_based_recommendations_from_db() → {"recommendations_by_rule": {...}, ...}
둘 다 recommendations_by_rule 키를 보장한 상태로 돌려준다.
Redis 캐시 데이터와 DB 데이터 모두 이 함수를 통해 정규화.
변환 실패 시 원본 rec를 그대로 반환 (런타임 에러 방지).
"""
if not rec:
return rec or {}
try:
# Case 1: Already normalized (dict)
if isinstance(rec.get("recommendations_by_rule"), dict):
return rec
# Determine the source of the recommendation list
raw_list = []
if "recommendations" in rec and isinstance(rec["recommendations"], list):
raw_list = rec["recommendations"]
elif "recommendations_by_rule" in rec and isinstance(rec["recommendations_by_rule"], list):
# This is the case that causes the bug
raw_list = rec["recommendations_by_rule"]
if not raw_list:
# if there is no list to process, make sure the output has a dict
rec["recommendations_by_rule"] = {}
return rec
# Group the list by rule
by_rule: dict = {}
for item in raw_list:
rule = (
item.get("rule_name")
or item.get("signal")
or item.get("strategy")
or "general"
)
by_rule.setdefault(rule, []).append(item)
# Return the original dict with the new/replaced 'recommendations_by_rule'
return {**rec, "recommendations_by_rule": by_rule}
except Exception as e:
logger.warning(f"⚠️ _normalize_recommendations 변환 실패, 원본 반환: {e}")
return rec
async def batch_analysis_scheduler():
"""10분 간격 배치 분석 스케줄러.
장중 10분마다 KIS API로 종목 분석 후 stock_analysis DB에 upsert.
분석 완료 후 Redis에 recommendations:latest 캐시를 저장해
auto_trade_scheduler가 DB 조회 없이 바로 매매 판단에 활용할 수 있도록 한다.
개선:
- 15:30 이후 장 종료 감지 → 익일 08:50까지 자동 중단
- 분석 실패 시 exponential backoff 재시도 (최대 3회: 10s/20s/40s)
"""
await asyncio.sleep(15) # 부팅 안정화 (auto_trade_scheduler보다 늦게 시작)
from app.api.endpoints.recommendations import get_rule_based_recommendations_realtime
from app.core.redis import setex_json, TTL_RECOMMENDATIONS, TTL_ANALYSIS
from datetime import timedelta as _td
interval = int(getattr(settings, "BATCH_ANALYSIS_INTERVAL", 600)) # 기본 10분
_KST = pytz.timezone("Asia/Seoul")
logger.info(f"📊 Batch analysis scheduler started (every {interval}s)")
try:
while True:
now_kst = pytz.datetime.datetime.now(_KST)
# 15:30 이후 → 장 종료, 익일 08:50까지 대기
if now_kst.hour > 15 or (now_kst.hour == 15 and now_kst.minute >= 30):
tomorrow_start = (
_KST.localize(
pytz.datetime.datetime(now_kst.year, now_kst.month, now_kst.day, 8, 50, 0)
) + _td(days=1)
)
sleep_sec = max((tomorrow_start - now_kst).total_seconds(), 3600)
logger.info(f"⏸️ [Batch] 장 종료 (15:30 이후). {sleep_sec / 3600:.1f}시간 후 재개")
await asyncio.sleep(sleep_sec)
continue
if not is_market_open():
await asyncio.sleep(1800)
continue
# ── exponential backoff 재시도 (최대 3회) ────────────────────────
max_retries = 3
for attempt in range(max_retries):
try:
suffix = f" (재시도 {attempt + 1}/{max_retries})" if attempt > 0 else ""
logger.info(f"🔄 [Batch] 10-min analysis cycle starting...{suffix}")
result = await get_rule_based_recommendations_realtime()
count = len(result.get("recommendations", [])) if result else 0
logger.info(f"✅ [Batch] Done: {count} stocks saved/updated in stock_analysis DB")
# ── Redis 캐시 업데이트 ─────────────────────────────────────────
if result:
# 정규화: recommendations_by_rule 키 보장 (auto_trade_scheduler 호환)
normalized = _normalize_recommendations(result)
ok = await setex_json(
"recommendations:latest", TTL_RECOMMENDATIONS, normalized
)
if ok:
rec_by_rule = normalized.get('recommendations_by_rule', [])
rec_count = len(rec_by_rule) if isinstance(rec_by_rule, (list, dict)) else 0
logger.info(
f"💾 [Batch] Redis 캐시 갱신 완료: recommendations:latest "
f"(rule 수: {rec_count}, "
f"TTL: {TTL_RECOMMENDATIONS}s)"
)
# ===== 개별 종목별 캐시 (병렬 처리 적용) =====
raw_list = result.get("recommendations", [])
cache_tasks = []
for item in raw_list:
code = item.get("stock_code") or item.get("code")
if code:
cache_tasks.append(setex_json(f"analysis:{code}", TTL_ANALYSIS, item))
if cache_tasks:
await asyncio.gather(*cache_tasks, return_exceptions=True)
logger.info(f"💾 [Batch] 개별 종목 분석 데이터 캐시 갱신 완료: {len(cache_tasks)}건 (TTL: {TTL_ANALYSIS}s)")
# ===============================================
# ───────────────────────────────────────────────────────
break # 성공 시 재시도 루프 탈출
except Exception as e:
wait = 10 * (2 ** attempt) # 10s → 20s → 40s
if attempt < max_retries - 1:
logger.warning(
f"⚠️ [Batch] 분석 실패 ({attempt + 1}/{max_retries}), "
f"{wait}초 후 재시도: {e}"
)
await asyncio.sleep(wait)
else:
logger.error(f"❌ Batch analysis error (최대 재시도 초과): {e}", exc_info=True)
await asyncio.sleep(interval)
except asyncio.CancelledError:
logger.info("⏹️ Batch analysis scheduler stopped")
raise
async def auto_trade_scheduler():
"""1분 간격 자동매매 스케줄러.
Redis 캐시(recommendations:latest)를 먼저 확인 → 캐시 히트 시 DB 조회 없이 매매 실행.
케시 미스(30분 TTL 만료) 시만 get_rule_based_recommendations_from_db() 호출.
주문 직전 MCP RISK_ASSESSMENT 호출 → 승인 시만 주문.
"""
await asyncio.sleep(2)
from app.api.endpoints.recommendations import (
get_rule_based_recommendations_from_db,
execute_auto_trade_background,
)
from app.api.endpoints.portfolio import check_and_execute_exit_trades
from app.api.endpoints.mcp import request_mcp_risk_assessment
from app.core.redis import get_json
logger.info("⏱️ Auto-trade scheduler started (every 60s, Redis→DB fallback mode)")
try:
while True:
try:
if not is_market_open():
logger.info("💤 Market is closed. Next check in 30 minutes.")
await asyncio.sleep(1800)
continue
async with AsyncSessionLocal() as session:
# 1. 보유 종목 손절/익절 체크
logger.info("💰 Checking portfolio for stop-loss/take-profit...")
try:
await check_and_execute_exit_trades(session)
except Exception as e:
logger.error(f"Exit trade check error: {e}", exc_info=True)
# 2. MDD 체크 (CLAUDE.md 5.3) — 신규 진입 가능 여부
from app.services.mdd_manager import mdd_manager
can_open_new = await mdd_manager.can_open_new_position()
if not can_open_new:
logger.warning(
"⚠️ [Auto-Trade] MDD -10% 이상 도달 — 신규 진입 차단. "
"기존 포지션만 손절/익절 모니터링 중"
)
# 3. 자동매매: Redis 캐시 우선 → cache miss 시만 DB 조회
if settings.AUTO_TRADE_ENABLED and can_open_new:
# ── Redis 캐시 확인 (10분 배치 결과, TTL 30분) ────────────────
rec = await get_json("recommendations:latest")
if rec:
rec_by_rule = rec.get('recommendations_by_rule', [])
rec_count = len(rec_by_rule) if isinstance(rec_by_rule, (list, dict)) else 0
logger.info(
"⚡ Redis cache hit: recommendations:latest "
f"(rule 수: {rec_count}) "
"→ DB 조회 생략"
)
# 포맷 정규화 (다른 키 조합 대응)
rec = _normalize_recommendations(rec)
else:
logger.info("🔄 Redis cache miss → DB에서 추천 조회")
rec = await get_rule_based_recommendations_from_db(session)
# ──────────────────────────────────────────────────────
if rec and rec.get("recommendations_by_rule"):
# ── MCP RISK_ASSESSMENT (공통 함수, 이슈 4) ──────────
recommendations = rec.get("recommendations_by_rule", [])
# Handle both list and dict formats for backwards compatibility
if isinstance(recommendations, dict):
# Old format: {rule_name: [stocks]}
recommendation_count = sum(len(v) for v in recommendations.values())
rules_list = list(recommendations.keys())
top_stocks_list = [
item.get("stock_code") or item.get("code", "")
for rule_items in recommendations.values()
for item in (
rule_items[:3]
if isinstance(rule_items, list)
else []
)
][:10]
else:
# New format: [{rule_id, rule_name, stocks: [...]}]
recommendation_count = sum(
len(rule_group.get("stocks", []))
for rule_group in recommendations
if isinstance(rule_group, dict)
)
rules_list = [
rule_group.get("rule_name", rule_group.get("rule_id", ""))
for rule_group in recommendations
if isinstance(rule_group, dict)
]
top_stocks_list = [
item.get("stock_code") or item.get("code", "")
for rule_group in recommendations
if isinstance(rule_group, dict)
for item in rule_group.get("stocks", [])[:3]
][:10]
trade_plan = {
"action": "BUY",
"strategy": "rule_based_batch",
"recommendation_count": recommendation_count,
"rules": rules_list,
"top_stocks": top_stocks_list,
}
portfolio: dict = {}
signals = {
"source": "db_recommendations",
"rules_triggered": rules_list,
}
approve, reason = await request_mcp_risk_assessment(
trade_plan, portfolio, signals
)
# ─────────────────────────────────────────────────────
if not approve:
logger.warning(
f"🛑 MCP RISK_ASSESSMENT DENY → 주문 스킵. 사유: {reason}"
)
try:
from app.services.db_worker import enqueue_db_write
await enqueue_db_write({
"type": "log_mcp_deny",
"reason": reason,
"trade_plan": trade_plan,
})
except Exception:
pass
else:
if reason:
logger.info(
f"✅ MCP RISK_ASSESSMENT APPROVE. 참고: {reason}"
)
logger.info("📊 Found recommendations, executing auto-trade")
await execute_auto_trade_background(rec, session)
else:
logger.info("⏭️ Auto-trade skipped: no recommendations")
elif settings.AUTO_TRADE_ENABLED and not can_open_new:
logger.info("⏸️ Auto-trade disabled (MDD protection) - only monitoring stop-loss/take-profit")
else:
logger.info("⏸️ Auto-trade disabled - only monitoring stop-loss/take-profit")
except Exception as e:
logger.error(f"❌ Auto-trade scheduler error: {e}", exc_info=True)
await asyncio.sleep(60)
except asyncio.CancelledError:
logger.info("⏹️ Auto-trade scheduler stopped")
raise
async def day_trade_scheduler():
"""30초 간격 데이트레이딩 스케줄러 (MDD 보호 기능 포함).
- Opening Range 수집 (09:00~09:30)
- 진입 신호 스캔 + 주문 실행 (09:30~15:00) — MDD -10% 이상이면 진입 중단
- EOD 강제 청산 (15:20~15:30)
- 장 외 시간: 30분 슬립
MDD 체크 (CLAUDE.md 섹션 5.3):
- MDD -10% 도달 시: 데이트레이딩(단기전략) 일시 중단
"""
await asyncio.sleep(5)
from app.api.endpoints.day_trading import run_day_trading_cycle
from app.services.mdd_manager import mdd_manager
logger.info("📈 Day-trade scheduler started (every 30s)")
try:
while True:
if not is_market_open():
await asyncio.sleep(1800)
continue
if not settings.DAY_TRADE_ENABLED:
await asyncio.sleep(60)
continue
# MDD 체크: 단기 전략 활성화 여부 확인 (CLAUDE.md 5.3)
short_term_enabled = await mdd_manager.is_short_term_strategy_enabled()
if not short_term_enabled:
logger.info("⏸️ [DayTrade] MDD -10% 이상 — 단기 전략(데이트레이딩) 중단 (신규 진입 불가)")
await asyncio.sleep(60) # 1분 후 재확인
continue
try:
result = await run_day_trading_cycle()
phase = result.get("phase", "")
if result.get("entries"):
logger.info(f"📈 데이트레이딩 진입: {result['entries']}")
if result.get("exits"):
logger.info(f"📉 데이트레이딩 청산: {result['exits']}")
if phase not in ("market_closed", "outside_window"):
logger.debug(f"Day-trade cycle [{phase}]: {result.get('time')}")
except Exception as e:
logger.error(f"❌ Day-trade scheduler error: {e}", exc_info=True)
await asyncio.sleep(30)
except asyncio.CancelledError:
logger.info("⏹️ Day-trade scheduler stopped")
raise
async def post_market_analyzer_scheduler():
"""장 종료 후 16:00 KST 1회 실행 — 매매일지 자동 생성 + 전략 자동 최적화.
조건:
- 매일 16:00 KST 에 1회 실행 (이미 오늘 실행했으면 스킵)
- 최근 7일 내 SELL FILLED 거래 >= 5건이면 최적화 실행
- 마지막 최적화로부터 3일 이상 경과 시만 최적화 실행
"""
import pytz as _pytz
from datetime import datetime as _dt, date as _date, timedelta as _td
_KST = _pytz.timezone("Asia/Seoul")
_last_run: _date | None = None
await asyncio.sleep(60) # 부팅 안정화
logger.info("📝 Post-market analyzer scheduler started (daily 16:00 KST)")
try:
while True:
now_kst = _dt.now(_KST)
today = now_kst.date()
if _last_run == today:
tomorrow_16 = _KST.localize(_dt(today.year, today.month, today.day, 16, 0, 0)) + _td(days=1)
sleep_sec = (tomorrow_16 - now_kst).total_seconds()
await asyncio.sleep(max(sleep_sec, 60))
continue
if (now_kst.hour, now_kst.minute) < (16, 0):
target = _KST.localize(_dt(today.year, today.month, today.day, 16, 0, 0))
sleep_sec = (target - now_kst).total_seconds()
if sleep_sec > 0:
await asyncio.sleep(min(sleep_sec, 1800))
continue
if today.weekday() >= 5:
await asyncio.sleep(3600)
continue
logger.info("📝 [PostMarket] 매매일지 자동 생성 + 전략 최적화 시작")
_last_run = today
try:
from app.services.trade_analyzer import (
analyze_performance,
get_uncovered_trades,
generate_journal_for_trade,
create_journal_record,
)
from app.services.strategy_optimizer import (
run_optimization,
save_optimization_log,
get_last_optimization_date,
)
from app.models.models import TradeHistory
from sqlalchemy import func, and_
from datetime import datetime as _utcnow_dt
async with AsyncSessionLocal() as db:
uncovered = await get_uncovered_trades(db, days=7)
perf = await analyze_performance(db, days=30)
journal_count = 0
for trade in uncovered:
try:
content = generate_journal_for_trade(trade, perf)
await create_journal_record(db, trade, content)
journal_count += 1
except Exception as e:
logger.warning(f"일지 생성 실패 ({trade.stock_code}): {e}")
if journal_count > 0:
await db.commit()
logger.info(f"📝 [PostMarket] 일지 {journal_count}건 생성 완료")
since_7d = _utcnow_dt.utcnow() - _td(days=7)
trade_count_result = await db.execute(
select(func.count(TradeHistory.id)).where(
and_(
TradeHistory.order_type == "SELL",
TradeHistory.status == "FILLED",
TradeHistory.created_at >= since_7d,
)
)
)
recent_trade_count = trade_count_result.scalar() or 0
last_opt = await get_last_optimization_date(db)
days_since_opt = (today - last_opt).days if last_opt else 999
if recent_trade_count >= 5 and days_since_opt >= 3:
logger.info(f"🔧 [PostMarket] 전략 최적화 실행 (최근거래:{recent_trade_count}건, 마지막:{days_since_opt}일 전)")
result = await run_optimization(db, perf, trigger="auto", period_days=90)
await save_optimization_log(db, result, trigger="auto")
logger.info(f"✅ [PostMarket] 최적화 완료: applied={result.applied}, {result.apply_reason}")
else:
logger.info(f"⏭️ [PostMarket] 최적화 스킵 (거래:{recent_trade_count}건, 마지막최적화:{days_since_opt}일 전)")
except Exception as e:
logger.error(f"❌ [PostMarket] 분석 실패: {e}", exc_info=True)
await asyncio.sleep(3600)
except asyncio.CancelledError:
logger.info("⏹️ Post-market analyzer scheduler stopped")
raise
async def krx_data_collector_scheduler():
"""장 종료 후 KRX 일봉 데이터 자동 수집 스케줄러.
매일 15:40 KST 이후 collect_all(update_mode=True) 를 1회 실행.
이미 오늘 수집 완료된 경우 다음 날까지 스킵.
"""
import pytz as _pytz
from datetime import datetime as _dt, date as _date
_KST = _pytz.timezone("Asia/Seoul")
_last_collected: _date | None = None
await asyncio.sleep(30) # 부팅 안정화
logger.info("📅 KRX data collector scheduler started (daily after 15:40 KST)")
try:
while True:
now_kst = _dt.now(_KST)
today = now_kst.date()
# 오늘 이미 수집했으면 자정까지 대기
if _last_collected == today:
# 다음 날 16:00까지 남은 초 계산
from datetime import timedelta as _td
tomorrow_16 = _KST.localize(
_dt(today.year, today.month, today.day, 16, 0, 0)
) + _td(days=1)
sleep_sec = (tomorrow_16 - now_kst).total_seconds()
logger.info(f"📅 KRX 오늘 수집 완료. 다음 수집까지 {sleep_sec/3600:.1f}시간 대기")
await asyncio.sleep(max(sleep_sec, 60))
continue
# 15:40 이전이면 대기
collect_hour, collect_min = 15, 40
if (now_kst.hour, now_kst.minute) < (collect_hour, collect_min):
# 오늘 15:40까지 남은 초
target = _KST.localize(
_dt(today.year, today.month, today.day, collect_hour, collect_min, 0)
)
sleep_sec = (target - now_kst).total_seconds()
if sleep_sec > 0:
logger.info(f"📅 KRX 수집 대기 중... 15:40까지 {sleep_sec/60:.0f}분 남음")
await asyncio.sleep(min(sleep_sec, 1800)) # 최대 30분마다 재확인
continue
# 주말(토/일)은 스킵하고 다음 날 재확인
if today.weekday() >= 5:
await asyncio.sleep(3600)
continue
# 수집 실행 (최대 3회 재시도, 30분 간격)
max_krx_retries = 3
for krx_attempt in range(max_krx_retries):
try:
suffix = f" (재시도 {krx_attempt + 1}/{max_krx_retries})" if krx_attempt > 0 else ""
logger.info(f"📥 [KRX] 일봉 데이터 증분 수집 시작 (update mode){suffix}...")
from collect_krx_data import collect_all
await collect_all(update_mode=True)
_last_collected = today
logger.info("✅ [KRX] 일봉 데이터 수집 완료")
break
except Exception as e:
if krx_attempt < max_krx_retries - 1:
logger.warning(
f"⚠️ [KRX] 수집 실패 ({krx_attempt + 1}/{max_krx_retries}), "
f"30분 후 재시도: {e}"
)
await asyncio.sleep(1800)
else:
logger.error(f"❌ [KRX] 데이터 수집 최대 재시도 초과: {e}", exc_info=True)
except asyncio.CancelledError:
logger.info("⏹️ KRX data collector scheduler stopped")
raise
# Import scheduler functions from dedicated module
from app.services.schedulers import (
batch_analysis_scheduler,
post_market_analyzer_scheduler,
krx_data_collector_scheduler,
news_collect_scheduler,
pre_market_us_scheduler,
)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""애플리케이션 시작/종료 시 실행될 코드"""
logger.info("Starting Auto Stock Trading System...")
logger.info(f"KIS API Mode: {'모의투자 (VIRTUAL)' if settings.is_virtual_trading else '실전투자 (REAL)'}")
logger.info(f"KIS API Mode: {'모의투자 (VIRTUAL)' if settings.is_virtual_trading else '⚠️ 실전투자 (REAL)'}")
logger.info(f"KIS Base URL: {settings.KOREA_INVESTMENT_API_BASE_URL}")
logger.info(f"KIS Account: {settings.KOREA_INVESTMENT_ACCOUNT_NUMBER}")
_acct = settings.KOREA_INVESTMENT_ACCOUNT_NUMBER
_masked_acct = f"{_acct[:4]}****{_acct[-2:]}" if len(_acct) >= 6 else "***"
logger.info(f"KIS Account: {_masked_acct}")
# ── 필수 환경변수 검증 (조기 경보) ──────────────────────────────────────────
for warn_msg in settings.validate_required():
@@ -672,14 +158,85 @@ async def lifespan(app: FastAPI):
from app.core.redis import init_redis, close_redis
await init_redis()
# 워커 + 스케줄러 시작
# ── MDD 상태 복원 (Redis 영속화) ────────────────────────────────────────
try:
from app.services.mdd_manager import mdd_manager
restored = await mdd_manager.load_from_redis()
if not restored:
logger.info("ℹ️ MDD Redis 상태 없음 — 초기 상태로 시작")
except Exception as e:
logger.warning(f"⚠️ MDD Redis 복원 실패 (non-critical): {e}")
# 워커 + 스케줄러 시작 (C5: 자동 재시작 콜백 포함)
def _restart_db_worker(task: asyncio.Task):
if task.cancelled():
return
exc = task.exception()
if exc:
logger.error(f"db_worker 크래시: {exc}, 자동 재시작...")
# Telegram 시스템 경고
try:
from app.services.telegram_notifier import telegram_notifier
asyncio.ensure_future(telegram_notifier.notify_system_warning(
category="DB_WORKER",
message=f"db_worker 크래시 후 자동 재시작: {type(exc).__name__}: {exc}",
))
except Exception:
pass
new_task = asyncio.create_task(db_writer_worker())
new_task.add_done_callback(_restart_db_worker)
app.state.db_worker_task = new_task
app.state.db_worker_task = asyncio.create_task(db_writer_worker())
app.state.auto_trade_task = asyncio.create_task(auto_trade_scheduler())
app.state.db_worker_task.add_done_callback(_restart_db_worker)
# ── 스윙 / 데이트레이딩 분리 스케줄러 (신규 아키텍처) ────────────────────
from app.services.swing.scheduler import swing_scheduler
from app.services.daytrading.scheduler import daytrading_scheduler
app.state.swing_trade_task = asyncio.create_task(swing_scheduler())
app.state.day_trade_task = asyncio.create_task(daytrading_scheduler())
# 배치 분석 / 일봉 수집 / 장 후 분석 (기존 유지)
app.state.batch_analysis_task = asyncio.create_task(batch_analysis_scheduler())
app.state.day_trade_task = asyncio.create_task(day_trade_scheduler())
app.state.krx_collector_task = asyncio.create_task(krx_data_collector_scheduler())
app.state.post_market_task = asyncio.create_task(post_market_analyzer_scheduler())
# ── 미국장 자동매매 스케줄러 (US_TRADING_ENABLED=True 시 활성화) ──────────
if getattr(settings, 'US_TRADING_ENABLED', False):
from app.services.us_market_scheduler import us_auto_trade_scheduler
app.state.us_trade_task = asyncio.create_task(us_auto_trade_scheduler())
logger.info("🇺🇸 US market auto-trade scheduler started (US_TRADING_ENABLED=True)")
else:
logger.info("⏭️ US market auto-trade disabled (US_TRADING_ENABLED=False in .env)")
app.state.us_trade_task = None
# ── 뉴스 수집 스케줄러 (NEWS_ENABLED=True 시 활성화) ─────────────────────
app.state.news_collect_task = asyncio.create_task(news_collect_scheduler())
logger.info("News collect scheduler started")
# ── 미장 프리마켓 심리 분석 (07:00 KST, 1회/일) ────────────────────────
app.state.pre_market_us_task = asyncio.create_task(pre_market_us_scheduler())
logger.info("🌍 Pre-market US sentiment scheduler registered (daily 07:00 KST)")
# ── ML 재학습 스케줄러 ───────────────────────────────────────────────────
from app.services.ml_retrain_pipeline import ml_retrain_scheduler
app.state.ml_retrain_task = asyncio.create_task(ml_retrain_scheduler())
logger.info("ML retrain scheduler started")
# ── 적응형 전략 엔진 초기화 + 주기적 갱신 ────────────────────────────────
async def _adaptive_strategy_scheduler():
"""적응형 전략 파라미터를 2분 주기로 갱신."""
from app.services.adaptive_strategy import refresh_adaptive_params
await asyncio.sleep(10) # 서버 기동 후 10초 대기
while True:
try:
await refresh_adaptive_params()
except Exception as e:
logger.warning("[Adaptive] 스케줄러 오류: %s", e)
await asyncio.sleep(120) # 2분 주기
app.state.adaptive_strategy_task = asyncio.create_task(_adaptive_strategy_scheduler())
logger.info("Adaptive strategy engine scheduler started")
# KIS 실시간 스트림 시작 (설정으로 제어 가능)
if settings.KIS_WS_ENABLED:
from app.services.kis_realtime_stream import run_kis_realtime_stream
@@ -693,13 +250,18 @@ async def lifespan(app: FastAPI):
# 태스크 정리
for task_attr in (
"auto_trade_task",
"swing_trade_task",
"batch_analysis_task",
"day_trade_task",
"krx_collector_task",
"post_market_task",
"db_worker_task",
"kis_stream_task",
"us_trade_task",
"news_collect_task",
"ml_retrain_task",
"pre_market_us_task",
"adaptive_strategy_task",
):
try:
task = getattr(app.state, task_attr, None)
@@ -722,6 +284,13 @@ async def lifespan(app: FastAPI):
except Exception as e:
logger.warning(f"Failed to close Redis: {e}")
# ── Telegram 클라이언트 종료 ───────────────────────────────────────────────
try:
from app.services.telegram_notifier import telegram_notifier
await telegram_notifier.close()
except Exception as e:
logger.warning(f"Failed to close Telegram notifier: {e}")
logger.info("Shutting down Auto Stock Trading System...")
await engine.dispose()
@@ -749,13 +318,63 @@ app.add_middleware(
CORSMiddleware,
allow_origins=_allowed_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
expose_headers=["*"],
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["Content-Type", "Authorization", "X-API-Key", "X-Requested-With"],
expose_headers=["X-Request-Id"],
)
logger.info("CORS middleware configured")
# ── [C6] 간이 Rate Limiter (IP 기반, 인메모리) ──────────────────────────────
_rate_limit_store: dict[str, list[float]] = {} # IP -> [timestamps]
_RATE_LIMIT_WINDOW = 60 # 초
_RATE_LIMIT_MAX_REQUESTS = 300 # 윈도우 내 최대 요청 수 (대시보드 폴링 고려)
_RATE_LIMIT_CLEANUP_INTERVAL = 100 # N 요청마다 stale IP 정리
_RATE_LIMIT_STALE_THRESHOLD = 3600 # 1시간 이상 미접근 IP 삭제
_rate_limit_counter = 0 # cleanup 트리거 카운터
@app.middleware("http")
async def rate_limit_middleware(request: Request, call_next):
"""IP 기반 간이 rate limiter — 인증 없는 엔드포인트 DoS 방어."""
global _rate_limit_counter
client_ip = request.client.host if request.client else "unknown"
now = time.time()
# /health, /ws/, OPTIONS(CORS preflight) 는 rate limit 제외
path = request.url.path
if path.startswith(("/health", "/ws/")) or request.method == "OPTIONS":
return await call_next(request)
timestamps = _rate_limit_store.get(client_ip, [])
# 윈도우 밖 타임스탬프 제거
timestamps = [t for t in timestamps if now - t < _RATE_LIMIT_WINDOW]
timestamps.append(now)
_rate_limit_store[client_ip] = timestamps
if len(timestamps) > _RATE_LIMIT_MAX_REQUESTS:
from fastapi.responses import JSONResponse
return JSONResponse(
status_code=429,
content={"detail": "Too many requests. Please try again later."},
)
# 100 요청마다 stale IP 키 정리 (1시간 이상 미접근)
_rate_limit_counter += 1
if _rate_limit_counter >= _RATE_LIMIT_CLEANUP_INTERVAL:
_rate_limit_counter = 0
stale_ips = [
ip for ip, ts_list in _rate_limit_store.items()
if not ts_list or (now - max(ts_list)) > _RATE_LIMIT_STALE_THRESHOLD
]
for ip in stale_ips:
del _rate_limit_store[ip]
if stale_ips:
logger.debug(f"Rate limit store cleanup: {len(stale_ips)} stale IPs removed, {len(_rate_limit_store)} remaining")
return await call_next(request)
_LOG_SKIP_PREFIXES = ("/health", "/ws/")
@@ -789,10 +408,11 @@ from fastapi.responses import JSONResponse as _JSONResponse
async def global_exception_handler(_req: _Request, exc: Exception) -> _JSONResponse:
"""처리되지 않은 예외를 500 JSON으로 변환해 일관된 에러 응답을 보장한다."""
logger.error(f"Unhandled exception: {_req.method} {_req.url} — {exc}", exc_info=True)
return _JSONResponse(
status_code=500,
content={"detail": "내부 서버 오류가 발생했습니다. 잠시 후 다시 시도해 주세요."},
)
content = {"detail": "내부 서버 오류가 발생했습니다. 잠시 후 다시 시도해 주세요."}
# DEBUG 모드에서만 스택트레이스 노출 (운영 환경 정보 유출 방지)
if settings.DEBUG:
content["error"] = str(exc)
return _JSONResponse(status_code=500, content=content)
@app.get("/")
@@ -836,6 +456,9 @@ async def health_check():
async def websocket_endpoint(websocket: WebSocket, client_id: str):
"""WebSocket 연결 엔드포인트.
인증: 쿼리 파라미터 ?token= 또는 첫 메시지로 {"type": "auth", "token": "..."}
개발 모드(DEBUG=true)에서는 인증 없이 접속 허용.
클라이언트→서버 지원 프로토콜:
{"type": "ping"} → {"type": "pong"}
{"type": "subscribe", "stock_codes": [...]} → ACK
@@ -845,39 +468,73 @@ async def websocket_endpoint(websocket: WebSocket, client_id: str):
→ {"type": "chart_data", ...}
그 외 메시지 → echo
"""
# WebSocket 인증: 운영 환경에서는 토큰 검증 (API_KEY 또는 SECRET_KEY 허용)
if not settings.DEBUG:
import hmac
from app.core.security import _get_api_key
token = websocket.query_params.get("token", "")
expected = _get_api_key()
if not token or not hmac.compare_digest(token.encode(), expected.encode()):
await websocket.close(code=4001, reason="Unauthorized")
return
await websocket_manager.connect(websocket, client_id)
# 연결 즉시 보유종목 자동 구독 (set_subscriptions 누락 대비 폴백)
async def _auto_subscribe_portfolio(cid: str):
try:
from app.api.endpoints.portfolio import portfolio_cache
holdings = portfolio_cache.holdings
if holdings:
codes = [h.stock_code for h in holdings if h.stock_code and h.quantity > 0]
if codes:
websocket_manager.subscribe(cid, codes)
from app.services.kis_realtime_stream import kis_stream
kis_stream.notify_subscription_change()
logger.info(f"[auto-sub] {cid}: 보유종목 {len(codes)}개 자동 구독 → {codes[:5]}...")
except Exception as e:
logger.debug(f"[auto-sub] 보유종목 자동 구독 실패: {e}")
asyncio.create_task(_auto_subscribe_portfolio(client_id))
try:
while True:
# 이 핸들러의 websocket이 active_connections에서 교체되었으면 종료
if websocket_manager.active_connections.get(client_id) is not websocket:
logger.debug(f"Client {client_id}: 교체된 연결 감지, 이전 핸들러 종료")
break
try:
data = await asyncio.wait_for(websocket.receive_text(), timeout=60.0)
except asyncio.TimeoutError:
# 60초 동안 메시지 없음 → ping 전송으로 연결 유지 확인
try:
await websocket_manager.send_personal_message(
json.dumps({"type": "ping"}), client_id
)
await websocket.send_text(_dumps({"type": "ping"}))
except Exception:
break
continue
try:
msg = json.loads(data)
except (json.JSONDecodeError, AttributeError):
await websocket_manager.send_personal_message(f"Echo: {data}", client_id)
try:
await websocket.send_text(f"Echo: {data}")
except Exception:
break
continue
msg_type = msg.get("type", "")
if msg_type == "ping":
await websocket_manager.send_personal_message(
json.dumps({"type": "pong"}), client_id
)
try:
await websocket.send_text(_dumps({"type": "pong"}))
except Exception:
break
continue
if msg_type == "subscribe":
codes = [str(c) for c in msg.get("stock_codes", [])]
websocket_manager.subscribe(client_id, codes)
await websocket_manager.send_personal_message(
json.dumps({
_dumps({
"type": "ack", "action": "subscribe",
"stock_codes": codes,
"subscriptions": websocket_manager.get_subscriptions(client_id),
@@ -890,7 +547,7 @@ async def websocket_endpoint(websocket: WebSocket, client_id: str):
codes = [str(c) for c in msg.get("stock_codes", [])]
websocket_manager.unsubscribe(client_id, codes)
await websocket_manager.send_personal_message(
json.dumps({
_dumps({
"type": "ack", "action": "unsubscribe",
"stock_codes": codes,
"subscriptions": websocket_manager.get_subscriptions(client_id),
@@ -901,29 +558,30 @@ async def websocket_endpoint(websocket: WebSocket, client_id: str):
if msg_type == "set_subscriptions":
codes = [str(c) for c in msg.get("stock_codes", [])]
logger.info(f"[WS] {client_id}: set_subscriptions → {codes}")
websocket_manager.set_subscriptions(client_id, codes)
# 구독 목록 변경 → KIS 스트림에 즉시 동기화 요청
from app.services.kis_realtime_stream import kis_stream
kis_stream.notify_subscription_change()
await websocket_manager.send_personal_message(
json.dumps({
try:
await websocket.send_text(_dumps({
"type": "ack", "action": "set_subscriptions",
"stock_codes": codes,
"subscriptions": websocket_manager.get_subscriptions(client_id),
}),
client_id,
)
}))
except Exception:
break
# 구독 종목 차트 캐시 사전 워밍업 (백그라운드, 논블로킹)
if codes:
async def _warmup_chart_cache(stock_codes: list):
from app.api.endpoints.market_data import get_chart_data_cached, chart_cache
from datetime import datetime
for code in stock_codes:
cached = chart_cache.get(f"{code}__D")
cached = chart_cache.get(f"{code}__D__200")
if cached and (datetime.now() - cached["timestamp"]).total_seconds() < 600:
continue
try:
await get_chart_data_cached(code, "D", 100)
await get_chart_data_cached(code, "D", 200)
logger.debug(f"[warmup] {code} 차트 캐시 완료")
except Exception as e:
logger.debug(f"[warmup] {code} 캐시 실패: {e}")
@@ -936,32 +594,48 @@ async def websocket_endpoint(websocket: WebSocket, client_id: str):
limit = int(msg.get("limit", 200))
if not stock_code:
continue
# 자동 구독 폴백: 클라이언트에 구독 종목이 없으면 요청 종목 자동 구독
current_subs = websocket_manager.get_subscriptions(client_id)
if stock_code not in current_subs:
websocket_manager.subscribe(client_id, [stock_code])
from app.services.kis_realtime_stream import kis_stream
kis_stream.notify_subscription_change()
logger.info(f"[auto-sub] {client_id}: get_chart 요청으로 {stock_code} 자동 구독 추가")
try:
from app.api.endpoints.market_data import get_chart_data_cached
chart_data = await get_chart_data_cached(stock_code, period, limit)
await websocket_manager.send_personal_message(
logger.info(f"[get_chart] {stock_code}/{period} → {len(chart_data)} candles → sending to {client_id}")
await websocket.send_text(
_dumps({"type": "chart_data", "stock_code": stock_code, "period": period, "data": chart_data}),
client_id,
)
except Exception as e:
logger.error(f"get_chart 오류 ({stock_code}): {e}")
await websocket_manager.send_personal_message(
_dumps({"type": "chart_data", "stock_code": stock_code, "period": period, "data": [], "error": str(e)}),
client_id,
)
try:
await websocket.send_text(
_dumps({"type": "chart_data", "stock_code": stock_code, "period": period, "data": [], "error": str(e)}),
)
except Exception:
break
continue
await websocket_manager.send_personal_message(f"Echo: {data}", client_id)
except WebSocketDisconnect:
websocket_manager.disconnect(client_id)
logger.info(f"Client {client_id} disconnected")
except WebSocketDisconnect as e:
# 동일 client_id로 새 연결이 교체되었을 경우, 이전 핸들러가 disconnect하면 새 연결까지 제거됨
# 현재 websocket이 active_connections에 있는 것과 동일한 경우에만 disconnect
if websocket_manager.active_connections.get(client_id) is websocket:
websocket_manager.disconnect(client_id)
logger.info(f"Client {client_id} disconnected (code={e.code})")
except Exception as e:
if websocket_manager.active_connections.get(client_id) is websocket:
websocket_manager.disconnect(client_id)
logger.error(f"Client {client_id} unexpected WS error: {type(e).__name__}: {e}")
@app.post("/api/admin/reset-daily-loss")
async def reset_daily_loss():
"""테스트용 일일 손실 한도 강제 리셋"""
async def reset_daily_loss(api_key: str = Depends(_require_admin_key)):
"""테스트용 일일 손실 한도 강제 리셋 (인증 필수)"""
from app.services.mdd_manager import mdd_manager
mdd_manager.reset() # 이미 reset() 메서드 존재 [cite:9]
await mdd_manager.reset()
return {"status": "ok", "message": "daily loss limit reset"}