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>
This commit is contained in:
2026-06-07 08:32:30 +09:00
co-authored by Claude Opus 4.8
parent e4e5228972
commit a30efa8f3b
47 changed files with 3399 additions and 36 deletions
+10
View File
@@ -8,6 +8,7 @@ trex_core.adapters.broker. Fills are observed asynchronously via poll_fill
from __future__ import annotations
from dataclasses import dataclass, field
from decimal import Decimal
from typing import Any, Optional, Protocol
@@ -90,6 +91,15 @@ class BrokerPort(Protocol):
"""
...
def get_current_price(self, symbol: str) -> Optional[Decimal]:
"""Return the current traded price (`stck_prpr`) for a symbol (REQ-038).
Used by the safety-sell worker to evaluate stop-loss/take-profit
thresholds. Returns None when the price is unavailable (network error,
unknown symbol, or — for the paper double — no programmed price).
"""
...
# --- shared fee model (REQ-018, orbit calculate_fee pattern) -----------------
# Conservative KR equities approximation (bps). Brokers can override, but we
+5
View File
@@ -14,6 +14,7 @@ from __future__ import annotations
from dataclasses import dataclass, field
from datetime import date, datetime
from decimal import Decimal
from typing import Any, Optional
from uuid import UUID
@@ -54,6 +55,8 @@ class BuyIntent:
sell_strategy_id: Optional[str] = None
portfolio_id: Optional[str] = None
forced_close_at: Optional[datetime] = None
stop_loss_price: Optional[Decimal] = None # REQ-035
take_profit_price: Optional[Decimal] = None # REQ-035
extra: dict[str, Any] = field(default_factory=dict)
@@ -157,6 +160,8 @@ class IntentService:
sell_strategy_id=intent.sell_strategy_id,
portfolio_id=intent.portfolio_id,
forced_close_at=intent.forced_close_at,
stop_loss_price=intent.stop_loss_price,
take_profit_price=intent.take_profit_price,
extra={"intent_id": intent.intent_id, "symbol": intent.symbol},
)
except SlotStateMismatchError:
+77 -2
View File
@@ -20,14 +20,25 @@ from trex_core.application.portfolio import (
View,
build_snapshot_envelope,
)
from trex_core.domain.slot import SlotRepository, SlotService
from trex_core.application.watchdog import WatchdogStore
from trex_core.domain.slot import (
SlotNotFoundError,
SlotRepository,
SlotService,
SlotState,
)
_log = logging.getLogger(__name__)
# ---- intent RPC handler -----------------------------------------------------
def make_intent_rpc_handler(intent_service: IntentService):
def make_intent_rpc_handler(
intent_service: IntentService,
*,
slot_service: Optional[SlotService] = None,
watchdog_store: Optional[WatchdogStore] = None,
):
"""Build the RPC handler for `trex.intent.req`.
Payload shape:
@@ -36,9 +47,14 @@ def make_intent_rpc_handler(intent_service: IntentService):
"intent_id": "<idempotency key, = correlation_id>",
... fields per BuyIntent / SellIntent ...
}
or (REQ-040):
{"action": "update_thresholds", "slot_id": ...,
"stop_loss_price"?, "take_profit_price"?, "forced_close_at"?}
Response shape:
{"intent_id": str, "status": "admitted"|"rejected", "slot_id": str|None, "reason": str|None}
or for update_thresholds:
{"status": "updated"|"ignored"|"error", "slot_id": str, "reason"?: str}
Dedup uses `intent_log.try_insert(intent_id, ...)` (REQ-007 gate). The
request's `correlation_id` is reused as `intent_id` so the messaging
@@ -48,6 +64,9 @@ def make_intent_rpc_handler(intent_service: IntentService):
def handler(req: RpcRequest) -> RpcResponse:
body = req.payload or {}
# REQ-040: update_thresholds action (separate from buy/sell intents).
if str(body.get("action") or "").lower() == "update_thresholds":
return _handle_update_thresholds(body, slot_service, watchdog_store)
intent_id = str(body.get("intent_id") or req.correlation_id)
intent_type = str(body.get("intent_type") or "").lower()
try:
@@ -63,6 +82,8 @@ def make_intent_rpc_handler(intent_service: IntentService):
sell_strategy_id=_opt_str(body.get("sell_strategy_id")),
portfolio_id=_opt_str(body.get("portfolio_id")),
forced_close_at=_opt_dt(body.get("forced_close_at")),
stop_loss_price=_opt_decimal(body.get("stop_loss_price")),
take_profit_price=_opt_decimal(body.get("take_profit_price")),
)
d = intent_service.submit_buy(buy)
elif intent_type == "sell":
@@ -93,6 +114,46 @@ def make_intent_rpc_handler(intent_service: IntentService):
return handler
def _handle_update_thresholds(
body: dict,
slot_service: Optional[SlotService],
watchdog_store: Optional[WatchdogStore],
) -> RpcResponse:
"""REQ-040: update stop_loss/take_profit/forced_close_at on a holding slot.
Only the keys actually present in the payload are forwarded, so an absent
field keeps its value while an explicit ``null`` clears it (AC-4 vs AC-5).
On success the slot's watchdog last_seen_at is reset (AC-3) — receiving an
update_thresholds is itself a strategy-module liveness signal.
"""
if slot_service is None:
return RpcResponse(payload={"status": "error", "reason": "update_thresholds_unsupported"})
try:
slot_id = UUID(str(body["slot_id"]))
except (KeyError, ValueError) as exc:
return RpcResponse(payload={"status": "error", "reason": f"bad_request:{exc}"})
kwargs: dict = {}
if "stop_loss_price" in body:
kwargs["stop_loss_price"] = _opt_decimal(body["stop_loss_price"])
if "take_profit_price" in body:
kwargs["take_profit_price"] = _opt_decimal(body["take_profit_price"])
if "forced_close_at" in body:
kwargs["forced_close_at"] = _opt_dt(body["forced_close_at"])
actor = str(body.get("actor") or "strategy")
try:
status = slot_service.update_thresholds(slot_id, actor=actor, **kwargs)
except SlotNotFoundError:
return RpcResponse(payload={
"status": "ignored", "slot_id": str(slot_id), "reason": "slot_not_found",
})
if status == "updated" and watchdog_store is not None:
watchdog_store.update(str(slot_id)) # AC-3: liveness signal
payload = {"status": status, "slot_id": str(slot_id)}
if status == "ignored":
payload["reason"] = "not_holding" # AC-6
return RpcResponse(payload=payload)
# ---- snapshot RPC handler ---------------------------------------------------
def make_snapshot_rpc_handler(
@@ -102,6 +163,7 @@ def make_snapshot_rpc_handler(
snapshot_store: Optional[SnapshotStore] = None,
pause_store: Optional[PauseStore] = None,
default_total_slots: int = 10,
watchdog_store: Optional[WatchdogStore] = None,
):
"""Build the RPC handler for `trex.snapshot.req` (REQ-028).
@@ -126,6 +188,12 @@ def make_snapshot_rpc_handler(
body = req.payload or {}
day = _parse_date(body.get("trading_date")) if body.get("trading_date") else _today()
# REQ-034: update watchdog for all holding slots visible in this RPC.
if watchdog_store is not None:
for s in slot_repo.list_slots(day):
if s.status is SlotState.HOLDING:
watchdog_store.update(str(s.slot_id))
# --- BAT-008 envelope path (snapshot store wired) ---
if snapshot_store is not None and pause_store is not None:
requested_view = str(body.get("view") or "all").lower()
@@ -244,6 +312,13 @@ def _opt_str(v) -> Optional[str]:
return str(v)
def _opt_decimal(v):
if v is None:
return None
from decimal import Decimal
return Decimal(str(v))
def _opt_float(v) -> Optional[float]:
if v is None:
return None
+190
View File
@@ -0,0 +1,190 @@
"""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
+49
View File
@@ -0,0 +1,49 @@
"""Per-slot watchdog store for safety-sell (REQ-034 / BAT-010).
WatchdogStore tracks the last time a snapshot RPC response included each
holding slot. BAT-011 trigger loops use is_expired() to decide whether a
slot is unmonitored (strategy module absent) and therefore eligible for
autonomous safety-sell actions.
Thread-safety: dict reads and writes in CPython are GIL-atomic for simple
assignments, which is sufficient here — one writer (snapshot-rpc thread)
and one or more readers (BAT-011 trigger-loop threads). No explicit lock
is needed.
"""
from __future__ import annotations
from datetime import datetime, timezone
class WatchdogStore:
"""In-memory per-slot last_seen_at tracker (REQ-034)."""
def __init__(self) -> None:
self._store: dict[str, datetime] = {}
self._started_at: datetime = datetime.now(tz=timezone.utc)
def update(self, slot_id: str) -> None:
"""Record that slot_id appeared in a snapshot RPC response."""
self._store[slot_id] = datetime.now(tz=timezone.utc)
def is_expired(self, slot_id: str, timeout_sec: int) -> bool:
"""Return True if slot_id has not been seen for longer than timeout_sec.
A slot that has never been seen is treated as expired (returns True)
unless in_grace_period() is True — callers must check grace period
before calling this method when they want to suppress false positives.
"""
last = self._store.get(slot_id)
if last is None:
return True
elapsed = (datetime.now(tz=timezone.utc) - last).total_seconds()
return elapsed > timeout_sec
def in_grace_period(self, grace_sec: int) -> bool:
"""Return True if the daemon started less than grace_sec seconds ago.
During the grace period ALL expiry judgements must be deferred —
no slot should be treated as watchdog-expired (REQ-034 AC-4).
"""
elapsed = (datetime.now(tz=timezone.utc) - self._started_at).total_seconds()
return elapsed < grace_sec