Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(trading): add Upbit broker connector

heonjinjeong7ff36917ae47
diff --git a/README.md b/README.md
index a1087c2a0..d634a1037 100644
--- a/README.md
+++ b/README.md
@@ -588,7 +588,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.
@@ -602,7 +602,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) |
-| **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** | US / HK · India (NSE/BSE) | read + paper only — no runtime paper/live discriminator, so live order placement is hard-refused |
+| **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** · **Upbit** | US / HK · India (NSE/BSE) · Korea (crypto) | 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 |
Paper-vs-live is a **structural per-broker runtime guard** (account-id format, host separation, demo flag, or trade environment), never a config flag the agent can flip. A broker exposing no such discriminator is capped at paper + read-only.
diff --git a/README_ar.md b/README_ar.md
index 815b975c2..3c40263c7 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -549,7 +549,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 فقط). ومسارات البحث / الاختبار الرجعي محظورة بنيوياً من أي نقطة نهاية حية.
@@ -563,7 +563,7 @@ LONGBRIDGE_ACCESS_TOKEN=...
| **Futu** | HK / US / A | قراءة + ورقي + تداول حي محدود |
| **eToro** | global | قراءة + ورقي + تداول حي محدود (Public API؛ مفاتيح demo لا تصل بنيويًا إلا إلى مسارات `/demo`، مع دعم تدفقات التداول بالنسخ) |
| **MetaTrader 5** | forex / CFD | قراءة + ورقي + تداول حي محدود (بأسلوب Exness؛ حارس هوية demo ⇔ paper) |
-| **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** | US / HK · الهند (NSE/BSE) | قراءة + ورقي فقط — لا يوجد مُميِّز وقت-تشغيل بين paper/live، لذا يُرفض تنفيذ الأوامر الحية بشكل صارم |
+| **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** · **Upbit** | US / HK · الهند (NSE/BSE) · كوريا (crypto) | قراءة + ورقي فقط — لا يوجد مُميِّز وقت-تشغيل بين paper/live، لذا يُرفض تنفيذ الأوامر الحية بشكل صارم |
| **Trading 212** | UK / EU | قراءة فقط بالكامل — تَرفض `place_order` / `cancel_order` حتى الورقي بشكل صارم |
التمييز بين الورقي والحي هو **حارس بنيوي على مستوى وقت التشغيل لكل وسيط** (صيغة معرّف الحساب، أو فصل المضيف، أو علامة demo، أو بيئة التداول)، وليس مجرّد إعداد يمكن للوكيل تبديله. أي وسيط لا يكشف عن هذا المُميِّز يُحصَر في الورقي + القراءة فقط.
diff --git a/README_es.md b/README_es.md
index efe2dc6f4..fb57a4b50 100644
--- a/README_es.md
+++ b/README_es.md
@@ -553,7 +553,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.
@@ -567,7 +567,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) |
-| **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 |
+| **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** · **Upbit** | EE. UU. / HK · India (NSE/BSE) · Corea (cripto) | 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 |
Paper-vs-live es una **guardia de runtime estructural por broker** (formato de id de cuenta, separación de host, flag demo, o entorno de trading), nunca un flag de configuración que el agente pueda cambiar. Un broker que no exponga tal discriminador queda limitado a paper + solo lectura.
diff --git a/README_ja.md b/README_ja.md
index db593be2f..f1c919d72 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -549,7 +549,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 から遮断されています。
@@ -563,7 +563,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) |
-| **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** | US / HK · India (NSE/BSE) | read + paper only — no runtime paper/live discriminator, so live order placement is hard-refused |
+| **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** · **Upbit** | US / HK · India (NSE/BSE) · Korea (crypto) | 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 |
Paper-vs-live is a **structural per-broker runtime guard** (account-id format, host separation, demo flag, or trade environment), never a config flag the agent can flip. A broker exposing no such discriminator is capped at paper + read-only.
diff --git a/README_ko.md b/README_ko.md
index a96f72d77..351253570 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -549,7 +549,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 전용). 리서치 / 백테스트 경로는 구조적으로 모든 실거래 엔드포인트에서 차단됩니다.
@@ -563,7 +563,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) |
-| **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** | US / HK · India (NSE/BSE) | read + paper only — no runtime paper/live discriminator, so live order placement is hard-refused |
+| **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** · **Upbit** | US / HK · India (NSE/BSE) · Korea (crypto) | 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 |
Paper-vs-live는 **구조적 브로커별 런타임 가드**(account-id 형식, 호스트 분리, demo 플래그, 또는 trade environment)이며, agent가 뒤집을 수 있는 config 플래그가 아닙니다. 그런 구분자를 노출하지 않는 브로커는 페이퍼 + 읽기 전용으로 제한됩니다.
diff --git a/README_zh.md b/README_zh.md
index cbc34ee13..26d565cd6 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -562,7 +562,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)。研究 / 回测路径在结构上被隔离,无法触达任何实盘端点。
@@ -576,7 +576,7 @@ LONGBRIDGE_ACCESS_TOKEN=...
| **Futu** | HK / US / A | 读取 + 模拟盘 + 受约束实盘 |
| **eToro** | global | 读取 + 模拟盘 + 受约束实盘(Public API;demo 密钥在结构上只能访问 `/demo` 路径,另支持跟单交易流程) |
| **MetaTrader 5** | forex / CFD | 读取 + 模拟盘 + 受约束实盘(Exness 风格;demo ⇔ 模拟盘身份守卫) |
-| **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** | US / HK · India (NSE/BSE) | 仅读取 + 模拟盘——无运行时模拟/实盘判别标识,因此实盘下单被硬拒 |
+| **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** · **Upbit** | US / HK · India (NSE/BSE) · 韩国 (crypto) | 仅读取 + 模拟盘——无运行时模拟/实盘判别标识,因此实盘下单被硬拒 |
| **Trading 212** | UK / EU | 完全只读——`place_order` / `cancel_order` 连模拟盘也硬拒 |
模拟盘与实盘的区分是**每家券商的结构性运行时守卫**(account-id 格式、host 隔离、demo 标志或交易环境),绝非 agent 能翻转的配置开关。不暴露此类判别标识的券商一律封顶为模拟盘 + 只读。
diff --git a/agent/SKILL.md b/agent/SKILL.md
index beaa3950e..abf1cf68f 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 crypto trading uses the **Upbit** connector (KRW markets; paper + read-only live — no runtime paper/live discriminator, so live order placement is structurally disabled, same as Shoonya/Dhan).
Example workflow:
1. Use `list_skills()` to discover strategy patterns
diff --git a/agent/src/live/registry.py b/agent/src/live/registry.py
index d6ca9fd21..e4b693f7b 100644
--- a/agent/src/live/registry.py
+++ b/agent/src/live/registry.py
@@ -36,6 +36,7 @@ from src.trading.connectors.shoonya.classification import SHOONYA_TOOL_CLASS
from src.trading.connectors.tiger.classification import TIGER_TOOL_CLASS
from src.trading.connectors.etoro.classification import ETORO_TOOL_CLASS
from src.trading.connectors.trading212.classification import TRADING212_TOOL_CLASS
+from src.trading.connectors.upbit.classification import UPBIT_TOOL_CLASS
from src.trading.connectors.zerodha.classification import ZERODHA_TOOL_CLASS
logger = logging.getLogger(__name__)
@@ -59,6 +60,7 @@ _BROKER_CURATED_MAPS = {
"mt5": MT5_TOOL_CLASS,
"etoro": ETORO_TOOL_CLASS,
"zerodha": ZERODHA_TOOL_CLASS,
+ "upbit": UPBIT_TOOL_CLASS,
}
diff --git a/agent/src/trading/connectors/upbit/__init__.py b/agent/src/trading/connectors/upbit/__init__.py
new file mode 100644
index 000000000..7d072206e
--- /dev/null
+++ b/agent/src/trading/connectors/upbit/__init__.py
@@ -0,0 +1,9 @@
+"""Upbit trading connector.
+
+Read-only and locally-simulated paper account access via Upbit's public REST
+API (JWT-signed, no third-party SDK required). A ``broker_sdk`` transport for
+the Korean won crypto markets (``KRW-*``).
+
+Upbit provides free API access with an account-scoped access/secret key pair.
+It exposes no sandbox and no runtime paper/live discriminator.
+"""
diff --git a/agent/src/trading/connectors/upbit/classification.py b/agent/src/trading/connectors/upbit/classification.py
new file mode 100644
index 000000000..866313edf
--- /dev/null
+++ b/agent/src/trading/connectors/upbit/classification.py
@@ -0,0 +1,23 @@
+"""Curated read/write classification for Upbit 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
+
+#: Upbit REST operation read/write catalog.
+UPBIT_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/upbit/profiles.py b/agent/src/trading/connectors/upbit/profiles.py
new file mode 100644
index 000000000..5d2bb9cf1
--- /dev/null
+++ b/agent/src/trading/connectors/upbit/profiles.py
@@ -0,0 +1,66 @@
+"""Built-in Upbit connector profiles.
+
+Upbit (https://upbit.com) is Korea's largest KRW crypto exchange with free
+API access.
+
+Paper-only by design: Upbit exposes no sandbox and no runtime paper/live
+discriminator — a single Access/Secret Key pair reads the same account
+whether the profile is declared ``paper`` or ``live``. Following the
+Dhan/Longbridge precedent, this connector therefore ships a read-only live
+profile plus a locally simulated paper-trade profile, and exposes NO live
+order placement. Paper vs live is operator-declared (config-trust); the
+connector's order path is structurally capped at paper (see
+``sdk.place_order``).
+"""
+
+from __future__ import annotations
+
+from src.trading.types import READ_CAPABILITIES, TradingProfile
+
+UPBIT_PROFILES: tuple[TradingProfile, ...] = (
+ TradingProfile(
+ id="upbit-paper-sdk",
+ connector="upbit",
+ label="Upbit Paper · REST (Korea)",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "paper"},
+ notes=(
+ "Reads real-time KRW crypto market data via Upbit's free public "
+ "API. Paper vs live is operator-declared (the API exposes no "
+ "runtime discriminator)."
+ ),
+ ),
+ TradingProfile(
+ id="upbit-paper-trade",
+ connector="upbit",
+ label="Upbit Paper · REST Trade (Korea)",
+ environment="paper",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES + ("orders.place",),
+ readonly=False,
+ config={"profile": "paper"},
+ notes=(
+ "Places PAPER orders simulated locally using a live Upbit quote "
+ "— no real money at risk. Paper-only by design: Upbit exposes no "
+ "runtime paper/live discriminator, so live order placement is "
+ "not supported."
+ ),
+ ),
+ TradingProfile(
+ id="upbit-live-sdk-readonly",
+ connector="upbit",
+ label="Upbit Live · REST Read-Only (Korea)",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "live-readonly"},
+ notes=(
+ "Reads a live Upbit account (account, positions, orders, quotes, "
+ "history). Order placement is not exposed in this profile."
+ ),
+ ),
+)
diff --git a/agent/src/trading/connectors/upbit/sdk.py b/agent/src/trading/connectors/upbit/sdk.py
new file mode 100644
index 000000000..7816d7d73
--- /dev/null
+++ b/agent/src/trading/connectors/upbit/sdk.py
@@ -0,0 +1,636 @@
+"""Read-only + locally-simulated-paper Upbit connector via the public REST API.
+
+Wraps Upbit's JWT-authenticated Exchange API (accounts, orders) and the public
+Quotation API (ticker, candles) for the five read operations plus paper order
+simulation. No third-party SDK is required — requests + PyJWT only.
+
+Paper-vs-live: Upbit has no sandbox environment and no runtime paper/live
+discriminator (a single Access/Secret Key pair reads the same account
+regardless of the declared profile). Following the Dhan/Longbridge precedent,
+this connector is therefore structurally capped at paper: order placement is
+simulated locally against a live ticker price and never reaches Upbit.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import uuid
+from dataclasses import asdict, dataclass
+from pathlib import Path
+from types import ModuleType
+from typing import Any, Mapping
+from urllib.parse import urlencode
+
+import requests
+
+from src.config.paths import get_runtime_root
+
+CONFIG_FILENAME = "upbit.json"
+
+PROFILE_ENVIRONMENTS = {
+ "paper": "paper",
+ "live-readonly": "live",
+}
+
+UPBIT_API_URL = "https://api.upbit.com/v1"
+
+#: Returned by order methods when a non-paper config reaches them. Upbit
+#: exposes no runtime paper/live discriminator (same key pair reads the same
+#: account), so — following the Dhan/Longbridge precedent — the connector is
+#: structurally capped at paper and never opens a live order path.
+_PAPER_ONLY_ERROR = (
+ "Upbit connector is paper-only: it exposes no runtime paper/live "
+ "discriminator, so live order placement is not supported. Use an "
+ "upbit-paper-* profile."
+)
+
+
+class UpbitDependencyError(RuntimeError):
+ """Raised when the optional ``PyJWT`` package is not installed."""
+
+
+class UpbitConfigError(RuntimeError):
+ """Raised when the connector configuration is missing or invalid."""
+
+
+class UpbitAPIError(RuntimeError):
+ """Raised when Upbit returns an auth, HTTP, network, or JSON error."""
+
+
+@dataclass(frozen=True)
+class UpbitConfig:
+ """Upbit connector connection settings.
+
+ Args:
+ access_key: Upbit Open API access key.
+ secret_key: Upbit Open API secret key.
+ profile: ``paper`` or ``live-readonly``.
+ timeout: Network timeout in seconds.
+ readonly: Whether order placement is disabled.
+ """
+
+ access_key: str = ""
+ secret_key: str = ""
+ profile: str = "paper"
+ timeout: float = 15.0
+ readonly: bool = True
+
+ @classmethod
+ def from_mapping(cls, data: Mapping[str, Any] | None = None) -> "UpbitConfig":
+ """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 UpbitConfigError("profile must be 'paper' or 'live-readonly'")
+ return cls(
+ access_key=str(payload.get("access_key") or "").strip(),
+ secret_key=str(payload.get("secret_key") or "").strip(),
+ profile=profile,
+ timeout=float(payload.get("timeout") or 15.0),
+ readonly=bool(payload.get("readonly", True)),
+ )
+
+ def with_overrides(
+ self,
+ *,
+ access_key: str | None = None,
+ secret_key: str | None = None,
+ profile: str | None = None,
+ ) -> "UpbitConfig":
+ """Return a copy with CLI/tool overrides applied."""
+ payload = asdict(self)
+ if access_key is not None:
+ payload["access_key"] = access_key
+ if secret_key is not None:
+ payload["secret_key"] = secret_key
+ if profile is not None:
+ payload["profile"] = profile
+ return UpbitConfig.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"
+
+
+_OVERRIDE_KEYS = ("access_key", "secret_key", "profile")
+
+
+def build_config(
+ profile_config: Mapping[str, Any] | None = None,
+ overrides: Mapping[str, Any] | None = None,
+) -> "UpbitConfig":
+ """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 = UpbitConfig.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() -> UpbitConfig:
+ path = config_path()
+ if not path.exists():
+ return UpbitConfig()
+ try:
+ return UpbitConfig.from_mapping(json.loads(path.read_text(encoding="utf-8")))
+ except (OSError, ValueError, json.JSONDecodeError) as exc:
+ raise UpbitConfigError(f"invalid Upbit config at {path}: {exc}") from exc
+
+
+def save_config(config: UpbitConfig) -> 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
+
+
+def upbit_jwt_available() -> bool:
+ try:
+ _require_jwt()
+ return True
+ except UpbitDependencyError:
+ return False
+
+
+# ---------------------------------------------------------------------------
+# Five read operations + order placement
+# ---------------------------------------------------------------------------
+
+
+def check_status(config: UpbitConfig | None = None) -> dict[str, Any]:
+ """Check SDK readiness and config completeness."""
+ cfg = config or load_config()
+ report: dict[str, Any] = {
+ "status": "ok",
+ "config": _public_config(cfg),
+ "sdk": {"package": "PyJWT", "installed": upbit_jwt_available()},
+ "paper_guard": "simulated_locally",
+ "host": UPBIT_API_URL,
+ }
+
+ missing = _missing_fields(cfg)
+ if missing:
+ report["status"] = "error"
+ report["error"] = f"Upbit connector not configured: missing {', '.join(missing)}."
+ return report
+
+ if not report["sdk"]["installed"]:
+ report["status"] = "error"
+ report["error"] = "Optional dependency missing: install with `pip install PyJWT`."
+ return report
+
+ try:
+ get_account_snapshot(cfg) # connectivity probe; result unused
+ except (UpbitConfigError, UpbitAPIError) 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: UpbitConfig | None = None) -> dict[str, Any]:
+ """Fetch the KRW cash balance (account summary) for the configured account."""
+ cfg = config or load_config()
+ accounts = _accounts(cfg)
+ krw = next((row for row in accounts if str(row.get("currency")) == "KRW"), None)
+
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_paper": cfg.is_paper,
+ "host": UPBIT_API_URL,
+ "account": {
+ "currency": "KRW",
+ "balance": _as_float(krw.get("balance")) if krw else 0.0,
+ "locked": _as_float(krw.get("locked")) if krw else 0.0,
+ },
+ }
+
+
+def get_positions(config: UpbitConfig | None = None) -> dict[str, Any]:
+ """Fetch current crypto holdings (every non-KRW balance)."""
+ cfg = config or load_config()
+ accounts = _accounts(cfg)
+
+ rows = []
+ for item in accounts:
+ currency = str(item.get("currency") or "")
+ if not currency or currency == "KRW":
+ continue
+ quantity = _as_float(item.get("balance")) + _as_float(item.get("locked"))
+ if quantity <= 0:
+ continue
+ unit_currency = str(item.get("unit_currency") or "KRW")
+ rows.append({
+ "symbol": f"{unit_currency}-{currency}",
+ "currency": currency,
+ "quantity": quantity,
+ "available": _as_float(item.get("balance")),
+ "locked": _as_float(item.get("locked")),
+ "average_cost": _as_float(item.get("avg_buy_price")),
+ "unit_currency": unit_currency,
+ })
+
+ return {"status": "ok", "profile": cfg.profile, "is_paper": cfg.is_paper, "positions": rows}
+
+
+def get_open_orders(
+ config: UpbitConfig | None = None,
+ *,
+ include_executions: bool = False,
+) -> dict[str, Any]:
+ """Fetch open (waiting) orders and optionally recently closed ones."""
+ cfg = config or load_config()
+ open_rows = _as_list(_request(cfg, "GET", "/orders/open"))
+ result: dict[str, Any] = {
+ "status": "ok",
+ "profile": cfg.profile,
+ "is_paper": cfg.is_paper,
+ "open_orders": [_order_to_dict(item) for item in open_rows],
+ }
+ if include_executions:
+ closed_rows = _as_list(_request(cfg, "GET", "/orders/closed"))
+ result["executions"] = [_order_to_dict(item) for item in closed_rows]
+ return result
+
+
+def get_quote(symbol: str, *, config: UpbitConfig | None = None, **_: Any) -> dict[str, Any]:
+ """Fetch the current ticker for a market (e.g. ``KRW-BTC``)."""
+ cfg = config or load_config()
+ market = _normalize_market(symbol)
+
+ try:
+ rows = _request(cfg, "GET", "/ticker", params={"markets": market}, authed=False)
+ except UpbitAPIError as exc:
+ return {"status": "error", "error": str(exc), "symbol": symbol}
+
+ row = _as_list(rows)[0] if _as_list(rows) else {}
+ return {
+ "status": "ok",
+ "symbol": market,
+ "quote": {
+ "last": row.get("trade_price"),
+ "open": row.get("opening_price"),
+ "high": row.get("high_price"),
+ "low": row.get("low_price"),
+ "prev_close": row.get("prev_closing_price"),
+ "change_rate": row.get("signed_change_rate"),
+ "volume_24h": row.get("acc_trade_volume_24h"),
+ },
+ }
+
+
+#: Minute candle units Upbit serves without remapping to a different bar size.
+_MINUTE_UNITS = {"1m": 1, "3m": 3, "5m": 5, "15m": 15, "30m": 30, "60m": 60, "240m": 240}
+
+
+def get_historical_bars(
+ symbol: str,
+ *,
+ config: UpbitConfig | None = None,
+ period: str = "1d",
+ limit: int = 200,
+) -> dict[str, Any]:
+ """Fetch historical OHLCV candles.
+
+ ``period`` tokens: ``1m``/``3m``/``5m``/``15m``/``30m``/``60m``/``240m`` →
+ minute candles; ``1d``/``1D`` → day candles; ``1w`` → week candles;
+ ``1M`` → month candles. Unsupported periods fail closed instead of
+ silently substituting a different bar size.
+ """
+ cfg = config or load_config()
+ market = _normalize_market(symbol)
+ token = period.strip()
+ capped_limit = min(int(limit), 200) # Upbit caps a single call at 200 candles.
+
+ if token in _MINUTE_UNITS:
+ path = f"/candles/minutes/{_MINUTE_UNITS[token]}"
+ elif token in ("1d", "1D"):
+ path = "/candles/days"
+ elif token == "1w":
+ path = "/candles/weeks"
+ elif token == "1M":
+ path = "/candles/months"
+ else:
+ return {
+ "status": "error",
+ "error": (
+ f"unsupported period: {period!r}; "
+ f"supported: {sorted(_MINUTE_UNITS)} + ['1d', '1w', '1M']"
+ ),
+ "symbol": market,
+ }
+
+ try:
+ rows = _request(
+ cfg, "GET", path, params={"market": market, "count": capped_limit}, authed=False
+ )
+ except UpbitAPIError as exc:
+ return {"status": "error", "error": str(exc), "symbol": market}
+
+ bars = [_candle_to_dict(item) for item in reversed(_as_list(rows))]
+ return {"status": "ok", "symbol": market, "period": period, "bars": bars}
+
+
+def place_order(
+ config: UpbitConfig | 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 a PAPER-ONLY order on Upbit (simulated locally against a live quote).
+
+ Upbit exposes no runtime paper/live discriminator, so this connector is
+ structurally capped at paper: the very first check refuses any config whose
+ ``environment`` is not ``paper``. There is therefore no live order path
+ here, by design.
+
+ Args:
+ symbol: Market code, e.g. ``KRW-BTC``.
+ side: ``buy`` or ``sell``.
+ quantity: Base-currency quantity (e.g. BTC amount). Mutually exclusive
+ with ``notional``, which is the more natural unit for Upbit market
+ buys (KRW amount to spend).
+ order_type: ``market`` or ``limit``.
+ limit_price: Required for limit orders.
+ """
+ cfg = config or load_config()
+
+ # ---- HARD GUARD: structurally paper-only (must run before anything) ----
+ if not cfg.is_paper:
+ return {"status": "error", "error": _PAPER_ONLY_ERROR}
+
+ market = _normalize_market(symbol)
+ if not market:
+ 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'"}
+
+ has_qty = quantity is not None
+ has_notional = notional is not None
+ if has_qty == has_notional:
+ return {"status": "error", "error": "provide exactly one of quantity or notional"}
+ if has_qty and float(quantity) <= 0: # type: ignore[arg-type]
+ return {"status": "error", "error": "quantity must be positive"}
+ if has_notional and float(notional) <= 0: # type: ignore[arg-type]
+ return {"status": "error", "error": "notional must be positive"}
+
+ if type_token == "limit" and limit_price is None:
+ return {"status": "error", "error": "limit order requires limit_price"}
+
+ # Paper-only: simulate locally against a live quote (Upbit has no sandbox).
+ fill_price = float(limit_price) if limit_price is not None else None
+ if fill_price is None:
+ quote = get_quote(market, config=cfg)
+ fill_price = _as_float(quote.get("quote", {}).get("last")) if quote.get("status") == "ok" else None
+
+ if has_notional:
+ # notional sizing needs a price to convert KRW spend into a quantity —
+ # an unpriced fill here would silently fabricate a null quantity.
+ if not fill_price:
+ return {
+ "status": "error",
+ "error": "could not resolve a live quote to size this notional order; retry or pass limit_price",
+ "symbol": market,
+ }
+ filled_qty = float(notional) / fill_price
+ else:
+ filled_qty = float(quantity)
+
+ return {
+ "status": "ok",
+ "order_id": f"PAPER-{market}-{side_token}-{uuid.uuid4().hex[:8]}",
+ "symbol": market,
+ "side": side_token,
+ "profile": cfg.profile,
+ "is_paper": True,
+ "paper_guard": "simulated_locally",
+ "order_type": type_token,
+ "quantity": filled_qty,
+ "limit_price": fill_price if type_token == "limit" else None,
+ "fill_price": fill_price,
+ "order_status": "simulated_fill",
+ }
+
+
+def cancel_order(
+ config: UpbitConfig | None = None,
+ order_id: str = "",
+ *,
+ symbol: str | None = None,
+) -> dict[str, Any]:
+ """Cancel a PAPER-ONLY order on Upbit (simulated locally).
+
+ Like :func:`place_order`, the first check refuses any non-paper config —
+ this connector never reaches a live order, so it never cancels one.
+ """
+ cfg = config or load_config()
+
+ # ---- HARD GUARD: structurally paper-only (must run before anything) ----
+ if not cfg.is_paper:
+ return {"status": "error", "error": _PAPER_ONLY_ERROR}
+
+ clean_id = str(order_id or "").strip()
+ if not clean_id:
+ return {"status": "error", "error": "order_id is required"}
+
+ return {
+ "status": "ok",
+ "order_id": clean_id,
+ "symbol": _normalize_market(symbol) if symbol else None,
+ "profile": cfg.profile,
+ "is_paper": True,
+ "cancelled": True,
+ }
+
+
+# ---------------------------------------------------------------------------
+# SDK plumbing
+# ---------------------------------------------------------------------------
+
+
+def _require_jwt() -> ModuleType:
+ try:
+ import jwt # type: ignore
+ except ModuleNotFoundError as exc:
+ raise UpbitDependencyError(
+ "PyJWT is not installed; run `pip install PyJWT`."
+ ) from exc
+ return jwt
+
+
+def _accounts(cfg: UpbitConfig) -> list[Any]:
+ return _as_list(_request(cfg, "GET", "/accounts"))
+
+
+def _auth_headers(cfg: UpbitConfig, params: Mapping[str, Any] | None) -> dict[str, str]:
+ jwt = _require_jwt()
+ if not cfg.access_key or not cfg.secret_key:
+ raise UpbitConfigError(
+ "Upbit connector not configured: set access_key and secret_key "
+ "in ~/.vibe-trading/upbit.json or via environment."
+ )
+ payload: dict[str, Any] = {"access_key": cfg.access_key, "nonce": str(uuid.uuid4())}
+ if params:
+ query_string = urlencode(list(params.items()), doseq=True)
+ payload["query_hash"] = hashlib.sha512(query_string.encode("utf-8")).hexdigest()
+ payload["query_hash_alg"] = "SHA512"
+ token = jwt.encode(payload, cfg.secret_key, algorithm="HS256")
+ if isinstance(token, bytes): # PyJWT < 2.0 returned bytes
+ token = token.decode("utf-8")
+ return {"Authorization": f"Bearer {token}"}
+
+
+def _request(
+ cfg: UpbitConfig,
+ method: str,
+ path: str,
+ *,
+ params: Mapping[str, Any] | None = None,
+ authed: bool = True,
+) -> Any:
+ """Run an HTTP request and normalize Upbit failure modes."""
+ if authed:
+ missing = _missing_fields(cfg)
+ if missing:
+ raise UpbitConfigError(f"Upbit connector not configured: missing {', '.join(missing)}.")
+ headers = {"Accept": "application/json"}
+ if authed:
+ headers.update(_auth_headers(cfg, params))
+
+ try:
+ response = requests.request(
+ method.upper(),
+ f"{UPBIT_API_URL}{path}",
+ headers=headers,
+ params=dict(params or {}),
+ timeout=cfg.timeout,
+ )
+ except requests.RequestException as exc:
+ raise UpbitAPIError(f"Upbit request failed: {exc}") from exc
+
+ if response.status_code in (401, 403):
+ raise UpbitAPIError("Upbit API authentication failed: check access_key/secret_key.")
+ if response.status_code >= 400:
+ raise UpbitAPIError(f"Upbit API returned HTTP {response.status_code}: {_error_message(response)}")
+ if not response.content:
+ return None
+ try:
+ return response.json()
+ except ValueError as exc:
+ raise UpbitAPIError("Upbit 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):
+ error = payload.get("error")
+ if isinstance(error, Mapping):
+ return str(error.get("message") or error.get("name") or payload)
+ return str(payload)
+
+
+def _missing_fields(cfg: UpbitConfig) -> list[str]:
+ missing = []
+ if not cfg.access_key:
+ missing.append("access_key")
+ if not cfg.secret_key:
+ missing.append("secret_key")
+ return missing
+
+
+def _public_config(cfg: UpbitConfig) -> dict[str, Any]:
+ data = asdict(cfg)
+ if data.get("access_key"):
+ data["access_key"] = data["access_key"][:8] + "***"
+ if data.get("secret_key"):
+ data["secret_key"] = "***redacted***"
+ return data
+
+
+def _normalize_market(symbol: str | None) -> str:
+ """Normalize a market code: uppercase, ``/`` → ``-`` (Upbit uses ``QUOTE-BASE``)."""
+ return str(symbol or "").strip().upper().replace("/", "-")
+
+
+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": str(item.get("uuid", "")),
+ "symbol": item.get("market", ""),
+ "side": item.get("side", ""),
+ "order_type": item.get("ord_type", ""),
+ "price": _as_float(item.get("price")) if item.get("price") is not None else None,
+ "quantity": _as_float(item.get("volume")) if item.get("volume") is not None else None,
+ "remaining_quantity": (
+ _as_float(item.get("remaining_volume")) if item.get("remaining_volume") is not None else None
+ ),
+ "executed_quantity": (
+ _as_float(item.get("executed_volume")) if item.get("executed_volume") is not None else None
+ ),
+ "status": item.get("state", ""),
+ "created_at": item.get("created_at", ""),
+ }
+
+
+def _candle_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "time": item.get("candle_date_time_utc"),
+ "open": item.get("opening_price"),
+ "high": item.get("high_price"),
+ "low": item.get("low_price"),
+ "close": item.get("trade_price"),
+ "volume": item.get("candle_acc_trade_volume"),
+ }
diff --git a/agent/src/trading/onboarding.py b/agent/src/trading/onboarding.py
index a488e3381..01031cddf 100644
--- a/agent/src/trading/onboarding.py
+++ b/agent/src/trading/onboarding.py
@@ -161,6 +161,16 @@ _BUILTIN: dict[str, ConnectorOnboarding] = {
dependency="requests",
install_command="pip install keyring",
),
+ "upbit": ConnectorOnboarding(
+ auth_type="api_key",
+ credential_fields=(
+ _field("access_key", "Access Key"),
+ _field("secret_key", "Secret Key"),
+ ),
+ dependency="PyJWT",
+ install_command="pip install PyJWT keyring",
+ setup_hint="Create a read-only key; do not grant withdrawal permission.",
+ ),
}
diff --git a/agent/src/trading/profiles.py b/agent/src/trading/profiles.py
index e01ecdc30..6a56f7510 100644
--- a/agent/src/trading/profiles.py
+++ b/agent/src/trading/profiles.py
@@ -19,6 +19,7 @@ from src.trading.connectors.shoonya.profiles import SHOONYA_PROFILES
from src.trading.connectors.tiger.profiles import TIGER_PROFILES
from src.trading.connectors.etoro.profiles import ETORO_PROFILES
from src.trading.connectors.trading212.profiles import TRADING212_PROFILES
+from src.trading.connectors.upbit.profiles import UPBIT_PROFILES
from src.trading.connectors.zerodha.profiles import ZERODHA_PROFILES
from src.trading.types import TradingProfile
@@ -40,6 +41,7 @@ BUILTIN_PROFILES: tuple[TradingProfile, ...] = (
*MT5_PROFILES,
*ETORO_PROFILES,
*ZERODHA_PROFILES,
+ *UPBIT_PROFILES,
)
diff --git a/agent/src/trading/service.py b/agent/src/trading/service.py
index 2d8693cc8..5b8b9d1af 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",
+ "upbit": "src.trading.connectors.upbit.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.py
index 4b2e1d52b..e6ba68205 100644
--- a/agent/tests/test_paper_capped_connectors_refuse_live.py
+++ b/agent/tests/test_paper_capped_connectors_refuse_live.py
@@ -28,7 +28,7 @@ _CONNECTOR_ROOT = Path(__file__).resolve().parents[1] / "src" / "trading" / "con
# Brokers with no runtime paper/live discriminator. Capped at paper; every
# order entry point must refuse a non-paper config up front.
-_PAPER_CAPPED = frozenset({"longbridge", "dhan", "shoonya", "trading212", "zerodha"})
+_PAPER_CAPPED = frozenset({"longbridge", "dhan", "shoonya", "trading212", "zerodha", "upbit"})
# Brokers with a structural discriminator (host separation, demo flag, account
# id format, trade environment). Live placement is allowed here, but only
diff --git a/agent/tests/test_portfolio_compatibility.py b/agent/tests/test_portfolio_compatibility.py
index cde1ec455..db3048b2c 100644
--- a/agent/tests/test_portfolio_compatibility.py
+++ b/agent/tests/test_portfolio_compatibility.py
@@ -28,6 +28,7 @@ def test_every_builtin_portfolio_connector_has_an_explicit_compatibility_tier():
"tiger": "experimental",
"trading212": "experimental",
"zerodha": "experimental",
+ "upbit": "experimental",
}
observed = {profile.connector: profile_compatibility(profile)["level"] for profile in eligible_profiles()}
diff --git a/agent/tests/test_readme_counts.py b/agent/tests/test_readme_counts.py
index 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 = 15
def _read(name: str) -> str:
diff --git a/agent/tests/test_sdk_connectors.py b/agent/tests/test_sdk_connectors.py
index 15fdb9351..225d29afe 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",
+ "upbit-paper-sdk", "upbit-paper-trade", "upbit-live-sdk-readonly",
} <= ids
@@ -66,7 +67,7 @@ def test_no_discriminator_brokers_expose_no_live_trade_profile() -> None:
Shoonya) must NOT register any live order-placing profile — the Longbridge
precedent. A ``*-live-trade`` profile here would be a red-line regression."""
ids = {p.id for p in profiles.list_profiles()}
- for broker in ("longbridge", "dhan", "shoonya"):
+ for broker in ("longbridge", "dhan", "shoonya", "upbit"):
assert f"{broker}-live-trade" not in ids
# No live profile for these brokers may advertise an order capability.
for p in profiles.list_profiles():
diff --git a/agent/tests/test_sdk_connectors_upbit.py b/agent/tests/test_sdk_connectors_upbit.py
new file mode 100644
index 000000000..165e21154
--- /dev/null
+++ b/agent/tests/test_sdk_connectors_upbit.py
@@ -0,0 +1,138 @@
+"""Tests for the Upbit direct-SDK trading connector.
+
+Mirrors ``test_sdk_connectors.py``: exercises profile registration, the
+structural paper-only guard (Upbit has no runtime paper/live discriminator),
+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.upbit import sdk as up
+from src.trading.connectors.upbit.classification import UPBIT_TOOL_CLASS
+
+pytestmark = pytest.mark.unit
+
+
+# --------------------------------------------------------------------------- #
+# Profile registration
+# --------------------------------------------------------------------------- #
+
+
+def test_upbit_sdk_profiles_registered() -> None:
+ ids = {p.id for p in profiles.list_profiles()}
+ assert {"upbit-paper-sdk", "upbit-paper-trade", "upbit-live-sdk-readonly"} <= ids
+
+
+def test_upbit_live_profile_is_readonly_broker_sdk() -> None:
+ profile = profiles.profile_by_id("upbit-live-sdk-readonly")
+ assert profile.connector == "upbit"
+ 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_upbit_exposes_no_live_trade_profile() -> None:
+ """No runtime discriminator -> no *-live-trade profile, ever (Longbridge precedent)."""
+ ids = {p.id for p in profiles.list_profiles()}
+ assert "upbit-live-trade" not in ids
+ for profile in profiles.list_profiles():
+ if profile.connector == "upbit" and profile.environment == "live":
+ assert not any(".place" in cap or "requires_mandate" in cap for cap in profile.capabilities)
+
+
+# --------------------------------------------------------------------------- #
+# Structural paper-only guard (no runtime discriminator)
+# --------------------------------------------------------------------------- #
+
+
+def test_upbit_paper_place_order_simulated_locally() -> None:
+ cfg = up.UpbitConfig(access_key="ak", secret_key="sk", profile="paper")
+ result = up.place_order(cfg, symbol="KRW-BTC", side="buy", quantity=0.01, limit_price=50_000_000)
+ assert result["status"] == "ok"
+ assert result["is_paper"] is True
+ assert result["order_status"] == "simulated_fill"
+ assert result["paper_guard"] == "simulated_locally"
+ assert result["fill_price"] == 50_000_000
+
+
+def test_upbit_paper_cancel_order_simulated() -> None:
+ cfg = up.UpbitConfig(access_key="ak", secret_key="sk", profile="paper")
+ result = up.cancel_order(cfg, "ORD1")
+ assert result["status"] == "ok"
+ assert result["cancelled"] is True
+ assert result["is_paper"] is True
+
+
+def test_upbit_live_order_hard_refused() -> None:
+ """The guard must be structurally impossible to bypass, not a checked flag:
+ it runs as the first statement in place_order/cancel_order, before any
+ network call — see test_paper_capped_connectors_refuse_live.py."""
+ cfg = up.UpbitConfig(access_key="ak", secret_key="sk", profile="live-readonly")
+ result = up.place_order(cfg, symbol="KRW-BTC", side="buy", quantity=1)
+ assert result["status"] == "error"
+ assert "paper-only" in result["error"]
+
+ cancel_result = up.cancel_order(cfg, "ORD1")
+ assert cancel_result["status"] == "error"
+ assert "paper-only" in cancel_result["error"]
+
+
+def test_upbit_notional_order_fails_closed_when_quote_unavailable(monkeypatch) -> None:
+ """A failed live-quote lookup must not fabricate a null-priced 'ok' fill."""
+ cfg = up.UpbitConfig(access_key="ak", secret_key="sk", profile="paper")
+ monkeypatch.setattr(up, "get_quote", lambda *a, **k: {"status": "error", "error": "network"})
+ result = up.place_order(cfg, symbol="KRW-BTC", side="buy", notional=100_000)
+ assert result["status"] == "error"
+
+
+def test_upbit_place_order_requires_exactly_one_of_quantity_or_notional() -> None:
+ cfg = up.UpbitConfig(access_key="ak", secret_key="sk", profile="paper")
+ both = up.place_order(cfg, symbol="KRW-BTC", side="buy", quantity=1, notional=1000)
+ neither = up.place_order(cfg, symbol="KRW-BTC", side="buy")
+ assert both["status"] == "error"
+ assert neither["status"] == "error"
+
+
+def test_upbit_normalizes_market_symbol() -> None:
+ assert up._normalize_market("krw/btc") == "KRW-BTC"
+ assert up._normalize_market(" KRW-eth ") == "KRW-ETH"
+
+
+def test_upbit_invalid_profile_rejected() -> None:
+ with pytest.raises(up.UpbitConfigError):
+ up.UpbitConfig.from_mapping({"profile": "live"}) # only paper/live-readonly
+
+
+# --------------------------------------------------------------------------- #
+# Redaction / service dispatch / classification
+# --------------------------------------------------------------------------- #
+
+
+def test_upbit_redacts_secret_key() -> None:
+ cfg = up.UpbitConfig(access_key="access-1234", secret_key="super-secret")
+ pub = up._public_config(cfg)
+ assert "super-secret" not in str(pub)
+ assert pub["access_key"].endswith("***")
+ assert pub["secret_key"] == "***redacted***"
+
+
+def test_upbit_service_unconfigured(monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(up, "get_runtime_root", lambda: tmp_path)
+ result = service.check_connection("upbit-paper-sdk")
+ assert result["status"] == "error"
+ assert result["connector"] == "upbit"
+ assert result["transport"] == "broker_sdk"
+
+
+def test_upbit_order_ops_classified_write() -> None:
+ for name in ("place_order", "cancel_order"):
+ assert UPBIT_TOOL_CLASS[name] is ToolClass.WRITE
+ for name in ("get_positions", "get_account_snapshot"):
+ assert UPBIT_TOOL_CLASS[name] is ToolClass.READ