- 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>
90 lines
3.3 KiB
Python
90 lines
3.3 KiB
Python
"""[R4 2026-10-09] MDD 축소 매도 TradeHistory 가 비용 차감 순손익 + commission + 수익률을 기록한다.
|
|
|
|
목킹 지점: 주문 종단 safe_place_order / 잔고 get_balance / 기록 종단 enqueue_trade_history(캡처).
|
|
"""
|
|
import pytest
|
|
|
|
from app.core.config import settings
|
|
from app.services import mdd_manager as mm
|
|
from app.services import trade_executor as te
|
|
from app.services.korea_investment_api import korea_investment_api
|
|
|
|
|
|
class _FakeRedis:
|
|
def __init__(self):
|
|
self.store = {}
|
|
|
|
async def set(self, k, v, **kw):
|
|
self.store[k] = v
|
|
return True
|
|
|
|
async def get(self, k):
|
|
return self.store.get(k)
|
|
|
|
|
|
def _expected(avg, cur, qty):
|
|
comm = settings.KR_COMMISSION_RATE
|
|
tax = settings.KR_SELL_TAX_RATE_KOSPI
|
|
cost = round(avg * qty * comm + cur * qty * comm + cur * qty * tax, 0)
|
|
gross = (cur - avg) * qty
|
|
return gross - cost, cost, (gross - cost) / (avg * qty) * 100
|
|
|
|
|
|
def test_helper_deducts_costs_settings_based():
|
|
r = mm._reduction_net_pnl_v2(10000.0, 10100.0, 30)
|
|
net, cost, rate = _expected(10000.0, 10100.0, 30)
|
|
assert r["net_profit_loss"] == pytest.approx(net)
|
|
assert r["commission"] == pytest.approx(cost)
|
|
assert r["profit_loss_rate"] == pytest.approx(rate)
|
|
assert r["net_profit_loss"] < (10100.0 - 10000.0) * 30 # gross 보다 작다
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_reduction_payload_has_net_pnl(monkeypatch):
|
|
import app.core.redis as redis_mod
|
|
monkeypatch.setattr(redis_mod, "get_redis", lambda: _FakeRedis())
|
|
|
|
async def _nosleep(*a, **k):
|
|
return None
|
|
monkeypatch.setattr(mm.asyncio, "sleep", _nosleep)
|
|
import app.core.market_schedule as _ms
|
|
monkeypatch.setattr(_ms, "is_market_open", lambda: True)
|
|
|
|
async def _noop(*a, **k):
|
|
return None
|
|
monkeypatch.setattr(mm, "_sync_active_trade_after_reduction", _noop)
|
|
monkeypatch.setattr(mm, "_reflect_reduction", _noop)
|
|
captured = []
|
|
|
|
async def _cap(payload):
|
|
captured.append(payload)
|
|
import app.services.db_worker as dbw
|
|
monkeypatch.setattr(dbw, "enqueue_trade_history", _cap)
|
|
|
|
async def _bal(*a, **k):
|
|
return {"rt_cd": "0", "output1": [
|
|
{"pdno": "005930", "prdt_name": "X", "hldg_qty": "100", "prpr": "10100",
|
|
"pchs_avg_pric": "10000"}]}
|
|
|
|
async def _order(stock_code, order_type, quantity, price=None, **kw):
|
|
return {"rt_cd": "0", "output": {"ODNO": "O1"}}
|
|
monkeypatch.setattr(korea_investment_api, "get_balance", _bal)
|
|
monkeypatch.setattr(korea_investment_api, "get_balance_all_v2", _bal) # [R9] 연속조회 목 보정 — 같은 목을 공유
|
|
monkeypatch.setattr(te, "safe_place_order", _order)
|
|
|
|
# 알림 fire-and-forget 태스크가 다른 테스트 루프로 새지 않게 차단
|
|
monkeypatch.setattr(mm.MDDManager, "_spawn_mdd_alert_v2", staticmethod(lambda *a, **k: None))
|
|
m = mm.MDDManager()
|
|
await m.update(100.0)
|
|
await m.update(89.0)
|
|
await m.execute_reduction(
|
|
{"action": "REDUCE_AND_PAUSE", "reduce_pct": 0.30, "prioritize_leverage": False}
|
|
)
|
|
assert len(captured) == 1
|
|
p = captured[0]
|
|
net, cost, rate = _expected(10000.0, 10100.0, 30)
|
|
assert p["net_profit_loss"] == pytest.approx(net)
|
|
assert p["commission"] == pytest.approx(cost)
|
|
assert p["profit_loss_rate"] == pytest.approx(rate)
|
|
assert p["strategy_type"] == "mdd_reduction"
|