Files
trex-core/docs/srs/Integration/req-013_order-execution-loop.md
T
genichinandClaude Opus 4.8 4746f74aae fix(broker): dcy-013 KIS 외부 취소 감지 + 부분 체결 회계 + stale 워치독 (BAT-017)
KIS 계좌에서 직접 매도 주문을 취소하면 poll_fill 이 cncl_yn 을 파싱하지 않아
슬롯이 pending_sell 에 영구히 갇히고 죽은 주문을 무한 폴링하던 버그(issue #9)
정정.

거버넌스: 전부 change-req (신규 REQ 없음, dcy-013 OQ-3).
- REQ-012: KIS poll_fill cncl_yn 파싱 → 외부 취소 감지. FillStatus.cancelled
  /is_partial_cancel 추가. 체결 0 취소→cancelled, 부분 체결 후 취소→partial+cancelled
- REQ-013: 집행 _on_partial_cancel — 체결분 원장 1회 + qty 차감(매도 잔여/매수 체결분)
  + holding 복귀 (OQ-1 A안). 전량 취소는 기존 롤백 경로 재사용
- REQ-018: 부분 체결분 원장 1회 기록 (_record_ledger 재사용)
- REQ-031: 잔여 포지션 정합 연계 (slot.qty ↔ 실 잔고, 과매도 방지)
- REQ-014: pending stale 워치독 Alert-only (TREX_PENDING_STALE_THRESHOLD,
  WARN+카운터, 상태 미변경) — 취소 감지 누락 backstop
- REQ-015: interface-contract/runtime-flows 정합

전량 취소는 holding 자동 복구(limit_price clear→재매도 시장가, dcy-012 연계).
KIS cncl_yn 실 규약은 운영 검증(미지 값 보수 처리 + 워치독 backstop).

검증: 단위 294 passed/32 skipped, 인프라 게이트(PG+RabbitMQ) 326 passed, ruff clean.
신규 test_kis_cancel(httpx stub) + test_execution_cancel(programmable broker).
BAT-017 release-candidate.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-08 14:11:49 +09:00

8.2 KiB

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 유지 단위.