Compare commits
51 Commits
feature/is
...
6a6d3bd631
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 | |||
|
|
6b74e4cc77 | ||
| 1a1fe7e637 | |||
|
|
2e27000760 | ||
| 5a41f86112 | |||
|
|
ff9c4d6082 | ||
| 25ad4776c9 | |||
|
|
9339824e22 | ||
| e6eae6c6e0 | |||
| bb6bd0392e | |||
| a66181b7a7 | |||
| da585ee547 | |||
| c737d5009a | |||
|
|
f7d33e69d1 | ||
|
|
7d99d8ec4a | ||
|
|
0727f28f77 | ||
|
|
ac4fb00644 |
@@ -94,6 +94,7 @@ Smart Scanner runs in `TRADE_MODE=realtime` only. Daily mode uses static watchli
|
||||
- **[Testing](docs/testing.md)** — Test structure, coverage requirements, writing tests
|
||||
- **[Agent Policies](docs/agents.md)** — Prime directives, constraints, prohibited actions
|
||||
- **[Requirements Log](docs/requirements-log.md)** — User requirements and feedback tracking
|
||||
- **[Live Trading Checklist](docs/live-trading-checklist.md)** — 모의→실전 전환 체크리스트
|
||||
|
||||
## Core Principles
|
||||
|
||||
|
||||
131
docs/live-trading-checklist.md
Normal file
131
docs/live-trading-checklist.md
Normal file
@@ -0,0 +1,131 @@
|
||||
# 실전 전환 체크리스트
|
||||
|
||||
모의 거래(paper)에서 실전(live)으로 전환하기 전에 아래 항목을 **순서대로** 모두 확인하세요.
|
||||
|
||||
---
|
||||
|
||||
## 1. 사전 조건
|
||||
|
||||
### 1-1. KIS OpenAPI 실전 계좌 준비
|
||||
- [ ] 한국투자증권 계좌 개설 완료 (일반 위탁 계좌)
|
||||
- [ ] OpenAPI 실전 사용 신청 (KIS 홈페이지 → Open API → 서비스 신청)
|
||||
- [ ] 실전용 APP_KEY / APP_SECRET 발급 완료
|
||||
- [ ] KIS_ACCOUNT_NO 형식 확인: `XXXXXXXX-XX` (8자리-2자리)
|
||||
|
||||
### 1-2. 리스크 파라미터 검토
|
||||
- [ ] `CIRCUIT_BREAKER_PCT` 확인: 기본값 -3.0% (더 엄격하게 조정 권장)
|
||||
- [ ] `FAT_FINGER_PCT` 확인: 기본값 30.0% (1회 주문 최대 잔고 대비 %)
|
||||
- [ ] `CONFIDENCE_THRESHOLD` 확인: BEARISH ≥ 90, NEUTRAL ≥ 80, BULLISH ≥ 75
|
||||
- [ ] 초기 투자금 결정 및 해외 주식 운용 한도 설정
|
||||
|
||||
### 1-3. 시스템 요건
|
||||
- [ ] 커버리지 80% 이상 유지 확인: `pytest --cov=src`
|
||||
- [ ] 타입 체크 통과: `mypy src/ --strict`
|
||||
- [ ] Lint 통과: `ruff check src/ tests/`
|
||||
|
||||
---
|
||||
|
||||
## 2. 환경 설정
|
||||
|
||||
### 2-1. `.env` 파일 수정
|
||||
|
||||
```bash
|
||||
# 1. KIS 실전 URL로 변경 (모의: openapivts 포트 29443)
|
||||
KIS_BASE_URL=https://openapi.koreainvestment.com:9443
|
||||
|
||||
# 2. 실전 APP_KEY / APP_SECRET으로 교체
|
||||
KIS_APP_KEY=<실전_APP_KEY>
|
||||
KIS_APP_SECRET=<실전_APP_SECRET>
|
||||
KIS_ACCOUNT_NO=<실전_계좌번호>
|
||||
|
||||
# 3. 모드를 live로 변경
|
||||
MODE=live
|
||||
|
||||
# 4. PAPER_OVERSEAS_CASH 비활성화 (live 모드에선 무시되지만 명시적으로 0 설정)
|
||||
PAPER_OVERSEAS_CASH=0
|
||||
```
|
||||
|
||||
> ⚠️ `KIS_BASE_URL` 포트 주의:
|
||||
> - **모의(VTS)**: `https://openapivts.koreainvestment.com:29443`
|
||||
> - **실전**: `https://openapi.koreainvestment.com:9443`
|
||||
|
||||
### 2-2. TR_ID 자동 분기 확인
|
||||
|
||||
아래 TR_ID는 `MODE` 값에 따라 코드에서 **자동으로 선택**됩니다.
|
||||
별도 설정 불필요하나, 문제 발생 시 아래 표를 참조하세요.
|
||||
|
||||
| 구분 | 모의 TR_ID | 실전 TR_ID |
|
||||
|------|-----------|-----------|
|
||||
| 국내 잔고 조회 | `VTTC8434R` | `TTTC8434R` |
|
||||
| 국내 현금 매수 | `VTTC0012U` | `TTTC0012U` |
|
||||
| 국내 현금 매도 | `VTTC0011U` | `TTTC0011U` |
|
||||
| 해외 잔고 조회 | `VTTS3012R` | `TTTS3012R` |
|
||||
| 해외 매수 | `VTTT1002U` | `TTTT1002U` |
|
||||
| 해외 매도 | `VTTT1001U` | `TTTT1006U` |
|
||||
|
||||
> **출처**: `docs/한국투자증권_오픈API_전체문서_20260221_030000.xlsx` (공식 문서 기준)
|
||||
|
||||
---
|
||||
|
||||
## 3. 최종 확인
|
||||
|
||||
### 3-1. 실전 시작 전 점검
|
||||
- [ ] DB 백업 완료: `data/trade_logs.db` → `data/backups/`
|
||||
- [ ] Telegram 알림 설정 확인 (실전에서는 알림이 더욱 중요)
|
||||
- [ ] 소액으로 첫 거래 진행 후 TR_ID/계좌 정상 동작 확인
|
||||
|
||||
### 3-2. 실행 명령
|
||||
|
||||
```bash
|
||||
# 실전 모드로 실행
|
||||
python -m src.main --mode=live
|
||||
|
||||
# 대시보드 함께 실행 (별도 터미널에서 모니터링)
|
||||
python -m src.main --mode=live --dashboard
|
||||
```
|
||||
|
||||
### 3-3. 실전 시작 직후 확인 사항
|
||||
- [ ] 로그에 `MODE=live` 출력 확인
|
||||
- [ ] 첫 잔고 조회 성공 (ConnectionError 없음)
|
||||
- [ ] Telegram 알림 수신 확인 ("System started")
|
||||
- [ ] 첫 주문 후 KIS 앱에서 체결 내역 확인
|
||||
|
||||
---
|
||||
|
||||
## 4. 비상 정지 방법
|
||||
|
||||
### 즉각 정지
|
||||
```bash
|
||||
# 터미널에서 Ctrl+C (정상 종료 트리거)
|
||||
# 또는 Telegram 봇 명령:
|
||||
/stop
|
||||
```
|
||||
|
||||
### Circuit Breaker 발동 시
|
||||
- CB가 발동되면 자동으로 거래 중단 및 Telegram 알림 전송
|
||||
- CB 임계값: `CIRCUIT_BREAKER_PCT` (기본 -3.0%)
|
||||
- **임계값은 엄격하게만 조정 가능** (더 낮은 음수 값으로만 변경)
|
||||
|
||||
---
|
||||
|
||||
## 5. 롤백 절차
|
||||
|
||||
실전 전환 후 문제 발생 시:
|
||||
|
||||
```bash
|
||||
# 1. 즉시 .env에서 MODE=paper로 복원
|
||||
# 2. 재시작
|
||||
python -m src.main --mode=paper
|
||||
|
||||
# 3. DB에서 최근 거래 확인
|
||||
sqlite3 data/trade_logs.db "SELECT * FROM trades ORDER BY id DESC LIMIT 20;"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 관련 문서
|
||||
|
||||
- [시스템 아키텍처](architecture.md)
|
||||
- [워크플로우 가이드](workflow.md)
|
||||
- [재해 복구](disaster_recovery.md)
|
||||
- [Agent 제약 조건](agents.md)
|
||||
@@ -292,3 +292,66 @@ Order result: 모의투자 매수주문이 완료 되었습니다. ✓
|
||||
```
|
||||
|
||||
**이슈/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
|
||||
|
||||
@@ -23,7 +23,7 @@ if [ -z "${APP_CMD:-}" ]; then
|
||||
|
||||
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
|
||||
|
||||
mkdir -p "$LOG_DIR"
|
||||
|
||||
@@ -346,8 +346,10 @@ class GeminiClient:
|
||||
# Validate required fields
|
||||
if not all(k in data for k in ("action", "confidence", "rationale")):
|
||||
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(
|
||||
action="HOLD", confidence=0, rationale="Missing required fields"
|
||||
action="HOLD", confidence=0, rationale=raw
|
||||
)
|
||||
|
||||
action = str(data["action"]).upper()
|
||||
@@ -439,6 +441,18 @@ class GeminiClient:
|
||||
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)
|
||||
self._total_decisions += 1
|
||||
|
||||
|
||||
@@ -179,8 +179,8 @@ class PromptOptimizer:
|
||||
# Minimal instructions
|
||||
prompt = (
|
||||
f"{market_name} trader. Analyze:\n{data_str}\n\n"
|
||||
'Return JSON: {"act":"BUY"|"SELL"|"HOLD","conf":<0-100>,"reason":"<text>"}\n'
|
||||
"Rules: act=BUY/SELL/HOLD, conf=0-100, reason=concise. No markdown."
|
||||
'Return JSON: {"action":"BUY"|"SELL"|"HOLD","confidence":<0-100>,"rationale":"<text>"}\n'
|
||||
"Rules: action=BUY/SELL/HOLD, confidence=0-100, rationale=concise. No markdown."
|
||||
)
|
||||
else:
|
||||
# Data only (for cached contexts where instructions are known)
|
||||
|
||||
@@ -8,7 +8,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import logging
|
||||
import ssl
|
||||
from typing import Any
|
||||
from typing import Any, cast
|
||||
|
||||
import aiohttp
|
||||
|
||||
@@ -430,7 +430,7 @@ class KISBroker:
|
||||
"fid_cond_mrkt_div_code": "J",
|
||||
"fid_cond_scr_div_code": "20170",
|
||||
"fid_input_iscd": "0000",
|
||||
"fid_rank_sort_cls_code": "0000",
|
||||
"fid_rank_sort_cls_code": "0",
|
||||
"fid_input_cnt_1": str(limit),
|
||||
"fid_prc_cls_code": "0",
|
||||
"fid_input_price_1": "0",
|
||||
@@ -466,7 +466,7 @@ class KISBroker:
|
||||
rankings = []
|
||||
for item in data.get("output", [])[:limit]:
|
||||
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", ""),
|
||||
"price": _safe_float(item.get("stck_prpr", "0")),
|
||||
"volume": _safe_float(item.get("acml_vol", "0")),
|
||||
@@ -478,6 +478,112 @@ class KISBroker:
|
||||
except (TimeoutError, aiohttp.ClientError) as 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(
|
||||
self,
|
||||
stock_code: str,
|
||||
|
||||
@@ -29,6 +29,20 @@ _RANKING_EXCHANGE_MAP: dict[str, str] = {
|
||||
# NASD → NAS, NYSE → NYS, AMEX → AMS (confirmed: AMEX returns empty, AMS returns price).
|
||||
_PRICE_EXCHANGE_MAP: dict[str, str] = _RANKING_EXCHANGE_MAP
|
||||
|
||||
# Cancel order TR_IDs per exchange code — (live_tr_id, paper_tr_id).
|
||||
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '해외주식 주문취소' 시트
|
||||
_CANCEL_TR_ID_MAP: dict[str, tuple[str, str]] = {
|
||||
"NASD": ("TTTT1004U", "VTTT1004U"),
|
||||
"NYSE": ("TTTT1004U", "VTTT1004U"),
|
||||
"AMEX": ("TTTT1004U", "VTTT1004U"),
|
||||
"SEHK": ("TTTS1003U", "VTTS1003U"),
|
||||
"TSE": ("TTTS0309U", "VTTS0309U"),
|
||||
"SHAA": ("TTTS0302U", "VTTS0302U"),
|
||||
"SZAA": ("TTTS0306U", "VTTS0306U"),
|
||||
"HNX": ("TTTS0312U", "VTTS0312U"),
|
||||
"HSX": ("TTTS0312U", "VTTS0312U"),
|
||||
}
|
||||
|
||||
|
||||
class OverseasBroker:
|
||||
"""KIS Overseas Stock API wrapper that reuses KISBroker infrastructure."""
|
||||
@@ -107,6 +121,7 @@ class OverseasBroker:
|
||||
tr_id = self._broker._settings.OVERSEAS_RANKING_VOLUME_TR_ID
|
||||
path = self._broker._settings.OVERSEAS_RANKING_VOLUME_PATH
|
||||
params: dict[str, str] = {
|
||||
"KEYB": "", # NEXT KEY BUFF — Required, 공백
|
||||
"AUTH": "",
|
||||
"EXCD": ranking_excd,
|
||||
"MIXN": "0",
|
||||
@@ -116,10 +131,11 @@ class OverseasBroker:
|
||||
tr_id = self._broker._settings.OVERSEAS_RANKING_FLUCT_TR_ID
|
||||
path = self._broker._settings.OVERSEAS_RANKING_FLUCT_PATH
|
||||
params = {
|
||||
"KEYB": "", # NEXT KEY BUFF — Required, 공백
|
||||
"AUTH": "",
|
||||
"EXCD": ranking_excd,
|
||||
"NDAY": "0",
|
||||
"GUBN": "1",
|
||||
"GUBN": "1", # 0=하락율, 1=상승율 — 변동성 스캐너는 급등 종목 우선
|
||||
"VOL_RANG": "0",
|
||||
}
|
||||
|
||||
@@ -292,6 +308,131 @@ class OverseasBroker:
|
||||
f"Network error sending overseas order: {exc}"
|
||||
) from exc
|
||||
|
||||
async def get_overseas_pending_orders(
|
||||
self, exchange_code: str
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Fetch unfilled (pending) overseas orders for a given exchange.
|
||||
|
||||
Args:
|
||||
exchange_code: Exchange code (e.g., "NASD", "SEHK").
|
||||
For US markets, NASD returns all US pending orders (NASD/NYSE/AMEX).
|
||||
|
||||
Returns:
|
||||
List of pending order dicts with fields: odno, pdno, sll_buy_dvsn_cd,
|
||||
ft_ord_qty, nccs_qty, ft_ord_unpr3, ovrs_excg_cd.
|
||||
Always returns [] in paper mode (TTTS3018R is live-only).
|
||||
|
||||
Raises:
|
||||
ConnectionError: On network or API errors (live mode only).
|
||||
"""
|
||||
if self._broker._settings.MODE != "live":
|
||||
logger.debug(
|
||||
"Pending orders API (TTTS3018R) not supported in paper mode; returning []"
|
||||
)
|
||||
return []
|
||||
|
||||
await self._broker._rate_limiter.acquire()
|
||||
session = self._broker._get_session()
|
||||
|
||||
# TTTS3018R: 해외주식 미체결내역조회 (실전 전용)
|
||||
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '해외주식 미체결조회' 시트
|
||||
headers = await self._broker._auth_headers("TTTS3018R")
|
||||
params = {
|
||||
"CANO": self._broker._account_no,
|
||||
"ACNT_PRDT_CD": self._broker._product_cd,
|
||||
"OVRS_EXCG_CD": exchange_code,
|
||||
"SORT_SQN": "DS",
|
||||
"CTX_AREA_FK200": "",
|
||||
"CTX_AREA_NK200": "",
|
||||
}
|
||||
url = (
|
||||
f"{self._broker._base_url}/uapi/overseas-stock/v1/trading/inquire-nccs"
|
||||
)
|
||||
|
||||
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_pending_orders failed ({resp.status}): {text}"
|
||||
)
|
||||
data = await resp.json()
|
||||
output = data.get("output", [])
|
||||
if isinstance(output, list):
|
||||
return output
|
||||
return []
|
||||
except (TimeoutError, aiohttp.ClientError) as exc:
|
||||
raise ConnectionError(
|
||||
f"Network error fetching pending orders: {exc}"
|
||||
) from exc
|
||||
|
||||
async def cancel_overseas_order(
|
||||
self,
|
||||
exchange_code: str,
|
||||
stock_code: str,
|
||||
odno: str,
|
||||
qty: int,
|
||||
) -> dict[str, Any]:
|
||||
"""Cancel an overseas limit order.
|
||||
|
||||
Args:
|
||||
exchange_code: Exchange code (e.g., "NASD", "SEHK").
|
||||
stock_code: Stock ticker symbol.
|
||||
odno: Original order number to cancel.
|
||||
qty: Unfilled quantity to cancel.
|
||||
|
||||
Returns:
|
||||
API response dict containing rt_cd and msg1.
|
||||
|
||||
Raises:
|
||||
ValueError: If exchange_code has no cancel TR_ID mapping.
|
||||
ConnectionError: On network or API errors.
|
||||
"""
|
||||
tr_ids = _CANCEL_TR_ID_MAP.get(exchange_code)
|
||||
if tr_ids is None:
|
||||
raise ValueError(f"No cancel TR_ID mapping for exchange: {exchange_code}")
|
||||
live_tr_id, paper_tr_id = tr_ids
|
||||
tr_id = live_tr_id if self._broker._settings.MODE == "live" else paper_tr_id
|
||||
|
||||
await self._broker._rate_limiter.acquire()
|
||||
session = self._broker._get_session()
|
||||
|
||||
# RVSE_CNCL_DVSN_CD="02" means cancel (not revision).
|
||||
# OVRS_ORD_UNPR must be "0" for cancellations.
|
||||
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '해외주식 정정취소주문' 시트
|
||||
body = {
|
||||
"CANO": self._broker._account_no,
|
||||
"ACNT_PRDT_CD": self._broker._product_cd,
|
||||
"OVRS_EXCG_CD": exchange_code,
|
||||
"PDNO": stock_code,
|
||||
"ORGN_ODNO": odno,
|
||||
"RVSE_CNCL_DVSN_CD": "02",
|
||||
"ORD_QTY": str(qty),
|
||||
"OVRS_ORD_UNPR": "0",
|
||||
"ORD_SVR_DVSN_CD": "0",
|
||||
}
|
||||
|
||||
hash_key = await self._broker._get_hash_key(body)
|
||||
headers = await self._broker._auth_headers(tr_id)
|
||||
headers["hashkey"] = hash_key
|
||||
|
||||
url = (
|
||||
f"{self._broker._base_url}/uapi/overseas-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_overseas_order failed ({resp.status}): {text}"
|
||||
)
|
||||
return await resp.json()
|
||||
except (TimeoutError, aiohttp.ClientError) as exc:
|
||||
raise ConnectionError(
|
||||
f"Network error cancelling overseas order: {exc}"
|
||||
) from exc
|
||||
|
||||
def _get_currency_code(self, exchange_code: str) -> str:
|
||||
"""
|
||||
Map exchange code to currency code.
|
||||
|
||||
@@ -17,7 +17,7 @@ class Settings(BaseSettings):
|
||||
|
||||
# Google Gemini
|
||||
GEMINI_API_KEY: str
|
||||
GEMINI_MODEL: str = "gemini-pro"
|
||||
GEMINI_MODEL: str = "gemini-2.0-flash"
|
||||
|
||||
# External Data APIs (optional — for data-driven decisions)
|
||||
NEWS_API_KEY: str | None = None
|
||||
|
||||
@@ -13,10 +13,11 @@ from fastapi import FastAPI, HTTPException, Query
|
||||
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."""
|
||||
app = FastAPI(title="The Ouroboros Dashboard", version="1.0.0")
|
||||
app.state.db_path = db_path
|
||||
app.state.mode = mode
|
||||
|
||||
@app.get("/")
|
||||
def index() -> FileResponse:
|
||||
@@ -111,6 +112,7 @@ def create_dashboard_app(db_path: str) -> FastAPI:
|
||||
|
||||
return {
|
||||
"date": today,
|
||||
"mode": mode,
|
||||
"markets": market_status,
|
||||
"totals": {
|
||||
"trade_count": total_trades,
|
||||
|
||||
@@ -43,6 +43,19 @@
|
||||
font-size: 12px; transition: border-color 0.2s;
|
||||
}
|
||||
.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-wrap {
|
||||
@@ -225,6 +238,7 @@
|
||||
<header>
|
||||
<h1>🐍 The Ouroboros</h1>
|
||||
<div class="header-right">
|
||||
<span class="mode-badge" id="mode-badge">--</span>
|
||||
<div class="cb-gauge-wrap" id="cb-gauge" title="Circuit Breaker">
|
||||
<span class="cb-dot unknown" id="cb-dot"></span>
|
||||
<span id="cb-label">CB --</span>
|
||||
@@ -512,9 +526,22 @@
|
||||
}
|
||||
document.getElementById('card-pnl-sub').textContent = `결정 ${t.decision_count ?? 0}건`;
|
||||
renderCbGauge(d.circuit_breaker);
|
||||
renderModeBadge(d.mode);
|
||||
} 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() {
|
||||
try {
|
||||
const r = await fetch('/api/performance?market=all');
|
||||
|
||||
@@ -254,7 +254,7 @@ def get_open_position(
|
||||
"""Return open position if latest trade is BUY, else None."""
|
||||
cursor = conn.execute(
|
||||
"""
|
||||
SELECT action, decision_id, price, quantity
|
||||
SELECT action, decision_id, price, quantity, timestamp
|
||||
FROM trades
|
||||
WHERE stock_code = ?
|
||||
AND market = ?
|
||||
@@ -266,7 +266,7 @@ def get_open_position(
|
||||
row = cursor.fetchone()
|
||||
if not row or row[0] != "BUY":
|
||||
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(
|
||||
|
||||
761
src/main.py
761
src/main.py
@@ -19,7 +19,7 @@ from src.analysis.smart_scanner import ScanCandidate, SmartVolatilityScanner
|
||||
from src.analysis.volatility import VolatilityAnalyzer
|
||||
from src.brain.context_selector import ContextSelector
|
||||
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.config import Settings
|
||||
from src.context.aggregator import ContextAggregator
|
||||
@@ -40,7 +40,7 @@ from src.evolution.daily_review import DailyReviewer
|
||||
from src.evolution.optimizer import EvolutionOptimizer
|
||||
from src.logging.decision_logger import DecisionLogger
|
||||
from src.logging_config import setup_logging
|
||||
from src.markets.schedule import MarketInfo, get_next_market_open, get_open_markets
|
||||
from src.markets.schedule import MARKETS, MarketInfo, get_next_market_open, get_open_markets
|
||||
from src.notifications.telegram_client import NotificationFilter, TelegramClient, TelegramCommandHandler
|
||||
from src.strategy.models import DayPlaybook, MarketOutlook
|
||||
from src.strategy.playbook_store import PlaybookStore
|
||||
@@ -88,6 +88,132 @@ DAILY_TRADE_SESSIONS = 4 # Number of trading sessions per day
|
||||
TRADE_SESSION_INTERVAL_HOURS = 6 # Hours between sessions
|
||||
|
||||
|
||||
async def _retry_connection(coro_factory: Any, *args: Any, label: str = "", **kwargs: Any) -> Any:
|
||||
"""Call an async function retrying on ConnectionError with exponential backoff.
|
||||
|
||||
Retries up to MAX_CONNECTION_RETRIES times (exclusive of the first attempt),
|
||||
sleeping 2^attempt seconds between attempts. Use only for idempotent read
|
||||
operations — never for order submission.
|
||||
|
||||
Args:
|
||||
coro_factory: Async callable (method or function) to invoke.
|
||||
*args: Positional arguments forwarded to coro_factory.
|
||||
label: Human-readable label for log messages.
|
||||
**kwargs: Keyword arguments forwarded to coro_factory.
|
||||
|
||||
Raises:
|
||||
ConnectionError: If all retries are exhausted.
|
||||
"""
|
||||
for attempt in range(1, MAX_CONNECTION_RETRIES + 1):
|
||||
try:
|
||||
return await coro_factory(*args, **kwargs)
|
||||
except ConnectionError as exc:
|
||||
if attempt < MAX_CONNECTION_RETRIES:
|
||||
wait_secs = 2 ** attempt
|
||||
logger.warning(
|
||||
"Connection error %s (attempt %d/%d), retrying in %ds: %s",
|
||||
label,
|
||||
attempt,
|
||||
MAX_CONNECTION_RETRIES,
|
||||
wait_secs,
|
||||
exc,
|
||||
)
|
||||
await asyncio.sleep(wait_secs)
|
||||
else:
|
||||
logger.error(
|
||||
"Connection error %s — all %d retries exhausted: %s",
|
||||
label,
|
||||
MAX_CONNECTION_RETRIES,
|
||||
exc,
|
||||
)
|
||||
raise
|
||||
|
||||
|
||||
async def sync_positions_from_broker(
|
||||
broker: Any,
|
||||
overseas_broker: Any,
|
||||
db_conn: Any,
|
||||
settings: "Settings",
|
||||
) -> int:
|
||||
"""Sync open positions from the live broker into the local DB at startup.
|
||||
|
||||
Fetches current holdings from the broker for all configured markets and
|
||||
inserts a synthetic BUY record for any position that the DB does not
|
||||
already know about. This prevents double-buy when positions were opened
|
||||
in a previous session or entered manually outside the system.
|
||||
|
||||
Returns:
|
||||
Number of new positions synced.
|
||||
"""
|
||||
synced = 0
|
||||
seen_exchange_codes: set[str] = set()
|
||||
|
||||
for market_code in settings.enabled_market_list:
|
||||
market = MARKETS.get(market_code)
|
||||
if market is None:
|
||||
continue
|
||||
|
||||
try:
|
||||
if market.is_domestic:
|
||||
balance_data = await broker.get_balance()
|
||||
log_market = market_code # "KR"
|
||||
else:
|
||||
if market.exchange_code in seen_exchange_codes:
|
||||
continue
|
||||
seen_exchange_codes.add(market.exchange_code)
|
||||
balance_data = await overseas_broker.get_overseas_balance(
|
||||
market.exchange_code
|
||||
)
|
||||
log_market = market_code # e.g. "US_NASDAQ"
|
||||
except ConnectionError as exc:
|
||||
logger.warning(
|
||||
"Startup sync: balance fetch failed for %s — skipping: %s",
|
||||
market_code,
|
||||
exc,
|
||||
)
|
||||
continue
|
||||
|
||||
held_codes = _extract_held_codes_from_balance(
|
||||
balance_data, is_domestic=market.is_domestic
|
||||
)
|
||||
for stock_code in held_codes:
|
||||
if get_open_position(db_conn, stock_code, log_market):
|
||||
continue # already tracked
|
||||
qty = _extract_held_qty_from_balance(
|
||||
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(
|
||||
conn=db_conn,
|
||||
stock_code=stock_code,
|
||||
action="BUY",
|
||||
confidence=0,
|
||||
rationale="[startup-sync] Position detected from broker at startup",
|
||||
quantity=qty,
|
||||
price=avg_price,
|
||||
market=log_market,
|
||||
exchange_code=market.exchange_code,
|
||||
mode=settings.MODE,
|
||||
)
|
||||
logger.info(
|
||||
"Startup sync: %s/%s recorded as open position (qty=%d)",
|
||||
log_market,
|
||||
stock_code,
|
||||
qty,
|
||||
)
|
||||
synced += 1
|
||||
|
||||
if synced:
|
||||
logger.info(
|
||||
"Startup sync complete: %d position(s) synced from broker", synced
|
||||
)
|
||||
else:
|
||||
logger.info("Startup sync: no new positions to sync from broker")
|
||||
return synced
|
||||
|
||||
|
||||
def _extract_symbol_from_holding(item: dict[str, Any]) -> str:
|
||||
"""Extract symbol from overseas holding payload variants."""
|
||||
for key in (
|
||||
@@ -134,7 +260,15 @@ def _extract_held_codes_from_balance(
|
||||
if is_domestic:
|
||||
qty = int(holding.get("ord_psbl_qty") or holding.get("hldg_qty") or 0)
|
||||
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:
|
||||
codes.append(code)
|
||||
return codes
|
||||
@@ -157,10 +291,12 @@ def _extract_held_qty_from_balance(
|
||||
ord_psbl_qty — 주문가능수량 (preferred: excludes unsettled)
|
||||
hldg_qty — 보유수량 (fallback)
|
||||
|
||||
Overseas fields (output1):
|
||||
Overseas fields (VTTS3012R / TTTS3012R output1):
|
||||
ovrs_pdno — 종목코드
|
||||
ovrs_cblc_qty — 해외잔고수량 (preferred)
|
||||
hldg_qty — 보유수량 (fallback)
|
||||
ord_psbl_qty — 주문가능수량 (preferred: actual sellable qty)
|
||||
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", [])
|
||||
if isinstance(output1, dict):
|
||||
@@ -178,11 +314,47 @@ def _extract_held_qty_from_balance(
|
||||
if is_domestic:
|
||||
qty = int(holding.get("ord_psbl_qty") or holding.get("hldg_qty") or 0)
|
||||
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 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(
|
||||
*,
|
||||
action: str,
|
||||
@@ -404,6 +576,22 @@ async def trading_cycle(
|
||||
market_data["rsi"] = candidate.rsi
|
||||
market_data["volume_ratio"] = candidate.volume_ratio
|
||||
|
||||
# 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)
|
||||
timeframe = datetime.now(UTC).isoformat()
|
||||
context_store.set_context(
|
||||
@@ -530,11 +718,11 @@ async def trading_cycle(
|
||||
# BUY 결정 전 기존 포지션 체크 (중복 매수 방지)
|
||||
if decision.action == "BUY":
|
||||
existing_position = get_open_position(db_conn, stock_code, market.code)
|
||||
if not existing_position and not market.is_domestic:
|
||||
if not existing_position:
|
||||
# SELL 지정가 접수 후 미체결 시 DB는 종료로 기록되나 브로커는 여전히 보유 중.
|
||||
# 이중 매수 방지를 위해 라이브 브로커 잔고를 authoritative source로 사용.
|
||||
# 국내/해외 모두 라이브 브로커 잔고를 authoritative source로 사용.
|
||||
broker_qty = _extract_held_qty_from_balance(
|
||||
balance_data, stock_code, is_domestic=False
|
||||
balance_data, stock_code, is_domestic=market.is_domestic
|
||||
)
|
||||
if broker_qty > 0:
|
||||
existing_position = {"price": 0.0, "quantity": broker_qty}
|
||||
@@ -558,7 +746,7 @@ async def trading_cycle(
|
||||
open_position = get_open_position(db_conn, stock_code, market.code)
|
||||
if open_position:
|
||||
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
|
||||
stop_loss_threshold = -2.0
|
||||
take_profit_threshold = 3.0
|
||||
@@ -730,28 +918,42 @@ async def trading_cycle(
|
||||
# 5. Send order
|
||||
order_succeeded = True
|
||||
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(
|
||||
stock_code=stock_code,
|
||||
order_type=decision.action,
|
||||
quantity=quantity,
|
||||
price=0, # market order
|
||||
price=order_price,
|
||||
)
|
||||
else:
|
||||
# For overseas orders:
|
||||
# - KIS VTS only accepts limit orders (지정가만 가능)
|
||||
# - BUY: use 0.5% premium over last price to improve fill probability
|
||||
# (ask price is typically slightly above last, and VTS won't fill below ask)
|
||||
# - SELL: use last price as the limit
|
||||
# For overseas orders, always use limit orders (지정가):
|
||||
# - KIS market orders (ORD_DVSN=01) calculate quantity based on upper limit
|
||||
# price (상한가 기준), resulting in only 60-80% of intended cash being used.
|
||||
# - BUY: +0.2% above last price — tight enough to minimise overpayment while
|
||||
# achieving >90% fill rate on large-cap US stocks.
|
||||
# - 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).
|
||||
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":
|
||||
order_price = round(current_price * 1.005, 4)
|
||||
overseas_price = round(current_price * 1.002, _price_decimals)
|
||||
else:
|
||||
order_price = current_price
|
||||
overseas_price = round(current_price * 0.998, _price_decimals)
|
||||
result = await overseas_broker.send_overseas_order(
|
||||
exchange_code=market.exchange_code,
|
||||
stock_code=stock_code,
|
||||
order_type=decision.action,
|
||||
quantity=quantity,
|
||||
price=order_price, # limit order — KIS VTS rejects market orders
|
||||
price=overseas_price, # limit order
|
||||
)
|
||||
# Check if KIS rejected the order (rt_cd != "0")
|
||||
if result.get("rt_cd", "") != "0":
|
||||
@@ -774,6 +976,33 @@ async def trading_cycle(
|
||||
stock_code,
|
||||
_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"))
|
||||
|
||||
# 5.5. Notify trade execution (only on success)
|
||||
@@ -853,6 +1082,328 @@ 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(
|
||||
overseas_broker: OverseasBroker,
|
||||
telegram: TelegramClient,
|
||||
settings: Settings,
|
||||
sell_resubmit_counts: dict[str, int],
|
||||
buy_cooldown: dict[str, float] | None = None,
|
||||
) -> None:
|
||||
"""Check and handle unfilled (pending) overseas limit orders.
|
||||
|
||||
Called once per market loop iteration before new orders are considered.
|
||||
In paper mode the KIS pending-orders API (TTTS3018R) is unsupported, so
|
||||
this function returns immediately without making any 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). Resubmission is attempted at most once per key
|
||||
per session to avoid infinite retry loops.
|
||||
|
||||
Args:
|
||||
overseas_broker: OverseasBroker instance.
|
||||
telegram: TelegramClient for notifications.
|
||||
settings: Application settings (MODE, ENABLED_MARKETS).
|
||||
sell_resubmit_counts: Mutable dict tracking SELL resubmission attempts
|
||||
per "{exchange_code}:{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.
|
||||
"""
|
||||
# Determine which exchange codes to query, deduplicating US exchanges.
|
||||
# NASD alone returns all US (NASD/NYSE/AMEX) pending orders.
|
||||
us_exchanges = frozenset({"NASD", "NYSE", "AMEX"})
|
||||
exchange_codes: list[str] = []
|
||||
seen_us = False
|
||||
for market_code in settings.enabled_market_list:
|
||||
market_info = MARKETS.get(market_code)
|
||||
if market_info is None or market_info.is_domestic:
|
||||
continue
|
||||
exc_code = market_info.exchange_code
|
||||
if exc_code in us_exchanges:
|
||||
if not seen_us:
|
||||
exchange_codes.append("NASD")
|
||||
seen_us = True
|
||||
elif exc_code not in exchange_codes:
|
||||
exchange_codes.append(exc_code)
|
||||
|
||||
now = asyncio.get_event_loop().time()
|
||||
|
||||
for exchange_code in exchange_codes:
|
||||
try:
|
||||
orders = await overseas_broker.get_overseas_pending_orders(exchange_code)
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"Failed to fetch pending orders for %s: %s", exchange_code, exc
|
||||
)
|
||||
continue
|
||||
|
||||
for order in orders:
|
||||
try:
|
||||
stock_code = order.get("pdno", "")
|
||||
odno = order.get("odno", "")
|
||||
sll_buy = order.get("sll_buy_dvsn_cd", "") # "01"=SELL, "02"=BUY
|
||||
nccs_qty = int(order.get("nccs_qty", "0") or "0")
|
||||
order_exchange = order.get("ovrs_excg_cd") or exchange_code
|
||||
key = f"{order_exchange}:{stock_code}"
|
||||
|
||||
if not stock_code or not odno or nccs_qty <= 0:
|
||||
continue
|
||||
|
||||
# Cancel the pending order first regardless of direction.
|
||||
cancel_result = await overseas_broker.cancel_overseas_order(
|
||||
exchange_code=order_exchange,
|
||||
stock_code=stock_code,
|
||||
odno=odno,
|
||||
qty=nccs_qty,
|
||||
)
|
||||
if cancel_result.get("rt_cd") != "0":
|
||||
logger.warning(
|
||||
"Cancel failed for %s %s: rt_cd=%s msg=%s",
|
||||
order_exchange,
|
||||
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=order_exchange,
|
||||
action="BUY",
|
||||
quantity=nccs_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 %s %s already resubmitted once — no further resubmit",
|
||||
order_exchange,
|
||||
stock_code,
|
||||
)
|
||||
try:
|
||||
await telegram.notify_unfilled_order(
|
||||
stock_code=stock_code,
|
||||
market=order_exchange,
|
||||
action="SELL",
|
||||
quantity=nccs_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:
|
||||
price_data = await overseas_broker.get_overseas_price(
|
||||
order_exchange, stock_code
|
||||
)
|
||||
last_price = float(
|
||||
price_data.get("output", {}).get("last", "0") or "0"
|
||||
)
|
||||
if last_price <= 0:
|
||||
raise ValueError(
|
||||
f"Invalid price ({last_price}) for {stock_code}"
|
||||
)
|
||||
new_price = round(last_price * 0.996, 4)
|
||||
await overseas_broker.send_overseas_order(
|
||||
exchange_code=order_exchange,
|
||||
stock_code=stock_code,
|
||||
order_type="SELL",
|
||||
quantity=nccs_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=order_exchange,
|
||||
action="SELL",
|
||||
quantity=nccs_qty,
|
||||
outcome="resubmitted",
|
||||
new_price=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 %s %s: %s",
|
||||
order_exchange,
|
||||
stock_code,
|
||||
exc,
|
||||
)
|
||||
|
||||
except Exception as exc:
|
||||
logger.error(
|
||||
"Error handling pending order for %s: %s",
|
||||
order.get("pdno", "?"),
|
||||
exc,
|
||||
)
|
||||
|
||||
|
||||
async def run_daily_session(
|
||||
broker: KISBroker,
|
||||
overseas_broker: OverseasBroker,
|
||||
@@ -867,29 +1418,70 @@ async def run_daily_session(
|
||||
telegram: TelegramClient,
|
||||
settings: Settings,
|
||||
smart_scanner: SmartVolatilityScanner | None = None,
|
||||
) -> None:
|
||||
daily_start_eval: float = 0.0,
|
||||
) -> float:
|
||||
"""Execute one daily trading session.
|
||||
|
||||
V2 proactive strategy: 1 Gemini call for playbook generation,
|
||||
then local scenario evaluation per stock (0 API calls).
|
||||
|
||||
Args:
|
||||
daily_start_eval: Portfolio evaluation at the start of the trading day.
|
||||
Used to compute intra-day P&L for the Circuit Breaker.
|
||||
Pass 0.0 on the first session of each day; the function will set
|
||||
it from the first balance query and return it for subsequent
|
||||
sessions.
|
||||
|
||||
Returns:
|
||||
The daily_start_eval value that should be forwarded to the next
|
||||
session of the same trading day.
|
||||
"""
|
||||
# Get currently open markets
|
||||
open_markets = get_open_markets(settings.enabled_market_list)
|
||||
|
||||
if not open_markets:
|
||||
logger.info("No markets open for this session")
|
||||
return
|
||||
return daily_start_eval
|
||||
|
||||
logger.info("Starting daily trading session for %d markets", len(open_markets))
|
||||
|
||||
# BUY cooldown: prevents retrying stocks rejected for insufficient balance
|
||||
daily_buy_cooldown: dict[str, float] = {} # "{market_code}:{stock_code}" -> expiry timestamp
|
||||
|
||||
# Tracks SELL resubmission attempts per "{exchange_code}:{stock_code}" (max 1 per session).
|
||||
sell_resubmit_counts: dict[str, int] = {}
|
||||
|
||||
# Process each open market
|
||||
for market in open_markets:
|
||||
# Use market-local date for playbook keying
|
||||
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.
|
||||
if not market.is_domestic:
|
||||
try:
|
||||
await handle_overseas_pending_orders(
|
||||
overseas_broker,
|
||||
telegram,
|
||||
settings,
|
||||
sell_resubmit_counts,
|
||||
daily_buy_cooldown,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning("Pending order check failed: %s", exc)
|
||||
|
||||
# Dynamic stock discovery via scanner (no static watchlists)
|
||||
candidates_list: list[ScanCandidate] = []
|
||||
fallback_stocks: list[str] | None = None
|
||||
@@ -964,11 +1556,18 @@ async def run_daily_session(
|
||||
try:
|
||||
if market.is_domestic:
|
||||
current_price, price_change_pct, foreigner_net = (
|
||||
await broker.get_current_price(stock_code)
|
||||
await _retry_connection(
|
||||
broker.get_current_price,
|
||||
stock_code,
|
||||
label=stock_code,
|
||||
)
|
||||
)
|
||||
else:
|
||||
price_data = await overseas_broker.get_overseas_price(
|
||||
market.exchange_code, stock_code
|
||||
price_data = await _retry_connection(
|
||||
overseas_broker.get_overseas_price,
|
||||
market.exchange_code,
|
||||
stock_code,
|
||||
label=f"{stock_code}@{market.exchange_code}",
|
||||
)
|
||||
current_price = safe_float(
|
||||
price_data.get("output", {}).get("last", "0")
|
||||
@@ -1019,9 +1618,27 @@ async def run_daily_session(
|
||||
logger.warning("No valid stock data for market %s", market.code)
|
||||
continue
|
||||
|
||||
# Get balance data once for the market
|
||||
# Get balance data once for the market (read-only — safe to retry)
|
||||
try:
|
||||
if market.is_domestic:
|
||||
balance_data = await _retry_connection(
|
||||
broker.get_balance, label=f"balance:{market.code}"
|
||||
)
|
||||
else:
|
||||
balance_data = await _retry_connection(
|
||||
overseas_broker.get_overseas_balance,
|
||||
market.exchange_code,
|
||||
label=f"overseas_balance:{market.exchange_code}",
|
||||
)
|
||||
except ConnectionError as exc:
|
||||
logger.error(
|
||||
"Balance fetch failed for market %s after all retries — skipping market: %s",
|
||||
market.code,
|
||||
exc,
|
||||
)
|
||||
continue
|
||||
|
||||
if market.is_domestic:
|
||||
balance_data = await broker.get_balance()
|
||||
output2 = balance_data.get("output2", [{}])
|
||||
total_eval = safe_float(
|
||||
output2[0].get("tot_evlu_amt", "0")
|
||||
@@ -1033,7 +1650,6 @@ async def run_daily_session(
|
||||
output2[0].get("pchs_amt_smtl_amt", "0")
|
||||
) if output2 else 0
|
||||
else:
|
||||
balance_data = await overseas_broker.get_overseas_balance(market.exchange_code)
|
||||
output2 = balance_data.get("output2", [{}])
|
||||
if isinstance(output2, list) and output2:
|
||||
balance_info = output2[0]
|
||||
@@ -1056,7 +1672,22 @@ async def run_daily_session(
|
||||
):
|
||||
total_cash = settings.PAPER_OVERSEAS_CASH
|
||||
|
||||
# Calculate daily P&L %
|
||||
# Capture the day's opening portfolio value on the first market processed
|
||||
# in this session. Used to compute intra-day P&L for the CB instead of
|
||||
# the cumulative purchase_total which spans the entire account history.
|
||||
if daily_start_eval <= 0 and total_eval > 0:
|
||||
daily_start_eval = total_eval
|
||||
logger.info(
|
||||
"Daily CB baseline set: total_eval=%.2f (first balance of the day)",
|
||||
daily_start_eval,
|
||||
)
|
||||
|
||||
# Daily P&L: compare current eval vs start-of-day eval.
|
||||
# Falls back to purchase_total if daily_start_eval is unavailable (e.g. paper
|
||||
# mode where balance API returns 0 for all values).
|
||||
if daily_start_eval > 0:
|
||||
pnl_pct = (total_eval - daily_start_eval) / daily_start_eval * 100
|
||||
else:
|
||||
pnl_pct = (
|
||||
((total_eval - purchase_total) / purchase_total * 100)
|
||||
if purchase_total > 0
|
||||
@@ -1095,11 +1726,11 @@ async def run_daily_session(
|
||||
# BUY 중복 방지: 브로커 잔고 기반 (미체결 SELL 리밋 주문 보호)
|
||||
if decision.action == "BUY":
|
||||
daily_existing = get_open_position(db_conn, stock_code, market.code)
|
||||
if not daily_existing and not market.is_domestic:
|
||||
if not daily_existing:
|
||||
# SELL 지정가 접수 후 미체결 시 DB는 종료로 기록되나 브로커는 여전히 보유 중.
|
||||
# 이중 매수 방지를 위해 라이브 브로커 잔고를 authoritative source로 사용.
|
||||
# 국내/해외 모두 라이브 브로커 잔고를 authoritative source로 사용.
|
||||
broker_qty = _extract_held_qty_from_balance(
|
||||
balance_data, stock_code, is_domestic=False
|
||||
balance_data, stock_code, is_domestic=market.is_domestic
|
||||
)
|
||||
if broker_qty > 0:
|
||||
daily_existing = {"price": 0.0, "quantity": broker_qty}
|
||||
@@ -1240,11 +1871,21 @@ async def run_daily_session(
|
||||
order_succeeded = True
|
||||
try:
|
||||
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(
|
||||
stock_code=stock_code,
|
||||
order_type=decision.action,
|
||||
quantity=quantity,
|
||||
price=0, # market order
|
||||
price=order_price,
|
||||
)
|
||||
else:
|
||||
# KIS VTS only accepts limit orders; use 0.5% premium for BUY
|
||||
@@ -1330,6 +1971,7 @@ async def run_daily_session(
|
||||
)
|
||||
|
||||
logger.info("Daily trading session completed")
|
||||
return daily_start_eval
|
||||
|
||||
|
||||
async def _handle_market_close(
|
||||
@@ -1456,7 +2098,7 @@ def _start_dashboard_server(settings: Settings) -> threading.Thread | None:
|
||||
import uvicorn
|
||||
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(
|
||||
app,
|
||||
host=settings.DASHBOARD_HOST,
|
||||
@@ -1908,6 +2550,9 @@ async def run(settings: Settings) -> None:
|
||||
# BUY cooldown: prevents retrying a stock rejected for insufficient balance
|
||||
buy_cooldown: dict[str, float] = {} # "{market_code}:{stock_code}" -> expiry timestamp
|
||||
|
||||
# Tracks SELL resubmission attempts per "{exchange_code}:{stock_code}" (max 1 until restart).
|
||||
sell_resubmit_counts: dict[str, int] = {}
|
||||
|
||||
# Initialize latency control system
|
||||
criticality_assessor = CriticalityAssessor(
|
||||
critical_pnl_threshold=-2.5, # Near circuit breaker at -3.0%
|
||||
@@ -1947,6 +2592,12 @@ async def run(settings: Settings) -> None:
|
||||
except Exception as exc:
|
||||
logger.warning("System startup notification failed: %s", exc)
|
||||
|
||||
# Sync broker positions → DB to prevent double-buy on restart
|
||||
try:
|
||||
await sync_positions_from_broker(broker, overseas_broker, db_conn, settings)
|
||||
except Exception as exc:
|
||||
logger.warning("Startup position sync failed (non-fatal): %s", exc)
|
||||
|
||||
# Start command handler
|
||||
try:
|
||||
await command_handler.start_polling()
|
||||
@@ -1965,13 +2616,26 @@ async def run(settings: Settings) -> None:
|
||||
|
||||
session_interval = settings.SESSION_INTERVAL_HOURS * 3600 # Convert to seconds
|
||||
|
||||
# daily_start_eval: portfolio eval captured at the first session of each
|
||||
# trading day. Reset on calendar-date change so the CB measures only
|
||||
# today's drawdown, not cumulative account history.
|
||||
_cb_daily_start_eval: float = 0.0
|
||||
_cb_last_date: str = ""
|
||||
|
||||
while not shutdown.is_set():
|
||||
# Wait for trading to be unpaused
|
||||
await pause_trading.wait()
|
||||
_run_context_scheduler(context_scheduler, now=datetime.now(UTC))
|
||||
|
||||
# Reset intra-day CB baseline on a new calendar date
|
||||
today_str = datetime.now(UTC).date().isoformat()
|
||||
if today_str != _cb_last_date:
|
||||
_cb_last_date = today_str
|
||||
_cb_daily_start_eval = 0.0
|
||||
logger.info("New trading day %s — daily CB baseline reset", today_str)
|
||||
|
||||
try:
|
||||
await run_daily_session(
|
||||
_cb_daily_start_eval = await run_daily_session(
|
||||
broker,
|
||||
overseas_broker,
|
||||
scenario_engine,
|
||||
@@ -1985,6 +2649,7 @@ async def run(settings: Settings) -> None:
|
||||
telegram,
|
||||
settings,
|
||||
smart_scanner=smart_scanner,
|
||||
daily_start_eval=_cb_daily_start_eval,
|
||||
)
|
||||
except CircuitBreakerTripped:
|
||||
logger.critical("Circuit breaker tripped — shutting down")
|
||||
@@ -2073,6 +2738,32 @@ async def run(settings: Settings) -> None:
|
||||
logger.warning("Market open notification failed: %s", exc)
|
||||
_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.
|
||||
if not market.is_domestic:
|
||||
try:
|
||||
await handle_overseas_pending_orders(
|
||||
overseas_broker,
|
||||
telegram,
|
||||
settings,
|
||||
sell_resubmit_counts,
|
||||
buy_cooldown,
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning("Pending order check failed: %s", exc)
|
||||
|
||||
# Smart Scanner: dynamic stock discovery (no static watchlists)
|
||||
now_timestamp = asyncio.get_event_loop().time()
|
||||
last_scan = last_scan_time.get(market.code, 0.0)
|
||||
|
||||
@@ -473,6 +473,48 @@ class TelegramClient:
|
||||
NotificationMessage(priority=priority, message=message)
|
||||
)
|
||||
|
||||
async def notify_unfilled_order(
|
||||
self,
|
||||
stock_code: str,
|
||||
market: str,
|
||||
action: str,
|
||||
quantity: int,
|
||||
outcome: str,
|
||||
new_price: float | None = None,
|
||||
) -> None:
|
||||
"""Notify about an unfilled overseas order that was cancelled or resubmitted.
|
||||
|
||||
Args:
|
||||
stock_code: Stock ticker symbol.
|
||||
market: Exchange/market code (e.g., "NASD", "SEHK").
|
||||
action: "BUY" or "SELL".
|
||||
quantity: Unfilled quantity.
|
||||
outcome: "cancelled" or "resubmitted".
|
||||
new_price: New order price if resubmitted (None if only cancelled).
|
||||
"""
|
||||
if not self._filter.trades:
|
||||
return
|
||||
# SELL resubmit is high priority — position liquidation at risk.
|
||||
# BUY cancel is medium priority — only cash is freed.
|
||||
priority = (
|
||||
NotificationPriority.HIGH
|
||||
if action == "SELL"
|
||||
else NotificationPriority.MEDIUM
|
||||
)
|
||||
outcome_emoji = "🔄" if outcome == "resubmitted" else "❌"
|
||||
outcome_label = "재주문" if outcome == "resubmitted" else "취소됨"
|
||||
action_emoji = "🔴" if action == "SELL" else "🟢"
|
||||
lines = [
|
||||
f"<b>{outcome_emoji} 미체결 주문 {outcome_label}</b>",
|
||||
f"Symbol: <code>{stock_code}</code> ({market})",
|
||||
f"Action: {action_emoji} {action}",
|
||||
f"Quantity: {quantity:,} shares",
|
||||
]
|
||||
if new_price is not None:
|
||||
lines.append(f"New Price: {new_price:.4f}")
|
||||
message = "\n".join(lines)
|
||||
await self._send_notification(NotificationMessage(priority=priority, message=message))
|
||||
|
||||
async def notify_error(
|
||||
self, error_type: str, error_msg: str, context: str
|
||||
) -> None:
|
||||
|
||||
@@ -93,9 +93,21 @@ class TestMalformedJsonHandling:
|
||||
|
||||
def test_json_with_missing_fields_returns_hold(self, settings):
|
||||
client = GeminiClient(settings)
|
||||
decision = client.parse_response('{"action": "BUY"}')
|
||||
raw = '{"action": "BUY"}'
|
||||
decision = client.parse_response(raw)
|
||||
assert decision.action == "HOLD"
|
||||
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):
|
||||
client = GeminiClient(settings)
|
||||
@@ -290,9 +302,10 @@ class TestPromptOverride:
|
||||
client = GeminiClient(settings)
|
||||
|
||||
custom_prompt = "You are a playbook generator. Return JSON with scenarios."
|
||||
playbook_json = '{"market_outlook": "neutral", "stocks": []}'
|
||||
|
||||
mock_response = MagicMock()
|
||||
mock_response.text = '{"action": "HOLD", "confidence": 50, "rationale": "test"}'
|
||||
mock_response.text = playbook_json
|
||||
|
||||
with patch.object(
|
||||
client._client.aio.models,
|
||||
@@ -305,7 +318,7 @@ class TestPromptOverride:
|
||||
"current_price": 0,
|
||||
"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
|
||||
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
|
||||
)
|
||||
assert actual_prompt == custom_prompt
|
||||
# Raw response preserved in rationale without parse_response (#247)
|
||||
assert decision.rationale == playbook_json
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_prompt_override_skips_optimization(self, settings):
|
||||
"""prompt_override should bypass prompt optimization."""
|
||||
async def test_prompt_override_skips_parse_response(self, settings):
|
||||
"""prompt_override bypasses parse_response — no Missing fields warning, raw preserved."""
|
||||
client = GeminiClient(settings)
|
||||
client._enable_optimization = True
|
||||
|
||||
custom_prompt = "Custom playbook prompt"
|
||||
playbook_json = '{"market_outlook": "bullish", "stocks": [{"stock_code": "AAPL"}]}'
|
||||
|
||||
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(
|
||||
client._client.aio.models,
|
||||
@@ -341,6 +387,7 @@ class TestPromptOverride:
|
||||
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
|
||||
)
|
||||
# The custom prompt must be used, not the compressed prompt
|
||||
assert actual_prompt == custom_prompt
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -354,6 +354,8 @@ class TestFetchMarketRankings:
|
||||
assert "ranking/fluctuation" in url
|
||||
assert headers.get("tr_id") == "FHPST01700000"
|
||||
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
|
||||
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]["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)
|
||||
@@ -725,3 +748,195 @@ class TestTRIDBranchingDomestic:
|
||||
|
||||
order_headers = mock_post.call_args_list[1][1].get("headers", {})
|
||||
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"]
|
||||
assert cb["status"] == "unknown"
|
||||
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"
|
||||
|
||||
1779
tests/test_main.py
1779
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_ACCOUNT_NO="12345678-01",
|
||||
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"]
|
||||
|
||||
assert "/uapi/overseas-stock/v1/ranking/updown-rate" in url
|
||||
assert params["KEYB"] == "" # Required by KIS API spec
|
||||
assert params["EXCD"] == "NAS"
|
||||
assert params["NDAY"] == "0"
|
||||
assert params["GUBN"] == "1"
|
||||
assert params["GUBN"] == "1" # 1=상승율 — 변동성 스캐너는 급등 종목 우선
|
||||
assert params["VOL_RANG"] == "0"
|
||||
|
||||
overseas_broker._broker._auth_headers.assert_called_with("HHDFS76290000")
|
||||
@@ -157,6 +159,7 @@ class TestFetchOverseasRankings:
|
||||
params = call_args[1]["params"]
|
||||
|
||||
assert "/uapi/overseas-stock/v1/ranking/volume-surge" in url
|
||||
assert params["KEYB"] == "" # Required by KIS API spec
|
||||
assert params["EXCD"] == "NYS"
|
||||
assert params["MIXN"] == "0"
|
||||
assert params["VOL_RANG"] == "0"
|
||||
@@ -813,3 +816,221 @@ class TestOverseasTRIDBranching:
|
||||
|
||||
await broker.send_overseas_order("NASD", "AAPL", "SELL", 1)
|
||||
assert "TTTT1006U" in captured
|
||||
|
||||
|
||||
class TestGetOverseasPendingOrders:
|
||||
"""Tests for get_overseas_pending_orders method."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_paper_mode_returns_empty(
|
||||
self, overseas_broker: OverseasBroker
|
||||
) -> None:
|
||||
"""Paper mode should immediately return [] without any API call."""
|
||||
# Default mock_settings has MODE="paper"
|
||||
overseas_broker._broker._settings = overseas_broker._broker._settings.model_copy(
|
||||
update={"MODE": "paper"}
|
||||
)
|
||||
mock_session = MagicMock()
|
||||
_setup_broker_mocks(overseas_broker, mock_session)
|
||||
|
||||
result = await overseas_broker.get_overseas_pending_orders("NASD")
|
||||
|
||||
assert result == []
|
||||
mock_session.get.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_live_mode_calls_ttts3018r_with_correct_params(
|
||||
self, overseas_broker: OverseasBroker
|
||||
) -> None:
|
||||
"""Live mode should call TTTS3018R with OVRS_EXCG_CD and return output list."""
|
||||
overseas_broker._broker._settings = overseas_broker._broker._settings.model_copy(
|
||||
update={"MODE": "live"}
|
||||
)
|
||||
captured_tr_id: list[str] = []
|
||||
captured_params: list[dict] = []
|
||||
|
||||
async def mock_auth_headers(tr_id: str) -> dict:
|
||||
captured_tr_id.append(tr_id)
|
||||
return {}
|
||||
|
||||
overseas_broker._broker._auth_headers = mock_auth_headers # type: ignore[method-assign]
|
||||
|
||||
pending_orders = [
|
||||
{"odno": "001", "pdno": "AAPL", "sll_buy_dvsn_cd": "02", "nccs_qty": "5"}
|
||||
]
|
||||
mock_resp = AsyncMock()
|
||||
mock_resp.status = 200
|
||||
mock_resp.json = AsyncMock(return_value={"output": pending_orders})
|
||||
|
||||
mock_session = MagicMock()
|
||||
|
||||
def _capture_get(url: str, **kwargs: object) -> MagicMock:
|
||||
captured_params.append(kwargs.get("params", {}))
|
||||
return _make_async_cm(mock_resp)
|
||||
|
||||
mock_session.get = MagicMock(side_effect=_capture_get)
|
||||
overseas_broker._broker._rate_limiter.acquire = AsyncMock()
|
||||
overseas_broker._broker._get_session = MagicMock(return_value=mock_session)
|
||||
|
||||
result = await overseas_broker.get_overseas_pending_orders("NASD")
|
||||
|
||||
assert result == pending_orders
|
||||
assert captured_tr_id == ["TTTS3018R"]
|
||||
assert captured_params[0]["OVRS_EXCG_CD"] == "NASD"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_live_mode_connection_error(
|
||||
self, overseas_broker: OverseasBroker
|
||||
) -> None:
|
||||
"""Network error in live mode should raise ConnectionError."""
|
||||
overseas_broker._broker._settings = overseas_broker._broker._settings.model_copy(
|
||||
update={"MODE": "live"}
|
||||
)
|
||||
cm = MagicMock()
|
||||
cm.__aenter__ = AsyncMock(side_effect=aiohttp.ClientError("timeout"))
|
||||
cm.__aexit__ = AsyncMock(return_value=False)
|
||||
|
||||
mock_session = MagicMock()
|
||||
mock_session.get = MagicMock(return_value=cm)
|
||||
_setup_broker_mocks(overseas_broker, mock_session)
|
||||
|
||||
with pytest.raises(ConnectionError, match="Network error fetching pending orders"):
|
||||
await overseas_broker.get_overseas_pending_orders("NASD")
|
||||
|
||||
|
||||
class TestCancelOverseasOrder:
|
||||
"""Tests for cancel_overseas_order method."""
|
||||
|
||||
def _setup_cancel_mocks(
|
||||
self, overseas_broker: OverseasBroker, response: dict
|
||||
) -> tuple[list[str], MagicMock]:
|
||||
"""Wire up mocks for a successful cancel call; return captured TR_IDs and session."""
|
||||
captured_tr_ids: list[str] = []
|
||||
|
||||
async def mock_auth_headers(tr_id: str) -> dict:
|
||||
captured_tr_ids.append(tr_id)
|
||||
return {}
|
||||
|
||||
overseas_broker._broker._auth_headers = mock_auth_headers # type: ignore[method-assign]
|
||||
overseas_broker._broker._get_hash_key = AsyncMock(return_value="hash_val") # type: ignore[method-assign]
|
||||
overseas_broker._broker._rate_limiter.acquire = AsyncMock()
|
||||
|
||||
mock_resp = AsyncMock()
|
||||
mock_resp.status = 200
|
||||
mock_resp.json = AsyncMock(return_value=response)
|
||||
|
||||
mock_session = MagicMock()
|
||||
mock_session.post = MagicMock(return_value=_make_async_cm(mock_resp))
|
||||
overseas_broker._broker._get_session = MagicMock(return_value=mock_session)
|
||||
|
||||
return captured_tr_ids, mock_session
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_us_live_uses_tttt1004u(
|
||||
self, overseas_broker: OverseasBroker
|
||||
) -> None:
|
||||
"""US exchange in live mode should use TTTT1004U."""
|
||||
overseas_broker._broker._settings = overseas_broker._broker._settings.model_copy(
|
||||
update={"MODE": "live"}
|
||||
)
|
||||
captured, _ = self._setup_cancel_mocks(
|
||||
overseas_broker, {"rt_cd": "0", "msg1": "OK"}
|
||||
)
|
||||
|
||||
await overseas_broker.cancel_overseas_order("NASD", "AAPL", "ORD001", 5)
|
||||
|
||||
assert "TTTT1004U" in captured
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_us_paper_uses_vttt1004u(
|
||||
self, overseas_broker: OverseasBroker
|
||||
) -> None:
|
||||
"""US exchange in paper mode should use VTTT1004U."""
|
||||
# Default mock_settings has MODE="paper"
|
||||
captured, _ = self._setup_cancel_mocks(
|
||||
overseas_broker, {"rt_cd": "0", "msg1": "OK"}
|
||||
)
|
||||
|
||||
await overseas_broker.cancel_overseas_order("NASD", "AAPL", "ORD001", 5)
|
||||
|
||||
assert "VTTT1004U" in captured
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_hk_live_uses_ttts1003u(
|
||||
self, overseas_broker: OverseasBroker
|
||||
) -> None:
|
||||
"""SEHK exchange in live mode should use TTTS1003U."""
|
||||
overseas_broker._broker._settings = overseas_broker._broker._settings.model_copy(
|
||||
update={"MODE": "live"}
|
||||
)
|
||||
captured, _ = self._setup_cancel_mocks(
|
||||
overseas_broker, {"rt_cd": "0", "msg1": "OK"}
|
||||
)
|
||||
|
||||
await overseas_broker.cancel_overseas_order("SEHK", "0700", "ORD002", 10)
|
||||
|
||||
assert "TTTS1003U" in captured
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancel_sets_rvse_cncl_dvsn_cd_02(
|
||||
self, overseas_broker: OverseasBroker
|
||||
) -> None:
|
||||
"""Cancel body must include RVSE_CNCL_DVSN_CD='02' and OVRS_ORD_UNPR='0'."""
|
||||
captured_body: list[dict] = []
|
||||
|
||||
async def mock_auth_headers(tr_id: str) -> dict:
|
||||
return {}
|
||||
|
||||
overseas_broker._broker._auth_headers = mock_auth_headers # type: ignore[method-assign]
|
||||
overseas_broker._broker._get_hash_key = AsyncMock(return_value="h") # type: ignore[method-assign]
|
||||
overseas_broker._broker._rate_limiter.acquire = AsyncMock()
|
||||
|
||||
mock_resp = AsyncMock()
|
||||
mock_resp.status = 200
|
||||
mock_resp.json = AsyncMock(return_value={"rt_cd": "0"})
|
||||
|
||||
mock_session = MagicMock()
|
||||
|
||||
def _capture_post(url: str, **kwargs: object) -> MagicMock:
|
||||
captured_body.append(kwargs.get("json", {}))
|
||||
return _make_async_cm(mock_resp)
|
||||
|
||||
mock_session.post = MagicMock(side_effect=_capture_post)
|
||||
overseas_broker._broker._get_session = MagicMock(return_value=mock_session)
|
||||
|
||||
await overseas_broker.cancel_overseas_order("NASD", "AAPL", "ORD003", 3)
|
||||
|
||||
assert captured_body[0]["RVSE_CNCL_DVSN_CD"] == "02"
|
||||
assert captured_body[0]["OVRS_ORD_UNPR"] == "0"
|
||||
assert captured_body[0]["ORGN_ODNO"] == "ORD003"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancel_sets_hashkey_header(
|
||||
self, overseas_broker: OverseasBroker
|
||||
) -> None:
|
||||
"""hashkey must be set in the request headers."""
|
||||
captured_headers: list[dict] = []
|
||||
overseas_broker._broker._get_hash_key = AsyncMock(return_value="test_hash") # type: ignore[method-assign]
|
||||
overseas_broker._broker._rate_limiter.acquire = AsyncMock()
|
||||
|
||||
async def mock_auth_headers(tr_id: str) -> dict:
|
||||
return {"tr_id": tr_id}
|
||||
|
||||
overseas_broker._broker._auth_headers = mock_auth_headers # type: ignore[method-assign]
|
||||
|
||||
mock_resp = AsyncMock()
|
||||
mock_resp.status = 200
|
||||
mock_resp.json = AsyncMock(return_value={"rt_cd": "0"})
|
||||
|
||||
mock_session = MagicMock()
|
||||
|
||||
def _capture_post(url: str, **kwargs: object) -> MagicMock:
|
||||
captured_headers.append(dict(kwargs.get("headers", {})))
|
||||
return _make_async_cm(mock_resp)
|
||||
|
||||
mock_session.post = MagicMock(side_effect=_capture_post)
|
||||
overseas_broker._broker._get_session = MagicMock(return_value=mock_session)
|
||||
|
||||
await overseas_broker.cancel_overseas_order("NASD", "AAPL", "ORD004", 2)
|
||||
|
||||
assert captured_headers[0].get("hashkey") == "test_hash"
|
||||
|
||||
@@ -124,6 +124,10 @@ class TestPromptOptimizer:
|
||||
assert len(prompt) < 300
|
||||
assert "005930" 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):
|
||||
"""Test compressed prompt without instructions."""
|
||||
|
||||
Reference in New Issue
Block a user