feat: 전일 미청산 데이트레이딩 포지션 즉시 청산 안전장치
15:20 EOD 강제청산이 누락/실패하면 포지션이 하룻밤 갭 리스크에 노출된 채 다음 날 일반 청산 로직을 탄다(2026-09-22 LG씨엔에스 7주 → 익일 09:30 분할매도). - exit_service.close_stale_positions(): 진입일이 오늘이 아닌 포지션을 장중 시장가 전량 청산, 현재가 조회 실패 시 진입가 폴백, 실패 시 다음 30초 사이클에서 재시도 - 청산 사이클(check_and_exit_positions) 및 스케줄러 기동 직후 양쪽에서 호출 - 테스트 5건, CLAUDE.md §7.3 반영 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -25,7 +25,7 @@ from datetime import datetime
|
||||
|
||||
import pytz
|
||||
|
||||
from app.core.market_schedule import is_eod_flat_time
|
||||
from app.core.market_schedule import is_eod_flat_time, is_market_open
|
||||
from app.services.korea_investment_api import korea_investment_api
|
||||
from app.services.day_trading_strategy import (
|
||||
parse_minute_candles, aggregate_to_5min,
|
||||
@@ -94,6 +94,15 @@ async def check_and_exit_positions() -> list[dict]:
|
||||
logger.info("[DayExit] EOD (15:20) → 전체 강제 청산")
|
||||
return await force_close_all(reason="EOD 강제 청산")
|
||||
|
||||
# [안전장치 2026-09-23] 전일 미청산 포지션 즉시 청산.
|
||||
# 데이트레이딩은 당일 청산이 원칙인데 15:20 EOD가 실패/누락되면(2026-09-22 LG씨엔에스)
|
||||
# 포지션이 하룻밤 갭 리스크에 노출된 채 다음 날 일반 청산 로직을 타게 된다.
|
||||
stale_exits = await close_stale_positions()
|
||||
if stale_exits:
|
||||
exits.extend(stale_exits)
|
||||
if not day_trading_state.positions:
|
||||
return exits
|
||||
|
||||
# 개별 포지션 청산 체크
|
||||
codes_snapshot = list(day_trading_state.positions.keys())
|
||||
for stock_code in codes_snapshot:
|
||||
@@ -297,6 +306,59 @@ async def _execute_exit(
|
||||
}
|
||||
|
||||
|
||||
async def close_stale_positions() -> list[dict]:
|
||||
"""진입일이 오늘이 아닌(전일 미청산) 데이트레이딩 포지션을 시장가 전량 청산.
|
||||
|
||||
EOD(15:20) 강제청산이 실패하거나 스케줄러가 그 구간을 놓친 경우의 안전장치.
|
||||
장중에만 동작하며(시장가 주문 필요), 청산 실패 시 다음 사이클에서 재시도된다.
|
||||
|
||||
Returns:
|
||||
list[dict]: 청산 실행 결과 목록
|
||||
"""
|
||||
if not is_market_open():
|
||||
return []
|
||||
|
||||
today = _kst_now().date()
|
||||
results: list[dict] = []
|
||||
|
||||
for stock_code in list(day_trading_state.positions.keys()):
|
||||
pos = day_trading_state.get_position(stock_code)
|
||||
if not pos:
|
||||
continue
|
||||
entry_time = pos.get("entry_time")
|
||||
if entry_time is None:
|
||||
continue
|
||||
entry_date = entry_time.date() if hasattr(entry_time, "date") else None
|
||||
if entry_date is None or entry_date >= today:
|
||||
continue
|
||||
|
||||
price = 0.0
|
||||
try:
|
||||
price_resp = await korea_investment_api.get_current_price(stock_code)
|
||||
price = float(price_resp.get("output", {}).get("stck_prpr", 0) or 0) if price_resp else 0.0
|
||||
except Exception as e:
|
||||
logger.warning(f"[DayExit] 전일 포지션 현재가 조회 실패 ({stock_code}): {e}")
|
||||
if price <= 0:
|
||||
price = float(pos.get("entry_price", 0) or 0)
|
||||
if price <= 0:
|
||||
continue
|
||||
|
||||
logger.warning(
|
||||
f"[DayExit] ⚠️ 전일 미청산 포지션 즉시 청산: {stock_code} "
|
||||
f"(진입일={entry_date}, 수량={pos.get('quantity')})"
|
||||
)
|
||||
result = await _execute_exit(
|
||||
stock_code, pos, price,
|
||||
reason=f"전일 미청산 포지션 강제 청산 (진입일 {entry_date}, EOD 누락)",
|
||||
sell_pct=1.0,
|
||||
)
|
||||
if result:
|
||||
results.append(result)
|
||||
await asyncio.sleep(0.3) # KIS 레이트 리밋
|
||||
|
||||
return results
|
||||
|
||||
|
||||
async def force_close_all(reason: str = "강제 청산") -> list[dict]:
|
||||
"""모든 데이트레이딩 포지션 강제 청산.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user