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>
This commit is contained in:
@@ -114,10 +114,12 @@ class ExecutionService:
|
||||
# surfaces via reconcile_core_holdings (REQ-062 A). No mirror
|
||||
# fallback by design.
|
||||
if sell_balance is None:
|
||||
sell_balance = {
|
||||
b.symbol: int(b.hldg_qty) for b in self._broker.get_balance()
|
||||
}
|
||||
qty = sell_balance.get(slot.symbol or "", 0)
|
||||
sell_balance = self._balance_map()
|
||||
bal = sell_balance.get(slot.symbol or "", 0)
|
||||
# dcy-021 / REQ-062 (D4): full sell (slot.qty is None) => broker
|
||||
# balance; partial sell => min(order qty, broker balance). Broker
|
||||
# flat -> skip + WARN (divergence surfaces via reconcile).
|
||||
qty = bal if slot.qty is None else min(int(slot.qty), bal)
|
||||
if qty <= 0:
|
||||
r.sell_skipped_no_balance += 1
|
||||
_log.warning(
|
||||
@@ -172,21 +174,47 @@ class ExecutionService:
|
||||
self._check_stale_pending(slot, now, r)
|
||||
|
||||
# ------------------------------------------------------------
|
||||
def _balance_map(self) -> dict:
|
||||
"""Current broker balance as {symbol: hldg_qty} (REQ-062 ground truth)."""
|
||||
return {b.symbol: int(b.hldg_qty) for b in self._broker.get_balance()}
|
||||
|
||||
def _on_filled(self, slot, fs, side: str, r: ExecutionResult) -> None:
|
||||
broker_order_id = slot.broker_order_id # captured BEFORE clear_dispatch
|
||||
try:
|
||||
if slot.status is SlotState.PENDING_BUY:
|
||||
# dcy-021/REQ-066: held qty = broker balance (authority, includes
|
||||
# the just-filled increase); avg_price = weighted average. For an
|
||||
# initial buy slot.avg_price is None (=0) so new_avg = fill price.
|
||||
total = self._balance_map().get(slot.symbol or "", 0)
|
||||
filled = float(fs.filled_qty)
|
||||
new_qty = float(total) if total > 0 else filled
|
||||
old_qty = max(0.0, new_qty - filled)
|
||||
old_avg = float(slot.avg_price) if slot.avg_price else 0.0
|
||||
fill_price = float(fs.avg_price) if fs.avg_price is not None else old_avg
|
||||
new_avg = (
|
||||
(old_qty * old_avg + filled * fill_price) / new_qty
|
||||
if new_qty > 0 else fill_price
|
||||
)
|
||||
updated = self._svc.transit_slot(
|
||||
slot.slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
|
||||
reason="buy_filled", actor="execution_loop",
|
||||
avg_price=fs.avg_price, qty=float(fs.filled_qty) or slot.qty,
|
||||
avg_price=new_avg, qty=new_qty,
|
||||
)
|
||||
event_type = "slot_filled_buy"
|
||||
else: # PENDING_SELL — asset slot returns to inactive (dcy-020/REQ-057)
|
||||
updated = self._svc.transit_slot(
|
||||
slot.slot_id, SlotState.PENDING_SELL, SlotState.INACTIVE,
|
||||
reason="sell_filled", actor="execution_loop",
|
||||
)
|
||||
else: # PENDING_SELL — dcy-021/REQ-066: remainder>0 stays holding,
|
||||
# full exit -> inactive. Held qty = broker balance.
|
||||
total = self._balance_map().get(slot.symbol or "", 0)
|
||||
if total > 0:
|
||||
updated = self._svc.transit_slot(
|
||||
slot.slot_id, SlotState.PENDING_SELL, SlotState.HOLDING,
|
||||
reason="sell_filled_partial", actor="execution_loop",
|
||||
qty=float(total), # avg_price (cost basis) preserved
|
||||
)
|
||||
else:
|
||||
updated = self._svc.transit_slot(
|
||||
slot.slot_id, SlotState.PENDING_SELL, SlotState.INACTIVE,
|
||||
reason="sell_filled", actor="execution_loop",
|
||||
)
|
||||
event_type = "slot_filled_sell"
|
||||
except SlotStateMismatchError:
|
||||
return # slot moved concurrently; next tick reconciles
|
||||
@@ -211,20 +239,36 @@ class ExecutionService:
|
||||
filled = float(fs.filled_qty)
|
||||
try:
|
||||
if slot.status is SlotState.PENDING_BUY:
|
||||
# Only the filled portion is held; avg_price = fill price.
|
||||
# dcy-021: held qty = broker balance; avg_price weighted average
|
||||
# (consistent with _on_filled). Only the filled portion recorded.
|
||||
total = self._balance_map().get(slot.symbol or "", 0)
|
||||
new_qty = float(total) if total > 0 else filled
|
||||
old_qty = max(0.0, new_qty - filled)
|
||||
old_avg = float(slot.avg_price) if slot.avg_price else 0.0
|
||||
fill_price = float(fs.avg_price) if fs.avg_price is not None else old_avg
|
||||
new_avg = (
|
||||
(old_qty * old_avg + filled * fill_price) / new_qty
|
||||
if new_qty > 0 else fill_price
|
||||
)
|
||||
updated = self._svc.transit_slot(
|
||||
slot.slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
|
||||
reason="buy_partial_cancel", actor="execution_loop",
|
||||
avg_price=fs.avg_price, qty=filled,
|
||||
avg_price=new_avg, qty=new_qty,
|
||||
)
|
||||
event_type = "slot_filled_buy"
|
||||
else: # PENDING_SELL: remainder stays held, cost basis unchanged.
|
||||
remaining = max(0.0, float(slot.qty or 0) - filled)
|
||||
updated = self._svc.transit_slot(
|
||||
slot.slot_id, SlotState.PENDING_SELL, SlotState.HOLDING,
|
||||
reason="sell_partial_cancel", actor="execution_loop",
|
||||
qty=remaining,
|
||||
)
|
||||
else: # PENDING_SELL: remainder = broker balance, cost basis unchanged.
|
||||
total = self._balance_map().get(slot.symbol or "", 0)
|
||||
if total > 0:
|
||||
updated = self._svc.transit_slot(
|
||||
slot.slot_id, SlotState.PENDING_SELL, SlotState.HOLDING,
|
||||
reason="sell_partial_cancel", actor="execution_loop",
|
||||
qty=float(total),
|
||||
)
|
||||
else:
|
||||
updated = self._svc.transit_slot(
|
||||
slot.slot_id, SlotState.PENDING_SELL, SlotState.INACTIVE,
|
||||
reason="sell_partial_cancel", actor="execution_loop",
|
||||
)
|
||||
event_type = "slot_filled_sell"
|
||||
except SlotStateMismatchError:
|
||||
return # slot moved concurrently; next tick reconciles
|
||||
@@ -297,16 +341,27 @@ class ExecutionService:
|
||||
r.ledger_enqueued += 1
|
||||
|
||||
def _rollback(self, slot, *, reason: str) -> None:
|
||||
total = self._balance_map().get(slot.symbol or "", 0)
|
||||
try:
|
||||
if slot.status is SlotState.PENDING_BUY:
|
||||
self._svc.transit_slot(
|
||||
slot.slot_id, SlotState.PENDING_BUY, SlotState.INACTIVE,
|
||||
reason=reason, actor="execution_loop",
|
||||
) # inactive reset clears broker_order_id in the domain
|
||||
else: # PENDING_SELL rejected -> back to holding, clear order for re-dispatch
|
||||
if total > 0:
|
||||
# dcy-021: increase rejected — the prior holding is intact
|
||||
# (broker still holds), so return to holding, not inactive.
|
||||
self._svc.transit_slot(
|
||||
slot.slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
|
||||
reason=reason, actor="execution_loop", qty=float(total),
|
||||
)
|
||||
self._repo.clear_dispatch(slot.slot_id)
|
||||
else: # initial buy rejected -> inactive (clears broker_order_id)
|
||||
self._svc.transit_slot(
|
||||
slot.slot_id, SlotState.PENDING_BUY, SlotState.INACTIVE,
|
||||
reason=reason, actor="execution_loop",
|
||||
)
|
||||
else: # PENDING_SELL rejected -> back to holding (broker authoritative qty)
|
||||
self._svc.transit_slot(
|
||||
slot.slot_id, SlotState.PENDING_SELL, SlotState.HOLDING,
|
||||
reason=reason, actor="execution_loop",
|
||||
qty=float(total) if total > 0 else None,
|
||||
)
|
||||
self._repo.clear_dispatch(slot.slot_id)
|
||||
except SlotStateMismatchError:
|
||||
|
||||
@@ -78,6 +78,9 @@ class SellIntent:
|
||||
# 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
|
||||
# dcy-021 / REQ-062: optional partial-sell quantity. None => sell the whole
|
||||
# position (broker balance); set => partial sell of min(qty, broker balance).
|
||||
qty: Optional[float] = None
|
||||
extra: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@@ -140,6 +143,7 @@ class IntentService:
|
||||
"slot_id": str(intent.slot_id),
|
||||
"reason": intent.reason,
|
||||
"sell_strategy_id": intent.sell_strategy_id,
|
||||
"qty": intent.qty,
|
||||
}
|
||||
prior = self._dedup(intent.intent_id, "sell", payload)
|
||||
if prior is not None:
|
||||
@@ -163,15 +167,17 @@ class IntentService:
|
||||
return IntentDecision(intent_id, rec.status, rec.slot_id, rec.reason)
|
||||
|
||||
def _admit_buy(self, intent: BuyIntent) -> IntentDecision:
|
||||
"""dcy-020 / REQ-059·REQ-061: activate the asset's permanent slot.
|
||||
"""dcy-020 / REQ-059·REQ-061 + dcy-021/REQ-066: activate or size up the
|
||||
asset's permanent slot.
|
||||
|
||||
Contract key is slot_id (REQ-061); portfolio_id is accepted as a legacy
|
||||
dual-accept mapping. Symbol is resolved from the slot's portfolio_id.
|
||||
FCFS + no eviction: already-active -> already_active; at M ->
|
||||
capacity_full (existing holdings untouched, incl. over-cap). Single
|
||||
intent thread + instance-scoped advisory lock serialize admissions
|
||||
(dcy-020 OQ-1)."""
|
||||
_ACTIVE = (SlotState.PENDING_BUY, SlotState.HOLDING, SlotState.PENDING_SELL)
|
||||
- INACTIVE slot -> initial buy (FCFS, M cap applies, no eviction).
|
||||
- HOLDING slot -> position-sizing INCREASE (dcy-021): adds to the held
|
||||
position; M cap does NOT apply (active asset count unchanged).
|
||||
- PENDING_* slot -> in-flight conflict (already_active).
|
||||
Single intent thread + instance-scoped advisory lock serialize
|
||||
admissions (dcy-020 OQ-1)."""
|
||||
|
||||
def _resolve(sl):
|
||||
pid = sl.portfolio_id
|
||||
@@ -191,12 +197,20 @@ class IntentService:
|
||||
return IntentDecision(intent.intent_id, "rejected", None, "slot_id_or_portfolio_required")
|
||||
if slot is None:
|
||||
return IntentDecision(intent.intent_id, "rejected", None, miss_reason)
|
||||
if slot.status in _ACTIVE:
|
||||
# dcy-021: a buy on a HOLDING slot is a position-sizing increase.
|
||||
is_increase = slot.status is SlotState.HOLDING
|
||||
if slot.status in (SlotState.PENDING_BUY, SlotState.PENDING_SELL):
|
||||
return IntentDecision(intent.intent_id, "rejected", None, "already_active")
|
||||
if slot.status not in (SlotState.INACTIVE, SlotState.HOLDING):
|
||||
return IntentDecision(
|
||||
intent.intent_id, "rejected", None, f"slot_not_buyable:{slot.status.value}"
|
||||
)
|
||||
symbol = _resolve(slot)
|
||||
if not symbol:
|
||||
return IntentDecision(intent.intent_id, "rejected", None, "unknown_portfolio")
|
||||
if (self._max_active_slots is not None
|
||||
# M cap applies only to NEW activations (initial buy). An increase on
|
||||
# an already-active asset does not change the active asset count.
|
||||
if (not is_increase and self._max_active_slots is not None
|
||||
and self._repo.count_active(self._instance_key) >= self._max_active_slots):
|
||||
return IntentDecision(intent.intent_id, "rejected", None, "capacity_full")
|
||||
try:
|
||||
@@ -204,7 +218,7 @@ class IntentService:
|
||||
slot.slot_id,
|
||||
slot.status,
|
||||
SlotState.PENDING_BUY,
|
||||
reason="buy_intent",
|
||||
reason="position_increase" if is_increase else "buy_intent",
|
||||
actor="intent_api",
|
||||
symbol=symbol,
|
||||
qty=intent.qty,
|
||||
@@ -243,6 +257,10 @@ class IntentService:
|
||||
sell_strategy_id=intent.sell_strategy_id,
|
||||
# dcy-012 / REQ-007: optional sell limit (None => market sell).
|
||||
limit_price=intent.limit_price,
|
||||
# dcy-021 / REQ-062: partial-sell order qty (None => sell all);
|
||||
# dispatch caps at the broker balance. Entering PENDING_SELL takes
|
||||
# this qty as-is (None = "sell all" sentinel).
|
||||
qty=intent.qty,
|
||||
extra={"intent_id": intent.intent_id},
|
||||
)
|
||||
except SlotStateMismatchError:
|
||||
|
||||
@@ -97,6 +97,8 @@ def make_intent_rpc_handler(
|
||||
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")),
|
||||
# dcy-021 / REQ-062: optional partial-sell qty; absent => sell all.
|
||||
qty=_opt_float(body.get("qty")),
|
||||
)
|
||||
d = intent_service.submit_sell(sell)
|
||||
else:
|
||||
|
||||
@@ -192,12 +192,22 @@ class SlotService:
|
||||
else: # HOLDING / ERROR — pending order limit no longer applies.
|
||||
new_limit_price = None
|
||||
|
||||
# qty semantics during a pending state = the ORDER quantity (dcy-021 D1/D4).
|
||||
# Entering PENDING_SELL takes the caller qty AS-IS so a full sell
|
||||
# (qty=None) records a "sell all" sentinel rather than the stale held
|
||||
# mirror; a partial-sell intent records its order qty. Other states keep
|
||||
# the caller-override-else-preserve rule.
|
||||
if to_state is SlotState.PENDING_SELL:
|
||||
new_qty = qty
|
||||
else:
|
||||
new_qty = qty if qty is not None else slot.qty
|
||||
|
||||
# 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,
|
||||
qty=new_qty,
|
||||
avg_price=avg_price if avg_price is not None else slot.avg_price,
|
||||
limit_price=new_limit_price,
|
||||
allocated_capital=(
|
||||
|
||||
@@ -37,17 +37,20 @@ class SlotState(str, Enum):
|
||||
ERROR = "error"
|
||||
|
||||
|
||||
# Canonical transitions (dcy-020/REQ-057). 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.
|
||||
# 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
|
||||
(SlotState.PENDING_SELL, SlotState.HOLDING), # 6. sell rejected/rollback (or partial-sell remainder)
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user