하네스 규칙 검사 전역 위반 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>
167 lines
8.5 KiB
Python
167 lines
8.5 KiB
Python
"""감사 P2 수정 검증: 주문 멱등성 / shield / 다중행 / v2·수동매도 / 스윙 쿨다운."""
|
|
import asyncio
|
|
import inspect
|
|
from unittest.mock import AsyncMock, patch
|
|
|
|
import pytest
|
|
|
|
from app.services import trade_executor as te
|
|
from app.services.korea_investment_api import KoreaInvestmentAPI
|
|
|
|
|
|
def test_order_endpoints_not_retried_internally():
|
|
"""주문은 내부 재시도 금지 — 상위 재시도와 중첩되면 동일 주문이 최대 12회 전송된다."""
|
|
src = inspect.getsource(KoreaInvestmentAPI._make_request_with_retry)
|
|
assert "_max_retries = 0 if endpoint in self._NON_IDEMPOTENT_ENDPOINTS" in src
|
|
# 재시도 판단은 전부 _max_retries 기준이어야 한다 (원본 self.max_retries 사용 금지)
|
|
body = src.split("for attempt in range(_max_retries + 1):", 1)[1]
|
|
assert "self.max_retries" not in body, "재시도 루프 안에 원본 max_retries 잔존"
|
|
assert body.count("attempt < _max_retries") == 2 # 5xx/429 경로 + 타임아웃 경로
|
|
eps = KoreaInvestmentAPI._NON_IDEMPOTENT_ENDPOINTS
|
|
assert "/uapi/domestic-stock/v1/trading/order-cash" in eps
|
|
assert "/uapi/overseas-stock/v1/trading/order" in eps
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_retry_stops_when_order_already_accepted():
|
|
"""타임아웃 후 재시도 전에 접수된 주문을 발견하면 재주문하지 않는다."""
|
|
calls = {"n": 0}
|
|
|
|
async def _boom(*a, **k):
|
|
calls["n"] += 1
|
|
raise TimeoutError("no response")
|
|
|
|
dup = {"rt_cd": "0", "odno": "0000012345", "output": {"ODNO": "0000012345"}}
|
|
with patch.object(te.korea_investment_api, "place_order", _boom), \
|
|
patch.object(te, "_find_recent_order", AsyncMock(return_value=dup)):
|
|
out = await te._place_order_with_retry(
|
|
stock_code="005930", order_type="SELL", quantity=3, price=None, is_domestic=True,
|
|
)
|
|
assert out["odno"] == "0000012345"
|
|
assert calls["n"] == 1, "중복 확인 후에도 재주문이 나감"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_find_recent_order_matches_side_and_qty():
|
|
rows = [
|
|
{"pdno": "005930", "sll_buy_dvsn_cd": "01", "ord_qty": "3", "ord_tmd": "103000", "odno": "A1"},
|
|
{"pdno": "005930", "sll_buy_dvsn_cd": "02", "ord_qty": "3", "ord_tmd": "103000", "odno": "B1"},
|
|
]
|
|
from datetime import datetime as _dt
|
|
|
|
class _FakeDT(_dt):
|
|
@classmethod
|
|
def now(cls, tz=None):
|
|
return _dt(2026, 9, 23, 10, 30, 30)
|
|
|
|
with patch.object(te.korea_investment_api, "get_todays_orders", AsyncMock(return_value=rows)), \
|
|
patch.object(te, "datetime", _FakeDT):
|
|
sell = await te._find_recent_order("005930", "SELL", 3)
|
|
buy = await te._find_recent_order("005930", "BUY", 3)
|
|
none = await te._find_recent_order("005930", "SELL", 5)
|
|
assert sell["odno"] == "A1" # 01 = 매도
|
|
assert buy["odno"] == "B1" # 02 = 매수
|
|
assert none is None # 수량 불일치
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dt_exit_state_update_is_shielded():
|
|
"""DT 청산의 '체결 이후 상태 반영' 은 취소로부터 보호(asyncio.shield)되어야 한다.
|
|
|
|
과거 버그(P2 감사): 스케줄러 단계 타임아웃(_guard)이 매도 주문 직후를 취소하면
|
|
"브로커는 팔았는데 인메모리 포지션은 그대로" 가 되어 다음 사이클이 같은 물량을
|
|
다시 팔았다(미보유 매도/중복 매도).
|
|
|
|
[2026-09-27] `_execute_exit` 가 `_execute_exit_impl` 로 위임하고 shield 는
|
|
impl 안 2곳(`_finalize_exit` / `_finalize_exit_stale`)으로 이동 — 동작은 보존됐고
|
|
`_execute_exit` 본문만 보던 문자열 가드의 **검사 범위**가 어긋났다.
|
|
이제 문자열이 아니라 **동작**을 본다: 주문 체결 직후 태스크를 취소해도
|
|
finalize 가 끝까지 완주하는지 확인한다(shield 제거 시 반드시 실패).
|
|
"""
|
|
from app.services.daytrading import exit_service as es
|
|
|
|
finished: list = []
|
|
|
|
async def _fake_finalize(*args, **kwargs):
|
|
await asyncio.sleep(0.05) # 취소가 개입할 수 있는 지점
|
|
finished.append(True) # shield 가 있으면 여기까지 도달
|
|
return {"stock_code": "005930"}
|
|
|
|
with patch.object(es, "_finalize_exit", _fake_finalize), \
|
|
patch("app.services.trade_executor.safe_place_order",
|
|
AsyncMock(return_value={"rt_cd": "0", "output": {"ODNO": "1"}})):
|
|
# [L-8 2026-10-02] _execute_exit_impl 은 판정 시점의 포지션 객체가 인메모리에 그대로
|
|
# 있어야 주문한다 → 실제 호출부처럼 등록된 포지션을 넘긴다.
|
|
from app.services.daytrading.position_manager import day_trading_state as _dts
|
|
_p = {"quantity": 10}
|
|
_dts.positions["005930"] = _p
|
|
task = asyncio.create_task(
|
|
es._execute_exit("005930", _p, 1000.0, "테스트 청산")
|
|
)
|
|
await asyncio.sleep(0.01) # 주문 완료 후 finalize 진입까지 진행
|
|
task.cancel()
|
|
with pytest.raises(asyncio.CancelledError):
|
|
await task
|
|
await asyncio.sleep(0.1) # shield 된 내부 코루틴 완주 대기
|
|
|
|
_dts.positions.pop("005930", None)
|
|
_dts.exits_in_progress.discard("005930")
|
|
assert finished, "체결 후 상태 반영이 취소됐다 — shield 누락 (중복 매도 위험)"
|
|
|
|
# 상태 반영 구현(인메모리 제거 + DB 기록)이 유지되는지 — 위임 체인을 따라 확인
|
|
fin = inspect.getsource(es._finalize_exit)
|
|
if "_finalize_exit_impl" in fin:
|
|
fin += inspect.getsource(es._finalize_exit_impl)
|
|
assert "remove_position" in fin and "enqueue_trade_history" in fin
|
|
# [H4 2026-10-02] shield 범위가 '주문 전송 ~ 상태 반영' 전체로 넓어졌다
|
|
# (_execute_exit_impl → asyncio.shield(_place_and_finalize_exit_guarded_impl(...))
|
|
# → _place_and_finalize_exit_impl). [H-B] guarded 는 진행 중 표식 해제(finally)만 더한다.
|
|
impl = inspect.getsource(es._execute_exit_impl)
|
|
assert "asyncio.shield(_place_and_finalize_exit_guarded_impl(" in impl
|
|
guarded = inspect.getsource(es._place_and_finalize_exit_guarded_impl)
|
|
assert "_place_and_finalize_exit_impl(" in guarded and "finally:" in guarded
|
|
inner = inspect.getsource(es._place_and_finalize_exit_impl)
|
|
# [4회차] 접수 판정 후 반영은 _finalize_after_accept_impl 로 위임된다(불명 주문 확인 경로 공유).
|
|
after = inspect.getsource(es._finalize_after_accept_impl)
|
|
# 전일(stale) 청산 경로도 같은 shield 구간 안에서 반영된다
|
|
assert "_finalize_exit_stale(" in after and "_finalize_exit(" in after
|
|
# 상태 반영은 반드시 주문 접수 판정 '이후'(거부 시 상태 반영 금지)
|
|
_send = inner.index("safe_place_order(\n")
|
|
assert _send < inner.index('if outcome == "rejected":') < inner.rindex("_finalize_after_accept_impl(")
|
|
|
|
|
|
def test_swing_active_trade_lookup_handles_multiple_rows():
|
|
from app.services.swing import position_manager as pm
|
|
src = inspect.getsource(pm.get_swing_active_trade)
|
|
code = "\n".join(l for l in src.splitlines() if "#" not in l and '"""' not in l)
|
|
assert "scalar_one_or_none" not in code, "행 2개면 예외 → 손절 통째 스킵"
|
|
assert "order_by(ActiveTrade.id.desc())" in src and "scalars().first()" in src
|
|
|
|
|
|
def test_swing_exit_has_repeat_guard():
|
|
from app.services.swing import exit_service as se
|
|
assert se.EXIT_COOLDOWN_SEC >= 60
|
|
src = inspect.getsource(se.check_and_execute_exit_v2)
|
|
assert "_recent_exits" in src and "쿨다운" in src
|
|
|
|
|
|
def test_v2_sell_maps_strategy_name_and_updates_quantity():
|
|
from app.api.endpoints import portfolio_v2 as v2
|
|
src = inspect.getsource(v2.sell_stock_v2)
|
|
# [M-5 2026-10-02] 보유 행 strategy_type 하나로 매핑하던 방식(_AT_STRATEGY) →
|
|
# DT 우선 배분 + 전략명 필터(strategy_name_not / strategy_names) 로 대체.
|
|
assert "allocate_sell_v2(" in src and "sync_active_trade_after_manual_sell_v2(" in src
|
|
assert "max(0, original_holding_qty - quantity)" in src
|
|
assert "db.delete(" not in src and "db.commit()" not in src, "§3.2 직접 쓰기"
|
|
|
|
|
|
def test_manual_sell_uses_lock_and_updates_dt_state():
|
|
from app.api.endpoints import portfolio as pf
|
|
src = inspect.getsource(pf.sell_stock)
|
|
assert "safe_place_order(" in src, "락 없는 직접 주문"
|
|
# [M-5 2026-10-02] DT 인메모리 차감은 manual_sell_service 로 이관
|
|
assert "reflect_dt_after_manual_sell_v2(" in src
|
|
from app.services import manual_sell_service as mss
|
|
msrc = inspect.getsource(mss.reflect_dt_after_manual_sell_v2)
|
|
assert "day_trading_state" in msrc and "remove_position" in msrc
|