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:
149
backend/tests/test_swing_safety_20261002.py
Normal file
149
backend/tests/test_swing_safety_20261002.py
Normal file
@@ -0,0 +1,149 @@
|
||||
"""스윙 매수 안전장치 동작 회귀 테스트 (2026-10-02 3회차).
|
||||
|
||||
test_position_cap_hard_ceiling.py 가 "동작 검증은 test_swing_safety_20261002.py" 라고
|
||||
참조하던 파일이다(이전엔 존재하지 않았다). 소스 문자열이 아니라 `_execute_buy` 를
|
||||
실제로 호출해 다음을 확인한다.
|
||||
|
||||
1. 적응형 position_size 6~7%(Normal/Aggressive)는 MAX_POSITION_SIZE(4%)로 클램프된다.
|
||||
2. 4% 이하 모드(Crisis 1.5% 등, 단 진입 허용 시)는 적응형 값이 그대로 쓰인다.
|
||||
3. Crisis(max_daily_trades=0) → 주문 관문 도달 전 SKIP.
|
||||
4. 적응형 조회 예외 / None → fail-closed SKIP.
|
||||
|
||||
규약(CLAUDE.md §4.1): 주문 경로 목은 예외 발생형(_Reached, BaseException),
|
||||
공통 종단(_acquire_order_lock)에 건다. 기대값은 settings.* 참조.
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.config import settings
|
||||
from app.services import trade_executor
|
||||
|
||||
|
||||
class _Reached(BaseException):
|
||||
"""가드를 통과해 사이징 지점에 도달했다는 신호 (except Exception 에 삼켜지지 않음)."""
|
||||
|
||||
|
||||
class _Result:
|
||||
def __init__(self, rows=None):
|
||||
self._rows = list(rows or [])
|
||||
|
||||
def scalars(self):
|
||||
return self
|
||||
|
||||
def first(self):
|
||||
return self._rows[0] if self._rows else None
|
||||
|
||||
def all(self):
|
||||
return list(self._rows)
|
||||
|
||||
|
||||
class _FakeDB:
|
||||
async def execute(self, stmt):
|
||||
return _Result([])
|
||||
|
||||
async def commit(self):
|
||||
raise AssertionError("trade_executor 가 db.commit() 을 직접 호출했다 (§3.2 위반)")
|
||||
|
||||
|
||||
TOTAL = 100_000_000.0
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def _pipeline(monkeypatch):
|
||||
"""_execute_buy 의 사이징 직전까지 통과시키고, Kelly 호출 인자를 기록한 뒤 중단한다."""
|
||||
monkeypatch.setattr(trade_executor, "check_opening_range_volatility", AsyncMock(return_value=False))
|
||||
monkeypatch.setattr(trade_executor, "check_surge_prevention", AsyncMock(return_value={}))
|
||||
monkeypatch.setattr(trade_executor, "check_trend_filter", AsyncMock(return_value={}))
|
||||
monkeypatch.setattr(trade_executor, "_get_cached_account", lambda: (TOTAL, TOTAL))
|
||||
monkeypatch.setattr(trade_executor, "_get_cached_account_v2", lambda: (TOTAL, TOTAL))
|
||||
monkeypatch.setattr(trade_executor, "validate_correlation_filter", AsyncMock(return_value=(True, "ok")))
|
||||
monkeypatch.setattr(trade_executor, "calculate_cooldown_minutes", lambda *a, **k: 0)
|
||||
gate = AsyncMock(side_effect=_Reached("order gate reached"))
|
||||
monkeypatch.setattr(trade_executor, "_acquire_order_lock", gate)
|
||||
from app.services.daytrading.position_manager import day_trading_state
|
||||
monkeypatch.setattr(day_trading_state, "positions", {})
|
||||
|
||||
seen = {}
|
||||
|
||||
async def _kelly(db, stock_code, total_assets, available_cash, max_per_position=None, **kw):
|
||||
seen["max_per_position"] = max_per_position
|
||||
raise _Reached("sizing reached")
|
||||
|
||||
monkeypatch.setattr(trade_executor, "_calculate_kelly_position", _kelly)
|
||||
return SimpleNamespace(seen=seen, gate=gate)
|
||||
|
||||
|
||||
def _set_adaptive(monkeypatch, factory):
|
||||
import app.services.adaptive_strategy as _ad
|
||||
monkeypatch.setattr(_ad, "get_current_adaptive_params", factory)
|
||||
|
||||
|
||||
async def _call_buy():
|
||||
return await trade_executor._execute_buy(
|
||||
stock={"_regime_str": "bull"}, db=_FakeDB(), holding=None,
|
||||
current_price=10_000.0, signals=["x"], score_val=5.0, is_domestic=True,
|
||||
exchange_code="KRX", stock_code="005930", stock_name="테스트",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("mode,size", [("normal", 0.06), ("aggressive", 0.07)])
|
||||
async def test_adaptive_position_size_is_clamped_to_hard_ceiling(monkeypatch, _pipeline, mode, size):
|
||||
_set_adaptive(monkeypatch, lambda: SimpleNamespace(
|
||||
fallback_used=False, trading_mode=mode, max_daily_trades=10, position_size=size,
|
||||
))
|
||||
with pytest.raises(_Reached):
|
||||
await _call_buy()
|
||||
assert _pipeline.seen["max_per_position"] == pytest.approx(settings.MAX_POSITION_SIZE)
|
||||
assert _pipeline.seen["max_per_position"] < size
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_adaptive_position_size_below_ceiling_is_kept(monkeypatch, _pipeline):
|
||||
small = settings.MAX_POSITION_SIZE / 2
|
||||
_set_adaptive(monkeypatch, lambda: SimpleNamespace(
|
||||
fallback_used=False, trading_mode="defensive", max_daily_trades=5, position_size=small,
|
||||
))
|
||||
with pytest.raises(_Reached):
|
||||
await _call_buy()
|
||||
assert _pipeline.seen["max_per_position"] == pytest.approx(small)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_adaptive_position_size_garbage_falls_back_to_ceiling(monkeypatch, _pipeline):
|
||||
_set_adaptive(monkeypatch, lambda: SimpleNamespace(
|
||||
fallback_used=False, trading_mode="normal", max_daily_trades=5, position_size="abc",
|
||||
))
|
||||
with pytest.raises(_Reached):
|
||||
await _call_buy()
|
||||
assert _pipeline.seen["max_per_position"] == pytest.approx(settings.MAX_POSITION_SIZE)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_crisis_mode_blocks_before_sizing(monkeypatch, _pipeline):
|
||||
_set_adaptive(monkeypatch, lambda: SimpleNamespace(
|
||||
fallback_used=False, trading_mode="crisis", max_daily_trades=0, position_size=0.015,
|
||||
))
|
||||
res = await _call_buy()
|
||||
assert res["action"] == "SKIP" and res["reason"] == "adaptive_crisis_mode"
|
||||
assert "max_per_position" not in _pipeline.seen
|
||||
_pipeline.gate.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_adaptive_lookup_failure_is_fail_closed(monkeypatch, _pipeline):
|
||||
def _boom():
|
||||
raise RuntimeError("adaptive down")
|
||||
_set_adaptive(monkeypatch, _boom)
|
||||
res = await _call_buy()
|
||||
assert res["action"] == "SKIP" and res["reason"] == "adaptive_params_unavailable"
|
||||
_pipeline.gate.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_adaptive_none_is_fail_closed(monkeypatch, _pipeline):
|
||||
_set_adaptive(monkeypatch, lambda: None)
|
||||
res = await _call_buy()
|
||||
assert res["action"] == "SKIP" and res["reason"] == "adaptive_params_unavailable"
|
||||
Reference in New Issue
Block a user