Files
trex-core/trex_core/domain/slot/state.py
T
genichinandClaude Opus 4.8 e4be4d60c2 feat(slot): dcy-021 포지션 사이징 — 보유 슬롯 증액·부분 매도 (BAT-031)
자산 영구 슬롯(dcy-020)의 수량 가변 전제 위에 보유 포지션 수량 조정 구현.
명령형 계약(전략이 cash+quantity 로 qty+price 계산), core 는 실행 substrate,
수량 정본 = 브로커 잔고 재동기화로 "주문 수량 vs 보유 수량" 충돌 해소(별도 필드 없음).

- state.py: holding→pending_buy 전이 추가(증액) → 13 transitions (REQ-057)
- service.py: PENDING_SELL 진입 qty=caller as-is(None=전량 sentinel, 값=부분 주문) (REQ-062)
- intents.py: 증액 admission(holding 슬롯 매수=increase, M 캡 미적용), SellIntent.qty 부분 매도 (REQ-061)
- execution.py: _balance_map; 매도 dispatch=브로커잔고(전량)/min(주문,잔고)(부분);
  매수 체결 avg_price 가중평균+브로커 정본 resync; 매도 체결 잔고>0→holding/0→inactive;
  증액 롤백 holding 복귀 (REQ-066/062)
- messaging_handlers.py: sell payload qty 파싱(부분 매도)
- baseline 4문서(data-model/runtime-flows/interface-contract/project-structure) 정합 (REQ-067)

검증: 단위 378 / 통합(PG+RabbitMQ) 422 passed, ruff clean. run-the-app 사이징 e2e:
매수 10@1000 → 증액 +5@1200 → 15@1066.67(가중평균) → 부분 매도 6 → 9@1066.67(cost basis) → 전량→inactive.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-10 18:53:37 +09:00

81 lines
3.4 KiB
Python

"""Slot state machine (REQ-001, REQ-002; dcy-020/REQ-057 asset-centric).
The asset-centric permanent slot has five states. `inactive` means "no open
position" — it replaced the pool-model `idle` (never-bought) and `closed`
(sold, now flat) states, whose aliases were removed at the cutover (BAT-030);
migration 010 rewrites any remaining `idle`/`closed` rows to `inactive` and
swaps the status CHECK constraint accordingly.
"""
from __future__ import annotations
import zlib
from enum import Enum
# Shared PostgreSQL advisory lock base id. dcy-020/REQ-057 (NFR-1): in a shared
# DB the lock is scoped per instance via `slot_advisory_lock_id(instance_key)` so
# one instance's transitions never serialize against another's.
SLOT_ADVISORY_LOCK_ID: int = 0x5107_4D31 # arbitrary mnemonic constant
def slot_advisory_lock_id(instance_key: str) -> int:
"""Per-instance advisory lock id (dcy-020/REQ-057). Combines the base id with
a stable hash of instance_key so distinct instances take distinct locks while
the same instance always takes the same lock. Result stays in signed-32 range
(pg advisory lock accepts bigint; this keeps it deterministic and small)."""
h = zlib.crc32((instance_key or "default").encode("utf-8")) & 0x7FFF_FFFF
return SLOT_ADVISORY_LOCK_ID ^ h
class SlotState(str, Enum):
"""Slot lifecycle states (dcy-020/REQ-057 asset-centric, 5 states)."""
INACTIVE = "inactive" # no open position (permanent slot at rest)
PENDING_BUY = "pending_buy"
HOLDING = "holding"
PENDING_SELL = "pending_sell"
ERROR = "error"
# Canonical transitions (dcy-020/REQ-057; dcy-021/REQ-057 CHG-03). There is no
# inactive self-loop and no closed->idle recovery family — a permanent slot
# simply returns to `inactive` and may activate again via inactive->pending_buy.
# dcy-021 adds holding->pending_buy for position-sizing increase (the slot stays
# a held position; the buy adds to it, returning to holding on fill).
_BASE_TRANSITIONS: frozenset[tuple[SlotState, SlotState]] = frozenset(
{
(SlotState.INACTIVE, SlotState.PENDING_BUY), # 1. buy decision (activate)
(SlotState.PENDING_BUY, SlotState.HOLDING), # 2. buy filled
(SlotState.PENDING_BUY, SlotState.INACTIVE), # 3. buy rejected/rollback
(SlotState.HOLDING, SlotState.PENDING_BUY), # 7. position-sizing increase (dcy-021)
(SlotState.HOLDING, SlotState.PENDING_SELL), # 4. sell decision
(SlotState.PENDING_SELL, SlotState.INACTIVE), # 5. sell filled (deactivate)
(SlotState.PENDING_SELL, SlotState.HOLDING), # 6. sell rejected/rollback (or partial-sell remainder)
}
)
# Any non-error state may move to error.
_TO_ERROR_TRANSITIONS: frozenset[tuple[SlotState, SlotState]] = frozenset(
(s, SlotState.ERROR)
for s in (SlotState.INACTIVE, SlotState.PENDING_BUY, SlotState.HOLDING,
SlotState.PENDING_SELL)
)
# Operator manual resolve out of error (REQ-004).
_FROM_ERROR_TRANSITIONS: frozenset[tuple[SlotState, SlotState]] = frozenset(
{
(SlotState.ERROR, SlotState.INACTIVE),
(SlotState.ERROR, SlotState.HOLDING),
}
)
ALLOWED_TRANSITIONS: frozenset[tuple[SlotState, SlotState]] = (
_BASE_TRANSITIONS | _TO_ERROR_TRANSITIONS | _FROM_ERROR_TRANSITIONS
)
def is_allowed_transition(from_state: SlotState, to_state: SlotState) -> bool:
"""Return True iff (from_state, to_state) is an allowed transition."""
return (from_state, to_state) in ALLOWED_TRANSITIONS