Files
auto-stock/backend/app/services/daytrading/scheduler.py
shuim d8550a2241 fix: 스케줄러 단계별 타임아웃 — KIS 무응답 시 EOD 청산 누락 방지
로그 분석(2026-09-22): 15:03:46 진입 스캔 이후 데이트레이딩 스케줄러가 16:52 재배포까지
1시간 49분간 아무 로그도 남기지 않음 = KIS API 무응답(500/Server disconnected 연속)으로
await가 반환되지 않아 루프 정지 → 15:20 EOD 강제청산 미실행 → 포지션 익일 보유.
- _guard(): 각 단계를 asyncio.wait_for로 감싸 초과 시 취소 후 다음 사이클 진행
- 단계별 상한: MDD 30s / watchlist 120s / ORB·EOD청산 300s / 청산·진입 180s
- MDD 판단 불가 시 보수적으로 신규 진입 차단
- 테스트 3건

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 10:18:00 +09:00

203 lines
9.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,
seconds_until_market_open,
)
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, is_watchlist_auto,
)
from app.services.daytrading.exit_service import check_and_exit_positions, force_close_all
logger = logging.getLogger(__name__)
# 단계별 최대 실행 시간(초). KIS API가 응답 없이 멈추면(2026-09-22 15:03 이후 1시간 49분
# 스케줄러 정지 → 15:20 EOD 청산 누락) 루프 전체가 얼어붙으므로 단계마다 상한을 둔다.
STEP_TIMEOUT = 180
async def _guard(coro, step: str, timeout: int = STEP_TIMEOUT):
"""단계 실행을 타임아웃으로 보호. 초과 시 취소하고 None 반환(루프는 계속)."""
try:
return await asyncio.wait_for(coro, timeout=timeout)
except asyncio.TimeoutError:
logger.error(
f"[DayTrading] ⏱️ '{step}' {timeout}초 초과 — 취소하고 다음 사이클로 진행 "
f"(KIS API 무응답 가능성)"
)
return None
# 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}개 포지션 복원됨")
# 전일 미청산 포지션은 기동 직후(장중이면) 즉시 청산 — EOD 누락 안전장치
try:
from app.services.daytrading.exit_service import close_stale_positions
stale = await close_stale_positions()
if stale:
logger.warning(f"[DayTrading] 기동 시 전일 포지션 {len(stale)}건 청산")
except Exception as e:
logger.error(f"[DayTrading] 기동 시 전일 포지션 청산 실패: {e}", exc_info=True)
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():
# [FIX 2026-09-23] 고정 1800초 sleep은 09:00 개장을 건너뛰어
# ORB 수집(09:00~09:30)을 통째로 놓칠 수 있다 → 개장까지 남은 시간만큼만 대기.
_until_open = seconds_until_market_open()
# 개장 3분 전이면 watchlist를 미리 채워 09:00부터 ORB 수집 가능
if _until_open is not None and _until_open <= 180 and not get_watchlist():
try:
count = await _guard(populate_daytrading_watchlist(), "watchlist 구성", 120)
if count:
logger.info(f"[DayTrading] 개장 전 watchlist 선구성: {count}개")
except Exception as e:
logger.warning(f"[DayTrading] 개장 전 watchlist 구성 실패: {e}")
_sleep = 1800.0 if _until_open is None else max(15.0, min(1800.0, _until_open))
await asyncio.sleep(_sleep)
continue
if not settings.DAY_TRADE_ENABLED:
await asyncio.sleep(60)
continue
# MDD 체크 (CLAUDE.md 5.3)
short_term_ok = await _guard(
mdd_manager.is_short_term_strategy_enabled(), "MDD 체크", 30
)
if short_term_ok is None:
short_term_ok = False # 판단 불가 → 보수적으로 신규 진입 차단
# EOD 강제 청산 (15:20)
if is_eod_flat_time():
if day_trading_state.positions:
exits = await _guard(
force_close_all(reason="EOD 강제 청산 (15:20)"), "EOD 강제청산", 300
)
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 _guard(collect_opening_ranges(), "ORB 수집", 300)
await asyncio.sleep(30)
continue
# 09:30~15:00 신호 스캔 + 청산 체크
if is_day_trade_entry_window():
global _last_wl_sync
wl = get_watchlist()
# 30분마다 갱신 (비어 있을 때만 → 항상): 09:00에 전일 분석으로 채운 목록을
# 당일 배치 완료 후 당일 분석 결과로 교체하기 위함 (ORB 캐시는 종목코드 기준 유지)
if not wl or (is_watchlist_auto() 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 _guard(check_and_exit_positions(), "청산 체크")
if exits:
logger.info(f"[DayTrading] 청산: {len(exits)}건")
# 진입 (MDD 허용 시만)
if short_term_ok:
entries = await _guard(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 _guard(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