fix: 프로그램 검증 루프 7회차 — 리스크·주문·청산·인프라 결함 일괄 수정 + 거래 확대 결정 반영

하네스 규칙 검사 전역 위반 117→0, 회차별 검증(code-verifier opus 4도메인)으로 Critical/High 해소.

주문·리스크
- MDD 강제축소 반복 매도(종목별 완료 집합·재시도 상한·날짜 롤오버·잔고 오류 보류·epoch·장외 미주문)
- KIS 거부 FAILED 기록, 결과 불명(전송 후) 재전송 금지·PENDING, 미전송 실패만 재시도(msg_cd 분류)
- 국내 전량·손실 매도 시장가, 부분 익절 직전 현재가, 지정가만 미체결 취소(cancel_order_v2: TR 0013U·조직번호) + 0체결 롤백
- 누적 4%·현금·레버리지(신규분 포함)·사이클 내 매수 누적, 수동매수 공용 가드(buy_guards), 수동매도 DT 차감·락
- 가드 우회 엔드포인트 차단(/recommendations/auto-trade 위임, US /execute 매수 410·매도 가드)
- 매수 슬롯=성공 매수, 평가 상한·회전, 업무거부/계좌 쿨다운, 프로세스 내 in-flight 주문 중복 차단
데이트레이딩
- 진입·청산 shield, 청산 진행 중 표식(소유 토큰), 2단계 청산 체크, 결과 불명 → 보유 감소 판정·비DT 차감 상한
- 전일 포지션 재시도(일시 실패 미산정), 분할매도 영속, ORB 구간 손절, /cycle 락, 사이클 내 현금 차감, 체결 수량 보정
스윙
- 손절 공백(판정 예외 시 하드 바닥), 단일 손절 소스·범위 검증, 매도 직전 KIS 잔고 상한(min(주문가능,보유)−DT)
- 결과 불명 체결 대조·장부 반영, 대체가(나이·진입 이후·ATR 캐시), 분할 단계 기록, 국면 실패 fail-closed
- 듀얼 플레이북·서킷브레이커 게이트, 평균회귀 우선·듀얼 독립, 시간손절 거래일
- 거래 확대(사용자 결정, 백테스트 미검증): RSI 46/35 정본 경로, 모멘텀 v2 ON, SIDEWAYS ADX AND, 트레일링 1차 익절 후, 20일 시간손절 ON
인프라·보안
- 계좌·손익 GET 인증, 세션 is_active·관리자 경로, 서명키 파생, realip, WS 토큰 마스킹
- KIS 토큰 즉시 실패(sleep 제거)·무효 시 캐시 삭제, 주문 5xx+JSON 본문 반환
- db_worker 종료 drain(멱등 재실행·커밋 불명 격리·예산·밴 커밋), stop_grace 40s, Redis 타임아웃·volatile-lru, /health DLQ·캐시
- KRX 휴장일, py3.11 비호환 f-string 수정 + Jenkins 이미지 내 compileall·헬스 실패 시 빌드 실패
하네스: rules_check 에 PEP 701 f-string 검사, 마커(allow-*), deploy 스모크 401 기준
CLAUDE.md: 실제 동작·플래그·백로그(§8.5-27~38) 갱신

backend 1451 passed / hooks 112 passed / tsc ok / py3.9 compile 0 errors

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-02 12:01:31 +09:00
parent 0f89a9d678
commit 9fab4018d4
99 changed files with 15712 additions and 1718 deletions

View File

@@ -141,3 +141,157 @@ def schedule(
_pending_tasks.add(task)
task.add_done_callback(_pending_tasks.discard)
return task
# ── [M7 2026-10-02] 부분체결·미체결 판정용 v2 ─────────────────────────────────
# 기존 parse_fill_row/fetch_fill/schedule 은 **체결수량>0 인 첫 조회 결과**만 돌려줘
# (a) 체결 0 과 조회 실패를 구분하지 못하고 (b) 아직 체결 중인 부분체결도 확정으로 본다.
# 매수 쪽 수량 보정은 "주문이 종결됐다"는 근거가 있을 때만 해야 한다 — 미종결 부분체결을
# 수량으로 확정하면 나머지가 체결된 뒤 실보유 > 인메모리가 되어 EOD 청산 뒤 잔량이 남는다.
# 종결 판정: 체결수량 ≥ 주문수량, 또는 응답의 잔여수량(rmn_qty)=0(취소·거부 포함).
# rmn_qty 가 없는 응답에서 체결<주문이면 '미확정' 으로 남긴다(보정하지 않음, warning).
def parse_fill_row_v2(rows: list, order_id: str) -> Optional[dict]:
"""주문번호가 일치하는 행 → {filled_qty, avg_price, ord_qty, rmn_qty}. 없거나 파싱 불가면 None.
체결수량 0 행도 돌려준다(미체결·취소 판정용). ord_qty/rmn_qty 는 응답에 없으면 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
_oq = row.get("ord_qty")
ord_qty = int(float(_oq)) if _oq not in (None, "") else None
_rq = row.get("rmn_qty")
rmn_qty = int(float(_rq)) if _rq not in (None, "") else None
_jq = row.get("rjct_qty")
rjct_qty = int(float(_jq)) if _jq not in (None, "") else None
except (TypeError, ValueError):
return None
if qty > 0 and avg <= 0:
return None
cncl_yn = str(row.get("cncl_yn", "") or "").upper() or None
return {"filled_qty": max(0, qty), "avg_price": avg, "ord_qty": ord_qty,
"rmn_qty": rmn_qty, "cncl_yn": cncl_yn, "rjct_qty": rjct_qty}
return None
def is_terminal_fill(info: dict, ordered_qty: int) -> bool:
"""주문 종결 여부 — 전량 체결 / 잔여수량 0 / 취소(cncl_yn=Y) / 거부수량>0.
[Low 2026-10-02] 거부·취소 행은 응답에 따라 rmn_qty 가 비거나 0 이 아닐 수 있어
cncl_yn·rjct_qty 도 본다(체결 0주 종결 판정 누락 방지).
"""
filled = int(info.get("filled_qty", 0) or 0)
if ordered_qty > 0 and filled >= ordered_qty:
return True
if str(info.get("cncl_yn") or "").upper() == "Y":
return True
rj = info.get("rjct_qty")
rmn = info.get("rmn_qty")
if rj is not None and int(rj) > 0 and (rmn is None or int(rmn) <= 0):
return True
return rmn is not None and int(rmn) <= 0
async def _poll_fill_v2(stock_code: str, order_id: str, ordered_qty: int) -> Optional[dict]:
"""종결될 때까지(또는 시도 소진까지) 폴링. 마지막으로 본 행 정보를 돌려준다."""
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)))
last: Optional[dict] = None
for i in range(attempts):
rows = await korea_investment_api.get_todays_orders(stock_code)
info = parse_fill_row_v2(rows, order_id)
if info is not None:
last = info
if is_terminal_fill(info, ordered_qty):
return info
if i < attempts - 1:
await asyncio.sleep(interval)
return last
async def fetch_fill_v2(
stock_code: str, order_id: str, side: str, ordered_qty: int,
) -> Optional[dict]:
"""[M7] 주문 체결 상태. 조회 실패·시간초과·행 없음이면 None + warning.
반환 dict 에 `terminal`(bool) 이 추가된다.
"""
if not order_id:
logger.warning(f"[DTFill] {stock_code} {side}: 주문번호 없음 — 신호가 기록 유지")
return None
timeout = float(settings.DAY_TRADE_FILL_CHECK_TIMEOUT_SEC)
try:
info = await asyncio.wait_for(
_poll_fill_v2(stock_code, order_id, ordered_qty), 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 info is None:
logger.warning(
f"[DTFill] {stock_code} {side} 주문 행 미확인 "
f"({int(settings.DAY_TRADE_FILL_CHECK_ATTEMPTS)}회 조회) order_id={order_id} — 신호가 기록 유지"
)
return None
info = dict(info)
info["terminal"] = is_terminal_fill(info, ordered_qty)
return info
def schedule_v2(
stock_code: str,
order_id: str,
side: str,
ordered_qty: int,
on_result: Callable[[dict], Awaitable[None]],
) -> Optional[asyncio.Task]:
"""[M7] fetch_fill_v2 결과(체결 0·부분체결 포함)를 `on_result(info)` 로 넘긴다.
`DAY_TRADE_FILL_CHECK_ENABLED=False` 면 아무것도 하지 않는다(None).
"""
if not settings.DAY_TRADE_FILL_CHECK_ENABLED:
return None
async def _run() -> None:
info = await fetch_fill_v2(stock_code, order_id, side, ordered_qty)
if info is None:
return
try:
await on_result(info)
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