Files
auto-stock/backend/tests/test_kis_breaker_orders_r4.py
shuim d140055e64 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>
2026-10-12 15:37:16 +09:00

100 lines
3.5 KiB
Python

"""R4: KIS 서킷브레이커는 주문(청산 포함)을 차단하지 않고, 주문 실패는 조회 breaker 에 세지 않는다."""
import asyncio
import pytest
from app.services import korea_investment_api as kia
from app.services.utils import CircuitBreakerState
ORDER_EP = "/uapi/domestic-stock/v1/trading/order-cash"
# [9회차 D-2] inquire-price 는 청산 경로 조회라 게이트 면제됨 → 차단 예시는 비면제 조회(일봉)로
QUOTE_EP = "/uapi/domestic-stock/v1/quotations/inquire-daily-price"
class _Resp:
def __init__(self, status=200, body=None):
self.status_code, self._b, self.headers, self.text = status, body or {}, {}, ""
def json(self):
return self._b
class _Client:
def __init__(self, resp):
self.resp, self.calls = resp, 0
async def request(self, *a, **k):
self.calls += 1
return self.resp
def _api(monkeypatch, resp):
api = kia.KoreaInvestmentAPI.__new__(kia.KoreaInvestmentAPI)
api.circuit_breaker = kia.CircuitBreaker(failure_threshold=2, recovery_timeout=120)
api.monitor = kia.APICallMonitor()
api.semaphore = asyncio.Semaphore(2)
api._throttle_lock = asyncio.Lock()
api.last_request_time = None
api.min_request_interval = 0
api.max_retries = 0
api.retry_delay = 0
api.retry_backoff = 1
api.timeout = 1
api.app_key = api.app_secret = "x"
api.base_url = "http://x"
client = _Client(resp)
async def _tok(*a, **k):
return "tok"
async def _cl():
return client
monkeypatch.setattr(api, "_get_access_token", _tok, raising=False)
monkeypatch.setattr(api, "_get_http_client", _cl, raising=False)
return api, client
def _open(api):
for _ in range(api.circuit_breaker.failure_threshold):
api.circuit_breaker.record_failure()
assert api.circuit_breaker.state == CircuitBreakerState.OPEN
@pytest.mark.asyncio
async def test_order_not_blocked_when_breaker_open(monkeypatch):
api, client = _api(monkeypatch, _Resp(200, {"rt_cd": "0"}))
_open(api)
out, _ = await api._make_request("POST", ORDER_EP, "TTTC0801U")
assert out["rt_cd"] == "0" and client.calls == 1
with pytest.raises(Exception, match="Circuit breaker open"):
await api._make_request("GET", QUOTE_EP, "X")
assert client.calls == 1
@pytest.mark.asyncio
async def test_order_failures_do_not_trip_breaker(monkeypatch):
api, _ = _api(monkeypatch, _Resp(500, {"rt_cd": "1", "msg_cd": "EGW00201"}))
for _ in range(api.circuit_breaker.failure_threshold + 3):
await api._make_request("POST", ORDER_EP, "TTTC0801U")
assert api.circuit_breaker.state == CircuitBreakerState.CLOSED
assert api.circuit_breaker.failure_count == 0
@pytest.mark.asyncio
async def test_query_failures_still_trip_and_alert(monkeypatch):
sent = []
from app.services import telegram_notifier as tn
async def _warn(cat, msg):
sent.append(cat)
monkeypatch.setattr(tn.telegram_notifier, "notify_system_warning", _warn)
api, _ = _api(monkeypatch, _Resp(500, {}))
for _ in range(api.circuit_breaker.failure_threshold):
with pytest.raises(Exception):
await api._make_request("GET", QUOTE_EP, "X")
await asyncio.sleep(0)
assert api.circuit_breaker.state == CircuitBreakerState.OPEN
assert api.circuit_breaker.open_count == 1
assert sent == ["KIS_CIRCUIT_BREAKER"]
assert api.circuit_breaker.health()["open_count"] == 1
assert "korea_investment_api" in kia.get_kis_breaker_health_v2()