Files
auto-stock/backend/app/services/daytrading/scheduler.py
shuim de7921d270 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>
2026-03-26 16:05:41 +09:00

157 lines
6.2 KiB
Python

"""데이트레이딩 독립 스케줄러
main.py의 lifespan에서 asyncio.create_task()로 시작되는
백그라운드 태스크. 기존 day_trade_scheduler()를 대체.
30초 주기 실행 흐름:
- 장외 시간: 30분 슬립 (CPU 낭비 방지)
- DAY_TRADE_ENABLED=False: 60초 슬립
- 09:00~09:30: ORB 수집 (collect_opening_ranges)
- 09:30~14:30: 신호 스캔 + 진입 (scan_and_enter) + 청산 체크 (check_and_exit_positions)
- 14:30~15:20: 청산 체크만 (신규 진입 마감)
- 15:20~15:30: EOD 강제 청산 (force_close_all)
MDD 규칙 (CLAUDE.md 5.3):
- MDD -10% 이하 시 신규 진입 차단
- 기존 포지션의 청산 체크는 MDD 무관하게 계속 수행 (포지션 보호)
watchlist 자동 설정:
- ORB 수집 시작 시 watchlist 없으면 stock_analysis에서 자동 로드
- 장중에도 30분 간격으로 watchlist 갱신 시도
"""
import asyncio
import logging
import time
from app.core.config import settings
from app.core.market_schedule import (
is_market_open, is_opening_range_period,
is_day_trade_entry_window, is_eod_flat_time,
)
from app.services.mdd_manager import mdd_manager
from app.services.daytrading.position_manager import day_trading_state
from app.services.daytrading.entry_service import (
collect_opening_ranges, scan_and_enter,
get_watchlist, populate_daytrading_watchlist,
)
from app.services.daytrading.exit_service import check_and_exit_positions, force_close_all
logger = logging.getLogger(__name__)
# watchlist 자동 갱신 타임스탬프 (epoch seconds)
# 30분(1800초)마다 stock_analysis에서 재조회
_last_wl_sync: float = 0.0
async def daytrading_scheduler() -> None:
"""30초 주기 데이트레이딩 스케줄러.
무한 루프로 실행되며 asyncio.CancelledError로만 종료.
각 사이클에서 예외 발생 시 로그 기록 후 다음 사이클 계속.
시간대별 동작:
- 장외: 30분 대기 (is_market_open() 기준)
- EOD: 보유 포지션 강제 청산
- ORB 시간: 시초가 레인지 수집
- 엔트리 윈도우: 진입 + 청산 동시 처리
- 기타: 보유 포지션 청산 체크만
"""
await asyncio.sleep(5)
logger.info("⚡ [DayTrading] Scheduler started (every 30s)")
# 앱 재시작 시 DB에서 당일 데이트레이딩 포지션 복원 (CRITICAL 버그 수정)
try:
from app.core.database import AsyncSessionLocal
async with AsyncSessionLocal() as db:
restored = await day_trading_state.restore_from_db(db)
if restored:
logger.info(f"[DayTrading] 시작 시 {restored}개 포지션 복원됨")
except Exception as e:
logger.error(f"[DayTrading] 시작 시 포지션 복원 실패: {e}", exc_info=True)
try:
while True:
try:
day_trading_state.reset_if_new_day()
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_ok = await mdd_manager.is_short_term_strategy_enabled()
# EOD 강제 청산 (15:20)
if is_eod_flat_time():
if day_trading_state.positions:
exits = await force_close_all(reason="EOD 강제 청산 (15:20)")
if exits:
logger.info(f"[DayTrading] EOD 청산: {len(exits)}건")
await asyncio.sleep(30)
continue
# 09:00~09:30 ORB 수집
if is_opening_range_period():
if not get_watchlist():
try:
count = await populate_daytrading_watchlist()
if count:
logger.info(f"[DayTrading] 자동 watchlist: {count}개")
except Exception as e:
logger.warning(f"[DayTrading] watchlist 자동설정 실패: {e}")
await collect_opening_ranges()
await asyncio.sleep(30)
continue
# 09:30~15:00 신호 스캔 + 청산 체크
if is_day_trade_entry_window():
global _last_wl_sync
wl = get_watchlist()
if not wl and (time.time() - _last_wl_sync) > 1800:
_last_wl_sync = time.time()
try:
await populate_daytrading_watchlist()
wl = get_watchlist()
except Exception:
pass
logger.info(
f"[DayTrading] 🔄 cycle: mdd_ok={short_term_ok}, "
f"watchlist={len(wl)}, positions={day_trading_state.position_count()}"
)
# 청산 체크 (MDD 무관 — 기존 포지션 보호)
exits = await check_and_exit_positions()
if exits:
logger.info(f"[DayTrading] 청산: {len(exits)}건")
# 진입 (MDD 허용 시만)
if short_term_ok:
entries = await scan_and_enter()
if entries:
logger.info(f"[DayTrading] 진입: {len(entries)}건")
else:
logger.info("[DayTrading] ⏸️ MDD -10% 이상 — 신규 진입 차단")
await asyncio.sleep(30)
continue
# 그 외 시간 — 보유 포지션 청산 체크만
if day_trading_state.positions:
exits = await check_and_exit_positions()
if exits:
logger.info(f"[DayTrading] 장외 청산: {len(exits)}건")
except Exception as e:
logger.error(f"[DayTrading] 스케줄러 오류: {e}", exc_info=True)
await asyncio.sleep(30)
except asyncio.CancelledError:
logger.info("[DayTrading] Scheduler stopped")
raise