Files
trex-core/trex_core/application/safety_sell.py
T
genichinandClaude Opus 4.8 a30efa8f3b feat(safety-sell): dcy-007 core 자율 안전 매도 — BAT-010 기반 + BAT-011 트리거
dcy-007(core 자율 안전 매도) 전체 delivery. BAT-010 기반 인프라가 미커밋
상태였고 BAT-011 트리거 레이어와 공유 파일에서 섞여 있어 한 커밋으로 묶음.

BAT-010 (REQ-034/035/036/041, release-candidate):
- WatchdogStore(application/watchdog.py) + snapshot RPC 워치독 갱신
- Slot stop_loss_price/take_profit_price 필드 + 004_add_price_thresholds.sql
- SlotService.sell() 자율 매도 내부 경로 + idempotency
- SafetySellConfig env 5종 파싱

BAT-011 (REQ-037/038/039/040/042, release-candidate):
- SafetySellService(application/safety_sell.py): forced_close 만기 / stop-loss·
  take-profit KIS polling / 장 마감 강제 청산 + trex-safety-sell 7번째 스레드
- BrokerPort.get_current_price + KIS inquire-price(TTTC8397R/VTTC8397R, stck_prpr)
  + paper stub
- SlotService.update_thresholds() + intent RPC update_thresholds 액션
  (부분 갱신/null 해제, 워치독 last_seen_at 리셋)
- baseline 3문서 정합(interface-contract/runtime-flows/project-structure)

거버넌스: REQ-034~042 Implemented 동기화, BAT-010/011 release-candidate,
dcy-007 discovery 포함.

검증: 신규 38 테스트 green, 단위 236 passed/23 skipped,
인프라 게이트(PG+RabbitMQ) 259 passed(마이그레이션 001~004 round-trip 포함),
ruff clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-07 08:32:30 +09:00

191 lines
8.1 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
@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
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 and self._safe_sell(s, "forced_close_at"):
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:
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"):
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"):
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)
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