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
+63 -7
View File
@@ -77,19 +77,75 @@ def test_sell_lifecycle_returns_to_inactive():
assert slot.qty is None and slot.portfolio_id == "PF-1"
def test_sell_qty_is_broker_balance_not_slot_mirror():
"""dcy-020/REQ-062 (D3): sell dispatch quantity = broker hldg_qty even when
the slot mirror qty is stale."""
def test_full_sell_qty_is_broker_balance():
"""dcy-020/REQ-062 (D3): full sell (slot.qty None) dispatches the broker
hldg_qty — independent of any stale mirror."""
broker = PaperBroker(fill_after_polls=0)
repo, svc, intents, execution = _wire(broker)
sid = _buy(intents, qty=10).slot_id
execution.run_once() # holding, broker balance = 10
# corrupt the mirror: slot says 7, broker says 10
svc.transit_slot(sid, SlotState.HOLDING, SlotState.PENDING_SELL,
reason="r", actor="t", qty=7.0)
execution.run_once() # dispatch sell with broker qty
svc.sell(sid, actor="t", reason="full") # qty=None -> sell all
execution.run_once()
sell_orders = [o for o in broker._orders.values() if o.side == "sell"]
assert len(sell_orders) == 1 and sell_orders[0].qty == 10
assert repo.fetch_slot(sid).status is SlotState.INACTIVE # full exit
def test_partial_sell_qty_is_min_intent_broker():
"""dcy-021/REQ-062 (D4): partial sell dispatches min(intent qty, broker);
remainder stays holding (broker-authoritative qty), cost basis preserved."""
broker = PaperBroker(fill_after_polls=0)
repo, svc, intents, execution = _wire(broker)
sid = _buy(intents, qty=10).slot_id
execution.run_once() # holding 10 @ avg 1000
intents.submit_sell(SellIntent(intent_id="ps", slot_id=sid, qty=4))
execution.run_once() # dispatch sell 4 + fill -> holding remainder 6
sell_orders = [o for o in broker._orders.values() if o.side == "sell"]
assert len(sell_orders) == 1 and sell_orders[0].qty == 4
slot = repo.fetch_slot(sid)
assert slot.status is SlotState.HOLDING and slot.qty == 6
assert slot.avg_price == 1000.0 # cost basis unchanged
def test_partial_sell_caps_at_broker_balance():
"""intent qty above the broker balance => full sell (min caps at balance)."""
broker = PaperBroker(fill_after_polls=0)
repo, svc, intents, execution = _wire(broker)
sid = _buy(intents, qty=10).slot_id
execution.run_once() # holding 10
intents.submit_sell(SellIntent(intent_id="ps", slot_id=sid, qty=999))
execution.run_once()
sell_orders = [o for o in broker._orders.values() if o.side == "sell"]
assert sell_orders[0].qty == 10 # capped at balance
assert repo.fetch_slot(sid).status is SlotState.INACTIVE # nothing left
def test_increase_accumulates_qty_and_weights_avg_price():
"""dcy-021/REQ-066: buy on a holding slot increases the position; held qty =
broker balance, avg_price = weighted average."""
broker = PaperBroker(fill_after_polls=0)
repo, svc, intents, execution = _wire(broker)
sid = _buy(intents, pid="PF-1").slot_id # qty 10 @ 1000
execution.run_once() # holding 10 @ 1000
assert repo.fetch_slot(sid).qty == 10 and repo.fetch_slot(sid).avg_price == 1000.0
# increase: same asset, +5 @ 1200 (buy on the holding slot)
d = intents.submit_buy(BuyIntent(intent_id="inc", slot_id=sid, qty=5, entry_price=1200))
assert d.status == "admitted"
assert repo.fetch_slot(sid).status is SlotState.PENDING_BUY
execution.run_once() # fill increase -> holding 15, weighted avg
slot = repo.fetch_slot(sid)
assert slot.status is SlotState.HOLDING and slot.qty == 15
assert slot.avg_price == (10 * 1000 + 5 * 1200) / 15 # 1066.67
def test_increase_does_not_consume_capacity():
"""dcy-021: increasing an already-active asset is not blocked by M cap."""
repo, svc, intents, execution = _wire(PaperBroker(fill_after_polls=0), max_active_slots=1)
sid = _buy(intents, iid="b0", pid="PF-0").slot_id
execution.run_once() # PF-0 holding (active=1=M)
# a NEW asset would be capacity_full, but an increase on PF-0 is allowed
d = intents.submit_buy(BuyIntent(intent_id="inc", slot_id=sid, qty=5, entry_price=1000))
assert d.status == "admitted"
def test_sell_skipped_when_broker_flat():
+4 -2
View File
@@ -103,7 +103,9 @@ def test_partial_fill_then_cancel_records_and_keeps_remainder():
writer.run_once() # drain the buy ledger item
intents.submit_sell(SellIntent(intent_id="s1", slot_id=sid))
# 4 of 10 sold, then externally cancelled
# 4 of 10 sold, then externally cancelled. dcy-021/REQ-062: remainder qty is
# the BROKER balance (authority) after the partial fill, not a slot subtraction.
broker.balance = {"005930": 6}
broker.responder = lambda side: FillStatus(
state="partially_filled", filled_qty=4, avg_price=1100.0,
execution_id="exec-partial", fee=0.5, tax=0.0, cancelled=True,
@@ -111,7 +113,7 @@ def test_partial_fill_then_cancel_records_and_keeps_remainder():
r = execution.run_once()
slot = repo.fetch_slot(sid)
assert slot.status is SlotState.HOLDING # remainder stays held
assert slot.qty == 6 # 10 - 4 sold
assert slot.qty == 6 # broker balance after partial
assert slot.avg_price == 1000.0 # cost basis preserved (not sell price)
assert slot.broker_order_id is None
assert r.filled == 1 and r.ledger_enqueued == 1
+37
View File
@@ -300,3 +300,40 @@ class TestAdvisoryLockSerialization:
)
elapsed_ms = (time.perf_counter() - t0) * 1000
assert elapsed_ms < 50.0, f"transition took {elapsed_ms:.2f} ms"
# ----------------------------------------------------------------------------
# dcy-021: position sizing — increase transition + INACTIVE/sell qty semantics
# ----------------------------------------------------------------------------
class TestPositionSizing:
def _holding(self, service, repo, qty=10.0, avg=1000.0):
slot = _seed(repo)[0]
service.transit_slot(slot.slot_id, SlotState.INACTIVE, SlotState.PENDING_BUY,
reason="buy", actor="t", symbol="005930", qty=qty)
return service.transit_slot(slot.slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
reason="filled", actor="t", avg_price=avg, qty=qty)
def test_holding_to_pending_buy_increase_preserves_avg(self, service, repo):
"""증액 pending: HOLDING→PENDING_BUY 가 허용되고 avg_price(가중평균용)가 보존된다."""
h = self._holding(service, repo)
inc = service.transit_slot(h.slot_id, SlotState.HOLDING, SlotState.PENDING_BUY,
reason="position_increase", actor="t", qty=5, limit_price=1200)
assert inc.status is SlotState.PENDING_BUY
assert inc.avg_price == 1000.0 # preserved for weighted-average at fill
assert inc.qty == 5 # order qty during pending
assert inc.limit_price == 1200
def test_full_sell_pending_clears_qty_to_none(self, service, repo):
"""전량 매도(qty 미지정) PENDING_SELL 진입 시 slot.qty = None('전량' sentinel)."""
h = self._holding(service, repo)
ps = service.transit_slot(h.slot_id, SlotState.HOLDING, SlotState.PENDING_SELL,
reason="sell", actor="t") # qty omitted
assert ps.status is SlotState.PENDING_SELL and ps.qty is None
def test_partial_sell_pending_records_order_qty(self, service, repo):
"""부분 매도 PENDING_SELL 진입 시 slot.qty = 주문 수량."""
h = self._holding(service, repo)
ps = service.transit_slot(h.slot_id, SlotState.HOLDING, SlotState.PENDING_SELL,
reason="sell", actor="t", qty=4, limit_price=1100)
assert ps.qty == 4 and ps.limit_price == 1100
assert ps.avg_price == 1000.0 # cost basis preserved
+3 -3
View File
@@ -59,6 +59,7 @@ def test_slot_advisory_lock_id_is_instance_scoped():
(SlotState.INACTIVE, SlotState.PENDING_BUY),
(SlotState.PENDING_BUY, SlotState.HOLDING),
(SlotState.PENDING_BUY, SlotState.INACTIVE),
(SlotState.HOLDING, SlotState.PENDING_BUY), # dcy-021 increase
(SlotState.HOLDING, SlotState.PENDING_SELL),
(SlotState.PENDING_SELL, SlotState.INACTIVE),
(SlotState.PENDING_SELL, SlotState.HOLDING),
@@ -83,7 +84,6 @@ def test_allowed_transition(from_state: SlotState, to_state: SlotState):
(SlotState.INACTIVE, SlotState.HOLDING),
(SlotState.INACTIVE, SlotState.PENDING_SELL),
(SlotState.HOLDING, SlotState.INACTIVE),
(SlotState.HOLDING, SlotState.PENDING_BUY),
(SlotState.PENDING_BUY, SlotState.PENDING_SELL),
(SlotState.PENDING_SELL, SlotState.PENDING_BUY),
# error has restricted exits — only inactive and holding
@@ -103,5 +103,5 @@ def test_self_loops_are_not_allowed():
def test_allowed_transitions_set_size():
"""6 base + 4 to-error + 2 operator-resolve = 12."""
assert len(ALLOWED_TRANSITIONS) == 12
"""7 base (incl. dcy-021 holding→pending_buy) + 4 to-error + 2 operator-resolve = 13."""
assert len(ALLOWED_TRANSITIONS) == 13