fix: 하드닝 루프 9회차 — 매수 원복·잔고 연속조회·결과 불명 매도·브레이커·경보 보강

- 8회차 HIGH 수정 16건 레드팀 재검증: 12 확인·3 부분·1 미수정 → 전부 보강
- trade_executor/fill_sweep: 늦게 확정된 0체결 BUY → CANCELLED + ActiveTrade close, 부분체결 → 수량 축소(멱등, 재기동 후 TH 재구성)
- korea_investment_api: get_balance_all_v2(tr_cont 연속조회, _partial), get_todays_orders_v2(실패 None), 브레이커 청산용 조회 면제(OPEN 중 미집계)
- swing/exit_service·mdd_manager: 매도 직전 상한·MDD 축소가 전체 잔고 페이지 사용(§8.5-37), 불명 대기 중 부분익절 skip·쿨다운·pre_hldg 차감, 대기 TTL 15:30+재매수 폐기(대조 1회 선행)(§8.5-38 해소)
- swing/scheduler: 청산 TIMED_OUT/SKIPPED/in-flight 시 MDD 축소·진입 보류(예외는 진입만), 3사이클 연속 시 error+텔레그램
- daytrading: 결과 불명 매도 재판정 v3(주문조회 v2 None→보류, 등록 이후 일치 행→accepted, 원장≤0→보류), 재기동 복원 min(주문가능,보유), 잔고 조회 후 일일손실한도 재확인, 단독 실행 Redis 접속 제거
- main: 스트림 무수신 경보 v4(희망 구독 기준), 첫 하트비트 없음 stale(HB_FIRST_BEAT_GRACE_SEC)
- 운영: Jenkinsfile health_watch.py 디렉터리 잔존 복구, prod_smoke 사이드카 확인, config 키 12개 선언(동작 무변경)
- 진입가 v3(max(AT,PA))는 KIS 이동평균 평단 전제 오류로 레드팀 반증 → 폐기
- CLAUDE.md §3.2 ③-d, §8.5-37/38 갱신, §8.5-39~48 신규(Crisis 손절 소급 §8.5-39 는 사용자 결정 대기)
- 유닛 스위트 2781 passed / 0 failed (소켓 차단), 네트워크 시도 0건

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
2026-10-12 15:37:16 +09:00
parent 0feaa61bfc
commit d140055e64
60 changed files with 2853 additions and 50 deletions

View File

@@ -101,7 +101,7 @@ async def _sell(sell_pct=1.0, qty=10, remaining_pct=1.0):
@pytest.mark.asyncio
async def test_recent_swing_exit_blocks_recommendation_sell(env, monkeypatch):
"""exit_service 가 막 청산한 종목은 추천 경로가 같은 단계를 다시 팔지 않는다."""
monkeypatch.setattr(es, "_fetch_kis_holding_v2", _boom("_fetch_kis_holding_v2"))
monkeypatch.setattr(es, "_fetch_kis_holding_v3", _boom("_fetch_kis_holding_v2"))
es._recent_exits[CODE] = time.time() - 5
r = await _sell(0.5)
assert r["action"] == "SKIP" and r["reason"] == "recent_swing_exit_cooldown"
@@ -110,7 +110,7 @@ async def test_recent_swing_exit_blocks_recommendation_sell(env, monkeypatch):
@pytest.mark.asyncio
async def test_cooldown_expired_allows_sell(env, monkeypatch):
monkeypatch.setattr(es, "_fetch_kis_holding_v2", _kis(10, 10))
monkeypatch.setattr(es, "_fetch_kis_holding_v3", _kis(10, 10))
es._recent_exits[CODE] = time.time() - float(es.EXIT_COOLDOWN_SEC) - 1
r = await _sell(1.0)
assert r["action"] == "SELL" and env and env[-1]["quantity"] == 10
@@ -119,7 +119,7 @@ async def test_cooldown_expired_allows_sell(env, monkeypatch):
@pytest.mark.asyncio
async def test_successful_sell_marks_shared_cooldown(env, monkeypatch):
"""추천 경로 매도 접수 → exit_service 도 같은 쿨다운을 본다."""
monkeypatch.setattr(es, "_fetch_kis_holding_v2", _kis(10, 10))
monkeypatch.setattr(es, "_fetch_kis_holding_v3", _kis(10, 10))
before = time.time()
await _sell(1.0)
assert es._recent_exits.get(CODE, 0) >= before
@@ -128,7 +128,7 @@ async def test_successful_sell_marks_shared_cooldown(env, monkeypatch):
@pytest.mark.asyncio
async def test_rejected_sell_does_not_mark_cooldown(env, monkeypatch):
"""업무 거부(FAILED)는 체결이 없으므로 쿨다운에 기록하지 않는다(즉시 재시도 허용)."""
monkeypatch.setattr(es, "_fetch_kis_holding_v2", _kis(10, 10))
monkeypatch.setattr(es, "_fetch_kis_holding_v3", _kis(10, 10))
env.result = {"rt_cd": "1", "msg_cd": "APBK0000", "msg1": "거부"}
r = await _sell(1.0)
assert r.get("success") is False
@@ -142,7 +142,7 @@ async def test_kis_cap_limits_stale_portfolio_quantity(env, monkeypatch):
"""Portfolio 10주(낡음)인데 KIS 실보유 6주 중 DT 4주 → 스윙 매도는 2주까지만."""
from app.services.daytrading.position_manager import day_trading_state
day_trading_state.positions[CODE] = {"quantity": 4}
monkeypatch.setattr(es, "_fetch_kis_holding_v2", _kis(6, 6))
monkeypatch.setattr(es, "_fetch_kis_holding_v3", _kis(6, 6))
r = await _sell(1.0, qty=10)
assert r["action"] == "SELL"
assert env[-1]["quantity"] == 2, "KIS 실보유 − DT 를 넘는 수량이 주문됐다(DT 물량 과다매도)"
@@ -151,7 +151,7 @@ async def test_kis_cap_limits_stale_portfolio_quantity(env, monkeypatch):
@pytest.mark.asyncio
async def test_kis_cap_uses_orderable_quantity(env, monkeypatch):
"""대기 매도 주문분(주문가능 < 보유)은 다시 팔지 않는다."""
monkeypatch.setattr(es, "_fetch_kis_holding_v2", _kis(10, 3))
monkeypatch.setattr(es, "_fetch_kis_holding_v3", _kis(10, 3))
await _sell(1.0, qty=10)
assert env[-1]["quantity"] == 3
@@ -160,7 +160,7 @@ async def test_kis_cap_uses_orderable_quantity(env, monkeypatch):
async def test_kis_check_failure_holds_sell(env, monkeypatch):
async def _none(stock_code):
return None
monkeypatch.setattr(es, "_fetch_kis_holding_v2", _none)
monkeypatch.setattr(es, "_fetch_kis_holding_v3", _none)
r = await _sell(1.0)
assert r["action"] == "SKIP" and r["reason"] == "kis_holding_check_failed"
assert env == []
@@ -168,7 +168,7 @@ async def test_kis_check_failure_holds_sell(env, monkeypatch):
@pytest.mark.asyncio
async def test_kis_sellable_zero_no_order(env, monkeypatch):
monkeypatch.setattr(es, "_fetch_kis_holding_v2", _kis(0, 0))
monkeypatch.setattr(es, "_fetch_kis_holding_v3", _kis(0, 0))
r = await _sell(0.5)
assert r["action"] == "SKIP" and r["reason"] == "kis_sellable_zero"
assert env == []
@@ -177,7 +177,7 @@ async def test_kis_sellable_zero_no_order(env, monkeypatch):
@pytest.mark.asyncio
async def test_kis_cap_not_applied_when_holding_matches(env, monkeypatch):
"""정상 상태(장부=KIS)에서는 분할매도 수량이 바뀌지 않는다 — 원본 대비 50% = 5주."""
monkeypatch.setattr(es, "_fetch_kis_holding_v2", _kis(10, 10))
monkeypatch.setattr(es, "_fetch_kis_holding_v3", _kis(10, 10))
await _sell(0.5, qty=10)
assert env[-1]["quantity"] == 5