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:
|
||||
|
||||
Reference in New Issue
Block a user