# req-013: 주문 집행 루프 (claim·송신·체결·롤백) - Status: Implemented - Type: Integration - Priority: High - Owner: project maintainers ## Intent - 코어 데몬 내 백그라운드 execution 루프가 pending 슬롯을 집행해 브로커에 주문을 송신하고 체결을 슬롯 상태로 반영한다(불변식 A 단일 writer 유지). intent API 는 pending 전이까지만, 집행은 루프가 비동기 수행. ## Requirement - 데몬 프로세스 내 별도 execution 루프가 주기적으로: ① `pending_buy`/`pending_sell` 슬롯을 `FOR UPDATE SKIP LOCKED`(broker_order_id IS NULL)로 claim → `BrokerPort.submit_order` → `broker_order_id` 기록(옵션 A), ② broker_order_id 있는 pending 슬롯을 `poll_fill` 로 비동기 관측해 매수 체결 시 `pending_buy→holding`(avg_price/qty), 매도 체결 시 `pending_sell→closed`(recovery 재진입 +1), ③ 거부/취소 시 `pending_buy→idle` 롤백을 수행한다. 모든 슬롯 쓰기는 SlotService(advisory lock) 단일 경로. ## Acceptance Criteria 1. Given pending_buy 슬롯(paper), When 집행 루프 1회, Then 매수 주문 송신 + broker_order_id 기록, broker_order_id 채워진 슬롯은 재디스패치되지 않는다(멱등). (NFR-2 단일 writer) 2. Given 송신된 매수 주문이 체결(poll), When 루프, Then `pending_buy→holding`(avg_price/qty 반영). 3. Given 매수 주문 거부(poll), When 루프, Then `pending_buy→idle` 롤백. 4. Given pending_sell 슬롯, When 집행+체결, Then 매도 주문 송신 → `pending_sell→closed` + 재진입 +1. 5. Given 슬롯 쓰기 경로, When 점검, Then 집행 루프도 SlotService(advisory lock)로만 슬롯을 전이한다(브로커 직접 슬롯 쓰기 없음). ## Impacted Area - Docs: docs/runtime-flows.md(집행/체결 흐름) — REQ-015 - Modules: trex_core/application 또는 runtime(execution 루프), SlotService 재사용 - Tests: paper 더블로 매수/매도 lifecycle, 멱등 재디스패치, 거부 롤백, 체결→전이 ## Notes - OQ-3(옵션 A 실행큐)·OQ-4(별도 루프)·OQ-2(비동기 poll) 결정 반영. 폴링 주기/배치 크기는 config. - reconciliation·크래시 복구는 REQ-014. KIS 어댑터는 REQ-012, paper 는 REQ-011. - 출처: dcy-003 FR-2, FR-3, FR-4. NFR-2 흡수. ## Change Log ### CHG-20260604-01 - Date: 2026-06-04 - Author: Justin Ko #### Change Summary - dcy-003 FR-2·FR-3·FR-4 로부터 최초 생성(Proposed). NFR-2 흡수. #### Intent - 주문 집행 루프(매수/매도 claim·송신·체결·롤백) 요구사항을 backlog 로 정규화. #### Acceptance Criteria Delta - Added: - 매수 claim/멱등, 매수 체결→holding, 거부 롤백, 매도 체결→closed, 단일 writer 5개 기준 - Updated: - 없음 - Removed: - 없음 #### Impacted Area Delta - Docs: - docs/runtime-flows.md - Modules: - application/runtime(execution 루프) - Tests: - paper lifecycle/멱등/롤백/체결 테스트 #### Delivery Trace Delta - Batches: - none - Releases: - none #### Revalidation Impact - Reverification Needed: no - Existing Implementation Invalidated: no - Status Recommendation: keep-current - Follow-up Action: confirm-req 후 batch 편성 #### Validation Plan - paper 더블 매수/매도 lifecycle + 멱등 + 롤백 테스트로 검증. ### CHG-20260604-02 - Date: 2026-06-04 - Author: Justin Ko #### Change Summary - Status Proposed → Approved (confirm-req). #### Intent - 승인 게이트(필수 필드·구체 AC·blocker 없음) 충족, source dcy-003(confirmed, handoff 승인)와 모순 없음 확인. #### Acceptance Criteria Delta - Added: - 없음 - Updated: - 없음 - Removed: - 없음 #### Impacted Area Delta - Docs: - docs/srs/index.md (Register 상태 Approved) - Modules: - 없음 - Tests: - 없음 #### Delivery Trace Delta - Batches: - none (batch 편성 전) - Releases: - none #### Revalidation Impact - Reverification Needed: no - Existing Implementation Invalidated: no - Status Recommendation: keep-current - Follow-up Action: suggest-batch-reqs / draft-batch 로 delivery batch 편성 #### Validation Plan - 승인 후 batch planning 에서 본 REQ 의 Acceptance Criteria 를 검증 기준으로 사용. ### CHG-20260604-03 - Date: 2026-06-04 - Author: Justin Ko #### Change Summary - Status Approved → Implemented (confirm-req-implemented, 근거 batch BAT-004 release-candidate). #### Intent - BAT-004 verification.md 의 acceptance mapping + evidence(pytest 92 pass / 도메인 순수성 / 데몬 E2E / KIS VTS 모의투자 round-trip)로 AC 충족 → 구현 완료 동기화. #### Acceptance Criteria Delta - Added: - 없음 - Updated: - 없음 - Removed: - 없음 #### Impacted Area Delta - Docs: - docs/srs/index.md (Register Implemented) - Modules: - 없음 - Tests: - 없음 #### Delivery Trace Delta - Batches: - BAT-004 (release-candidate) - Releases: - none #### Revalidation Impact - Reverification Needed: no - Existing Implementation Invalidated: no - Status Recommendation: keep-current - Follow-up Action: draft-release 로 release 편성(BAT-001~004) #### Validation Plan - BAT-004 verification evidence 재참조로 충분. ### CHG-20260608-01 - Date: 2026-06-08 - Author: Justin Ko #### Change Summary - (change-req, dcy-012/issue #10) `_dispatch` 의 매도 가격 버그 정정: side 분기로 `entry_price`(매수가)를 지정가로 재사용하던 로직을 제거하고, side 무관 슬롯 `limit_price` **단일 필드**만 읽어 주문유형/가격을 결정한다 — 값 있으면 `order_type="00"`(그 지정가), 없으면 `order_type="01"`(시장가). BAT-016 재구현·재검증 완료 → Implemented 유지. #### Intent - 매도가 매수 지정가에 걸린 지정가로 나가 미체결되는 정합성 버그(issue #10) 제거. dispatch 의 가격 결정을 `slot.limit_price` 로 일원화. #### Acceptance Criteria Delta - Updated: - dispatch 가격/주문유형은 `slot.limit_price` 한 필드로 결정(side 분기 없음, 매수가 재사용 금지). #### Impacted Area Delta - Modules: `trex_core/application/execution.py`(`_dispatch`) - Tests: tests/application/test_sell_pricing.py(지정가 매수 슬롯의 시장가/지정가 매도, 회귀) #### Delivery Trace Delta - Batches: BAT-016 - Releases: none #### Revalidation Impact - Reverification Needed: yes (BAT-016 에서 완료) - Existing Implementation Invalidated: yes (entry_price 재사용 dispatch 경로) - Status Recommendation: Implemented (change-req → BAT-016 재검증) - Follow-up Action: confirm-req-implemented(BAT-016). #### Validation Plan - BAT-016: 지정가 매수 슬롯 + 가격 미전달 매도 → 시장가(entry_price 미사용 증명), + 가격 전달 매도 → 그 지정가, 시장가 매수 슬롯 회귀. ### CHG-20260608-02 - Date: 2026-06-08 - Author: Justin Ko #### Change Summary - (change-req, dcy-013/issue #9) 집행 루프에 외부 취소 처리 추가: 전량 취소(`is_terminal_reject`)는 기존 롤백 경로 재사용, 부분 체결 후 취소(`is_partial_cancel`)는 신규 `_on_partial_cancel` — 체결분 원장 1회 기록 + 슬롯 qty 차감(매도 잔여 held / 매수 체결분) + holding 복귀(OQ-1 A안). BAT-017 재구현·재검증 완료 → Implemented 유지. #### Intent - 부분 체결 후 취소에서 과매도·이중기록 없이 잔여 포지션만 재매도 가능하게(NFR-3). 전량 취소는 자동 holding 복귀. #### Acceptance Criteria Delta - Added: - `_poll` 이 is_partial_cancel 분기로 부분 체결 회계 수행(원장 1회 + qty 차감 + holding 복귀). 전량 취소는 롤백. #### Impacted Area Delta - Modules: `trex_core/application/execution.py`(`_poll`, `_on_partial_cancel`, ExecutionResult.stale_pending) - Tests: tests/application/test_execution_cancel.py #### Delivery Trace Delta - Batches: BAT-017 - Releases: none #### Revalidation Impact - Reverification Needed: yes (BAT-017 에서 완료) - Existing Implementation Invalidated: no (신규 분기 추가, 기존 filled/reject 경로 불변) - Status Recommendation: Implemented (change-req → BAT-017 재검증) - Follow-up Action: confirm-req-implemented(BAT-017). #### Validation Plan - BAT-017: 전량 취소 → holding 복귀, 부분 취소 → 원장 1건 + qty 차감 + cost basis 유지 단위. ### CHG-20260610-03 - Date: 2026-06-10 - Author: Justin Ko #### Change Summary - (change-req, dcy-022 실행 정책) 집행 루프에 두 가지 확장: ① **slippage dispatch**: `_dispatch` 가 슬롯의 `slippage_pct` 를 읽어 `entry_price*(1±pct)` 실효 지정가로 주문을 제출(매수 올림/매도 내림, KRX 호가단위). ② **timeout 취소**: `_poll` 이 dispatched-pending 슬롯의 `timeout_sec` 초과 시 `broker.cancel_order` 를 송신(best-effort, 취소-체결 race는 기존 is_terminal_reject/is_partial_cancel 경로로 수렴). Implemented → Approved 되돌림(신규 집행 로직 미구현, BAT-032 에서 재구현). #### Intent - 실행 정책(slippage + timeout)을 집행 루프에 배선해 미체결 고착 예방 + 과도한 불리 체결 방지. #### Acceptance Criteria Delta - Added: - dispatch 시 슬롯 `slippage_pct` 가 있으면 `limit_price*(1+pct)` (buy) / `limit_price*(1-pct)` (sell) 실효 지정가로 제출한다(`entry_price` 없으면 무시). - dispatched-pending 슬롯이 `timeout_sec` 를 초과하면 `broker.cancel_order` 를 송신하고, 다음 poll 에서 is_terminal_reject / is_partial_cancel 경로로 롤백/부분 보존이 수렴한다. - timeout/slippage 미지정 슬롯은 기존 dispatch·poll 경로와 동일(회귀 없음). - Updated: 없음 - Removed: 없음 #### Impacted Area Delta - Modules: `trex_core/application/execution.py`(`_dispatch` slippage, `_poll` timeout cancel), ExecutionResult(+timeout_cancelled) - Tests: tests/application/test_execution.py(slippage dispatch), test_execution_cancel.py(timeout cancel) #### Delivery Trace Delta - Batches: BAT-032 - Releases: none #### Revalidation Impact - Reverification Needed: yes (BAT-032 에서 완료 예정) - Existing Implementation Invalidated: no (신규 분기 추가, 기존 dispatch/poll 경로 보존) - Status Recommendation: revert-to-approved - Follow-up Action: BAT-032 구현 후 confirm-req-implemented. #### Validation Plan - BAT-032: slippage 실효 지정가 단위 + timeout 취소 → 롤백/부분 보존 단위 + 회귀. ### CHG-20260611-IMPL - Date: 2026-06-11 - Author: Justin Ko - Type: status - Summary: Approved → Implemented (confirm-req-implemented). 근거: BAT-032(release-candidate) verification — 실행 정책(timeout_sec·slippage_pct) 계약·집행·운영자 cancel 백스톱 전 AC acceptance mapping 존재(신규 71 tests), 단위 425 passed 회귀 없음, baseline 2문서 수동 확인(M5). Blocking Issues 없음.