"""데이트레이딩 실제 체결가 확인 (백그라운드). [2026-10-01] DT 는 시장가 주문 후 신호 시점 가격(1분봉 종가)을 체결가로 기록했다. 실제 체결가와의 차이(슬리피지)가 원장·일일 손익·성과 통계에서 사라진다. 설계: - 주문 응답(KIS order-cash)에는 체결가가 없다 → 당일 주문체결 조회 (`korea_investment_api.get_todays_orders`, inquire-daily-ccld)에서 주문번호(ODNO)로 찾는다. `get_order_execution()` 은 쓰지 않는다 — 국내 경로가 같은 TR(TTTC8001R)을 `/trading/inquire-ccnl` 로 호출해(같은 TR 의 다른 메서드 `get_todays_orders` 는 `/trading/inquire-daily-ccld`) 경로가 어긋나 있을 가능성이 높고, 실패를 debug 로 삼켜 체결 0 과 구분되지 않는다(운영 확인 필요 — 보고 사항). - **실시간 루프를 막지 않는다**: `schedule()` 이 asyncio 태스크로 띄우고 즉시 반환. 전체를 `DAY_TRADE_FILL_CHECK_TIMEOUT_SEC` 로 감싼다 — KIS 토큰 rate-limit 의 `asyncio.sleep(≈70초)` 에 걸려도 상한에서 끊긴다. - DB I/O 없음. 반영은 호출부 콜백이 인메모리 + db_worker 큐로 한다(§3). - 확인 실패 시 None → 호출부는 신호가 기록을 유지하고 warning 을 남긴다. """ from __future__ import annotations import asyncio import logging from typing import Awaitable, Callable, Optional from app.core.config import settings from app.services.korea_investment_api import korea_investment_api logger = logging.getLogger(__name__) # create_task 결과의 강한 참조 — 참조가 없으면 GC 로 태스크가 중간에 사라질 수 있다. _pending_tasks: "set[asyncio.Task]" = set() def _norm_odno(value) -> str: """KIS 주문번호 정규화 — 응답(ODNO)은 0 패딩, 조회(odno)는 경우에 따라 다르다.""" s = str(value or "").strip() return s.lstrip("0") or ("0" if s else "") def parse_fill_row(rows: list, order_id: str) -> Optional[tuple[int, float]]: """inquire-daily-ccld output1 에서 주문번호가 일치하는 행의 (체결수량, 평균체결가). 체결수량 0 이거나 평균가를 구할 수 없으면 None. """ target = _norm_odno(order_id) if not target: return None for row in rows or []: if not isinstance(row, dict): continue if _norm_odno(row.get("odno")) != target: continue try: qty = int(float(row.get("tot_ccld_qty", 0) or 0)) avg = float(row.get("avg_prvs", 0) or 0) if avg <= 0 and qty > 0: amt = float(row.get("tot_ccld_amt", 0) or 0) avg = amt / qty if amt > 0 else 0.0 except (TypeError, ValueError): return None if qty > 0 and avg > 0: return qty, avg return None return None async def _poll_fill(stock_code: str, order_id: str) -> Optional[tuple[int, float]]: """체결 조회 폴링 (타임아웃은 호출부 wait_for 가 건다).""" attempts = max(1, int(settings.DAY_TRADE_FILL_CHECK_ATTEMPTS)) interval = max(0.0, float(settings.DAY_TRADE_FILL_CHECK_INTERVAL_SEC)) await asyncio.sleep(max(0.0, float(settings.DAY_TRADE_FILL_CHECK_DELAY_SEC))) for i in range(attempts): rows = await korea_investment_api.get_todays_orders(stock_code) fill = parse_fill_row(rows, order_id) if fill is not None: return fill if i < attempts - 1: await asyncio.sleep(interval) return None async def fetch_fill(stock_code: str, order_id: str, side: str) -> Optional[tuple[int, float]]: """주문번호의 실제 (체결수량, 평균체결가). 실패·시간초과·미체결이면 None + warning.""" if not order_id: logger.warning(f"[DTFill] {stock_code} {side}: 주문번호 없음 — 신호가 기록 유지") return None timeout = float(settings.DAY_TRADE_FILL_CHECK_TIMEOUT_SEC) try: fill = await asyncio.wait_for(_poll_fill(stock_code, order_id), timeout=timeout) except asyncio.TimeoutError: logger.warning( f"[DTFill] {stock_code} {side} 체결 조회 시간초과({timeout:.0f}초) " f"order_id={order_id} — 신호가 기록 유지" ) return None except Exception as e: logger.warning( f"[DTFill] {stock_code} {side} 체결 조회 실패 order_id={order_id}: " f"{type(e).__name__}: {e} — 신호가 기록 유지" ) return None if fill is None: logger.warning( f"[DTFill] {stock_code} {side} 체결 미확인 " f"({int(settings.DAY_TRADE_FILL_CHECK_ATTEMPTS)}회 조회) order_id={order_id} — 신호가 기록 유지" ) return fill def schedule( stock_code: str, order_id: str, side: str, on_fill: Callable[[int, float], Awaitable[None]], ) -> Optional[asyncio.Task]: """체결 확인을 백그라운드로 띄우고 즉시 반환. 확인되면 `on_fill(qty, avg_price)` 호출. `DAY_TRADE_FILL_CHECK_ENABLED=False` 면 아무것도 하지 않는다(None). """ if not settings.DAY_TRADE_FILL_CHECK_ENABLED: return None async def _run() -> None: fill = await fetch_fill(stock_code, order_id, side) if fill is None: return try: await on_fill(*fill) except Exception as e: logger.warning( f"[DTFill] {stock_code} {side} 체결가 반영 실패 order_id={order_id}: " f"{type(e).__name__}: {e}", exc_info=True, ) try: task = asyncio.get_running_loop().create_task(_run()) except RuntimeError as e: logger.warning(f"[DTFill] {stock_code} {side} 체결 확인 예약 실패: {e}") return None _pending_tasks.add(task) task.add_done_callback(_pending_tasks.discard) return task