- 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>
247 lines
10 KiB
Python
247 lines
10 KiB
Python
"""전일 미청산 데이트레이딩 포지션 안전장치.
|
|
|
|
2026-09-22: 14:38 진입한 LG씨엔에스가 15:20 EOD 청산을 타지 않고 익일까지 보유됨.
|
|
장중이면 전일 포지션을 즉시 전량 시장가 청산해야 한다.
|
|
"""
|
|
from datetime import datetime, timedelta
|
|
from types import SimpleNamespace
|
|
from unittest.mock import AsyncMock, patch
|
|
|
|
import pytest
|
|
|
|
from app.services.daytrading import exit_service as es
|
|
from app.services.daytrading.position_manager import day_trading_state
|
|
|
|
|
|
class LiveCallBlocked(AssertionError):
|
|
"""테스트가 실제 외부 I/O(KIS/DB)를 호출하려 한 경우 — 목킹 누락 신호."""
|
|
|
|
|
|
def _blocked(name):
|
|
async def _boom(*a, **k):
|
|
raise LiveCallBlocked(f"실호출 차단: {name} — 목킹이 누락되었습니다")
|
|
return _boom
|
|
|
|
|
|
class _EmptySession:
|
|
"""AsyncSessionLocal 대체 — SELECT 결과가 빈 목록인 세션(네트워크 없음)."""
|
|
|
|
async def __aenter__(self):
|
|
return self
|
|
|
|
async def __aexit__(self, *a):
|
|
return False
|
|
|
|
async def execute(self, *a, **k):
|
|
return SimpleNamespace(scalars=lambda: SimpleNamespace(all=lambda: []))
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _block_live_io():
|
|
"""KIS 실호출·DB 실접속 전면 차단.
|
|
|
|
close_stale_positions() 가 타는 외부 I/O 경로를 모두 막는다:
|
|
- trade_executor.safe_place_order (exit_service._execute_exit_impl 내부 지연 임포트)
|
|
- korea_investment_api.place_order / place_overseas_order / _get_access_token
|
|
- korea_investment_api.get_current_price / get_balance / 분봉 조회
|
|
- app.core.database.AsyncSessionLocal (ActiveTrade 조회)
|
|
개별 테스트는 필요한 항목만 중첩 patch 로 정상 응답으로 덮어쓴다.
|
|
"""
|
|
import app.services.trade_executor as te
|
|
|
|
api = es.korea_investment_api
|
|
patches = [
|
|
patch.object(te, "safe_place_order", _blocked("safe_place_order")),
|
|
patch.object(te, "safe_place_order_v2", _blocked("safe_place_order_v2")),
|
|
patch.object(api, "place_order", _blocked("place_order")),
|
|
patch.object(api, "place_overseas_order", _blocked("place_overseas_order")),
|
|
patch.object(api, "_get_access_token", _blocked("_get_access_token")),
|
|
patch.object(api, "_request_new_token", _blocked("_request_new_token")),
|
|
patch.object(api, "get_current_price", _blocked("get_current_price")),
|
|
patch.object(api, "get_balance", _blocked("get_balance")),
|
|
patch.object(api, "get_minute_chart", _blocked("get_minute_chart")),
|
|
patch.object(api, "get_minute_chart_full_day", _blocked("get_minute_chart_full_day")),
|
|
patch("app.core.database.AsyncSessionLocal", _EmptySession),
|
|
]
|
|
for p in patches:
|
|
p.start()
|
|
try:
|
|
yield
|
|
finally:
|
|
for p in reversed(patches):
|
|
p.stop()
|
|
|
|
|
|
def _pos(entry_dt):
|
|
return {
|
|
"stock_name": "LG씨엔에스", "strategy": "day_trade", "entry_price": 70800.0,
|
|
"stop_loss": 69000.0, "target_price": 73000.0, "quantity": 4,
|
|
"highest_price": 72200.0, "entry_time": entry_dt, "reason": "", "order_id": "",
|
|
}
|
|
|
|
|
|
def _impl_call(mock) -> dict:
|
|
"""_execute_exit_impl(stock_code, pos, price, reason, sell_pct, is_stale) 호출 인자 → dict."""
|
|
names = ["stock_code", "pos", "price", "reason", "sell_pct", "is_stale"]
|
|
d = dict(zip(names, mock.await_args.args))
|
|
d.update(mock.await_args.kwargs)
|
|
return d
|
|
|
|
|
|
def _holdings(code="064400", qty=4):
|
|
"""[H3] KIS 실보유 응답 — close_stale_positions 는 실보유 확인 없이는 매도하지 않는다."""
|
|
return AsyncMock(return_value={"output1": [{"pdno": code, "hldg_qty": str(qty)}], "output2": [{}]})
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _clean():
|
|
es._stale_sell_attempted.clear()
|
|
es._stale_sell_failures.clear()
|
|
es._last_exit_order_outcome.clear()
|
|
es._unresolved_exit_unknown.clear()
|
|
es._stale_cleaned.clear()
|
|
es._exit_tokens.clear()
|
|
day_trading_state.exits_in_progress.clear()
|
|
day_trading_state.positions = {}
|
|
# reset_if_new_day()가 포지션을 비우지 않도록 오늘로 맞춤
|
|
day_trading_state.last_reset_date = es._kst_now().date()
|
|
yield
|
|
day_trading_state.positions = {}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_stale_position_closed_in_full():
|
|
yesterday = es._kst_now() - timedelta(days=1)
|
|
day_trading_state.positions["064400"] = _pos(yesterday)
|
|
exec_mock = AsyncMock(return_value={"stock_code": "064400", "quantity": 4})
|
|
|
|
with patch.object(es, "is_market_open", return_value=True), \
|
|
patch.object(es.korea_investment_api, "get_balance", _holdings()), \
|
|
patch.object(es.korea_investment_api, "get_current_price",
|
|
AsyncMock(return_value={"output": {"stck_prpr": "71200"}})), \
|
|
patch.object(es, "_execute_exit_impl", exec_mock):
|
|
out = await es.close_stale_positions()
|
|
|
|
assert len(out) == 1
|
|
call = _impl_call(exec_mock)
|
|
assert call["sell_pct"] == 1.0 and "전일 미청산" in call["reason"]
|
|
assert call["is_stale"] is True # 전일 손익은 당일 집계 제외
|
|
assert call["price"] == 71200.0 # 현재가로 매도
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_today_position_untouched():
|
|
day_trading_state.positions["064400"] = _pos(es._kst_now())
|
|
exec_mock = AsyncMock()
|
|
with patch.object(es, "is_market_open", return_value=True), \
|
|
patch.object(es, "_execute_exit_impl", exec_mock):
|
|
assert await es.close_stale_positions() == []
|
|
exec_mock.assert_not_awaited()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_stale_position_found_from_db_after_midnight_reset():
|
|
"""자정 reset 으로 인메모리가 비어도 DB(ActiveTrade)에서 전일 포지션을 찾아 청산한다."""
|
|
from datetime import datetime as _dt
|
|
|
|
day_trading_state.positions = {}
|
|
row = SimpleNamespace(
|
|
stock_code="064400", stock_name="LG씨엔에스", entry_price=70800.0, quantity=4,
|
|
highest_since_entry=71200.0, created_at=_dt.now().replace(microsecond=0) - timedelta(days=1),
|
|
order_id="1", strategy_name="day_trade", status="active",
|
|
)
|
|
|
|
class _Result:
|
|
def scalars(self):
|
|
return SimpleNamespace(all=lambda: [row])
|
|
|
|
class _Empty:
|
|
def scalars(self):
|
|
return SimpleNamespace(all=lambda: [])
|
|
|
|
class _Sess:
|
|
"""1번째 SELECT = day_trade active 행, 2번째 SELECT(H3 비-DT 보유분) = 없음."""
|
|
calls = 0
|
|
async def __aenter__(self): return self
|
|
async def __aexit__(self, *a): return False
|
|
async def execute(self, *a, **k):
|
|
type(self).calls += 1
|
|
return _Result() if type(self).calls == 1 else _Empty()
|
|
|
|
exec_mock = AsyncMock(return_value={"stock_code": "064400", "quantity": 4})
|
|
with patch.object(es, "is_market_open", return_value=True), \
|
|
patch.object(es.korea_investment_api, "get_balance", _holdings()), \
|
|
patch("app.core.database.AsyncSessionLocal", _Sess), \
|
|
patch.object(es.korea_investment_api, "get_current_price",
|
|
AsyncMock(return_value={"output": {"stck_prpr": "70300"}})), \
|
|
patch.object(es, "_execute_exit_impl", exec_mock):
|
|
out = await es.close_stale_positions()
|
|
|
|
assert len(out) == 1
|
|
call = _impl_call(exec_mock)
|
|
assert call["pos"]["quantity"] == 4
|
|
assert call["sell_pct"] == 1.0
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_no_action_when_market_closed():
|
|
day_trading_state.positions["064400"] = _pos(es._kst_now() - timedelta(days=1))
|
|
exec_mock = AsyncMock()
|
|
with patch.object(es, "is_market_open", return_value=False), \
|
|
patch.object(es, "_execute_exit_impl", exec_mock):
|
|
assert await es.close_stale_positions() == []
|
|
exec_mock.assert_not_awaited()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_falls_back_to_entry_price_when_quote_fails():
|
|
day_trading_state.positions["064400"] = _pos(es._kst_now() - timedelta(days=1))
|
|
exec_mock = AsyncMock(return_value={"stock_code": "064400"})
|
|
with patch.object(es, "is_market_open", return_value=True), \
|
|
patch.object(es.korea_investment_api, "get_balance", _holdings()), \
|
|
patch.object(es.korea_investment_api, "get_current_price",
|
|
AsyncMock(side_effect=RuntimeError("quote down"))), \
|
|
patch.object(es, "_execute_exit_impl", exec_mock):
|
|
out = await es.close_stale_positions()
|
|
assert len(out) == 1
|
|
assert _impl_call(exec_mock)["price"] == 70800.0 # entry_price 폴백
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_exit_cycle_invokes_stale_guard():
|
|
"""청산 사이클이 개별 포지션 체크 전에 전일 포지션 안전장치를 호출한다."""
|
|
day_trading_state.positions["064400"] = _pos(es._kst_now() - timedelta(days=1))
|
|
order: list[str] = []
|
|
|
|
async def _guard():
|
|
order.append("guard")
|
|
day_trading_state.positions.pop("064400", None) # 청산 성공 가정
|
|
return [{"stock_code": "064400", "reason": "전일 미청산"}]
|
|
|
|
async def _single(code):
|
|
order.append(f"single:{code}")
|
|
return None
|
|
|
|
with patch.object(es, "is_eod_flat_time", return_value=False), \
|
|
patch.object(es, "is_daily_loss_exceeded", return_value=False), \
|
|
patch.object(es, "close_stale_positions", _guard), \
|
|
patch.object(es, "_check_single_position", _single):
|
|
out = await es.check_and_exit_positions()
|
|
|
|
assert order == ["guard"], f"안전장치가 먼저 실행되어야 함: {order}"
|
|
assert len(out) == 1 and out[0]["stock_code"] == "064400"
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _no_live_redis():
|
|
"""[C-4 r9] close_stale_positions → save_daily_state 가 app.core.redis 에 실접속하던 누수 차단.
|
|
|
|
단독 실행 시 앞선 파일의 Redis 목킹이 없어 localhost:6379 로 나가 4건이 실패했다(§4.1 순서 의존).
|
|
이 파일은 저장 호출 여부만 볼 뿐 값은 검증하지 않으므로 no-op 기록형으로 덮는다.
|
|
"""
|
|
import app.core.redis as _r
|
|
|
|
with patch.object(_r, "setex_json", AsyncMock(return_value=True)) as _set, \
|
|
patch.object(_r, "get_json", AsyncMock(return_value=None)) as _get:
|
|
yield SimpleNamespace(setex_json=_set, get_json=_get)
|