Compare commits
44 Commits
feature/is
...
feature/is
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4660310ee4 | ||
|
|
c383a411ff | ||
| 7b3ba27ef7 | |||
|
|
6ff887c047 | ||
| 219eef6388 | |||
|
|
9d7ca12275 | ||
|
|
ccb00ee77d | ||
| b1b728f62e | |||
|
|
df12be1305 | ||
| 6a6d3bd631 | |||
|
|
7aa5fedc12 | ||
|
|
3e777a5ab8 | ||
| 6f93258983 | |||
|
|
82167c5b8a | ||
| f87c4dc2f0 | |||
|
|
8af5f564c3 | ||
| 06e4fc5597 | |||
|
|
b697b6d515 | ||
| 42db5b3cc1 | |||
|
|
f252a84d65 | ||
| adc5211fd2 | |||
|
|
67e0e8df41 | ||
| ffdb99c6c7 | |||
|
|
ce5ea5abde | ||
| 5ae302b083 | |||
|
|
d31a61cd0b | ||
|
|
1c7a17320c | ||
| f58d42fdb0 | |||
|
|
0b20251de0 | ||
| bffe6e9288 | |||
|
|
0146d1bf8a | ||
| 497564e75c | |||
|
|
988a56c07c | ||
| c9f1345e3c | |||
|
|
8c492eae3a | ||
| 271c592a46 | |||
|
|
a063bd9d10 | ||
| 847456e0af | |||
|
|
a3a9fd1f24 | ||
|
|
f34117bc81 | ||
| 17e012cd04 | |||
|
|
a030dcc0dc | ||
|
|
d1698dee33 | ||
| 8a8ba3b0cb |
56
docs/ouroboros/00_validation_system.md
Normal file
56
docs/ouroboros/00_validation_system.md
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
<!--
|
||||||
|
Doc-ID: DOC-VAL-001
|
||||||
|
Version: 1.0.0
|
||||||
|
Status: active
|
||||||
|
Owner: strategy
|
||||||
|
Updated: 2026-02-26
|
||||||
|
-->
|
||||||
|
|
||||||
|
# 문서 검증 시스템
|
||||||
|
|
||||||
|
본 문서는 문서 간 허위 내용, 수치 충돌, 구현 불가능 지시를 사전에 제거하기 위한 검증 규칙이다.
|
||||||
|
|
||||||
|
## 검증 목표
|
||||||
|
|
||||||
|
- 단일 진실원장 기준으로 모든 지시서의 수치/규칙 정합성 보장
|
||||||
|
- 설계 문장과 코드 작업 지시 간 추적성 보장
|
||||||
|
- 테스트 미정의 상태에서 구현 착수 금지
|
||||||
|
|
||||||
|
## 불일치 유형 정의
|
||||||
|
|
||||||
|
- `RULE-DOC-001`: 정의되지 않은 요구사항 ID 사용
|
||||||
|
- `RULE-DOC-002`: 동일 요구사항 ID에 상충되는 값(예: 슬리피지 수치) 기술
|
||||||
|
- `RULE-DOC-003`: 시간대 미표기 또는 KST/UTC 혼용 지시
|
||||||
|
- `RULE-DOC-004`: 주문 정책과 리스크 정책 충돌(예: 저유동 세션 시장가 허용)
|
||||||
|
- `RULE-DOC-005`: 구현 태스크에 테스트 ID 미연결
|
||||||
|
- `RULE-DOC-006`: 문서 라우팅 링크 깨짐
|
||||||
|
|
||||||
|
## 검증 파이프라인
|
||||||
|
|
||||||
|
1. 정적 검사 (자동)
|
||||||
|
- 대상: `docs/ouroboros/*.md`
|
||||||
|
- 검사: 메타데이터, 링크 유효성, ID 정의/참조 일치, REQ-추적성 매핑
|
||||||
|
- 도구: `scripts/validate_ouroboros_docs.py`
|
||||||
|
|
||||||
|
2. 추적성 검사 (자동 + 수동)
|
||||||
|
- 자동: `REQ-*`가 최소 1개 `TASK-*`와 1개 `TEST-*`에 연결되었는지 확인
|
||||||
|
- 수동: 정책 충돌 후보를 PR 체크리스트로 검토
|
||||||
|
|
||||||
|
3. 도메인 무결성 검사 (수동)
|
||||||
|
- KIS 점검시간 회피, 주문 유형 강제, Kill Switch 순서, 환율 정책이 동시에 존재하는지 점검
|
||||||
|
- 백테스트 체결가가 보수 가정인지 점검
|
||||||
|
|
||||||
|
## 변경 통제 규칙
|
||||||
|
|
||||||
|
- `REQ-*` 추가/수정 시 반드시 `01_requirements_registry.md` 먼저 변경
|
||||||
|
- `TASK-*` 수정 시 반드시 `40_acceptance_and_test_plan.md`의 대응 테스트를 동시 수정
|
||||||
|
- 충돌 발생 시 우선순위: `requirements_registry > phase execution > code work order`
|
||||||
|
|
||||||
|
적용 룰셋:
|
||||||
|
- `RULE-DOC-001` `RULE-DOC-002` `RULE-DOC-003` `RULE-DOC-004` `RULE-DOC-005` `RULE-DOC-006`
|
||||||
|
|
||||||
|
## PR 게이트
|
||||||
|
|
||||||
|
- `python3 scripts/validate_ouroboros_docs.py` 성공
|
||||||
|
- 신규/변경 `REQ-*`가 테스트 기준(`TEST-*`)과 연결됨
|
||||||
|
- 원본 계획(v2/v3)과 모순 없음
|
||||||
39
docs/ouroboros/01_requirements_registry.md
Normal file
39
docs/ouroboros/01_requirements_registry.md
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
<!--
|
||||||
|
Doc-ID: DOC-REQ-001
|
||||||
|
Version: 1.0.0
|
||||||
|
Status: active
|
||||||
|
Owner: strategy
|
||||||
|
Updated: 2026-02-26
|
||||||
|
-->
|
||||||
|
|
||||||
|
# 요구사항 원장 (Single Source of Truth)
|
||||||
|
|
||||||
|
이 문서의 ID가 계획/구현/테스트 전 문서에서 참조되는 유일한 요구사항 집합이다.
|
||||||
|
|
||||||
|
## v2 핵심 요구사항
|
||||||
|
|
||||||
|
- `REQ-V2-001`: 상태는 `HOLDING`, `BE_LOCK`, `ARMED`, `EXITED` 4단계여야 한다.
|
||||||
|
- `REQ-V2-002`: 상태 전이는 매 틱/바 평가 시 최상위 상태로 즉시 승격되어야 한다.
|
||||||
|
- `REQ-V2-003`: `EXITED` 조건은 모든 상태보다 우선 평가되어야 한다.
|
||||||
|
- `REQ-V2-004`: 청산 로직은 Hard Stop, BE Lock, ATR Trailing, 모델 확률 보조 트리거를 포함해야 한다.
|
||||||
|
- `REQ-V2-005`: 라벨링은 Triple Barrier(Upper/Lower/Time) 방식이어야 한다.
|
||||||
|
- `REQ-V2-006`: 검증은 Walk-forward + Purge/Embargo를 강제한다.
|
||||||
|
- `REQ-V2-007`: 백테스트는 비용/슬리피지/체결실패를 반영하지 않으면 채택 불가다.
|
||||||
|
- `REQ-V2-008`: Kill Switch는 신규주문차단 -> 미체결취소 -> 재조회 -> 리스크축소 -> 스냅샷 순서다.
|
||||||
|
|
||||||
|
## v3 핵심 요구사항
|
||||||
|
|
||||||
|
- `REQ-V3-001`: 모든 신호/주문/로그는 `session_id`를 포함해야 한다.
|
||||||
|
- `REQ-V3-002`: 세션 전환 시 리스크 파라미터 재로딩이 수행되어야 한다.
|
||||||
|
- `REQ-V3-003`: 브로커 블랙아웃 시간대에는 신규 주문이 금지되어야 한다.
|
||||||
|
- `REQ-V3-004`: 블랙아웃 중 신호는 Queue에 적재되고, 복구 후 유효성 재검증을 거친다.
|
||||||
|
- `REQ-V3-005`: 저유동 세션(`NXT_AFTER`, `US_PRE`, `US_DAY`, `US_AFTER`)은 시장가 주문 금지다.
|
||||||
|
- `REQ-V3-006`: 백테스트 체결가는 불리한 방향 체결 가정을 기본으로 한다.
|
||||||
|
- `REQ-V3-007`: US 운용은 환율 손익 분리 추적과 통화 버퍼 정책을 포함해야 한다.
|
||||||
|
- `REQ-V3-008`: 마감/오버나잇 규칙은 Kill Switch와 충돌 없이 연동되어야 한다.
|
||||||
|
|
||||||
|
## 공통 운영 요구사항
|
||||||
|
|
||||||
|
- `REQ-OPS-001`: 타임존은 모든 시간 필드에 명시(KST/UTC)되어야 한다.
|
||||||
|
- `REQ-OPS-002`: 문서의 수치 정책은 원장에서만 변경한다.
|
||||||
|
- `REQ-OPS-003`: 구현 태스크는 반드시 테스트 태스크를 동반한다.
|
||||||
63
docs/ouroboros/10_phase_v2_execution.md
Normal file
63
docs/ouroboros/10_phase_v2_execution.md
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
<!--
|
||||||
|
Doc-ID: DOC-PHASE-V2-001
|
||||||
|
Version: 1.0.0
|
||||||
|
Status: active
|
||||||
|
Owner: strategy
|
||||||
|
Updated: 2026-02-26
|
||||||
|
-->
|
||||||
|
|
||||||
|
# v2 실행 지시서 (설계 -> 코드)
|
||||||
|
|
||||||
|
참조 요구사항: `REQ-V2-001` `REQ-V2-002` `REQ-V2-003` `REQ-V2-004` `REQ-V2-005` `REQ-V2-006` `REQ-V2-007` `REQ-V2-008` `REQ-OPS-001` `REQ-OPS-002` `REQ-OPS-003`
|
||||||
|
|
||||||
|
## 단계 1: 도메인 모델 확정
|
||||||
|
|
||||||
|
- `TASK-V2-001`: 상태머신 enum/전이 이벤트/전이 사유 스키마 설계
|
||||||
|
- `TASK-V2-002`: `position_state` 스냅샷 구조(현재상태, peak, stops, last_reason) 정의
|
||||||
|
- `TASK-V2-003`: 청산 판단 입력 DTO(가격, ATR, pred_prob, liquidity_signal) 정의
|
||||||
|
|
||||||
|
완료 기준:
|
||||||
|
- 상태와 전이 사유가 로그/DB에서 재현 가능
|
||||||
|
- `REQ-V2-001`~`003`을 코드 타입 수준에서 강제
|
||||||
|
|
||||||
|
## 단계 2: 청산 엔진 구현
|
||||||
|
|
||||||
|
- `TASK-V2-004`: 우선순위 기반 전이 함수 구현(`evaluate_exit_first` -> `promote_state`)
|
||||||
|
- `TASK-V2-005`: Hard Stop/BE Lock/ATR Trailing 결합 로직 구현
|
||||||
|
- `TASK-V2-006`: 모델 확률 신호를 보조 트리거로 결합(단독 청산 금지)
|
||||||
|
|
||||||
|
완료 기준:
|
||||||
|
- 갭 상황에서 다중 조건 동시 충족 시 최상위 상태로 단번 전이
|
||||||
|
- `REQ-V2-004` 준수
|
||||||
|
|
||||||
|
## 단계 3: 라벨링/학습 데이터 파이프라인
|
||||||
|
|
||||||
|
- `TASK-V2-007`: Triple Barrier 라벨러 구현(장벽 선터치 우선)
|
||||||
|
- `TASK-V2-008`: 피처 구간/라벨 구간 분리 검증 유틸 구현
|
||||||
|
- `TASK-V2-009`: 라벨 생성 로그(진입시각, 터치장벽, 만기장벽) 기록
|
||||||
|
|
||||||
|
완료 기준:
|
||||||
|
- look-ahead 차단 증빙 로그 확보
|
||||||
|
- `REQ-V2-005` 충족
|
||||||
|
|
||||||
|
## 단계 4: 검증 프레임워크
|
||||||
|
|
||||||
|
- `TASK-V2-010`: Walk-forward split + Purge/Embargo 분할기 구현
|
||||||
|
- `TASK-V2-011`: 베이스라인(`B0`,`B1`,`M1`) 비교 리포트 포맷 구현
|
||||||
|
- `TASK-V2-012`: 체결 비용/슬리피지/실패 반영 백테스트 옵션 강제
|
||||||
|
|
||||||
|
완료 기준:
|
||||||
|
- `REQ-V2-006`, `REQ-V2-007` 충족
|
||||||
|
|
||||||
|
## 단계 5: Kill Switch 통합
|
||||||
|
|
||||||
|
- `TASK-V2-013`: Kill Switch 순차 실행 오케스트레이터 구현 (`src/core/risk_manager.py` 수정 금지)
|
||||||
|
- `TASK-V2-014`: 주문 차단 플래그/미체결 취소/재조회 재시도 로직 구현
|
||||||
|
- `TASK-V2-015`: 스냅샷/알림/복구 진입 절차 구현
|
||||||
|
|
||||||
|
완료 기준:
|
||||||
|
- `REQ-V2-008` 순서 일치
|
||||||
|
|
||||||
|
라우팅:
|
||||||
|
- 코드 지시 상세: [30_code_level_work_orders.md](./30_code_level_work_orders.md)
|
||||||
|
- 테스트 상세: [40_acceptance_and_test_plan.md](./40_acceptance_and_test_plan.md)
|
||||||
60
docs/ouroboros/20_phase_v3_execution.md
Normal file
60
docs/ouroboros/20_phase_v3_execution.md
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
<!--
|
||||||
|
Doc-ID: DOC-PHASE-V3-001
|
||||||
|
Version: 1.0.0
|
||||||
|
Status: active
|
||||||
|
Owner: strategy
|
||||||
|
Updated: 2026-02-26
|
||||||
|
-->
|
||||||
|
|
||||||
|
# v3 실행 지시서 (세션 확장)
|
||||||
|
|
||||||
|
참조 요구사항: `REQ-V3-001` `REQ-V3-002` `REQ-V3-003` `REQ-V3-004` `REQ-V3-005` `REQ-V3-006` `REQ-V3-007` `REQ-V3-008` `REQ-OPS-001` `REQ-OPS-002` `REQ-OPS-003`
|
||||||
|
|
||||||
|
## 단계 1: 세션 엔진
|
||||||
|
|
||||||
|
- `TASK-V3-001`: `session_id` 분류기 구현(KR/US 확장 세션)
|
||||||
|
- `TASK-V3-002`: 세션 전환 훅에서 리스크 파라미터 재로딩 구현
|
||||||
|
- `TASK-V3-003`: 로그/DB 스키마에 `session_id` 필드 강제
|
||||||
|
|
||||||
|
완료 기준:
|
||||||
|
- `REQ-V3-001`, `REQ-V3-002` 충족
|
||||||
|
|
||||||
|
## 단계 2: 블랙아웃/복구 제어
|
||||||
|
|
||||||
|
- `TASK-V3-004`: 블랙아웃 윈도우 정책 로더 구현(설정 기반)
|
||||||
|
- `TASK-V3-005`: 블랙아웃 중 신규 주문 차단 + 의도 큐 적재 구현
|
||||||
|
- `TASK-V3-006`: 복구 시 동기화(잔고/미체결/체결) 후 큐 재검증 실행
|
||||||
|
|
||||||
|
완료 기준:
|
||||||
|
- `REQ-V3-003`, `REQ-V3-004` 충족
|
||||||
|
|
||||||
|
## 단계 3: 주문 정책 강화
|
||||||
|
|
||||||
|
- `TASK-V3-007`: 세션별 주문 타입 매트릭스 구현
|
||||||
|
- `TASK-V3-008`: 저유동 세션 시장가 주문 하드 차단
|
||||||
|
- `TASK-V3-009`: 재호가 간격/횟수 제한 및 주문 철회 조건 구현
|
||||||
|
|
||||||
|
완료 기준:
|
||||||
|
- `REQ-V3-005` 충족
|
||||||
|
|
||||||
|
## 단계 4: 비용/체결 모델 정교화
|
||||||
|
|
||||||
|
- `TASK-V3-010`: 세션별 슬리피지/비용 테이블 엔진 반영
|
||||||
|
- `TASK-V3-011`: 불리한 체결 가정(상대 호가 방향) 체결기 구현
|
||||||
|
- `TASK-V3-012`: 시나리오별 체결 실패/부분체결 모델 반영
|
||||||
|
|
||||||
|
완료 기준:
|
||||||
|
- `REQ-V3-006` 충족
|
||||||
|
|
||||||
|
## 단계 5: 환율/오버나잇/Kill Switch 연동
|
||||||
|
|
||||||
|
- `TASK-V3-013`: 전략 PnL과 FX PnL 분리 회계 구현
|
||||||
|
- `TASK-V3-014`: USD/KRW 버퍼 규칙 위반 시 신규 진입 제한 구현
|
||||||
|
- `TASK-V3-015`: 오버나잇 예외와 Kill Switch 우선순위 통합
|
||||||
|
|
||||||
|
완료 기준:
|
||||||
|
- `REQ-V3-007`, `REQ-V3-008` 충족
|
||||||
|
|
||||||
|
라우팅:
|
||||||
|
- 코드 지시 상세: [30_code_level_work_orders.md](./30_code_level_work_orders.md)
|
||||||
|
- 테스트 상세: [40_acceptance_and_test_plan.md](./40_acceptance_and_test_plan.md)
|
||||||
59
docs/ouroboros/30_code_level_work_orders.md
Normal file
59
docs/ouroboros/30_code_level_work_orders.md
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
<!--
|
||||||
|
Doc-ID: DOC-CODE-001
|
||||||
|
Version: 1.0.0
|
||||||
|
Status: active
|
||||||
|
Owner: strategy
|
||||||
|
Updated: 2026-02-26
|
||||||
|
-->
|
||||||
|
|
||||||
|
# 코드 레벨 작업 지시서
|
||||||
|
|
||||||
|
본 문서는 파일 단위 구현 지시서다. 모든 작업은 요구사항 ID와 테스트 ID를 포함해야 한다.
|
||||||
|
|
||||||
|
제약:
|
||||||
|
- `src/core/risk_manager.py`는 READ-ONLY로 간주하고 수정하지 않는다.
|
||||||
|
- Kill Switch는 별도 모듈(예: `src/core/kill_switch.py`)로 추가하고 상위 실행 루프에서 연동한다.
|
||||||
|
|
||||||
|
## 구현 단위 A: 상태기계/청산
|
||||||
|
|
||||||
|
- `TASK-CODE-001` (`REQ-V2-001`,`REQ-V2-002`,`REQ-V2-003`): `src/strategy/`에 상태기계 모듈 추가
|
||||||
|
- `TASK-CODE-002` (`REQ-V2-004`): ATR/BE/Hard Stop 결합 청산 함수 추가
|
||||||
|
- `TASK-CODE-003` (`REQ-V2-008`): Kill Switch 오케스트레이터를 `src/core/kill_switch.py`에 추가
|
||||||
|
- `TEST-CODE-001`: 갭 점프 시 최고상태 승격 테스트
|
||||||
|
- `TEST-CODE-002`: EXIT 우선순위 테스트
|
||||||
|
|
||||||
|
## 구현 단위 B: 라벨링/검증
|
||||||
|
|
||||||
|
- `TASK-CODE-004` (`REQ-V2-005`): Triple Barrier 라벨러 모듈 추가(`src/analysis/` 또는 `src/strategy/`)
|
||||||
|
- `TASK-CODE-005` (`REQ-V2-006`): Walk-forward + Purge/Embargo 분할 유틸 추가
|
||||||
|
- `TASK-CODE-006` (`REQ-V2-007`): 백테스트 실행기에서 비용/슬리피지 옵션 필수화
|
||||||
|
- `TEST-CODE-003`: 라벨 선터치 우선 테스트
|
||||||
|
- `TEST-CODE-004`: 누수 차단 테스트
|
||||||
|
|
||||||
|
## 구현 단위 C: 세션/주문 정책
|
||||||
|
|
||||||
|
- `TASK-CODE-007` (`REQ-V3-001`,`REQ-V3-002`): 세션 분류/전환 훅을 `src/markets/schedule.py` 연동
|
||||||
|
- `TASK-CODE-008` (`REQ-V3-003`,`REQ-V3-004`): 블랙아웃 큐 처리기를 `src/broker/`에 추가
|
||||||
|
- `TASK-CODE-009` (`REQ-V3-005`): 세션별 주문 타입 검증기 추가
|
||||||
|
- `TEST-CODE-005`: 블랙아웃 신규주문 차단 테스트
|
||||||
|
- `TEST-CODE-006`: 저유동 세션 시장가 거부 테스트
|
||||||
|
|
||||||
|
## 구현 단위 D: 체결/환율/오버나잇
|
||||||
|
|
||||||
|
- `TASK-CODE-010` (`REQ-V3-006`): 불리한 체결가 모델을 백테스트 체결기로 구현
|
||||||
|
- `TASK-CODE-011` (`REQ-V3-007`): FX PnL 분리 회계 테이블/컬럼 추가
|
||||||
|
- `TASK-CODE-012` (`REQ-V3-008`): 오버나잇 예외와 Kill Switch 충돌 해소 로직 구현
|
||||||
|
- `TEST-CODE-007`: 불리한 체결가 모델 테스트
|
||||||
|
- `TEST-CODE-008`: FX 버퍼 위반 시 신규진입 제한 테스트
|
||||||
|
|
||||||
|
## 구현 단위 E: 운영/문서 거버넌스
|
||||||
|
|
||||||
|
- `TASK-OPS-001` (`REQ-OPS-001`): 시간 필드/로그 스키마의 타임존 표기 강제 규칙 구현
|
||||||
|
- `TASK-OPS-002` (`REQ-OPS-002`): 정책 수치 변경 시 `01_requirements_registry.md` 선수정 CI 체크 추가
|
||||||
|
- `TASK-OPS-003` (`REQ-OPS-003`): `TASK-*` 없는 `REQ-*` 또는 `TEST-*` 없는 `REQ-*`를 차단하는 문서 검증 게이트 유지
|
||||||
|
|
||||||
|
## 커밋 규칙
|
||||||
|
|
||||||
|
- 커밋 메시지에 `TASK-*` 포함
|
||||||
|
- PR 본문에 `REQ-*`, `TEST-*` 매핑 표 포함
|
||||||
|
- 변경 파일마다 최소 1개 테스트 연결
|
||||||
57
docs/ouroboros/40_acceptance_and_test_plan.md
Normal file
57
docs/ouroboros/40_acceptance_and_test_plan.md
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
<!--
|
||||||
|
Doc-ID: DOC-TEST-001
|
||||||
|
Version: 1.0.0
|
||||||
|
Status: active
|
||||||
|
Owner: strategy
|
||||||
|
Updated: 2026-02-26
|
||||||
|
-->
|
||||||
|
|
||||||
|
# 수용 기준 및 테스트 계획
|
||||||
|
|
||||||
|
## 수용 기준
|
||||||
|
|
||||||
|
- `TEST-ACC-000` (`REQ-V2-001`): 상태 enum은 4개(`HOLDING`,`BE_LOCK`,`ARMED`,`EXITED`)만 허용한다.
|
||||||
|
- `TEST-ACC-001` (`REQ-V2-002`): 상태 전이는 순차 if-else가 아닌 우선순위 승격으로 동작한다.
|
||||||
|
- `TEST-ACC-010` (`REQ-V2-003`): `EXITED` 조건은 어떤 상태보다 먼저 평가된다.
|
||||||
|
- `TEST-ACC-011` (`REQ-V2-004`): 청산 판단은 Hard Stop/BE Lock/ATR/모델보조 4요소를 모두 포함한다.
|
||||||
|
- `TEST-ACC-012` (`REQ-V2-005`): Triple Barrier 라벨은 first-touch 규칙으로 결정된다.
|
||||||
|
- `TEST-ACC-013` (`REQ-V2-006`): 학습/검증 분할은 Walk-forward + Purge/Embargo를 적용한다.
|
||||||
|
- `TEST-ACC-014` (`REQ-V2-007`): 비용/슬리피지/체결실패 옵션 비활성 시 백테스트 실행을 거부한다.
|
||||||
|
- `TEST-ACC-002` (`REQ-V2-008`): Kill Switch 실행 순서가 고정 순서를 위반하지 않는다.
|
||||||
|
- `TEST-ACC-015` (`REQ-V3-001`): 모든 주문/로그 레코드에 `session_id`가 저장된다.
|
||||||
|
- `TEST-ACC-016` (`REQ-V3-002`): 세션 전환 이벤트 시 리스크 파라미터가 재로딩된다.
|
||||||
|
- `TEST-ACC-003` (`REQ-V3-003`): 블랙아웃 중 신규 주문 API 호출이 발생하지 않는다.
|
||||||
|
- `TEST-ACC-017` (`REQ-V3-004`): 블랙아웃 큐는 복구 후 재검증을 통과한 주문만 실행한다.
|
||||||
|
- `TEST-ACC-004` (`REQ-V3-005`): 저유동 세션 시장가 주문은 항상 거부된다.
|
||||||
|
- `TEST-ACC-005` (`REQ-V3-006`): 백테스트 체결가가 단순 종가 체결보다 보수적 손익을 낸다.
|
||||||
|
- `TEST-ACC-006` (`REQ-V3-007`): 전략 손익과 환율 손익이 별도 집계된다.
|
||||||
|
- `TEST-ACC-018` (`REQ-V3-008`): 오버나잇 예외 상태에서도 Kill Switch 우선순위가 유지된다.
|
||||||
|
- `TEST-ACC-007` (`REQ-OPS-001`): 시간 관련 필드는 타임존(KST/UTC)이 누락되면 검증 실패한다.
|
||||||
|
- `TEST-ACC-008` (`REQ-OPS-002`): 정책 수치 변경이 원장 미반영이면 검증 실패한다.
|
||||||
|
- `TEST-ACC-009` (`REQ-OPS-003`): `REQ-*`가 `TASK-*`/`TEST-*` 매핑 없이 존재하면 검증 실패한다.
|
||||||
|
|
||||||
|
## 테스트 계층
|
||||||
|
|
||||||
|
1. 단위 테스트
|
||||||
|
- 상태 전이, 주문타입 검증, 큐 복구 로직, 체결가 모델
|
||||||
|
|
||||||
|
2. 통합 테스트
|
||||||
|
- 세션 전환 -> 주문 정책 -> 리스크 엔진 연동
|
||||||
|
- 블랙아웃 시작/해제 이벤트 연동
|
||||||
|
|
||||||
|
3. 회귀 테스트
|
||||||
|
- 기존 `tests/` 스위트 전량 실행
|
||||||
|
- 신규 기능 플래그 ON/OFF 비교
|
||||||
|
|
||||||
|
## 실행 명령
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pytest -q
|
||||||
|
python3 scripts/validate_ouroboros_docs.py
|
||||||
|
```
|
||||||
|
|
||||||
|
## 실패 처리 규칙
|
||||||
|
|
||||||
|
- 문서 검증 실패 시 구현 PR 병합 금지
|
||||||
|
- `REQ-*` 변경 후 테스트 매핑 누락 시 병합 금지
|
||||||
|
- 회귀 실패 시 원인 모듈 분리 후 재검증
|
||||||
36
docs/ouroboros/README.md
Normal file
36
docs/ouroboros/README.md
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
<!--
|
||||||
|
Doc-ID: DOC-ROOT-001
|
||||||
|
Version: 1.0.0
|
||||||
|
Status: active
|
||||||
|
Owner: strategy
|
||||||
|
Updated: 2026-02-26
|
||||||
|
-->
|
||||||
|
|
||||||
|
# The Ouroboros 실행 문서 허브
|
||||||
|
|
||||||
|
이 폴더는 `ouroboros_plan_v2.txt`, `ouroboros_plan_v3.txt`를 구현 가능한 작업 지시서 수준으로 분해한 문서 허브다.
|
||||||
|
|
||||||
|
## 읽기 순서 (Routing)
|
||||||
|
|
||||||
|
1. 검증 체계부터 확정: [00_validation_system.md](./00_validation_system.md)
|
||||||
|
2. 단일 진실원장(요구사항): [01_requirements_registry.md](./01_requirements_registry.md)
|
||||||
|
3. v2 실행 지시서: [10_phase_v2_execution.md](./10_phase_v2_execution.md)
|
||||||
|
4. v3 실행 지시서: [20_phase_v3_execution.md](./20_phase_v3_execution.md)
|
||||||
|
5. 코드 레벨 작업 지시: [30_code_level_work_orders.md](./30_code_level_work_orders.md)
|
||||||
|
6. 수용 기준/테스트 계획: [40_acceptance_and_test_plan.md](./40_acceptance_and_test_plan.md)
|
||||||
|
|
||||||
|
## 운영 규칙
|
||||||
|
|
||||||
|
- 계획 변경은 반드시 `01_requirements_registry.md`의 ID 정의부터 수정한다.
|
||||||
|
- 구현 문서는 원장 ID만 참조하고 자체 숫자/정책을 새로 만들지 않는다.
|
||||||
|
- 문서 품질 룰셋(`RULE-DOC-001` `RULE-DOC-002` `RULE-DOC-003` `RULE-DOC-004` `RULE-DOC-005` `RULE-DOC-006`)은 [00_validation_system.md](./00_validation_system.md)를 기준으로 적용한다.
|
||||||
|
- 문서 병합 전 아래 검증을 통과해야 한다.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 scripts/validate_ouroboros_docs.py
|
||||||
|
```
|
||||||
|
|
||||||
|
## 원본 계획 문서
|
||||||
|
|
||||||
|
- [v2](/home/agentson/repos/The-Ouroboros/ouroboros_plan_v2.txt)
|
||||||
|
- [v3](/home/agentson/repos/The-Ouroboros/ouroboros_plan_v3.txt)
|
||||||
@@ -292,3 +292,66 @@ Order result: 모의투자 매수주문이 완료 되었습니다. ✓
|
|||||||
```
|
```
|
||||||
|
|
||||||
**이슈/PR:** #149, #150
|
**이슈/PR:** #149, #150
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2026-02-23
|
||||||
|
|
||||||
|
### 국내주식 지정가 전환 및 미체결 처리 (#232)
|
||||||
|
|
||||||
|
**배경:**
|
||||||
|
- 해외주식은 #211에서 지정가로 전환했으나 국내주식은 여전히 `price=0` (시장가)
|
||||||
|
- KRX도 지정가 주문 사용 시 동일한 미체결 위험이 존재
|
||||||
|
- 지정가 전환 + 미체결 처리를 함께 구현
|
||||||
|
|
||||||
|
**구현 내용:**
|
||||||
|
|
||||||
|
1. `src/broker/kis_api.py`
|
||||||
|
- `get_domestic_pending_orders()`: 모의 즉시 `[]`, 실전 `TTTC0084R` GET
|
||||||
|
- `cancel_domestic_order()`: 실전 `TTTC0013U` / 모의 `VTTC0013U`, hashkey 필수
|
||||||
|
|
||||||
|
2. `src/main.py`
|
||||||
|
- import `kr_round_down` 추가
|
||||||
|
- `trading_cycle`, `run_daily_session` 국내 주문 `price=0` → 지정가:
|
||||||
|
BUY +0.2% / SELL -0.2%, `kr_round_down` KRX 틱 반올림 적용
|
||||||
|
- `handle_domestic_pending_orders` 함수: BUY→취소+쿨다운, SELL→취소+재주문(-0.4%, 최대1회)
|
||||||
|
- daily/realtime 두 모드에서 domestic pending 체크 호출 추가
|
||||||
|
|
||||||
|
3. 테스트 14개 추가:
|
||||||
|
- `TestGetDomesticPendingOrders` (3), `TestCancelDomesticOrder` (5)
|
||||||
|
- `TestHandleDomesticPendingOrders` (4), `TestDomesticLimitOrderPrice` (2)
|
||||||
|
|
||||||
|
**이슈/PR:** #232, PR #233
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2026-02-24
|
||||||
|
|
||||||
|
### 해외잔고 ghost position 수정 — '모의투자 잔고내역이 없습니다' 반복 방지 (#235)
|
||||||
|
|
||||||
|
**배경:**
|
||||||
|
- 모의투자 실행 시 MLECW, KNRX, NBY, SNSE 등 만료/정지된 종목에 대해
|
||||||
|
`모의투자 잔고내역이 없습니다` 오류가 매 사이클 반복됨
|
||||||
|
|
||||||
|
**근본 원인:**
|
||||||
|
1. `ovrs_cblc_qty` (해외잔고수량, 총 보유) vs `ord_psbl_qty` (주문가능수량, 실제 매도 가능)
|
||||||
|
- 기존 코드: `ovrs_cblc_qty` 우선 사용 → 만료 Warrant가 `ovrs_cblc_qty=289456`이지만 실제 `ord_psbl_qty=0`
|
||||||
|
- startup sync / build_overseas_symbol_universe가 이 종목들을 포지션으로 기록
|
||||||
|
2. SELL 실패 시 DB 포지션이 닫히지 않아 다음 사이클에서도 재시도 (무한 반복)
|
||||||
|
|
||||||
|
**구현 내용:**
|
||||||
|
|
||||||
|
1. `src/main.py` — `_extract_held_codes_from_balance`, `_extract_held_qty_from_balance`
|
||||||
|
- 해외 잔고 필드 우선순위 변경: `ord_psbl_qty` → `ovrs_cblc_qty` → `hldg_qty` (fallback 유지)
|
||||||
|
- KIS 공식 문서(VTTS3012R) 기준: `ord_psbl_qty`가 실제 매도 가능 수량
|
||||||
|
|
||||||
|
2. `src/main.py` — `trading_cycle` ghost-close 처리
|
||||||
|
- 해외 SELL이 `잔고내역이 없습니다`로 실패 시 DB 포지션을 `[ghost-close]` SELL로 종료
|
||||||
|
- exchange code 불일치 등 예외 상황에서 무한 반복 방지
|
||||||
|
|
||||||
|
3. 테스트 7개 추가:
|
||||||
|
- `TestExtractHeldQtyFromBalance` 3개: ord_psbl_qty 우선, 0이면 0 반환, fallback
|
||||||
|
- `TestExtractHeldCodesFromBalance` 2개: ord_psbl_qty=0인 종목 제외, fallback
|
||||||
|
- `TestOverseasGhostPositionClose` 2개: ghost-close 로그 확인, 일반 오류 무시
|
||||||
|
|
||||||
|
**이슈/PR:** #235, PR #236
|
||||||
|
|||||||
@@ -13,6 +13,57 @@
|
|||||||
|
|
||||||
**Never commit directly to `main`.** This policy applies to all changes, no exceptions.
|
**Never commit directly to `main`.** This policy applies to all changes, no exceptions.
|
||||||
|
|
||||||
|
## Gitea CLI Formatting Troubleshooting
|
||||||
|
|
||||||
|
Issue/PR 본문 작성 시 줄바꿈(`\n`)이 문자열 그대로 저장되는 문제가 반복될 수 있다. 원인은 `-d "...\n..."` 형태에서 쉘/CLI가 이스케이프를 실제 개행으로 해석하지 않기 때문이다.
|
||||||
|
|
||||||
|
권장 패턴:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ISSUE_BODY=$(cat <<'EOF'
|
||||||
|
## Summary
|
||||||
|
- 변경 내용 1
|
||||||
|
- 변경 내용 2
|
||||||
|
|
||||||
|
## Why
|
||||||
|
- 배경 1
|
||||||
|
- 배경 2
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
- 포함 범위
|
||||||
|
- 제외 범위
|
||||||
|
EOF
|
||||||
|
)
|
||||||
|
|
||||||
|
tea issues create \
|
||||||
|
-t "docs: 제목" \
|
||||||
|
-d "$ISSUE_BODY"
|
||||||
|
```
|
||||||
|
|
||||||
|
PR도 동일하게 적용:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
PR_BODY=$(cat <<'EOF'
|
||||||
|
## Summary
|
||||||
|
- ...
|
||||||
|
|
||||||
|
## Validation
|
||||||
|
- python3 scripts/validate_ouroboros_docs.py
|
||||||
|
EOF
|
||||||
|
)
|
||||||
|
|
||||||
|
tea pr create \
|
||||||
|
--base main \
|
||||||
|
--head feature/issue-N-something \
|
||||||
|
--title "docs: ... (#N)" \
|
||||||
|
--description "$PR_BODY"
|
||||||
|
```
|
||||||
|
|
||||||
|
금지 패턴:
|
||||||
|
|
||||||
|
- `-d "line1\nline2"` (웹 UI에 `\n` 문자 그대로 노출될 수 있음)
|
||||||
|
- 본문에 백틱/괄호를 인라인로 넣고 적절한 quoting 없이 즉시 실행
|
||||||
|
|
||||||
## Agent Workflow
|
## Agent Workflow
|
||||||
|
|
||||||
**Modern AI development leverages specialized agents for concurrent, efficient task execution.**
|
**Modern AI development leverages specialized agents for concurrent, efficient task execution.**
|
||||||
|
|||||||
165
ouroboros_plan_v2.txt
Normal file
165
ouroboros_plan_v2.txt
Normal file
@@ -0,0 +1,165 @@
|
|||||||
|
[The Ouroboros] 운영/전략 계획서 v2
|
||||||
|
작성일: 2026-02-26
|
||||||
|
상태: 코드 구현 전 설계안(전략/검증 중심)
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
0) 목적
|
||||||
|
==================================================
|
||||||
|
고정 익절(+3%) 중심 로직에서 벗어나, 다음을 만족하는 실전형 청산 체계로 전환한다.
|
||||||
|
- 수익 구간 보호 (손익 역전 방지)
|
||||||
|
- 변동성 적응형 청산
|
||||||
|
- 예측 모델의 확률 신호를 보조적으로 결합
|
||||||
|
- 과적합 방지를 최우선으로 한 검증 프레임워크
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
1) 핵심 설계 원칙
|
||||||
|
==================================================
|
||||||
|
1. 예측 성능과 전략 성능을 분리 평가
|
||||||
|
- 예측 성능: PR-AUC, Brier, Calibration
|
||||||
|
- 전략 성능: Net PnL, Sharpe, MDD, Profit Factor, Turnover
|
||||||
|
|
||||||
|
2. 시계열 검증 규율 강제
|
||||||
|
- Walk-forward 분할
|
||||||
|
- Purge/Embargo 적용
|
||||||
|
- Random split 금지
|
||||||
|
|
||||||
|
3. 실거래 리얼리즘 우선
|
||||||
|
- 거래비용/슬리피지/체결실패 반영 없는 백테스트 결과는 채택 금지
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
2) 매도 상태기계 (State Machine)
|
||||||
|
==================================================
|
||||||
|
상태:
|
||||||
|
- HOLDING
|
||||||
|
- BE_LOCK
|
||||||
|
- ARMED
|
||||||
|
- EXITED
|
||||||
|
|
||||||
|
정의:
|
||||||
|
- HOLDING: 일반 보유 상태
|
||||||
|
- BE_LOCK: 일정 수익권 진입 시 손절선을 본전(또는 비용 반영 본전)으로 상향
|
||||||
|
- ARMED: 추세 추적(피크 추적) 기반 청산 준비 상태
|
||||||
|
- EXITED: 청산 완료
|
||||||
|
|
||||||
|
전이 규칙(개념):
|
||||||
|
- HOLDING -> BE_LOCK: unrealized_pnl_pct >= be_arm_pct
|
||||||
|
- BE_LOCK -> ARMED: unrealized_pnl_pct >= arm_pct
|
||||||
|
- ARMED -> EXITED: 아래 조건 중 하나 충족
|
||||||
|
1) hard stop 도달
|
||||||
|
2) trailing stop 도달 (peak 대비 하락)
|
||||||
|
3) 모델 하락확률 + 유동성 약화 조건 충족
|
||||||
|
|
||||||
|
상태 전이 구현 규칙(필수):
|
||||||
|
- 매 틱/바 평가 시 "현재 조건이 허용하는 최상위 상태"로 즉시 승격
|
||||||
|
- 순차 if-else로 인한 전이 누락 금지 (예: 갭으로 BE_LOCK/ARMED 동시 충족)
|
||||||
|
- EXITED 조건은 모든 상태보다 우선 평가
|
||||||
|
- 상태 전이 로그에 이전/이후 상태, 전이 사유, 기준 가격/수익률 기록
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
3) 청산 로직 구성 (4중 안전장치)
|
||||||
|
==================================================
|
||||||
|
A. Hard Stop
|
||||||
|
- 계좌/포지션 보호용 절대 하한
|
||||||
|
- 항상 활성화
|
||||||
|
|
||||||
|
B. Dynamic Stop (Break-even Lock)
|
||||||
|
- BE_LOCK 진입 시 손절선을 본전 이상으로 상향
|
||||||
|
- "수익 포지션이 손실로 반전"되는 구조적 리스크 차단
|
||||||
|
|
||||||
|
C. ATR 기반 Trailing Stop
|
||||||
|
- 고정 trail_pct 대신 변동성 적응형 사용
|
||||||
|
- 예시: ExitPrice = PeakPrice - (k * ATR)
|
||||||
|
|
||||||
|
D. 모델 확률 신호
|
||||||
|
- 하락전환 확률(pred_prob)이 임계값 이상일 때 청산 가중
|
||||||
|
- 단독 트리거가 아닌 trailing/리스크 룰 보조 트리거로 사용
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
4) 라벨링 체계 (Triple Barrier)
|
||||||
|
==================================================
|
||||||
|
목표:
|
||||||
|
고정 H-window 라벨 편향을 줄이고, 금융 시계열의 경로 의존성을 반영한다.
|
||||||
|
|
||||||
|
라벨 정의:
|
||||||
|
- Upper barrier (익절)
|
||||||
|
- Lower barrier (손절)
|
||||||
|
- Time barrier (만기)
|
||||||
|
|
||||||
|
규칙:
|
||||||
|
- 세 장벽 중 "먼저 터치한 장벽"으로 라벨 확정
|
||||||
|
- 라벨은 entry 시점 이후 데이터만 사용해 생성
|
||||||
|
- 피처 생성 구간과 라벨 구간을 엄격 분리해 look-ahead bias 방지
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
5) 검증 프레임워크
|
||||||
|
==================================================
|
||||||
|
5.1 분할 방식
|
||||||
|
- Fold 단위 Walk-forward
|
||||||
|
- Purge/Embargo로 인접 샘플 누수 차단
|
||||||
|
|
||||||
|
5.2 비교군(Baseline) 구조
|
||||||
|
- B0: 기존 고정 손절/익절
|
||||||
|
- B1: 모델 없는 trailing only
|
||||||
|
- M1: trailing + 모델 확률 결합
|
||||||
|
|
||||||
|
5.3 채택 기준
|
||||||
|
- M1이 B0/B1 대비 OOS(Out-of-sample)에서 일관된 우위
|
||||||
|
- 단일 구간 성과가 아닌 fold 분포 기준으로 판단
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
6) 실행 아키텍처 원칙
|
||||||
|
==================================================
|
||||||
|
1. 저지연 실행 경로
|
||||||
|
- 실시간 청산 판단은 경량 엔진(룰/GBDT) 담당
|
||||||
|
- LLM은 레짐 판단/비중 조절/상위 의사결정 보조
|
||||||
|
|
||||||
|
2. 체결 현실 반영
|
||||||
|
- 세션 유동성에 따른 슬리피지 페널티 차등 적용
|
||||||
|
- 미체결/재호가/재접수 시나리오를 백테스트에 반영
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
7) 운영 리스크 관리
|
||||||
|
==================================================
|
||||||
|
승격 단계:
|
||||||
|
- Offline backtest -> Paper shadow -> Small-capital live
|
||||||
|
|
||||||
|
중단(Kill Switch):
|
||||||
|
- rolling Sharpe 악화
|
||||||
|
- MDD 한도 초과
|
||||||
|
- 체결 실패율/슬리피지 급등
|
||||||
|
|
||||||
|
Kill Switch 실행 순서(원자적):
|
||||||
|
1) 모든 신규 주문 차단 플래그 ON
|
||||||
|
2) 모든 미체결 주문 취소 요청
|
||||||
|
3) 취소 결과 재조회(실패 건 재시도)
|
||||||
|
4) 포지션 리스크 재계산 후 강제 축소/청산 판단
|
||||||
|
5) 상태/로그 스냅샷 저장 및 운영 경보 발송
|
||||||
|
|
||||||
|
원칙:
|
||||||
|
- 모델이 실패해도 hard stop 기반 보수 모드로 즉시 디그레이드 가능해야 함
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
8) 고정 파라미터(초기안)
|
||||||
|
==================================================
|
||||||
|
(15분봉 단기 스윙 기준 제안)
|
||||||
|
- KR: be_arm_pct=1.2, arm_pct=2.8, atr_period=14, atr_multiplier_k=2.2,
|
||||||
|
time_barrier_bars=26, p_thresh=0.62
|
||||||
|
- US: be_arm_pct=1.0, arm_pct=2.4, atr_period=14, atr_multiplier_k=2.0,
|
||||||
|
time_barrier_bars=32, p_thresh=0.60
|
||||||
|
|
||||||
|
민감도 범위(초기 탐색):
|
||||||
|
- be_arm_pct: KR 0.9~1.8 / US 0.7~1.5
|
||||||
|
- arm_pct: KR 2.2~3.8 / US 1.8~3.2
|
||||||
|
- atr_multiplier_k: KR 1.8~2.8 / US 1.6~2.4
|
||||||
|
- time_barrier_bars: KR 20~36 / US 24~48
|
||||||
|
- p_thresh: 0.55~0.70
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
9) 구현 전 체크리스트
|
||||||
|
==================================================
|
||||||
|
- 파라미터 튜닝 시 nested leakage 방지
|
||||||
|
- 수수료/세금/슬리피지 전부 반영 여부 확인
|
||||||
|
- 세션/타임존/DST 처리 일관성 확인
|
||||||
|
- 모델 버전/설정 해시/실험 로그 재현성 확보
|
||||||
|
|
||||||
|
끝.
|
||||||
185
ouroboros_plan_v3.txt
Normal file
185
ouroboros_plan_v3.txt
Normal file
@@ -0,0 +1,185 @@
|
|||||||
|
[The Ouroboros] 운영확장 v3
|
||||||
|
작성일: 2026-02-26
|
||||||
|
상태: v2 확장판 / 야간·프리마켓 포함 글로벌 세션 운영 설계안
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
0) 목적
|
||||||
|
==================================================
|
||||||
|
"24시간 무중단 자산 증식" 비전을 위해 거래 세션 범위를 KR 정규장 중심에서
|
||||||
|
NXT/미국 확장 세션까지 확대한다. 핵심은 다음 3가지다.
|
||||||
|
- 세션 인지형 의사결정
|
||||||
|
- 세션별 리스크/비용 차등 적용
|
||||||
|
- 시간장벽의 현실적 재정의
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
1) 세션 모델 (Session-aware Engine)
|
||||||
|
==================================================
|
||||||
|
KR 세션:
|
||||||
|
- NXT_PRE : 08:00 ~ 08:50 (KST)
|
||||||
|
- KRX_REG : 09:00 ~ 15:30 (KST)
|
||||||
|
- NXT_AFTER : 15:30 ~ 20:00 (KST)
|
||||||
|
|
||||||
|
US 세션(KST 관점 운영):
|
||||||
|
- US_DAY : 10:00 ~ 18:00
|
||||||
|
- US_PRE : 18:00 ~ 23:30
|
||||||
|
- US_REG : 23:30 ~ 06:00
|
||||||
|
- US_AFTER : 06:00 ~ 07:00
|
||||||
|
|
||||||
|
원칙:
|
||||||
|
- 모든 피처/신호/주문/로그에 session_id를 명시적으로 포함
|
||||||
|
- 세션 전환 시 상태 업데이트 및 리스크 파라미터 재로딩
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
2) 캘린더/휴장/DST 고정 소스
|
||||||
|
==================================================
|
||||||
|
KR:
|
||||||
|
- 기본: pykrx 또는 FinanceDataReader (KRX 기준)
|
||||||
|
- 예외: 연휴/임시 휴장/NXT 특이 운영은 KIS 공지 기반 보완
|
||||||
|
|
||||||
|
US:
|
||||||
|
- pandas_market_calendars (NYSE 기준)
|
||||||
|
- 2026 DST:
|
||||||
|
- 시작: 2026-03-08
|
||||||
|
- 종료: 2026-11-01
|
||||||
|
|
||||||
|
정합성 규칙:
|
||||||
|
- 스케줄 충돌 시 "거래소 캘린더 > 로컬 추정" 우선
|
||||||
|
- 시장 상태(open/close/half-day)는 주문 엔진 진입 전 최종 검증
|
||||||
|
|
||||||
|
KIS 점검시간 회피 정책(필수):
|
||||||
|
- 브로커 점검/장애 블랙아웃 윈도우는 운영 설정으로 별도 관리
|
||||||
|
- 블랙아웃 구간에는 신규 주문 전송 금지, 취소/정정도 정책적으로 제한
|
||||||
|
- 신호는 유지하되 주문 의도는 Queue에 적재, 복구 후 유효성 재검증 뒤 실행
|
||||||
|
- 복구 직후에는 잔고/미체결/체결내역을 우선 동기화한 뒤 주문 엔진 재가동
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
3) 시간장벽 재정의
|
||||||
|
==================================================
|
||||||
|
v2의 time_barrier_bars 고정값을 v3에서 다음으로 확장:
|
||||||
|
- max_holding_minutes (시장별 기본 만기)
|
||||||
|
- 봉 개수는 세션 길이/간격으로 동적 계산
|
||||||
|
|
||||||
|
기본값:
|
||||||
|
- KR: max_holding_minutes = 2160 (약 3거래일, NXT 포함 관점)
|
||||||
|
- US: max_holding_minutes = 4320 (약 72시간)
|
||||||
|
|
||||||
|
운영 주의:
|
||||||
|
- 고정 "일중 청산"보다 "포지션 유지 시간" 기준 만기 적용
|
||||||
|
- 세션 종료 강제청산 규칙과 충돌 시 우선순위 명시 필요
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
4) 세션별 비용/슬리피지 모델 (보수적)
|
||||||
|
==================================================
|
||||||
|
KRX_REG:
|
||||||
|
- 슬리피지: 2~3틱 (약 0.05%)
|
||||||
|
- 수수료+세금: 0.20% ~ 0.23%
|
||||||
|
|
||||||
|
NXT_AFTER:
|
||||||
|
- 슬리피지: 5~8틱 (약 0.15%)
|
||||||
|
- 수수료+세금: 0.20% ~ 0.23%
|
||||||
|
|
||||||
|
US_REG:
|
||||||
|
- 슬리피지: 2~3틱 (약 0.03%)
|
||||||
|
- 수수료+기타 비용: 0.07% ~ 0.15%
|
||||||
|
|
||||||
|
US_PRE / US_DAY:
|
||||||
|
- 슬리피지: 10틱+ (약 0.3% ~ 0.5%)
|
||||||
|
- 수수료+기타 비용: 0.07% ~ 0.15%
|
||||||
|
|
||||||
|
원칙:
|
||||||
|
- 백테스트 체결가는 세션별 보수 가정 적용
|
||||||
|
- 저유동 세션은 자동 보수 모드(p_thresh 상향, atr_k 상향) 권장
|
||||||
|
- 백테스트 체결가 기본은 "불리한 방향 체결" 가정 (단순 close 체결 금지)
|
||||||
|
|
||||||
|
세션별 주문 유형 강제(필수):
|
||||||
|
- KRX_REG / US_REG: 지정가 우선, 시장가 제한적 허용
|
||||||
|
- NXT_AFTER / US_PRE / US_DAY / US_AFTER: 시장가 금지
|
||||||
|
- 저유동 세션은 최우선 지정가 또는 IOC/FOK(가격 보호 한도 포함)만 허용
|
||||||
|
- 주문 실패 시 재호가 간격/횟수 상한을 두고, 초과 시 주문 철회
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
5) 포지션/잔고 통합 규칙 (KIS 특성 반영)
|
||||||
|
==================================================
|
||||||
|
문제:
|
||||||
|
- KRX/NXT 잔고 조회가 venue 단위로 분리되거나 반영 지연 가능
|
||||||
|
|
||||||
|
규칙:
|
||||||
|
- 종목 식별은 동일 종목코드(또는 ISIN) 기준 통합 포지션으로 관리
|
||||||
|
- 다만 주문 가능 수량은 venue별 API 응답을 최종 기준으로 사용
|
||||||
|
- 매도 가능 수량 검증은 주문 직전 재조회로 확정
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
6) 마감 강제청산/오버나잇 예외 규칙
|
||||||
|
==================================================
|
||||||
|
기본 원칙:
|
||||||
|
- 모든 포지션에 대해 세션 종료 10분 전 REDUCE_ALL 검토
|
||||||
|
|
||||||
|
오버나잇 예외 허용 (모두 충족 시):
|
||||||
|
1) ARMED 상태 (예: +2.8% 이상)
|
||||||
|
2) 모델 하락확률 < 0.30
|
||||||
|
3) 포트폴리오 현금 비중 >= 50%
|
||||||
|
|
||||||
|
갭 리스크 통제:
|
||||||
|
- 다음 개장 시 hard stop를 시가 기준으로 재산정
|
||||||
|
- 조건 위반 시 즉시 청산 우선
|
||||||
|
|
||||||
|
Kill Switch 연동:
|
||||||
|
- MDD/실패율 임계치 초과 시 "미체결 전량 취소 -> 신규 주문 차단 -> 리스크 축소" 순서 강제
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
7) 데이터 저장/용량 정책
|
||||||
|
==================================================
|
||||||
|
핵심 테이블(계획):
|
||||||
|
- feature_snapshots
|
||||||
|
- position_states
|
||||||
|
- model_predictions
|
||||||
|
|
||||||
|
저장 규칙:
|
||||||
|
- feature_hash 기반 중복 제거
|
||||||
|
- 가격 변화가 작아도 session_id 변경 시 강제 스냅샷
|
||||||
|
- 월 단위 DB 로테이션 권장 (예: trading_YYYY_MM.db)
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
8) 환율/정산 리스크 정책 (US 필수)
|
||||||
|
==================================================
|
||||||
|
원칙:
|
||||||
|
- USD 노출은 전략 손익과 별도로 환율 손익을 분리 추적
|
||||||
|
- 원화 주문 서비스 사용 시 가환율 체결/익일 정산 리스크를 예수금 규칙에 반영
|
||||||
|
|
||||||
|
운영 규칙:
|
||||||
|
- 환전 시점 정책(사전 환전/수시 환전)을 고정하고 로그에 기록
|
||||||
|
- 최소 USD 버퍼와 KRW 버퍼를 각각 설정해 주문 가능금 부족 리스크 완화
|
||||||
|
- 환율 급변 구간에는 포지션 한도 축소 또는 신규 진입 제한
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
9) v3 실험 매트릭스 (우선 3선)
|
||||||
|
==================================================
|
||||||
|
EXP-KR-01:
|
||||||
|
- 시장: KR
|
||||||
|
- 포커스: NXT 야간 특화
|
||||||
|
- 제안: time barrier 확장(예: 48 bars 상당), p_thresh 상향(0.65)
|
||||||
|
|
||||||
|
EXP-US-01:
|
||||||
|
- 시장: US
|
||||||
|
- 포커스: 21h 준연속 운용
|
||||||
|
- 제안: time barrier 확장(예: 80 bars 상당), atr_k 상향(2.5)
|
||||||
|
|
||||||
|
EXP-HYB-01:
|
||||||
|
- 시장: Global
|
||||||
|
- 포커스: KR 낮 + US 밤 연계
|
||||||
|
- 제안: 레짐 기반 자산배분 자동조절
|
||||||
|
|
||||||
|
==================================================
|
||||||
|
10) 코드 착수 전 최종 확정 체크
|
||||||
|
==================================================
|
||||||
|
1) 세션별 공식 캘린더 소스/우선순위
|
||||||
|
2) 세션별 슬리피지/비용 테이블 수치
|
||||||
|
3) 시장별 max_holding_minutes
|
||||||
|
4) 마감 강제청산 예외 조건 임계값
|
||||||
|
5) 블랙아웃(점검/장애) 시간대와 주문 큐 처리 규칙
|
||||||
|
6) 세션별 허용 주문 유형(시장가 허용 범위 포함)
|
||||||
|
7) 환전/정산 정책 및 통화 버퍼 임계값
|
||||||
|
|
||||||
|
모든 항목 확정 후 Step 1 구현(코드)로 이동.
|
||||||
|
|
||||||
|
끝.
|
||||||
@@ -23,7 +23,7 @@ if [ -z "${APP_CMD:-}" ]; then
|
|||||||
|
|
||||||
dashboard_port="${DASHBOARD_PORT:-8080}"
|
dashboard_port="${DASHBOARD_PORT:-8080}"
|
||||||
|
|
||||||
APP_CMD="DASHBOARD_PORT=$dashboard_port $PYTHON_BIN -m src.main --mode=paper --dashboard"
|
APP_CMD="DASHBOARD_PORT=$dashboard_port $PYTHON_BIN -m src.main --mode=live --dashboard"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
mkdir -p "$LOG_DIR"
|
mkdir -p "$LOG_DIR"
|
||||||
|
|||||||
140
scripts/validate_ouroboros_docs.py
Executable file
140
scripts/validate_ouroboros_docs.py
Executable file
@@ -0,0 +1,140 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Validate Ouroboros planning docs for metadata, links, and ID consistency."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
DOC_DIR = Path("docs/ouroboros")
|
||||||
|
META_PATTERN = re.compile(
|
||||||
|
r"<!--\n"
|
||||||
|
r"Doc-ID: (?P<doc_id>[^\n]+)\n"
|
||||||
|
r"Version: (?P<version>[^\n]+)\n"
|
||||||
|
r"Status: (?P<status>[^\n]+)\n"
|
||||||
|
r"Owner: (?P<owner>[^\n]+)\n"
|
||||||
|
r"Updated: (?P<updated>\d{4}-\d{2}-\d{2})\n"
|
||||||
|
r"-->",
|
||||||
|
re.MULTILINE,
|
||||||
|
)
|
||||||
|
ID_PATTERN = re.compile(r"\b(?:REQ|RULE|TASK|TEST|DOC)-[A-Z0-9-]+-\d{3}\b")
|
||||||
|
DEF_PATTERN = re.compile(r"^-\s+`(?P<id>(?:REQ|RULE|TASK|TEST|DOC)-[A-Z0-9-]+-\d{3})`", re.MULTILINE)
|
||||||
|
LINK_PATTERN = re.compile(r"\[[^\]]+\]\((?P<link>[^)]+)\)")
|
||||||
|
LINE_DEF_PATTERN = re.compile(r"^-\s+`(?P<id>(?:REQ|RULE|TASK|TEST|DOC)-[A-Z0-9-]+-\d{3})`.*$", re.MULTILINE)
|
||||||
|
|
||||||
|
|
||||||
|
def iter_docs() -> list[Path]:
|
||||||
|
return sorted([p for p in DOC_DIR.glob("*.md") if p.is_file()])
|
||||||
|
|
||||||
|
|
||||||
|
def validate_metadata(path: Path, text: str, errors: list[str], doc_ids: dict[str, Path]) -> None:
|
||||||
|
match = META_PATTERN.search(text)
|
||||||
|
if not match:
|
||||||
|
errors.append(f"{path}: missing or malformed metadata block")
|
||||||
|
return
|
||||||
|
doc_id = match.group("doc_id").strip()
|
||||||
|
if doc_id in doc_ids:
|
||||||
|
errors.append(f"{path}: duplicate Doc-ID {doc_id} (already in {doc_ids[doc_id]})")
|
||||||
|
else:
|
||||||
|
doc_ids[doc_id] = path
|
||||||
|
|
||||||
|
|
||||||
|
def validate_links(path: Path, text: str, errors: list[str]) -> None:
|
||||||
|
for m in LINK_PATTERN.finditer(text):
|
||||||
|
link = m.group("link").strip()
|
||||||
|
if not link or link.startswith("http") or link.startswith("#"):
|
||||||
|
continue
|
||||||
|
if link.startswith("/"):
|
||||||
|
target = Path(link)
|
||||||
|
else:
|
||||||
|
target = (path.parent / link).resolve()
|
||||||
|
if not target.exists():
|
||||||
|
errors.append(f"{path}: broken link -> {link}")
|
||||||
|
|
||||||
|
|
||||||
|
def collect_ids(path: Path, text: str, defs: dict[str, Path], refs: dict[str, set[Path]]) -> None:
|
||||||
|
for m in DEF_PATTERN.finditer(text):
|
||||||
|
defs[m.group("id")] = path
|
||||||
|
for m in ID_PATTERN.finditer(text):
|
||||||
|
idv = m.group(0)
|
||||||
|
refs.setdefault(idv, set()).add(path)
|
||||||
|
|
||||||
|
|
||||||
|
def collect_req_traceability(text: str, req_to_task: dict[str, set[str]], req_to_test: dict[str, set[str]]) -> None:
|
||||||
|
for m in LINE_DEF_PATTERN.finditer(text):
|
||||||
|
line = m.group(0)
|
||||||
|
item_id = m.group("id")
|
||||||
|
req_ids = [rid for rid in ID_PATTERN.findall(line) if rid.startswith("REQ-")]
|
||||||
|
if item_id.startswith("TASK-"):
|
||||||
|
for req_id in req_ids:
|
||||||
|
req_to_task.setdefault(req_id, set()).add(item_id)
|
||||||
|
if item_id.startswith("TEST-"):
|
||||||
|
for req_id in req_ids:
|
||||||
|
req_to_test.setdefault(req_id, set()).add(item_id)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
if not DOC_DIR.exists():
|
||||||
|
print(f"ERROR: missing directory {DOC_DIR}")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
docs = iter_docs()
|
||||||
|
if not docs:
|
||||||
|
print(f"ERROR: no markdown docs found in {DOC_DIR}")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
errors: list[str] = []
|
||||||
|
doc_ids: dict[str, Path] = {}
|
||||||
|
defs: dict[str, Path] = {}
|
||||||
|
refs: dict[str, set[Path]] = {}
|
||||||
|
req_to_task: dict[str, set[str]] = {}
|
||||||
|
req_to_test: dict[str, set[str]] = {}
|
||||||
|
|
||||||
|
for path in docs:
|
||||||
|
text = path.read_text(encoding="utf-8")
|
||||||
|
validate_metadata(path, text, errors, doc_ids)
|
||||||
|
validate_links(path, text, errors)
|
||||||
|
collect_ids(path, text, defs, refs)
|
||||||
|
collect_req_traceability(text, req_to_task, req_to_test)
|
||||||
|
|
||||||
|
for idv, where_used in sorted(refs.items()):
|
||||||
|
if idv.startswith("DOC-"):
|
||||||
|
continue
|
||||||
|
if idv not in defs:
|
||||||
|
files = ", ".join(str(p) for p in sorted(where_used))
|
||||||
|
errors.append(f"undefined ID {idv}, used in: {files}")
|
||||||
|
|
||||||
|
for idv in sorted(defs):
|
||||||
|
if not idv.startswith("REQ-"):
|
||||||
|
continue
|
||||||
|
if idv not in req_to_task:
|
||||||
|
errors.append(f"REQ without TASK mapping: {idv}")
|
||||||
|
if idv not in req_to_test:
|
||||||
|
errors.append(f"REQ without TEST mapping: {idv}")
|
||||||
|
|
||||||
|
warnings: list[str] = []
|
||||||
|
for idv, where_def in sorted(defs.items()):
|
||||||
|
if len(refs.get(idv, set())) <= 1 and (idv.startswith("REQ-") or idv.startswith("RULE-")):
|
||||||
|
warnings.append(f"orphan ID {idv} defined in {where_def} (not referenced elsewhere)")
|
||||||
|
|
||||||
|
if errors:
|
||||||
|
print("[FAIL] Ouroboros docs validation failed")
|
||||||
|
for err in errors:
|
||||||
|
print(f"- {err}")
|
||||||
|
return 1
|
||||||
|
|
||||||
|
print(f"[OK] validated {len(docs)} docs in {DOC_DIR}")
|
||||||
|
print(f"[OK] unique Doc-ID: {len(doc_ids)}")
|
||||||
|
print(f"[OK] definitions: {len(defs)}, references: {len(refs)}")
|
||||||
|
print(f"[OK] req->task mappings: {len(req_to_task)}")
|
||||||
|
print(f"[OK] req->test mappings: {len(req_to_test)}")
|
||||||
|
if warnings:
|
||||||
|
print(f"[WARN] orphan IDs: {len(warnings)}")
|
||||||
|
for w in warnings:
|
||||||
|
print(f"- {w}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -346,8 +346,10 @@ class GeminiClient:
|
|||||||
# Validate required fields
|
# Validate required fields
|
||||||
if not all(k in data for k in ("action", "confidence", "rationale")):
|
if not all(k in data for k in ("action", "confidence", "rationale")):
|
||||||
logger.warning("Missing fields in Gemini response — defaulting to HOLD")
|
logger.warning("Missing fields in Gemini response — defaulting to HOLD")
|
||||||
|
# Preserve raw text in rationale so prompt_override callers (e.g. pre_market_planner)
|
||||||
|
# can extract their own JSON format from decision.rationale (#245)
|
||||||
return TradeDecision(
|
return TradeDecision(
|
||||||
action="HOLD", confidence=0, rationale="Missing required fields"
|
action="HOLD", confidence=0, rationale=raw
|
||||||
)
|
)
|
||||||
|
|
||||||
action = str(data["action"]).upper()
|
action = str(data["action"]).upper()
|
||||||
@@ -439,6 +441,18 @@ class GeminiClient:
|
|||||||
action="HOLD", confidence=0, rationale=f"API error: {exc}", token_count=token_count
|
action="HOLD", confidence=0, rationale=f"API error: {exc}", token_count=token_count
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# prompt_override callers (e.g. pre_market_planner) expect raw text back,
|
||||||
|
# not a parsed TradeDecision. Skip parse_response to avoid spurious
|
||||||
|
# "Missing fields" warnings and return the raw response directly. (#247)
|
||||||
|
if "prompt_override" in market_data:
|
||||||
|
logger.info(
|
||||||
|
"Gemini raw response received (prompt_override, tokens=%d)", token_count
|
||||||
|
)
|
||||||
|
# Not a trade decision — don't inflate _total_decisions metrics
|
||||||
|
return TradeDecision(
|
||||||
|
action="HOLD", confidence=0, rationale=raw, token_count=token_count
|
||||||
|
)
|
||||||
|
|
||||||
decision = self.parse_response(raw)
|
decision = self.parse_response(raw)
|
||||||
self._total_decisions += 1
|
self._total_decisions += 1
|
||||||
|
|
||||||
|
|||||||
@@ -179,8 +179,8 @@ class PromptOptimizer:
|
|||||||
# Minimal instructions
|
# Minimal instructions
|
||||||
prompt = (
|
prompt = (
|
||||||
f"{market_name} trader. Analyze:\n{data_str}\n\n"
|
f"{market_name} trader. Analyze:\n{data_str}\n\n"
|
||||||
'Return JSON: {"act":"BUY"|"SELL"|"HOLD","conf":<0-100>,"reason":"<text>"}\n'
|
'Return JSON: {"action":"BUY"|"SELL"|"HOLD","confidence":<0-100>,"rationale":"<text>"}\n'
|
||||||
"Rules: act=BUY/SELL/HOLD, conf=0-100, reason=concise. No markdown."
|
"Rules: action=BUY/SELL/HOLD, confidence=0-100, rationale=concise. No markdown."
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
# Data only (for cached contexts where instructions are known)
|
# Data only (for cached contexts where instructions are known)
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ from __future__ import annotations
|
|||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
import ssl
|
import ssl
|
||||||
from typing import Any
|
from typing import Any, cast
|
||||||
|
|
||||||
import aiohttp
|
import aiohttp
|
||||||
|
|
||||||
@@ -430,7 +430,7 @@ class KISBroker:
|
|||||||
"fid_cond_mrkt_div_code": "J",
|
"fid_cond_mrkt_div_code": "J",
|
||||||
"fid_cond_scr_div_code": "20170",
|
"fid_cond_scr_div_code": "20170",
|
||||||
"fid_input_iscd": "0000",
|
"fid_input_iscd": "0000",
|
||||||
"fid_rank_sort_cls_code": "0000",
|
"fid_rank_sort_cls_code": "0",
|
||||||
"fid_input_cnt_1": str(limit),
|
"fid_input_cnt_1": str(limit),
|
||||||
"fid_prc_cls_code": "0",
|
"fid_prc_cls_code": "0",
|
||||||
"fid_input_price_1": "0",
|
"fid_input_price_1": "0",
|
||||||
@@ -466,7 +466,7 @@ class KISBroker:
|
|||||||
rankings = []
|
rankings = []
|
||||||
for item in data.get("output", [])[:limit]:
|
for item in data.get("output", [])[:limit]:
|
||||||
rankings.append({
|
rankings.append({
|
||||||
"stock_code": item.get("mksc_shrn_iscd", ""),
|
"stock_code": item.get("stck_shrn_iscd") or item.get("mksc_shrn_iscd", ""),
|
||||||
"name": item.get("hts_kor_isnm", ""),
|
"name": item.get("hts_kor_isnm", ""),
|
||||||
"price": _safe_float(item.get("stck_prpr", "0")),
|
"price": _safe_float(item.get("stck_prpr", "0")),
|
||||||
"volume": _safe_float(item.get("acml_vol", "0")),
|
"volume": _safe_float(item.get("acml_vol", "0")),
|
||||||
@@ -478,6 +478,112 @@ class KISBroker:
|
|||||||
except (TimeoutError, aiohttp.ClientError) as exc:
|
except (TimeoutError, aiohttp.ClientError) as exc:
|
||||||
raise ConnectionError(f"Network error fetching rankings: {exc}") from exc
|
raise ConnectionError(f"Network error fetching rankings: {exc}") from exc
|
||||||
|
|
||||||
|
async def get_domestic_pending_orders(self) -> list[dict[str, Any]]:
|
||||||
|
"""Fetch unfilled (pending) domestic limit orders.
|
||||||
|
|
||||||
|
The KIS pending-orders API (TTTC0084R) is unsupported in paper (VTS)
|
||||||
|
mode, so this method returns an empty list immediately when MODE is
|
||||||
|
not "live".
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
List of pending order dicts from the KIS ``output`` field.
|
||||||
|
Each dict includes keys such as ``odno``, ``orgn_odno``,
|
||||||
|
``ord_gno_brno``, ``psbl_qty``, ``sll_buy_dvsn_cd``, ``pdno``.
|
||||||
|
"""
|
||||||
|
if self._settings.MODE != "live":
|
||||||
|
logger.debug(
|
||||||
|
"get_domestic_pending_orders: paper mode — TTTC0084R unsupported, returning []"
|
||||||
|
)
|
||||||
|
return []
|
||||||
|
|
||||||
|
await self._rate_limiter.acquire()
|
||||||
|
session = self._get_session()
|
||||||
|
|
||||||
|
# TR_ID: 실전 TTTC0084R (모의 미지원)
|
||||||
|
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '주식 미체결조회' 시트
|
||||||
|
headers = await self._auth_headers("TTTC0084R")
|
||||||
|
params = {
|
||||||
|
"CANO": self._account_no,
|
||||||
|
"ACNT_PRDT_CD": self._product_cd,
|
||||||
|
"INQR_DVSN_1": "0",
|
||||||
|
"INQR_DVSN_2": "0",
|
||||||
|
"CTX_AREA_FK100": "",
|
||||||
|
"CTX_AREA_NK100": "",
|
||||||
|
}
|
||||||
|
url = f"{self._base_url}/uapi/domestic-stock/v1/trading/inquire-psbl-rvsecncl"
|
||||||
|
|
||||||
|
try:
|
||||||
|
async with session.get(url, headers=headers, params=params) as resp:
|
||||||
|
if resp.status != 200:
|
||||||
|
text = await resp.text()
|
||||||
|
raise ConnectionError(
|
||||||
|
f"get_domestic_pending_orders failed ({resp.status}): {text}"
|
||||||
|
)
|
||||||
|
data = await resp.json()
|
||||||
|
return data.get("output", []) or []
|
||||||
|
except (TimeoutError, aiohttp.ClientError) as exc:
|
||||||
|
raise ConnectionError(
|
||||||
|
f"Network error fetching domestic pending orders: {exc}"
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
async def cancel_domestic_order(
|
||||||
|
self,
|
||||||
|
stock_code: str,
|
||||||
|
orgn_odno: str,
|
||||||
|
krx_fwdg_ord_orgno: str,
|
||||||
|
qty: int,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Cancel an unfilled domestic limit order.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stock_code: 6-digit domestic stock code (``pdno``).
|
||||||
|
orgn_odno: Original order number from pending-orders response
|
||||||
|
(``orgn_odno`` field).
|
||||||
|
krx_fwdg_ord_orgno: KRX forwarding order branch number from
|
||||||
|
pending-orders response (``ord_gno_brno`` field).
|
||||||
|
qty: Quantity to cancel (use ``psbl_qty`` from pending order).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Raw KIS API response dict (check ``rt_cd == "0"`` for success).
|
||||||
|
"""
|
||||||
|
await self._rate_limiter.acquire()
|
||||||
|
session = self._get_session()
|
||||||
|
|
||||||
|
# TR_ID: 실전 TTTC0013U, 모의 VTTC0013U
|
||||||
|
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '주식주문(정정취소)' 시트
|
||||||
|
tr_id = "TTTC0013U" if self._settings.MODE == "live" else "VTTC0013U"
|
||||||
|
|
||||||
|
body = {
|
||||||
|
"CANO": self._account_no,
|
||||||
|
"ACNT_PRDT_CD": self._product_cd,
|
||||||
|
"KRX_FWDG_ORD_ORGNO": krx_fwdg_ord_orgno,
|
||||||
|
"ORGN_ODNO": orgn_odno,
|
||||||
|
"ORD_DVSN": "00",
|
||||||
|
"ORD_QTY": str(qty),
|
||||||
|
"ORD_UNPR": "0",
|
||||||
|
"RVSE_CNCL_DVSN_CD": "02",
|
||||||
|
"QTY_ALL_ORD_YN": "Y",
|
||||||
|
}
|
||||||
|
|
||||||
|
hash_key = await self._get_hash_key(body)
|
||||||
|
headers = await self._auth_headers(tr_id)
|
||||||
|
headers["hashkey"] = hash_key
|
||||||
|
|
||||||
|
url = f"{self._base_url}/uapi/domestic-stock/v1/trading/order-rvsecncl"
|
||||||
|
|
||||||
|
try:
|
||||||
|
async with session.post(url, headers=headers, json=body) as resp:
|
||||||
|
if resp.status != 200:
|
||||||
|
text = await resp.text()
|
||||||
|
raise ConnectionError(
|
||||||
|
f"cancel_domestic_order failed ({resp.status}): {text}"
|
||||||
|
)
|
||||||
|
return cast(dict[str, Any], await resp.json())
|
||||||
|
except (TimeoutError, aiohttp.ClientError) as exc:
|
||||||
|
raise ConnectionError(
|
||||||
|
f"Network error cancelling domestic order: {exc}"
|
||||||
|
) from exc
|
||||||
|
|
||||||
async def get_daily_prices(
|
async def get_daily_prices(
|
||||||
self,
|
self,
|
||||||
stock_code: str,
|
stock_code: str,
|
||||||
|
|||||||
@@ -121,6 +121,7 @@ class OverseasBroker:
|
|||||||
tr_id = self._broker._settings.OVERSEAS_RANKING_VOLUME_TR_ID
|
tr_id = self._broker._settings.OVERSEAS_RANKING_VOLUME_TR_ID
|
||||||
path = self._broker._settings.OVERSEAS_RANKING_VOLUME_PATH
|
path = self._broker._settings.OVERSEAS_RANKING_VOLUME_PATH
|
||||||
params: dict[str, str] = {
|
params: dict[str, str] = {
|
||||||
|
"KEYB": "", # NEXT KEY BUFF — Required, 공백
|
||||||
"AUTH": "",
|
"AUTH": "",
|
||||||
"EXCD": ranking_excd,
|
"EXCD": ranking_excd,
|
||||||
"MIXN": "0",
|
"MIXN": "0",
|
||||||
@@ -130,10 +131,11 @@ class OverseasBroker:
|
|||||||
tr_id = self._broker._settings.OVERSEAS_RANKING_FLUCT_TR_ID
|
tr_id = self._broker._settings.OVERSEAS_RANKING_FLUCT_TR_ID
|
||||||
path = self._broker._settings.OVERSEAS_RANKING_FLUCT_PATH
|
path = self._broker._settings.OVERSEAS_RANKING_FLUCT_PATH
|
||||||
params = {
|
params = {
|
||||||
|
"KEYB": "", # NEXT KEY BUFF — Required, 공백
|
||||||
"AUTH": "",
|
"AUTH": "",
|
||||||
"EXCD": ranking_excd,
|
"EXCD": ranking_excd,
|
||||||
"NDAY": "0",
|
"NDAY": "0",
|
||||||
"GUBN": "1",
|
"GUBN": "1", # 0=하락율, 1=상승율 — 변동성 스캐너는 급등 종목 우선
|
||||||
"VOL_RANG": "0",
|
"VOL_RANG": "0",
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -220,6 +222,59 @@ class OverseasBroker:
|
|||||||
f"Network error fetching overseas balance: {exc}"
|
f"Network error fetching overseas balance: {exc}"
|
||||||
) from exc
|
) from exc
|
||||||
|
|
||||||
|
async def get_overseas_buying_power(
|
||||||
|
self,
|
||||||
|
exchange_code: str,
|
||||||
|
stock_code: str,
|
||||||
|
price: float,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Fetch overseas buying power for a specific stock and price.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
exchange_code: Exchange code (e.g., "NASD", "NYSE")
|
||||||
|
stock_code: Stock ticker symbol
|
||||||
|
price: Current stock price (used for quantity calculation)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
API response; key field: output.ord_psbl_frcr_amt (주문가능외화금액)
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ConnectionError: On network or API errors
|
||||||
|
"""
|
||||||
|
await self._broker._rate_limiter.acquire()
|
||||||
|
session = self._broker._get_session()
|
||||||
|
|
||||||
|
# TR_ID: 실전 TTTS3007R, 모의 VTTS3007R
|
||||||
|
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '해외주식 매수가능금액조회' 시트
|
||||||
|
ps_tr_id = (
|
||||||
|
"TTTS3007R" if self._broker._settings.MODE == "live" else "VTTS3007R"
|
||||||
|
)
|
||||||
|
headers = await self._broker._auth_headers(ps_tr_id)
|
||||||
|
params = {
|
||||||
|
"CANO": self._broker._account_no,
|
||||||
|
"ACNT_PRDT_CD": self._broker._product_cd,
|
||||||
|
"OVRS_EXCG_CD": exchange_code,
|
||||||
|
"OVRS_ORD_UNPR": f"{price:.2f}",
|
||||||
|
"ITEM_CD": stock_code,
|
||||||
|
}
|
||||||
|
url = (
|
||||||
|
f"{self._broker._base_url}/uapi/overseas-stock/v1/trading/inquire-psamount"
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
async with session.get(url, headers=headers, params=params) as resp:
|
||||||
|
if resp.status != 200:
|
||||||
|
text = await resp.text()
|
||||||
|
raise ConnectionError(
|
||||||
|
f"get_overseas_buying_power failed ({resp.status}): {text}"
|
||||||
|
)
|
||||||
|
return await resp.json()
|
||||||
|
except (TimeoutError, aiohttp.ClientError) as exc:
|
||||||
|
raise ConnectionError(
|
||||||
|
f"Network error fetching overseas buying power: {exc}"
|
||||||
|
) from exc
|
||||||
|
|
||||||
async def send_overseas_order(
|
async def send_overseas_order(
|
||||||
self,
|
self,
|
||||||
exchange_code: str,
|
exchange_code: str,
|
||||||
|
|||||||
@@ -13,10 +13,11 @@ from fastapi import FastAPI, HTTPException, Query
|
|||||||
from fastapi.responses import FileResponse
|
from fastapi.responses import FileResponse
|
||||||
|
|
||||||
|
|
||||||
def create_dashboard_app(db_path: str) -> FastAPI:
|
def create_dashboard_app(db_path: str, mode: str = "paper") -> FastAPI:
|
||||||
"""Create dashboard FastAPI app bound to a SQLite database path."""
|
"""Create dashboard FastAPI app bound to a SQLite database path."""
|
||||||
app = FastAPI(title="The Ouroboros Dashboard", version="1.0.0")
|
app = FastAPI(title="The Ouroboros Dashboard", version="1.0.0")
|
||||||
app.state.db_path = db_path
|
app.state.db_path = db_path
|
||||||
|
app.state.mode = mode
|
||||||
|
|
||||||
@app.get("/")
|
@app.get("/")
|
||||||
def index() -> FileResponse:
|
def index() -> FileResponse:
|
||||||
@@ -111,6 +112,7 @@ def create_dashboard_app(db_path: str) -> FastAPI:
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
"date": today,
|
"date": today,
|
||||||
|
"mode": mode,
|
||||||
"markets": market_status,
|
"markets": market_status,
|
||||||
"totals": {
|
"totals": {
|
||||||
"trade_count": total_trades,
|
"trade_count": total_trades,
|
||||||
|
|||||||
@@ -43,6 +43,19 @@
|
|||||||
font-size: 12px; transition: border-color 0.2s;
|
font-size: 12px; transition: border-color 0.2s;
|
||||||
}
|
}
|
||||||
.refresh-btn:hover { border-color: var(--accent); color: var(--accent); }
|
.refresh-btn:hover { border-color: var(--accent); color: var(--accent); }
|
||||||
|
.mode-badge {
|
||||||
|
padding: 3px 10px; border-radius: 5px; font-size: 12px; font-weight: 700;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
}
|
||||||
|
.mode-badge.live {
|
||||||
|
background: rgba(224, 85, 85, 0.15); color: var(--red);
|
||||||
|
border: 1px solid rgba(224, 85, 85, 0.4);
|
||||||
|
animation: pulse-warn 2s ease-in-out infinite;
|
||||||
|
}
|
||||||
|
.mode-badge.paper {
|
||||||
|
background: rgba(232, 160, 64, 0.15); color: var(--warn);
|
||||||
|
border: 1px solid rgba(232, 160, 64, 0.4);
|
||||||
|
}
|
||||||
|
|
||||||
/* CB Gauge */
|
/* CB Gauge */
|
||||||
.cb-gauge-wrap {
|
.cb-gauge-wrap {
|
||||||
@@ -225,6 +238,7 @@
|
|||||||
<header>
|
<header>
|
||||||
<h1>🐍 The Ouroboros</h1>
|
<h1>🐍 The Ouroboros</h1>
|
||||||
<div class="header-right">
|
<div class="header-right">
|
||||||
|
<span class="mode-badge" id="mode-badge">--</span>
|
||||||
<div class="cb-gauge-wrap" id="cb-gauge" title="Circuit Breaker">
|
<div class="cb-gauge-wrap" id="cb-gauge" title="Circuit Breaker">
|
||||||
<span class="cb-dot unknown" id="cb-dot"></span>
|
<span class="cb-dot unknown" id="cb-dot"></span>
|
||||||
<span id="cb-label">CB --</span>
|
<span id="cb-label">CB --</span>
|
||||||
@@ -512,9 +526,22 @@
|
|||||||
}
|
}
|
||||||
document.getElementById('card-pnl-sub').textContent = `결정 ${t.decision_count ?? 0}건`;
|
document.getElementById('card-pnl-sub').textContent = `결정 ${t.decision_count ?? 0}건`;
|
||||||
renderCbGauge(d.circuit_breaker);
|
renderCbGauge(d.circuit_breaker);
|
||||||
|
renderModeBadge(d.mode);
|
||||||
} catch {}
|
} catch {}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function renderModeBadge(mode) {
|
||||||
|
const el = document.getElementById('mode-badge');
|
||||||
|
if (!el) return;
|
||||||
|
if (mode === 'live') {
|
||||||
|
el.textContent = '🔴 실전투자';
|
||||||
|
el.className = 'mode-badge live';
|
||||||
|
} else {
|
||||||
|
el.textContent = '🟡 모의투자';
|
||||||
|
el.className = 'mode-badge paper';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function fetchPerformance() {
|
async function fetchPerformance() {
|
||||||
try {
|
try {
|
||||||
const r = await fetch('/api/performance?market=all');
|
const r = await fetch('/api/performance?market=all');
|
||||||
|
|||||||
@@ -254,10 +254,11 @@ def get_open_position(
|
|||||||
"""Return open position if latest trade is BUY, else None."""
|
"""Return open position if latest trade is BUY, else None."""
|
||||||
cursor = conn.execute(
|
cursor = conn.execute(
|
||||||
"""
|
"""
|
||||||
SELECT action, decision_id, price, quantity
|
SELECT action, decision_id, price, quantity, timestamp
|
||||||
FROM trades
|
FROM trades
|
||||||
WHERE stock_code = ?
|
WHERE stock_code = ?
|
||||||
AND market = ?
|
AND market = ?
|
||||||
|
AND action IN ('BUY', 'SELL')
|
||||||
ORDER BY timestamp DESC
|
ORDER BY timestamp DESC
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
""",
|
""",
|
||||||
@@ -266,7 +267,7 @@ def get_open_position(
|
|||||||
row = cursor.fetchone()
|
row = cursor.fetchone()
|
||||||
if not row or row[0] != "BUY":
|
if not row or row[0] != "BUY":
|
||||||
return None
|
return None
|
||||||
return {"decision_id": row[1], "price": row[2], "quantity": row[3]}
|
return {"decision_id": row[1], "price": row[2], "quantity": row[3], "timestamp": row[4]}
|
||||||
|
|
||||||
|
|
||||||
def get_recent_symbols(
|
def get_recent_symbols(
|
||||||
|
|||||||
439
src/main.py
439
src/main.py
@@ -19,7 +19,7 @@ from src.analysis.smart_scanner import ScanCandidate, SmartVolatilityScanner
|
|||||||
from src.analysis.volatility import VolatilityAnalyzer
|
from src.analysis.volatility import VolatilityAnalyzer
|
||||||
from src.brain.context_selector import ContextSelector
|
from src.brain.context_selector import ContextSelector
|
||||||
from src.brain.gemini_client import GeminiClient, TradeDecision
|
from src.brain.gemini_client import GeminiClient, TradeDecision
|
||||||
from src.broker.kis_api import KISBroker
|
from src.broker.kis_api import KISBroker, kr_round_down
|
||||||
from src.broker.overseas import OverseasBroker
|
from src.broker.overseas import OverseasBroker
|
||||||
from src.config import Settings
|
from src.config import Settings
|
||||||
from src.context.aggregator import ContextAggregator
|
from src.context.aggregator import ContextAggregator
|
||||||
@@ -182,6 +182,9 @@ async def sync_positions_from_broker(
|
|||||||
qty = _extract_held_qty_from_balance(
|
qty = _extract_held_qty_from_balance(
|
||||||
balance_data, stock_code, is_domestic=market.is_domestic
|
balance_data, stock_code, is_domestic=market.is_domestic
|
||||||
)
|
)
|
||||||
|
avg_price = _extract_avg_price_from_balance(
|
||||||
|
balance_data, stock_code, is_domestic=market.is_domestic
|
||||||
|
)
|
||||||
log_trade(
|
log_trade(
|
||||||
conn=db_conn,
|
conn=db_conn,
|
||||||
stock_code=stock_code,
|
stock_code=stock_code,
|
||||||
@@ -189,7 +192,7 @@ async def sync_positions_from_broker(
|
|||||||
confidence=0,
|
confidence=0,
|
||||||
rationale="[startup-sync] Position detected from broker at startup",
|
rationale="[startup-sync] Position detected from broker at startup",
|
||||||
quantity=qty,
|
quantity=qty,
|
||||||
price=0.0,
|
price=avg_price,
|
||||||
market=log_market,
|
market=log_market,
|
||||||
exchange_code=market.exchange_code,
|
exchange_code=market.exchange_code,
|
||||||
mode=settings.MODE,
|
mode=settings.MODE,
|
||||||
@@ -257,7 +260,15 @@ def _extract_held_codes_from_balance(
|
|||||||
if is_domestic:
|
if is_domestic:
|
||||||
qty = int(holding.get("ord_psbl_qty") or holding.get("hldg_qty") or 0)
|
qty = int(holding.get("ord_psbl_qty") or holding.get("hldg_qty") or 0)
|
||||||
else:
|
else:
|
||||||
qty = int(holding.get("ovrs_cblc_qty") or holding.get("hldg_qty") or 0)
|
# ord_psbl_qty (주문가능수량) is the actual sellable quantity.
|
||||||
|
# ovrs_cblc_qty (해외잔고수량) includes unsettled/expired holdings
|
||||||
|
# that cannot actually be sold (e.g. expired warrants).
|
||||||
|
qty = int(
|
||||||
|
holding.get("ord_psbl_qty")
|
||||||
|
or holding.get("ovrs_cblc_qty")
|
||||||
|
or holding.get("hldg_qty")
|
||||||
|
or 0
|
||||||
|
)
|
||||||
if qty > 0:
|
if qty > 0:
|
||||||
codes.append(code)
|
codes.append(code)
|
||||||
return codes
|
return codes
|
||||||
@@ -280,10 +291,12 @@ def _extract_held_qty_from_balance(
|
|||||||
ord_psbl_qty — 주문가능수량 (preferred: excludes unsettled)
|
ord_psbl_qty — 주문가능수량 (preferred: excludes unsettled)
|
||||||
hldg_qty — 보유수량 (fallback)
|
hldg_qty — 보유수량 (fallback)
|
||||||
|
|
||||||
Overseas fields (output1):
|
Overseas fields (VTTS3012R / TTTS3012R output1):
|
||||||
ovrs_pdno — 종목코드
|
ovrs_pdno — 종목코드
|
||||||
ovrs_cblc_qty — 해외잔고수량 (preferred)
|
ord_psbl_qty — 주문가능수량 (preferred: actual sellable qty)
|
||||||
hldg_qty — 보유수량 (fallback)
|
ovrs_cblc_qty — 해외잔고수량 (fallback: total holding, may include
|
||||||
|
unsettled or expired positions with ord_psbl_qty=0)
|
||||||
|
hldg_qty — 보유수량 (last-resort fallback)
|
||||||
"""
|
"""
|
||||||
output1 = balance_data.get("output1", [])
|
output1 = balance_data.get("output1", [])
|
||||||
if isinstance(output1, dict):
|
if isinstance(output1, dict):
|
||||||
@@ -301,11 +314,47 @@ def _extract_held_qty_from_balance(
|
|||||||
if is_domestic:
|
if is_domestic:
|
||||||
qty = int(holding.get("ord_psbl_qty") or holding.get("hldg_qty") or 0)
|
qty = int(holding.get("ord_psbl_qty") or holding.get("hldg_qty") or 0)
|
||||||
else:
|
else:
|
||||||
qty = int(holding.get("ovrs_cblc_qty") or holding.get("hldg_qty") or 0)
|
qty = int(
|
||||||
|
holding.get("ord_psbl_qty")
|
||||||
|
or holding.get("ovrs_cblc_qty")
|
||||||
|
or holding.get("hldg_qty")
|
||||||
|
or 0
|
||||||
|
)
|
||||||
return qty
|
return qty
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_avg_price_from_balance(
|
||||||
|
balance_data: dict[str, Any],
|
||||||
|
stock_code: str,
|
||||||
|
*,
|
||||||
|
is_domestic: bool,
|
||||||
|
) -> float:
|
||||||
|
"""Extract the broker-reported average purchase price for a stock.
|
||||||
|
|
||||||
|
Uses ``pchs_avg_pric`` (매입평균가격) from the balance response (output1).
|
||||||
|
Returns 0.0 when absent so callers can use ``if price > 0`` as sentinel.
|
||||||
|
|
||||||
|
Domestic fields (VTTC8434R output1): pdno, pchs_avg_pric
|
||||||
|
Overseas fields (VTTS3012R output1): ovrs_pdno, pchs_avg_pric
|
||||||
|
"""
|
||||||
|
output1 = balance_data.get("output1", [])
|
||||||
|
if isinstance(output1, dict):
|
||||||
|
output1 = [output1]
|
||||||
|
if not isinstance(output1, list):
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
for holding in output1:
|
||||||
|
if not isinstance(holding, dict):
|
||||||
|
continue
|
||||||
|
code_key = "pdno" if is_domestic else "ovrs_pdno"
|
||||||
|
held_code = str(holding.get(code_key, "")).strip().upper()
|
||||||
|
if held_code != stock_code.strip().upper():
|
||||||
|
continue
|
||||||
|
return safe_float(holding.get("pchs_avg_pric"), 0.0)
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
|
||||||
def _determine_order_quantity(
|
def _determine_order_quantity(
|
||||||
*,
|
*,
|
||||||
action: str,
|
action: str,
|
||||||
@@ -428,6 +477,7 @@ async def trading_cycle(
|
|||||||
cycle_start_time = asyncio.get_event_loop().time()
|
cycle_start_time = asyncio.get_event_loop().time()
|
||||||
|
|
||||||
# 1. Fetch market data
|
# 1. Fetch market data
|
||||||
|
price_output: dict[str, Any] = {} # Populated for overseas markets; used for fallback metrics
|
||||||
if market.is_domestic:
|
if market.is_domestic:
|
||||||
current_price, price_change_pct, foreigner_net = await broker.get_current_price(
|
current_price, price_change_pct, foreigner_net = await broker.get_current_price(
|
||||||
stock_code
|
stock_code
|
||||||
@@ -459,9 +509,44 @@ async def trading_cycle(
|
|||||||
balance_info = {}
|
balance_info = {}
|
||||||
|
|
||||||
total_eval = safe_float(balance_info.get("frcr_evlu_tota", "0") or "0")
|
total_eval = safe_float(balance_info.get("frcr_evlu_tota", "0") or "0")
|
||||||
total_cash = safe_float(balance_info.get("frcr_dncl_amt_2", "0") or "0")
|
|
||||||
purchase_total = safe_float(balance_info.get("frcr_buy_amt_smtl", "0") or "0")
|
purchase_total = safe_float(balance_info.get("frcr_buy_amt_smtl", "0") or "0")
|
||||||
|
|
||||||
|
# Resolve current price first (needed for buying power API)
|
||||||
|
price_output = price_data.get("output", {})
|
||||||
|
current_price = safe_float(price_output.get("last", "0"))
|
||||||
|
if current_price <= 0:
|
||||||
|
market_candidates_lookup = scan_candidates.get(market.code, {})
|
||||||
|
cand_lookup = market_candidates_lookup.get(stock_code)
|
||||||
|
if cand_lookup and cand_lookup.price > 0:
|
||||||
|
logger.debug(
|
||||||
|
"Price API returned 0 for %s; using scanner candidate price %.4f",
|
||||||
|
stock_code,
|
||||||
|
cand_lookup.price,
|
||||||
|
)
|
||||||
|
current_price = cand_lookup.price
|
||||||
|
foreigner_net = 0.0 # Not available for overseas
|
||||||
|
price_change_pct = safe_float(price_output.get("rate", "0"))
|
||||||
|
|
||||||
|
# Fetch available foreign currency cash via inquire-psamount (TTTS3007R/VTTS3007R).
|
||||||
|
# TTTS3012R output2 does not include a cash/deposit field — frcr_dncl_amt_2 does not exist.
|
||||||
|
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '해외주식 매수가능금액조회' 시트
|
||||||
|
total_cash = 0.0
|
||||||
|
if current_price > 0:
|
||||||
|
try:
|
||||||
|
ps_data = await overseas_broker.get_overseas_buying_power(
|
||||||
|
market.exchange_code, stock_code, current_price
|
||||||
|
)
|
||||||
|
total_cash = safe_float(
|
||||||
|
ps_data.get("output", {}).get("ovrs_ord_psbl_amt", "0") or "0"
|
||||||
|
)
|
||||||
|
except ConnectionError as exc:
|
||||||
|
logger.warning(
|
||||||
|
"Could not fetch overseas buying power for %s/%s: %s",
|
||||||
|
market.exchange_code,
|
||||||
|
stock_code,
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
|
||||||
# Paper mode fallback: VTS overseas balance API often fails for many accounts.
|
# Paper mode fallback: VTS overseas balance API often fails for many accounts.
|
||||||
# Only activate in paper mode — live mode must use real balance from KIS.
|
# Only activate in paper mode — live mode must use real balance from KIS.
|
||||||
if (
|
if (
|
||||||
@@ -477,34 +562,6 @@ async def trading_cycle(
|
|||||||
)
|
)
|
||||||
total_cash = settings.PAPER_OVERSEAS_CASH
|
total_cash = settings.PAPER_OVERSEAS_CASH
|
||||||
|
|
||||||
current_price = safe_float(price_data.get("output", {}).get("last", "0"))
|
|
||||||
# Fallback: if price API returns 0, use scanner candidate price
|
|
||||||
if current_price <= 0:
|
|
||||||
market_candidates_lookup = scan_candidates.get(market.code, {})
|
|
||||||
cand_lookup = market_candidates_lookup.get(stock_code)
|
|
||||||
if cand_lookup and cand_lookup.price > 0:
|
|
||||||
logger.debug(
|
|
||||||
"Price API returned 0 for %s; using scanner candidate price %.4f",
|
|
||||||
stock_code,
|
|
||||||
cand_lookup.price,
|
|
||||||
)
|
|
||||||
current_price = cand_lookup.price
|
|
||||||
foreigner_net = 0.0 # Not available for overseas
|
|
||||||
price_change_pct = safe_float(price_data.get("output", {}).get("rate", "0"))
|
|
||||||
|
|
||||||
# Price API may return 0/empty for certain VTS exchange codes.
|
|
||||||
# Fall back to the scanner candidate's price so order sizing still works.
|
|
||||||
if current_price <= 0:
|
|
||||||
market_candidates_lookup = scan_candidates.get(market.code, {})
|
|
||||||
cand_lookup = market_candidates_lookup.get(stock_code)
|
|
||||||
if cand_lookup and cand_lookup.price > 0:
|
|
||||||
current_price = cand_lookup.price
|
|
||||||
logger.debug(
|
|
||||||
"Price API returned 0 for %s; using scanner price %.4f",
|
|
||||||
stock_code,
|
|
||||||
current_price,
|
|
||||||
)
|
|
||||||
|
|
||||||
# Calculate daily P&L %
|
# Calculate daily P&L %
|
||||||
pnl_pct = (
|
pnl_pct = (
|
||||||
((total_eval - purchase_total) / purchase_total * 100)
|
((total_eval - purchase_total) / purchase_total * 100)
|
||||||
@@ -526,6 +583,44 @@ async def trading_cycle(
|
|||||||
if candidate:
|
if candidate:
|
||||||
market_data["rsi"] = candidate.rsi
|
market_data["rsi"] = candidate.rsi
|
||||||
market_data["volume_ratio"] = candidate.volume_ratio
|
market_data["volume_ratio"] = candidate.volume_ratio
|
||||||
|
else:
|
||||||
|
# Holding stocks not in scanner: derive metrics from price API data already fetched.
|
||||||
|
# For overseas stocks, price_output contains high/low/rate from get_overseas_price.
|
||||||
|
# For domestic stocks, only price_change_pct is available from get_current_price.
|
||||||
|
market_data["rsi"] = max(0.0, min(100.0, 50.0 + price_change_pct * 2.0))
|
||||||
|
if price_output and current_price > 0:
|
||||||
|
pr_high = safe_float(
|
||||||
|
price_output.get("high") or price_output.get("ovrs_hgpr")
|
||||||
|
or price_output.get("stck_hgpr")
|
||||||
|
)
|
||||||
|
pr_low = safe_float(
|
||||||
|
price_output.get("low") or price_output.get("ovrs_lwpr")
|
||||||
|
or price_output.get("stck_lwpr")
|
||||||
|
)
|
||||||
|
if pr_high > 0 and pr_low > 0 and pr_high >= pr_low:
|
||||||
|
intraday_range_pct = (pr_high - pr_low) / current_price * 100.0
|
||||||
|
volatility_pct = max(abs(price_change_pct), intraday_range_pct)
|
||||||
|
market_data["volume_ratio"] = max(1.0, volatility_pct / 2.0)
|
||||||
|
else:
|
||||||
|
market_data["volume_ratio"] = 1.0
|
||||||
|
else:
|
||||||
|
market_data["volume_ratio"] = 1.0
|
||||||
|
|
||||||
|
# Enrich market_data with holding info for SELL/HOLD scenario conditions
|
||||||
|
open_pos = get_open_position(db_conn, stock_code, market.code)
|
||||||
|
if open_pos and current_price > 0:
|
||||||
|
entry_price = safe_float(open_pos.get("price"), 0.0)
|
||||||
|
if entry_price > 0:
|
||||||
|
market_data["unrealized_pnl_pct"] = (
|
||||||
|
(current_price - entry_price) / entry_price * 100
|
||||||
|
)
|
||||||
|
entry_ts = open_pos.get("timestamp")
|
||||||
|
if entry_ts:
|
||||||
|
try:
|
||||||
|
entry_date = datetime.fromisoformat(entry_ts).date()
|
||||||
|
market_data["holding_days"] = (datetime.now(UTC).date() - entry_date).days
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
|
||||||
# 1.3. Record L7 real-time context (market-scoped keys)
|
# 1.3. Record L7 real-time context (market-scoped keys)
|
||||||
timeframe = datetime.now(UTC).isoformat()
|
timeframe = datetime.now(UTC).isoformat()
|
||||||
@@ -681,7 +776,7 @@ async def trading_cycle(
|
|||||||
open_position = get_open_position(db_conn, stock_code, market.code)
|
open_position = get_open_position(db_conn, stock_code, market.code)
|
||||||
if open_position:
|
if open_position:
|
||||||
entry_price = safe_float(open_position.get("price"), 0.0)
|
entry_price = safe_float(open_position.get("price"), 0.0)
|
||||||
if entry_price > 0:
|
if entry_price > 0 and current_price > 0:
|
||||||
loss_pct = (current_price - entry_price) / entry_price * 100
|
loss_pct = (current_price - entry_price) / entry_price * 100
|
||||||
stop_loss_threshold = -2.0
|
stop_loss_threshold = -2.0
|
||||||
take_profit_threshold = 3.0
|
take_profit_threshold = 3.0
|
||||||
@@ -853,11 +948,19 @@ async def trading_cycle(
|
|||||||
# 5. Send order
|
# 5. Send order
|
||||||
order_succeeded = True
|
order_succeeded = True
|
||||||
if market.is_domestic:
|
if market.is_domestic:
|
||||||
|
# Use limit orders (지정가) for domestic stocks to avoid market order
|
||||||
|
# quantity calculation issues. KRX tick rounding applied via kr_round_down.
|
||||||
|
# BUY: +0.2% — ensures fill even when ask is slightly above last price.
|
||||||
|
# SELL: -0.2% — ensures fill even when bid is slightly below last price.
|
||||||
|
if decision.action == "BUY":
|
||||||
|
order_price = kr_round_down(current_price * 1.002)
|
||||||
|
else:
|
||||||
|
order_price = kr_round_down(current_price * 0.998)
|
||||||
result = await broker.send_order(
|
result = await broker.send_order(
|
||||||
stock_code=stock_code,
|
stock_code=stock_code,
|
||||||
order_type=decision.action,
|
order_type=decision.action,
|
||||||
quantity=quantity,
|
quantity=quantity,
|
||||||
price=0, # market order
|
price=order_price,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
# For overseas orders, always use limit orders (지정가):
|
# For overseas orders, always use limit orders (지정가):
|
||||||
@@ -867,16 +970,20 @@ async def trading_cycle(
|
|||||||
# achieving >90% fill rate on large-cap US stocks.
|
# achieving >90% fill rate on large-cap US stocks.
|
||||||
# - SELL: -0.2% below last price — ensures fill even when price dips slightly
|
# - SELL: -0.2% below last price — ensures fill even when price dips slightly
|
||||||
# (placing at exact last price risks no-fill if the bid is just below).
|
# (placing at exact last price risks no-fill if the bid is just below).
|
||||||
|
overseas_price: float
|
||||||
|
# KIS requires at most 2 decimal places for prices >= $1 (≥1달러 소수점 2자리 제한).
|
||||||
|
# Penny stocks (< $1) keep 4 decimal places to preserve price precision.
|
||||||
|
_price_decimals = 2 if current_price >= 1.0 else 4
|
||||||
if decision.action == "BUY":
|
if decision.action == "BUY":
|
||||||
order_price = round(current_price * 1.002, 4)
|
overseas_price = round(current_price * 1.002, _price_decimals)
|
||||||
else:
|
else:
|
||||||
order_price = round(current_price * 0.998, 4)
|
overseas_price = round(current_price * 0.998, _price_decimals)
|
||||||
result = await overseas_broker.send_overseas_order(
|
result = await overseas_broker.send_overseas_order(
|
||||||
exchange_code=market.exchange_code,
|
exchange_code=market.exchange_code,
|
||||||
stock_code=stock_code,
|
stock_code=stock_code,
|
||||||
order_type=decision.action,
|
order_type=decision.action,
|
||||||
quantity=quantity,
|
quantity=quantity,
|
||||||
price=order_price, # limit order
|
price=overseas_price, # limit order
|
||||||
)
|
)
|
||||||
# Check if KIS rejected the order (rt_cd != "0")
|
# Check if KIS rejected the order (rt_cd != "0")
|
||||||
if result.get("rt_cd", "") != "0":
|
if result.get("rt_cd", "") != "0":
|
||||||
@@ -899,6 +1006,33 @@ async def trading_cycle(
|
|||||||
stock_code,
|
stock_code,
|
||||||
_BUY_COOLDOWN_SECONDS,
|
_BUY_COOLDOWN_SECONDS,
|
||||||
)
|
)
|
||||||
|
# Close ghost position when broker has no matching balance.
|
||||||
|
# This prevents infinite SELL retry cycles for positions that
|
||||||
|
# exist in the DB (from startup sync) but are no longer
|
||||||
|
# sellable at the broker (expired warrants, delisted stocks, etc.)
|
||||||
|
if decision.action == "SELL" and "잔고내역이 없습니다" in msg1:
|
||||||
|
logger.warning(
|
||||||
|
"Ghost position detected for %s (%s): broker reports no balance."
|
||||||
|
" Closing DB position to prevent infinite retry.",
|
||||||
|
stock_code,
|
||||||
|
market.exchange_code,
|
||||||
|
)
|
||||||
|
log_trade(
|
||||||
|
conn=db_conn,
|
||||||
|
stock_code=stock_code,
|
||||||
|
action="SELL",
|
||||||
|
confidence=0,
|
||||||
|
rationale=(
|
||||||
|
"[ghost-close] Broker reported no balance;"
|
||||||
|
" position closed without fill"
|
||||||
|
),
|
||||||
|
quantity=0,
|
||||||
|
price=0.0,
|
||||||
|
pnl=0.0,
|
||||||
|
market=market.code,
|
||||||
|
exchange_code=market.exchange_code,
|
||||||
|
mode=settings.MODE if settings else "paper",
|
||||||
|
)
|
||||||
logger.info("Order result: %s", result.get("msg1", "OK"))
|
logger.info("Order result: %s", result.get("msg1", "OK"))
|
||||||
|
|
||||||
# 5.5. Notify trade execution (only on success)
|
# 5.5. Notify trade execution (only on success)
|
||||||
@@ -978,6 +1112,153 @@ async def trading_cycle(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def handle_domestic_pending_orders(
|
||||||
|
broker: KISBroker,
|
||||||
|
telegram: TelegramClient,
|
||||||
|
settings: Settings,
|
||||||
|
sell_resubmit_counts: dict[str, int],
|
||||||
|
buy_cooldown: dict[str, float] | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Check and handle unfilled (pending) domestic limit orders.
|
||||||
|
|
||||||
|
Called once per market loop iteration before new orders are considered.
|
||||||
|
In paper mode the KIS pending-orders API (TTTC0084R) is unsupported, so
|
||||||
|
``get_domestic_pending_orders`` returns [] immediately and this function
|
||||||
|
exits without making further API calls.
|
||||||
|
|
||||||
|
BUY pending → cancel (to free up balance) + optionally set cooldown.
|
||||||
|
SELL pending → cancel then resubmit at a wider spread (-0.4% from last
|
||||||
|
price, kr_round_down applied). Resubmission is attempted
|
||||||
|
at most once per key per session to avoid infinite loops.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
broker: KISBroker instance.
|
||||||
|
telegram: TelegramClient for notifications.
|
||||||
|
settings: Application settings.
|
||||||
|
sell_resubmit_counts: Mutable dict tracking SELL resubmission attempts
|
||||||
|
per "KR:{stock_code}" key. Passed by reference so counts persist
|
||||||
|
across calls within the same session.
|
||||||
|
buy_cooldown: Optional cooldown dict shared with the main trading loop.
|
||||||
|
When provided, cancelled BUY orders are added with a
|
||||||
|
_BUY_COOLDOWN_SECONDS expiry.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
orders = await broker.get_domestic_pending_orders()
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Failed to fetch domestic pending orders: %s", exc)
|
||||||
|
return
|
||||||
|
|
||||||
|
now = asyncio.get_event_loop().time()
|
||||||
|
|
||||||
|
for order in orders:
|
||||||
|
try:
|
||||||
|
stock_code = order.get("pdno", "")
|
||||||
|
orgn_odno = order.get("orgn_odno", "")
|
||||||
|
krx_fwdg_ord_orgno = order.get("ord_gno_brno", "")
|
||||||
|
sll_buy = order.get("sll_buy_dvsn_cd", "") # "01"=SELL, "02"=BUY
|
||||||
|
psbl_qty = int(order.get("psbl_qty", "0") or "0")
|
||||||
|
key = f"KR:{stock_code}"
|
||||||
|
|
||||||
|
if not stock_code or not orgn_odno or psbl_qty <= 0:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Cancel the pending order first regardless of direction.
|
||||||
|
cancel_result = await broker.cancel_domestic_order(
|
||||||
|
stock_code=stock_code,
|
||||||
|
orgn_odno=orgn_odno,
|
||||||
|
krx_fwdg_ord_orgno=krx_fwdg_ord_orgno,
|
||||||
|
qty=psbl_qty,
|
||||||
|
)
|
||||||
|
if cancel_result.get("rt_cd") != "0":
|
||||||
|
logger.warning(
|
||||||
|
"Cancel failed for KR %s: rt_cd=%s msg=%s",
|
||||||
|
stock_code,
|
||||||
|
cancel_result.get("rt_cd"),
|
||||||
|
cancel_result.get("msg1"),
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if sll_buy == "02":
|
||||||
|
# BUY pending → cancelled; set cooldown to avoid immediate re-buy.
|
||||||
|
if buy_cooldown is not None:
|
||||||
|
buy_cooldown[key] = now + _BUY_COOLDOWN_SECONDS
|
||||||
|
try:
|
||||||
|
await telegram.notify_unfilled_order(
|
||||||
|
stock_code=stock_code,
|
||||||
|
market="KR",
|
||||||
|
action="BUY",
|
||||||
|
quantity=psbl_qty,
|
||||||
|
outcome="cancelled",
|
||||||
|
)
|
||||||
|
except Exception as notify_exc:
|
||||||
|
logger.warning("notify_unfilled_order failed: %s", notify_exc)
|
||||||
|
|
||||||
|
elif sll_buy == "01":
|
||||||
|
# SELL pending — attempt one resubmit at a wider spread.
|
||||||
|
if sell_resubmit_counts.get(key, 0) >= 1:
|
||||||
|
# Already resubmitted once — only cancel (already done above).
|
||||||
|
logger.warning(
|
||||||
|
"SELL KR %s already resubmitted once — no further resubmit",
|
||||||
|
stock_code,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
await telegram.notify_unfilled_order(
|
||||||
|
stock_code=stock_code,
|
||||||
|
market="KR",
|
||||||
|
action="SELL",
|
||||||
|
quantity=psbl_qty,
|
||||||
|
outcome="cancelled",
|
||||||
|
)
|
||||||
|
except Exception as notify_exc:
|
||||||
|
logger.warning(
|
||||||
|
"notify_unfilled_order failed: %s", notify_exc
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# First unfilled SELL → resubmit at last * 0.996 (-0.4%).
|
||||||
|
try:
|
||||||
|
last_price, _, _ = await broker.get_current_price(stock_code)
|
||||||
|
if last_price <= 0:
|
||||||
|
raise ValueError(
|
||||||
|
f"Invalid price ({last_price}) for {stock_code}"
|
||||||
|
)
|
||||||
|
new_price = kr_round_down(last_price * 0.996)
|
||||||
|
await broker.send_order(
|
||||||
|
stock_code=stock_code,
|
||||||
|
order_type="SELL",
|
||||||
|
quantity=psbl_qty,
|
||||||
|
price=new_price,
|
||||||
|
)
|
||||||
|
sell_resubmit_counts[key] = (
|
||||||
|
sell_resubmit_counts.get(key, 0) + 1
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
await telegram.notify_unfilled_order(
|
||||||
|
stock_code=stock_code,
|
||||||
|
market="KR",
|
||||||
|
action="SELL",
|
||||||
|
quantity=psbl_qty,
|
||||||
|
outcome="resubmitted",
|
||||||
|
new_price=float(new_price),
|
||||||
|
)
|
||||||
|
except Exception as notify_exc:
|
||||||
|
logger.warning(
|
||||||
|
"notify_unfilled_order failed: %s", notify_exc
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.error(
|
||||||
|
"SELL resubmit failed for KR %s: %s",
|
||||||
|
stock_code,
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
logger.error(
|
||||||
|
"Error handling domestic pending order for %s: %s",
|
||||||
|
order.get("pdno", "?"),
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
async def handle_overseas_pending_orders(
|
async def handle_overseas_pending_orders(
|
||||||
overseas_broker: OverseasBroker,
|
overseas_broker: OverseasBroker,
|
||||||
telegram: TelegramClient,
|
telegram: TelegramClient,
|
||||||
@@ -1205,6 +1486,19 @@ async def run_daily_session(
|
|||||||
# Use market-local date for playbook keying
|
# Use market-local date for playbook keying
|
||||||
market_today = datetime.now(market.timezone).date()
|
market_today = datetime.now(market.timezone).date()
|
||||||
|
|
||||||
|
# Check and handle domestic pending (unfilled) limit orders before new decisions.
|
||||||
|
if market.is_domestic:
|
||||||
|
try:
|
||||||
|
await handle_domestic_pending_orders(
|
||||||
|
broker,
|
||||||
|
telegram,
|
||||||
|
settings,
|
||||||
|
sell_resubmit_counts,
|
||||||
|
daily_buy_cooldown,
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Domestic pending order check failed: %s", exc)
|
||||||
|
|
||||||
# Check and handle overseas pending (unfilled) limit orders before new decisions.
|
# Check and handle overseas pending (unfilled) limit orders before new decisions.
|
||||||
if not market.is_domestic:
|
if not market.is_domestic:
|
||||||
try:
|
try:
|
||||||
@@ -1229,8 +1523,9 @@ async def run_daily_session(
|
|||||||
active_stocks={},
|
active_stocks={},
|
||||||
)
|
)
|
||||||
if not fallback_stocks:
|
if not fallback_stocks:
|
||||||
logger.warning(
|
logger.debug(
|
||||||
"No dynamic overseas symbol universe for %s; scanner cannot run",
|
"No dynamic overseas symbol universe for %s;"
|
||||||
|
" scanner will use overseas ranking API",
|
||||||
market.code,
|
market.code,
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
@@ -1395,10 +1690,35 @@ async def run_daily_session(
|
|||||||
balance_info = {}
|
balance_info = {}
|
||||||
|
|
||||||
total_eval = safe_float(balance_info.get("frcr_evlu_tota", "0") or "0")
|
total_eval = safe_float(balance_info.get("frcr_evlu_tota", "0") or "0")
|
||||||
total_cash = safe_float(balance_info.get("frcr_dncl_amt_2", "0") or "0")
|
|
||||||
purchase_total = safe_float(
|
purchase_total = safe_float(
|
||||||
balance_info.get("frcr_buy_amt_smtl", "0") or "0"
|
balance_info.get("frcr_buy_amt_smtl", "0") or "0"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Fetch available foreign currency cash via inquire-psamount (TTTS3007R/VTTS3007R).
|
||||||
|
# TTTS3012R output2 does not include a cash/deposit field — frcr_dncl_amt_2 does not exist.
|
||||||
|
# Use the first stock with a valid price as the reference for the buying power query.
|
||||||
|
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '해외주식 매수가능금액조회' 시트
|
||||||
|
total_cash = 0.0
|
||||||
|
ref_stock = next(
|
||||||
|
(s for s in stocks_data if s.get("current_price", 0) > 0), None
|
||||||
|
)
|
||||||
|
if ref_stock:
|
||||||
|
try:
|
||||||
|
ps_data = await overseas_broker.get_overseas_buying_power(
|
||||||
|
market.exchange_code,
|
||||||
|
ref_stock["stock_code"],
|
||||||
|
ref_stock["current_price"],
|
||||||
|
)
|
||||||
|
total_cash = safe_float(
|
||||||
|
ps_data.get("output", {}).get("ovrs_ord_psbl_amt", "0") or "0"
|
||||||
|
)
|
||||||
|
except ConnectionError as exc:
|
||||||
|
logger.warning(
|
||||||
|
"Could not fetch overseas buying power for %s: %s",
|
||||||
|
market.exchange_code,
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
|
||||||
# Paper mode fallback: VTS overseas balance API often fails for many accounts.
|
# Paper mode fallback: VTS overseas balance API often fails for many accounts.
|
||||||
# Only activate in paper mode — live mode must use real balance from KIS.
|
# Only activate in paper mode — live mode must use real balance from KIS.
|
||||||
if (
|
if (
|
||||||
@@ -1607,11 +1927,21 @@ async def run_daily_session(
|
|||||||
order_succeeded = True
|
order_succeeded = True
|
||||||
try:
|
try:
|
||||||
if market.is_domestic:
|
if market.is_domestic:
|
||||||
|
# Use limit orders (지정가) for domestic stocks.
|
||||||
|
# KRX tick rounding applied via kr_round_down.
|
||||||
|
if decision.action == "BUY":
|
||||||
|
order_price = kr_round_down(
|
||||||
|
stock_data["current_price"] * 1.002
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
order_price = kr_round_down(
|
||||||
|
stock_data["current_price"] * 0.998
|
||||||
|
)
|
||||||
result = await broker.send_order(
|
result = await broker.send_order(
|
||||||
stock_code=stock_code,
|
stock_code=stock_code,
|
||||||
order_type=decision.action,
|
order_type=decision.action,
|
||||||
quantity=quantity,
|
quantity=quantity,
|
||||||
price=0, # market order
|
price=order_price,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
# KIS VTS only accepts limit orders; use 0.5% premium for BUY
|
# KIS VTS only accepts limit orders; use 0.5% premium for BUY
|
||||||
@@ -1824,7 +2154,7 @@ def _start_dashboard_server(settings: Settings) -> threading.Thread | None:
|
|||||||
import uvicorn
|
import uvicorn
|
||||||
from src.dashboard import create_dashboard_app
|
from src.dashboard import create_dashboard_app
|
||||||
|
|
||||||
app = create_dashboard_app(settings.DB_PATH)
|
app = create_dashboard_app(settings.DB_PATH, mode=settings.MODE)
|
||||||
uvicorn.run(
|
uvicorn.run(
|
||||||
app,
|
app,
|
||||||
host=settings.DASHBOARD_HOST,
|
host=settings.DASHBOARD_HOST,
|
||||||
@@ -2464,6 +2794,19 @@ async def run(settings: Settings) -> None:
|
|||||||
logger.warning("Market open notification failed: %s", exc)
|
logger.warning("Market open notification failed: %s", exc)
|
||||||
_market_states[market.code] = True
|
_market_states[market.code] = True
|
||||||
|
|
||||||
|
# Check and handle domestic pending (unfilled) limit orders.
|
||||||
|
if market.is_domestic:
|
||||||
|
try:
|
||||||
|
await handle_domestic_pending_orders(
|
||||||
|
broker,
|
||||||
|
telegram,
|
||||||
|
settings,
|
||||||
|
sell_resubmit_counts,
|
||||||
|
buy_cooldown,
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning("Domestic pending order check failed: %s", exc)
|
||||||
|
|
||||||
# Check and handle overseas pending (unfilled) limit orders.
|
# Check and handle overseas pending (unfilled) limit orders.
|
||||||
if not market.is_domestic:
|
if not market.is_domestic:
|
||||||
try:
|
try:
|
||||||
@@ -2494,9 +2837,9 @@ async def run(settings: Settings) -> None:
|
|||||||
active_stocks=active_stocks,
|
active_stocks=active_stocks,
|
||||||
)
|
)
|
||||||
if not fallback_stocks:
|
if not fallback_stocks:
|
||||||
logger.warning(
|
logger.debug(
|
||||||
"No dynamic overseas symbol universe for %s;"
|
"No dynamic overseas symbol universe for %s;"
|
||||||
" scanner cannot run",
|
" scanner will use overseas ranking API",
|
||||||
market.code,
|
market.code,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -1,114 +0,0 @@
|
|||||||
"""Auto-generated strategy: v20260220_210124
|
|
||||||
|
|
||||||
Generated at: 2026-02-20T21:01:24.706847+00:00
|
|
||||||
Rationale: Auto-evolved from 6 failures. Primary failure markets: ['US_AMEX', 'US_NYSE', 'US_NASDAQ']. Average loss: -194.69
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
from typing import Any
|
|
||||||
from src.strategies.base import BaseStrategy
|
|
||||||
|
|
||||||
|
|
||||||
class Strategy_v20260220_210124(BaseStrategy):
|
|
||||||
"""Strategy: v20260220_210124"""
|
|
||||||
|
|
||||||
def evaluate(self, market_data: dict[str, Any]) -> dict[str, Any]:
|
|
||||||
import datetime
|
|
||||||
|
|
||||||
# --- Strategy Constants ---
|
|
||||||
# Minimum price for a stock to be considered for trading (avoids penny stocks)
|
|
||||||
MIN_PRICE = 5.0
|
|
||||||
|
|
||||||
# Momentum signal thresholds (stricter than previous failures)
|
|
||||||
MOMENTUM_PRICE_CHANGE_THRESHOLD = 7.0 # % price change
|
|
||||||
MOMENTUM_VOLUME_RATIO_THRESHOLD = 4.0 # X times average volume
|
|
||||||
|
|
||||||
# Oversold signal thresholds (more conservative)
|
|
||||||
OVERSOLD_RSI_THRESHOLD = 25.0 # RSI value (lower means more oversold)
|
|
||||||
|
|
||||||
# Confidence levels
|
|
||||||
CONFIDENCE_HOLD = 30
|
|
||||||
CONFIDENCE_BUY_OVERSOLD = 65
|
|
||||||
CONFIDENCE_BUY_MOMENTUM = 85
|
|
||||||
CONFIDENCE_BUY_STRONG_MOMENTUM = 90 # For higher-priced stocks with strong momentum
|
|
||||||
|
|
||||||
# Market hours in UTC (9:30 AM ET to 4:00 PM ET)
|
|
||||||
MARKET_OPEN_UTC = datetime.time(14, 30)
|
|
||||||
MARKET_CLOSE_UTC = datetime.time(21, 0)
|
|
||||||
|
|
||||||
# Volatile periods within market hours (UTC) to avoid
|
|
||||||
# First hour after open (14:30 UTC - 15:30 UTC)
|
|
||||||
VOLATILE_OPEN_END_UTC = datetime.time(15, 30)
|
|
||||||
# Last 30 minutes before close (20:30 UTC - 21:00 UTC)
|
|
||||||
VOLATILE_CLOSE_START_UTC = datetime.time(20, 30)
|
|
||||||
|
|
||||||
current_price = market_data.get('current_price')
|
|
||||||
price_change_pct = market_data.get('price_change_pct')
|
|
||||||
volume_ratio = market_data.get('volume_ratio') # Assumed pre-computed indicator
|
|
||||||
rsi = market_data.get('rsi') # Assumed pre-computed indicator
|
|
||||||
timestamp_str = market_data.get('timestamp')
|
|
||||||
|
|
||||||
action = "HOLD"
|
|
||||||
confidence = CONFIDENCE_HOLD
|
|
||||||
rationale = "Initial HOLD: No clear signal or conditions not met."
|
|
||||||
|
|
||||||
# --- 1. Basic Data Validation ---
|
|
||||||
if current_price is None or price_change_pct is None:
|
|
||||||
return {"action": "HOLD", "confidence": CONFIDENCE_HOLD,
|
|
||||||
"rationale": "Insufficient core data (price or price change) to evaluate."}
|
|
||||||
|
|
||||||
# --- 2. Price Filter: Avoid low-priced/penny stocks ---
|
|
||||||
if current_price < MIN_PRICE:
|
|
||||||
return {"action": "HOLD", "confidence": CONFIDENCE_HOLD,
|
|
||||||
"rationale": f"Avoiding low-priced stock (${current_price:.2f} < ${MIN_PRICE:.2f})."}
|
|
||||||
|
|
||||||
# --- 3. Time Filter: Only trade during core market hours ---
|
|
||||||
if timestamp_str:
|
|
||||||
try:
|
|
||||||
dt_object = datetime.datetime.fromisoformat(timestamp_str)
|
|
||||||
current_time_utc = dt_object.time()
|
|
||||||
|
|
||||||
if not (MARKET_OPEN_UTC <= current_time_utc < MARKET_CLOSE_UTC):
|
|
||||||
return {"action": "HOLD", "confidence": CONFIDENCE_HOLD,
|
|
||||||
"rationale": f"Avoiding trade outside core market hours ({current_time_utc} UTC)."}
|
|
||||||
|
|
||||||
if (MARKET_OPEN_UTC <= current_time_utc < VOLATILE_OPEN_END_UTC) or \
|
|
||||||
(VOLATILE_CLOSE_START_UTC <= current_time_utc < MARKET_CLOSE_UTC):
|
|
||||||
return {"action": "HOLD", "confidence": CONFIDENCE_HOLD,
|
|
||||||
"rationale": f"Avoiding trade during volatile market open/close periods ({current_time_utc} UTC)."}
|
|
||||||
|
|
||||||
except ValueError:
|
|
||||||
rationale += " (Warning: Malformed timestamp, time filters skipped)"
|
|
||||||
|
|
||||||
# --- Initialize signal states ---
|
|
||||||
has_momentum_buy_signal = False
|
|
||||||
has_oversold_buy_signal = False
|
|
||||||
|
|
||||||
# --- 4. Evaluate Enhanced Buy Signals ---
|
|
||||||
|
|
||||||
# Momentum Buy Signal
|
|
||||||
if volume_ratio is not None and \
|
|
||||||
price_change_pct > MOMENTUM_PRICE_CHANGE_THRESHOLD and \
|
|
||||||
volume_ratio > MOMENTUM_VOLUME_RATIO_THRESHOLD:
|
|
||||||
has_momentum_buy_signal = True
|
|
||||||
rationale = f"Momentum BUY: Price change {price_change_pct:.2f}%, Volume {volume_ratio:.2f}x."
|
|
||||||
confidence = CONFIDENCE_BUY_MOMENTUM
|
|
||||||
if current_price >= 10.0:
|
|
||||||
confidence = CONFIDENCE_BUY_STRONG_MOMENTUM
|
|
||||||
|
|
||||||
# Oversold Buy Signal
|
|
||||||
if rsi is not None and rsi < OVERSOLD_RSI_THRESHOLD:
|
|
||||||
has_oversold_buy_signal = True
|
|
||||||
if not has_momentum_buy_signal:
|
|
||||||
rationale = f"Oversold BUY: RSI {rsi:.2f}."
|
|
||||||
confidence = CONFIDENCE_BUY_OVERSOLD
|
|
||||||
if current_price >= 10.0:
|
|
||||||
confidence = min(CONFIDENCE_BUY_OVERSOLD + 5, 80)
|
|
||||||
|
|
||||||
# --- 5. Decision Logic ---
|
|
||||||
if has_momentum_buy_signal:
|
|
||||||
action = "BUY"
|
|
||||||
elif has_oversold_buy_signal:
|
|
||||||
action = "BUY"
|
|
||||||
|
|
||||||
return {"action": action, "confidence": confidence, "rationale": rationale}
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
"""Auto-generated strategy: v20260220_210159
|
|
||||||
|
|
||||||
Generated at: 2026-02-20T21:01:59.391523+00:00
|
|
||||||
Rationale: Auto-evolved from 6 failures. Primary failure markets: ['US_AMEX', 'US_NYSE', 'US_NASDAQ']. Average loss: -194.69
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
from typing import Any
|
|
||||||
from src.strategies.base import BaseStrategy
|
|
||||||
|
|
||||||
|
|
||||||
class Strategy_v20260220_210159(BaseStrategy):
|
|
||||||
"""Strategy: v20260220_210159"""
|
|
||||||
|
|
||||||
def evaluate(self, market_data: dict[str, Any]) -> dict[str, Any]:
|
|
||||||
import datetime
|
|
||||||
|
|
||||||
current_price = market_data.get('current_price')
|
|
||||||
price_change_pct = market_data.get('price_change_pct')
|
|
||||||
volume_ratio = market_data.get('volume_ratio')
|
|
||||||
rsi = market_data.get('rsi')
|
|
||||||
timestamp_str = market_data.get('timestamp')
|
|
||||||
market_name = market_data.get('market')
|
|
||||||
|
|
||||||
# Default action
|
|
||||||
action = "HOLD"
|
|
||||||
confidence = 0
|
|
||||||
rationale = "No strong signal or conditions not met."
|
|
||||||
|
|
||||||
# --- FAILURE PATTERN AVOIDANCE ---
|
|
||||||
|
|
||||||
# 1. Avoid low-priced/penny stocks
|
|
||||||
MIN_PRICE_THRESHOLD = 5.0 # USD
|
|
||||||
if current_price is not None and current_price < MIN_PRICE_THRESHOLD:
|
|
||||||
rationale = (
|
|
||||||
f"HOLD: Stock price (${current_price:.2f}) is below minimum threshold "
|
|
||||||
f"(${MIN_PRICE_THRESHOLD:.2f}). Past failures consistently involved low-priced stocks."
|
|
||||||
)
|
|
||||||
return {"action": action, "confidence": confidence, "rationale": rationale}
|
|
||||||
|
|
||||||
# 2. Avoid early market hour volatility
|
|
||||||
if timestamp_str:
|
|
||||||
try:
|
|
||||||
dt_obj = datetime.datetime.fromisoformat(timestamp_str)
|
|
||||||
utc_hour = dt_obj.hour
|
|
||||||
utc_minute = dt_obj.minute
|
|
||||||
|
|
||||||
if (utc_hour == 14 and utc_minute < 45) or (utc_hour == 13 and utc_minute >= 30):
|
|
||||||
rationale = (
|
|
||||||
f"HOLD: Trading during early market hours (UTC {utc_hour}:{utc_minute}), "
|
|
||||||
f"a period identified with past failures due to high volatility."
|
|
||||||
)
|
|
||||||
return {"action": action, "confidence": confidence, "rationale": rationale}
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# --- IMPROVED BUY STRATEGY ---
|
|
||||||
|
|
||||||
# Momentum BUY signal
|
|
||||||
if volume_ratio is not None and price_change_pct is not None:
|
|
||||||
if price_change_pct > 7.0 and volume_ratio > 3.0:
|
|
||||||
action = "BUY"
|
|
||||||
confidence = 70
|
|
||||||
rationale = "Improved BUY: Momentum signal with high volume and above price threshold."
|
|
||||||
|
|
||||||
if market_name == 'US_AMEX':
|
|
||||||
confidence = max(55, confidence - 5)
|
|
||||||
rationale += " (Adjusted lower for AMEX market's higher risk profile)."
|
|
||||||
elif market_name == 'US_NASDAQ' and price_change_pct > 20:
|
|
||||||
confidence = max(50, confidence - 10)
|
|
||||||
rationale += " (Adjusted lower for aggressive NASDAQ momentum volatility)."
|
|
||||||
|
|
||||||
if price_change_pct > 15.0:
|
|
||||||
confidence = max(50, confidence - 5)
|
|
||||||
rationale += " (Caution: Very high daily price change, potential for reversal)."
|
|
||||||
|
|
||||||
return {"action": action, "confidence": confidence, "rationale": rationale}
|
|
||||||
|
|
||||||
# Oversold BUY signal
|
|
||||||
if rsi is not None and price_change_pct is not None:
|
|
||||||
if rsi < 30 and price_change_pct < -3.0:
|
|
||||||
action = "BUY"
|
|
||||||
confidence = 65
|
|
||||||
rationale = "Improved BUY: Oversold signal with recent decline and above price threshold."
|
|
||||||
|
|
||||||
if market_name == 'US_AMEX':
|
|
||||||
confidence = max(50, confidence - 5)
|
|
||||||
rationale += " (Adjusted lower for AMEX market's higher risk on oversold assets)."
|
|
||||||
|
|
||||||
if price_change_pct < -10.0:
|
|
||||||
confidence = max(45, confidence - 10)
|
|
||||||
rationale += " (Caution: Very steep decline, potential falling knife)."
|
|
||||||
|
|
||||||
return {"action": action, "confidence": confidence, "rationale": rationale}
|
|
||||||
|
|
||||||
# If no specific BUY signal, default to HOLD
|
|
||||||
return {"action": action, "confidence": confidence, "rationale": rationale}
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
"""Auto-generated strategy: v20260220_210244
|
|
||||||
|
|
||||||
Generated at: 2026-02-20T21:02:44.387355+00:00
|
|
||||||
Rationale: Auto-evolved from 6 failures. Primary failure markets: ['US_AMEX', 'US_NYSE', 'US_NASDAQ']. Average loss: -194.69
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
from typing import Any
|
|
||||||
from src.strategies.base import BaseStrategy
|
|
||||||
|
|
||||||
|
|
||||||
class Strategy_v20260220_210244(BaseStrategy):
|
|
||||||
"""Strategy: v20260220_210244"""
|
|
||||||
|
|
||||||
def evaluate(self, market_data: dict[str, Any]) -> dict[str, Any]:
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
# Extract required data points safely
|
|
||||||
current_price = market_data.get("current_price")
|
|
||||||
price_change_pct = market_data.get("price_change_pct")
|
|
||||||
volume_ratio = market_data.get("volume_ratio")
|
|
||||||
rsi = market_data.get("rsi")
|
|
||||||
timestamp_str = market_data.get("timestamp")
|
|
||||||
market_name = market_data.get("market")
|
|
||||||
stock_code = market_data.get("stock_code", "UNKNOWN")
|
|
||||||
|
|
||||||
# Default action is HOLD with conservative confidence and rationale
|
|
||||||
action = "HOLD"
|
|
||||||
confidence = 50
|
|
||||||
rationale = f"No strong BUY signal for {stock_code} or awaiting more favorable conditions after avoiding known failure patterns."
|
|
||||||
|
|
||||||
# --- 1. Failure Pattern Avoidance Filters ---
|
|
||||||
|
|
||||||
# A. Avoid low-priced (penny) stocks
|
|
||||||
if current_price is not None and current_price < 5.0:
|
|
||||||
return {
|
|
||||||
"action": "HOLD",
|
|
||||||
"confidence": 50,
|
|
||||||
"rationale": f"AVOID {stock_code}: Stock price (${current_price:.2f}) is below minimum threshold ($5.00) for BUY action. Identified past failures on highly volatile, low-priced stocks."
|
|
||||||
}
|
|
||||||
|
|
||||||
# B. Avoid initiating BUY trades during identified high-volatility hours
|
|
||||||
if timestamp_str:
|
|
||||||
try:
|
|
||||||
trade_hour = datetime.fromisoformat(timestamp_str).hour
|
|
||||||
if trade_hour in [14, 20]:
|
|
||||||
return {
|
|
||||||
"action": "HOLD",
|
|
||||||
"confidence": 50,
|
|
||||||
"rationale": f"AVOID {stock_code}: Trading during historically volatile hour ({trade_hour} UTC) where previous BUYs resulted in losses. Prefer to observe market stability."
|
|
||||||
}
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# C. Be cautious with extreme momentum spikes
|
|
||||||
if volume_ratio is not None and price_change_pct is not None:
|
|
||||||
if volume_ratio >= 9.0 and price_change_pct >= 15.0:
|
|
||||||
return {
|
|
||||||
"action": "HOLD",
|
|
||||||
"confidence": 50,
|
|
||||||
"rationale": f"AVOID {stock_code}: Extreme short-term momentum detected (price change: +{price_change_pct:.2f}%, volume ratio: {volume_ratio:.1f}x). Historical failures indicate buying into such rapid spikes often leads to reversals."
|
|
||||||
}
|
|
||||||
|
|
||||||
# D. Be cautious with "oversold" signals without further confirmation
|
|
||||||
if rsi is not None and rsi < 30:
|
|
||||||
return {
|
|
||||||
"action": "HOLD",
|
|
||||||
"confidence": 50,
|
|
||||||
"rationale": f"AVOID {stock_code}: Oversold signal (RSI={rsi:.1f}) detected. While often a BUY signal, historical failures on similar 'oversold' trades suggest waiting for stronger confirmation."
|
|
||||||
}
|
|
||||||
|
|
||||||
# --- 2. Improved BUY Signal Generation ---
|
|
||||||
if volume_ratio is not None and 2.0 <= volume_ratio < 9.0 and \
|
|
||||||
price_change_pct is not None and 2.0 <= price_change_pct < 15.0:
|
|
||||||
|
|
||||||
action = "BUY"
|
|
||||||
confidence = 70
|
|
||||||
rationale = f"BUY {stock_code}: Moderate momentum detected (price change: +{price_change_pct:.2f}%, volume ratio: {volume_ratio:.1f}x). Passed filters for price and extreme momentum, avoiding past failure patterns."
|
|
||||||
|
|
||||||
if market_name in ["US_AMEX", "US_NASDAQ"]:
|
|
||||||
confidence = max(60, confidence - 5)
|
|
||||||
rationale += f" Adjusted confidence for {market_name} market characteristics."
|
|
||||||
elif market_name == "US_NYSE":
|
|
||||||
confidence = max(65, confidence)
|
|
||||||
|
|
||||||
confidence = max(50, min(85, confidence))
|
|
||||||
|
|
||||||
return {"action": action, "confidence": confidence, "rationale": rationale}
|
|
||||||
@@ -93,9 +93,21 @@ class TestMalformedJsonHandling:
|
|||||||
|
|
||||||
def test_json_with_missing_fields_returns_hold(self, settings):
|
def test_json_with_missing_fields_returns_hold(self, settings):
|
||||||
client = GeminiClient(settings)
|
client = GeminiClient(settings)
|
||||||
decision = client.parse_response('{"action": "BUY"}')
|
raw = '{"action": "BUY"}'
|
||||||
|
decision = client.parse_response(raw)
|
||||||
assert decision.action == "HOLD"
|
assert decision.action == "HOLD"
|
||||||
assert decision.confidence == 0
|
assert decision.confidence == 0
|
||||||
|
# rationale preserves raw so prompt_override callers (e.g. pre_market_planner)
|
||||||
|
# can extract non-TradeDecision JSON from decision.rationale (#245)
|
||||||
|
assert decision.rationale == raw
|
||||||
|
|
||||||
|
def test_non_trade_decision_json_preserves_raw_in_rationale(self, settings):
|
||||||
|
"""Playbook JSON (no action/confidence/rationale) must be preserved for planner."""
|
||||||
|
client = GeminiClient(settings)
|
||||||
|
playbook_json = '{"market_outlook": "neutral", "stocks": []}'
|
||||||
|
decision = client.parse_response(playbook_json)
|
||||||
|
assert decision.action == "HOLD"
|
||||||
|
assert decision.rationale == playbook_json
|
||||||
|
|
||||||
def test_json_with_invalid_action_returns_hold(self, settings):
|
def test_json_with_invalid_action_returns_hold(self, settings):
|
||||||
client = GeminiClient(settings)
|
client = GeminiClient(settings)
|
||||||
@@ -290,9 +302,10 @@ class TestPromptOverride:
|
|||||||
client = GeminiClient(settings)
|
client = GeminiClient(settings)
|
||||||
|
|
||||||
custom_prompt = "You are a playbook generator. Return JSON with scenarios."
|
custom_prompt = "You are a playbook generator. Return JSON with scenarios."
|
||||||
|
playbook_json = '{"market_outlook": "neutral", "stocks": []}'
|
||||||
|
|
||||||
mock_response = MagicMock()
|
mock_response = MagicMock()
|
||||||
mock_response.text = '{"action": "HOLD", "confidence": 50, "rationale": "test"}'
|
mock_response.text = playbook_json
|
||||||
|
|
||||||
with patch.object(
|
with patch.object(
|
||||||
client._client.aio.models,
|
client._client.aio.models,
|
||||||
@@ -305,7 +318,7 @@ class TestPromptOverride:
|
|||||||
"current_price": 0,
|
"current_price": 0,
|
||||||
"prompt_override": custom_prompt,
|
"prompt_override": custom_prompt,
|
||||||
}
|
}
|
||||||
await client.decide(market_data)
|
decision = await client.decide(market_data)
|
||||||
|
|
||||||
# Verify the custom prompt was sent, not a built prompt
|
# Verify the custom prompt was sent, not a built prompt
|
||||||
mock_generate.assert_called_once()
|
mock_generate.assert_called_once()
|
||||||
@@ -313,17 +326,50 @@ class TestPromptOverride:
|
|||||||
"contents", mock_generate.call_args[0][1] if len(mock_generate.call_args[0]) > 1 else None
|
"contents", mock_generate.call_args[0][1] if len(mock_generate.call_args[0]) > 1 else None
|
||||||
)
|
)
|
||||||
assert actual_prompt == custom_prompt
|
assert actual_prompt == custom_prompt
|
||||||
|
# Raw response preserved in rationale without parse_response (#247)
|
||||||
|
assert decision.rationale == playbook_json
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_prompt_override_skips_optimization(self, settings):
|
async def test_prompt_override_skips_parse_response(self, settings):
|
||||||
"""prompt_override should bypass prompt optimization."""
|
"""prompt_override bypasses parse_response — no Missing fields warning, raw preserved."""
|
||||||
client = GeminiClient(settings)
|
client = GeminiClient(settings)
|
||||||
client._enable_optimization = True
|
client._enable_optimization = True
|
||||||
|
|
||||||
custom_prompt = "Custom playbook prompt"
|
custom_prompt = "Custom playbook prompt"
|
||||||
|
playbook_json = '{"market_outlook": "bullish", "stocks": [{"stock_code": "AAPL"}]}'
|
||||||
|
|
||||||
mock_response = MagicMock()
|
mock_response = MagicMock()
|
||||||
mock_response.text = '{"action": "HOLD", "confidence": 50, "rationale": "ok"}'
|
mock_response.text = playbook_json
|
||||||
|
|
||||||
|
with patch.object(
|
||||||
|
client._client.aio.models,
|
||||||
|
"generate_content",
|
||||||
|
new_callable=AsyncMock,
|
||||||
|
return_value=mock_response,
|
||||||
|
):
|
||||||
|
with patch.object(client, "parse_response") as mock_parse:
|
||||||
|
market_data = {
|
||||||
|
"stock_code": "PLANNER",
|
||||||
|
"current_price": 0,
|
||||||
|
"prompt_override": custom_prompt,
|
||||||
|
}
|
||||||
|
decision = await client.decide(market_data)
|
||||||
|
|
||||||
|
# parse_response must NOT be called for prompt_override
|
||||||
|
mock_parse.assert_not_called()
|
||||||
|
# Raw playbook JSON preserved in rationale
|
||||||
|
assert decision.rationale == playbook_json
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_prompt_override_takes_priority_over_optimization(self, settings):
|
||||||
|
"""prompt_override must win over enable_optimization=True."""
|
||||||
|
client = GeminiClient(settings)
|
||||||
|
client._enable_optimization = True
|
||||||
|
|
||||||
|
custom_prompt = "Explicit playbook prompt"
|
||||||
|
|
||||||
|
mock_response = MagicMock()
|
||||||
|
mock_response.text = '{"market_outlook": "neutral", "stocks": []}'
|
||||||
|
|
||||||
with patch.object(
|
with patch.object(
|
||||||
client._client.aio.models,
|
client._client.aio.models,
|
||||||
@@ -341,6 +387,7 @@ class TestPromptOverride:
|
|||||||
actual_prompt = mock_generate.call_args[1].get(
|
actual_prompt = mock_generate.call_args[1].get(
|
||||||
"contents", mock_generate.call_args[0][1] if len(mock_generate.call_args[0]) > 1 else None
|
"contents", mock_generate.call_args[0][1] if len(mock_generate.call_args[0]) > 1 else None
|
||||||
)
|
)
|
||||||
|
# The custom prompt must be used, not the compressed prompt
|
||||||
assert actual_prompt == custom_prompt
|
assert actual_prompt == custom_prompt
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -354,6 +354,8 @@ class TestFetchMarketRankings:
|
|||||||
assert "ranking/fluctuation" in url
|
assert "ranking/fluctuation" in url
|
||||||
assert headers.get("tr_id") == "FHPST01700000"
|
assert headers.get("tr_id") == "FHPST01700000"
|
||||||
assert params.get("fid_cond_scr_div_code") == "20170"
|
assert params.get("fid_cond_scr_div_code") == "20170"
|
||||||
|
# 실전 API는 4자리("0000") 거부 — 1자리("0")여야 한다 (#240)
|
||||||
|
assert params.get("fid_rank_sort_cls_code") == "0"
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_volume_returns_parsed_rows(self, broker: KISBroker) -> None:
|
async def test_volume_returns_parsed_rows(self, broker: KISBroker) -> None:
|
||||||
@@ -376,6 +378,27 @@ class TestFetchMarketRankings:
|
|||||||
assert result[0]["price"] == 75000.0
|
assert result[0]["price"] == 75000.0
|
||||||
assert result[0]["change_rate"] == 2.5
|
assert result[0]["change_rate"] == 2.5
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_fluctuation_parses_stck_shrn_iscd(self, broker: KISBroker) -> None:
|
||||||
|
"""실전 API는 mksc_shrn_iscd 대신 stck_shrn_iscd를 반환한다 (#240)."""
|
||||||
|
items = [
|
||||||
|
{
|
||||||
|
"stck_shrn_iscd": "015260",
|
||||||
|
"hts_kor_isnm": "에이엔피",
|
||||||
|
"stck_prpr": "794",
|
||||||
|
"acml_vol": "4896196",
|
||||||
|
"prdy_ctrt": "29.74",
|
||||||
|
"vol_inrt": "0",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
mock_resp = _make_ranking_mock(items)
|
||||||
|
with patch("aiohttp.ClientSession.get", return_value=mock_resp):
|
||||||
|
result = await broker.fetch_market_rankings(ranking_type="fluctuation")
|
||||||
|
|
||||||
|
assert len(result) == 1
|
||||||
|
assert result[0]["stock_code"] == "015260"
|
||||||
|
assert result[0]["change_rate"] == 29.74
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# KRX tick unit / round-down helpers (issue #157)
|
# KRX tick unit / round-down helpers (issue #157)
|
||||||
@@ -725,3 +748,195 @@ class TestTRIDBranchingDomestic:
|
|||||||
|
|
||||||
order_headers = mock_post.call_args_list[1][1].get("headers", {})
|
order_headers = mock_post.call_args_list[1][1].get("headers", {})
|
||||||
assert order_headers["tr_id"] == "TTTC0011U"
|
assert order_headers["tr_id"] == "TTTC0011U"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Domestic Pending Orders (get_domestic_pending_orders)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class TestGetDomesticPendingOrders:
|
||||||
|
"""get_domestic_pending_orders must return [] in paper mode and call TTTC0084R in live."""
|
||||||
|
|
||||||
|
def _make_broker(self, settings, mode: str) -> KISBroker:
|
||||||
|
from src.config import Settings
|
||||||
|
|
||||||
|
s = Settings(
|
||||||
|
KIS_APP_KEY=settings.KIS_APP_KEY,
|
||||||
|
KIS_APP_SECRET=settings.KIS_APP_SECRET,
|
||||||
|
KIS_ACCOUNT_NO=settings.KIS_ACCOUNT_NO,
|
||||||
|
GEMINI_API_KEY=settings.GEMINI_API_KEY,
|
||||||
|
DB_PATH=":memory:",
|
||||||
|
ENABLED_MARKETS="KR",
|
||||||
|
MODE=mode,
|
||||||
|
)
|
||||||
|
b = KISBroker(s)
|
||||||
|
b._access_token = "tok"
|
||||||
|
b._token_expires_at = float("inf")
|
||||||
|
b._rate_limiter.acquire = AsyncMock()
|
||||||
|
return b
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_paper_mode_returns_empty(self, settings) -> None:
|
||||||
|
"""Paper mode must return [] immediately without any API call."""
|
||||||
|
broker = self._make_broker(settings, "paper")
|
||||||
|
|
||||||
|
with patch("aiohttp.ClientSession.get") as mock_get:
|
||||||
|
result = await broker.get_domestic_pending_orders()
|
||||||
|
|
||||||
|
assert result == []
|
||||||
|
mock_get.assert_not_called()
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_live_mode_calls_tttc0084r_with_correct_params(
|
||||||
|
self, settings
|
||||||
|
) -> None:
|
||||||
|
"""Live mode must call TTTC0084R with INQR_DVSN_1/2 and paging params."""
|
||||||
|
broker = self._make_broker(settings, "live")
|
||||||
|
pending = [{"odno": "001", "pdno": "005930", "psbl_qty": "10"}]
|
||||||
|
mock_resp = AsyncMock()
|
||||||
|
mock_resp.status = 200
|
||||||
|
mock_resp.json = AsyncMock(return_value={"output": pending})
|
||||||
|
mock_resp.__aenter__ = AsyncMock(return_value=mock_resp)
|
||||||
|
mock_resp.__aexit__ = AsyncMock(return_value=False)
|
||||||
|
|
||||||
|
with patch("aiohttp.ClientSession.get", return_value=mock_resp) as mock_get:
|
||||||
|
result = await broker.get_domestic_pending_orders()
|
||||||
|
|
||||||
|
assert result == pending
|
||||||
|
headers = mock_get.call_args[1].get("headers", {})
|
||||||
|
assert headers["tr_id"] == "TTTC0084R"
|
||||||
|
params = mock_get.call_args[1].get("params", {})
|
||||||
|
assert params["INQR_DVSN_1"] == "0"
|
||||||
|
assert params["INQR_DVSN_2"] == "0"
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_live_mode_connection_error(self, settings) -> None:
|
||||||
|
"""Network error must raise ConnectionError."""
|
||||||
|
import aiohttp as _aiohttp
|
||||||
|
|
||||||
|
broker = self._make_broker(settings, "live")
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"aiohttp.ClientSession.get",
|
||||||
|
side_effect=_aiohttp.ClientError("timeout"),
|
||||||
|
):
|
||||||
|
with pytest.raises(ConnectionError):
|
||||||
|
await broker.get_domestic_pending_orders()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Domestic Order Cancellation (cancel_domestic_order)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class TestCancelDomesticOrder:
|
||||||
|
"""cancel_domestic_order must use correct TR_ID and build body correctly."""
|
||||||
|
|
||||||
|
def _make_broker(self, settings, mode: str) -> KISBroker:
|
||||||
|
from src.config import Settings
|
||||||
|
|
||||||
|
s = Settings(
|
||||||
|
KIS_APP_KEY=settings.KIS_APP_KEY,
|
||||||
|
KIS_APP_SECRET=settings.KIS_APP_SECRET,
|
||||||
|
KIS_ACCOUNT_NO=settings.KIS_ACCOUNT_NO,
|
||||||
|
GEMINI_API_KEY=settings.GEMINI_API_KEY,
|
||||||
|
DB_PATH=":memory:",
|
||||||
|
ENABLED_MARKETS="KR",
|
||||||
|
MODE=mode,
|
||||||
|
)
|
||||||
|
b = KISBroker(s)
|
||||||
|
b._access_token = "tok"
|
||||||
|
b._token_expires_at = float("inf")
|
||||||
|
b._rate_limiter.acquire = AsyncMock()
|
||||||
|
return b
|
||||||
|
|
||||||
|
def _make_post_mocks(self, order_payload: dict) -> tuple:
|
||||||
|
mock_hash = AsyncMock()
|
||||||
|
mock_hash.status = 200
|
||||||
|
mock_hash.json = AsyncMock(return_value={"HASH": "h"})
|
||||||
|
mock_hash.__aenter__ = AsyncMock(return_value=mock_hash)
|
||||||
|
mock_hash.__aexit__ = AsyncMock(return_value=False)
|
||||||
|
|
||||||
|
mock_order = AsyncMock()
|
||||||
|
mock_order.status = 200
|
||||||
|
mock_order.json = AsyncMock(return_value=order_payload)
|
||||||
|
mock_order.__aenter__ = AsyncMock(return_value=mock_order)
|
||||||
|
mock_order.__aexit__ = AsyncMock(return_value=False)
|
||||||
|
|
||||||
|
return mock_hash, mock_order
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_live_uses_tttc0013u(self, settings) -> None:
|
||||||
|
"""Live mode must use TR_ID TTTC0013U."""
|
||||||
|
broker = self._make_broker(settings, "live")
|
||||||
|
mock_hash, mock_order = self._make_post_mocks({"rt_cd": "0"})
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"aiohttp.ClientSession.post", side_effect=[mock_hash, mock_order]
|
||||||
|
) as mock_post:
|
||||||
|
await broker.cancel_domestic_order("005930", "ORD001", "BRNO01", 5)
|
||||||
|
|
||||||
|
order_headers = mock_post.call_args_list[1][1].get("headers", {})
|
||||||
|
assert order_headers["tr_id"] == "TTTC0013U"
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_paper_uses_vttc0013u(self, settings) -> None:
|
||||||
|
"""Paper mode must use TR_ID VTTC0013U."""
|
||||||
|
broker = self._make_broker(settings, "paper")
|
||||||
|
mock_hash, mock_order = self._make_post_mocks({"rt_cd": "0"})
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"aiohttp.ClientSession.post", side_effect=[mock_hash, mock_order]
|
||||||
|
) as mock_post:
|
||||||
|
await broker.cancel_domestic_order("005930", "ORD001", "BRNO01", 5)
|
||||||
|
|
||||||
|
order_headers = mock_post.call_args_list[1][1].get("headers", {})
|
||||||
|
assert order_headers["tr_id"] == "VTTC0013U"
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_cancel_sets_rvse_cncl_dvsn_cd_02(self, settings) -> None:
|
||||||
|
"""Body must have RVSE_CNCL_DVSN_CD='02' (취소) and QTY_ALL_ORD_YN='Y'."""
|
||||||
|
broker = self._make_broker(settings, "live")
|
||||||
|
mock_hash, mock_order = self._make_post_mocks({"rt_cd": "0"})
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"aiohttp.ClientSession.post", side_effect=[mock_hash, mock_order]
|
||||||
|
) as mock_post:
|
||||||
|
await broker.cancel_domestic_order("005930", "ORD001", "BRNO01", 5)
|
||||||
|
|
||||||
|
body = mock_post.call_args_list[1][1].get("json", {})
|
||||||
|
assert body["RVSE_CNCL_DVSN_CD"] == "02"
|
||||||
|
assert body["QTY_ALL_ORD_YN"] == "Y"
|
||||||
|
assert body["ORD_UNPR"] == "0"
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_cancel_sets_krx_fwdg_ord_orgno_in_body(self, settings) -> None:
|
||||||
|
"""Body must include KRX_FWDG_ORD_ORGNO and ORGN_ODNO from arguments."""
|
||||||
|
broker = self._make_broker(settings, "live")
|
||||||
|
mock_hash, mock_order = self._make_post_mocks({"rt_cd": "0"})
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"aiohttp.ClientSession.post", side_effect=[mock_hash, mock_order]
|
||||||
|
) as mock_post:
|
||||||
|
await broker.cancel_domestic_order("005930", "ORD123", "BRN456", 3)
|
||||||
|
|
||||||
|
body = mock_post.call_args_list[1][1].get("json", {})
|
||||||
|
assert body["KRX_FWDG_ORD_ORGNO"] == "BRN456"
|
||||||
|
assert body["ORGN_ODNO"] == "ORD123"
|
||||||
|
assert body["ORD_QTY"] == "3"
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_cancel_sets_hashkey_header(self, settings) -> None:
|
||||||
|
"""Request must include hashkey header (same pattern as send_order)."""
|
||||||
|
broker = self._make_broker(settings, "live")
|
||||||
|
mock_hash, mock_order = self._make_post_mocks({"rt_cd": "0"})
|
||||||
|
|
||||||
|
with patch(
|
||||||
|
"aiohttp.ClientSession.post", side_effect=[mock_hash, mock_order]
|
||||||
|
) as mock_post:
|
||||||
|
await broker.cancel_domestic_order("005930", "ORD001", "BRNO01", 2)
|
||||||
|
|
||||||
|
order_headers = mock_post.call_args_list[1][1].get("headers", {})
|
||||||
|
assert "hashkey" in order_headers
|
||||||
|
assert order_headers["hashkey"] == "h"
|
||||||
|
|||||||
@@ -413,3 +413,39 @@ def test_status_circuit_breaker_unknown_when_no_data(tmp_path: Path) -> None:
|
|||||||
cb = body["circuit_breaker"]
|
cb = body["circuit_breaker"]
|
||||||
assert cb["status"] == "unknown"
|
assert cb["status"] == "unknown"
|
||||||
assert cb["current_pnl_pct"] is None
|
assert cb["current_pnl_pct"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_status_mode_paper(tmp_path: Path) -> None:
|
||||||
|
"""mode=paper로 생성하면 status 응답에 mode=paper가 포함돼야 한다."""
|
||||||
|
db_path = tmp_path / "dashboard_test.db"
|
||||||
|
conn = init_db(str(db_path))
|
||||||
|
_seed_db(conn)
|
||||||
|
conn.close()
|
||||||
|
app = create_dashboard_app(str(db_path), mode="paper")
|
||||||
|
get_status = _endpoint(app, "/api/status")
|
||||||
|
body = get_status()
|
||||||
|
assert body["mode"] == "paper"
|
||||||
|
|
||||||
|
|
||||||
|
def test_status_mode_live(tmp_path: Path) -> None:
|
||||||
|
"""mode=live로 생성하면 status 응답에 mode=live가 포함돼야 한다."""
|
||||||
|
db_path = tmp_path / "dashboard_test.db"
|
||||||
|
conn = init_db(str(db_path))
|
||||||
|
_seed_db(conn)
|
||||||
|
conn.close()
|
||||||
|
app = create_dashboard_app(str(db_path), mode="live")
|
||||||
|
get_status = _endpoint(app, "/api/status")
|
||||||
|
body = get_status()
|
||||||
|
assert body["mode"] == "live"
|
||||||
|
|
||||||
|
|
||||||
|
def test_status_mode_default_paper(tmp_path: Path) -> None:
|
||||||
|
"""mode 파라미터 미전달 시 기본값은 paper여야 한다."""
|
||||||
|
db_path = tmp_path / "dashboard_test.db"
|
||||||
|
conn = init_db(str(db_path))
|
||||||
|
_seed_db(conn)
|
||||||
|
conn.close()
|
||||||
|
app = create_dashboard_app(str(db_path))
|
||||||
|
get_status = _endpoint(app, "/api/status")
|
||||||
|
body = get_status()
|
||||||
|
assert body["mode"] == "paper"
|
||||||
|
|||||||
1027
tests/test_main.py
1027
tests/test_main.py
File diff suppressed because it is too large
Load Diff
@@ -28,6 +28,7 @@ def mock_settings() -> Settings:
|
|||||||
KIS_APP_SECRET="test_secret",
|
KIS_APP_SECRET="test_secret",
|
||||||
KIS_ACCOUNT_NO="12345678-01",
|
KIS_ACCOUNT_NO="12345678-01",
|
||||||
GEMINI_API_KEY="test_gemini_key",
|
GEMINI_API_KEY="test_gemini_key",
|
||||||
|
MODE="paper", # Explicitly set to avoid .env MODE=live override
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -122,9 +123,10 @@ class TestFetchOverseasRankings:
|
|||||||
params = call_args[1]["params"]
|
params = call_args[1]["params"]
|
||||||
|
|
||||||
assert "/uapi/overseas-stock/v1/ranking/updown-rate" in url
|
assert "/uapi/overseas-stock/v1/ranking/updown-rate" in url
|
||||||
|
assert params["KEYB"] == "" # Required by KIS API spec
|
||||||
assert params["EXCD"] == "NAS"
|
assert params["EXCD"] == "NAS"
|
||||||
assert params["NDAY"] == "0"
|
assert params["NDAY"] == "0"
|
||||||
assert params["GUBN"] == "1"
|
assert params["GUBN"] == "1" # 1=상승율 — 변동성 스캐너는 급등 종목 우선
|
||||||
assert params["VOL_RANG"] == "0"
|
assert params["VOL_RANG"] == "0"
|
||||||
|
|
||||||
overseas_broker._broker._auth_headers.assert_called_with("HHDFS76290000")
|
overseas_broker._broker._auth_headers.assert_called_with("HHDFS76290000")
|
||||||
@@ -157,6 +159,7 @@ class TestFetchOverseasRankings:
|
|||||||
params = call_args[1]["params"]
|
params = call_args[1]["params"]
|
||||||
|
|
||||||
assert "/uapi/overseas-stock/v1/ranking/volume-surge" in url
|
assert "/uapi/overseas-stock/v1/ranking/volume-surge" in url
|
||||||
|
assert params["KEYB"] == "" # Required by KIS API spec
|
||||||
assert params["EXCD"] == "NYS"
|
assert params["EXCD"] == "NYS"
|
||||||
assert params["MIXN"] == "0"
|
assert params["MIXN"] == "0"
|
||||||
assert params["VOL_RANG"] == "0"
|
assert params["VOL_RANG"] == "0"
|
||||||
|
|||||||
@@ -124,6 +124,10 @@ class TestPromptOptimizer:
|
|||||||
assert len(prompt) < 300
|
assert len(prompt) < 300
|
||||||
assert "005930" in prompt
|
assert "005930" in prompt
|
||||||
assert "75000" in prompt
|
assert "75000" in prompt
|
||||||
|
# Keys must match parse_response expectations (#242)
|
||||||
|
assert '"action"' in prompt
|
||||||
|
assert '"confidence"' in prompt
|
||||||
|
assert '"rationale"' in prompt
|
||||||
|
|
||||||
def test_build_compressed_prompt_no_instructions(self):
|
def test_build_compressed_prompt_no_instructions(self):
|
||||||
"""Test compressed prompt without instructions."""
|
"""Test compressed prompt without instructions."""
|
||||||
|
|||||||
37
workflow/issue-271-runlog.md
Normal file
37
workflow/issue-271-runlog.md
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
# Issue #271 Workflow Run Log
|
||||||
|
|
||||||
|
## 2026-02-26
|
||||||
|
|
||||||
|
### Step 1: Gitea issue creation
|
||||||
|
- Attempt 1: Succeeded, but formatting degraded
|
||||||
|
- Command style: `tea issues create -t ... -d "...\n..."`
|
||||||
|
- Symptom: Issue body rendered literal `\n` text in web UI instead of line breaks
|
||||||
|
- Root cause
|
||||||
|
- `tea` does not provide `--description-file`
|
||||||
|
- Shell-escaped `\n` inside double quotes is passed as backslash+n text
|
||||||
|
- Resolution
|
||||||
|
- Build body with heredoc and pass as variable (`-d "$ISSUE_BODY"`)
|
||||||
|
|
||||||
|
### Step 2: PR description creation
|
||||||
|
- Attempt 1: Succeeded, but same newline rendering risk detected
|
||||||
|
- Resolution
|
||||||
|
- Same heredoc variable pattern applied for PR body (`--description "$PR_BODY"`)
|
||||||
|
|
||||||
|
### Preventive Action
|
||||||
|
- `docs/workflow.md` updated with "Gitea CLI Formatting Troubleshooting" section
|
||||||
|
- Standard command templates added for issues and PRs
|
||||||
|
|
||||||
|
### Reusable Safe Template
|
||||||
|
```bash
|
||||||
|
ISSUE_BODY=$(cat <<'EOF'
|
||||||
|
## Summary
|
||||||
|
- item A
|
||||||
|
- item B
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
- docs only
|
||||||
|
EOF
|
||||||
|
)
|
||||||
|
|
||||||
|
tea issues create -t "title" -d "$ISSUE_BODY"
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user