Files
trex-core/trex_core/application/intents.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

193 lines
7.3 KiB
Python

"""Intent application service (REQ-007).
Turns a buy/sell intent submitted over HTTP into a single-writer slot
transition, with intent_id idempotency backed by a durable intent_log.
Idempotency model (dcy-002 OQ-1): `intent_store.try_insert` is the dedup
gate. On a duplicate intent_id it returns the prior decision without
re-driving any transition (NFR-3). Slot transitions go exclusively through
SlotService (advisory-lock serialized) so the single-writer invariant
holds (NFR-2). Concurrency on the last idle slot is resolved by retrying
on SlotStateMismatchError.
"""
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
from trex_core.application.ports import IntentStore
from trex_core.domain.slot import (
SlotRepository,
SlotService,
SlotState,
SlotStateMismatchError,
)
_MAX_IDLE_RETRY = 8
@dataclass(frozen=True)
class IntentDecision:
"""Result of submitting an intent."""
intent_id: str
status: str # 'admitted' | 'rejected'
slot_id: Optional[UUID] = None
reason: Optional[str] = None
@property
def admitted(self) -> bool:
return self.status == "admitted"
@dataclass(frozen=True)
class BuyIntent:
intent_id: str
trading_date: date
symbol: str
qty: Optional[float] = None
allocated_capital: Optional[float] = None
entry_price: Optional[float] = None
strategy_id: Optional[str] = None
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)
@dataclass(frozen=True)
class SellIntent:
intent_id: str
slot_id: UUID
reason: str = "discretionary_sell"
sell_strategy_id: Optional[str] = None
extra: dict[str, Any] = field(default_factory=dict)
class IntentService:
"""Admission + slot transition for buy/sell intents (single writer)."""
def __init__(
self,
slot_service: SlotService,
slot_repo: SlotRepository,
intent_store: IntentStore,
) -> None:
self._svc = slot_service
self._repo = slot_repo
self._intents = intent_store
# ------------------------------------------------------------
def lookup(self, intent_id: str) -> Optional[IntentDecision]:
"""Return the recorded decision for an intent_id, or None (re-query)."""
rec = self._intents.get(intent_id)
if rec is None:
return None
return IntentDecision(rec.intent_id, rec.status, rec.slot_id, rec.reason)
def submit_buy(self, intent: BuyIntent) -> IntentDecision:
payload = {
"trading_date": intent.trading_date.isoformat(),
"symbol": intent.symbol,
"qty": intent.qty,
"allocated_capital": intent.allocated_capital,
"entry_price": intent.entry_price,
"strategy_id": intent.strategy_id,
"sell_strategy_id": intent.sell_strategy_id,
"portfolio_id": intent.portfolio_id,
}
prior = self._dedup(intent.intent_id, "buy", payload)
if prior is not None:
return prior
decision = self._admit_buy(intent)
self._intents.finalize(
intent.intent_id, decision.status, decision.slot_id, decision.reason
)
return decision
def submit_sell(self, intent: SellIntent) -> IntentDecision:
payload = {
"slot_id": str(intent.slot_id),
"reason": intent.reason,
"sell_strategy_id": intent.sell_strategy_id,
}
prior = self._dedup(intent.intent_id, "sell", payload)
if prior is not None:
return prior
decision = self._admit_sell(intent)
self._intents.finalize(
intent.intent_id, decision.status, decision.slot_id, decision.reason
)
return decision
# ------------------------------------------------------------
def _dedup(self, intent_id: str, intent_type: str, payload: dict) -> Optional[IntentDecision]:
"""Return prior decision if intent_id already seen; else None (and reserve it)."""
inserted = self._intents.try_insert(intent_id, intent_type, payload)
if inserted:
return None
rec = self._intents.get(intent_id)
if rec is None: # extremely unlikely race; treat as not-yet-decided
return IntentDecision(intent_id, "rejected", None, "duplicate_in_flight")
return IntentDecision(intent_id, rec.status, rec.slot_id, rec.reason)
def _admit_buy(self, intent: BuyIntent) -> IntentDecision:
# Retry on the last-idle-slot race: another intent may claim the slot
# between our find and transit (SlotStateMismatchError).
for _ in range(_MAX_IDLE_RETRY):
slot = self._repo.find_idle_slot(intent.trading_date)
if slot is None:
return IntentDecision(intent.intent_id, "rejected", None, "no_idle_slot")
try:
updated = self._svc.transit_slot(
slot.slot_id,
SlotState.IDLE,
SlotState.PENDING_BUY,
reason="buy_intent",
actor="intent_api",
symbol=intent.symbol,
qty=intent.qty,
allocated_capital=intent.allocated_capital,
entry_price=intent.entry_price,
strategy_id=intent.strategy_id,
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:
continue # slot was claimed concurrently; try another idle slot
return IntentDecision(intent.intent_id, "admitted", updated.slot_id, None)
return IntentDecision(intent.intent_id, "rejected", None, "idle_slot_contended")
def _admit_sell(self, intent: SellIntent) -> IntentDecision:
slot = self._repo.fetch_slot(intent.slot_id)
if slot is None:
return IntentDecision(intent.intent_id, "rejected", None, "slot_not_found")
if slot.status is not SlotState.HOLDING:
return IntentDecision(
intent.intent_id, "rejected", None, f"slot_not_holding:{slot.status.value}"
)
try:
updated = self._svc.transit_slot(
slot.slot_id,
SlotState.HOLDING,
SlotState.PENDING_SELL,
reason=intent.reason,
actor="intent_api",
sell_strategy_id=intent.sell_strategy_id,
extra={"intent_id": intent.intent_id},
)
except SlotStateMismatchError:
return IntentDecision(intent.intent_id, "rejected", None, "slot_state_changed")
return IntentDecision(intent.intent_id, "admitted", updated.slot_id, None)