- 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>
192 lines
8.8 KiB
Python
192 lines
8.8 KiB
Python
"""스윙 6회차 — 대체가 손절의 고변동 판정(H-1)·연속 skip 경보(M-4)·로그 없는 except(Low).
|
|
|
|
H-1 재현: 고변동 종목(ATR/종가 > 3%)이 -8% 일 때 실시세 주기에는 고변동 손절(-10%)이라 보유,
|
|
시세 조회 1회 실패(대체가) 주기에는 일봉 미조회 → ATR None → 일반 손절(-7%)로 시장가 오손절.
|
|
수정: 직전 정상 지표 경로의 ATR 을 캐시해 대체가 판정에 쓰고, 없으면 가장 느슨한 손절률.
|
|
"""
|
|
import logging
|
|
import time
|
|
from datetime import timedelta
|
|
from types import SimpleNamespace
|
|
from unittest.mock import AsyncMock, MagicMock
|
|
|
|
import pytest
|
|
|
|
import app.services.mean_reversion_strategy as mr
|
|
from app.core.config import settings
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _reset(monkeypatch):
|
|
import app.services.swing.exit_service as es
|
|
for name in ("_pending_unknown_sells", "_last_live_prices", "_last_atr",
|
|
"_presell_check_failures", "_no_price_skips"):
|
|
monkeypatch.setattr(es, name, {})
|
|
from app.core import log_throttle
|
|
log_throttle.reset_for_tests()
|
|
import app.services.adaptive_strategy as ad
|
|
monkeypatch.setattr(ad, "get_current_adaptive_params", lambda: SimpleNamespace(fallback_used=True))
|
|
monkeypatch.setattr(mr.strategy_cfg, "get", lambda k, d=None: None)
|
|
|
|
|
|
def _env(monkeypatch, *, avg=10000, price, prices, high_vol=True, holding_updated_ago=30):
|
|
"""prices: get_current_price 응답 순서(Exception 이면 조회 실패)."""
|
|
import app.services.swing.exit_service as es
|
|
import app.services.trade_executor as te
|
|
from app.core.timeutil import now_kst
|
|
holding = SimpleNamespace(stock_code="005930", stock_name="T", quantity=10, average_price=avg,
|
|
current_price=price, market="KRX",
|
|
updated_at=now_kst() - timedelta(seconds=holding_updated_ago))
|
|
monkeypatch.setattr(es, "get_swing_holdings", AsyncMock(return_value=[holding]))
|
|
monkeypatch.setattr(es, "check_market_regime", AsyncMock(return_value={"regime_200d": "bull"}))
|
|
at = SimpleNamespace(strategy_name="swing", remaining_pct=1.0, highest_since_entry=None,
|
|
created_at=now_kst() - timedelta(days=2), entry_reason=None)
|
|
monkeypatch.setattr(es, "get_swing_active_trade", AsyncMock(return_value=at))
|
|
api = MagicMock()
|
|
rng = 250 if high_vol else 40 # 고변동: ATR≈500(>3%)
|
|
bars = [{"stck_clpr": str(price + 100 + (i % 3) * 50), "stck_hgpr": str(price + 100 + rng + (i % 3) * 50),
|
|
"stck_lwpr": str(price + 100 - rng + (i % 3) * 50)} for i in range(30)]
|
|
api.get_daily_chart = AsyncMock(return_value={"output2": bars})
|
|
queue = list(prices)
|
|
|
|
async def _gcp(code):
|
|
p = queue.pop(0) if queue else RuntimeError("no more")
|
|
if isinstance(p, Exception):
|
|
raise p
|
|
return {"output": {"stck_prpr": str(p)}}
|
|
api.get_current_price = _gcp
|
|
api.get_balance = AsyncMock(return_value={"rt_cd": "0", "output1": [
|
|
{"pdno": "005930", "hldg_qty": "10", "ord_psbl_qty": "10"}]})
|
|
api.get_balance_all_v2 = api.get_balance # [R9] 연속조회 목 보정 — 같은 목을 공유
|
|
monkeypatch.setattr(es, "korea_investment_api", api)
|
|
from app.services.daytrading.position_manager import day_trading_state
|
|
monkeypatch.setattr(day_trading_state, "positions", {})
|
|
orders = []
|
|
|
|
async def _spo(**kw):
|
|
orders.append(kw["quantity"])
|
|
return {"rt_cd": "1", "msg_cd": "X", "msg1": "stop here"}
|
|
monkeypatch.setattr(te, "safe_place_order", _spo)
|
|
return es, orders
|
|
|
|
|
|
async def _cycle(es):
|
|
es._recent_exits.clear()
|
|
await es.check_and_execute_exit_v2(MagicMock())
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_h1_high_vol_stale_quote_uses_cached_atr(monkeypatch):
|
|
"""[재현 반전] 실시세 주기 보유(-8%, 고변동) → 시세 실패 주기에도 보유(이전: -7% 오손절)."""
|
|
es, orders = _env(monkeypatch, price=9200, prices=[9200, RuntimeError("EGW00201")])
|
|
await _cycle(es)
|
|
assert orders == []
|
|
assert "005930" in es._last_atr
|
|
await _cycle(es)
|
|
assert orders == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_h1_stale_without_atr_uses_loosest_stop(monkeypatch):
|
|
loosest = -max(abs(settings.STOP_LOSS_PERCENT), abs(settings.STOP_LOSS_HIGH_VOL))
|
|
tight = -min(abs(settings.STOP_LOSS_PERCENT), abs(settings.STOP_LOSS_HIGH_VOL))
|
|
between = int(10000 * (1 + (tight + loosest) / 2 / 100)) # 타이트 손절 초과·느슨 손절 미만
|
|
es, orders = _env(monkeypatch, price=between, prices=[RuntimeError("down")])
|
|
await _cycle(es)
|
|
assert orders == []
|
|
beyond = int(10000 * (1 + (loosest - 1) / 100))
|
|
es2, orders2 = _env(monkeypatch, price=beyond, prices=[RuntimeError("down")])
|
|
await _cycle(es2)
|
|
assert orders2 == [10]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_h1_cached_low_vol_atr_keeps_normal_stop(monkeypatch):
|
|
"""캐시된 ATR 이 저변동이면 일반 손절률 그대로(완화는 ATR 을 모를 때만)."""
|
|
floor = -abs(settings.STOP_LOSS_PERCENT)
|
|
below = int(10000 * (1 + (floor - 1) / 100))
|
|
es, orders = _env(monkeypatch, price=below, prices=[RuntimeError("down")])
|
|
from app.core.timeutil import now_kst
|
|
es._last_atr["005930"] = (below * 0.01, time.monotonic(), now_kst()) # ATR 1%
|
|
await _cycle(es)
|
|
assert orders == [10]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_h1_expired_or_pre_entry_atr_ignored(monkeypatch):
|
|
floor = -abs(settings.STOP_LOSS_PERCENT)
|
|
below = int(10000 * (1 + (floor - 1) / 100)) # 일반 손절 초과, 느슨 손절 미만
|
|
from app.core.timeutil import now_kst
|
|
age = float(settings.SWING_FALLBACK_PRICE_MAX_AGE_SEC) + 60
|
|
es, orders = _env(monkeypatch, price=below, prices=[RuntimeError("down")])
|
|
es._last_atr["005930"] = (below * 0.01, time.monotonic() - age, now_kst() - timedelta(seconds=age))
|
|
await _cycle(es)
|
|
assert orders == [] # 만료된 저변동 ATR 무시 → 느슨한 손절
|
|
es2, orders2 = _env(monkeypatch, price=below, prices=[RuntimeError("down")])
|
|
es2._last_atr["005930"] = (below * 0.01, time.monotonic(), now_kst() - timedelta(days=5)) # 진입 이전
|
|
await _cycle(es2)
|
|
assert orders2 == []
|
|
|
|
|
|
def test_stale_fallback_stop_pct_v2_resolver_failure_floor(monkeypatch):
|
|
import app.services.swing.exit_service as es
|
|
|
|
def _boom(*a, **k):
|
|
raise RuntimeError("x")
|
|
monkeypatch.setattr(mr, "resolve_swing_stop_params_v2", _boom)
|
|
assert es._stale_fallback_stop_pct_v2("005930", 10000.0, None) == -max(
|
|
abs(settings.STOP_LOSS_PERCENT), abs(settings.STOP_LOSS_HIGH_VOL))
|
|
|
|
|
|
# ── M-4 연속 skip 경보 ────────────────────────────────────────────────────
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_m4_no_price_skip_alerts_per_stock(monkeypatch):
|
|
n = int(settings.SWING_FALLBACK_SKIP_ALERT_AFTER)
|
|
age = float(settings.SWING_FALLBACK_PRICE_MAX_AGE_SEC) + 60
|
|
es, orders = _env(monkeypatch, price=8000, prices=[RuntimeError("down")] * (n + 1),
|
|
holding_updated_ago=age)
|
|
import app.services.telegram_notifier as tn
|
|
notify = AsyncMock()
|
|
monkeypatch.setattr(tn.telegram_notifier, "notify_system_warning", notify)
|
|
for _ in range(n - 1):
|
|
await _cycle(es)
|
|
notify.assert_not_awaited()
|
|
await _cycle(es)
|
|
notify.assert_awaited_once()
|
|
assert "005930" in notify.await_args.args[1]
|
|
assert orders == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_m4_skip_counter_resets_on_live_price(monkeypatch):
|
|
age = float(settings.SWING_FALLBACK_PRICE_MAX_AGE_SEC) + 60
|
|
es, _ = _env(monkeypatch, price=10000, prices=[RuntimeError("down"), 10000],
|
|
holding_updated_ago=age)
|
|
await _cycle(es)
|
|
assert es._no_price_skips.get("005930") == 1
|
|
await _cycle(es)
|
|
assert "005930" not in es._no_price_skips
|
|
|
|
|
|
# ── Low: 로그 없는 except → warning ───────────────────────────────────────
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_low_regime_and_dt_lookup_failures_warn(monkeypatch, caplog):
|
|
es, _ = _env(monkeypatch, price=10000, prices=[10000])
|
|
monkeypatch.setattr(es, "check_market_regime", AsyncMock(side_effect=RuntimeError("regime")))
|
|
from app.services.daytrading.position_manager import day_trading_state
|
|
|
|
class _Boom:
|
|
def get(self, *a):
|
|
raise RuntimeError("dt state")
|
|
monkeypatch.setattr(day_trading_state, "positions", _Boom())
|
|
with caplog.at_level(logging.WARNING, logger=es.logger.name):
|
|
await _cycle(es)
|
|
msgs = [r.getMessage() for r in caplog.records if r.levelno >= logging.WARNING]
|
|
assert any("시장 국면 조회 실패" in m for m in msgs)
|
|
assert any("DT 보유분 조회 실패" in m for m in msgs)
|
|
|
|
|
|
from _swing_redis_guard import _swing_redis_guard # noqa: E402,F401 (R9: 단독 실행 시 Redis 실접속 방지)
|