Compare commits
11 Commits
cd36d53a47
...
feature/is
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0727f28f77 | ||
| 641f3e8811 | |||
|
|
ebd0a0297c | ||
| 02a72e0f7e | |||
| 478a659ac2 | |||
|
|
16b9b6832d | ||
|
|
48b87a79f6 | ||
|
|
ad79082dcc | ||
|
|
11dff9d3e5 | ||
|
|
3c5f1752e6 | ||
|
|
d6a389e0b7 |
64
.env.example
64
.env.example
@@ -1,36 +1,82 @@
|
||||
# ============================================================
|
||||
# The Ouroboros — Environment Configuration
|
||||
# ============================================================
|
||||
# Copy this file to .env and fill in your values.
|
||||
# Lines starting with # are comments.
|
||||
|
||||
# ============================================================
|
||||
# Korea Investment Securities API
|
||||
# ============================================================
|
||||
KIS_APP_KEY=your_app_key_here
|
||||
KIS_APP_SECRET=your_app_secret_here
|
||||
KIS_ACCOUNT_NO=12345678-01
|
||||
KIS_BASE_URL=https://openapivts.koreainvestment.com:9443
|
||||
|
||||
# Paper trading (VTS): https://openapivts.koreainvestment.com:29443
|
||||
# Live trading: https://openapi.koreainvestment.com:9443
|
||||
KIS_BASE_URL=https://openapivts.koreainvestment.com:29443
|
||||
|
||||
# ============================================================
|
||||
# Trading Mode
|
||||
# ============================================================
|
||||
# paper = 모의투자 (safe for testing), live = 실전투자 (real money)
|
||||
MODE=paper
|
||||
|
||||
# daily = batch per session, realtime = per-stock continuous scan
|
||||
TRADE_MODE=daily
|
||||
|
||||
# Comma-separated market codes: KR, US, JP, HK, CN, VN
|
||||
ENABLED_MARKETS=KR,US
|
||||
|
||||
# Simulated USD cash for paper (VTS) overseas trading.
|
||||
# VTS overseas balance API often returns 0; this value is used as fallback.
|
||||
# Set to 0 to disable fallback (not used in live mode).
|
||||
PAPER_OVERSEAS_CASH=50000.0
|
||||
|
||||
# ============================================================
|
||||
# Google Gemini
|
||||
# ============================================================
|
||||
GEMINI_API_KEY=your_gemini_api_key_here
|
||||
GEMINI_MODEL=gemini-pro
|
||||
# Recommended: gemini-2.0-flash-exp or gemini-1.5-pro
|
||||
GEMINI_MODEL=gemini-2.0-flash-exp
|
||||
|
||||
# ============================================================
|
||||
# Risk Management
|
||||
# ============================================================
|
||||
CIRCUIT_BREAKER_PCT=-3.0
|
||||
FAT_FINGER_PCT=30.0
|
||||
CONFIDENCE_THRESHOLD=80
|
||||
|
||||
# ============================================================
|
||||
# Database
|
||||
# ============================================================
|
||||
DB_PATH=data/trade_logs.db
|
||||
|
||||
# Rate Limiting (requests per second for KIS API)
|
||||
# Reduced to 5.0 to avoid "초당 거래건수 초과" errors (EGW00201)
|
||||
RATE_LIMIT_RPS=5.0
|
||||
# ============================================================
|
||||
# Rate Limiting
|
||||
# ============================================================
|
||||
# KIS API real limit is ~2 RPS. Keep at 2.0 for maximum safety.
|
||||
# Increasing this risks EGW00201 "초당 거래건수 초과" errors.
|
||||
RATE_LIMIT_RPS=2.0
|
||||
|
||||
# Trading Mode (paper / live)
|
||||
MODE=paper
|
||||
|
||||
# External Data APIs (optional — for enhanced decision-making)
|
||||
# ============================================================
|
||||
# External Data APIs (optional)
|
||||
# ============================================================
|
||||
# NEWS_API_KEY=your_news_api_key_here
|
||||
# NEWS_API_PROVIDER=alphavantage
|
||||
# MARKET_DATA_API_KEY=your_market_data_key_here
|
||||
|
||||
# ============================================================
|
||||
# Telegram Notifications (optional)
|
||||
# ============================================================
|
||||
# Get bot token from @BotFather on Telegram
|
||||
# Get chat ID from @userinfobot or your chat
|
||||
# TELEGRAM_BOT_TOKEN=1234567890:ABCdefGHIjklMNOpqrsTUVwxyz
|
||||
# TELEGRAM_CHAT_ID=123456789
|
||||
# TELEGRAM_ENABLED=true
|
||||
|
||||
# ============================================================
|
||||
# Dashboard (optional)
|
||||
# ============================================================
|
||||
# DASHBOARD_ENABLED=false
|
||||
# DASHBOARD_HOST=127.0.0.1
|
||||
# DASHBOARD_PORT=8080
|
||||
|
||||
@@ -170,7 +170,7 @@ Markets auto-detected based on timezone and enabled in `ENABLED_MARKETS` env var
|
||||
- `src/core/risk_manager.py` is **READ-ONLY** — changes require human approval
|
||||
- Circuit breaker at -3.0% P&L — may only be made **stricter**
|
||||
- Fat-finger protection: max 30% of cash per order — always enforced
|
||||
- Confidence < 80 → force HOLD — cannot be weakened
|
||||
- Confidence 임계값 (market_outlook별, 낮출 수 없음): BEARISH ≥ 90, NEUTRAL/기본 ≥ 80, BULLISH ≥ 75
|
||||
- All code changes → corresponding tests → coverage ≥ 80%
|
||||
|
||||
## Contributing
|
||||
|
||||
@@ -285,7 +285,10 @@ class KISBroker:
|
||||
await self._rate_limiter.acquire()
|
||||
session = self._get_session()
|
||||
|
||||
headers = await self._auth_headers("VTTC8434R") # 모의투자 잔고조회
|
||||
# TR_ID: 실전 TTTC8434R, 모의 VTTC8434R
|
||||
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '국내주식 잔고조회' 시트
|
||||
tr_id = "TTTC8434R" if self._settings.MODE == "live" else "VTTC8434R"
|
||||
headers = await self._auth_headers(tr_id)
|
||||
params = {
|
||||
"CANO": self._account_no,
|
||||
"ACNT_PRDT_CD": self._product_cd,
|
||||
@@ -330,7 +333,13 @@ class KISBroker:
|
||||
await self._rate_limiter.acquire()
|
||||
session = self._get_session()
|
||||
|
||||
tr_id = "VTTC0802U" if order_type == "BUY" else "VTTC0801U"
|
||||
# TR_ID: 실전 BUY=TTTC0012U SELL=TTTC0011U, 모의 BUY=VTTC0012U SELL=VTTC0011U
|
||||
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '주식주문(현금)' 시트
|
||||
# ※ TTTC0802U/VTTC0802U는 미수매수(증거금40% 계좌 전용) — 현금주문에 사용 금지
|
||||
if self._settings.MODE == "live":
|
||||
tr_id = "TTTC0012U" if order_type == "BUY" else "TTTC0011U"
|
||||
else:
|
||||
tr_id = "VTTC0012U" if order_type == "BUY" else "VTTC0011U"
|
||||
|
||||
# KRX requires limit orders to be rounded down to the tick unit.
|
||||
# ORD_DVSN: "00"=지정가, "01"=시장가
|
||||
|
||||
@@ -175,8 +175,12 @@ class OverseasBroker:
|
||||
await self._broker._rate_limiter.acquire()
|
||||
session = self._broker._get_session()
|
||||
|
||||
# Virtual trading TR_ID for overseas balance inquiry
|
||||
headers = await self._broker._auth_headers("VTTS3012R")
|
||||
# TR_ID: 실전 TTTS3012R, 모의 VTTS3012R
|
||||
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '해외주식 잔고조회' 시트
|
||||
balance_tr_id = (
|
||||
"TTTS3012R" if self._broker._settings.MODE == "live" else "VTTS3012R"
|
||||
)
|
||||
headers = await self._broker._auth_headers(balance_tr_id)
|
||||
params = {
|
||||
"CANO": self._broker._account_no,
|
||||
"ACNT_PRDT_CD": self._broker._product_cd,
|
||||
@@ -229,9 +233,11 @@ class OverseasBroker:
|
||||
await self._broker._rate_limiter.acquire()
|
||||
session = self._broker._get_session()
|
||||
|
||||
# Virtual trading TR_IDs for overseas orders
|
||||
# TR_ID: 실전 BUY=TTTT1002U SELL=TTTT1006U, 모의 BUY=VTTT1002U SELL=VTTT1001U
|
||||
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '해외주식 주문' 시트
|
||||
# VTTT1002U: 모의투자 미국 매수, VTTT1001U: 모의투자 미국 매도
|
||||
if self._broker._settings.MODE == "live":
|
||||
tr_id = "TTTT1002U" if order_type == "BUY" else "TTTT1006U"
|
||||
else:
|
||||
tr_id = "VTTT1002U" if order_type == "BUY" else "VTTT1001U"
|
||||
|
||||
body = {
|
||||
|
||||
@@ -13,7 +13,7 @@ class Settings(BaseSettings):
|
||||
KIS_APP_KEY: str
|
||||
KIS_APP_SECRET: str
|
||||
KIS_ACCOUNT_NO: str # format: "XXXXXXXX-XX"
|
||||
KIS_BASE_URL: str = "https://openapivts.koreainvestment.com:9443"
|
||||
KIS_BASE_URL: str = "https://openapivts.koreainvestment.com:29443"
|
||||
|
||||
# Google Gemini
|
||||
GEMINI_API_KEY: str
|
||||
|
||||
21
src/db.py
21
src/db.py
@@ -14,6 +14,11 @@ def init_db(db_path: str) -> sqlite3.Connection:
|
||||
if db_path != ":memory:":
|
||||
Path(db_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
conn = sqlite3.connect(db_path)
|
||||
# Enable WAL mode for concurrent read/write (dashboard + trading loop).
|
||||
# WAL does not apply to in-memory databases.
|
||||
if db_path != ":memory:":
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
conn.execute("PRAGMA busy_timeout=5000")
|
||||
conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS trades (
|
||||
@@ -28,12 +33,13 @@ def init_db(db_path: str) -> sqlite3.Connection:
|
||||
pnl REAL DEFAULT 0.0,
|
||||
market TEXT DEFAULT 'KR',
|
||||
exchange_code TEXT DEFAULT 'KRX',
|
||||
decision_id TEXT
|
||||
decision_id TEXT,
|
||||
mode TEXT DEFAULT 'paper'
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
# Migration: Add market and exchange_code columns if they don't exist
|
||||
# Migration: Add columns if they don't exist (backward-compatible schema upgrades)
|
||||
cursor = conn.execute("PRAGMA table_info(trades)")
|
||||
columns = {row[1] for row in cursor.fetchall()}
|
||||
|
||||
@@ -45,6 +51,8 @@ def init_db(db_path: str) -> sqlite3.Connection:
|
||||
conn.execute("ALTER TABLE trades ADD COLUMN selection_context TEXT")
|
||||
if "decision_id" not in columns:
|
||||
conn.execute("ALTER TABLE trades ADD COLUMN decision_id TEXT")
|
||||
if "mode" not in columns:
|
||||
conn.execute("ALTER TABLE trades ADD COLUMN mode TEXT DEFAULT 'paper'")
|
||||
|
||||
# Context tree tables for multi-layered memory management
|
||||
conn.execute(
|
||||
@@ -167,6 +175,7 @@ def log_trade(
|
||||
exchange_code: str = "KRX",
|
||||
selection_context: dict[str, any] | None = None,
|
||||
decision_id: str | None = None,
|
||||
mode: str = "paper",
|
||||
) -> None:
|
||||
"""Insert a trade record into the database.
|
||||
|
||||
@@ -182,6 +191,8 @@ def log_trade(
|
||||
market: Market code
|
||||
exchange_code: Exchange code
|
||||
selection_context: Scanner selection data (RSI, volume_ratio, signal, score)
|
||||
decision_id: Unique decision identifier for audit linking
|
||||
mode: Trading mode ('paper' or 'live') for data separation
|
||||
"""
|
||||
# Serialize selection context to JSON
|
||||
context_json = json.dumps(selection_context) if selection_context else None
|
||||
@@ -190,9 +201,10 @@ def log_trade(
|
||||
"""
|
||||
INSERT INTO trades (
|
||||
timestamp, stock_code, action, confidence, rationale,
|
||||
quantity, price, pnl, market, exchange_code, selection_context, decision_id
|
||||
quantity, price, pnl, market, exchange_code, selection_context, decision_id,
|
||||
mode
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
datetime.now(UTC).isoformat(),
|
||||
@@ -207,6 +219,7 @@ def log_trade(
|
||||
exchange_code,
|
||||
context_json,
|
||||
decision_id,
|
||||
mode,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
27
src/main.py
27
src/main.py
@@ -340,7 +340,13 @@ async def trading_cycle(
|
||||
purchase_total = safe_float(balance_info.get("frcr_buy_amt_smtl", "0") or "0")
|
||||
|
||||
# Paper mode fallback: VTS overseas balance API often fails for many accounts.
|
||||
if total_cash <= 0 and settings and settings.PAPER_OVERSEAS_CASH > 0:
|
||||
# Only activate in paper mode — live mode must use real balance from KIS.
|
||||
if (
|
||||
total_cash <= 0
|
||||
and settings
|
||||
and settings.MODE == "paper"
|
||||
and settings.PAPER_OVERSEAS_CASH > 0
|
||||
):
|
||||
logger.debug(
|
||||
"Overseas cash balance is 0 for %s; using paper fallback %.2f USD",
|
||||
market.exchange_code,
|
||||
@@ -822,6 +828,7 @@ async def trading_cycle(
|
||||
exchange_code=market.exchange_code,
|
||||
selection_context=selection_context,
|
||||
decision_id=decision_id,
|
||||
mode=settings.MODE if settings else "paper",
|
||||
)
|
||||
|
||||
# 7. Latency monitoring
|
||||
@@ -1041,11 +1048,12 @@ async def run_daily_session(
|
||||
balance_info.get("frcr_buy_amt_smtl", "0") or "0"
|
||||
)
|
||||
# Paper mode fallback: VTS overseas balance API often fails for many accounts.
|
||||
if total_cash <= 0 and settings.PAPER_OVERSEAS_CASH > 0:
|
||||
total_cash = settings.PAPER_OVERSEAS_CASH
|
||||
|
||||
# VTS overseas balance API often returns 0; use paper fallback.
|
||||
if total_cash <= 0 and settings.PAPER_OVERSEAS_CASH > 0:
|
||||
# Only activate in paper mode — live mode must use real balance from KIS.
|
||||
if (
|
||||
total_cash <= 0
|
||||
and settings.MODE == "paper"
|
||||
and settings.PAPER_OVERSEAS_CASH > 0
|
||||
):
|
||||
total_cash = settings.PAPER_OVERSEAS_CASH
|
||||
|
||||
# Calculate daily P&L %
|
||||
@@ -1318,6 +1326,7 @@ async def run_daily_session(
|
||||
market=market.code,
|
||||
exchange_code=market.exchange_code,
|
||||
decision_id=decision_id,
|
||||
mode=settings.MODE,
|
||||
)
|
||||
|
||||
logger.info("Daily trading session completed")
|
||||
@@ -1979,6 +1988,10 @@ async def run(settings: Settings) -> None:
|
||||
)
|
||||
except CircuitBreakerTripped:
|
||||
logger.critical("Circuit breaker tripped — shutting down")
|
||||
await telegram.notify_circuit_breaker(
|
||||
pnl_pct=settings.CIRCUIT_BREAKER_PCT,
|
||||
threshold=settings.CIRCUIT_BREAKER_PCT,
|
||||
)
|
||||
shutdown.set()
|
||||
break
|
||||
except Exception as exc:
|
||||
@@ -2296,6 +2309,8 @@ async def run(settings: Settings) -> None:
|
||||
except TimeoutError:
|
||||
pass # Normal — timeout means it's time for next cycle
|
||||
finally:
|
||||
# Notify shutdown before closing resources
|
||||
await telegram.notify_system_shutdown("Normal shutdown")
|
||||
# Clean up resources
|
||||
await command_handler.stop_polling()
|
||||
await broker.close()
|
||||
|
||||
114
src/strategies/v20260220_210124_evolved.py
Normal file
114
src/strategies/v20260220_210124_evolved.py
Normal file
@@ -0,0 +1,114 @@
|
||||
"""Auto-generated strategy: v20260220_210124
|
||||
|
||||
Generated at: 2026-02-20T21:01:24.706847+00:00
|
||||
Rationale: Auto-evolved from 6 failures. Primary failure markets: ['US_AMEX', 'US_NYSE', 'US_NASDAQ']. Average loss: -194.69
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
from typing import Any
|
||||
from src.strategies.base import BaseStrategy
|
||||
|
||||
|
||||
class Strategy_v20260220_210124(BaseStrategy):
|
||||
"""Strategy: v20260220_210124"""
|
||||
|
||||
def evaluate(self, market_data: dict[str, Any]) -> dict[str, Any]:
|
||||
import datetime
|
||||
|
||||
# --- Strategy Constants ---
|
||||
# Minimum price for a stock to be considered for trading (avoids penny stocks)
|
||||
MIN_PRICE = 5.0
|
||||
|
||||
# Momentum signal thresholds (stricter than previous failures)
|
||||
MOMENTUM_PRICE_CHANGE_THRESHOLD = 7.0 # % price change
|
||||
MOMENTUM_VOLUME_RATIO_THRESHOLD = 4.0 # X times average volume
|
||||
|
||||
# Oversold signal thresholds (more conservative)
|
||||
OVERSOLD_RSI_THRESHOLD = 25.0 # RSI value (lower means more oversold)
|
||||
|
||||
# Confidence levels
|
||||
CONFIDENCE_HOLD = 30
|
||||
CONFIDENCE_BUY_OVERSOLD = 65
|
||||
CONFIDENCE_BUY_MOMENTUM = 85
|
||||
CONFIDENCE_BUY_STRONG_MOMENTUM = 90 # For higher-priced stocks with strong momentum
|
||||
|
||||
# Market hours in UTC (9:30 AM ET to 4:00 PM ET)
|
||||
MARKET_OPEN_UTC = datetime.time(14, 30)
|
||||
MARKET_CLOSE_UTC = datetime.time(21, 0)
|
||||
|
||||
# Volatile periods within market hours (UTC) to avoid
|
||||
# First hour after open (14:30 UTC - 15:30 UTC)
|
||||
VOLATILE_OPEN_END_UTC = datetime.time(15, 30)
|
||||
# Last 30 minutes before close (20:30 UTC - 21:00 UTC)
|
||||
VOLATILE_CLOSE_START_UTC = datetime.time(20, 30)
|
||||
|
||||
current_price = market_data.get('current_price')
|
||||
price_change_pct = market_data.get('price_change_pct')
|
||||
volume_ratio = market_data.get('volume_ratio') # Assumed pre-computed indicator
|
||||
rsi = market_data.get('rsi') # Assumed pre-computed indicator
|
||||
timestamp_str = market_data.get('timestamp')
|
||||
|
||||
action = "HOLD"
|
||||
confidence = CONFIDENCE_HOLD
|
||||
rationale = "Initial HOLD: No clear signal or conditions not met."
|
||||
|
||||
# --- 1. Basic Data Validation ---
|
||||
if current_price is None or price_change_pct is None:
|
||||
return {"action": "HOLD", "confidence": CONFIDENCE_HOLD,
|
||||
"rationale": "Insufficient core data (price or price change) to evaluate."}
|
||||
|
||||
# --- 2. Price Filter: Avoid low-priced/penny stocks ---
|
||||
if current_price < MIN_PRICE:
|
||||
return {"action": "HOLD", "confidence": CONFIDENCE_HOLD,
|
||||
"rationale": f"Avoiding low-priced stock (${current_price:.2f} < ${MIN_PRICE:.2f})."}
|
||||
|
||||
# --- 3. Time Filter: Only trade during core market hours ---
|
||||
if timestamp_str:
|
||||
try:
|
||||
dt_object = datetime.datetime.fromisoformat(timestamp_str)
|
||||
current_time_utc = dt_object.time()
|
||||
|
||||
if not (MARKET_OPEN_UTC <= current_time_utc < MARKET_CLOSE_UTC):
|
||||
return {"action": "HOLD", "confidence": CONFIDENCE_HOLD,
|
||||
"rationale": f"Avoiding trade outside core market hours ({current_time_utc} UTC)."}
|
||||
|
||||
if (MARKET_OPEN_UTC <= current_time_utc < VOLATILE_OPEN_END_UTC) or \
|
||||
(VOLATILE_CLOSE_START_UTC <= current_time_utc < MARKET_CLOSE_UTC):
|
||||
return {"action": "HOLD", "confidence": CONFIDENCE_HOLD,
|
||||
"rationale": f"Avoiding trade during volatile market open/close periods ({current_time_utc} UTC)."}
|
||||
|
||||
except ValueError:
|
||||
rationale += " (Warning: Malformed timestamp, time filters skipped)"
|
||||
|
||||
# --- Initialize signal states ---
|
||||
has_momentum_buy_signal = False
|
||||
has_oversold_buy_signal = False
|
||||
|
||||
# --- 4. Evaluate Enhanced Buy Signals ---
|
||||
|
||||
# Momentum Buy Signal
|
||||
if volume_ratio is not None and \
|
||||
price_change_pct > MOMENTUM_PRICE_CHANGE_THRESHOLD and \
|
||||
volume_ratio > MOMENTUM_VOLUME_RATIO_THRESHOLD:
|
||||
has_momentum_buy_signal = True
|
||||
rationale = f"Momentum BUY: Price change {price_change_pct:.2f}%, Volume {volume_ratio:.2f}x."
|
||||
confidence = CONFIDENCE_BUY_MOMENTUM
|
||||
if current_price >= 10.0:
|
||||
confidence = CONFIDENCE_BUY_STRONG_MOMENTUM
|
||||
|
||||
# Oversold Buy Signal
|
||||
if rsi is not None and rsi < OVERSOLD_RSI_THRESHOLD:
|
||||
has_oversold_buy_signal = True
|
||||
if not has_momentum_buy_signal:
|
||||
rationale = f"Oversold BUY: RSI {rsi:.2f}."
|
||||
confidence = CONFIDENCE_BUY_OVERSOLD
|
||||
if current_price >= 10.0:
|
||||
confidence = min(CONFIDENCE_BUY_OVERSOLD + 5, 80)
|
||||
|
||||
# --- 5. Decision Logic ---
|
||||
if has_momentum_buy_signal:
|
||||
action = "BUY"
|
||||
elif has_oversold_buy_signal:
|
||||
action = "BUY"
|
||||
|
||||
return {"action": action, "confidence": confidence, "rationale": rationale}
|
||||
97
src/strategies/v20260220_210159_evolved.py
Normal file
97
src/strategies/v20260220_210159_evolved.py
Normal file
@@ -0,0 +1,97 @@
|
||||
"""Auto-generated strategy: v20260220_210159
|
||||
|
||||
Generated at: 2026-02-20T21:01:59.391523+00:00
|
||||
Rationale: Auto-evolved from 6 failures. Primary failure markets: ['US_AMEX', 'US_NYSE', 'US_NASDAQ']. Average loss: -194.69
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
from typing import Any
|
||||
from src.strategies.base import BaseStrategy
|
||||
|
||||
|
||||
class Strategy_v20260220_210159(BaseStrategy):
|
||||
"""Strategy: v20260220_210159"""
|
||||
|
||||
def evaluate(self, market_data: dict[str, Any]) -> dict[str, Any]:
|
||||
import datetime
|
||||
|
||||
current_price = market_data.get('current_price')
|
||||
price_change_pct = market_data.get('price_change_pct')
|
||||
volume_ratio = market_data.get('volume_ratio')
|
||||
rsi = market_data.get('rsi')
|
||||
timestamp_str = market_data.get('timestamp')
|
||||
market_name = market_data.get('market')
|
||||
|
||||
# Default action
|
||||
action = "HOLD"
|
||||
confidence = 0
|
||||
rationale = "No strong signal or conditions not met."
|
||||
|
||||
# --- FAILURE PATTERN AVOIDANCE ---
|
||||
|
||||
# 1. Avoid low-priced/penny stocks
|
||||
MIN_PRICE_THRESHOLD = 5.0 # USD
|
||||
if current_price is not None and current_price < MIN_PRICE_THRESHOLD:
|
||||
rationale = (
|
||||
f"HOLD: Stock price (${current_price:.2f}) is below minimum threshold "
|
||||
f"(${MIN_PRICE_THRESHOLD:.2f}). Past failures consistently involved low-priced stocks."
|
||||
)
|
||||
return {"action": action, "confidence": confidence, "rationale": rationale}
|
||||
|
||||
# 2. Avoid early market hour volatility
|
||||
if timestamp_str:
|
||||
try:
|
||||
dt_obj = datetime.datetime.fromisoformat(timestamp_str)
|
||||
utc_hour = dt_obj.hour
|
||||
utc_minute = dt_obj.minute
|
||||
|
||||
if (utc_hour == 14 and utc_minute < 45) or (utc_hour == 13 and utc_minute >= 30):
|
||||
rationale = (
|
||||
f"HOLD: Trading during early market hours (UTC {utc_hour}:{utc_minute}), "
|
||||
f"a period identified with past failures due to high volatility."
|
||||
)
|
||||
return {"action": action, "confidence": confidence, "rationale": rationale}
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# --- IMPROVED BUY STRATEGY ---
|
||||
|
||||
# Momentum BUY signal
|
||||
if volume_ratio is not None and price_change_pct is not None:
|
||||
if price_change_pct > 7.0 and volume_ratio > 3.0:
|
||||
action = "BUY"
|
||||
confidence = 70
|
||||
rationale = "Improved BUY: Momentum signal with high volume and above price threshold."
|
||||
|
||||
if market_name == 'US_AMEX':
|
||||
confidence = max(55, confidence - 5)
|
||||
rationale += " (Adjusted lower for AMEX market's higher risk profile)."
|
||||
elif market_name == 'US_NASDAQ' and price_change_pct > 20:
|
||||
confidence = max(50, confidence - 10)
|
||||
rationale += " (Adjusted lower for aggressive NASDAQ momentum volatility)."
|
||||
|
||||
if price_change_pct > 15.0:
|
||||
confidence = max(50, confidence - 5)
|
||||
rationale += " (Caution: Very high daily price change, potential for reversal)."
|
||||
|
||||
return {"action": action, "confidence": confidence, "rationale": rationale}
|
||||
|
||||
# Oversold BUY signal
|
||||
if rsi is not None and price_change_pct is not None:
|
||||
if rsi < 30 and price_change_pct < -3.0:
|
||||
action = "BUY"
|
||||
confidence = 65
|
||||
rationale = "Improved BUY: Oversold signal with recent decline and above price threshold."
|
||||
|
||||
if market_name == 'US_AMEX':
|
||||
confidence = max(50, confidence - 5)
|
||||
rationale += " (Adjusted lower for AMEX market's higher risk on oversold assets)."
|
||||
|
||||
if price_change_pct < -10.0:
|
||||
confidence = max(45, confidence - 10)
|
||||
rationale += " (Caution: Very steep decline, potential falling knife)."
|
||||
|
||||
return {"action": action, "confidence": confidence, "rationale": rationale}
|
||||
|
||||
# If no specific BUY signal, default to HOLD
|
||||
return {"action": action, "confidence": confidence, "rationale": rationale}
|
||||
88
src/strategies/v20260220_210244_evolved.py
Normal file
88
src/strategies/v20260220_210244_evolved.py
Normal file
@@ -0,0 +1,88 @@
|
||||
"""Auto-generated strategy: v20260220_210244
|
||||
|
||||
Generated at: 2026-02-20T21:02:44.387355+00:00
|
||||
Rationale: Auto-evolved from 6 failures. Primary failure markets: ['US_AMEX', 'US_NYSE', 'US_NASDAQ']. Average loss: -194.69
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
from typing import Any
|
||||
from src.strategies.base import BaseStrategy
|
||||
|
||||
|
||||
class Strategy_v20260220_210244(BaseStrategy):
|
||||
"""Strategy: v20260220_210244"""
|
||||
|
||||
def evaluate(self, market_data: dict[str, Any]) -> dict[str, Any]:
|
||||
from datetime import datetime
|
||||
|
||||
# Extract required data points safely
|
||||
current_price = market_data.get("current_price")
|
||||
price_change_pct = market_data.get("price_change_pct")
|
||||
volume_ratio = market_data.get("volume_ratio")
|
||||
rsi = market_data.get("rsi")
|
||||
timestamp_str = market_data.get("timestamp")
|
||||
market_name = market_data.get("market")
|
||||
stock_code = market_data.get("stock_code", "UNKNOWN")
|
||||
|
||||
# Default action is HOLD with conservative confidence and rationale
|
||||
action = "HOLD"
|
||||
confidence = 50
|
||||
rationale = f"No strong BUY signal for {stock_code} or awaiting more favorable conditions after avoiding known failure patterns."
|
||||
|
||||
# --- 1. Failure Pattern Avoidance Filters ---
|
||||
|
||||
# A. Avoid low-priced (penny) stocks
|
||||
if current_price is not None and current_price < 5.0:
|
||||
return {
|
||||
"action": "HOLD",
|
||||
"confidence": 50,
|
||||
"rationale": f"AVOID {stock_code}: Stock price (${current_price:.2f}) is below minimum threshold ($5.00) for BUY action. Identified past failures on highly volatile, low-priced stocks."
|
||||
}
|
||||
|
||||
# B. Avoid initiating BUY trades during identified high-volatility hours
|
||||
if timestamp_str:
|
||||
try:
|
||||
trade_hour = datetime.fromisoformat(timestamp_str).hour
|
||||
if trade_hour in [14, 20]:
|
||||
return {
|
||||
"action": "HOLD",
|
||||
"confidence": 50,
|
||||
"rationale": f"AVOID {stock_code}: Trading during historically volatile hour ({trade_hour} UTC) where previous BUYs resulted in losses. Prefer to observe market stability."
|
||||
}
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
# C. Be cautious with extreme momentum spikes
|
||||
if volume_ratio is not None and price_change_pct is not None:
|
||||
if volume_ratio >= 9.0 and price_change_pct >= 15.0:
|
||||
return {
|
||||
"action": "HOLD",
|
||||
"confidence": 50,
|
||||
"rationale": f"AVOID {stock_code}: Extreme short-term momentum detected (price change: +{price_change_pct:.2f}%, volume ratio: {volume_ratio:.1f}x). Historical failures indicate buying into such rapid spikes often leads to reversals."
|
||||
}
|
||||
|
||||
# D. Be cautious with "oversold" signals without further confirmation
|
||||
if rsi is not None and rsi < 30:
|
||||
return {
|
||||
"action": "HOLD",
|
||||
"confidence": 50,
|
||||
"rationale": f"AVOID {stock_code}: Oversold signal (RSI={rsi:.1f}) detected. While often a BUY signal, historical failures on similar 'oversold' trades suggest waiting for stronger confirmation."
|
||||
}
|
||||
|
||||
# --- 2. Improved BUY Signal Generation ---
|
||||
if volume_ratio is not None and 2.0 <= volume_ratio < 9.0 and \
|
||||
price_change_pct is not None and 2.0 <= price_change_pct < 15.0:
|
||||
|
||||
action = "BUY"
|
||||
confidence = 70
|
||||
rationale = f"BUY {stock_code}: Moderate momentum detected (price change: +{price_change_pct:.2f}%, volume ratio: {volume_ratio:.1f}x). Passed filters for price and extreme momentum, avoiding past failure patterns."
|
||||
|
||||
if market_name in ["US_AMEX", "US_NASDAQ"]:
|
||||
confidence = max(60, confidence - 5)
|
||||
rationale += f" Adjusted confidence for {market_name} market characteristics."
|
||||
elif market_name == "US_NYSE":
|
||||
confidence = max(65, confidence)
|
||||
|
||||
confidence = max(50, min(85, confidence))
|
||||
|
||||
return {"action": action, "confidence": confidence, "rationale": rationale}
|
||||
@@ -572,4 +572,156 @@ class TestSendOrderTickRounding:
|
||||
order_call = mock_post.call_args_list[1]
|
||||
body = order_call[1].get("json", {})
|
||||
assert body["ORD_DVSN"] == "01"
|
||||
assert body["ORD_UNPR"] == "0"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TR_ID live/paper branching (issues #201, #202, #203)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestTRIDBranchingDomestic:
|
||||
"""get_balance and send_order must use correct TR_ID for live vs paper mode."""
|
||||
|
||||
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_get_balance_paper_uses_vttc8434r(self, settings) -> None:
|
||||
broker = self._make_broker(settings, "paper")
|
||||
mock_resp = AsyncMock()
|
||||
mock_resp.status = 200
|
||||
mock_resp.json = AsyncMock(
|
||||
return_value={"output1": [], "output2": {}}
|
||||
)
|
||||
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:
|
||||
await broker.get_balance()
|
||||
|
||||
headers = mock_get.call_args[1].get("headers", {})
|
||||
assert headers["tr_id"] == "VTTC8434R"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_balance_live_uses_tttc8434r(self, settings) -> None:
|
||||
broker = self._make_broker(settings, "live")
|
||||
mock_resp = AsyncMock()
|
||||
mock_resp.status = 200
|
||||
mock_resp.json = AsyncMock(
|
||||
return_value={"output1": [], "output2": {}}
|
||||
)
|
||||
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:
|
||||
await broker.get_balance()
|
||||
|
||||
headers = mock_get.call_args[1].get("headers", {})
|
||||
assert headers["tr_id"] == "TTTC8434R"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_order_buy_paper_uses_vttc0012u(self, settings) -> None:
|
||||
broker = self._make_broker(settings, "paper")
|
||||
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={"rt_cd": "0"})
|
||||
mock_order.__aenter__ = AsyncMock(return_value=mock_order)
|
||||
mock_order.__aexit__ = AsyncMock(return_value=False)
|
||||
|
||||
with patch(
|
||||
"aiohttp.ClientSession.post", side_effect=[mock_hash, mock_order]
|
||||
) as mock_post:
|
||||
await broker.send_order("005930", "BUY", 1)
|
||||
|
||||
order_headers = mock_post.call_args_list[1][1].get("headers", {})
|
||||
assert order_headers["tr_id"] == "VTTC0012U"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_order_buy_live_uses_tttc0012u(self, settings) -> None:
|
||||
broker = self._make_broker(settings, "live")
|
||||
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={"rt_cd": "0"})
|
||||
mock_order.__aenter__ = AsyncMock(return_value=mock_order)
|
||||
mock_order.__aexit__ = AsyncMock(return_value=False)
|
||||
|
||||
with patch(
|
||||
"aiohttp.ClientSession.post", side_effect=[mock_hash, mock_order]
|
||||
) as mock_post:
|
||||
await broker.send_order("005930", "BUY", 1)
|
||||
|
||||
order_headers = mock_post.call_args_list[1][1].get("headers", {})
|
||||
assert order_headers["tr_id"] == "TTTC0012U"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_order_sell_paper_uses_vttc0011u(self, settings) -> None:
|
||||
broker = self._make_broker(settings, "paper")
|
||||
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={"rt_cd": "0"})
|
||||
mock_order.__aenter__ = AsyncMock(return_value=mock_order)
|
||||
mock_order.__aexit__ = AsyncMock(return_value=False)
|
||||
|
||||
with patch(
|
||||
"aiohttp.ClientSession.post", side_effect=[mock_hash, mock_order]
|
||||
) as mock_post:
|
||||
await broker.send_order("005930", "SELL", 1)
|
||||
|
||||
order_headers = mock_post.call_args_list[1][1].get("headers", {})
|
||||
assert order_headers["tr_id"] == "VTTC0011U"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_order_sell_live_uses_tttc0011u(self, settings) -> None:
|
||||
broker = self._make_broker(settings, "live")
|
||||
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={"rt_cd": "0"})
|
||||
mock_order.__aenter__ = AsyncMock(return_value=mock_order)
|
||||
mock_order.__aexit__ = AsyncMock(return_value=False)
|
||||
|
||||
with patch(
|
||||
"aiohttp.ClientSession.post", side_effect=[mock_hash, mock_order]
|
||||
) as mock_post:
|
||||
await broker.send_order("005930", "SELL", 1)
|
||||
|
||||
order_headers = mock_post.call_args_list[1][1].get("headers", {})
|
||||
assert order_headers["tr_id"] == "TTTC0011U"
|
||||
|
||||
135
tests/test_db.py
135
tests/test_db.py
@@ -1,5 +1,8 @@
|
||||
"""Tests for database helper functions."""
|
||||
|
||||
import tempfile
|
||||
import os
|
||||
|
||||
from src.db import get_open_position, init_db, log_trade
|
||||
|
||||
|
||||
@@ -58,3 +61,135 @@ def test_get_open_position_returns_none_when_latest_is_sell() -> None:
|
||||
def test_get_open_position_returns_none_when_no_trades() -> None:
|
||||
conn = init_db(":memory:")
|
||||
assert get_open_position(conn, "AAPL", "US_NASDAQ") is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# WAL mode tests (issue #210)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_wal_mode_applied_to_file_db() -> None:
|
||||
"""File-based DB must use WAL journal mode for dashboard concurrent reads."""
|
||||
with tempfile.NamedTemporaryFile(suffix=".db", delete=False) as f:
|
||||
db_path = f.name
|
||||
try:
|
||||
conn = init_db(db_path)
|
||||
cursor = conn.execute("PRAGMA journal_mode")
|
||||
mode = cursor.fetchone()[0]
|
||||
assert mode == "wal", f"Expected WAL mode, got {mode}"
|
||||
conn.close()
|
||||
finally:
|
||||
os.unlink(db_path)
|
||||
# Clean up WAL auxiliary files if they exist
|
||||
for ext in ("-wal", "-shm"):
|
||||
path = db_path + ext
|
||||
if os.path.exists(path):
|
||||
os.unlink(path)
|
||||
|
||||
|
||||
def test_wal_mode_not_applied_to_memory_db() -> None:
|
||||
""":memory: DB must not apply WAL (SQLite does not support WAL for in-memory)."""
|
||||
conn = init_db(":memory:")
|
||||
cursor = conn.execute("PRAGMA journal_mode")
|
||||
mode = cursor.fetchone()[0]
|
||||
# In-memory DBs default to 'memory' journal mode
|
||||
assert mode != "wal", "WAL should not be set on in-memory database"
|
||||
conn.close()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# mode column tests (issue #212)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_log_trade_stores_mode_paper() -> None:
|
||||
"""log_trade must persist mode='paper' in the trades table."""
|
||||
conn = init_db(":memory:")
|
||||
log_trade(
|
||||
conn=conn,
|
||||
stock_code="005930",
|
||||
action="BUY",
|
||||
confidence=85,
|
||||
rationale="test",
|
||||
mode="paper",
|
||||
)
|
||||
row = conn.execute("SELECT mode FROM trades ORDER BY id DESC LIMIT 1").fetchone()
|
||||
assert row is not None
|
||||
assert row[0] == "paper"
|
||||
|
||||
|
||||
def test_log_trade_stores_mode_live() -> None:
|
||||
"""log_trade must persist mode='live' in the trades table."""
|
||||
conn = init_db(":memory:")
|
||||
log_trade(
|
||||
conn=conn,
|
||||
stock_code="005930",
|
||||
action="BUY",
|
||||
confidence=85,
|
||||
rationale="test",
|
||||
mode="live",
|
||||
)
|
||||
row = conn.execute("SELECT mode FROM trades ORDER BY id DESC LIMIT 1").fetchone()
|
||||
assert row is not None
|
||||
assert row[0] == "live"
|
||||
|
||||
|
||||
def test_log_trade_default_mode_is_paper() -> None:
|
||||
"""log_trade without explicit mode must default to 'paper'."""
|
||||
conn = init_db(":memory:")
|
||||
log_trade(
|
||||
conn=conn,
|
||||
stock_code="005930",
|
||||
action="HOLD",
|
||||
confidence=50,
|
||||
rationale="test",
|
||||
)
|
||||
row = conn.execute("SELECT mode FROM trades ORDER BY id DESC LIMIT 1").fetchone()
|
||||
assert row is not None
|
||||
assert row[0] == "paper"
|
||||
|
||||
|
||||
def test_mode_column_exists_in_schema() -> None:
|
||||
"""trades table must have a mode column after init_db."""
|
||||
conn = init_db(":memory:")
|
||||
cursor = conn.execute("PRAGMA table_info(trades)")
|
||||
columns = {row[1] for row in cursor.fetchall()}
|
||||
assert "mode" in columns
|
||||
|
||||
|
||||
def test_mode_migration_adds_column_to_existing_db() -> None:
|
||||
"""init_db must add mode column to existing DBs that lack it (migration)."""
|
||||
import sqlite3
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".db", delete=False) as f:
|
||||
db_path = f.name
|
||||
try:
|
||||
# Create DB without mode column (simulate old schema)
|
||||
old_conn = sqlite3.connect(db_path)
|
||||
old_conn.execute(
|
||||
"""CREATE TABLE trades (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
timestamp TEXT NOT NULL,
|
||||
stock_code TEXT NOT NULL,
|
||||
action TEXT NOT NULL,
|
||||
confidence INTEGER NOT NULL,
|
||||
rationale TEXT,
|
||||
quantity INTEGER,
|
||||
price REAL,
|
||||
pnl REAL DEFAULT 0.0,
|
||||
market TEXT DEFAULT 'KR',
|
||||
exchange_code TEXT DEFAULT 'KRX',
|
||||
decision_id TEXT
|
||||
)"""
|
||||
)
|
||||
old_conn.commit()
|
||||
old_conn.close()
|
||||
|
||||
# Run init_db — should add mode column via migration
|
||||
conn = init_db(db_path)
|
||||
cursor = conn.execute("PRAGMA table_info(trades)")
|
||||
columns = {row[1] for row in cursor.fetchall()}
|
||||
assert "mode" in columns
|
||||
conn.close()
|
||||
finally:
|
||||
os.unlink(db_path)
|
||||
|
||||
@@ -640,4 +640,176 @@ class TestPaperOverseasCash:
|
||||
GEMINI_API_KEY="g",
|
||||
)
|
||||
assert settings.PAPER_OVERSEAS_CASH == 0.0
|
||||
del os.environ["PAPER_OVERSEAS_CASH"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# TR_ID live/paper branching — overseas (issues #201, #203)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _make_overseas_broker_with_mode(mode: str) -> OverseasBroker:
|
||||
s = Settings(
|
||||
KIS_APP_KEY="k",
|
||||
KIS_APP_SECRET="s",
|
||||
KIS_ACCOUNT_NO="12345678-01",
|
||||
GEMINI_API_KEY="g",
|
||||
DB_PATH=":memory:",
|
||||
MODE=mode,
|
||||
)
|
||||
kis = KISBroker(s)
|
||||
kis._access_token = "tok"
|
||||
kis._token_expires_at = float("inf")
|
||||
kis._rate_limiter.acquire = AsyncMock()
|
||||
return OverseasBroker(kis)
|
||||
|
||||
|
||||
class TestOverseasTRIDBranching:
|
||||
"""get_overseas_balance and send_overseas_order must use correct TR_ID."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_overseas_balance_paper_uses_vtts3012r(self) -> None:
|
||||
broker = _make_overseas_broker_with_mode("paper")
|
||||
captured: list[str] = []
|
||||
|
||||
async def mock_auth_headers(tr_id: str) -> dict:
|
||||
captured.append(tr_id)
|
||||
return {"tr_id": tr_id, "authorization": "Bearer tok"}
|
||||
|
||||
broker._broker._auth_headers = mock_auth_headers # type: ignore[method-assign]
|
||||
|
||||
mock_resp = AsyncMock()
|
||||
mock_resp.status = 200
|
||||
mock_resp.json = AsyncMock(return_value={"output1": [], "output2": []})
|
||||
mock_resp.__aenter__ = AsyncMock(return_value=mock_resp)
|
||||
mock_resp.__aexit__ = AsyncMock(return_value=False)
|
||||
|
||||
mock_session = MagicMock()
|
||||
mock_session.get = MagicMock(return_value=mock_resp)
|
||||
broker._broker._get_session = MagicMock(return_value=mock_session)
|
||||
|
||||
await broker.get_overseas_balance("NASD")
|
||||
assert "VTTS3012R" in captured
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_overseas_balance_live_uses_ttts3012r(self) -> None:
|
||||
broker = _make_overseas_broker_with_mode("live")
|
||||
captured: list[str] = []
|
||||
|
||||
async def mock_auth_headers(tr_id: str) -> dict:
|
||||
captured.append(tr_id)
|
||||
return {"tr_id": tr_id, "authorization": "Bearer tok"}
|
||||
|
||||
broker._broker._auth_headers = mock_auth_headers # type: ignore[method-assign]
|
||||
|
||||
mock_resp = AsyncMock()
|
||||
mock_resp.status = 200
|
||||
mock_resp.json = AsyncMock(return_value={"output1": [], "output2": []})
|
||||
mock_resp.__aenter__ = AsyncMock(return_value=mock_resp)
|
||||
mock_resp.__aexit__ = AsyncMock(return_value=False)
|
||||
|
||||
mock_session = MagicMock()
|
||||
mock_session.get = MagicMock(return_value=mock_resp)
|
||||
broker._broker._get_session = MagicMock(return_value=mock_session)
|
||||
|
||||
await broker.get_overseas_balance("NASD")
|
||||
assert "TTTS3012R" in captured
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_overseas_order_buy_paper_uses_vttt1002u(self) -> None:
|
||||
broker = _make_overseas_broker_with_mode("paper")
|
||||
captured: list[str] = []
|
||||
|
||||
async def mock_auth_headers(tr_id: str) -> dict:
|
||||
captured.append(tr_id)
|
||||
return {"tr_id": tr_id, "authorization": "Bearer tok"}
|
||||
|
||||
broker._broker._auth_headers = mock_auth_headers # type: ignore[method-assign]
|
||||
broker._broker._get_hash_key = AsyncMock(return_value="h") # type: ignore[method-assign]
|
||||
|
||||
mock_resp = AsyncMock()
|
||||
mock_resp.status = 200
|
||||
mock_resp.json = AsyncMock(return_value={"rt_cd": "0", "msg1": "OK"})
|
||||
mock_resp.__aenter__ = AsyncMock(return_value=mock_resp)
|
||||
mock_resp.__aexit__ = AsyncMock(return_value=False)
|
||||
|
||||
mock_session = MagicMock()
|
||||
mock_session.post = MagicMock(return_value=mock_resp)
|
||||
broker._broker._get_session = MagicMock(return_value=mock_session)
|
||||
|
||||
await broker.send_overseas_order("NASD", "AAPL", "BUY", 1)
|
||||
assert "VTTT1002U" in captured
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_overseas_order_buy_live_uses_tttt1002u(self) -> None:
|
||||
broker = _make_overseas_broker_with_mode("live")
|
||||
captured: list[str] = []
|
||||
|
||||
async def mock_auth_headers(tr_id: str) -> dict:
|
||||
captured.append(tr_id)
|
||||
return {"tr_id": tr_id, "authorization": "Bearer tok"}
|
||||
|
||||
broker._broker._auth_headers = mock_auth_headers # type: ignore[method-assign]
|
||||
broker._broker._get_hash_key = AsyncMock(return_value="h") # type: ignore[method-assign]
|
||||
|
||||
mock_resp = AsyncMock()
|
||||
mock_resp.status = 200
|
||||
mock_resp.json = AsyncMock(return_value={"rt_cd": "0", "msg1": "OK"})
|
||||
mock_resp.__aenter__ = AsyncMock(return_value=mock_resp)
|
||||
mock_resp.__aexit__ = AsyncMock(return_value=False)
|
||||
|
||||
mock_session = MagicMock()
|
||||
mock_session.post = MagicMock(return_value=mock_resp)
|
||||
broker._broker._get_session = MagicMock(return_value=mock_session)
|
||||
|
||||
await broker.send_overseas_order("NASD", "AAPL", "BUY", 1)
|
||||
assert "TTTT1002U" in captured
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_overseas_order_sell_paper_uses_vttt1001u(self) -> None:
|
||||
broker = _make_overseas_broker_with_mode("paper")
|
||||
captured: list[str] = []
|
||||
|
||||
async def mock_auth_headers(tr_id: str) -> dict:
|
||||
captured.append(tr_id)
|
||||
return {"tr_id": tr_id, "authorization": "Bearer tok"}
|
||||
|
||||
broker._broker._auth_headers = mock_auth_headers # type: ignore[method-assign]
|
||||
broker._broker._get_hash_key = AsyncMock(return_value="h") # type: ignore[method-assign]
|
||||
|
||||
mock_resp = AsyncMock()
|
||||
mock_resp.status = 200
|
||||
mock_resp.json = AsyncMock(return_value={"rt_cd": "0", "msg1": "OK"})
|
||||
mock_resp.__aenter__ = AsyncMock(return_value=mock_resp)
|
||||
mock_resp.__aexit__ = AsyncMock(return_value=False)
|
||||
|
||||
mock_session = MagicMock()
|
||||
mock_session.post = MagicMock(return_value=mock_resp)
|
||||
broker._broker._get_session = MagicMock(return_value=mock_session)
|
||||
|
||||
await broker.send_overseas_order("NASD", "AAPL", "SELL", 1)
|
||||
assert "VTTT1001U" in captured
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_send_overseas_order_sell_live_uses_tttt1006u(self) -> None:
|
||||
broker = _make_overseas_broker_with_mode("live")
|
||||
captured: list[str] = []
|
||||
|
||||
async def mock_auth_headers(tr_id: str) -> dict:
|
||||
captured.append(tr_id)
|
||||
return {"tr_id": tr_id, "authorization": "Bearer tok"}
|
||||
|
||||
broker._broker._auth_headers = mock_auth_headers # type: ignore[method-assign]
|
||||
broker._broker._get_hash_key = AsyncMock(return_value="h") # type: ignore[method-assign]
|
||||
|
||||
mock_resp = AsyncMock()
|
||||
mock_resp.status = 200
|
||||
mock_resp.json = AsyncMock(return_value={"rt_cd": "0", "msg1": "OK"})
|
||||
mock_resp.__aenter__ = AsyncMock(return_value=mock_resp)
|
||||
mock_resp.__aexit__ = AsyncMock(return_value=False)
|
||||
|
||||
mock_session = MagicMock()
|
||||
mock_session.post = MagicMock(return_value=mock_resp)
|
||||
broker._broker._get_session = MagicMock(return_value=mock_session)
|
||||
|
||||
await broker.send_overseas_order("NASD", "AAPL", "SELL", 1)
|
||||
assert "TTTT1006U" in captured
|
||||
|
||||
Reference in New Issue
Block a user