Files
KArtSell.Aegis/docs/CURRENT/SLICE_SPECS/VS-12-SLICE_SPEC.md
T
kjh2064 b1e38ac374 feat: Phase 3 J/K/L (Sell Decision, Trade Execution, Portfolio Reconciliation) + fix pre-existing build/boot breakage
Completes VS-10/VS-12/VS-14 and makes the solution and Host actually
build and boot for the first time on this branch (main did not build
before this commit).

Root-cause fixes required to reach a green build/boot (not scoped to
J/K/L but blocking any verification of it):
- Restore Polly PackageVersion accidentally deleted from
  Directory.Packages.props (broke KArtSell.Host).
- Remove MediatR dependency from Compliance/VS-04 (package was never
  installed; ICommand/ICommandHandler/IMediator never existed) and
  wire Endpoint -> Handler directly per this repo's convention.
- Migrate FastEndpoints v5 API calls (SendOkAsync/SendAsync/
  SendCreatedAtAsync/SendNotFoundAsync, Description().WithName()) to
  the v7 Send.* fluent API across ~10 endpoint files.
- Fix migrations 0036/0038/0039/0040: rewritten from invalid T-SQL
  (`IF NOT EXISTS ... BEGIN ... END`) to idiomatic Postgres
  (`CREATE TABLE/INDEX IF NOT EXISTS`) — these could not apply to any
  fresh database before this fix.
- Collapse 3 duplicate cross-cutting abstractions that shadowed the
  BuildingBlocks versions and caused type-mismatch compile errors:
  IKrxDataService, IOutboxWriter (ReconcileTradeHandler), IClock
  (ApprovalWorkflow/ApprovalPolicy).
- Inject IClock (BuildingBlocks.Time) in place of direct
  DateTime.Now/UtcNow across 19 files to satisfy the architecture
  test AGENTS.md#DateTime-abstraction rule (13/13 architecture tests
  now pass, was 12/13).
- Register all new and previously-unregistered slices in
  Program.cs DI (SellDecision, TradeExecution, PortfolioReconciliation,
  Compliance, Features/ApprovalWorkflow) — the Host had never
  successfully completed a boot with this code present.
- Disable ("[DontRegister]") the older, route-colliding
  ApprovalWorkflow/ (Workstream H) endpoint set in favor of
  Features/ApprovalWorkflow/ (Workstream G, matches the documented
  Features/<Slice>/ convention); kept for its existing test coverage.
  See TECH_DEBT-017 for the follow-up decision needed.

Verified: dotnet build 0 errors/0 warnings; architecture tests 13/13;
unit tests 54/54 + 18/18; integration tests 34/36 (2 failures are a
local test-DB migration-journal/schema mismatch, not a code defect);
Host boots cleanly and registers all 34 endpoints.

New tech debt recorded: DEBT-017 (duplicate VS-03 implementation),
DEBT-018 (outbox write not co-transactional with entity write in
TradeExecution/PortfolioReconciliation), DEBT-019 (duplicate
BuildingBlocks-shadowing abstractions, partially resolved).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-07 19:53:38 +09:00

225 lines
5.4 KiB
Markdown

# VS-12: Trade Execution System (KIS Integration)
**Vertical Slice:** VS-12 (Trade Execution)
**Version:** 1.0 COMPLETE
**Date:** 2026-08-07
**Owner:** Backend Lead + Trading Ops
**Status:** ✅ READY FOR IMPLEMENTATION
**Depends On:** VS-10 (sell decisions), VS-03 (approval), VS-04 (audit)
---
## 📋 User Story
**As a** trading operations officer
**I want to** execute approved sell decisions through KIS API
**So that** portfolios are rebalanced automatically with full audit trail
**Acceptance Criteria:**
- ✅ Execute trade only after VS-03 approval
- ✅ Submit order to KIS, track order status
- ✅ Handle partial fills and slippage
- ✅ Confirm settlement and update cost basis
- ✅ Classify errors (transient/permanent/liquidity)
- ✅ All state changes logged (VS-04 audit)
---
## 🎯 Non-Goals
- ❌ Real-time market feeds (separate slice)
- ❌ Algorithm execution (beyond KIS API)
- ❌ Manual order override (compliance requirement)
- ❌ Cross-exchange routing (KIS only)
---
## 🔄 State Machine
```
PENDING (created from sell decision)
SUBMITTED (sent to KIS)
ACCEPTED (KIS confirmed receipt)
PARTIAL_FILLED / FULLY_FILLED (execution progress)
CONFIRMED (settlement confirmed)
RECONCILED (cost basis updated by VS-14)
```
---
## 📊 Data Schema
```sql
CREATE TABLE trades (
id UUID PRIMARY KEY,
sell_decision_id UUID NOT NULL REFERENCES sell_decisions(id),
kis_order_id VARCHAR(50), -- KIS-assigned order ID
status VARCHAR(50) NOT NULL, -- PENDING, SUBMITTED, ACCEPTED, FILLED, CONFIRMED, RECONCILED
quantity INT NOT NULL,
executed_quantity INT,
unit_price DECIMAL(15,2),
total_amount DECIMAL(18,2),
commission DECIMAL(15,2),
net_proceeds DECIMAL(18,2),
error_message TEXT,
kis_response JSONB, -- Full KIS API response (order details, fills, errors)
execution_timestamp TIMESTAMPTZ,
settlement_timestamp TIMESTAMPTZ,
published_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
correlation_id UUID NOT NULL,
revision INT NOT NULL DEFAULT 1
);
CREATE INDEX idx_trades_decision_id ON trades(sell_decision_id);
CREATE INDEX idx_trades_status ON trades(status);
CREATE INDEX idx_trades_kis_order_id ON trades(kis_order_id);
CREATE INDEX idx_trades_correlation_id ON trades(correlation_id);
```
---
## 🔐 API Contract
### POST /trades (Create Trade)
**Role:** System (after VS-03 approval)
**Request:**
```json
{
"sellDecisionId": "uuid",
"quantity": 1000,
"limitPrice": 50.00
}
```
**Response (202 Accepted):**
```json
{
"id": "trade-uuid",
"status": "PENDING",
"sellDecisionId": "uuid",
"quantity": 1000
}
```
### GET /trades (List)
**Query:** `status=FILLED&sellDecisionId=uuid`
**Response (200):**
```json
{
"items": [
{
"id": "trade-uuid",
"status": "CONFIRMED",
"quantity": 1000,
"executedQuantity": 1000,
"unitPrice": 49.95,
"totalAmount": 49950,
"commission": 50,
"netProceeds": 49900
}
]
}
```
---
## 🔄 KIS API Integration
**Service:** `KisTradeExecutionService`
```csharp
ExecuteTradeAsync(tradeId, quantity, limitPrice, correlationId)
GetOrderStatusAsync(kisOrderId, correlationId)
CancelOrderAsync(kisOrderId, reason, correlationId)
ConfirmSettlementAsync(kisOrderId, correlationId)
```
**Error Classification:**
- **Transient:** Network timeout, rate limit → Retry with backoff
- **Permanent:** Invalid order, insufficient funds → Log & alert
- **Liquidity:** Partial fill, slippage > threshold → Manual review queue
---
## 🔧 Handlers & Jobs
### SubmitTradeHandler
- Create trade record (status=PENDING)
- Submit to KIS
- Update status=SUBMITTED on success
- Classify error if failure
### PollTradeStatusJob (Hangfire q-evaluation)
- Poll KIS every 1 minute (configurable)
- Update trade status (ACCEPTED, FILLED)
- Trigger ConfirmSettlementHandler when FILLED
### ConfirmSettlementHandler
- Wait 1 business day after FILLED
- Confirm settlement with KIS
- Update status=CONFIRMED
- Emit event to VS-14 (reconciliation)
### ReconcileTradeHandler
- Receive settlement event
- Update status=RECONCILED
- Mark ready for VS-14 processing
---
## ✅ Governance Gates
### Pre-Merge Gates
- [x] SLICE_SPEC complete
- [x] API contract finalized
- [x] KIS error classification designed
- [x] Idempotency key strategy (kis_order_id dedup)
### Post-Merge Validation
- [ ] Unit tests: 12/12 PASS
- [ ] Integration tests: 8/8 PASS
- [ ] Failure scenario tests: 3/3 PASS
- [ ] No SELECT *, schema-qualified SQL
- [ ] Immutable trades (INSERT-only)
- [ ] Correlation_id traceability
---
## 🛡️ Security & Compliance
**Immutability Guarantees:**
- INSERT-only trade records (no UPDATE)
- Timestamp immutable after insertion
- kis_response JSONB for full audit trail
**Error Classification:**
- Transient: Network issues, retryable
- Permanent: Invalid input, authorization
- Liquidity: Partial fills, slippage
**RBAC:**
- System role: Submit trades (via VS-03 approval)
- Operations: View & monitor execution
- Audit: Query immutable trail
---
## 📋 Related Specifications
- **VS-10:** Sell Decision (generates trades)
- **VS-03:** Approval Workflow (prerequisite)
- **VS-04:** Audit Trail (logs all state changes)
- **VS-14:** Portfolio Reconciliation (consumes trade settlement)
---
**Co-Authored-By:** Claude Haiku 4.5 <noreply@anthropic.com>
**Status:** ✅ READY FOR IMPLEMENTATION
**Next:** Database migration, KIS service implementation