Deliver BAT-001: bootstrap trex-core + port slot pure domain
Implement REQ-001~004 (dcy-001): scaffold the trex-core package (pyproject, trex_core/, tests/), port the slot pure domain into trex_core.domain.slot with import rewrites, add the EXPECTED_SLOT_FIELDS contract guard (test_contract), and port the state/service unit tests. Verification: 56 passed, ruff clean, import sweep shows zero external deps, public __all__ exposes no infra symbols, contract negative case reproduced. Align project-structure/runtime-flows baselines to the real tree. Sync SDLC tracking: REQ-001~004 → Implemented, BAT-001 → release-candidate. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""trex-core — shared core for the trex product family."""
|
||||
@@ -0,0 +1 @@
|
||||
"""trex-core domain layer."""
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Slot domain — daily lifecycle source of truth for trading slots.
|
||||
|
||||
Storage-agnostic pure domain: no broker, DB driver, CLI, or config dependency.
|
||||
A repository implementation is injected via the `SlotRepository` protocol.
|
||||
|
||||
Public API:
|
||||
- SlotState: enum of 6 slot states + allowed transitions
|
||||
- Slot: data class for a slot row
|
||||
- SlotCapacity: capacity snapshot returned by compute_slot_capacity
|
||||
- SlotTransitionRecord: append-only transition record
|
||||
- EXPECTED_SLOT_FIELDS: canonical `Slot` column contract (guarded by test_contract)
|
||||
- SlotService: main domain service (preallocate, transit, capacity, entry count)
|
||||
- SlotRepository: abstract storage protocol
|
||||
- SlotTransitionError / SlotStateMismatchError / SlotNotFoundError: domain errors
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from trex_core.domain.slot.errors import (
|
||||
SlotDomainError,
|
||||
SlotNotFoundError,
|
||||
SlotStateMismatchError,
|
||||
SlotTransitionError,
|
||||
)
|
||||
from trex_core.domain.slot.models import (
|
||||
EXPECTED_SLOT_FIELDS,
|
||||
Slot,
|
||||
SlotCapacity,
|
||||
SlotTransitionRecord,
|
||||
)
|
||||
from trex_core.domain.slot.repository import SlotRepository
|
||||
from trex_core.domain.slot.service import SlotService
|
||||
from trex_core.domain.slot.state import (
|
||||
ALLOWED_TRANSITIONS,
|
||||
SLOT_ADVISORY_LOCK_ID,
|
||||
SlotState,
|
||||
is_allowed_transition,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"ALLOWED_TRANSITIONS",
|
||||
"EXPECTED_SLOT_FIELDS",
|
||||
"SLOT_ADVISORY_LOCK_ID",
|
||||
"Slot",
|
||||
"SlotCapacity",
|
||||
"SlotDomainError",
|
||||
"SlotNotFoundError",
|
||||
"SlotRepository",
|
||||
"SlotService",
|
||||
"SlotState",
|
||||
"SlotStateMismatchError",
|
||||
"SlotTransitionError",
|
||||
"SlotTransitionRecord",
|
||||
"is_allowed_transition",
|
||||
]
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Slot domain exceptions (REQ-002, REQ-004)."""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class SlotDomainError(Exception):
|
||||
"""Base class for slot domain errors."""
|
||||
|
||||
|
||||
class SlotNotFoundError(SlotDomainError):
|
||||
"""Raised when a slot_id is not present in the repository."""
|
||||
|
||||
|
||||
class SlotTransitionError(SlotDomainError):
|
||||
"""Raised when a (from_state, to_state) pair is not in the allowed set."""
|
||||
|
||||
|
||||
class SlotStateMismatchError(SlotDomainError):
|
||||
"""Raised when expected from_state does not match the current slot state.
|
||||
|
||||
Distinct from SlotTransitionError: this fires when the slot moved to a
|
||||
different state between read and write (race detection inside the
|
||||
transition function).
|
||||
"""
|
||||
@@ -0,0 +1,113 @@
|
||||
"""In-memory SlotRepository — for unit tests and current trex-core runtime.
|
||||
|
||||
Simulates advisory lock via threading.Lock so contention tests are still
|
||||
meaningful even without a real PostgreSQL instance.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from contextlib import contextmanager
|
||||
from datetime import date, datetime, timezone
|
||||
from typing import Iterator, Optional
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from trex_core.domain.slot.errors import SlotNotFoundError
|
||||
from trex_core.domain.slot.models import Slot, SlotTransitionRecord
|
||||
from trex_core.domain.slot.state import SlotState
|
||||
|
||||
|
||||
class InMemorySlotRepository:
|
||||
"""Thread-safe in-memory repository for tests."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._slots: dict[UUID, Slot] = {}
|
||||
self._transitions: list[SlotTransitionRecord] = []
|
||||
self._entries: dict[tuple[date, str], tuple[int, datetime]] = {}
|
||||
# Per-lock-id threading.Lock; mirrors pg_advisory_xact_lock semantics
|
||||
# at process level. lock_time and contention can be observed.
|
||||
self._lock_table: dict[int, threading.Lock] = {}
|
||||
self._lock_table_guard = threading.Lock()
|
||||
|
||||
# --- lock + transaction ---
|
||||
@contextmanager
|
||||
def transactional_advisory_lock(self, lock_id: int) -> Iterator[None]:
|
||||
lock = self._lock_for(lock_id)
|
||||
lock.acquire()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
lock.release()
|
||||
|
||||
def _lock_for(self, lock_id: int) -> threading.Lock:
|
||||
with self._lock_table_guard:
|
||||
lock = self._lock_table.get(lock_id)
|
||||
if lock is None:
|
||||
lock = threading.Lock()
|
||||
self._lock_table[lock_id] = lock
|
||||
return lock
|
||||
|
||||
# --- daily_slot CRUD ---
|
||||
def pre_allocate_slots(self, trading_date: date, count: int) -> int:
|
||||
existing = [s for s in self._slots.values() if s.trading_date == trading_date]
|
||||
if existing:
|
||||
return 0
|
||||
now = datetime.now(tz=timezone.utc)
|
||||
for _ in range(count):
|
||||
slot_id = uuid4()
|
||||
self._slots[slot_id] = Slot(
|
||||
slot_id=slot_id,
|
||||
trading_date=trading_date,
|
||||
status=SlotState.IDLE,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
return count
|
||||
|
||||
def list_slots(self, trading_date: date) -> list[Slot]:
|
||||
return [s for s in self._slots.values() if s.trading_date == trading_date]
|
||||
|
||||
def fetch_slot(self, slot_id: UUID) -> Optional[Slot]:
|
||||
return self._slots.get(slot_id)
|
||||
|
||||
def find_idle_slot(self, trading_date: date) -> Optional[Slot]:
|
||||
for s in self._slots.values():
|
||||
if s.trading_date == trading_date and s.status is SlotState.IDLE:
|
||||
return s
|
||||
return None
|
||||
|
||||
def update_slot(self, slot: Slot) -> None:
|
||||
if slot.slot_id not in self._slots:
|
||||
raise SlotNotFoundError(f"slot not found: {slot.slot_id}")
|
||||
self._slots[slot.slot_id] = slot
|
||||
|
||||
# --- slot_transition_log (append-only) ---
|
||||
def append_transition_log(self, record: SlotTransitionRecord) -> None:
|
||||
# Defensive copy; reject any external mutation attempt on the list.
|
||||
self._transitions.append(record)
|
||||
|
||||
def transition_log_for(self, slot_id: UUID) -> list[SlotTransitionRecord]:
|
||||
return [t for t in self._transitions if t.slot_id == slot_id]
|
||||
|
||||
def all_transition_log(self) -> list[SlotTransitionRecord]:
|
||||
return list(self._transitions)
|
||||
|
||||
# --- daily_symbol_entries ---
|
||||
def increment_symbol_entry(self, trading_date: date, symbol: str) -> int:
|
||||
key = (trading_date, symbol)
|
||||
count, _ = self._entries.get(key, (0, datetime.min))
|
||||
new_count = count + 1
|
||||
self._entries[key] = (new_count, datetime.now(tz=timezone.utc))
|
||||
return new_count
|
||||
|
||||
def get_symbol_entry_count(self, trading_date: date, symbol: str) -> int:
|
||||
count, _ = self._entries.get((trading_date, symbol), (0, datetime.min))
|
||||
return count
|
||||
|
||||
# --- bulk counts ---
|
||||
def count_slots_by_status(self, trading_date: date) -> dict[SlotState, int]:
|
||||
result: dict[SlotState, int] = {}
|
||||
for s in self._slots.values():
|
||||
if s.trading_date != trading_date:
|
||||
continue
|
||||
result[s.status] = result.get(s.status, 0) + 1
|
||||
return result
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Slot domain data classes (REQ-001, REQ-002)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
from trex_core.domain.slot.state import SlotState
|
||||
|
||||
|
||||
@dataclass
|
||||
class Slot:
|
||||
"""Single daily_slot row.
|
||||
|
||||
Matches the slot column contract recorded in dcy-001 부록 A and
|
||||
docs/data-model.md (trex-core stores this in-memory for now; a future
|
||||
persistence layer must satisfy the same contract).
|
||||
"""
|
||||
|
||||
slot_id: UUID
|
||||
trading_date: date
|
||||
status: SlotState
|
||||
symbol: Optional[str] = None
|
||||
qty: Optional[float] = None
|
||||
avg_price: Optional[float] = None
|
||||
entry_price: Optional[float] = None
|
||||
allocated_capital: Optional[float] = None
|
||||
order_id: Optional[str] = None
|
||||
strategy_id: Optional[str] = None
|
||||
broker_order_id: Optional[str] = None # BAT-003 / REQ-011 (trex-orbit lineage)
|
||||
portfolio_id: Optional[str] = None # BAT-006 / REQ-025 (trex-orbit lineage)
|
||||
sell_strategy_id: Optional[str] = None # BAT-008 / REQ-047 (trex-orbit lineage)
|
||||
forced_close_at: Optional[datetime] = None # BAT-014 / REQ-066 (trex-orbit lineage)
|
||||
created_at: Optional[datetime] = None
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
|
||||
# Canonical column contract for `Slot` (dcy-001 OQ-2 / FR-5).
|
||||
# test_contract.py asserts this matches `dataclasses.fields(Slot)` so any
|
||||
# field add/remove fails loudly. Type mapping lives in the docs (dcy-001 부록 A
|
||||
# / docs/data-model.md), not here — names/presence only.
|
||||
EXPECTED_SLOT_FIELDS: frozenset[str] = frozenset({
|
||||
"slot_id",
|
||||
"trading_date",
|
||||
"status",
|
||||
"symbol",
|
||||
"qty",
|
||||
"avg_price",
|
||||
"entry_price",
|
||||
"allocated_capital",
|
||||
"order_id",
|
||||
"strategy_id",
|
||||
"broker_order_id",
|
||||
"portfolio_id",
|
||||
"sell_strategy_id",
|
||||
"forced_close_at",
|
||||
"created_at",
|
||||
"updated_at",
|
||||
})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SlotCapacity:
|
||||
"""Snapshot of slot capacity returned by compute_slot_capacity (REQ-002 AC-6)."""
|
||||
|
||||
idle_count: int
|
||||
holding_count: int
|
||||
pending_count: int
|
||||
total_slots: int
|
||||
scarcity_ratio: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SlotTransitionRecord:
|
||||
"""One append-only row in slot_transition_log (REQ-001, REQ-002)."""
|
||||
|
||||
slot_id: UUID
|
||||
from_state: SlotState
|
||||
to_state: SlotState
|
||||
ts: datetime
|
||||
reason: str
|
||||
actor: str
|
||||
extra: dict = field(default_factory=dict)
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Abstract slot repository protocol (REQ-002).
|
||||
|
||||
Concrete implementations:
|
||||
- InMemorySlotRepository — unit tests / current trex-core runtime
|
||||
- (future) PostgreSQL-backed repository — added in the persistence iteration
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import AbstractContextManager
|
||||
from datetime import date
|
||||
from typing import Optional, Protocol
|
||||
from uuid import UUID
|
||||
|
||||
from trex_core.domain.slot.models import Slot, SlotTransitionRecord
|
||||
from trex_core.domain.slot.state import SlotState
|
||||
|
||||
|
||||
class SlotRepository(Protocol):
|
||||
"""Storage protocol for slot domain.
|
||||
|
||||
Implementations MUST guarantee:
|
||||
- `transactional_advisory_lock()` runs the with-block inside a single transaction
|
||||
protected by an advisory lock. External I/O MUST NOT be performed inside the block.
|
||||
- `append_transition_log()` is append-only (no UPDATE/DELETE).
|
||||
"""
|
||||
|
||||
# --- lock + transaction ---
|
||||
def transactional_advisory_lock(self, lock_id: int) -> AbstractContextManager[None]:
|
||||
"""Return a context manager: BEGIN + pg_advisory_xact_lock + (block) + COMMIT.
|
||||
|
||||
On exception the transaction is rolled back and the lock released.
|
||||
"""
|
||||
...
|
||||
|
||||
# --- daily_slot CRUD ---
|
||||
def pre_allocate_slots(self, trading_date: date, count: int) -> int:
|
||||
"""Insert `count` idle slots for trading_date if none exist; return inserted count.
|
||||
|
||||
Idempotent — if slots for trading_date already exist, returns 0 (REQ-002 AC-4).
|
||||
"""
|
||||
...
|
||||
|
||||
def list_slots(self, trading_date: date) -> list[Slot]:
|
||||
"""Return all slots for the trading day."""
|
||||
...
|
||||
|
||||
def fetch_slot(self, slot_id: UUID) -> Optional[Slot]:
|
||||
"""Return single slot row or None."""
|
||||
...
|
||||
|
||||
def find_idle_slot(self, trading_date: date) -> Optional[Slot]:
|
||||
"""Return any one idle slot (None if exhausted)."""
|
||||
...
|
||||
|
||||
def update_slot(self, slot: Slot) -> None:
|
||||
"""Persist slot row (UPDATE by slot_id)."""
|
||||
...
|
||||
|
||||
# --- slot_transition_log (append-only) ---
|
||||
def append_transition_log(self, record: SlotTransitionRecord) -> None:
|
||||
"""Append one row to slot_transition_log (no UPDATE/DELETE allowed)."""
|
||||
...
|
||||
|
||||
# --- daily_symbol_entries ---
|
||||
def increment_symbol_entry(self, trading_date: date, symbol: str) -> int:
|
||||
"""Upsert (trading_date, symbol) with entry_count += 1, last_entry_at = now.
|
||||
|
||||
Returns the resulting entry_count (REQ-002 AC-3).
|
||||
"""
|
||||
...
|
||||
|
||||
def get_symbol_entry_count(self, trading_date: date, symbol: str) -> int:
|
||||
"""Return today's entry_count for symbol, or 0 if no row."""
|
||||
...
|
||||
|
||||
# --- bulk counts for capacity ---
|
||||
def count_slots_by_status(self, trading_date: date) -> dict[SlotState, int]:
|
||||
"""Return dict mapping SlotState -> count for trading_date."""
|
||||
...
|
||||
@@ -0,0 +1,250 @@
|
||||
"""Slot domain service — 4 main APIs (REQ-002).
|
||||
|
||||
- preallocate_daily_slots(trading_date, count)
|
||||
- transit_slot(slot_id, from_state, to_state, reason, actor, **fields)
|
||||
- get_today_entry_count(trading_date, symbol)
|
||||
- compute_slot_capacity(trading_date, total_slots)
|
||||
|
||||
All state-mutating APIs run inside repository.transactional_advisory_lock()
|
||||
to serialize Buy/Sell decision threads + operator CLI (REQ-002 AC-2).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
from datetime import date, datetime, timezone
|
||||
from typing import Any, Optional
|
||||
from uuid import UUID
|
||||
|
||||
from trex_core.domain.slot.errors import (
|
||||
SlotNotFoundError,
|
||||
SlotStateMismatchError,
|
||||
SlotTransitionError,
|
||||
)
|
||||
from trex_core.domain.slot.models import Slot, SlotCapacity, SlotTransitionRecord
|
||||
from trex_core.domain.slot.repository import SlotRepository
|
||||
from trex_core.domain.slot.state import SLOT_ADVISORY_LOCK_ID, SlotState, is_allowed_transition
|
||||
|
||||
|
||||
class SlotService:
|
||||
"""Slot lifecycle service. Race-free transitions via advisory lock + transaction."""
|
||||
|
||||
def __init__(self, repository: SlotRepository) -> None:
|
||||
self._repo = repository
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# preallocate_daily_slots
|
||||
# ------------------------------------------------------------
|
||||
def preallocate_daily_slots(self, trading_date: date, count: int) -> int:
|
||||
"""Insert `count` idle slots for trading_date if none exist.
|
||||
|
||||
Idempotent: second+ call on the same trading_date returns 0.
|
||||
Returns number of slots inserted.
|
||||
|
||||
REQ-002 AC-4, REQ-003 AC-5 (count must be > 0).
|
||||
"""
|
||||
if count <= 0:
|
||||
raise ValueError(f"slot count must be > 0, got {count}")
|
||||
with self._repo.transactional_advisory_lock(SLOT_ADVISORY_LOCK_ID):
|
||||
return self._repo.pre_allocate_slots(trading_date, count)
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# transit_slot
|
||||
# ------------------------------------------------------------
|
||||
def transit_slot(
|
||||
self,
|
||||
slot_id: UUID,
|
||||
from_state: SlotState,
|
||||
to_state: SlotState,
|
||||
reason: str,
|
||||
actor: str,
|
||||
*,
|
||||
symbol: Optional[str] = None,
|
||||
qty: Optional[float] = None,
|
||||
avg_price: Optional[float] = None,
|
||||
entry_price: Optional[float] = None,
|
||||
allocated_capital: Optional[float] = None,
|
||||
order_id: Optional[str] = None,
|
||||
strategy_id: Optional[str] = None,
|
||||
broker_order_id: Optional[str] = None,
|
||||
portfolio_id: Optional[str] = None,
|
||||
sell_strategy_id: Optional[str] = None,
|
||||
forced_close_at: Optional[datetime] = None,
|
||||
extra: Optional[dict[str, Any]] = None,
|
||||
) -> Slot:
|
||||
"""Transition slot from one state to another atomically.
|
||||
|
||||
Within a single advisory-locked transaction:
|
||||
1. fetch slot
|
||||
2. verify current state == from_state (race detection)
|
||||
3. verify (from_state, to_state) is in the allowed set
|
||||
4. update slot row (fields per to_state semantics)
|
||||
5. append transition_log row
|
||||
6. on closed->idle, increment daily_symbol_entries (REQ-002 AC-3)
|
||||
|
||||
External I/O (broker, kis-data-hub, portfolio-hub) MUST NOT be performed
|
||||
inside this function — caller does I/O outside the lock (REQ-002 AC-5).
|
||||
"""
|
||||
if not is_allowed_transition(from_state, to_state):
|
||||
raise SlotTransitionError(
|
||||
f"transition not allowed: {from_state.value} -> {to_state.value}"
|
||||
)
|
||||
|
||||
with self._repo.transactional_advisory_lock(SLOT_ADVISORY_LOCK_ID):
|
||||
slot = self._repo.fetch_slot(slot_id)
|
||||
if slot is None:
|
||||
raise SlotNotFoundError(f"slot not found: {slot_id}")
|
||||
|
||||
# Race detection — current state must match caller's from_state.
|
||||
if slot.status is not from_state:
|
||||
raise SlotStateMismatchError(
|
||||
f"slot {slot_id} current state {slot.status.value} "
|
||||
f"!= requested from_state {from_state.value}"
|
||||
)
|
||||
|
||||
updated = self._apply_transition_fields(
|
||||
slot,
|
||||
to_state,
|
||||
symbol=symbol,
|
||||
qty=qty,
|
||||
avg_price=avg_price,
|
||||
entry_price=entry_price,
|
||||
allocated_capital=allocated_capital,
|
||||
order_id=order_id,
|
||||
strategy_id=strategy_id,
|
||||
broker_order_id=broker_order_id,
|
||||
portfolio_id=portfolio_id,
|
||||
sell_strategy_id=sell_strategy_id,
|
||||
forced_close_at=forced_close_at,
|
||||
)
|
||||
self._repo.update_slot(updated)
|
||||
|
||||
# closed -> idle recovery: bump daily_symbol_entries atomically
|
||||
# (REQ-002 AC-3, REQ-001 split-by-purpose).
|
||||
if from_state is SlotState.CLOSED and to_state is SlotState.IDLE:
|
||||
# Use the symbol carried by the slot before reset.
|
||||
symbol_for_entry = slot.symbol
|
||||
if symbol_for_entry:
|
||||
self._repo.increment_symbol_entry(slot.trading_date, symbol_for_entry)
|
||||
|
||||
self._repo.append_transition_log(
|
||||
SlotTransitionRecord(
|
||||
slot_id=slot_id,
|
||||
from_state=from_state,
|
||||
to_state=to_state,
|
||||
ts=datetime.now(tz=timezone.utc),
|
||||
reason=reason,
|
||||
actor=actor,
|
||||
extra=extra or {},
|
||||
)
|
||||
)
|
||||
return updated
|
||||
|
||||
@staticmethod
|
||||
def _apply_transition_fields(
|
||||
slot: Slot,
|
||||
to_state: SlotState,
|
||||
*,
|
||||
symbol: Optional[str],
|
||||
qty: Optional[float],
|
||||
avg_price: Optional[float],
|
||||
entry_price: Optional[float],
|
||||
allocated_capital: Optional[float],
|
||||
order_id: Optional[str],
|
||||
strategy_id: Optional[str],
|
||||
broker_order_id: Optional[str] = None,
|
||||
portfolio_id: Optional[str] = None,
|
||||
sell_strategy_id: Optional[str] = None,
|
||||
forced_close_at: Optional[datetime] = None,
|
||||
) -> Slot:
|
||||
"""Compute the post-transition Slot row.
|
||||
|
||||
Special: closed -> idle resets occupancy fields (FR-2 #7).
|
||||
Special: pending_buy -> idle resets occupancy (REQ-011 AC-6 rollback).
|
||||
"""
|
||||
if to_state is SlotState.IDLE and slot.status in {
|
||||
SlotState.CLOSED,
|
||||
SlotState.PENDING_BUY,
|
||||
}:
|
||||
# Recovery / rollback: clear occupancy + broker handle.
|
||||
# transition_log retains audit trail.
|
||||
return replace(
|
||||
slot,
|
||||
status=SlotState.IDLE,
|
||||
symbol=None,
|
||||
qty=None,
|
||||
avg_price=None,
|
||||
entry_price=None,
|
||||
allocated_capital=None,
|
||||
order_id=None,
|
||||
strategy_id=None,
|
||||
broker_order_id=None,
|
||||
portfolio_id=None,
|
||||
sell_strategy_id=None,
|
||||
forced_close_at=None,
|
||||
updated_at=datetime.now(tz=timezone.utc),
|
||||
)
|
||||
|
||||
# Generic update: caller-supplied fields override; None means "keep".
|
||||
return replace(
|
||||
slot,
|
||||
status=to_state,
|
||||
symbol=symbol if symbol is not None else slot.symbol,
|
||||
qty=qty if qty is not None else slot.qty,
|
||||
avg_price=avg_price if avg_price is not None else slot.avg_price,
|
||||
entry_price=entry_price if entry_price is not None else slot.entry_price,
|
||||
allocated_capital=(
|
||||
allocated_capital if allocated_capital is not None else slot.allocated_capital
|
||||
),
|
||||
order_id=order_id if order_id is not None else slot.order_id,
|
||||
strategy_id=strategy_id if strategy_id is not None else slot.strategy_id,
|
||||
broker_order_id=(
|
||||
broker_order_id if broker_order_id is not None else slot.broker_order_id
|
||||
),
|
||||
portfolio_id=(
|
||||
portfolio_id if portfolio_id is not None else slot.portfolio_id
|
||||
),
|
||||
sell_strategy_id=(
|
||||
sell_strategy_id
|
||||
if sell_strategy_id is not None
|
||||
else slot.sell_strategy_id
|
||||
),
|
||||
forced_close_at=(
|
||||
forced_close_at if forced_close_at is not None else slot.forced_close_at
|
||||
),
|
||||
updated_at=datetime.now(tz=timezone.utc),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# get_today_entry_count
|
||||
# ------------------------------------------------------------
|
||||
def get_today_entry_count(self, trading_date: date, symbol: str) -> int:
|
||||
"""Return today's entry_count for a symbol (0 if no entries yet).
|
||||
|
||||
Used by buy decision state gate to enforce re-entry policy.
|
||||
Reads daily_symbol_entries (decision input), NEVER queries
|
||||
slot_transition_log (audit only). REQ-001, dcy-001 5.3.5.5.
|
||||
"""
|
||||
return self._repo.get_symbol_entry_count(trading_date, symbol)
|
||||
|
||||
# ------------------------------------------------------------
|
||||
# compute_slot_capacity
|
||||
# ------------------------------------------------------------
|
||||
def compute_slot_capacity(self, trading_date: date, total_slots: int) -> SlotCapacity:
|
||||
"""Return idle/holding/pending counts + scarcity_ratio (REQ-002 AC-6).
|
||||
|
||||
scarcity_ratio = 1 - idle_count / total_slots, clamped to [0.0, 1.0].
|
||||
"""
|
||||
if total_slots <= 0:
|
||||
raise ValueError(f"total_slots must be > 0, got {total_slots}")
|
||||
counts = self._repo.count_slots_by_status(trading_date)
|
||||
idle = counts.get(SlotState.IDLE, 0)
|
||||
holding = counts.get(SlotState.HOLDING, 0)
|
||||
pending = counts.get(SlotState.PENDING_BUY, 0) + counts.get(SlotState.PENDING_SELL, 0)
|
||||
scarcity = max(0.0, min(1.0, 1.0 - (idle / total_slots)))
|
||||
return SlotCapacity(
|
||||
idle_count=idle,
|
||||
holding_count=holding,
|
||||
pending_count=pending,
|
||||
total_slots=total_slots,
|
||||
scarcity_ratio=scarcity,
|
||||
)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Slot state machine: 6 states + 8 allowed transitions (REQ-001, REQ-002).
|
||||
|
||||
The transitions match dcy-001 FR-2 and BAT-001 design.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import Enum
|
||||
|
||||
|
||||
# Shared PostgreSQL advisory lock id for Buy/Sell decision threads and
|
||||
# operator CLI manual transitions. Single constant so all callers serialize
|
||||
# through the same lock (REQ-002 NFR-1, dcy-001 R-1).
|
||||
SLOT_ADVISORY_LOCK_ID: int = 0x5107_4D31 # arbitrary mnemonic constant
|
||||
|
||||
|
||||
class SlotState(str, Enum):
|
||||
"""6-state slot lifecycle (dcy-001 5.3.5.1)."""
|
||||
|
||||
IDLE = "idle"
|
||||
PENDING_BUY = "pending_buy"
|
||||
HOLDING = "holding"
|
||||
PENDING_SELL = "pending_sell"
|
||||
CLOSED = "closed"
|
||||
ERROR = "error"
|
||||
|
||||
|
||||
# 8 allowed transitions per dcy-001 FR-2. Any pair not in this set must be
|
||||
# rejected by SlotService.
|
||||
# Note: `* -> error` is represented as transitions from every non-error state.
|
||||
_BASE_TRANSITIONS: frozenset[tuple[SlotState, SlotState]] = frozenset(
|
||||
{
|
||||
(SlotState.IDLE, SlotState.PENDING_BUY), # 1. buy decision
|
||||
(SlotState.PENDING_BUY, SlotState.HOLDING), # 2. buy filled
|
||||
(SlotState.PENDING_BUY, SlotState.IDLE), # 3. buy rejected/rollback
|
||||
(SlotState.HOLDING, SlotState.PENDING_SELL), # 4. sell decision
|
||||
(SlotState.PENDING_SELL, SlotState.CLOSED), # 5. sell filled
|
||||
(SlotState.PENDING_SELL, SlotState.HOLDING), # 6. sell rejected/rollback
|
||||
(SlotState.CLOSED, SlotState.IDLE), # 7. recovery (with daily_symbol_entries +1)
|
||||
}
|
||||
)
|
||||
|
||||
# 8th transition family: any non-error state may move to error (operator manual
|
||||
# resolve uses `error -> idle | holding` which is also covered explicitly).
|
||||
_TO_ERROR_TRANSITIONS: frozenset[tuple[SlotState, SlotState]] = frozenset(
|
||||
(s, SlotState.ERROR) for s in SlotState if s is not SlotState.ERROR
|
||||
)
|
||||
|
||||
# Operator manual resolve transitions out of error (REQ-004).
|
||||
_FROM_ERROR_TRANSITIONS: frozenset[tuple[SlotState, SlotState]] = frozenset(
|
||||
{
|
||||
(SlotState.ERROR, SlotState.IDLE),
|
||||
(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 one of the 8 transition families."""
|
||||
return (from_state, to_state) in ALLOWED_TRANSITIONS
|
||||
Reference in New Issue
Block a user