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:
2026-06-10 18:53:37 +09:00
co-authored by Claude Opus 4.8
parent b2ba8c73fe
commit e4be4d60c2
13 changed files with 251 additions and 56 deletions
+27 -9
View File
@@ -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: