feat(safety-sell): dcy-010 BAT-014 — 영속 거부 재시도 쿨다운 (REQ-052~054)
dcy-010(safety-sell 영속 거부 재시도 백오프) 전체 SDLC: draft-req → confirm-req → draft-batch(BAT-014 batch-lite) → run-batch-delivery → confirm-req-implemented. 2026-06-07 실 KIS LIVE SL/TP e2e에서 발견한 KIS 주문 spam 위험(영속 거부 시 매도 무한 재제출) 차단. - REQ-052 (Integration): SafetySellService per-slot 인메모리 쿨다운 (_in_cooldown/_attempt_sell/_prune_cooldown) — forced_close·stop-loss·take-profit 트리거에 min_retry_interval_sec(600s) 이내 재시도 skip(가격 poll 포함) + max_retry_warn_count(3) 도달 시 WARNING + holding 이탈 정리. market_close 제외. - REQ-053 (Configuration): SafetySellConfig min_retry_interval_sec/max_retry_warn_count + TREX_SAFETY_SELL_MIN_RETRY_INTERVAL/MAX_RETRY_WARN_COUNT env (additive) - REQ-054 (Documentation): runtime-flows 쿨다운 flow + 가격체크 tr_id(FHKST01010100) 정정 인메모리 only(DB/스레드/인터페이스 변경 없음), default 미설정 시 기존 동작 불변. 검증: 신규 8 단위(쿨다운 6 + config 2), 전체 278 passed, ruff clean. REQ-052~054 Implemented, BAT-014 release-candidate. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -65,6 +65,9 @@ class SafetySellService:
|
||||
self._last_liquidation_date: date_cls | None = None
|
||||
self._last_forced_close_at: datetime | None = None
|
||||
self._last_price_check_at: datetime | None = None
|
||||
# BAT-014 / REQ-052: per-slot retry cooldown for persistent rejection.
|
||||
self._last_attempt: dict = {} # slot_id -> last sell-attempt datetime
|
||||
self._attempt_count: dict = {} # slot_id -> consecutive attempt count
|
||||
|
||||
@property
|
||||
def base_tick_sec(self) -> float:
|
||||
@@ -99,6 +102,38 @@ class SafetySellService:
|
||||
slot.slot_id, reason, exc_info=True)
|
||||
return False
|
||||
|
||||
# ------------------------------------------------ REQ-052 retry cooldown
|
||||
def _in_cooldown(self, slot_id, now: datetime) -> bool:
|
||||
"""True if the slot was attempted within min_retry_interval_sec (skip retry)."""
|
||||
last = self._last_attempt.get(slot_id)
|
||||
if last is None:
|
||||
return False
|
||||
return (now - last).total_seconds() < self._cfg.min_retry_interval_sec
|
||||
|
||||
def _attempt_sell(self, slot: Slot, reason: str, now: datetime) -> bool:
|
||||
"""Record a sell attempt (cooldown already cleared by caller) + warn on repeat.
|
||||
|
||||
Updates last_attempt/attempt_count regardless of success (dcy-010 FR-2).
|
||||
"""
|
||||
sid = slot.slot_id
|
||||
count = self._attempt_count.get(sid, 0) + 1
|
||||
if count >= self._cfg.max_retry_warn_count:
|
||||
_log.warning(
|
||||
"safety-sell repeated rejection: slot=%s count=%d reason=%s last_attempt_at=%s",
|
||||
sid, count, reason, self._last_attempt.get(sid),
|
||||
)
|
||||
self._last_attempt[sid] = now
|
||||
self._attempt_count[sid] = count
|
||||
return self._safe_sell(slot, reason)
|
||||
|
||||
def _prune_cooldown(self, now: datetime) -> None:
|
||||
"""Drop cooldown state for slots no longer holding (dcy-010 FR-4)."""
|
||||
holding_ids = {s.slot_id for s in self._holding(now)}
|
||||
for sid in list(self._last_attempt):
|
||||
if sid not in holding_ids:
|
||||
self._last_attempt.pop(sid, None)
|
||||
self._attempt_count.pop(sid, None)
|
||||
|
||||
def estimated_hourly_kis_calls(self, n_slots: int) -> int:
|
||||
"""REQ-038 AC-8: worst-case current-price polls per hour for n_slots."""
|
||||
interval = max(1, self._cfg.stop_loss_poll_interval_sec)
|
||||
@@ -115,7 +150,11 @@ class SafetySellService:
|
||||
continue
|
||||
if not self._watchdog_expired(s):
|
||||
continue # strategy module active — do not interfere (AC-3)
|
||||
if s.forced_close_at <= now and self._safe_sell(s, "forced_close_at"):
|
||||
if s.forced_close_at > now:
|
||||
continue
|
||||
if self._in_cooldown(s.slot_id, now):
|
||||
continue # REQ-052: persistent-rejection backoff
|
||||
if self._attempt_sell(s, "forced_close_at", now):
|
||||
fired.append(s.slot_id)
|
||||
return fired
|
||||
|
||||
@@ -138,14 +177,16 @@ class SafetySellService:
|
||||
)
|
||||
fired = []
|
||||
for s in candidates:
|
||||
if self._in_cooldown(s.slot_id, now):
|
||||
continue # REQ-052: skip KIS poll + retry during cooldown
|
||||
price = self._broker.get_current_price(s.symbol)
|
||||
if price is None:
|
||||
continue # unavailable — skip, retry next tick (no false trigger)
|
||||
if s.stop_loss_price is not None and price <= s.stop_loss_price:
|
||||
if self._safe_sell(s, "stop_loss"):
|
||||
if self._attempt_sell(s, "stop_loss", now):
|
||||
fired.append(s.slot_id)
|
||||
elif s.take_profit_price is not None and price >= s.take_profit_price:
|
||||
if self._safe_sell(s, "take_profit"):
|
||||
if self._attempt_sell(s, "take_profit", now):
|
||||
fired.append(s.slot_id)
|
||||
return fired
|
||||
|
||||
@@ -172,6 +213,7 @@ class SafetySellService:
|
||||
def run_once(self, now: datetime | None = None) -> None:
|
||||
"""One worker tick — market-close, then cadence-gated forced_close + prices."""
|
||||
now = now or datetime.now(tz=timezone.utc)
|
||||
self._prune_cooldown(now) # REQ-052 FR-4: drop state for non-holding slots
|
||||
try:
|
||||
self.check_market_close(now)
|
||||
except Exception: # noqa: BLE001
|
||||
|
||||
@@ -83,6 +83,9 @@ class SafetySellConfig:
|
||||
forced_close_check_interval_sec: int = 60
|
||||
stop_loss_poll_interval_sec: int = 30
|
||||
market_close_liquidation_time: Optional[str] = None # "HH:MM" KST, optional
|
||||
# BAT-014 / REQ-053: persistent-rejection retry cooldown (dcy-010).
|
||||
min_retry_interval_sec: int = 600 # per-slot cooldown between sell retries
|
||||
max_retry_warn_count: int = 3 # WARNING after this many consecutive retries
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -197,6 +200,12 @@ class DaemonConfig:
|
||||
os.environ.get("TREX_STOP_LOSS_POLL_INTERVAL", "30")
|
||||
),
|
||||
market_close_liquidation_time=_mc_time,
|
||||
min_retry_interval_sec=int(
|
||||
os.environ.get("TREX_SAFETY_SELL_MIN_RETRY_INTERVAL", "600")
|
||||
),
|
||||
max_retry_warn_count=int(
|
||||
os.environ.get("TREX_SAFETY_SELL_MAX_RETRY_WARN_COUNT", "3")
|
||||
),
|
||||
)
|
||||
return DaemonConfig(
|
||||
dsn=dsn,
|
||||
|
||||
Reference in New Issue
Block a user