1856 lines
43 KiB
Markdown
1856 lines
43 KiB
Markdown
# QuantBench System Specification
|
|
|
|
## System Overview
|
|
|
|
QuantBench는 개인 투자자를 위한 퀀트 트레이딩 플랫폼으로, 다중 계좌 관리, 전략 기반 자동매매, 리스크 관리, 성과 분석을 통합 제공합니다. 컨테이너 기반 자산 격리를 통해 하나의 계좌에서 여러 전략을 안전하게 병렬 운영할 수 있습니다.
|
|
|
|
---
|
|
|
|
## Phase 1: MVP (Minimum Viable Product)
|
|
|
|
**목표**: 안전하게 전략을 실행하고 리스크를 통제할 수 있는 기본 시스템 구축
|
|
|
|
### System Architecture
|
|
|
|
```
|
|
┌─────────────────────────────────────────────────────┐
|
|
│ User Interface │
|
|
└──────────────────┬──────────────────────────────────┘
|
|
│
|
|
┌──────────────────┴──────────────────────────────────┐
|
|
│ API Gateway │
|
|
└─┬────────┬────────┬────────┬────────┬──────────────┘
|
|
│ │ │ │ │
|
|
▼ ▼ ▼ ▼ ▼
|
|
┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐
|
|
│mgmt│ │stgy│ │schd│ │risk│ │data│
|
|
└─┬──┘ └─┬──┘ └─┬──┘ └─┬──┘ └─┬──┘
|
|
│ │ │ │ │
|
|
└───────┴───────┴───────┴───────┘
|
|
│
|
|
▼
|
|
┌──────────┐
|
|
│ balance │
|
|
└────┬─────┘
|
|
│
|
|
┌────────────┼────────────┐
|
|
▼ ▼ ▼
|
|
[API] [API] [API]
|
|
한국투자증권 삼성증권 키움증권
|
|
```
|
|
|
|
---
|
|
|
|
## 📦 Component Specifications - Phase 1
|
|
|
|
### 1. balance (계좌 관리)
|
|
|
|
**책임**: 증권사 API 통합 및 계좌 자산 관리
|
|
|
|
#### 주요 기능
|
|
|
|
**1.1 계좌 연동 관리**
|
|
- 증권사 API 인증 및 세션 관리
|
|
- 다중 계좌 등록/수정/삭제
|
|
- API 키 암호화 저장 및 갱신
|
|
|
|
**1.2 자산 조회**
|
|
```
|
|
getCurrentBalance(accountId: string): Balance
|
|
- 원화/외화 현금 잔고
|
|
- 보유 종목별 수량/평가액
|
|
- 매수 가능 금액
|
|
- 출금 가능 금액
|
|
|
|
getPortfolioSnapshot(accountId: string): Portfolio
|
|
- 자산 클래스별 비중 (주식/채권/현금 등)
|
|
- 종목별 손익률
|
|
- 총 자산 평가액
|
|
```
|
|
|
|
**1.3 시세 조회**
|
|
```
|
|
getCurrentPrice(symbol: string): Price
|
|
- 현재가, 시가, 고가, 저가
|
|
- 거래량
|
|
- 호가 정보 (매수/매도 5호가)
|
|
|
|
getHistoricalPrices(symbol: string, from: Date, to: Date): Price[]
|
|
- 일/주/월봉 데이터
|
|
- 조정 가격 (배당, 액면분할 반영)
|
|
```
|
|
|
|
**1.4 주문 처리**
|
|
```
|
|
placeOrder(order: Order): OrderResult
|
|
- 시장가/지정가/조건부 주문
|
|
- 주문 검증 (잔고 확인, 호가 단위 등)
|
|
- 주문 번호 반환
|
|
|
|
cancelOrder(orderId: string): boolean
|
|
- 미체결 주문 취소
|
|
|
|
getOrderStatus(orderId: string): OrderStatus
|
|
- 주문 상태 조회 (접수/체결/취소)
|
|
- 부분 체결 정보
|
|
```
|
|
|
|
**1.5 증권사 추상화 인터페이스**
|
|
```typescript
|
|
interface BrokerAdapter {
|
|
connect(credentials: Credentials): Promise<Session>
|
|
getBalance(accountId: string): Promise<Balance>
|
|
getQuote(symbol: string): Promise<Quote>
|
|
submitOrder(order: Order): Promise<OrderResult>
|
|
cancelOrder(orderId: string): Promise<boolean>
|
|
getOrderHistory(accountId: string, from: Date): Promise<Order[]>
|
|
}
|
|
|
|
// 구현체 예시
|
|
class KoreaInvestmentAdapter implements BrokerAdapter { ... }
|
|
class SamsungAdapter implements BrokerAdapter { ... }
|
|
class KiwoomAdapter implements BrokerAdapter { ... }
|
|
```
|
|
|
|
**데이터 모델**
|
|
```typescript
|
|
interface Account {
|
|
id: string
|
|
brokerId: string // 증권사 식별자
|
|
accountNumber: string
|
|
accountName: string
|
|
accountType: 'STOCK' | 'FUTURES' | 'FOREX'
|
|
credentials: EncryptedCredentials
|
|
isActive: boolean
|
|
createdAt: Date
|
|
}
|
|
|
|
interface Balance {
|
|
accountId: string
|
|
cash: {
|
|
krw: number
|
|
usd: number
|
|
// ... 기타 통화
|
|
}
|
|
positions: Position[]
|
|
totalEquity: number
|
|
buyingPower: number
|
|
timestamp: Date
|
|
}
|
|
|
|
interface Position {
|
|
symbol: string
|
|
quantity: number
|
|
averagePrice: number
|
|
currentPrice: number
|
|
marketValue: number
|
|
unrealizedPnL: number
|
|
realizedPnL: number
|
|
}
|
|
|
|
interface Order {
|
|
orderId?: string
|
|
accountId: string
|
|
symbol: string
|
|
side: 'BUY' | 'SELL'
|
|
orderType: 'MARKET' | 'LIMIT' | 'STOP'
|
|
quantity: number
|
|
price?: number
|
|
status: 'PENDING' | 'FILLED' | 'PARTIALLY_FILLED' | 'CANCELLED' | 'REJECTED'
|
|
filledQuantity?: number
|
|
averageFillPrice?: number
|
|
submittedAt?: Date
|
|
executedAt?: Date
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
### 2. mgmt (컨테이너 관리)
|
|
|
|
**책임**: 가상 자산 컨테이너 생성 및 운영 관리
|
|
|
|
#### 주요 기능
|
|
|
|
**2.1 컨테이너 생명주기 관리**
|
|
```
|
|
createContainer(config: ContainerConfig): Container
|
|
- 계좌 내 자산 할당
|
|
- 컨테이너 설정 (이름, 목표, 제약조건)
|
|
- 초기 자산 스냅샷 생성
|
|
|
|
updateContainer(id: string, config: Partial<ContainerConfig>): Container
|
|
- 설정 변경 (전략, 리밸런싱 주기 등)
|
|
- 변경 이력 기록
|
|
|
|
deleteContainer(id: string): boolean
|
|
- 컨테이너 비활성화
|
|
- 자산 원 계좌로 회수
|
|
```
|
|
|
|
**2.2 가상 자산 격리**
|
|
```
|
|
allocateAssets(containerId: string, allocation: AssetAllocation): boolean
|
|
- 실제 계좌 잔고에서 가상 할당
|
|
- 총 할당 금액 검증 (계좌 잔고 초과 방지)
|
|
|
|
getContainerBalance(containerId: string): VirtualBalance
|
|
- 컨테이너별 독립 잔고 조회
|
|
- 현금 + 보유 종목 평가
|
|
|
|
reconcileAssets(accountId: string): ReconciliationReport
|
|
- 실제 계좌 vs 컨테이너 총합 일치 확인
|
|
- 불일치 시 경고 및 조정
|
|
```
|
|
|
|
**2.3 컨테이너 간 자산 이동**
|
|
```
|
|
transferAssets(from: string, to: string, amount: number): Transfer
|
|
- 컨테이너 간 현금/종목 이전
|
|
- 거래 기록 생성
|
|
- 양쪽 컨테이너 밸런스 업데이트
|
|
```
|
|
|
|
**2.4 컨테이너 상태 모니터링**
|
|
```
|
|
getContainerStatus(containerId: string): ContainerStatus
|
|
- 현재 실행 중인 전략
|
|
- 마지막 리밸런싱 일시
|
|
- 활성/비활성 상태
|
|
- 에러/경고 메시지
|
|
```
|
|
|
|
**데이터 모델**
|
|
```typescript
|
|
interface Container {
|
|
id: string
|
|
accountId: string
|
|
name: string
|
|
description?: string
|
|
strategyId?: string // 연결된 전략
|
|
|
|
allocation: {
|
|
initialAmount: number
|
|
currentEquity: number
|
|
cashReserve: number // 최소 현금 보유량
|
|
}
|
|
|
|
constraints: {
|
|
maxSinglePositionPct: number // 단일 종목 최대 비중
|
|
maxDrawdown: number // 최대 허용 낙폭
|
|
allowedAssetClasses: string[] // 투자 가능 자산군
|
|
}
|
|
|
|
rebalancing: {
|
|
frequency: 'DAILY' | 'WEEKLY' | 'MONTHLY' | 'QUARTERLY'
|
|
dayOfWeek?: number // WEEKLY인 경우
|
|
dayOfMonth?: number // MONTHLY인 경우
|
|
autoExecute: boolean // 자동 실행 여부
|
|
}
|
|
|
|
status: 'ACTIVE' | 'PAUSED' | 'ARCHIVED'
|
|
createdAt: Date
|
|
lastRebalancedAt?: Date
|
|
}
|
|
|
|
interface VirtualBalance {
|
|
containerId: string
|
|
cash: number
|
|
positions: Position[]
|
|
totalValue: number
|
|
availableCash: number // 주문 가능 현금
|
|
allocatedValue: number // 실제 배정받은 금액
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
### 3. strategy (전략 관리)
|
|
|
|
**책임**: 투자 전략 구현, 백테스트, 버전 관리
|
|
|
|
#### 주요 기능
|
|
|
|
**3.1 전략 등록 및 관리**
|
|
```
|
|
registerStrategy(strategy: StrategyDefinition): Strategy
|
|
- 전략 코드/설정 등록
|
|
- 메타데이터 저장 (작성자, 설명, 파라미터)
|
|
- 초기 검증 (구문 오류, 필수 메서드 존재)
|
|
|
|
updateStrategy(id: string, version: StrategyVersion): Strategy
|
|
- 새 버전 생성
|
|
- 이전 버전 보존 (불변성)
|
|
- 변경 사항 추적
|
|
|
|
getStrategy(id: string, version?: string): Strategy
|
|
- 특정 버전 조회 (미지정 시 최신)
|
|
```
|
|
|
|
**3.2 전략 실행 엔진**
|
|
```
|
|
calculateSignals(strategyId: string, marketData: MarketData): Signal[]
|
|
- 현재 시장 상황 기반 매매 신호 생성
|
|
- 매수/매도/보유 결정
|
|
- 목표 비중 계산
|
|
|
|
generateOrders(containerId: string, signals: Signal[]): Order[]
|
|
- 신호를 실제 주문으로 변환
|
|
- 현재 포지션과 목표 포지션 차이 계산
|
|
- 주문 수량/가격 결정
|
|
```
|
|
|
|
**3.3 백테스트**
|
|
```
|
|
runBacktest(config: BacktestConfig): BacktestResult
|
|
- 과거 데이터 기반 전략 시뮬레이션
|
|
- 거래 비용, 슬리피지 반영
|
|
- 일별 포트폴리오 가치 계산
|
|
|
|
calculateMetrics(backtestResult: BacktestResult): PerformanceMetrics
|
|
- 총 수익률, CAGR
|
|
- 샤프 비율, 소르티노 비율
|
|
- 최대 낙폭 (MDD)
|
|
- 승률, 평균 수익/손실
|
|
- 변동성 (연율화)
|
|
```
|
|
|
|
**3.4 전략 파라미터 관리**
|
|
```
|
|
getParameters(strategyId: string): Parameter[]
|
|
- 전략에서 사용하는 파라미터 목록
|
|
- 파라미터 타입, 기본값, 범위
|
|
|
|
setParameters(strategyId: string, params: Record<string, any>): void
|
|
- 파라미터 값 설정
|
|
- 유효성 검증
|
|
```
|
|
|
|
**전략 인터페이스**
|
|
```typescript
|
|
interface StrategyInterface {
|
|
// 필수 구현 메서드
|
|
initialize(context: StrategyContext): void
|
|
generateSignals(data: MarketData): Signal[]
|
|
|
|
// 선택적 메서드
|
|
onMarketOpen?(): void
|
|
onMarketClose?(): void
|
|
onOrderFilled?(order: Order): void
|
|
}
|
|
|
|
// 내장 전략 예시
|
|
class BoldAssetAllocation implements StrategyInterface {
|
|
private params: {
|
|
stockAllocation: number // 주식 비중 (0-1)
|
|
bondAllocation: number // 채권 비중 (0-1)
|
|
rebalanceThreshold: number // 리밸런싱 임계값
|
|
}
|
|
|
|
initialize(context: StrategyContext) {
|
|
this.params = context.parameters
|
|
}
|
|
|
|
generateSignals(data: MarketData): Signal[] {
|
|
// 현재 포트폴리오와 목표 비중 비교
|
|
// 임계값 초과 시 리밸런싱 신호 생성
|
|
// ...
|
|
}
|
|
}
|
|
```
|
|
|
|
**데이터 모델**
|
|
```typescript
|
|
interface Strategy {
|
|
id: string
|
|
name: string
|
|
description: string
|
|
category: 'ASSET_ALLOCATION' | 'MOMENTUM' | 'VALUE' | 'ARBITRAGE' | 'CUSTOM'
|
|
|
|
versions: StrategyVersion[]
|
|
currentVersion: string
|
|
|
|
parameters: Parameter[]
|
|
requiredData: string[] // 필요한 데이터 종류
|
|
|
|
createdBy: string
|
|
createdAt: Date
|
|
isPublic: boolean
|
|
}
|
|
|
|
interface StrategyVersion {
|
|
version: string // "1.0.0"
|
|
code: string // 전략 구현 코드
|
|
changelog?: string
|
|
createdAt: Date
|
|
backtestResults?: BacktestResult[]
|
|
}
|
|
|
|
interface Signal {
|
|
symbol: string
|
|
action: 'BUY' | 'SELL' | 'HOLD'
|
|
targetWeight?: number // 목표 비중 (0-1)
|
|
targetQuantity?: number // 목표 수량
|
|
reason?: string // 신호 발생 이유
|
|
confidence?: number // 신호 신뢰도 (0-1)
|
|
generatedAt: Date
|
|
}
|
|
|
|
interface BacktestConfig {
|
|
strategyId: string
|
|
strategyVersion: string
|
|
startDate: Date
|
|
endDate: Date
|
|
initialCapital: number
|
|
universe: string[] // 투자 대상 종목
|
|
benchmark?: string // 벤치마크 (예: 'SPY')
|
|
|
|
costs: {
|
|
commission: number // 거래 수수료
|
|
slippage: number // 슬리피지 (bps)
|
|
}
|
|
}
|
|
|
|
interface BacktestResult {
|
|
strategyId: string
|
|
config: BacktestConfig
|
|
|
|
equity: {
|
|
date: Date
|
|
value: number
|
|
cash: number
|
|
positions: Record<string, number>
|
|
}[]
|
|
|
|
trades: {
|
|
date: Date
|
|
symbol: string
|
|
action: 'BUY' | 'SELL'
|
|
quantity: number
|
|
price: number
|
|
commission: number
|
|
}[]
|
|
|
|
metrics: PerformanceMetrics
|
|
runAt: Date
|
|
}
|
|
|
|
interface PerformanceMetrics {
|
|
totalReturn: number // %
|
|
cagr: number // %
|
|
sharpeRatio: number
|
|
sortinoRatio: number
|
|
maxDrawdown: number // %
|
|
volatility: number // % (annualized)
|
|
winRate: number // %
|
|
avgWin: number // %
|
|
avgLoss: number // %
|
|
profitFactor: number
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
### 4. scheduler (실행 스케줄러)
|
|
|
|
**책임**: 전략 실행 자동화 및 리밸런싱 관리
|
|
|
|
#### 주요 기능
|
|
|
|
**4.1 스케줄 관리**
|
|
```
|
|
createSchedule(containerId: string, schedule: ScheduleConfig): Schedule
|
|
- 컨테이너별 실행 계획 생성
|
|
- Cron 표현식 지원
|
|
- 시장 시간 고려 (장 전/후, 장 중)
|
|
|
|
updateSchedule(scheduleId: string, config: Partial<ScheduleConfig>): Schedule
|
|
- 스케줄 수정
|
|
|
|
pauseSchedule(scheduleId: string): boolean
|
|
resumeSchedule(scheduleId: string): boolean
|
|
- 일시 정지/재개
|
|
```
|
|
|
|
**4.2 실행 트리거**
|
|
```
|
|
executeStrategy(containerId: string, mode: 'AUTO' | 'MANUAL'): Execution
|
|
- 전략 실행 시작
|
|
- 신호 생성 → 리스크 체크 → 주문 생성 → 승인 처리
|
|
|
|
scheduleRebalancing(containerId: string): void
|
|
- 다음 리밸런싱 일정 등록
|
|
- 시장 휴일 자동 회피
|
|
```
|
|
|
|
**4.3 승인 워크플로우**
|
|
```
|
|
requestApproval(execution: Execution): ApprovalRequest
|
|
- 사용자 승인 요청 생성
|
|
- 예상 주문 내역, 비용 계산
|
|
- 알림 발송 (이메일/푸시)
|
|
|
|
approveExecution(requestId: string, approved: boolean): boolean
|
|
- 승인/거부 처리
|
|
- 승인 시 주문 실행
|
|
- 거부 시 로그 기록
|
|
|
|
autoExecuteWithNotification(execution: Execution): ExecutionResult
|
|
- 자동 실행 모드
|
|
- 실행 후 결과 알림
|
|
```
|
|
|
|
**4.4 실행 이력 관리**
|
|
```
|
|
getExecutionHistory(containerId: string, from: Date): Execution[]
|
|
- 과거 실행 기록 조회
|
|
|
|
getExecutionDetail(executionId: string): ExecutionDetail
|
|
- 실행 상세 정보 (생성된 주문, 체결 내역)
|
|
```
|
|
|
|
**데이터 모델**
|
|
```typescript
|
|
interface Schedule {
|
|
id: string
|
|
containerId: string
|
|
|
|
trigger: {
|
|
type: 'CRON' | 'INTERVAL' | 'EVENT'
|
|
expression?: string // Cron: "0 9 * * 1-5"
|
|
intervalMinutes?: number
|
|
event?: 'MARKET_OPEN' | 'MARKET_CLOSE'
|
|
}
|
|
|
|
executionMode: 'AUTO' | 'APPROVAL_REQUIRED'
|
|
|
|
constraints: {
|
|
marketHoursOnly: boolean
|
|
skipHolidays: boolean
|
|
minIntervalHours?: number // 최소 실행 간격
|
|
}
|
|
|
|
isActive: boolean
|
|
nextRun?: Date
|
|
lastRun?: Date
|
|
}
|
|
|
|
interface Execution {
|
|
id: string
|
|
containerId: string
|
|
strategyId: string
|
|
|
|
status: 'PENDING' | 'APPROVED' | 'REJECTED' | 'RUNNING' | 'COMPLETED' | 'FAILED'
|
|
|
|
signals: Signal[]
|
|
plannedOrders: Order[]
|
|
executedOrders: Order[]
|
|
|
|
estimatedCost: {
|
|
commission: number
|
|
totalValue: number
|
|
}
|
|
|
|
approvalRequest?: ApprovalRequest
|
|
|
|
startedAt?: Date
|
|
completedAt?: Date
|
|
error?: string
|
|
}
|
|
|
|
interface ApprovalRequest {
|
|
id: string
|
|
executionId: string
|
|
|
|
summary: {
|
|
numOrders: number
|
|
buyValue: number
|
|
sellValue: number
|
|
estimatedCommission: number
|
|
}
|
|
|
|
orders: Order[]
|
|
|
|
requestedAt: Date
|
|
expiresAt: Date
|
|
approvedAt?: Date
|
|
approvedBy?: string
|
|
decision?: 'APPROVED' | 'REJECTED'
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
### 5. data (데이터 관리) ⭐ NEW
|
|
|
|
**책임**: 시계열 데이터 수집, 저장, 제공
|
|
|
|
#### 주요 기능
|
|
|
|
**5.1 데이터 수집**
|
|
```
|
|
collectMarketData(symbols: string[], from: Date, to: Date): void
|
|
- 외부 데이터 소스에서 시세 수집
|
|
- 일/분봉 데이터 저장
|
|
- 증분 업데이트 (새로운 데이터만)
|
|
|
|
updateRealTimeData(symbols: string[]): void
|
|
- 실시간 시세 스트리밍
|
|
- 인메모리 캐시 업데이트
|
|
```
|
|
|
|
**5.2 데이터 제공**
|
|
```
|
|
getPriceHistory(symbol: string, from: Date, to: Date, interval: Interval): PriceBar[]
|
|
- 과거 가격 데이터 조회
|
|
- interval: '1m', '5m', '1h', '1d', '1w', '1M'
|
|
|
|
getLatestPrice(symbol: string): Price
|
|
- 최신 시세 (캐시 우선)
|
|
|
|
getMultipleSymbols(symbols: string[], date: Date): Record<string, Price>
|
|
- 특정 일자 여러 종목 시세
|
|
- 백테스트 최적화
|
|
```
|
|
|
|
**5.3 데이터 품질 관리**
|
|
```
|
|
validateData(symbol: string, from: Date, to: Date): ValidationReport
|
|
- 결측치 검사
|
|
- 이상치 탐지 (급등락, 거래량 0 등)
|
|
- 데이터 연속성 확인
|
|
|
|
adjustForCorporateActions(symbol: string): void
|
|
- 배당, 액면분할, 병합 반영
|
|
- 조정 가격 계산
|
|
|
|
fillMissingData(symbol: string, method: 'FORWARD_FILL' | 'INTERPOLATE'): void
|
|
- 결측치 보정
|
|
```
|
|
|
|
**5.4 데이터 소스 관리**
|
|
```
|
|
addDataSource(source: DataSourceConfig): DataSource
|
|
- 외부 데이터 제공자 연동 (Yahoo Finance, Alpha Vantage 등)
|
|
|
|
syncDataSource(sourceId: string): SyncResult
|
|
- 데이터 동기화
|
|
- 충돌 해결 전략
|
|
```
|
|
|
|
**데이터 모델**
|
|
```typescript
|
|
interface PriceBar {
|
|
symbol: string
|
|
timestamp: Date
|
|
open: number
|
|
high: number
|
|
low: number
|
|
close: number
|
|
volume: number
|
|
adjustedClose?: number // 조정 종가
|
|
}
|
|
|
|
interface DataSource {
|
|
id: string
|
|
name: string
|
|
provider: 'BROKER' | 'YAHOO' | 'ALPHA_VANTAGE' | 'CUSTOM'
|
|
|
|
config: {
|
|
apiKey?: string
|
|
endpoint?: string
|
|
rateLimit?: number // requests per minute
|
|
}
|
|
|
|
coverage: {
|
|
symbols: string[] // 지원 종목
|
|
intervals: string[] // 지원 주기
|
|
delay: number // 데이터 지연 시간 (분)
|
|
}
|
|
|
|
priority: number // 다중 소스 시 우선순위
|
|
isActive: boolean
|
|
}
|
|
|
|
interface ValidationReport {
|
|
symbol: string
|
|
period: { from: Date, to: Date }
|
|
|
|
issues: {
|
|
type: 'MISSING_DATA' | 'OUTLIER' | 'ZERO_VOLUME' | 'PRICE_GAP'
|
|
date: Date
|
|
description: string
|
|
severity: 'LOW' | 'MEDIUM' | 'HIGH'
|
|
}[]
|
|
|
|
completeness: number // 0-1
|
|
quality: 'EXCELLENT' | 'GOOD' | 'FAIR' | 'POOR'
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
### 6. risk (리스크 관리) ⭐ NEW
|
|
|
|
**책임**: 포지션 리스크 통제 및 사전 주문 검증
|
|
|
|
#### 주요 기능
|
|
|
|
**6.1 사전 주문 검증 (Pre-Trade Risk Check)**
|
|
```
|
|
validateOrder(order: Order, container: Container): RiskCheckResult
|
|
- 잔고 충분성 확인
|
|
- 포지션 사이즈 한도 검증
|
|
- 집중도 리스크 평가
|
|
- 레버리지 제한 확인
|
|
|
|
validateOrderBatch(orders: Order[], container: Container): RiskCheckResult[]
|
|
- 여러 주문의 통합 리스크 평가
|
|
- 주문 간 상호작용 고려
|
|
```
|
|
|
|
**6.2 포지션 리스크 모니터링**
|
|
```
|
|
calculatePositionRisk(containerId: string): PositionRisk
|
|
- 포지션별 VaR (Value at Risk)
|
|
- 포트폴리오 베타
|
|
- 섹터/산업 집중도
|
|
|
|
checkRiskLimits(containerId: string): LimitViolation[]
|
|
- 설정된 리스크 한도 위반 검사
|
|
- 위반 항목 및 심각도 반환
|
|
```
|
|
|
|
**6.3 손절/익절 관리**
|
|
```
|
|
setStopLoss(containerId: string, symbol: string, config: StopLossConfig): void
|
|
- 종목별 손절 설정
|
|
- 트레일링 스톱 지원
|
|
|
|
setTakeProfit(containerId: string, symbol: string, level: number): void
|
|
- 익절 목표 설정
|
|
|
|
checkStopConditions(containerId: string): StopTrigger[]
|
|
- 손절/익절 조건 충족 확인
|
|
- 자동 청산 주문 생성 준비
|
|
```
|
|
|
|
**6.4 리스크 한도 설정**
|
|
```
|
|
setRiskLimits(containerId: string, limits: RiskLimits): void
|
|
- 컨테이너별 리스크 한도 지정
|
|
- 글로벌 한도 vs 개별 한도
|
|
|
|
getRiskProfile(containerId: string): RiskProfile
|
|
- 현재 리스크 프로필 조회
|
|
- 한도 대비 현황
|
|
```
|
|
|
|
**6.5 포트폴리오 리스크 분석**
|
|
```
|
|
calculatePortfolioVaR(containerId: string, confidence: number, horizon: number): VaRResult
|
|
- 포트폴리오 VaR 계산 (역사적 방법, 파라메트릭 방법)
|
|
- confidence: 신뢰수준 (예: 0.95, 0.99)
|
|
- horizon: 기간 (일)
|
|
|
|
calculateCorrelationMatrix(containerId: string): CorrelationMatrix
|
|
- 보유 종목 간 상관관계
|
|
- 분산 효과 분석
|
|
|
|
stressTest(containerId: string, scenarios: Scenario[]): StressTestResult[]
|
|
- 시나리오별 손실 추정
|
|
- 극단 상황 대비
|
|
```
|
|
|
|
**데이터 모델**
|
|
```typescript
|
|
interface RiskLimits {
|
|
containerId: string
|
|
|
|
position: {
|
|
maxSinglePositionPct: number // 단일 종목 최대 비중 (%)
|
|
maxSectorPct: number // 단일 섹터 최대 비중 (%)
|
|
maxTotalLeverage: number // 최대 레버리지 배수
|
|
}
|
|
|
|
loss: {
|
|
maxDailyLossPct: number // 일일 최대 손실 (%)
|
|
maxDrawdownPct: number // 최대 낙폭 (%)
|
|
stopLossEnabled: boolean
|
|
}
|
|
|
|
exposure: {
|
|
maxLongExposure: number // 최대 롱 익스포저
|
|
maxShortExposure: number // 최대 숏 익스포저
|
|
maxGrossExposure: number // 최대 총 익스포저
|
|
}
|
|
}
|
|
|
|
interface RiskCheckResult {
|
|
passed: boolean
|
|
violations: {
|
|
rule: string
|
|
severity: 'BLOCKING' | 'WARNING'
|
|
message: string
|
|
currentValue: number
|
|
limitValue: number
|
|
}[]
|
|
recommendations?: string[]
|
|
}
|
|
|
|
interface PositionRisk {
|
|
containerId: string
|
|
|
|
positions: {
|
|
symbol: string
|
|
marketValue: number
|
|
weightPct: number
|
|
VaR95: number // 95% 신뢰수준 VaR
|
|
beta: number
|
|
sector: string
|
|
}[]
|
|
|
|
portfolio: {
|
|
totalValue: number
|
|
totalVaR95: number
|
|
beta: number
|
|
correlationRisk: number // 집중도 점수
|
|
}
|
|
|
|
limits: {
|
|
type: string
|
|
current: number
|
|
limit: number
|
|
utilizationPct: number
|
|
}[]
|
|
|
|
calculatedAt: Date
|
|
}
|
|
|
|
interface StopLossConfig {
|
|
type: 'FIXED' | 'TRAILING' | 'TIME_BASED'
|
|
|
|
// FIXED: 고정 가격/비율
|
|
fixedPrice?: number
|
|
fixedPct?: number // 매수가 대비 %
|
|
|
|
// TRAILING: 최고가 대비 추적
|
|
trailingPct?: number
|
|
|
|
// TIME_BASED: 기간 경과 후
|
|
holdingPeriodDays?: number
|
|
|
|
autoExecute: boolean // 자동 청산 여부
|
|
}
|
|
|
|
interface VaRResult {
|
|
confidence: number
|
|
horizon: number
|
|
VaR: number // 금액
|
|
VaRPct: number // 비율
|
|
method: 'HISTORICAL' | 'PARAMETRIC' | 'MONTE_CARLO'
|
|
calculatedAt: Date
|
|
}
|
|
|
|
interface Scenario {
|
|
name: string
|
|
description: string
|
|
changes: {
|
|
symbol: string
|
|
priceChangePct: number
|
|
}[]
|
|
}
|
|
|
|
interface StressTestResult {
|
|
scenario: Scenario
|
|
estimatedLoss: number
|
|
estimatedLossPct: number
|
|
affectedPositions: {
|
|
symbol: string
|
|
currentValue: number
|
|
projectedValue: number
|
|
lossPct: number
|
|
}[]
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## 🔄 Phase 1 Workflow Example
|
|
|
|
**전략 실행 플로우**:
|
|
```
|
|
1. [scheduler] 스케줄 트리거 발생
|
|
↓
|
|
2. [scheduler] 컨테이너 정보 조회 (mgmt)
|
|
↓
|
|
3. [strategy] 신호 생성 (data에서 시세 조회)
|
|
↓
|
|
4. [risk] 사전 리스크 체크
|
|
├─ PASS → 주문 생성
|
|
└─ FAIL → 실행 중단, 알림 발송
|
|
↓
|
|
5. [scheduler] 승인 요청 (AUTO인 경우 skip)
|
|
↓
|
|
6. [balance] 주문 제출
|
|
↓
|
|
7. [mgmt] 컨테이너 밸런스 업데이트
|
|
↓
|
|
8. [scheduler] 실행 결과 기록 및 알림
|
|
```
|
|
|
|
---
|
|
|
|
## Phase 2: Production Ready
|
|
|
|
**목표**: 실전 운영을 위한 모니터링, 분석, 알림 체계 구축
|
|
|
|
### Additional Components
|
|
|
|
---
|
|
|
|
## 📦 Component Specifications - Phase 2
|
|
|
|
### 7. analytics (성과 분석 및 리포팅) ⭐ NEW
|
|
|
|
**책임**: 실거래 성과 측정 및 리포팅
|
|
|
|
#### 주요 기능
|
|
|
|
**7.1 성과 측정**
|
|
```
|
|
calculatePerformance(containerId: string, period: DateRange): PerformanceReport
|
|
- 기간별 수익률 (일/주/월/분기/연)
|
|
- 벤치마크 대비 초과 수익
|
|
- 리스크 조정 수익률 (샤프, 소르티노)
|
|
|
|
getReturnsTimeseries(containerId: string, from: Date): TimeseriesData
|
|
- 일별 수익률 시계열
|
|
- 누적 수익률 차트 데이터
|
|
```
|
|
|
|
**7.2 귀속 분석 (Attribution Analysis)**
|
|
```
|
|
analyzeReturns(containerId: string, period: DateRange): AttributionReport
|
|
- 수익 원천 분해
|
|
- 자산 배분 효과
|
|
- 종목 선택 효과
|
|
- 타이밍 효과
|
|
- 섹터/테마별 기여도
|
|
```
|
|
|
|
**7.3 거래 분석**
|
|
```
|
|
analyzeTrades(containerId: string, from: Date): TradeAnalysis
|
|
- 총 거래 건수, 거래 회전율
|
|
- 승률, 손익비
|
|
- 평균 보유 기간
|
|
- 최대 연속 수익/손실
|
|
|
|
calculateTradingCosts(containerId: string, period: DateRange): CostAnalysis
|
|
- 총 수수료
|
|
- 슬리피지 추정
|
|
- 세금 (양도소득세 등)
|
|
- 순수익률 (비용 차감 후)
|
|
```
|
|
|
|
**7.4 리포트 생성**
|
|
```
|
|
generateReport(containerId: string, type: ReportType, period: DateRange): Report
|
|
- type: 'DAILY' | 'WEEKLY' | 'MONTHLY' | 'QUARTERLY' | 'ANNUAL'
|
|
- PDF/HTML 형식
|
|
- 자동 이메일 발송 옵션
|
|
|
|
scheduleReport(config: ReportSchedule): void
|
|
- 정기 리포트 자동 생성
|
|
```
|
|
|
|
**7.5 벤치마크 비교**
|
|
```
|
|
compareWithBenchmark(containerId: string, benchmarkSymbol: string, period: DateRange): ComparisonReport
|
|
- 누적 수익률 비교
|
|
- 추적 오차 (Tracking Error)
|
|
- 정보 비율 (Information Ratio)
|
|
- 상승/하락 시장 성과
|
|
```
|
|
|
|
**데이터 모델**
|
|
```typescript
|
|
interface PerformanceReport {
|
|
containerId: string
|
|
period: DateRange
|
|
|
|
returns: {
|
|
total: number // %
|
|
annualized: number // CAGR
|
|
daily: number
|
|
weekly: number
|
|
monthly: number
|
|
ytd: number
|
|
}
|
|
|
|
risk: {
|
|
volatility: number // annualized
|
|
sharpeRatio: number
|
|
sortinoRatio: number
|
|
maxDrawdown: number
|
|
calmarRatio: number
|
|
}
|
|
|
|
benchmark?: {
|
|
symbol: string
|
|
returns: number
|
|
excessReturn: number
|
|
beta: number
|
|
alpha: number
|
|
trackingError: number
|
|
informationRatio: number
|
|
}
|
|
|
|
generatedAt: Date
|
|
}
|
|
|
|
interface AttributionReport {
|
|
containerId: string
|
|
period: DateRange
|
|
|
|
totalReturn: number
|
|
|
|
attribution: {
|
|
assetAllocation: number // 자산 배분 효과
|
|
stockSelection: number // 종목 선택 효과
|
|
timing: number // 타이밍 효과
|
|
interaction: number // 상호작용 효과
|
|
}
|
|
|
|
sectorContribution: {
|
|
sector: string
|
|
weight: number
|
|
return: number
|
|
contribution: number
|
|
}[]
|
|
|
|
topContributors: {
|
|
symbol: string
|
|
contribution: number
|
|
}[]
|
|
|
|
topDetractors: {
|
|
symbol: string
|
|
contribution: number
|
|
}[]
|
|
}
|
|
|
|
interface TradeAnalysis {
|
|
containerId: string
|
|
period: DateRange
|
|
|
|
summary: {
|
|
totalTrades: number
|
|
winningTrades: number
|
|
losingTrades: number
|
|
winRate: number // %
|
|
|
|
avgWin: number // %
|
|
avgLoss: number // %
|
|
profitFactor: number // avgWin / avgLoss
|
|
|
|
avgHoldingPeriod: number // days
|
|
turnoverRate: number // annualized
|
|
}
|
|
|
|
longestWinStreak: number
|
|
longestLossStreak: number
|
|
|
|
largestWin: {
|
|
symbol: string
|
|
return: number
|
|
date: Date
|
|
}
|
|
|
|
largestLoss: {
|
|
symbol: string
|
|
return: number
|
|
date: Date
|
|
}
|
|
}
|
|
|
|
interface CostAnalysis {
|
|
period: DateRange
|
|
|
|
costs: {
|
|
commission: number
|
|
estimatedSlippage: number
|
|
tax: number
|
|
other: number
|
|
total: number
|
|
}
|
|
|
|
impact: {
|
|
grossReturn: number
|
|
netReturn: number
|
|
costDrag: number // bps
|
|
}
|
|
|
|
costByType: {
|
|
buy: number
|
|
sell: number
|
|
}
|
|
}
|
|
|
|
interface Report {
|
|
id: string
|
|
containerId: string
|
|
type: ReportType
|
|
period: DateRange
|
|
|
|
sections: {
|
|
summary: PerformanceSummary
|
|
positions: CurrentPositions
|
|
trades: RecentTrades
|
|
performance: PerformanceCharts
|
|
attribution: AttributionAnalysis
|
|
risk: RiskMetrics
|
|
}
|
|
|
|
format: 'PDF' | 'HTML' | 'JSON'
|
|
fileUrl?: string
|
|
generatedAt: Date
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
### 8. monitor (모니터링 및 알림) ⭐ NEW
|
|
|
|
**책임**: 시스템 상태 감시 및 이상 탐지
|
|
|
|
#### 주요 기능
|
|
|
|
**8.1 시스템 헬스 체크**
|
|
```
|
|
checkSystemHealth(): HealthStatus
|
|
- 각 컴포넌트 상태 확인
|
|
- API 연결 상태
|
|
- 데이터베이스 응답 시간
|
|
- 메모리/CPU 사용률
|
|
|
|
monitorApiConnections(): ConnectionStatus[]
|
|
- 증권사 API 연결 상태
|
|
- 데이터 소스 연결 상태
|
|
- 마지막 성공 시간
|
|
- 실패 시 재연결 시도
|
|
```
|
|
|
|
**8.2 이상 거래 탐지**
|
|
```
|
|
detectAnomalies(containerId: string): Anomaly[]
|
|
- 급격한 포지션 변화 (설정치 초과)
|
|
- 비정상적 주문 크기
|
|
- 예상치 못한 체결
|
|
- 시장 충격 (market impact) 과다
|
|
|
|
checkMarketConditions(): MarketAlert[]
|
|
- 극심한 변동성
|
|
- 유동성 부족
|
|
- 서킷브레이커 발동
|
|
- 시장 전체 급락/급등
|
|
```
|
|
|
|
**8.3 알림 관리**
|
|
```
|
|
sendAlert(alert: Alert): void
|
|
- 채널별 알림 발송 (이메일/SMS/푸시/Slack)
|
|
- 중요도별 라우팅
|
|
- 알림 이력 저장
|
|
|
|
configureAlertRules(rules: AlertRule[]): void
|
|
- 알림 조건 설정
|
|
- 임계값, 빈도 제한
|
|
- 수신자 그룹 관리
|
|
|
|
getAlertHistory(from: Date, severity?: AlertSeverity): Alert[]
|
|
- 과거 알림 조회
|
|
- 필터링 및 검색
|
|
```
|
|
|
|
**8.4 대시보드 데이터**
|
|
```
|
|
getDashboardData(): DashboardSnapshot
|
|
- 전체 계좌 요약
|
|
- 컨테이너별 상태
|
|
- 최근 실행 이력
|
|
- 활성 알림
|
|
|
|
getRealtimeMetrics(containerId: string): RealtimeMetrics
|
|
- 현재 P&L
|
|
- 당일 수익률
|
|
- 포지션 변화
|
|
- 리스크 지표
|
|
```
|
|
|
|
**8.5 성능 모니터링**
|
|
```
|
|
trackLatency(operation: string, duration: number): void
|
|
- 주요 작업 소요 시간 추적
|
|
- 주문 처리 지연 모니터링
|
|
|
|
logError(error: Error, context: any): void
|
|
- 에러 로깅 및 분류
|
|
- 스택 트레이스 저장
|
|
- 재발 패턴 분석
|
|
```
|
|
|
|
**데이터 모델**
|
|
```typescript
|
|
interface HealthStatus {
|
|
overall: 'HEALTHY' | 'DEGRADED' | 'DOWN'
|
|
|
|
components: {
|
|
name: string
|
|
status: 'UP' | 'DOWN' | 'SLOW'
|
|
responseTime?: number // ms
|
|
lastCheck: Date
|
|
message?: string
|
|
}[]
|
|
|
|
connections: {
|
|
broker: 'CONNECTED' | 'DISCONNECTED' | 'ERROR'
|
|
database: 'CONNECTED' | 'DISCONNECTED'
|
|
dataProviders: Record<string, 'CONNECTED' | 'DISCONNECTED'>
|
|
}
|
|
|
|
resources: {
|
|
cpuUsage: number // %
|
|
memoryUsage: number // %
|
|
diskUsage: number // %
|
|
}
|
|
|
|
checkedAt: Date
|
|
}
|
|
|
|
interface Anomaly {
|
|
type: 'POSITION_SPIKE' | 'UNUSUAL_ORDER' | 'UNEXPECTED_FILL' | 'HIGH_IMPACT'
|
|
severity: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL'
|
|
|
|
containerId: string
|
|
description: string
|
|
|
|
details: {
|
|
expected?: any
|
|
actual: any
|
|
threshold?: any
|
|
}
|
|
|
|
detectedAt: Date
|
|
resolved: boolean
|
|
}
|
|
|
|
interface Alert {
|
|
id: string
|
|
type: 'SYSTEM' | 'RISK' | 'EXECUTION' | 'PERFORMANCE' | 'ANOMALY'
|
|
severity: 'INFO' | 'WARNING' | 'ERROR' | 'CRITICAL'
|
|
|
|
title: string
|
|
message: string
|
|
|
|
source: string // 발생 컴포넌트
|
|
containerId?: string
|
|
|
|
channels: ('EMAIL' | 'SMS' | 'PUSH' | 'SLACK')[]
|
|
sentAt?: Date
|
|
|
|
acknowledged: boolean
|
|
acknowledgedAt?: Date
|
|
acknowledgedBy?: string
|
|
|
|
createdAt: Date
|
|
}
|
|
|
|
interface AlertRule {
|
|
id: string
|
|
name: string
|
|
description: string
|
|
|
|
condition: {
|
|
metric: string // 'drawdown', 'dailyLoss', 'positionSize', etc.
|
|
operator: '>' | '<' | '=' | '>=' | '<='
|
|
threshold: number
|
|
}
|
|
|
|
severity: AlertSeverity
|
|
channels: AlertChannel[]
|
|
|
|
throttle: {
|
|
enabled: boolean
|
|
minIntervalMinutes: number // 최소 알림 간격
|
|
}
|
|
|
|
isActive: boolean
|
|
}
|
|
|
|
interface DashboardSnapshot {
|
|
accounts: {
|
|
accountId: string
|
|
totalEquity: number
|
|
cashBalance: number
|
|
todayPnL: number
|
|
todayReturn: number
|
|
}[]
|
|
|
|
containers: {
|
|
containerId: string
|
|
name: string
|
|
status: 'ACTIVE' | 'PAUSED'
|
|
equity: number
|
|
todayReturn: number
|
|
activeStrategy: string
|
|
lastRebalanced: Date
|
|
}[]
|
|
|
|
recentExecutions: {
|
|
executionId: string
|
|
containerId: string
|
|
status: string
|
|
completedAt: Date
|
|
}[]
|
|
|
|
activeAlerts: Alert[]
|
|
|
|
systemHealth: 'HEALTHY' | 'DEGRADED' | 'DOWN'
|
|
|
|
timestamp: Date
|
|
}
|
|
|
|
interface RealtimeMetrics {
|
|
containerId: string
|
|
|
|
current: {
|
|
equity: number
|
|
cash: number
|
|
positionsCount: number
|
|
}
|
|
|
|
today: {
|
|
pnl: number
|
|
return: number
|
|
tradesCount: number
|
|
}
|
|
|
|
risk: {
|
|
currentDrawdown: number
|
|
VaR95: number
|
|
leverage: number
|
|
}
|
|
|
|
updatedAt: Date
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## 🔄 Phase 2 Enhanced Workflow
|
|
|
|
**성과 모니터링 플로우**:
|
|
```
|
|
1. [scheduler] 전략 실행 완료
|
|
↓
|
|
2. [analytics] 실시간 성과 계산
|
|
├─ 일일 수익률 업데이트
|
|
├─ 리스크 지표 재계산
|
|
└─ 벤치마크 대비 성과 비교
|
|
↓
|
|
3. [monitor] 이상 탐지
|
|
├─ 급격한 손실 → CRITICAL 알림
|
|
├─ 리스크 한도 근접 → WARNING 알림
|
|
└─ 정상 범위 → 로그만 기록
|
|
↓
|
|
4. [monitor] 대시보드 업데이트
|
|
↓
|
|
5. [analytics] 정기 리포트 생성 (일정에 따라)
|
|
```
|
|
|
|
---
|
|
|
|
## Phase 3: Enterprise Grade
|
|
|
|
**목표**: 규제 대응, 감사 추적, 고급 시뮬레이션
|
|
|
|
### Additional Components
|
|
|
|
---
|
|
|
|
## 📦 Component Specifications - Phase 3
|
|
|
|
### 9. audit (감사 및 로깅) ⭐ NEW
|
|
|
|
**책임**: 불변 감사 로그 및 규제 리포팅
|
|
|
|
#### 주요 기능
|
|
|
|
**9.1 감사 로그 기록**
|
|
```
|
|
logEvent(event: AuditEvent): void
|
|
- 모든 중요 이벤트 불변 저장
|
|
- 타임스탬프, 사용자, 작업 내용
|
|
- 변경 전/후 데이터
|
|
|
|
logOrderActivity(order: Order, action: OrderAction): void
|
|
- 주문 생성/수정/취소/체결
|
|
- 호가 정보 스냅샷
|
|
- 결정 근거 (전략 신호)
|
|
```
|
|
|
|
**9.2 변경 이력 추적**
|
|
```
|
|
trackConfigChange(entity: string, entityId: string, changes: any): void
|
|
- 컨테이너 설정 변경
|
|
- 전략 파라미터 수정
|
|
- 리스크 한도 조정
|
|
|
|
getChangeHistory(entity: string, entityId: string): ChangeLog[]
|
|
- 시간순 변경 이력
|
|
- 변경자, 사유 포함
|
|
```
|
|
|
|
**9.3 규제 리포팅**
|
|
```
|
|
generateComplianceReport(type: ComplianceReportType, period: DateRange): ComplianceReport
|
|
- 거래 내역 보고서
|
|
- 포지션 보유 명세
|
|
- 이상 거래 탐지 결과
|
|
|
|
exportAuditTrail(from: Date, to: Date, format: 'CSV' | 'JSON'): File
|
|
- 감사 추적 데이터 추출
|
|
- 외부 감사 대비
|
|
```
|
|
|
|
**9.4 데이터 보존 정책**
|
|
```
|
|
archiveOldData(cutoffDate: Date): ArchiveResult
|
|
- 오래된 데이터 아카이브
|
|
- 빠른 조회용 DB vs 장기 보관용 스토리지
|
|
|
|
retainCriticalData(dataType: string, retentionYears: number): void
|
|
- 법적 보존 기간 관리
|
|
- 자동 삭제 방지
|
|
```
|
|
|
|
**9.5 무결성 검증**
|
|
```
|
|
verifyAuditIntegrity(from: Date, to: Date): IntegrityReport
|
|
- 감사 로그 변조 검사
|
|
- 체인 연속성 확인
|
|
- 해시 검증
|
|
```
|
|
|
|
**데이터 모델**
|
|
```typescript
|
|
interface AuditEvent {
|
|
id: string
|
|
timestamp: Date
|
|
|
|
eventType: 'ORDER' | 'CONFIG_CHANGE' | 'EXECUTION' | 'LOGIN' | 'DATA_EXPORT'
|
|
action: string // 'CREATE', 'UPDATE', 'DELETE', 'EXECUTE'
|
|
|
|
userId?: string
|
|
containerId?: string
|
|
|
|
entity: string // 'Container', 'Strategy', 'Order', etc.
|
|
entityId: string
|
|
|
|
before?: any // 변경 전 상태
|
|
after?: any // 변경 후 상태
|
|
|
|
metadata: {
|
|
ipAddress?: string
|
|
userAgent?: string
|
|
reason?: string
|
|
}
|
|
|
|
hash: string // 무결성 검증용
|
|
previousHash?: string // 이전 이벤트 해시 (체인)
|
|
}
|
|
|
|
interface ChangeLog {
|
|
timestamp: Date
|
|
changedBy: string
|
|
field: string
|
|
oldValue: any
|
|
newValue: any
|
|
reason?: string
|
|
}
|
|
|
|
interface ComplianceReport {
|
|
type: 'TRADE_HISTORY' | 'POSITION_STATEMENT' | 'UNUSUAL_ACTIVITY'
|
|
period: DateRange
|
|
|
|
trades: {
|
|
date: Date
|
|
orderId: string
|
|
symbol: string
|
|
side: 'BUY' | 'SELL'
|
|
quantity: number
|
|
price: number
|
|
value: number
|
|
}[]
|
|
|
|
positions: {
|
|
symbol: string
|
|
quantity: number
|
|
averagePrice: number
|
|
marketValue: number
|
|
unrealizedPnL: number
|
|
}[]
|
|
|
|
unusualActivities: {
|
|
date: Date
|
|
type: string
|
|
description: string
|
|
resolution: string
|
|
}[]
|
|
|
|
generatedAt: Date
|
|
certifiedBy?: string
|
|
}
|
|
|
|
interface IntegrityReport {
|
|
period: DateRange
|
|
totalEvents: number
|
|
|
|
verification: {
|
|
hashChainValid: boolean
|
|
noGaps: boolean
|
|
noModifications: boolean
|
|
}
|
|
|
|
issues: {
|
|
eventId: string
|
|
issue: string
|
|
severity: 'LOW' | 'HIGH'
|
|
}[]
|
|
|
|
overall: 'PASS' | 'FAIL'
|
|
verifiedAt: Date
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
### 10. simulation (시뮬레이션 환경) ⭐ NEW
|
|
|
|
**책임**: 실전 배포 전 안전한 테스트 환경 제공
|
|
|
|
#### 주요 기능
|
|
|
|
**10.1 Paper Trading**
|
|
```
|
|
createPaperAccount(config: PaperAccountConfig): PaperAccount
|
|
- 가상 계좌 생성
|
|
- 초기 자본금 설정
|
|
- 실시간 시세 연동
|
|
|
|
executePaperTrade(order: Order): PaperOrderResult
|
|
- 가상 주문 실행
|
|
- 실제 호가 기반 체결 시뮬레이션
|
|
- 슬리피지 모델링
|
|
```
|
|
|
|
**10.2 전략 시뮬레이션**
|
|
```
|
|
runSimulation(config: SimulationConfig): SimulationResult
|
|
- 특정 기간 실전 시뮬레이션
|
|
- 다양한 시장 시나리오 테스트
|
|
- 컨테이너 설정 검증
|
|
|
|
compareStrategies(strategyIds: string[], config: SimulationConfig): ComparisonResult
|
|
- 여러 전략 동시 비교
|
|
- 동일 조건 시뮬레이션
|
|
- 상대 성과 분석
|
|
```
|
|
|
|
**10.3 파라미터 최적화**
|
|
```
|
|
optimizeParameters(strategyId: string, searchSpace: ParameterSpace): OptimizationResult
|
|
- 그리드 서치
|
|
- 랜덤 서치
|
|
- 베이지안 최적화
|
|
- 유전 알고리즘
|
|
|
|
validateOptimization(result: OptimizationResult, outOfSampleData: MarketData): ValidationResult
|
|
- 과최적화 검증
|
|
- Out-of-sample 테스트
|
|
- 워크포워드 분석
|
|
```
|
|
|
|
**10.4 시나리오 테스트**
|
|
```
|
|
testScenario(containerId: string, scenario: Scenario): ScenarioResult
|
|
- 특정 시장 상황 시뮬레이션
|
|
- 블랙스완 이벤트 대비
|
|
- 극단 변동성 테스트
|
|
|
|
runMonteCarloSimulation(containerId: string, iterations: number): MonteCarloResult
|
|
- 확률적 시뮬레이션
|
|
- 수익률 분포 추정
|
|
- 최악 시나리오 확률
|
|
```
|
|
|
|
**10.5 전환 지원**
|
|
```
|
|
promoteToProd(paperAccountId: string, realAccountId: string): MigrationPlan
|
|
- Paper → 실계좌 전환 계획
|
|
- 설정 검증
|
|
- 리스크 재확인
|
|
|
|
cloneContainer(sourceId: string, targetAccountId: string): Container
|
|
- 검증된 설정 복제
|
|
- 실계좌 적용
|
|
```
|
|
|
|
**데이터 모델**
|
|
```typescript
|
|
interface PaperAccount {
|
|
id: string
|
|
name: string
|
|
|
|
balance: {
|
|
initialCash: number
|
|
currentCash: number
|
|
positions: Position[]
|
|
totalEquity: number
|
|
}
|
|
|
|
settings: {
|
|
commissionModel: 'FIXED' | 'PERCENTAGE'
|
|
commissionRate: number
|
|
slippageModel: 'FIXED_BPS' | 'VOLUME_BASED'
|
|
slippageBps: number
|
|
}
|
|
|
|
isActive: boolean
|
|
createdAt: Date
|
|
}
|
|
|
|
interface SimulationConfig {
|
|
strategyId: string
|
|
startDate: Date
|
|
endDate: Date
|
|
|
|
initialCapital: number
|
|
universe: string[]
|
|
|
|
costs: {
|
|
commission: number
|
|
slippage: number
|
|
tax: number
|
|
}
|
|
|
|
constraints: RiskLimits
|
|
|
|
rebalanceFrequency: string
|
|
}
|
|
|
|
interface SimulationResult {
|
|
config: SimulationConfig
|
|
|
|
performance: PerformanceMetrics
|
|
|
|
equity: {
|
|
date: Date
|
|
value: number
|
|
}[]
|
|
|
|
trades: {
|
|
date: Date
|
|
symbol: string
|
|
action: 'BUY' | 'SELL'
|
|
quantity: number
|
|
price: number
|
|
}[]
|
|
|
|
drawdowns: {
|
|
start: Date
|
|
end: Date
|
|
depth: number // %
|
|
recovery: number // days
|
|
}[]
|
|
|
|
completedAt: Date
|
|
}
|
|
|
|
interface ParameterSpace {
|
|
parameters: {
|
|
name: string
|
|
type: 'INTEGER' | 'FLOAT' | 'CATEGORICAL'
|
|
min?: number
|
|
max?: number
|
|
step?: number
|
|
values?: any[]
|
|
}[]
|
|
}
|
|
|
|
interface OptimizationResult {
|
|
strategyId: string
|
|
searchSpace: ParameterSpace
|
|
|
|
bestParameters: Record<string, any>
|
|
bestMetric: number // 최적화 목표 지표값
|
|
|
|
trials: {
|
|
parameters: Record<string, any>
|
|
metrics: PerformanceMetrics
|
|
}[]
|
|
|
|
optimizationTime: number // seconds
|
|
|
|
warnings: {
|
|
overfitting: boolean
|
|
insufficientData: boolean
|
|
unstableParameters: string[]
|
|
}
|
|
}
|
|
|
|
interface MonteCarloResult {
|
|
iterations: number
|
|
|
|
returns: {
|
|
mean: number
|
|
median: number
|
|
std: number
|
|
percentiles: {
|
|
p5: number
|
|
p25: number
|
|
p75: number
|
|
p95: number
|
|
}
|
|
}
|
|
|
|
drawdowns: {
|
|
mean: number
|
|
max: number
|
|
percentiles: {
|
|
p95: number
|
|
p99: number
|
|
}
|
|
}
|
|
|
|
probabilities: {
|
|
profit: number // 수익 확률
|
|
loss10pct: number // 10% 이상 손실 확률
|
|
loss20pct: number
|
|
}
|
|
|
|
distribution: number[] // 수익률 히스토그램
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## 🔄 Phase 3 Advanced Workflow
|
|
|
|
**전략 검증 및 배포 플로우**:
|
|
```
|
|
1. [simulation] Paper Trading 시작
|
|
├─ 가상 계좌 생성
|
|
└─ 실시간 시세 연동
|
|
↓
|
|
2. [simulation] 1개월 Paper Trading 실행
|
|
├─ [strategy] 신호 생성
|
|
├─ [risk] 리스크 체크
|
|
└─ [simulation] 가상 주문 체결
|
|
↓
|
|
3. [analytics] Paper Trading 성과 분석
|
|
├─ 수익률, 리스크 지표 계산
|
|
└─ 백테스트 vs 실시간 비교
|
|
↓
|
|
4. [simulation] 파라미터 최적화 (필요 시)
|
|
├─ 그리드 서치 실행
|
|
└─ Out-of-sample 검증
|
|
↓
|
|
5. [simulation] 스트레스 테스트
|
|
├─ 극단 시나리오 시뮬레이션
|
|
└─ 몬테카를로 시뮬레이션
|
|
↓
|
|
6. [simulation] 실계좌 전환 계획 생성
|
|
├─ 설정 검증
|
|
└─ 리스크 재확인
|
|
↓
|
|
7. [audit] 전환 승인 및 기록
|
|
↓
|
|
8. [mgmt] 실계좌 컨테이너 생성
|
|
↓
|
|
9. [scheduler] 자동 실행 시작
|
|
↓
|
|
10. [monitor] 지속적 모니터링
|
|
└─ [audit] 모든 활동 기록
|
|
```
|
|
|
|
---
|
|
|
|
## 📊 Final System Architecture (All Phases)
|
|
|
|
```
|
|
┌────────────────────────────────────────────────────────────┐
|
|
│ User Interface │
|
|
│ (Web/Mobile Dashboard, Reports, Alerts, Admin Panel) │
|
|
└────────────────────────┬───────────────────────────────────┘
|
|
│
|
|
┌────────────────────────┴───────────────────────────────────┐
|
|
│ API Gateway │
|
|
│ (Authentication, Rate Limiting) │
|
|
└─┬────┬────┬────┬────┬────┬────┬────┬────┬────┬───────────┘
|
|
│ │ │ │ │ │ │ │ │ │
|
|
▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼ ▼
|
|
┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐┌───┐
|
|
│mgt││stg││sch││rsk││dat││ana││mon││aud││sim││bal│
|
|
└─┬─┘└─┬─┘└─┬─┘└─┬─┘└─┬─┘└─┬─┘└─┬─┘└─┬─┘└─┬─┘└─┬─┘
|
|
│ │ │ │ │ │ │ │ │ │
|
|
└────┴────┴────┴────┴────┴────┴────┴────┴────┘
|
|
│
|
|
┌────────────────┼────────────────┐
|
|
│ │ │
|
|
▼ ▼ ▼
|
|
┌─────────┐ ┌─────────┐ ┌─────────┐
|
|
│Message │ │Database │ │ Cache │
|
|
│ Queue │ │ Cluster │ │ (Redis) │
|
|
└─────────┘ └─────────┘ └─────────┘
|
|
│
|
|
┌────────────┼────────────┐
|
|
▼ ▼ ▼
|
|
[Broker [Broker [Broker
|
|
API 1] API 2] API 3]
|
|
```
|
|
|
|
**Component Legend**:
|
|
- **mgt**: Container Management
|
|
- **stg**: Strategy Management
|
|
- **sch**: Scheduler
|
|
- **rsk**: Risk Management
|
|
- **dat**: Data Management
|
|
- **ana**: Analytics
|
|
- **mon**: Monitor
|
|
- **aud**: Audit
|
|
- **sim**: Simulation
|
|
- **bal**: Balance (Broker Integration)
|
|
|
|
---
|
|
|
|
## 🎯 Implementation Roadmap
|
|
|
|
### Phase 1 Timeline (3-4 months)
|
|
- Week 1-4: balance + data 기본 구현
|
|
- Week 5-8: mgmt + strategy 핵심 기능
|
|
- Week 9-12: scheduler + risk
|
|
- Week 13-16: 통합 테스트 및 버그 수정
|
|
|
|
### Phase 2 Timeline (2-3 months)
|
|
- Week 1-4: analytics 구현
|
|
- Week 5-8: monitor + 알림 시스템
|
|
- Week 9-12: 대시보드 및 리포팅
|
|
|
|
### Phase 3 Timeline (2-3 months)
|
|
- Week 1-4: audit 시스템
|
|
- Week 5-8: simulation 환경
|
|
- Week 9-12: 최종 통합 및 규제 대응
|