Files
trex-core/tests/application/test_execution.py
T
genichinandClaude Opus 4.8 e4be4d60c2 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>
2026-06-10 18:53:37 +09:00

206 lines
9.4 KiB
Python

"""Order execution loop tests via paper broker (REQ-013, REQ-014; BAT-030 asset-centric).
In-memory adapters; deterministic paper double drives the full async path.
"""
from __future__ import annotations
from trex_core.adapters.broker.paper import PaperBroker
from trex_core.adapters.persistence.in_memory_intent_store import InMemoryIntentStore
from trex_core.application.execution import ExecutionService
from trex_core.application.intents import BuyIntent, IntentService, SellIntent
from trex_core.domain.slot import SlotService, SlotState
from trex_core.domain.slot.in_memory_repository import InMemorySlotRepository
INST = "default"
SYMBOLS = {f"PF-{i}": f"00593{i}" for i in range(5)}
def _wire(broker, max_active_slots=None):
repo = InMemorySlotRepository()
svc = SlotService(repo, instance_key=INST)
intents = IntentService(
svc, repo, InMemoryIntentStore(),
resolve_symbol=SYMBOLS.get,
instance_key=INST, max_active_slots=max_active_slots,
)
execution = ExecutionService(svc, repo, broker, instance_key=INST)
repo.reconcile_universe(INST, set(SYMBOLS)) # permanent asset slots
return repo, svc, intents, execution
def _buy(intents, iid="b1", pid="PF-1", qty=10):
return intents.submit_buy(
BuyIntent(intent_id=iid, portfolio_id=pid, qty=qty, entry_price=1000)
)
def test_buy_lifecycle_to_holding():
repo, svc, intents, execution = _wire(PaperBroker(fill_after_polls=0))
d = _buy(intents)
sid = d.slot_id
assert repo.fetch_slot(sid).status is SlotState.PENDING_BUY
execution.run_once() # dispatch + poll(fill immediately)
slot = repo.fetch_slot(sid)
assert slot.status is SlotState.HOLDING and slot.qty == 10 and slot.avg_price == 1000.0
def test_buy_dispatch_is_idempotent_no_double_order():
broker = PaperBroker(fill_after_polls=5) # stays accepted (not filled) across ticks
repo, svc, intents, execution = _wire(broker)
sid = _buy(intents).slot_id
execution.run_once() # dispatch (1 order) + poll(accepted)
bid1 = repo.fetch_slot(sid).broker_order_id
execution.run_once() # must NOT re-dispatch
bid2 = repo.fetch_slot(sid).broker_order_id
assert bid1 == bid2 and len(broker._orders) == 1 # exactly one broker order
def test_buy_reject_rolls_back_to_inactive():
repo, svc, intents, execution = _wire(PaperBroker(reject_symbols={"005931"}))
sid = _buy(intents).slot_id
execution.run_once() # dispatch + poll(reject)
slot = repo.fetch_slot(sid)
assert slot.status is SlotState.INACTIVE and slot.broker_order_id is None
assert slot.portfolio_id == "PF-1" # permanent slot keeps its asset binding
def test_sell_lifecycle_returns_to_inactive():
repo, svc, intents, execution = _wire(PaperBroker(fill_after_polls=0))
sid = _buy(intents).slot_id
execution.run_once() # -> holding
assert repo.fetch_slot(sid).status is SlotState.HOLDING
intents.submit_sell(SellIntent(intent_id="s1", slot_id=sid))
assert repo.fetch_slot(sid).status is SlotState.PENDING_SELL
execution.run_once() # dispatch sell + fill -> inactive (asset slot at rest)
slot = repo.fetch_slot(sid)
assert slot.status is SlotState.INACTIVE
assert slot.qty is None and slot.portfolio_id == "PF-1"
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
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():
"""dcy-020/REQ-062 (D3): broker flat -> sell skipped (no mirror fallback),
surfaced via the sell_skipped_no_balance counter; no broker order is sent."""
broker = PaperBroker(fill_after_polls=0)
repo, svc, intents, execution = _wire(broker)
sid = _buy(intents).slot_id
execution.run_once() # holding (broker balance 10)
broker._orders.clear() # simulate divergence: broker is actually flat
svc.transit_slot(sid, SlotState.HOLDING, SlotState.PENDING_SELL,
reason="r", actor="t")
r = execution.run_once()
assert r.sell_skipped_no_balance == 1
assert r.dispatched == 0
assert repo.fetch_slot(sid).status is SlotState.PENDING_SELL # untouched
assert not [o for o in broker._orders.values() if o.side == "sell"]
def test_skipped_sell_does_not_block_other_dispatches():
"""A broker-flat sell must not head-block the dispatch queue."""
broker = PaperBroker(fill_after_polls=0)
repo, svc, intents, execution = _wire(broker)
sid = _buy(intents, iid="b1", pid="PF-1").slot_id
execution.run_once() # PF-1 holding
broker._orders.clear() # broker flat for PF-1's symbol
svc.transit_slot(sid, SlotState.HOLDING, SlotState.PENDING_SELL,
reason="r", actor="t")
d2 = _buy(intents, iid="b2", pid="PF-2") # a buy behind the stuck sell
r = execution.run_once()
assert r.sell_skipped_no_balance == 1
assert r.dispatched >= 1 # the buy went out
assert repo.fetch_slot(d2.slot_id).status is SlotState.HOLDING
def test_reconcile_after_crash_completes_fill_without_redispatch():
broker = PaperBroker(fill_after_polls=1)
repo, svc, intents, execution = _wire(broker)
sid = _buy(intents).slot_id
execution.run_once() # dispatch + poll1 (accepted, not filled) — simulates crash here
assert repo.fetch_slot(sid).status is SlotState.PENDING_BUY
orders_before = len(broker._orders)
execution.reconcile() # restart: re-poll -> fills, no new order
slot = repo.fetch_slot(sid)
assert slot.status is SlotState.HOLDING
assert len(broker._orders) == orders_before # reconcile did not submit a new order
def test_capacity_full_blocks_further_buys():
"""dcy-020/REQ-059: at M active slots further buys reject capacity_full."""
repo, svc, intents, execution = _wire(
PaperBroker(fill_after_polls=0), max_active_slots=2,
)
assert _buy(intents, iid="b0", pid="PF-0").status == "admitted"
assert _buy(intents, iid="b1", pid="PF-1").status == "admitted"
over = _buy(intents, iid="b2", pid="PF-2")
assert over.status == "rejected" and over.reason == "capacity_full"