fix(execution): dcy-012 매도 가격 버그 정정 — slot entry_price→limit_price rename (BAT-016)
매도(sell) 주문이 현재가가 아닌 매수가(entry_price) 지정가로 나가던 버그(issue #10) 정정. 슬롯의 매수 전용 entry_price 를 side 무관 "현재 pending 주문 지정가" limit_price 로 내부 rename 하고, pending 이탈(→holding/→closed) 시 clear 해 매수 지정가가 매도로 누수되는 경로를 구조적으로 제거. 거버넌스: 전부 change-req (신규 REQ 없음, dcy-012 OQ-3). - REQ-002: Slot entry_price→limit_price rename + clear-on-exit 생애주기 - REQ-006: daily_slot 컬럼 rename 마이그레이션 006 (idempotent) + persistence 매핑 - REQ-013: _dispatch 가 slot.limit_price 단일 필드로 가격/주문유형 결정 - REQ-007: SellIntent/sell payload optional limit_price + _admit_sell 운반 - REQ-036: SlotService.sell optional 가격 → 자율 매도(safety-sell/kill-switch) 시장가 - REQ-003: 컬럼 계약/드리프트 가드 limit_price 반영 - REQ-015: runtime-flows/interface-contract/data-model 정합 매도 정책(OQ-1 하이브리드): 가격 지정→지정가("00"), 미지정→시장가("01"). 자율 매도는 가격 미전달 → 항상 시장가 (손절 미체결 pending_sell 갇힘 방지, issue #9 연계). 검증: 단위 286 passed/32 skipped, 인프라 게이트(PG+RabbitMQ) 318 passed, ruff clean. 신규 test_sell_pricing(recording broker)로 지정가 매수 슬롯의 매도가 매수가 재사용 안 함을 직접 검증. BAT-016 release-candidate. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -27,7 +27,7 @@ from trex_core.application.ports import IntentRecord
|
||||
from trex_core.domain.slot import Slot, SlotNotFoundError, SlotState, SlotTransitionRecord
|
||||
|
||||
_SLOT_COLUMNS = (
|
||||
"slot_id, trading_date, status, symbol, qty, avg_price, entry_price, "
|
||||
"slot_id, trading_date, status, symbol, qty, avg_price, limit_price, "
|
||||
"allocated_capital, order_id, strategy_id, broker_order_id, portfolio_id, "
|
||||
"sell_strategy_id, forced_close_at, stop_loss_price, take_profit_price, "
|
||||
"created_at, updated_at"
|
||||
@@ -121,13 +121,13 @@ class PostgreSQLSlotRepository:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"UPDATE daily_slot SET status=%s, symbol=%s, qty=%s, avg_price=%s, "
|
||||
"entry_price=%s, allocated_capital=%s, order_id=%s, strategy_id=%s, "
|
||||
"limit_price=%s, allocated_capital=%s, order_id=%s, strategy_id=%s, "
|
||||
"broker_order_id=%s, portfolio_id=%s, sell_strategy_id=%s, "
|
||||
"forced_close_at=%s, stop_loss_price=%s, take_profit_price=%s, "
|
||||
"updated_at=%s WHERE slot_id=%s",
|
||||
(
|
||||
slot.status.value, slot.symbol, slot.qty, slot.avg_price,
|
||||
slot.entry_price, slot.allocated_capital, slot.order_id,
|
||||
slot.limit_price, slot.allocated_capital, slot.order_id,
|
||||
slot.strategy_id, slot.broker_order_id, slot.portfolio_id,
|
||||
slot.sell_strategy_id, slot.forced_close_at,
|
||||
slot.stop_loss_price, slot.take_profit_price,
|
||||
@@ -236,7 +236,7 @@ class PostgreSQLSlotRepository:
|
||||
f = lambda v: float(v) if v is not None else None # noqa: E731
|
||||
d = lambda v: Decimal(str(v)) if v is not None else None # noqa: E731
|
||||
# Column order: slot_id(0) trading_date(1) status(2) symbol(3) qty(4)
|
||||
# avg_price(5) entry_price(6) allocated_capital(7) order_id(8)
|
||||
# avg_price(5) limit_price(6) allocated_capital(7) order_id(8)
|
||||
# strategy_id(9) broker_order_id(10) portfolio_id(11) sell_strategy_id(12)
|
||||
# forced_close_at(13) stop_loss_price(14) take_profit_price(15)
|
||||
# created_at(16) updated_at(17)
|
||||
@@ -247,7 +247,7 @@ class PostgreSQLSlotRepository:
|
||||
symbol=row[3],
|
||||
qty=f(row[4]),
|
||||
avg_price=f(row[5]),
|
||||
entry_price=f(row[6]),
|
||||
limit_price=f(row[6]),
|
||||
allocated_capital=f(row[7]),
|
||||
order_id=row[8],
|
||||
strategy_id=row[9],
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
-- BAT-016 / dcy-012 / REQ-006: rename daily_slot.entry_price -> limit_price.
|
||||
-- The column becomes the side-agnostic "current pending order limit price"
|
||||
-- (cleared on entering holding/closed), fixing the sell-uses-buy-limit bug
|
||||
-- (issue #10). Pure rename preserves existing row data (S-3).
|
||||
-- Idempotent: only renames when the old column still exists and the new one
|
||||
-- does not, so re-running the migration set is safe.
|
||||
DO $$
|
||||
BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'daily_slot' AND column_name = 'entry_price'
|
||||
) AND NOT EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'daily_slot' AND column_name = 'limit_price'
|
||||
) THEN
|
||||
ALTER TABLE daily_slot RENAME COLUMN entry_price TO limit_price;
|
||||
END IF;
|
||||
END $$;
|
||||
@@ -88,7 +88,11 @@ class ExecutionService:
|
||||
return
|
||||
side = "buy" if slot.status is SlotState.PENDING_BUY else "sell"
|
||||
qty = int(slot.qty or 0)
|
||||
limit = int(slot.entry_price) if slot.entry_price else None
|
||||
# dcy-012 / REQ-013: side-agnostic — use the slot's pending-order
|
||||
# limit_price only. A sell never reuses a buy limit (issue #10):
|
||||
# limit_price is cleared on entering HOLDING, so a market sell
|
||||
# carries None -> order_type "01".
|
||||
limit = int(slot.limit_price) if slot.limit_price else None
|
||||
ack = self._broker.submit_order(
|
||||
OrderRequest(
|
||||
slot_id=str(slot.slot_id),
|
||||
|
||||
@@ -70,6 +70,9 @@ class SellIntent:
|
||||
slot_id: UUID
|
||||
reason: str = "discretionary_sell"
|
||||
sell_strategy_id: Optional[str] = None
|
||||
# dcy-012 / REQ-007: optional sell limit price. None => market sell
|
||||
# (the path used by safety-sell / kill-switch). Set => limit sell at price.
|
||||
limit_price: Optional[float] = None
|
||||
extra: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@@ -176,7 +179,9 @@ class IntentService:
|
||||
symbol=symbol,
|
||||
qty=intent.qty,
|
||||
allocated_capital=intent.allocated_capital,
|
||||
entry_price=intent.entry_price,
|
||||
# dcy-012 / REQ-007: buy entry price maps to the slot's
|
||||
# side-agnostic pending limit_price (cleared on fill→HOLDING).
|
||||
limit_price=intent.entry_price,
|
||||
strategy_id=intent.strategy_id,
|
||||
sell_strategy_id=intent.sell_strategy_id,
|
||||
portfolio_id=intent.portfolio_id,
|
||||
@@ -206,6 +211,8 @@ class IntentService:
|
||||
reason=intent.reason,
|
||||
actor="intent_api",
|
||||
sell_strategy_id=intent.sell_strategy_id,
|
||||
# dcy-012 / REQ-007: optional sell limit (None => market sell).
|
||||
limit_price=intent.limit_price,
|
||||
extra={"intent_id": intent.intent_id},
|
||||
)
|
||||
except SlotStateMismatchError:
|
||||
|
||||
@@ -94,6 +94,8 @@ def make_intent_rpc_handler(
|
||||
slot_id=UUID(str(body["slot_id"])),
|
||||
reason=str(body.get("reason") or "discretionary_sell"),
|
||||
sell_strategy_id=_opt_str(body.get("sell_strategy_id")),
|
||||
# dcy-012 / REQ-007: optional sell limit price; absent => market sell.
|
||||
limit_price=_opt_float(body.get("limit_price")),
|
||||
)
|
||||
d = intent_service.submit_sell(sell)
|
||||
else:
|
||||
@@ -427,7 +429,10 @@ def _slot_to_dict(s) -> dict:
|
||||
"symbol": s.symbol,
|
||||
"qty": float(s.qty) if s.qty is not None else None,
|
||||
"avg_price": float(s.avg_price) if s.avg_price is not None else None,
|
||||
"entry_price": float(s.entry_price) if s.entry_price is not None else None,
|
||||
# dcy-012 / NFR-3: external read field name kept as "entry_price" for
|
||||
# contract compatibility; internally backed by the renamed limit_price
|
||||
# (the pending order limit, cleared once holding).
|
||||
"entry_price": float(s.limit_price) if s.limit_price is not None else None,
|
||||
"allocated_capital": float(s.allocated_capital) if s.allocated_capital is not None else None,
|
||||
"strategy_id": s.strategy_id,
|
||||
"sell_strategy_id": s.sell_strategy_id,
|
||||
|
||||
@@ -25,7 +25,11 @@ class Slot:
|
||||
symbol: Optional[str] = None
|
||||
qty: Optional[float] = None
|
||||
avg_price: Optional[float] = None
|
||||
entry_price: Optional[float] = None
|
||||
# dcy-012 / REQ-002: side-agnostic "current pending order limit price"
|
||||
# (renamed from entry_price). Set on pending entry (buy/sell limit), cleared
|
||||
# on pending exit (→HOLDING, →CLOSED) so a buy limit never leaks into a sell
|
||||
# order (issue #10). None => market order at dispatch.
|
||||
limit_price: Optional[float] = None
|
||||
allocated_capital: Optional[float] = None
|
||||
order_id: Optional[str] = None
|
||||
strategy_id: Optional[str] = None
|
||||
@@ -50,7 +54,7 @@ EXPECTED_SLOT_FIELDS: frozenset[str] = frozenset({
|
||||
"symbol",
|
||||
"qty",
|
||||
"avg_price",
|
||||
"entry_price",
|
||||
"limit_price",
|
||||
"allocated_capital",
|
||||
"order_id",
|
||||
"strategy_id",
|
||||
|
||||
@@ -66,7 +66,7 @@ class SlotService:
|
||||
symbol: Optional[str] = None,
|
||||
qty: Optional[float] = None,
|
||||
avg_price: Optional[float] = None,
|
||||
entry_price: Optional[float] = None,
|
||||
limit_price: Optional[float] = None,
|
||||
allocated_capital: Optional[float] = None,
|
||||
order_id: Optional[str] = None,
|
||||
strategy_id: Optional[str] = None,
|
||||
@@ -114,7 +114,7 @@ class SlotService:
|
||||
symbol=symbol,
|
||||
qty=qty,
|
||||
avg_price=avg_price,
|
||||
entry_price=entry_price,
|
||||
limit_price=limit_price,
|
||||
allocated_capital=allocated_capital,
|
||||
order_id=order_id,
|
||||
strategy_id=strategy_id,
|
||||
@@ -156,7 +156,7 @@ class SlotService:
|
||||
symbol: Optional[str],
|
||||
qty: Optional[float],
|
||||
avg_price: Optional[float],
|
||||
entry_price: Optional[float],
|
||||
limit_price: Optional[float],
|
||||
allocated_capital: Optional[float],
|
||||
order_id: Optional[str],
|
||||
strategy_id: Optional[str],
|
||||
@@ -171,6 +171,10 @@ class SlotService:
|
||||
|
||||
Special: closed -> idle resets occupancy fields (FR-2 #7).
|
||||
Special: pending_buy -> idle resets occupancy (REQ-011 AC-6 rollback).
|
||||
dcy-012 / REQ-002: limit_price is set only while a slot is in a pending
|
||||
state (the live order's limit); entering any non-pending state
|
||||
(IDLE/HOLDING/CLOSED) clears it so a buy limit never leaks into the next
|
||||
sell order (issue #10 root cause).
|
||||
"""
|
||||
if to_state is SlotState.IDLE and slot.status in {
|
||||
SlotState.CLOSED,
|
||||
@@ -184,7 +188,7 @@ class SlotService:
|
||||
symbol=None,
|
||||
qty=None,
|
||||
avg_price=None,
|
||||
entry_price=None,
|
||||
limit_price=None,
|
||||
allocated_capital=None,
|
||||
order_id=None,
|
||||
strategy_id=None,
|
||||
@@ -197,6 +201,13 @@ class SlotService:
|
||||
updated_at=datetime.now(tz=timezone.utc),
|
||||
)
|
||||
|
||||
# limit_price lifecycle (dcy-012 FR-1): set only on entering a pending
|
||||
# state (the order's limit); cleared on entering HOLDING/CLOSED.
|
||||
if to_state in {SlotState.PENDING_BUY, SlotState.PENDING_SELL}:
|
||||
new_limit_price = limit_price if limit_price is not None else slot.limit_price
|
||||
else: # HOLDING / CLOSED — pending order limit no longer applies.
|
||||
new_limit_price = None
|
||||
|
||||
# Generic update: caller-supplied fields override; None means "keep".
|
||||
return replace(
|
||||
slot,
|
||||
@@ -204,7 +215,7 @@ class SlotService:
|
||||
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,
|
||||
limit_price=new_limit_price,
|
||||
allocated_capital=(
|
||||
allocated_capital if allocated_capital is not None else slot.allocated_capital
|
||||
),
|
||||
@@ -236,12 +247,23 @@ class SlotService:
|
||||
# ------------------------------------------------------------
|
||||
# sell (REQ-036 / BAT-010)
|
||||
# ------------------------------------------------------------
|
||||
def sell(self, slot_id: UUID, actor: str, reason: str) -> None:
|
||||
def sell(
|
||||
self,
|
||||
slot_id: UUID,
|
||||
actor: str,
|
||||
reason: str,
|
||||
*,
|
||||
limit_price: Optional[float] = None,
|
||||
) -> None:
|
||||
"""Trigger an autonomous safety-sell for a holding slot (REQ-036).
|
||||
|
||||
Idempotent: silently returns if the slot is already pending_sell.
|
||||
Raises SlotNotFoundError if slot_id is unknown.
|
||||
Raises SlotTransitionError if the slot is neither holding nor pending_sell.
|
||||
|
||||
dcy-012 / REQ-036: ``limit_price`` defaults to None so autonomous sells
|
||||
(safety-sell / kill-switch) dispatch at market; only callers that pass a
|
||||
price (discretionary RPC sell) get a limit order.
|
||||
"""
|
||||
slot = self._repo.fetch_slot(slot_id)
|
||||
if slot is None:
|
||||
@@ -258,6 +280,7 @@ class SlotService:
|
||||
SlotState.PENDING_SELL,
|
||||
reason=reason,
|
||||
actor=actor,
|
||||
limit_price=limit_price,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user