Files
trex-core/trex_core/application/safety_sell.py
T
genichinandClaude Opus 4.8 565af6792c 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>
2026-06-08 00:35:11 +09:00

233 lines
10 KiB
Python

"""Safety-sell trigger service (REQ-037, REQ-038, REQ-039 / BAT-011).
A single service that the `trex-safety-sell` daemon worker drives once per
tick. It evaluates three autonomous sell triggers on `holding` slots:
- forced_close_at expiry (REQ-037) — watchdog-gated
- stop-loss / take-profit price (REQ-038) — watchdog-gated, KIS polling
- market-close liquidation (REQ-039) — watchdog-INDEPENDENT, once/day
Watchdog gating: forced_close and price checks only act on slots whose
watchdog has expired (strategy module is absent). During the grace period
no expiry-gated trigger fires (REQ-034). Market-close liquidation ignores
the watchdog and the grace period entirely (REQ-039 AC-2/AC-6).
All sells go through `SlotService.sell()` (REQ-036), which is idempotent on
`pending_sell` — so concurrent/duplicate triggers never double-submit.
Each trigger is exception-isolated: a single slot's failure (KIS error,
transition race) is logged and the loop continues (REQ-024 degrade policy).
"""
from __future__ import annotations
import logging
from datetime import date as date_cls
from datetime import datetime, time as time_cls, timedelta, timezone
from trex_core.application.broker_port import BrokerPort
from trex_core.application.watchdog import WatchdogStore
from trex_core.domain.slot import SlotRepository, SlotService, SlotState
from trex_core.domain.slot.models import Slot
from trex_core.runtime.config import SafetySellConfig
_log = logging.getLogger(__name__)
_KST = timezone(timedelta(hours=9))
# Conservative KIS current-price quota guard (REQ-038 AC-8). When the
# estimated hourly polling volume crosses this, we log a warning so the
# operator can widen TREX_STOP_LOSS_POLL_INTERVAL.
_KIS_PRICE_QUOTA_PER_HOUR = 1000
_ACTOR = "trex-safety-sell"
def _parse_kst_time(spec: str) -> time_cls:
parts = spec.split(":")
return time_cls(hour=int(parts[0]), minute=int(parts[1]) if len(parts) > 1 else 0)
class SafetySellService:
"""Evaluates safety-sell triggers for one daemon tick (REQ-037/038/039)."""
def __init__(
self,
*,
slot_repo: SlotRepository,
slot_service: SlotService,
broker: BrokerPort,
watchdog: WatchdogStore,
config: SafetySellConfig,
) -> None:
self._repo = slot_repo
self._svc = slot_service
self._broker = broker
self._watchdog = watchdog
self._cfg = config
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:
"""Worker loop sleep — the finest of the configured check cadences."""
return float(max(
1,
min(self._cfg.forced_close_check_interval_sec,
self._cfg.stop_loss_poll_interval_sec),
))
# ---------------------------------------------------------------- helpers
@staticmethod
def _trading_date(now: datetime) -> date_cls:
return now.astimezone(timezone.utc).date()
def _holding(self, now: datetime) -> list[Slot]:
return [s for s in self._repo.list_slots(self._trading_date(now))
if s.status is SlotState.HOLDING]
def _watchdog_expired(self, slot: Slot) -> bool:
return self._watchdog.is_expired(str(slot.slot_id), self._cfg.watchdog_timeout_sec)
def _in_grace(self) -> bool:
return self._watchdog.in_grace_period(self._cfg.watchdog_grace_period_sec)
def _safe_sell(self, slot: Slot, reason: str) -> bool:
try:
self._svc.sell(slot.slot_id, actor=_ACTOR, reason=reason)
return True
except Exception: # noqa: BLE001 - one slot's failure must not stop the loop
_log.warning("safety-sell failed (slot=%s reason=%s)",
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)
return n_slots * (3600 // interval)
# ---------------------------------------------------- REQ-037 forced_close
def check_forced_close(self, now: datetime) -> list:
"""Sell holding+watchdog-expired slots whose forced_close_at has passed."""
if self._in_grace():
return []
fired = []
for s in self._holding(now):
if s.forced_close_at is None:
continue
if not self._watchdog_expired(s):
continue # strategy module active — do not interfere (AC-3)
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
# ----------------------------------------------- REQ-038 stop-loss/take-profit
def check_prices(self, now: datetime) -> list:
"""Poll KIS current price for eligible slots and trigger SL/TP sells."""
if self._in_grace():
return []
candidates = [
s for s in self._holding(now)
if (s.stop_loss_price is not None or s.take_profit_price is not None)
and self._watchdog_expired(s) # no KIS call for watchdog-active (AC-4)
]
if self.estimated_hourly_kis_calls(len(candidates)) > _KIS_PRICE_QUOTA_PER_HOUR:
_log.warning(
"safety-sell KIS price polling may exceed quota: ~%d calls/hour "
"(%d slots, interval=%ds). Consider widening TREX_STOP_LOSS_POLL_INTERVAL.",
self.estimated_hourly_kis_calls(len(candidates)),
len(candidates), self._cfg.stop_loss_poll_interval_sec,
)
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._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._attempt_sell(s, "take_profit", now):
fired.append(s.slot_id)
return fired
# ------------------------------------------------ REQ-039 market-close liquidation
def check_market_close(self, now: datetime) -> list:
"""Liquidate ALL holding slots at the configured KST time, once per day."""
spec = self._cfg.market_close_liquidation_time
if not spec:
return [] # feature disabled (AC-3)
now_kst = now.astimezone(_KST)
today = now_kst.date()
if self._last_liquidation_date == today:
return [] # already fired this trading day (AC-4)
if now_kst.time() < _parse_kst_time(spec):
return [] # not yet
fired = []
for s in self._holding(now): # watchdog/grace ignored (AC-2/AC-6)
if self._safe_sell(s, "market_close_liquidation"):
fired.append(s.slot_id)
self._last_liquidation_date = today
return fired
# ----------------------------------------------------------------- run_once
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
_log.warning("market-close liquidation tick failed", exc_info=True)
if self._due(self._last_forced_close_at, now, self._cfg.forced_close_check_interval_sec):
self._last_forced_close_at = now
self.check_forced_close(now)
if self._due(self._last_price_check_at, now, self._cfg.stop_loss_poll_interval_sec):
self._last_price_check_at = now
self.check_prices(now)
@staticmethod
def _due(last: datetime | None, now: datetime, interval_sec: int) -> bool:
if last is None:
return True
return (now - last).total_seconds() >= interval_sec