Compare commits
1 Commits
feature/is
...
d01f4d93a3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d01f4d93a3 |
@@ -292,33 +292,3 @@ 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
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ from __future__ import annotations
|
|||||||
import asyncio
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
import ssl
|
import ssl
|
||||||
from typing import Any, cast
|
from typing import Any
|
||||||
|
|
||||||
import aiohttp
|
import aiohttp
|
||||||
|
|
||||||
@@ -478,112 +478,6 @@ 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,
|
||||||
|
|||||||
@@ -29,20 +29,6 @@ _RANKING_EXCHANGE_MAP: dict[str, str] = {
|
|||||||
# NASD → NAS, NYSE → NYS, AMEX → AMS (confirmed: AMEX returns empty, AMS returns price).
|
# NASD → NAS, NYSE → NYS, AMEX → AMS (confirmed: AMEX returns empty, AMS returns price).
|
||||||
_PRICE_EXCHANGE_MAP: dict[str, str] = _RANKING_EXCHANGE_MAP
|
_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:
|
class OverseasBroker:
|
||||||
"""KIS Overseas Stock API wrapper that reuses KISBroker infrastructure."""
|
"""KIS Overseas Stock API wrapper that reuses KISBroker infrastructure."""
|
||||||
@@ -306,131 +292,6 @@ class OverseasBroker:
|
|||||||
f"Network error sending overseas order: {exc}"
|
f"Network error sending overseas order: {exc}"
|
||||||
) from 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:
|
def _get_currency_code(self, exchange_code: str) -> str:
|
||||||
"""
|
"""
|
||||||
Map exchange code to currency code.
|
Map exchange code to currency code.
|
||||||
|
|||||||
483
src/main.py
483
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, kr_round_down
|
from src.broker.kis_api import KISBroker
|
||||||
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
|
||||||
@@ -853,39 +853,28 @@ 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=order_price,
|
price=0, # market order
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
# For overseas orders, always use limit orders (지정가):
|
# For overseas orders:
|
||||||
# - KIS market orders (ORD_DVSN=01) calculate quantity based on upper limit
|
# - KIS VTS only accepts limit orders (지정가만 가능)
|
||||||
# price (상한가 기준), resulting in only 60-80% of intended cash being used.
|
# - BUY: use 0.5% premium over last price to improve fill probability
|
||||||
# - BUY: +0.2% above last price — tight enough to minimise overpayment while
|
# (ask price is typically slightly above last, and VTS won't fill below ask)
|
||||||
# achieving >90% fill rate on large-cap US stocks.
|
# - SELL: use last price as the limit
|
||||||
# - 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
|
|
||||||
if decision.action == "BUY":
|
if decision.action == "BUY":
|
||||||
overseas_price = round(current_price * 1.002, 4)
|
order_price = round(current_price * 1.005, 4)
|
||||||
else:
|
else:
|
||||||
overseas_price = round(current_price * 0.998, 4)
|
order_price = current_price
|
||||||
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=overseas_price, # limit order
|
price=order_price, # limit order — KIS VTS rejects market orders
|
||||||
)
|
)
|
||||||
# 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":
|
||||||
@@ -987,328 +976,6 @@ 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(
|
async def run_daily_session(
|
||||||
broker: KISBroker,
|
broker: KISBroker,
|
||||||
overseas_broker: OverseasBroker,
|
overseas_broker: OverseasBroker,
|
||||||
@@ -1323,70 +990,29 @@ async def run_daily_session(
|
|||||||
telegram: TelegramClient,
|
telegram: TelegramClient,
|
||||||
settings: Settings,
|
settings: Settings,
|
||||||
smart_scanner: SmartVolatilityScanner | None = None,
|
smart_scanner: SmartVolatilityScanner | None = None,
|
||||||
daily_start_eval: float = 0.0,
|
) -> None:
|
||||||
) -> float:
|
|
||||||
"""Execute one daily trading session.
|
"""Execute one daily trading session.
|
||||||
|
|
||||||
V2 proactive strategy: 1 Gemini call for playbook generation,
|
V2 proactive strategy: 1 Gemini call for playbook generation,
|
||||||
then local scenario evaluation per stock (0 API calls).
|
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
|
# Get currently open markets
|
||||||
open_markets = get_open_markets(settings.enabled_market_list)
|
open_markets = get_open_markets(settings.enabled_market_list)
|
||||||
|
|
||||||
if not open_markets:
|
if not open_markets:
|
||||||
logger.info("No markets open for this session")
|
logger.info("No markets open for this session")
|
||||||
return daily_start_eval
|
return
|
||||||
|
|
||||||
logger.info("Starting daily trading session for %d markets", len(open_markets))
|
logger.info("Starting daily trading session for %d markets", len(open_markets))
|
||||||
|
|
||||||
# BUY cooldown: prevents retrying stocks rejected for insufficient balance
|
# BUY cooldown: prevents retrying stocks rejected for insufficient balance
|
||||||
daily_buy_cooldown: dict[str, float] = {} # "{market_code}:{stock_code}" -> expiry timestamp
|
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
|
# Process each open market
|
||||||
for market in open_markets:
|
for market in open_markets:
|
||||||
# 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.
|
|
||||||
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)
|
# Dynamic stock discovery via scanner (no static watchlists)
|
||||||
candidates_list: list[ScanCandidate] = []
|
candidates_list: list[ScanCandidate] = []
|
||||||
fallback_stocks: list[str] | None = None
|
fallback_stocks: list[str] | None = None
|
||||||
@@ -1577,27 +1203,12 @@ async def run_daily_session(
|
|||||||
):
|
):
|
||||||
total_cash = settings.PAPER_OVERSEAS_CASH
|
total_cash = settings.PAPER_OVERSEAS_CASH
|
||||||
|
|
||||||
# Capture the day's opening portfolio value on the first market processed
|
# Calculate daily P&L %
|
||||||
# in this session. Used to compute intra-day P&L for the CB instead of
|
pnl_pct = (
|
||||||
# the cumulative purchase_total which spans the entire account history.
|
((total_eval - purchase_total) / purchase_total * 100)
|
||||||
if daily_start_eval <= 0 and total_eval > 0:
|
if purchase_total > 0
|
||||||
daily_start_eval = total_eval
|
else 0.0
|
||||||
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
|
|
||||||
else 0.0
|
|
||||||
)
|
|
||||||
portfolio_data = {
|
portfolio_data = {
|
||||||
"portfolio_pnl_pct": pnl_pct,
|
"portfolio_pnl_pct": pnl_pct,
|
||||||
"total_cash": total_cash,
|
"total_cash": total_cash,
|
||||||
@@ -1776,21 +1387,11 @@ 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=order_price,
|
price=0, # market order
|
||||||
)
|
)
|
||||||
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
|
||||||
@@ -1876,7 +1477,6 @@ async def run_daily_session(
|
|||||||
)
|
)
|
||||||
|
|
||||||
logger.info("Daily trading session completed")
|
logger.info("Daily trading session completed")
|
||||||
return daily_start_eval
|
|
||||||
|
|
||||||
|
|
||||||
async def _handle_market_close(
|
async def _handle_market_close(
|
||||||
@@ -2455,9 +2055,6 @@ async def run(settings: Settings) -> None:
|
|||||||
# BUY cooldown: prevents retrying a stock rejected for insufficient balance
|
# BUY cooldown: prevents retrying a stock rejected for insufficient balance
|
||||||
buy_cooldown: dict[str, float] = {} # "{market_code}:{stock_code}" -> expiry timestamp
|
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
|
# Initialize latency control system
|
||||||
criticality_assessor = CriticalityAssessor(
|
criticality_assessor = CriticalityAssessor(
|
||||||
critical_pnl_threshold=-2.5, # Near circuit breaker at -3.0%
|
critical_pnl_threshold=-2.5, # Near circuit breaker at -3.0%
|
||||||
@@ -2521,26 +2118,13 @@ async def run(settings: Settings) -> None:
|
|||||||
|
|
||||||
session_interval = settings.SESSION_INTERVAL_HOURS * 3600 # Convert to seconds
|
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():
|
while not shutdown.is_set():
|
||||||
# Wait for trading to be unpaused
|
# Wait for trading to be unpaused
|
||||||
await pause_trading.wait()
|
await pause_trading.wait()
|
||||||
_run_context_scheduler(context_scheduler, now=datetime.now(UTC))
|
_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:
|
try:
|
||||||
_cb_daily_start_eval = await run_daily_session(
|
await run_daily_session(
|
||||||
broker,
|
broker,
|
||||||
overseas_broker,
|
overseas_broker,
|
||||||
scenario_engine,
|
scenario_engine,
|
||||||
@@ -2554,7 +2138,6 @@ async def run(settings: Settings) -> None:
|
|||||||
telegram,
|
telegram,
|
||||||
settings,
|
settings,
|
||||||
smart_scanner=smart_scanner,
|
smart_scanner=smart_scanner,
|
||||||
daily_start_eval=_cb_daily_start_eval,
|
|
||||||
)
|
)
|
||||||
except CircuitBreakerTripped:
|
except CircuitBreakerTripped:
|
||||||
logger.critical("Circuit breaker tripped — shutting down")
|
logger.critical("Circuit breaker tripped — shutting down")
|
||||||
@@ -2643,32 +2226,6 @@ 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.
|
|
||||||
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)
|
# Smart Scanner: dynamic stock discovery (no static watchlists)
|
||||||
now_timestamp = asyncio.get_event_loop().time()
|
now_timestamp = asyncio.get_event_loop().time()
|
||||||
last_scan = last_scan_time.get(market.code, 0.0)
|
last_scan = last_scan_time.get(market.code, 0.0)
|
||||||
|
|||||||
@@ -473,48 +473,6 @@ class TelegramClient:
|
|||||||
NotificationMessage(priority=priority, message=message)
|
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(
|
async def notify_error(
|
||||||
self, error_type: str, error_msg: str, context: str
|
self, error_type: str, error_msg: str, context: str
|
||||||
) -> None:
|
) -> None:
|
||||||
|
|||||||
@@ -725,195 +725,3 @@ 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"
|
|
||||||
|
|||||||
@@ -22,9 +22,6 @@ from src.main import (
|
|||||||
_run_context_scheduler,
|
_run_context_scheduler,
|
||||||
_run_evolution_loop,
|
_run_evolution_loop,
|
||||||
_start_dashboard_server,
|
_start_dashboard_server,
|
||||||
handle_domestic_pending_orders,
|
|
||||||
handle_overseas_pending_orders,
|
|
||||||
run_daily_session,
|
|
||||||
safe_float,
|
safe_float,
|
||||||
sync_positions_from_broker,
|
sync_positions_from_broker,
|
||||||
trading_cycle,
|
trading_cycle,
|
||||||
@@ -1107,11 +1104,10 @@ class TestOverseasBalanceParsing:
|
|||||||
mock_telegram: MagicMock,
|
mock_telegram: MagicMock,
|
||||||
mock_overseas_market: MagicMock,
|
mock_overseas_market: MagicMock,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Overseas BUY order must use current_price +0.2% limit, not market order.
|
"""Overseas BUY order must use current_price (limit), not 0 (market).
|
||||||
|
|
||||||
KIS market orders (ORD_DVSN=01) calculate quantity based on upper limit price
|
KIS VTS rejects market orders for overseas paper trading.
|
||||||
(상한가 기준), resulting in only 60-80% of intended cash being used.
|
Regression test for issue #149.
|
||||||
Regression test for issue #149 / #211.
|
|
||||||
"""
|
"""
|
||||||
mock_telegram.notify_trade_execution = AsyncMock()
|
mock_telegram.notify_trade_execution = AsyncMock()
|
||||||
|
|
||||||
@@ -1132,93 +1128,14 @@ class TestOverseasBalanceParsing:
|
|||||||
scan_candidates={},
|
scan_candidates={},
|
||||||
)
|
)
|
||||||
|
|
||||||
# Verify BUY limit order uses +0.2% premium (issue #211)
|
# Verify limit order was sent with actual price + 0.5% premium (issue #151), not 0.0
|
||||||
mock_overseas_broker_with_buy_scenario.send_overseas_order.assert_called_once()
|
mock_overseas_broker_with_buy_scenario.send_overseas_order.assert_called_once()
|
||||||
call_kwargs = mock_overseas_broker_with_buy_scenario.send_overseas_order.call_args
|
call_kwargs = mock_overseas_broker_with_buy_scenario.send_overseas_order.call_args
|
||||||
sent_price = call_kwargs[1].get("price") or call_kwargs[0][4]
|
sent_price = call_kwargs[1].get("price") or call_kwargs[0][4]
|
||||||
expected_price = round(182.5 * 1.002, 4) # 0.2% premium for BUY limit orders
|
expected_price = round(182.5 * 1.005, 4) # 0.5% premium for BUY limit orders
|
||||||
assert sent_price == expected_price, (
|
assert sent_price == expected_price, (
|
||||||
f"Expected limit price {expected_price} (182.5 * 1.002) but got {sent_price}. "
|
f"Expected limit price {expected_price} (182.5 * 1.005) but got {sent_price}. "
|
||||||
"BUY uses +0.2% to improve fill rate while minimising overpayment (#211)."
|
"KIS VTS only accepts limit orders; BUY uses 0.5% premium to improve fill rate."
|
||||||
)
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_overseas_sell_order_uses_limit_price_below_current(
|
|
||||||
self,
|
|
||||||
mock_domestic_broker: MagicMock,
|
|
||||||
mock_playbook: DayPlaybook,
|
|
||||||
mock_risk: MagicMock,
|
|
||||||
mock_db: MagicMock,
|
|
||||||
mock_decision_logger: MagicMock,
|
|
||||||
mock_context_store: MagicMock,
|
|
||||||
mock_criticality_assessor: MagicMock,
|
|
||||||
mock_telegram: MagicMock,
|
|
||||||
mock_overseas_market: MagicMock,
|
|
||||||
) -> None:
|
|
||||||
"""Overseas SELL order must use current_price -0.2% limit (#211).
|
|
||||||
|
|
||||||
Placing SELL at exact last price risks no-fill when the bid is just below.
|
|
||||||
Using -0.2% ensures the order fills even if the price dips slightly.
|
|
||||||
"""
|
|
||||||
sell_price = 182.5
|
|
||||||
|
|
||||||
# Broker mock: returns price data and a balance with 5 AAPL shares held.
|
|
||||||
overseas_broker = MagicMock()
|
|
||||||
overseas_broker.get_overseas_price = AsyncMock(
|
|
||||||
return_value={"output": {"last": str(sell_price), "rate": "1.5", "tvol": "5000000"}}
|
|
||||||
)
|
|
||||||
overseas_broker.get_overseas_balance = AsyncMock(
|
|
||||||
return_value={
|
|
||||||
"output1": [
|
|
||||||
{
|
|
||||||
"ovrs_pdno": "AAPL",
|
|
||||||
"ovrs_cblc_qty": "5",
|
|
||||||
"pchs_avg_pric": "170.0",
|
|
||||||
"evlu_pfls_rt": "7.35",
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"output2": [
|
|
||||||
{
|
|
||||||
"frcr_evlu_tota": "100000.00",
|
|
||||||
"frcr_dncl_amt_2": "50000.00",
|
|
||||||
"frcr_buy_amt_smtl": "50000.00",
|
|
||||||
}
|
|
||||||
],
|
|
||||||
}
|
|
||||||
)
|
|
||||||
overseas_broker.send_overseas_order = AsyncMock(
|
|
||||||
return_value={"rt_cd": "0", "msg1": "OK"}
|
|
||||||
)
|
|
||||||
|
|
||||||
sell_engine = MagicMock(spec=ScenarioEngine)
|
|
||||||
sell_engine.evaluate = MagicMock(return_value=_make_sell_match("AAPL"))
|
|
||||||
mock_telegram.notify_trade_execution = AsyncMock()
|
|
||||||
|
|
||||||
with patch("src.main.log_trade"), patch("src.main.get_open_position") as mock_pos:
|
|
||||||
mock_pos.return_value = {"quantity": 5, "stock_code": "AAPL", "price": 170.0}
|
|
||||||
await trading_cycle(
|
|
||||||
broker=mock_domestic_broker,
|
|
||||||
overseas_broker=overseas_broker,
|
|
||||||
scenario_engine=sell_engine,
|
|
||||||
playbook=mock_playbook,
|
|
||||||
risk=mock_risk,
|
|
||||||
db_conn=mock_db,
|
|
||||||
decision_logger=mock_decision_logger,
|
|
||||||
context_store=mock_context_store,
|
|
||||||
criticality_assessor=mock_criticality_assessor,
|
|
||||||
telegram=mock_telegram,
|
|
||||||
market=mock_overseas_market,
|
|
||||||
stock_code="AAPL",
|
|
||||||
scan_candidates={},
|
|
||||||
)
|
|
||||||
|
|
||||||
overseas_broker.send_overseas_order.assert_called_once()
|
|
||||||
call_kwargs = overseas_broker.send_overseas_order.call_args
|
|
||||||
sent_price = call_kwargs[1].get("price") or call_kwargs[0][4]
|
|
||||||
expected_price = round(sell_price * 0.998, 4) # -0.2% for SELL limit orders
|
|
||||||
assert sent_price == expected_price, (
|
|
||||||
f"Expected SELL limit price {expected_price} (182.5 * 0.998) but got {sent_price}. "
|
|
||||||
"SELL uses -0.2% to ensure fill even when price dips slightly (#211)."
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -3357,245 +3274,6 @@ class TestRetryConnection:
|
|||||||
assert call_count == 1 # No retry for non-ConnectionError
|
assert call_count == 1 # No retry for non-ConnectionError
|
||||||
|
|
||||||
|
|
||||||
# run_daily_session — daily CB baseline (daily_start_eval) tests (issue #207)
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
class TestDailyCBBaseline:
|
|
||||||
"""Tests for run_daily_session's daily_start_eval (CB baseline) behaviour.
|
|
||||||
|
|
||||||
Issue #207: CB P&L should be computed relative to the portfolio value at
|
|
||||||
the start of each trading day, not the cumulative purchase_total.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def _make_settings(self) -> Settings:
|
|
||||||
return Settings(
|
|
||||||
KIS_APP_KEY="test-key",
|
|
||||||
KIS_APP_SECRET="test-secret",
|
|
||||||
KIS_ACCOUNT_NO="12345678-01",
|
|
||||||
GEMINI_API_KEY="test-gemini",
|
|
||||||
MODE="paper",
|
|
||||||
PAPER_OVERSEAS_CASH=0,
|
|
||||||
)
|
|
||||||
|
|
||||||
def _make_domestic_balance(
|
|
||||||
self, tot_evlu_amt: float = 0.0, dnca_tot_amt: float = 50000.0
|
|
||||||
) -> dict:
|
|
||||||
return {
|
|
||||||
"output1": [],
|
|
||||||
"output2": [
|
|
||||||
{
|
|
||||||
"tot_evlu_amt": str(tot_evlu_amt),
|
|
||||||
"dnca_tot_amt": str(dnca_tot_amt),
|
|
||||||
"pchs_amt_smtl_amt": "40000.0",
|
|
||||||
}
|
|
||||||
],
|
|
||||||
}
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_returns_daily_start_eval_when_no_markets_open(self) -> None:
|
|
||||||
"""run_daily_session returns the unchanged daily_start_eval when no markets are open."""
|
|
||||||
with patch("src.main.get_open_markets", return_value=[]):
|
|
||||||
result = await run_daily_session(
|
|
||||||
broker=MagicMock(),
|
|
||||||
overseas_broker=MagicMock(),
|
|
||||||
scenario_engine=MagicMock(),
|
|
||||||
playbook_store=MagicMock(),
|
|
||||||
pre_market_planner=MagicMock(),
|
|
||||||
risk=MagicMock(),
|
|
||||||
db_conn=init_db(":memory:"),
|
|
||||||
decision_logger=MagicMock(),
|
|
||||||
context_store=MagicMock(),
|
|
||||||
criticality_assessor=MagicMock(),
|
|
||||||
telegram=MagicMock(),
|
|
||||||
settings=self._make_settings(),
|
|
||||||
smart_scanner=None,
|
|
||||||
daily_start_eval=12345.0,
|
|
||||||
)
|
|
||||||
assert result == 12345.0
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_returns_zero_when_no_markets_and_no_baseline(self) -> None:
|
|
||||||
"""run_daily_session returns 0.0 when no markets are open and daily_start_eval=0."""
|
|
||||||
with patch("src.main.get_open_markets", return_value=[]):
|
|
||||||
result = await run_daily_session(
|
|
||||||
broker=MagicMock(),
|
|
||||||
overseas_broker=MagicMock(),
|
|
||||||
scenario_engine=MagicMock(),
|
|
||||||
playbook_store=MagicMock(),
|
|
||||||
pre_market_planner=MagicMock(),
|
|
||||||
risk=MagicMock(),
|
|
||||||
db_conn=init_db(":memory:"),
|
|
||||||
decision_logger=MagicMock(),
|
|
||||||
context_store=MagicMock(),
|
|
||||||
criticality_assessor=MagicMock(),
|
|
||||||
telegram=MagicMock(),
|
|
||||||
settings=self._make_settings(),
|
|
||||||
smart_scanner=None,
|
|
||||||
daily_start_eval=0.0,
|
|
||||||
)
|
|
||||||
assert result == 0.0
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_captures_total_eval_as_baseline_on_first_session(self) -> None:
|
|
||||||
"""When daily_start_eval=0 and balance returns a positive total_eval, the returned
|
|
||||||
value equals total_eval (the captured baseline for the day)."""
|
|
||||||
from src.analysis.smart_scanner import ScanCandidate
|
|
||||||
|
|
||||||
settings = self._make_settings()
|
|
||||||
broker = MagicMock()
|
|
||||||
# Domestic balance: tot_evlu_amt=55000
|
|
||||||
broker.get_balance = AsyncMock(
|
|
||||||
return_value=self._make_domestic_balance(tot_evlu_amt=55000.0)
|
|
||||||
)
|
|
||||||
# Price data for the stock
|
|
||||||
broker.get_current_price = AsyncMock(
|
|
||||||
return_value=(100.0, 1.5, 100.0)
|
|
||||||
)
|
|
||||||
|
|
||||||
market = MagicMock()
|
|
||||||
market.name = "KR"
|
|
||||||
market.code = "KR"
|
|
||||||
market.exchange_code = "KRX"
|
|
||||||
market.is_domestic = True
|
|
||||||
market.timezone = __import__("zoneinfo").ZoneInfo("Asia/Seoul")
|
|
||||||
|
|
||||||
smart_scanner = MagicMock()
|
|
||||||
smart_scanner.scan = AsyncMock(
|
|
||||||
return_value=[
|
|
||||||
ScanCandidate(
|
|
||||||
stock_code="005930",
|
|
||||||
name="Samsung",
|
|
||||||
price=100.0,
|
|
||||||
volume=1_000_000.0,
|
|
||||||
volume_ratio=2.5,
|
|
||||||
rsi=45.0,
|
|
||||||
signal="momentum",
|
|
||||||
score=80.0,
|
|
||||||
)
|
|
||||||
]
|
|
||||||
)
|
|
||||||
|
|
||||||
playbook_store = MagicMock()
|
|
||||||
playbook_store.load = MagicMock(return_value=_make_playbook("KR"))
|
|
||||||
|
|
||||||
scenario_engine = MagicMock(spec=ScenarioEngine)
|
|
||||||
scenario_engine.evaluate = MagicMock(return_value=_make_hold_match("005930"))
|
|
||||||
|
|
||||||
risk = MagicMock()
|
|
||||||
risk.check_circuit_breaker = MagicMock()
|
|
||||||
risk.check_fat_finger = MagicMock()
|
|
||||||
|
|
||||||
telegram = MagicMock()
|
|
||||||
telegram.notify_trade_execution = AsyncMock()
|
|
||||||
telegram.notify_scenario_matched = AsyncMock()
|
|
||||||
|
|
||||||
decision_logger = MagicMock()
|
|
||||||
decision_logger.log_decision = MagicMock(return_value="d1")
|
|
||||||
|
|
||||||
async def _passthrough(fn, *a, label: str = "", **kw): # type: ignore[override]
|
|
||||||
return await fn(*a, **kw)
|
|
||||||
|
|
||||||
with patch("src.main.get_open_markets", return_value=[market]), \
|
|
||||||
patch("src.main._retry_connection", new=_passthrough):
|
|
||||||
result = await run_daily_session(
|
|
||||||
broker=broker,
|
|
||||||
overseas_broker=MagicMock(),
|
|
||||||
scenario_engine=scenario_engine,
|
|
||||||
playbook_store=playbook_store,
|
|
||||||
pre_market_planner=MagicMock(),
|
|
||||||
risk=risk,
|
|
||||||
db_conn=init_db(":memory:"),
|
|
||||||
decision_logger=decision_logger,
|
|
||||||
context_store=MagicMock(),
|
|
||||||
criticality_assessor=MagicMock(),
|
|
||||||
telegram=telegram,
|
|
||||||
settings=settings,
|
|
||||||
smart_scanner=smart_scanner,
|
|
||||||
daily_start_eval=0.0,
|
|
||||||
)
|
|
||||||
|
|
||||||
assert result == 55000.0 # captured from tot_evlu_amt
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_does_not_overwrite_existing_baseline(self) -> None:
|
|
||||||
"""When daily_start_eval > 0, it must not be overwritten even if balance returns
|
|
||||||
a different value (baseline is fixed at the start of each trading day)."""
|
|
||||||
from src.analysis.smart_scanner import ScanCandidate
|
|
||||||
|
|
||||||
settings = self._make_settings()
|
|
||||||
broker = MagicMock()
|
|
||||||
# Balance reports a different eval value (market moved during the day)
|
|
||||||
broker.get_balance = AsyncMock(
|
|
||||||
return_value=self._make_domestic_balance(tot_evlu_amt=58000.0)
|
|
||||||
)
|
|
||||||
broker.get_current_price = AsyncMock(return_value=(100.0, 1.5, 100.0))
|
|
||||||
|
|
||||||
market = MagicMock()
|
|
||||||
market.name = "KR"
|
|
||||||
market.code = "KR"
|
|
||||||
market.exchange_code = "KRX"
|
|
||||||
market.is_domestic = True
|
|
||||||
market.timezone = __import__("zoneinfo").ZoneInfo("Asia/Seoul")
|
|
||||||
|
|
||||||
smart_scanner = MagicMock()
|
|
||||||
smart_scanner.scan = AsyncMock(
|
|
||||||
return_value=[
|
|
||||||
ScanCandidate(
|
|
||||||
stock_code="005930",
|
|
||||||
name="Samsung",
|
|
||||||
price=100.0,
|
|
||||||
volume=1_000_000.0,
|
|
||||||
volume_ratio=2.5,
|
|
||||||
rsi=45.0,
|
|
||||||
signal="momentum",
|
|
||||||
score=80.0,
|
|
||||||
)
|
|
||||||
]
|
|
||||||
)
|
|
||||||
|
|
||||||
playbook_store = MagicMock()
|
|
||||||
playbook_store.load = MagicMock(return_value=_make_playbook("KR"))
|
|
||||||
|
|
||||||
scenario_engine = MagicMock(spec=ScenarioEngine)
|
|
||||||
scenario_engine.evaluate = MagicMock(return_value=_make_hold_match("005930"))
|
|
||||||
|
|
||||||
risk = MagicMock()
|
|
||||||
risk.check_circuit_breaker = MagicMock()
|
|
||||||
|
|
||||||
telegram = MagicMock()
|
|
||||||
telegram.notify_trade_execution = AsyncMock()
|
|
||||||
telegram.notify_scenario_matched = AsyncMock()
|
|
||||||
|
|
||||||
decision_logger = MagicMock()
|
|
||||||
decision_logger.log_decision = MagicMock(return_value="d1")
|
|
||||||
|
|
||||||
async def _passthrough(fn, *a, label: str = "", **kw): # type: ignore[override]
|
|
||||||
return await fn(*a, **kw)
|
|
||||||
|
|
||||||
with patch("src.main.get_open_markets", return_value=[market]), \
|
|
||||||
patch("src.main._retry_connection", new=_passthrough):
|
|
||||||
result = await run_daily_session(
|
|
||||||
broker=broker,
|
|
||||||
overseas_broker=MagicMock(),
|
|
||||||
scenario_engine=scenario_engine,
|
|
||||||
playbook_store=playbook_store,
|
|
||||||
pre_market_planner=MagicMock(),
|
|
||||||
risk=risk,
|
|
||||||
db_conn=init_db(":memory:"),
|
|
||||||
decision_logger=decision_logger,
|
|
||||||
context_store=MagicMock(),
|
|
||||||
criticality_assessor=MagicMock(),
|
|
||||||
telegram=telegram,
|
|
||||||
settings=settings,
|
|
||||||
smart_scanner=smart_scanner,
|
|
||||||
daily_start_eval=55000.0, # existing baseline
|
|
||||||
)
|
|
||||||
|
|
||||||
# Must return the original baseline, NOT the new total_eval (58000)
|
|
||||||
assert result == 55000.0
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# sync_positions_from_broker — startup DB sync tests (issue #206)
|
# sync_positions_from_broker — startup DB sync tests (issue #206)
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -3874,507 +3552,3 @@ class TestDomesticBuyDoublePreventionTradingCycle:
|
|||||||
|
|
||||||
# BUY must NOT have been executed because broker still holds the stock
|
# BUY must NOT have been executed because broker still holds the stock
|
||||||
broker.send_order.assert_not_called()
|
broker.send_order.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
class TestHandleOverseasPendingOrders:
|
|
||||||
"""Tests for handle_overseas_pending_orders function."""
|
|
||||||
|
|
||||||
def _make_settings(self, markets: str = "US_NASDAQ,US_NYSE,US_AMEX") -> Settings:
|
|
||||||
return Settings(
|
|
||||||
KIS_APP_KEY="k",
|
|
||||||
KIS_APP_SECRET="s",
|
|
||||||
KIS_ACCOUNT_NO="12345678-01",
|
|
||||||
GEMINI_API_KEY="g",
|
|
||||||
ENABLED_MARKETS=markets,
|
|
||||||
)
|
|
||||||
|
|
||||||
def _make_telegram(self) -> MagicMock:
|
|
||||||
t = MagicMock()
|
|
||||||
t.notify_unfilled_order = AsyncMock()
|
|
||||||
return t
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_buy_pending_is_cancelled_and_cooldown_set(self) -> None:
|
|
||||||
"""BUY pending order should be cancelled and buy_cooldown should be set."""
|
|
||||||
settings = self._make_settings("US_NASDAQ")
|
|
||||||
telegram = self._make_telegram()
|
|
||||||
|
|
||||||
pending_order = {
|
|
||||||
"pdno": "AAPL",
|
|
||||||
"odno": "ORD001",
|
|
||||||
"sll_buy_dvsn_cd": "02", # BUY
|
|
||||||
"nccs_qty": "3",
|
|
||||||
"ovrs_excg_cd": "NASD",
|
|
||||||
}
|
|
||||||
overseas_broker = MagicMock()
|
|
||||||
overseas_broker.get_overseas_pending_orders = AsyncMock(
|
|
||||||
return_value=[pending_order]
|
|
||||||
)
|
|
||||||
overseas_broker.cancel_overseas_order = AsyncMock(
|
|
||||||
return_value={"rt_cd": "0", "msg1": "OK"}
|
|
||||||
)
|
|
||||||
|
|
||||||
sell_resubmit_counts: dict[str, int] = {}
|
|
||||||
buy_cooldown: dict[str, float] = {}
|
|
||||||
|
|
||||||
await handle_overseas_pending_orders(
|
|
||||||
overseas_broker, telegram, settings, sell_resubmit_counts, buy_cooldown
|
|
||||||
)
|
|
||||||
|
|
||||||
overseas_broker.cancel_overseas_order.assert_called_once_with(
|
|
||||||
exchange_code="NASD",
|
|
||||||
stock_code="AAPL",
|
|
||||||
odno="ORD001",
|
|
||||||
qty=3,
|
|
||||||
)
|
|
||||||
assert "NASD:AAPL" in buy_cooldown
|
|
||||||
telegram.notify_unfilled_order.assert_called_once()
|
|
||||||
call_kwargs = telegram.notify_unfilled_order.call_args[1]
|
|
||||||
assert call_kwargs["action"] == "BUY"
|
|
||||||
assert call_kwargs["outcome"] == "cancelled"
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_sell_pending_is_cancelled_then_resubmitted(self) -> None:
|
|
||||||
"""First unfilled SELL should be cancelled then resubmitted at -0.4% price."""
|
|
||||||
settings = self._make_settings("US_NASDAQ")
|
|
||||||
telegram = self._make_telegram()
|
|
||||||
|
|
||||||
pending_order = {
|
|
||||||
"pdno": "AAPL",
|
|
||||||
"odno": "ORD002",
|
|
||||||
"sll_buy_dvsn_cd": "01", # SELL
|
|
||||||
"nccs_qty": "5",
|
|
||||||
"ovrs_excg_cd": "NASD",
|
|
||||||
}
|
|
||||||
overseas_broker = MagicMock()
|
|
||||||
overseas_broker.get_overseas_pending_orders = AsyncMock(
|
|
||||||
return_value=[pending_order]
|
|
||||||
)
|
|
||||||
overseas_broker.cancel_overseas_order = AsyncMock(
|
|
||||||
return_value={"rt_cd": "0", "msg1": "OK"}
|
|
||||||
)
|
|
||||||
overseas_broker.get_overseas_price = AsyncMock(
|
|
||||||
return_value={"output": {"last": "200.0"}}
|
|
||||||
)
|
|
||||||
overseas_broker.send_overseas_order = AsyncMock(
|
|
||||||
return_value={"rt_cd": "0", "msg1": "OK"}
|
|
||||||
)
|
|
||||||
|
|
||||||
sell_resubmit_counts: dict[str, int] = {}
|
|
||||||
|
|
||||||
await handle_overseas_pending_orders(
|
|
||||||
overseas_broker, telegram, settings, sell_resubmit_counts
|
|
||||||
)
|
|
||||||
|
|
||||||
overseas_broker.cancel_overseas_order.assert_called_once()
|
|
||||||
overseas_broker.send_overseas_order.assert_called_once()
|
|
||||||
resubmit_kwargs = overseas_broker.send_overseas_order.call_args[1]
|
|
||||||
assert resubmit_kwargs["order_type"] == "SELL"
|
|
||||||
assert resubmit_kwargs["price"] == round(200.0 * 0.996, 4)
|
|
||||||
assert sell_resubmit_counts.get("NASD:AAPL") == 1
|
|
||||||
notify_kwargs = telegram.notify_unfilled_order.call_args[1]
|
|
||||||
assert notify_kwargs["outcome"] == "resubmitted"
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_sell_cancel_failure_skips_resubmit(self) -> None:
|
|
||||||
"""When cancel returns rt_cd != '0', resubmit should NOT be attempted."""
|
|
||||||
settings = self._make_settings("US_NASDAQ")
|
|
||||||
telegram = self._make_telegram()
|
|
||||||
|
|
||||||
pending_order = {
|
|
||||||
"pdno": "AAPL",
|
|
||||||
"odno": "ORD003",
|
|
||||||
"sll_buy_dvsn_cd": "01", # SELL
|
|
||||||
"nccs_qty": "2",
|
|
||||||
"ovrs_excg_cd": "NASD",
|
|
||||||
}
|
|
||||||
overseas_broker = MagicMock()
|
|
||||||
overseas_broker.get_overseas_pending_orders = AsyncMock(
|
|
||||||
return_value=[pending_order]
|
|
||||||
)
|
|
||||||
overseas_broker.cancel_overseas_order = AsyncMock(
|
|
||||||
return_value={"rt_cd": "1", "msg1": "Error"} # failure
|
|
||||||
)
|
|
||||||
overseas_broker.send_overseas_order = AsyncMock()
|
|
||||||
|
|
||||||
sell_resubmit_counts: dict[str, int] = {}
|
|
||||||
|
|
||||||
await handle_overseas_pending_orders(
|
|
||||||
overseas_broker, telegram, settings, sell_resubmit_counts
|
|
||||||
)
|
|
||||||
|
|
||||||
overseas_broker.send_overseas_order.assert_not_called()
|
|
||||||
telegram.notify_unfilled_order.assert_not_called()
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_sell_already_resubmitted_is_only_cancelled(self) -> None:
|
|
||||||
"""Second unfilled SELL (sell_resubmit_counts >= 1) should only cancel, no resubmit."""
|
|
||||||
settings = self._make_settings("US_NASDAQ")
|
|
||||||
telegram = self._make_telegram()
|
|
||||||
|
|
||||||
pending_order = {
|
|
||||||
"pdno": "AAPL",
|
|
||||||
"odno": "ORD004",
|
|
||||||
"sll_buy_dvsn_cd": "01", # SELL
|
|
||||||
"nccs_qty": "4",
|
|
||||||
"ovrs_excg_cd": "NASD",
|
|
||||||
}
|
|
||||||
overseas_broker = MagicMock()
|
|
||||||
overseas_broker.get_overseas_pending_orders = AsyncMock(
|
|
||||||
return_value=[pending_order]
|
|
||||||
)
|
|
||||||
overseas_broker.cancel_overseas_order = AsyncMock(
|
|
||||||
return_value={"rt_cd": "0", "msg1": "OK"}
|
|
||||||
)
|
|
||||||
overseas_broker.send_overseas_order = AsyncMock()
|
|
||||||
|
|
||||||
# Already resubmitted once
|
|
||||||
sell_resubmit_counts: dict[str, int] = {"NASD:AAPL": 1}
|
|
||||||
|
|
||||||
await handle_overseas_pending_orders(
|
|
||||||
overseas_broker, telegram, settings, sell_resubmit_counts
|
|
||||||
)
|
|
||||||
|
|
||||||
overseas_broker.cancel_overseas_order.assert_called_once()
|
|
||||||
overseas_broker.send_overseas_order.assert_not_called()
|
|
||||||
notify_kwargs = telegram.notify_unfilled_order.call_args[1]
|
|
||||||
assert notify_kwargs["outcome"] == "cancelled"
|
|
||||||
assert notify_kwargs["action"] == "SELL"
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_us_exchanges_deduplicated_to_nasd(self) -> None:
|
|
||||||
"""US_NASDAQ, US_NYSE, US_AMEX should result in only one NASD query."""
|
|
||||||
settings = self._make_settings("US_NASDAQ,US_NYSE,US_AMEX")
|
|
||||||
telegram = self._make_telegram()
|
|
||||||
|
|
||||||
overseas_broker = MagicMock()
|
|
||||||
overseas_broker.get_overseas_pending_orders = AsyncMock(return_value=[])
|
|
||||||
|
|
||||||
sell_resubmit_counts: dict[str, int] = {}
|
|
||||||
|
|
||||||
await handle_overseas_pending_orders(
|
|
||||||
overseas_broker, telegram, settings, sell_resubmit_counts
|
|
||||||
)
|
|
||||||
|
|
||||||
# Should be called exactly once with "NASD"
|
|
||||||
assert overseas_broker.get_overseas_pending_orders.call_count == 1
|
|
||||||
overseas_broker.get_overseas_pending_orders.assert_called_once_with("NASD")
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Domestic Pending Order Handling
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
class TestHandleDomesticPendingOrders:
|
|
||||||
"""Tests for handle_domestic_pending_orders function."""
|
|
||||||
|
|
||||||
def _make_settings(self) -> Settings:
|
|
||||||
return Settings(
|
|
||||||
KIS_APP_KEY="k",
|
|
||||||
KIS_APP_SECRET="s",
|
|
||||||
KIS_ACCOUNT_NO="12345678-01",
|
|
||||||
GEMINI_API_KEY="g",
|
|
||||||
ENABLED_MARKETS="KR",
|
|
||||||
)
|
|
||||||
|
|
||||||
def _make_telegram(self) -> MagicMock:
|
|
||||||
t = MagicMock()
|
|
||||||
t.notify_unfilled_order = AsyncMock()
|
|
||||||
return t
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_buy_pending_is_cancelled_and_cooldown_set(self) -> None:
|
|
||||||
"""BUY pending order should be cancelled and buy_cooldown should be set."""
|
|
||||||
settings = self._make_settings()
|
|
||||||
telegram = self._make_telegram()
|
|
||||||
|
|
||||||
pending_order = {
|
|
||||||
"pdno": "005930",
|
|
||||||
"orgn_odno": "ORD001",
|
|
||||||
"ord_gno_brno": "BRN01",
|
|
||||||
"sll_buy_dvsn_cd": "02", # BUY
|
|
||||||
"psbl_qty": "3",
|
|
||||||
}
|
|
||||||
broker = MagicMock()
|
|
||||||
broker.get_domestic_pending_orders = AsyncMock(return_value=[pending_order])
|
|
||||||
broker.cancel_domestic_order = AsyncMock(
|
|
||||||
return_value={"rt_cd": "0", "msg1": "OK"}
|
|
||||||
)
|
|
||||||
|
|
||||||
sell_resubmit_counts: dict[str, int] = {}
|
|
||||||
buy_cooldown: dict[str, float] = {}
|
|
||||||
|
|
||||||
await handle_domestic_pending_orders(
|
|
||||||
broker, telegram, settings, sell_resubmit_counts, buy_cooldown
|
|
||||||
)
|
|
||||||
|
|
||||||
broker.cancel_domestic_order.assert_called_once_with(
|
|
||||||
stock_code="005930",
|
|
||||||
orgn_odno="ORD001",
|
|
||||||
krx_fwdg_ord_orgno="BRN01",
|
|
||||||
qty=3,
|
|
||||||
)
|
|
||||||
assert "KR:005930" in buy_cooldown
|
|
||||||
telegram.notify_unfilled_order.assert_called_once()
|
|
||||||
call_kwargs = telegram.notify_unfilled_order.call_args[1]
|
|
||||||
assert call_kwargs["action"] == "BUY"
|
|
||||||
assert call_kwargs["outcome"] == "cancelled"
|
|
||||||
assert call_kwargs["market"] == "KR"
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_sell_pending_is_cancelled_then_resubmitted(self) -> None:
|
|
||||||
"""First unfilled SELL should be cancelled then resubmitted at -0.4% price."""
|
|
||||||
from src.broker.kis_api import kr_round_down
|
|
||||||
|
|
||||||
settings = self._make_settings()
|
|
||||||
telegram = self._make_telegram()
|
|
||||||
|
|
||||||
pending_order = {
|
|
||||||
"pdno": "005930",
|
|
||||||
"orgn_odno": "ORD002",
|
|
||||||
"ord_gno_brno": "BRN02",
|
|
||||||
"sll_buy_dvsn_cd": "01", # SELL
|
|
||||||
"psbl_qty": "5",
|
|
||||||
}
|
|
||||||
broker = MagicMock()
|
|
||||||
broker.get_domestic_pending_orders = AsyncMock(return_value=[pending_order])
|
|
||||||
broker.cancel_domestic_order = AsyncMock(
|
|
||||||
return_value={"rt_cd": "0", "msg1": "OK"}
|
|
||||||
)
|
|
||||||
broker.get_current_price = AsyncMock(return_value=(50000.0, 0.0, 0.0))
|
|
||||||
broker.send_order = AsyncMock(return_value={"rt_cd": "0"})
|
|
||||||
|
|
||||||
sell_resubmit_counts: dict[str, int] = {}
|
|
||||||
|
|
||||||
await handle_domestic_pending_orders(
|
|
||||||
broker, telegram, settings, sell_resubmit_counts
|
|
||||||
)
|
|
||||||
|
|
||||||
broker.cancel_domestic_order.assert_called_once()
|
|
||||||
broker.send_order.assert_called_once()
|
|
||||||
resubmit_kwargs = broker.send_order.call_args[1]
|
|
||||||
assert resubmit_kwargs["order_type"] == "SELL"
|
|
||||||
expected_price = kr_round_down(50000.0 * 0.996)
|
|
||||||
assert resubmit_kwargs["price"] == expected_price
|
|
||||||
assert sell_resubmit_counts.get("KR:005930") == 1
|
|
||||||
notify_kwargs = telegram.notify_unfilled_order.call_args[1]
|
|
||||||
assert notify_kwargs["outcome"] == "resubmitted"
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_sell_cancel_failure_skips_resubmit(self) -> None:
|
|
||||||
"""When cancel returns rt_cd != '0', resubmit should NOT be attempted."""
|
|
||||||
settings = self._make_settings()
|
|
||||||
telegram = self._make_telegram()
|
|
||||||
|
|
||||||
pending_order = {
|
|
||||||
"pdno": "005930",
|
|
||||||
"orgn_odno": "ORD003",
|
|
||||||
"ord_gno_brno": "BRN03",
|
|
||||||
"sll_buy_dvsn_cd": "01", # SELL
|
|
||||||
"psbl_qty": "2",
|
|
||||||
}
|
|
||||||
broker = MagicMock()
|
|
||||||
broker.get_domestic_pending_orders = AsyncMock(return_value=[pending_order])
|
|
||||||
broker.cancel_domestic_order = AsyncMock(
|
|
||||||
return_value={"rt_cd": "1", "msg1": "Error"} # failure
|
|
||||||
)
|
|
||||||
broker.send_order = AsyncMock()
|
|
||||||
|
|
||||||
sell_resubmit_counts: dict[str, int] = {}
|
|
||||||
|
|
||||||
await handle_domestic_pending_orders(
|
|
||||||
broker, telegram, settings, sell_resubmit_counts
|
|
||||||
)
|
|
||||||
|
|
||||||
broker.send_order.assert_not_called()
|
|
||||||
telegram.notify_unfilled_order.assert_not_called()
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_sell_already_resubmitted_is_only_cancelled(self) -> None:
|
|
||||||
"""Second unfilled SELL (sell_resubmit_counts >= 1) should only cancel, no resubmit."""
|
|
||||||
settings = self._make_settings()
|
|
||||||
telegram = self._make_telegram()
|
|
||||||
|
|
||||||
pending_order = {
|
|
||||||
"pdno": "005930",
|
|
||||||
"orgn_odno": "ORD004",
|
|
||||||
"ord_gno_brno": "BRN04",
|
|
||||||
"sll_buy_dvsn_cd": "01", # SELL
|
|
||||||
"psbl_qty": "4",
|
|
||||||
}
|
|
||||||
broker = MagicMock()
|
|
||||||
broker.get_domestic_pending_orders = AsyncMock(return_value=[pending_order])
|
|
||||||
broker.cancel_domestic_order = AsyncMock(
|
|
||||||
return_value={"rt_cd": "0", "msg1": "OK"}
|
|
||||||
)
|
|
||||||
broker.send_order = AsyncMock()
|
|
||||||
|
|
||||||
# Already resubmitted once
|
|
||||||
sell_resubmit_counts: dict[str, int] = {"KR:005930": 1}
|
|
||||||
|
|
||||||
await handle_domestic_pending_orders(
|
|
||||||
broker, telegram, settings, sell_resubmit_counts
|
|
||||||
)
|
|
||||||
|
|
||||||
broker.cancel_domestic_order.assert_called_once()
|
|
||||||
broker.send_order.assert_not_called()
|
|
||||||
notify_kwargs = telegram.notify_unfilled_order.call_args[1]
|
|
||||||
assert notify_kwargs["outcome"] == "cancelled"
|
|
||||||
assert notify_kwargs["action"] == "SELL"
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Domestic Limit Order Price in trading_cycle
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
class TestDomesticLimitOrderPrice:
|
|
||||||
"""trading_cycle must use kr_round_down limit prices for domestic orders."""
|
|
||||||
|
|
||||||
def _make_market(self) -> MagicMock:
|
|
||||||
market = MagicMock()
|
|
||||||
market.name = "Korea"
|
|
||||||
market.code = "KR"
|
|
||||||
market.exchange_code = "KRX"
|
|
||||||
market.is_domestic = True
|
|
||||||
return market
|
|
||||||
|
|
||||||
def _make_broker(self, current_price: float, balance_data: dict) -> MagicMock:
|
|
||||||
broker = MagicMock()
|
|
||||||
broker.get_current_price = AsyncMock(return_value=(current_price, 0.0, 0.0))
|
|
||||||
broker.get_balance = AsyncMock(return_value=balance_data)
|
|
||||||
broker.send_order = AsyncMock(return_value={"rt_cd": "0", "msg1": "OK"})
|
|
||||||
return broker
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_trading_cycle_domestic_buy_uses_limit_price(self) -> None:
|
|
||||||
"""BUY order for domestic stock must use kr_round_down(price * 1.002)."""
|
|
||||||
from src.broker.kis_api import kr_round_down
|
|
||||||
from src.strategy.models import ScenarioAction
|
|
||||||
|
|
||||||
current_price = 70000.0
|
|
||||||
balance_data = {
|
|
||||||
"output2": [
|
|
||||||
{
|
|
||||||
"tot_evlu_amt": "10000000",
|
|
||||||
"dnca_tot_amt": "5000000",
|
|
||||||
"pchs_amt_smtl_amt": "5000000",
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
broker = self._make_broker(current_price, balance_data)
|
|
||||||
market = self._make_market()
|
|
||||||
|
|
||||||
buy_match = ScenarioMatch(
|
|
||||||
stock_code="005930",
|
|
||||||
matched_scenario=None,
|
|
||||||
action=ScenarioAction.BUY,
|
|
||||||
confidence=85,
|
|
||||||
rationale="test",
|
|
||||||
)
|
|
||||||
engine = MagicMock(spec=ScenarioEngine)
|
|
||||||
engine.evaluate = MagicMock(return_value=buy_match)
|
|
||||||
|
|
||||||
risk = MagicMock()
|
|
||||||
risk.validate_order = MagicMock()
|
|
||||||
risk.check_circuit_breaker = MagicMock()
|
|
||||||
telegram = MagicMock()
|
|
||||||
telegram.notify_trade_execution = AsyncMock()
|
|
||||||
telegram.notify_fat_finger = AsyncMock()
|
|
||||||
telegram.notify_circuit_breaker = AsyncMock()
|
|
||||||
telegram.notify_scenario_matched = AsyncMock()
|
|
||||||
|
|
||||||
with patch("src.main.log_trade"):
|
|
||||||
await trading_cycle(
|
|
||||||
broker=broker,
|
|
||||||
overseas_broker=MagicMock(),
|
|
||||||
scenario_engine=engine,
|
|
||||||
playbook=_make_playbook(),
|
|
||||||
risk=risk,
|
|
||||||
db_conn=MagicMock(),
|
|
||||||
decision_logger=MagicMock(),
|
|
||||||
context_store=MagicMock(get_latest_timeframe=MagicMock(return_value=None)),
|
|
||||||
criticality_assessor=MagicMock(
|
|
||||||
assess_market_conditions=MagicMock(return_value=MagicMock(value="NORMAL")),
|
|
||||||
get_timeout=MagicMock(return_value=5.0),
|
|
||||||
),
|
|
||||||
telegram=telegram,
|
|
||||||
market=market,
|
|
||||||
stock_code="005930",
|
|
||||||
scan_candidates={},
|
|
||||||
)
|
|
||||||
|
|
||||||
broker.send_order.assert_called_once()
|
|
||||||
call_kwargs = broker.send_order.call_args[1]
|
|
||||||
expected_price = kr_round_down(current_price * 1.002)
|
|
||||||
assert call_kwargs["price"] == expected_price
|
|
||||||
assert call_kwargs["order_type"] == "BUY"
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_trading_cycle_domestic_sell_uses_limit_price(self) -> None:
|
|
||||||
"""SELL order for domestic stock must use kr_round_down(price * 0.998)."""
|
|
||||||
from src.broker.kis_api import kr_round_down
|
|
||||||
from src.strategy.models import ScenarioAction
|
|
||||||
|
|
||||||
current_price = 70000.0
|
|
||||||
stock_code = "005930"
|
|
||||||
balance_data = {
|
|
||||||
"output1": [
|
|
||||||
{"pdno": stock_code, "hldg_qty": "5", "prpr": "70000", "evlu_amt": "350000"}
|
|
||||||
],
|
|
||||||
"output2": [
|
|
||||||
{
|
|
||||||
"tot_evlu_amt": "350000",
|
|
||||||
"dnca_tot_amt": "0",
|
|
||||||
"pchs_amt_smtl_amt": "350000",
|
|
||||||
}
|
|
||||||
],
|
|
||||||
}
|
|
||||||
broker = self._make_broker(current_price, balance_data)
|
|
||||||
market = self._make_market()
|
|
||||||
|
|
||||||
sell_match = ScenarioMatch(
|
|
||||||
stock_code=stock_code,
|
|
||||||
matched_scenario=None,
|
|
||||||
action=ScenarioAction.SELL,
|
|
||||||
confidence=85,
|
|
||||||
rationale="test",
|
|
||||||
)
|
|
||||||
engine = MagicMock(spec=ScenarioEngine)
|
|
||||||
engine.evaluate = MagicMock(return_value=sell_match)
|
|
||||||
|
|
||||||
risk = MagicMock()
|
|
||||||
risk.validate_order = MagicMock()
|
|
||||||
risk.check_circuit_breaker = MagicMock()
|
|
||||||
telegram = MagicMock()
|
|
||||||
telegram.notify_trade_execution = AsyncMock()
|
|
||||||
telegram.notify_fat_finger = AsyncMock()
|
|
||||||
telegram.notify_circuit_breaker = AsyncMock()
|
|
||||||
telegram.notify_scenario_matched = AsyncMock()
|
|
||||||
|
|
||||||
with patch("src.main.log_trade"):
|
|
||||||
await trading_cycle(
|
|
||||||
broker=broker,
|
|
||||||
overseas_broker=MagicMock(),
|
|
||||||
scenario_engine=engine,
|
|
||||||
playbook=_make_playbook(),
|
|
||||||
risk=risk,
|
|
||||||
db_conn=MagicMock(),
|
|
||||||
decision_logger=MagicMock(),
|
|
||||||
context_store=MagicMock(get_latest_timeframe=MagicMock(return_value=None)),
|
|
||||||
criticality_assessor=MagicMock(
|
|
||||||
assess_market_conditions=MagicMock(return_value=MagicMock(value="NORMAL")),
|
|
||||||
get_timeout=MagicMock(return_value=5.0),
|
|
||||||
),
|
|
||||||
telegram=telegram,
|
|
||||||
market=market,
|
|
||||||
stock_code=stock_code,
|
|
||||||
scan_candidates={},
|
|
||||||
)
|
|
||||||
|
|
||||||
broker.send_order.assert_called_once()
|
|
||||||
call_kwargs = broker.send_order.call_args[1]
|
|
||||||
expected_price = kr_round_down(current_price * 0.998)
|
|
||||||
assert call_kwargs["price"] == expected_price
|
|
||||||
assert call_kwargs["order_type"] == "SELL"
|
|
||||||
|
|||||||
@@ -813,221 +813,3 @@ class TestOverseasTRIDBranching:
|
|||||||
|
|
||||||
await broker.send_overseas_order("NASD", "AAPL", "SELL", 1)
|
await broker.send_overseas_order("NASD", "AAPL", "SELL", 1)
|
||||||
assert "TTTT1006U" in captured
|
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"
|
|
||||||
|
|||||||
Reference in New Issue
Block a user