"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(trading): add KIS (한국투자증권) broker connector
heonjinjeong4a4aa12b0121
diff --git a/README.md b/README.mdindex d72167bee..f1a22236b 100644--- a/README.md+++ b/README.md@@ -585,7 +585,7 @@ run from a clone (`pip install -e .`).</details><details>-<summary><b>Broker Connectors</b> <sub>14 brokers — read + paper, bounded-live where supported</sub></summary>+<summary><b>Broker Connectors</b> <sub>15 brokers — read + paper, bounded-live where supported</sub></summary>Connector-first profiles. Most do read + paper-account order placement — IBKR is read-only, Robinhood is live-only (no paper account), and Trading 212 refuses order placement entirely, paper included; live order placement is bounded by a user-defined mandate (symbol allowlist, order-size / exposure caps, daily trade cap, instant kill switch) and never holds funds — the broker executes. Order-placing tools stay off MCP (agent + CLI only). Research / backtest paths are structurally barred from any live endpoint.@@ -599,6 +599,7 @@ Connector-first profiles. Most do read + paper-account order placement — IBKR| **Futu** | HK / US / A | read + paper + bounded live || **eToro** | global | read + paper + bounded live (Public API; demo keys reach only `/demo` paths, plus copy-trading workflows) || **MetaTrader 5** | forex / CFD | read + paper + bounded live (Exness-style; demo ⇔ paper identity guard) |+| **KIS** (한국투자증권) | Korea (KOSPI/KOSDAQ) | read + genuine paper (모의투자, a real broker-side sandbox on a separate host) — live order placement not yet wired for this market || **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** | US / HK · India (NSE/BSE) | read + paper only — no runtime paper/live discriminator, so live order placement is hard-refused || **Trading 212** | UK / EU | fully read-only — `place_order` / `cancel_order` hard-refuse even paper |diff --git a/README_ar.md b/README_ar.mdindex de31517bf..e6ae65dcb 100644--- a/README_ar.md+++ b/README_ar.md@@ -546,7 +546,7 @@ LONGBRIDGE_ACCESS_TOKEN=...</details><details>-<summary><b>موصّلات الوسطاء</b> <sub>14 وسيطاً — قراءة + حساب ورقي، وتداول حي محدود حيثما يُدعم</sub></summary>+<summary><b>موصّلات الوسطاء</b> <sub>15 وسيطاً — قراءة + حساب ورقي، وتداول حي محدود حيثما يُدعم</sub></summary>ملفات تعريف قائمة على الموصّل. يوفّر معظم الموصّلات قراءةً وتنفيذ أوامر على حساب ورقي (paper) — أما IBKR فللقراءة فقط، وRobinhood حيّ فقط (بلا حساب ورقي)، وTrading 212 يرفض تنفيذ الأوامر كلياً بما فيها الورقية؛ أما تنفيذ الأوامر الحية فمحدود بتفويض يحدّده المستخدم (قائمة رموز مسموح بها، وحدود لحجم الأمر / الانكشاف، وحد يومي للصفقات، ومفتاح إيقاف فوري) ولا يحتفظ الموصّل بأي أموال — الوسيط هو من ينفّذ. تبقى أدوات تنفيذ الأوامر خارج MCP (عبر agent + CLI فقط). ومسارات البحث / الاختبار الرجعي محظورة بنيوياً من أي نقطة نهاية حية.@@ -560,6 +560,7 @@ LONGBRIDGE_ACCESS_TOKEN=...| **Futu** | HK / US / A | قراءة + ورقي + تداول حي محدود || **eToro** | global | قراءة + ورقي + تداول حي محدود (Public API؛ مفاتيح demo لا تصل بنيويًا إلا إلى مسارات `/demo`، مع دعم تدفقات التداول بالنسخ) || **MetaTrader 5** | forex / CFD | قراءة + ورقي + تداول حي محدود (بأسلوب Exness؛ حارس هوية demo ⇔ paper) |+| **KIS** | كوريا الجنوبية (KOSPI/KOSDAQ) | قراءة + حساب ورقي حقيقي (모의투자، بيئة اختبار حقيقية لدى الوسيط على مضيف منفصل) — تنفيذ الأوامر الحية لهذا السوق غير مفعّل بعد || **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** | US / HK · الهند (NSE/BSE) | قراءة + ورقي فقط — لا يوجد مُميِّز وقت-تشغيل بين paper/live، لذا يُرفض تنفيذ الأوامر الحية بشكل صارم || **Trading 212** | UK / EU | قراءة فقط بالكامل — تَرفض `place_order` / `cancel_order` حتى الورقي بشكل صارم |diff --git a/README_es.md b/README_es.mdindex 4e54d23f0..c38e70437 100644--- a/README_es.md+++ b/README_es.md@@ -550,7 +550,7 @@ clon (`pip install -e .`).</details><details>-<summary><b>Conectores de Broker</b> <sub>14 brokers — lectura + paper, live acotado donde esté soportado</sub></summary>+<summary><b>Conectores de Broker</b> <sub>15 brokers — lectura + paper, live acotado donde esté soportado</sub></summary>Perfiles centrados en el conector. La mayoría hace lectura + colocación de órdenes en cuenta paper — IBKR es de solo lectura, Robinhood es solo live (sin cuenta paper), y Trading 212 rechaza la colocación de órdenes por completo, incluido el paper; la colocación de órdenes live está acotada por un mandato definido por el usuario (lista blanca de símbolos, límites de tamaño de orden / exposición, límite diario de operaciones, interruptor de apagado instantáneo) y nunca retiene fondos — el broker ejecuta. Las herramientas de colocación de órdenes se mantienen fuera de MCP (solo agente + CLI). Las rutas de investigación / backtest están estructuralmente vetadas de cualquier endpoint live.@@ -564,6 +564,7 @@ Perfiles centrados en el conector. La mayoría hace lectura + colocación de ór| **Futu** | HK / EE. UU. / A | lectura + paper + live acotado || **eToro** | global | lectura + paper + live acotado (API pública; las claves demo solo alcanzan rutas `/demo`, además de flujos de copy-trading) || **MetaTrader 5** | forex / CFD | lectura + paper + live acotado (estilo Exness; guardia de identidad demo ⇔ paper) |+| **KIS** (Korea Investment & Securities) | Corea (KOSPI/KOSDAQ) | lectura + paper genuino (모의투자, un sandbox real del lado del broker en un host separado) — la colocación de órdenes live aún no está conectada para este mercado || **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** | EE. UU. / HK · India (NSE/BSE) | solo lectura + paper — sin discriminador de runtime paper/live, por lo que la colocación de órdenes live se rechaza de forma estricta || **Trading 212** | Reino Unido / UE | completamente de solo lectura — `place_order` / `cancel_order` se rechazan de forma estricta incluso en paper |diff --git a/README_ja.md b/README_ja.mdindex a1f4d472a..74a1a023a 100644--- a/README_ja.md+++ b/README_ja.md@@ -546,7 +546,7 @@ clone から実行してください(`pip install -e .`)。</details><details>-<summary><b>ブローカー connectors</b> <sub>14 ブローカー — read + paper、対応先では bounded-live</sub></summary>+<summary><b>ブローカー connectors</b> <sub>15 ブローカー — read + paper、対応先では bounded-live</sub></summary>connector-first のプロファイル。多くは read + ペーパー口座での発注に対応します —— IBKR は読み取り専用、Robinhood はライブのみ(ペーパー口座なし)、Trading 212 はペーパーを含め発注を一切拒否します。ライブ発注はユーザーが定義した mandate(銘柄許可リスト、発注サイズ / エクスポージャー上限、1 日の取引回数上限、即時 kill switch)で制限され、資金を預かることは一切ありません —— 執行するのはブローカーです。発注系ツールは MCP に公開されません(agent + CLI のみ)。リサーチ / バックテスト経路は構造的にあらゆるライブ endpoint から遮断されています。@@ -560,6 +560,7 @@ connector-first のプロファイル。多くは read + ペーパー口座で| **Futu** | HK / US / A | read + paper + bounded live || **eToro** | global | read + paper + bounded live(Public API;demo キーは構造上 `/demo` パスにしか到達せず、コピートレードのワークフローにも対応) || **MetaTrader 5** | forex / CFD | read + paper + bounded live (Exness-style; demo ⇔ paper identity guard) |+| **KIS**(韓国投資証券) | 韓国 (KOSPI/KOSDAQ) | read + 本物のペーパー(모의투자、別ホストの本物のブローカー側サンドボックス)—— このマーケットのライブ発注は未対応 || **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** | US / HK · India (NSE/BSE) | read + paper only — no runtime paper/live discriminator, so live order placement is hard-refused || **Trading 212** | UK / EU | fully read-only — `place_order` / `cancel_order` hard-refuse even paper |diff --git a/README_ko.md b/README_ko.mdindex ab040629c..da462b3bd 100644--- a/README_ko.md+++ b/README_ko.md@@ -546,7 +546,7 @@ clone에서 실행하세요(`pip install -e .`).</details><details>-<summary><b>브로커 커넥터</b> <sub>14개 브로커 — read + paper, 지원 시 bounded-live</sub></summary>+<summary><b>브로커 커넥터</b> <sub>15개 브로커 — read + paper, 지원 시 bounded-live</sub></summary>connector-first 프로필. 대부분의 브로커가 read + 페이퍼 계정 주문 실행을 지원하지만 IBKR은 읽기 전용이고, Robinhood는 페이퍼 계정 없이 실거래 전용이며, Trading 212는 페이퍼를 포함해 주문 실행을 모두 거부하고, 실거래 주문 실행은 사용자 정의 mandate(심볼 허용목록, 주문 크기 / 익스포저 상한, 일일 거래 한도, 즉시 kill switch)로 제한되고 자금을 보관하지 않습니다 — 실행은 브로커가 합니다. 주문 실행 도구는 MCP에 노출되지 않습니다(agent + CLI 전용). 리서치 / 백테스트 경로는 구조적으로 모든 실거래 엔드포인트에서 차단됩니다.@@ -560,6 +560,7 @@ connector-first 프로필. 대부분의 브로커가 read + 페이퍼 계정 주| **Futu** | HK / US / A | read + paper + bounded live || **eToro** | global | read + paper + bounded live (Public API; demo 키는 구조적으로 `/demo` 경로에만 도달하며, 카피 트레이딩 워크플로도 지원) || **MetaTrader 5** | forex / CFD | read + paper + bounded live (Exness-style; demo ⇔ paper identity guard) |+| **KIS** (한국투자증권) | 한국 (KOSPI/KOSDAQ) | read + 진짜 페이퍼(모의투자 — 별도 호스트의 실제 증권사 사이드 샌드박스) — 이 시장의 실거래 주문 실행은 아직 연결되지 않음 || **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** | US / HK · India (NSE/BSE) | read + paper only — no runtime paper/live discriminator, so live order placement is hard-refused || **Trading 212** | UK / EU | fully read-only — `place_order` / `cancel_order` hard-refuse even paper |diff --git a/README_zh.md b/README_zh.mdindex 676c2ee11..b844e9908 100644--- a/README_zh.md+++ b/README_zh.md@@ -559,7 +559,7 @@ LONGBRIDGE_ACCESS_TOKEN=...</details><details>-<summary><b>Broker Connectors</b> <sub>14 家券商——读取 + 模拟盘,支持的券商可受约束实盘</sub></summary>+<summary><b>Broker Connectors</b> <sub>15 家券商——读取 + 模拟盘,支持的券商可受约束实盘</sub></summary>连接器优先(connector-first)的配置档。多数连接器支持读取 + 模拟盘下单 —— IBKR 只读,Robinhood 只有实盘(没有模拟盘),Trading 212 连模拟盘下单也一律拒绝;实盘下单受用户定义的 mandate 约束(标的白名单、下单规模 / 敞口上限、每日交易次数上限、即时 kill switch),且从不托管资金——由券商执行。下单类工具不经 MCP 暴露(仅 agent + CLI)。研究 / 回测路径在结构上被隔离,无法触达任何实盘端点。@@ -573,6 +573,7 @@ LONGBRIDGE_ACCESS_TOKEN=...| **Futu** | HK / US / A | 读取 + 模拟盘 + 受约束实盘 || **eToro** | global | 读取 + 模拟盘 + 受约束实盘(Public API;demo 密钥在结构上只能访问 `/demo` 路径,另支持跟单交易流程) || **MetaTrader 5** | forex / CFD | 读取 + 模拟盘 + 受约束实盘(Exness 风格;demo ⇔ 模拟盘身份守卫) |+| **KIS** | 韩国 (KOSPI/KOSDAQ) | 读取 + 真实模拟盘(모의투자,独立主机上的真实券商侧沙盒)——该市场的实盘下单尚未接入 || **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** | US / HK · India (NSE/BSE) | 仅读取 + 模拟盘——无运行时模拟/实盘判别标识,因此实盘下单被硬拒 || **Trading 212** | UK / EU | 完全只读——`place_order` / `cancel_order` 连模拟盘也硬拒 |diff --git a/agent/SKILL.md b/agent/SKILL.mdindex beaa3950e..c62a2bfdb 100644--- a/agent/SKILL.md+++ b/agent/SKILL.md@@ -89,7 +89,7 @@ Create and run quantitative strategies across 10 engines (ChinaA, GlobalEquity,- **Premium cross-market data** via QVeris (optional API key)- **Premium US data** via optional-key finnhub / alphavantage / tiingo / fmp (graceful fallback to free sources)-Factors: the Alpha101 and QLib158 zoos are tagged for the `equity_in` and `equity_kr` universes, so they compute on NSE/BSE and KRX bars (the GTJA191 zoo stays China-only). Live/paper India trading uses the Shoonya / Dhan connectors (paper + read-only live; live order placement is structurally disabled because those brokers expose no paper/live switch).+Factors: the Alpha101 and QLib158 zoos are tagged for the `equity_in` and `equity_kr` universes, so they compute on NSE/BSE and KRX bars (the GTJA191 zoo stays China-only). Live/paper India trading uses the Shoonya / Dhan connectors (paper + read-only live; live order placement is structurally disabled because those brokers expose no paper/live switch). Live/paper Korea equity trading uses the **KIS** connector (한국투자증권; genuine 모의투자 paper sandbox on a separate host/port from 실전투자 live, plus read-only live — no mandate-gated live-trade profile yet).Example workflow:1. Use `list_skills()` to discover strategy patternsdiff --git a/agent/src/live/registry.py b/agent/src/live/registry.pyindex d6ca9fd21..defcbf74a 100644--- a/agent/src/live/registry.py+++ b/agent/src/live/registry.py@@ -28,6 +28,7 @@ from src.trading.connectors.binance.classification import BINANCE_TOOL_CLASSfrom src.trading.connectors.dhan.classification import DHAN_TOOL_CLASSfrom src.trading.connectors.futu.classification import FUTU_TOOL_CLASSfrom src.trading.connectors.ibkr.classification import IBKR_TOOL_CLASS+from src.trading.connectors.kis.classification import KIS_TOOL_CLASSfrom src.trading.connectors.longbridge.classification import LONGBRIDGE_TOOL_CLASSfrom src.trading.connectors.mt5.classification import MT5_TOOL_CLASSfrom src.trading.connectors.okx.classification import OKX_TOOL_CLASS@@ -59,6 +60,7 @@ _BROKER_CURATED_MAPS = {"mt5": MT5_TOOL_CLASS,"etoro": ETORO_TOOL_CLASS,"zerodha": ZERODHA_TOOL_CLASS,+ "kis": KIS_TOOL_CLASS,}diff --git a/agent/src/trading/connectors/kis/__init__.py b/agent/src/trading/connectors/kis/__init__.pynew file mode 100644index 000000000..2d3b47a46--- /dev/null+++ b/agent/src/trading/connectors/kis/__init__.py@@ -0,0 +1,10 @@+"""Korea Investment & Securities (한국투자증권 KIS) trading connector.++Read-only and genuine broker-side paper account access via the official KIS+Developers REST API (OAuth2 client-credentials token, no third-party SDK+required). A ``broker_sdk`` transport for Korean equities (KRX: KOSPI/KOSDAQ).++Unlike Dhan/Upbit, KIS exposes a REAL structural paper/live discriminator:+paper (모의투자) and live (실전투자) accounts are reached through entirely+different hosts, so a paper-declared profile can never reach the live host.+"""diff --git a/agent/src/trading/connectors/kis/classification.py b/agent/src/trading/connectors/kis/classification.pynew file mode 100644index 000000000..64948d4bb--- /dev/null+++ b/agent/src/trading/connectors/kis/classification.py@@ -0,0 +1,23 @@+"""Curated read/write classification for KIS SDK operations.++Keys are the connector's own operation names. Order-mutating SDK calls are+pinned WRITE so the live gate never treats them as plain reads; anything+unlisted and not a known read is treated as WRITE (fail-closed) by the gate.+"""++from __future__ import annotations++from src.live.classification import ToolClass++#: KIS REST operation read/write catalog.+KIS_TOOL_CLASS: dict[str, ToolClass] = {+ # READ+ "get_account_snapshot": ToolClass.READ,+ "get_positions": ToolClass.READ,+ "get_open_orders": ToolClass.READ,+ "get_quote": ToolClass.READ,+ "get_historical_bars": ToolClass.READ,+ # WRITE+ "place_order": ToolClass.WRITE,+ "cancel_order": ToolClass.WRITE,+}diff --git a/agent/src/trading/connectors/kis/profiles.py b/agent/src/trading/connectors/kis/profiles.pynew file mode 100644index 000000000..15cd0e4f4--- /dev/null+++ b/agent/src/trading/connectors/kis/profiles.py@@ -0,0 +1,67 @@+"""Built-in Korea Investment & Securities (KIS) connector profiles.++KIS (https://apiportal.koreainvestment.com) is a Korean broker with free API+access and a REAL structural paper/live discriminator: paper (모의투자) and+live (실전투자) accounts are reached through entirely different hosts, each+with its own OAuth token. Unlike Dhan/Upbit, the paper profile here places+GENUINE orders against KIS's own paper-trading server — not a local+simulation — because the host separation makes that safe.++This initial contribution deliberately ships paper (read + trade) and+live-readonly only, mirroring the Dhan/Shoonya precedent for a first+connector into a new market: no live order placement, even though KIS's host+separation would technically support a mandate-gated live-trade profile like+Alpaca's. Wiring that up would need a new ``AssetClass.KR_EQUITY`` in the+mandate model (``src/live/mandate/model.py``) and is left for a follow-up.+"""++from __future__ import annotations++from src.trading.types import READ_CAPABILITIES, TradingProfile++KIS_PROFILES: tuple[TradingProfile, ...] = (+ TradingProfile(+ id="kis-paper-sdk",+ connector="kis",+ label="KIS Paper · REST (Korea)",+ environment="paper",+ transport="broker_sdk",+ capabilities=READ_CAPABILITIES,+ readonly=True,+ config={"profile": "paper"},+ notes=(+ "Reads a genuine KIS 모의투자 (paper) account via KIS's own paper "+ "host — a real sandbox, not local simulation."+ ),+ ),+ TradingProfile(+ id="kis-paper-trade",+ connector="kis",+ label="KIS Paper · REST Trade (Korea)",+ environment="paper",+ transport="broker_sdk",+ capabilities=READ_CAPABILITIES + ("orders.place",),+ readonly=False,+ config={"profile": "paper"},+ notes=(+ "Places orders against KIS's own 모의투자 (paper) trading server — "+ "a real broker-side sandbox account, not a local simulation. No "+ "real money is at risk; the paper host is structurally separate "+ "from the live host."+ ),+ ),+ TradingProfile(+ id="kis-live-sdk-readonly",+ connector="kis",+ label="KIS Live · REST Read-Only (Korea)",+ environment="live",+ transport="broker_sdk",+ capabilities=READ_CAPABILITIES,+ readonly=True,+ config={"profile": "live-readonly"},+ notes=(+ "Reads a live KIS account (account, positions, orders, quotes, "+ "history). Order placement is not exposed in this profile."+ ),+ ),+)diff --git a/agent/src/trading/connectors/kis/sdk.py b/agent/src/trading/connectors/kis/sdk.pynew file mode 100644index 000000000..ef42572b8--- /dev/null+++ b/agent/src/trading/connectors/kis/sdk.py@@ -0,0 +1,764 @@+"""Read-only + genuine-paper KIS connector via the official REST API.++Wraps Korea Investment & Securities' (한국투자증권) KIS Developers REST API for+account balance, positions, order history, quotes, and historical bars, plus+order placement/cancellation in the paper profile. No third-party SDK is+required — ``requests`` only, following the public API guide at+https://apiportal.koreainvestment.com and the official example repo+https://github.com/koreainvestment/open-trading-api.++Paper-vs-live is a REAL structural guard: paper (모의투자) and live (실전투자)+accounts are reached through entirely different hosts/ports, each issuing its+own OAuth token scoped to that host. A paper-declared config can therefore+never place an order against the live host — unlike Dhan/Upbit, this is not+an operator-trust convention, it is enforced by which URL the request goes to.++Caveat: TR_ID codes and field names below were sourced from the official KIS+example repository and public documentation, not verified against a live KIS+account (this connector was authored without KIS credentials). Verify against+https://apiportal.koreainvestment.com before relying on this in production.+"""++from __future__ import annotations++import json+import time+from dataclasses import asdict, dataclass+from pathlib import Path+from typing import Any, Mapping++import requests++from src.config.paths import get_runtime_root++CONFIG_FILENAME = "kis.json"++PROFILE_ENVIRONMENTS = {+ "paper": "paper",+ "live-readonly": "live",+}++#: Real per-environment hosts (the structural paper/live discriminator).+BASE_URLS = {+ "paper": "https://openapivts.koreainvestment.com:29443",+ "live": "https://openapi.koreainvestment.com:9443",+}++#: TR_ID transaction codes, per KIS Developers docs. Price/chart codes are+#: shared across both environments; trading codes are environment-specific.+_TR_BALANCE = {"paper": "VTTC8434R", "live": "TTTC8434R"}+_TR_ORDER_BUY = {"paper": "VTTC0012U", "live": "TTTC0012U"}+_TR_ORDER_SELL = {"paper": "VTTC0011U", "live": "TTTC0011U"}+_TR_ORDER_CANCEL = {"paper": "VTTC0013U", "live": "TTTC0013U"}+_TR_DAILY_CCLD = {"paper": "VTTC0081R", "live": "TTTC0081R"}+_TR_PRICE = "FHKST01010100"+_TR_CHART = "FHKST03010100"++#: KRX market division code used by every quotations call.+_MARKET_DIV_KRX = "J"+#: Exchange id division code required by order-cash since the 2024 API rev.+_EXCHANGE_ID_KRX = "KRX"++#: Safety margin subtracted from the token's reported TTL before it is+#: treated as expired, so a request never races an in-flight expiry.+_TOKEN_REFRESH_MARGIN_SECONDS = 120+++class KISConfigError(RuntimeError):+ """Raised when the connector configuration is missing or invalid."""+++class KISAPIError(RuntimeError):+ """Raised when KIS returns an auth, HTTP, network, or JSON error."""+++@dataclass(frozen=True)+class KISConfig:+ """KIS connector connection settings.++ Args:+ app_key: KIS Developers App Key.+ app_secret: KIS Developers App Secret.+ account_no: 8-digit account number (CANO), e.g. ``"12345678"``.+ account_product_code: 2-digit account product code (ACNT_PRDT_CD),+ e.g. ``"01"``.+ profile: ``paper`` or ``live-readonly``.+ timeout: Network timeout in seconds.+ readonly: Whether order placement is disabled.+ """++ app_key: str = ""+ app_secret: str = ""+ account_no: str = ""+ account_product_code: str = "01"+ profile: str = "paper"+ timeout: float = 15.0+ readonly: bool = True++ @classmethod+ def from_mapping(cls, data: Mapping[str, Any] | None = None) -> "KISConfig":+ """Build a config from a JSON-like mapping."""+ payload = dict(data or {})+ profile = str(payload.get("profile") or "paper").strip().lower()+ if profile not in PROFILE_ENVIRONMENTS:+ raise KISConfigError("profile must be 'paper' or 'live-readonly'")+ return cls(+ app_key=str(payload.get("app_key") or "").strip(),+ app_secret=str(payload.get("app_secret") or "").strip(),+ account_no=str(payload.get("account_no") or "").strip(),+ account_product_code=str(payload.get("account_product_code") or "01").strip(),+ profile=profile,+ timeout=float(payload.get("timeout") or 15.0),+ readonly=bool(payload.get("readonly", True)),+ )++ def with_overrides(+ self,+ *,+ app_key: str | None = None,+ app_secret: str | None = None,+ account_no: str | None = None,+ account_product_code: str | None = None,+ profile: str | None = None,+ ) -> "KISConfig":+ """Return a copy with CLI/tool overrides applied."""+ payload = asdict(self)+ if app_key is not None:+ payload["app_key"] = app_key+ if app_secret is not None:+ payload["app_secret"] = app_secret+ if account_no is not None:+ payload["account_no"] = account_no+ if account_product_code is not None:+ payload["account_product_code"] = account_product_code+ if profile is not None:+ payload["profile"] = profile+ return KISConfig.from_mapping(payload)++ @property+ def environment(self) -> str:+ return PROFILE_ENVIRONMENTS.get(self.profile, "paper")++ @property+ def is_paper(self) -> bool:+ return self.environment == "paper"++ @property+ def base_url(self) -> str:+ return BASE_URLS[self.environment]+++_OVERRIDE_KEYS = ("app_key", "app_secret", "account_no", "account_product_code", "profile")+++def build_config(+ profile_config: Mapping[str, Any] | None = None,+ overrides: Mapping[str, Any] | None = None,+) -> "KISConfig":+ """Resolve config: saved file ← profile defaults ← CLI overrides."""+ base = asdict(load_config())+ for key, value in dict(profile_config or {}).items():+ if value is not None:+ base[key] = value+ cfg = KISConfig.from_mapping(base)+ clean = {+ k: v+ for k, v in dict(overrides or {}).items()+ if k in _OVERRIDE_KEYS and v not in (None, "")+ }+ return cfg.with_overrides(**clean) if clean else cfg+++def config_path() -> Path:+ return get_runtime_root() / CONFIG_FILENAME+++def load_config() -> KISConfig:+ path = config_path()+ if not path.exists():+ return KISConfig()+ try:+ return KISConfig.from_mapping(json.loads(path.read_text(encoding="utf-8")))+ except (OSError, ValueError, json.JSONDecodeError) as exc:+ raise KISConfigError(f"invalid KIS config at {path}: {exc}") from exc+++def save_config(config: KISConfig) -> Path:+ path = config_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(+ json.dumps(asdict(config), indent=2, ensure_ascii=False) + "\n",+ encoding="utf-8",+ )+ try:+ path.chmod(0o600)+ except OSError:+ pass+ return path+++# ---------------------------------------------------------------------------+# Five read operations + order placement (paper only)+# ---------------------------------------------------------------------------+++def check_status(config: KISConfig | None = None) -> dict[str, Any]:+ """Check REST readiness and config completeness without mutating broker state."""+ cfg = config or load_config()+ report: dict[str, Any] = {+ "status": "ok",+ "config": _public_config(cfg),+ "sdk": {"package": "requests", "installed": True},+ "host": cfg.base_url,+ }++ missing = _missing_fields(cfg)+ if missing:+ report["status"] = "error"+ report["error"] = f"KIS connector not configured: missing {', '.join(missing)}."+ return report++ try:+ get_account_snapshot(cfg) # connectivity probe; result unused+ except (KISConfigError, KISAPIError) as exc:+ report["status"] = "error"+ report["error"] = str(exc)+ return report++ report["account"] = {"profile": cfg.profile, "is_paper": cfg.is_paper}+ return report+++def get_account_snapshot(config: KISConfig | None = None) -> dict[str, Any]:+ """Fetch cash/valuation summary (account.summary, ``output2``) for the account."""+ cfg = config or load_config()+ payload = _balance(cfg)+ summary = _first_row(payload.get("output2"))++ return {+ "status": "ok",+ "profile": cfg.profile,+ "is_paper": cfg.is_paper,+ "host": cfg.base_url,+ "account": {+ "currency": "KRW",+ "cash": _as_float(summary.get("dnca_tot_amt")),+ "settlement_cash": _as_float(summary.get("prvs_rcdl_excc_amt")),+ "total_evaluation": _as_float(summary.get("tot_evlu_amt")),+ "purchase_amount": _as_float(summary.get("pchs_amt_smtl_amt")),+ "unrealized_pnl": _as_float(summary.get("evlu_pfls_smtl_amt")),+ },+ }+++def get_positions(config: KISConfig | None = None) -> dict[str, Any]:+ """Fetch current KRX equity holdings (``output1``)."""+ cfg = config or load_config()+ payload = _balance(cfg)+ rows = []+ for item in _as_list(payload.get("output1")):+ quantity = _as_float(item.get("hldg_qty"))+ if quantity <= 0:+ continue+ rows.append({+ "symbol": item.get("pdno", ""),+ "name": item.get("prdt_name", ""),+ "quantity": quantity,+ "average_cost": _as_float(item.get("pchs_avg_pric")),+ "current_price": _as_float(item.get("prpr")),+ "unrealized_pnl": _as_float(item.get("evlu_pfls_amt")),+ "unrealized_pnl_rate": _as_float(item.get("evlu_pfls_rt")),+ })++ return {"status": "ok", "profile": cfg.profile, "is_paper": cfg.is_paper, "positions": rows}+++def get_open_orders(+ config: KISConfig | None = None,+ *,+ include_executions: bool = False,+) -> dict[str, Any]:+ """Fetch today's orders, split into still-open vs already-executed."""+ cfg = config or load_config()+ today = time.strftime("%Y%m%d")+ payload = _get(+ cfg,+ "/uapi/domestic-stock/v1/trading/inquire-daily-ccld",+ tr_id=_TR_DAILY_CCLD[cfg.environment],+ params={+ "CANO": cfg.account_no,+ "ACNT_PRDT_CD": cfg.account_product_code,+ "INQR_STRT_DT": today,+ "INQR_END_DT": today,+ "SLL_BUY_DVSN_CD": "00",+ "CCLD_DVSN": "00",+ "ORD_GNO_BRNO": "",+ "ODNO": "",+ "INQR_DVSN_3": "00",+ "INQR_DVSN_1": "",+ "INQR_DVSN": "00",+ "EXCG_ID_DVSN_CD": _EXCHANGE_ID_KRX,+ "CTX_AREA_FK100": "",+ "CTX_AREA_NK100": "",+ },+ )++ open_orders, executions = [], []+ for item in _as_list(payload.get("output1")):+ row = _order_to_dict(item)+ remaining = _as_float(item.get("rmn_qty"))+ if remaining > 0:+ open_orders.append(row)+ elif include_executions:+ executions.append(row)++ result: dict[str, Any] = {+ "status": "ok",+ "profile": cfg.profile,+ "is_paper": cfg.is_paper,+ "open_orders": open_orders,+ }+ if include_executions:+ result["executions"] = executions+ return result+++def get_quote(symbol: str, *, config: KISConfig | None = None, **_: Any) -> dict[str, Any]:+ """Fetch the current price snapshot for a 6-digit KRX ticker."""+ cfg = config or load_config()+ ticker = str(symbol or "").strip().upper()++ try:+ payload = _get(+ cfg,+ "/uapi/domestic-stock/v1/quotations/inquire-price",+ tr_id=_TR_PRICE,+ params={"FID_COND_MRKT_DIV_CODE": _MARKET_DIV_KRX, "FID_INPUT_ISCD": ticker},+ )+ except KISAPIError as exc:+ return {"status": "error", "error": str(exc), "symbol": ticker}++ row = payload.get("output") or {}+ return {+ "status": "ok",+ "symbol": ticker,+ "quote": {+ "last": _as_float(row.get("stck_prpr")),+ "open": _as_float(row.get("stck_oprc")),+ "high": _as_float(row.get("stck_hgpr")),+ "low": _as_float(row.get("stck_lwpr")),+ "prev_close": _as_float(row.get("stck_sdpr")),+ "change_rate": _as_float(row.get("prdy_ctrt")),+ "volume": _as_float(row.get("acml_vol")),+ },+ }+++def get_historical_bars(+ symbol: str,+ *,+ config: KISConfig | None = None,+ period: str = "1d",+ limit: int = 100,+) -> dict[str, Any]:+ """Fetch daily/weekly/monthly OHLCV bars for a 6-digit KRX ticker.++ ``period`` tokens: ``1d``/``1D`` → daily, ``1w`` → weekly, ``1M`` →+ monthly. Intraday periods are not exposed by this endpoint and fail+ closed instead of silently substituting daily bars.+ """+ cfg = config or load_config()+ ticker = str(symbol or "").strip().upper()+ token = period.strip()+ period_code = {"1d": "D", "1D": "D", "1w": "W", "1M": "M"}.get(token)+ if period_code is None:+ return {+ "status": "error",+ "error": f"unsupported period: {period!r}; supported: ['1d', '1w', '1M']",+ "symbol": ticker,+ }++ end = time.strftime("%Y%m%d")+ try:+ payload = _get(+ cfg,+ "/uapi/domestic-stock/v1/quotations/inquire-daily-itemchartprice",+ tr_id=_TR_CHART,+ params={+ "FID_COND_MRKT_DIV_CODE": _MARKET_DIV_KRX,+ "FID_INPUT_ISCD": ticker,+ "FID_INPUT_DATE_1": "19900101",+ "FID_INPUT_DATE_2": end,+ "FID_PERIOD_DIV_CODE": period_code,+ "FID_ORG_ADJ_PRC": "0",+ },+ )+ except KISAPIError as exc:+ return {"status": "error", "error": str(exc), "symbol": ticker}++ bars = [_bar_to_dict(item) for item in reversed(_as_list(payload.get("output2")))]+ capped = max(int(limit), 0)+ return {"status": "ok", "symbol": ticker, "period": period, "bars": bars[-capped:] if capped else []}+++def place_order(+ config: KISConfig | None = None,+ *,+ symbol: str,+ side: str,+ quantity: float | None = None,+ notional: float | None = None,+ order_type: str = "market",+ limit_price: float | None = None,+ time_in_force: str = "day",+) -> dict[str, Any]:+ """Place an order against the account matching ``config``'s environment.++ Paper-vs-live is structural: :func:`_get`/:func:`_post` send the request to+ ``config.base_url``, which is the paper host for a ``paper`` profile and+ the live host for a ``live-readonly`` profile — but ``live-readonly``+ profiles set ``readonly=True`` and never reach this function (the caller,+ ``src.trading.service.place_order``, refuses before calling any connector).+ So in practice only a genuine KIS paper (모의투자) account is ever ordered+ against here.++ Args:+ symbol: 6-digit KRX ticker, e.g. ``"005930"``.+ side: ``buy`` or ``sell``.+ quantity: Share quantity (KIS trades whole shares only).+ order_type: ``market`` or ``limit``.+ limit_price: Required for limit orders.+ """+ cfg = config or load_config()++ ticker = str(symbol or "").strip().upper()+ if not ticker:+ return {"status": "error", "error": "symbol is required"}++ side_token = str(side or "").strip().lower()+ if side_token not in ("buy", "sell"):+ return {"status": "error", "error": "side must be 'buy' or 'sell'"}++ type_token = str(order_type or "").strip().lower()+ if type_token not in ("market", "limit"):+ return {"status": "error", "error": "order_type must be 'market' or 'limit'"}++ if notional is not None:+ return {"status": "error", "error": "KIS requires a share quantity; notional-based sizing is not supported"}+ if quantity is None or float(quantity) < 1:+ return {"status": "error", "error": "quantity must be a positive whole number of shares"}+ qty = int(float(quantity))++ if type_token == "limit" and limit_price is None:+ return {"status": "error", "error": "limit order requires limit_price"}++ ord_dvsn = "00" if type_token == "limit" else "01" # 00=지정가, 01=시장가+ unit_price = str(int(limit_price)) if type_token == "limit" else "0"+ tr_id = (_TR_ORDER_BUY if side_token == "buy" else _TR_ORDER_SELL)[cfg.environment]++ payload = _post(+ cfg,+ "/uapi/domestic-stock/v1/trading/order-cash",+ tr_id=tr_id,+ body={+ "CANO": cfg.account_no,+ "ACNT_PRDT_CD": cfg.account_product_code,+ "PDNO": ticker,+ "ORD_DVSN": ord_dvsn,+ "ORD_QTY": str(qty),+ "ORD_UNPR": unit_price,+ "EXCG_ID_DVSN_CD": _EXCHANGE_ID_KRX,+ },+ )++ output = payload.get("output") or {}+ return {+ "status": "ok" if str(payload.get("rt_cd")) == "0" else "error",+ "error": None if str(payload.get("rt_cd")) == "0" else str(payload.get("msg1") or "order rejected"),+ "order_id": output.get("ODNO", ""),+ "order_branch": output.get("KRX_FWDG_ORD_ORGNO", ""),+ "symbol": ticker,+ "side": side_token,+ "profile": cfg.profile,+ "is_paper": cfg.is_paper,+ "order_type": type_token,+ "quantity": qty,+ "limit_price": float(limit_price) if type_token == "limit" else None,+ }+++def cancel_order(+ config: KISConfig | None = None,+ order_id: str = "",+ *,+ symbol: str | None = None,+ order_branch: str = "",+ quantity: float | None = None,+) -> dict[str, Any]:+ """Cancel a resting order via the KIS order-modify/cancel endpoint.++ Args:+ order_id: The broker order number (``ODNO``) from :func:`place_order`.+ order_branch: The branch code (``KRX_FWDG_ORD_ORGNO``) returned+ alongside ``order_id`` by :func:`place_order` — KIS requires it to+ identify which order to cancel.+ quantity: Quantity to cancel; omit or ``0`` to cancel the full+ remaining quantity (``전량``).+ """+ cfg = config or load_config()++ clean_id = str(order_id or "").strip()+ if not clean_id:+ return {"status": "error", "error": "order_id is required"}+ if not order_branch:+ return {"status": "error", "error": "order_branch (KRX_FWDG_ORD_ORGNO) is required"}+ if quantity is not None and 0 < float(quantity) < 1:+ return {"status": "error", "error": "quantity must be 0 (cancel all) or a whole number of shares"}++ qty = int(float(quantity)) if quantity else 0+ payload = _post(+ cfg,+ "/uapi/domestic-stock/v1/trading/order-rvsecncl",+ tr_id=_TR_ORDER_CANCEL[cfg.environment],+ body={+ "CANO": cfg.account_no,+ "ACNT_PRDT_CD": cfg.account_product_code,+ "KRX_FWDG_ORD_ORGNO": order_branch,+ "ORGN_ODNO": clean_id,+ "ORD_DVSN": "00",+ "RVSE_CNCL_DVSN_CD": "02", # 02=취소+ "ORD_QTY": str(qty),+ "ORD_UNPR": "0",+ "QTY_ALL_ORD_YN": "N" if qty else "Y",+ },+ )++ ok = str(payload.get("rt_cd")) == "0"+ return {+ "status": "ok" if ok else "error",+ "error": None if ok else str(payload.get("msg1") or "cancel rejected"),+ "order_id": clean_id,+ "symbol": symbol.strip().upper() if isinstance(symbol, str) and symbol.strip() else None,+ "profile": cfg.profile,+ "is_paper": cfg.is_paper,+ "cancelled": ok,+ }+++# ---------------------------------------------------------------------------+# SDK plumbing+# ---------------------------------------------------------------------------+++def _balance(cfg: KISConfig) -> dict[str, Any]:+ return _get(+ cfg,+ "/uapi/domestic-stock/v1/trading/inquire-balance",+ tr_id=_TR_BALANCE[cfg.environment],+ params={+ "CANO": cfg.account_no,+ "ACNT_PRDT_CD": cfg.account_product_code,+ "AFHR_FLPR_YN": "N",+ "OFL_YN": "",+ "INQR_DVSN": "02",+ "UNPR_DVSN": "01",+ "FUND_STTL_ICLD_YN": "N",+ "FNCG_AMT_AUTO_RDPT_YN": "N",+ "PRCS_DVSN": "01",+ "CTX_AREA_FK100": "",+ "CTX_AREA_NK100": "",+ },+ )+++def _token_cache_path(cfg: KISConfig) -> Path:+ return get_runtime_root() / f"kis-token-{cfg.environment}.json"+++def _access_token(cfg: KISConfig) -> str:+ """Return a cached or freshly issued OAuth token for ``cfg``'s host.++ KIS rate-limits token issuance to once per minute, so a valid cached token+ (keyed by the configured app_key, with a safety margin before its reported+ expiry) is always preferred over a fresh call.+ """+ path = _token_cache_path(cfg)+ now = time.time()+ if path.exists():+ try:+ cached = json.loads(path.read_text(encoding="utf-8"))+ if (+ cached.get("app_key") == cfg.app_key+ and float(cached.get("expires_at", 0)) > now+ ):+ return str(cached["access_token"])+ except (OSError, ValueError, json.JSONDecodeError, KeyError):+ pass++ try:+ response = requests.post(+ f"{cfg.base_url}/oauth2/tokenP",+ json={"grant_type": "client_credentials", "appkey": cfg.app_key, "appsecret": cfg.app_secret},+ headers={"content-type": "application/json; charset=utf-8"},+ timeout=cfg.timeout,+ )+ except requests.RequestException as exc:+ raise KISAPIError(f"KIS token request failed: {exc}") from exc+ if response.status_code >= 400:+ raise KISAPIError(f"KIS token issuance returned HTTP {response.status_code}: {_error_message(response)}")++ body = response.json()+ token = str(body.get("access_token") or "")+ if not token:+ raise KISAPIError(f"KIS token issuance returned no access_token: {body}")+ expires_in = float(body.get("expires_in") or 0)++ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(+ json.dumps({+ "app_key": cfg.app_key,+ "access_token": token,+ "expires_at": now + max(expires_in - _TOKEN_REFRESH_MARGIN_SECONDS, 0),+ }),+ encoding="utf-8",+ )+ try:+ path.chmod(0o600)+ except OSError:+ pass+ return token+++def _headers(cfg: KISConfig, tr_id: str) -> dict[str, str]:+ return {+ "content-type": "application/json; charset=utf-8",+ "authorization": f"Bearer {_access_token(cfg)}",+ "appkey": cfg.app_key,+ "appsecret": cfg.app_secret,+ "tr_id": tr_id,+ "custtype": "P",+ }+++def _get(cfg: KISConfig, path: str, *, tr_id: str, params: Mapping[str, Any]) -> dict[str, Any]:+ return _request(cfg, "GET", path, tr_id=tr_id, params=params)+++def _post(cfg: KISConfig, path: str, *, tr_id: str, body: Mapping[str, Any]) -> dict[str, Any]:+ return _request(cfg, "POST", path, tr_id=tr_id, body=body)+++def _request(+ cfg: KISConfig,+ method: str,+ path: str,+ *,+ tr_id: str,+ params: Mapping[str, Any] | None = None,+ body: Mapping[str, Any] | None = None,+) -> dict[str, Any]:+ missing = _missing_fields(cfg)+ if missing:+ raise KISConfigError(f"KIS connector not configured: missing {', '.join(missing)}.")++ try:+ response = requests.request(+ method.upper(),+ f"{cfg.base_url}{path}",+ headers=_headers(cfg, tr_id),+ params=dict(params or {}),+ json=dict(body) if body is not None else None,+ timeout=cfg.timeout,+ )+ except requests.RequestException as exc:+ raise KISAPIError(f"KIS request failed: {exc}") from exc++ if response.status_code in (401, 403):+ raise KISAPIError("KIS API authentication failed: check app_key/app_secret.")+ if response.status_code >= 400:+ raise KISAPIError(f"KIS API returned HTTP {response.status_code}: {_error_message(response)}")+ try:+ return response.json()+ except ValueError as exc:+ raise KISAPIError("KIS API returned invalid JSON.") from exc+++def _error_message(response: requests.Response) -> str:+ try:+ payload = response.json()+ except ValueError:+ return response.text.strip() or response.reason or "request failed"+ if isinstance(payload, Mapping):+ for key in ("msg1", "error_description", "message"):+ value = payload.get(key)+ if value:+ return str(value)+ return str(payload)+++def _missing_fields(cfg: KISConfig) -> list[str]:+ missing = []+ if not cfg.app_key:+ missing.append("app_key")+ if not cfg.app_secret:+ missing.append("app_secret")+ if not cfg.account_no:+ missing.append("account_no")+ return missing+++def _public_config(cfg: KISConfig) -> dict[str, Any]:+ data = asdict(cfg)+ if data.get("app_key"):+ data["app_key"] = data["app_key"][:6] + "***"+ if data.get("app_secret"):+ data["app_secret"] = "***redacted***"+ return data+++def _first_row(value: Any) -> dict[str, Any]:+ rows = _as_list(value)+ return dict(rows[0]) if rows and isinstance(rows[0], Mapping) else {}+++def _as_list(value: Any) -> list[Any]:+ if value is None:+ return []+ if isinstance(value, (list, tuple)):+ return list(value)+ return [value]+++def _as_float(value: Any) -> float:+ try:+ return float(value)+ except (TypeError, ValueError):+ return 0.0+++def _order_to_dict(item: Any) -> dict[str, Any]:+ return {+ "order_id": item.get("odno", ""),+ "order_branch": item.get("ord_gno_brno", ""),+ "symbol": item.get("pdno", ""),+ "name": item.get("prdt_name", ""),+ "side": "buy" if str(item.get("sll_buy_dvsn_cd_name", "")).find("매수") >= 0 else "sell",+ "order_type": item.get("ord_dvsn_name", ""),+ "quantity": _as_float(item.get("ord_qty")),+ "filled_quantity": _as_float(item.get("tot_ccld_qty")),+ "remaining_quantity": _as_float(item.get("rmn_qty")),+ "price": _as_float(item.get("ord_unpr")),+ "avg_fill_price": _as_float(item.get("avg_prvs")),+ "ordered_at": item.get("ord_tmd", ""),+ }+++def _bar_to_dict(item: Any) -> dict[str, Any]:+ return {+ "time": item.get("stck_bsop_date"),+ "open": _as_float(item.get("stck_oprc")),+ "high": _as_float(item.get("stck_hgpr")),+ "low": _as_float(item.get("stck_lwpr")),+ "close": _as_float(item.get("stck_clpr")),+ "volume": _as_float(item.get("acml_vol")),+ }diff --git a/agent/src/trading/onboarding.py b/agent/src/trading/onboarding.pyindex a488e3381..157b06d64 100644--- a/agent/src/trading/onboarding.py+++ b/agent/src/trading/onboarding.py@@ -94,6 +94,21 @@ _BUILTIN: dict[str, ConnectorOnboarding] = {install_command="pip install futu-api",setup_hint="Start and sign in to Futu OpenD on this computer before testing.",),+ "kis": ConnectorOnboarding(+ auth_type="api_key",+ credential_fields=(+ _field("app_key", "App Key"),+ _field("app_secret", "App Secret"),+ _field("account_no", "Account Number (CANO)", secret=False),+ _field("account_product_code", "Account Product Code", secret=False, required=False),+ ),+ dependency="requests",+ install_command="pip install keyring",+ setup_hint=(+ "Apply for an app key/secret at apiportal.koreainvestment.com; test "+ "against a 모의투자 (paper) account before ever using live-readonly."+ ),+ ),"longbridge": ConnectorOnboarding(auth_type="api_key",credential_fields=(diff --git a/agent/src/trading/profiles.py b/agent/src/trading/profiles.pyindex e01ecdc30..253431a30 100644--- a/agent/src/trading/profiles.py+++ b/agent/src/trading/profiles.py@@ -11,6 +11,7 @@ from src.trading.connectors.binance.profiles import BINANCE_PROFILESfrom src.trading.connectors.dhan.profiles import DHAN_PROFILESfrom src.trading.connectors.futu.profiles import FUTU_PROFILESfrom src.trading.connectors.ibkr.profiles import IBKR_PROFILES+from src.trading.connectors.kis.profiles import KIS_PROFILESfrom src.trading.connectors.longbridge.profiles import LONGBRIDGE_PROFILESfrom src.trading.connectors.mt5.profiles import MT5_PROFILESfrom src.trading.connectors.okx.profiles import OKX_PROFILES@@ -40,6 +41,7 @@ BUILTIN_PROFILES: tuple[TradingProfile, ...] = (*MT5_PROFILES,*ETORO_PROFILES,*ZERODHA_PROFILES,+ *KIS_PROFILES,)diff --git a/agent/src/trading/service.py b/agent/src/trading/service.pyindex 2d8693cc8..be02c944b 100644--- a/agent/src/trading/service.py+++ b/agent/src/trading/service.py@@ -25,6 +25,7 @@ _SDK_CONNECTOR_MODULES = {"dhan": "src.trading.connectors.dhan.sdk","shoonya": "src.trading.connectors.shoonya.sdk","zerodha": "src.trading.connectors.zerodha.sdk",+ "kis": "src.trading.connectors.kis.sdk","trading212": "src.trading.connectors.trading212.sdk","mt5": "src.trading.connectors.mt5.sdk","etoro": "src.trading.connectors.etoro.sdk",diff --git a/agent/tests/test_paper_capped_connectors_refuse_live.py b/agent/tests/test_paper_capped_connectors_refuse_live.pyindex 4b2e1d52b..422122cac 100644--- a/agent/tests/test_paper_capped_connectors_refuse_live.py+++ b/agent/tests/test_paper_capped_connectors_refuse_live.py@@ -45,6 +45,7 @@ _LIVE_CAPABLE = frozenset("robinhood","ibkr","mt5",+ "kis",})diff --git a/agent/tests/test_portfolio_compatibility.py b/agent/tests/test_portfolio_compatibility.pyindex 17092b98a..632c8044a 100644--- a/agent/tests/test_portfolio_compatibility.py+++ b/agent/tests/test_portfolio_compatibility.py@@ -21,6 +21,7 @@ def test_every_builtin_portfolio_connector_has_an_explicit_compatibility_tier():"etoro": "experimental","futu": "experimental","ibkr": "native",+ "kis": "experimental","longbridge": "native","mt5": "experimental","okx": "contract_tested",diff --git a/agent/tests/test_readme_counts.py b/agent/tests/test_readme_counts.pyindex 277392d07..e780b16fd 100644--- a/agent/tests/test_readme_counts.py+++ b/agent/tests/test_readme_counts.py@@ -70,7 +70,7 @@ BADGE_ORDER = ("skills", "brokers", "presets", "alphas", "engines", "quantlib")# Without that guard the count tests only prove the five READMEs agree with# each other, which they did while all five were uniformly wrong — eToro# shipped as the 13th connector and the pin stayed at 12.-EXPECTED_BROKERS = 14+EXPECTED_BROKERS = 15def _read(name: str) -> str:diff --git a/agent/tests/test_sdk_connectors.py b/agent/tests/test_sdk_connectors.pyindex 15fdb9351..05a632fa8 100644--- a/agent/tests/test_sdk_connectors.py+++ b/agent/tests/test_sdk_connectors.py@@ -58,6 +58,7 @@ def test_sdk_profiles_registered() -> None:"shoonya-paper-sdk", "shoonya-live-sdk-readonly","etoro-paper-sdk", "etoro-paper-trade","etoro-live-sdk-readonly", "etoro-live-trade",+ "kis-paper-sdk", "kis-paper-trade", "kis-live-sdk-readonly",} <= idsdiff --git a/agent/tests/test_sdk_connectors_kis.py b/agent/tests/test_sdk_connectors_kis.pynew file mode 100644index 000000000..ee3b8e52f--- /dev/null+++ b/agent/tests/test_sdk_connectors_kis.py@@ -0,0 +1,132 @@+"""Tests for the KIS (한국투자증권) direct-SDK trading connector.++Mirrors ``test_sdk_connectors.py``: exercises profile registration, the+genuine structural paper/live host separation, config resolution, read/write+classification, secret redaction, and service dispatch degrading cleanly when+nothing is configured — no live credentials or network access required.+"""++from __future__ import annotations++import pytest++from src.live.classification import ToolClass+from src.trading import profiles, service+from src.trading.connectors.kis import sdk as kis+from src.trading.connectors.kis.classification import KIS_TOOL_CLASS++pytestmark = pytest.mark.unit+++# --------------------------------------------------------------------------- #+# Profile registration+# --------------------------------------------------------------------------- #+++def test_kis_sdk_profiles_registered() -> None:+ ids = {p.id for p in profiles.list_profiles()}+ assert {"kis-paper-sdk", "kis-paper-trade", "kis-live-sdk-readonly"} <= ids+++def test_kis_live_profile_is_readonly_broker_sdk() -> None:+ profile = profiles.profile_by_id("kis-live-sdk-readonly")+ assert profile.connector == "kis"+ assert profile.environment == "live"+ assert profile.transport == "broker_sdk"+ assert profile.readonly is True+ assert not any(".place" in cap or "requires_mandate" in cap for cap in profile.capabilities)+++def test_kis_paper_trade_profile_allows_order_placement() -> None:+ profile = profiles.profile_by_id("kis-paper-trade")+ assert profile.environment == "paper"+ assert profile.readonly is False+ assert "orders.place" in profile.capabilities+++# --------------------------------------------------------------------------- #+# Genuine structural paper/live host separation+# --------------------------------------------------------------------------- #+++def test_kis_base_url_differs_by_environment() -> None:+ paper = kis.KISConfig(profile="paper")+ live = kis.KISConfig(profile="live-readonly")+ assert paper.base_url != live.base_url+ assert "vts" in paper.base_url # 모의투자 (paper) host+ assert paper.base_url.endswith(":29443")+ assert live.base_url.endswith(":9443")+++def test_kis_order_tr_id_differs_by_environment_and_side() -> None:+ assert kis._TR_ORDER_BUY["paper"] != kis._TR_ORDER_BUY["live"]+ assert kis._TR_ORDER_BUY["paper"] != kis._TR_ORDER_SELL["paper"]+++def test_kis_invalid_profile_rejected() -> None:+ with pytest.raises(kis.KISConfigError):+ kis.KISConfig.from_mapping({"profile": "live"}) # only paper/live-readonly+++# --------------------------------------------------------------------------- #+# Order validation+# --------------------------------------------------------------------------- #+++def test_kis_place_order_validates_before_any_request() -> None:+ cfg = kis.KISConfig(app_key="k", app_secret="s", account_no="12345678", profile="paper")+ missing_qty = kis.place_order(cfg, symbol="005930", side="buy")+ bad_side = kis.place_order(cfg, symbol="005930", side="hold", quantity=10)+ missing_limit_price = kis.place_order(cfg, symbol="005930", side="buy", quantity=10, order_type="limit")+ notional_rejected = kis.place_order(cfg, symbol="005930", side="buy", notional=100_000)+ assert missing_qty["status"] == "error"+ assert bad_side["status"] == "error"+ assert missing_limit_price["status"] == "error"+ assert notional_rejected["status"] == "error"+ assert "notional" in notional_rejected["error"]+++def test_kis_cancel_order_rejects_fractional_sub_share_quantity() -> None:+ """0.5 must not silently truncate to 0 and flip into a full-quantity cancel."""+ cfg = kis.KISConfig(app_key="k", app_secret="s", account_no="12345678", profile="paper")+ result = kis.cancel_order(cfg, "ORD1", order_branch="00001", quantity=0.5)+ assert result["status"] == "error"+++def test_kis_get_historical_bars_limit_zero_returns_no_bars(monkeypatch) -> None:+ cfg = kis.KISConfig(app_key="k", app_secret="s", account_no="12345678", profile="paper")+ monkeypatch.setattr(+ kis,+ "_get",+ lambda *a, **k: {"output2": [{"stck_bsop_date": "20260101", "stck_clpr": "100"}]},+ )+ result = kis.get_historical_bars("005930", config=cfg, limit=0)+ assert result["bars"] == []+++# --------------------------------------------------------------------------- #+# Redaction / service dispatch / classification+# --------------------------------------------------------------------------- #+++def test_kis_redacts_app_secret() -> None:+ cfg = kis.KISConfig(app_key="APPKEY123456", app_secret="topsecret", account_no="12345678")+ pub = kis._public_config(cfg)+ assert "topsecret" not in str(pub)+ assert pub["app_key"].endswith("***")+ assert pub["app_secret"] == "***redacted***"+++def test_kis_service_unconfigured(monkeypatch, tmp_path) -> None:+ monkeypatch.setattr(kis, "get_runtime_root", lambda: tmp_path)+ result = service.check_connection("kis-paper-sdk")+ assert result["status"] == "error"+ assert result["connector"] == "kis"+ assert result["transport"] == "broker_sdk"+++def test_kis_order_ops_classified_write() -> None:+ for name in ("place_order", "cancel_order"):+ assert KIS_TOOL_CLASS[name] is ToolClass.WRITE+ for name in ("get_positions", "get_account_snapshot"):+ assert KIS_TOOL_CLASS[name] is ToolClass.READ