Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(trading): add Toss Securities (토스증권) broker connector

heonjinjeong044d46a0e973
diff --git a/README.md b/README.md
index a1087c2a0..50f4cbf5c 100644
--- a/README.md
+++ b/README.md
@@ -588,9 +588,9 @@ 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.
+Connector-first profiles. Most do read + paper-account order placement — IBKR is read-only, Robinhood is live-only (no paper account), and Trading 212 and Toss Securities refuse 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.
| Broker | Markets | Capabilities |
|--------|---------|--------------|
@@ -603,7 +603,7 @@ Connector-first profiles. Most do read + paper-account order placement — IBKR
| **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 |
-| **Trading 212** | UK / EU | fully read-only — `place_order` / `cancel_order` hard-refuse even paper |
+| **Trading 212** · **Toss Securities** | UK / EU · Korea/US | fully read-only — `place_order` / `cancel_order` hard-refuse even paper (no verified sandbox) |
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..69ffa4701 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -549,9 +549,9 @@ 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 فقط). ومسارات البحث / الاختبار الرجعي محظورة بنيوياً من أي نقطة نهاية حية.
+ملفات تعريف قائمة على الموصّل. يوفّر معظم الموصّلات قراءةً وتنفيذ أوامر على حساب ورقي (paper) — أما IBKR فللقراءة فقط، وRobinhood حيّ فقط (بلا حساب ورقي)، وTrading 212 وToss Securities يرفضان تنفيذ الأوامر كلياً بما فيها الورقية؛ أما تنفيذ الأوامر الحية فمحدود بتفويض يحدّده المستخدم (قائمة رموز مسموح بها، وحدود لحجم الأمر / الانكشاف، وحد يومي للصفقات، ومفتاح إيقاف فوري) ولا يحتفظ الموصّل بأي أموال — الوسيط هو من ينفّذ. تبقى أدوات تنفيذ الأوامر خارج MCP (عبر agent + CLI فقط). ومسارات البحث / الاختبار الرجعي محظورة بنيوياً من أي نقطة نهاية حية.
| الوسيط | الأسواق | القدرات |
|--------|---------|---------|
@@ -564,7 +564,7 @@ LONGBRIDGE_ACCESS_TOKEN=...
| **eToro** | global | قراءة + ورقي + تداول حي محدود (Public API؛ مفاتيح demo لا تصل بنيويًا إلا إلى مسارات `/demo`، مع دعم تدفقات التداول بالنسخ) |
| **MetaTrader 5** | forex / CFD | قراءة + ورقي + تداول حي محدود (بأسلوب Exness؛ حارس هوية demo ⇔ paper) |
| **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** | US / HK · الهند (NSE/BSE) | قراءة + ورقي فقط — لا يوجد مُميِّز وقت-تشغيل بين paper/live، لذا يُرفض تنفيذ الأوامر الحية بشكل صارم |
-| **Trading 212** | UK / EU | قراءة فقط بالكامل — تَرفض `place_order` / `cancel_order` حتى الورقي بشكل صارم |
+| **Trading 212** · **Toss Securities** | UK / EU · كوريا/US | قراءة فقط بالكامل — تَرفض `place_order` / `cancel_order` حتى الورقي بشكل صارم (لا توجد بيئة اختبار موثّقة) |
التمييز بين الورقي والحي هو **حارس بنيوي على مستوى وقت التشغيل لكل وسيط** (صيغة معرّف الحساب، أو فصل المضيف، أو علامة demo، أو بيئة التداول)، وليس مجرّد إعداد يمكن للوكيل تبديله. أي وسيط لا يكشف عن هذا المُميِّز يُحصَر في الورقي + القراءة فقط.
diff --git a/README_es.md b/README_es.md
index efe2dc6f4..adafa2f6e 100644
--- a/README_es.md
+++ b/README_es.md
@@ -553,9 +553,9 @@ 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.
+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 y Toss Securities rechazan 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.
| Broker | Mercados | Capacidades |
|--------|---------|--------------|
@@ -568,7 +568,7 @@ Perfiles centrados en el conector. La mayoría hace lectura + colocación de ór
| **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 |
-| **Trading 212** | Reino Unido / UE | completamente de solo lectura — `place_order` / `cancel_order` se rechazan de forma estricta incluso en paper |
+| **Trading 212** · **Toss Securities** | Reino Unido / UE · Corea/EE. UU. | completamente de solo lectura — `place_order` / `cancel_order` se rechazan de forma estricta incluso en paper (sin sandbox verificado) |
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..78147afe9 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -549,9 +549,9 @@ 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 から遮断されています。
+connector-first のプロファイル。多くは read + ペーパー口座での発注に対応します —— IBKR は読み取り専用、Robinhood はライブのみ(ペーパー口座なし)、Trading 212 と Toss Securities はペーパーを含め発注を一切拒否します。ライブ発注はユーザーが定義した mandate(銘柄許可リスト、発注サイズ / エクスポージャー上限、1 日の取引回数上限、即時 kill switch)で制限され、資金を預かることは一切ありません —— 執行するのはブローカーです。発注系ツールは MCP に公開されません(agent + CLI のみ)。リサーチ / バックテスト経路は構造的にあらゆるライブ endpoint から遮断されています。
| Broker | Markets | Capabilities |
|--------|---------|--------------|
@@ -564,7 +564,7 @@ connector-first のプロファイル。多くは read + ペーパー口座で
| **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 |
-| **Trading 212** | UK / EU | fully read-only — `place_order` / `cancel_order` hard-refuse even paper |
+| **Trading 212** · **Toss Securities** | UK / EU · Korea/US | fully read-only — `place_order` / `cancel_order` hard-refuse even paper (no verified sandbox) |
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..a9492846a 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -549,9 +549,9 @@ 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 전용). 리서치 / 백테스트 경로는 구조적으로 모든 실거래 엔드포인트에서 차단됩니다.
+connector-first 프로필. 대부분의 브로커가 read + 페이퍼 계정 주문 실행을 지원하지만 IBKR은 읽기 전용이고, Robinhood는 페이퍼 계정 없이 실거래 전용이며, Trading 212와 Toss Securities는 페이퍼를 포함해 주문 실행을 모두 거부하고, 실거래 주문 실행은 사용자 정의 mandate(심볼 허용목록, 주문 크기 / 익스포저 상한, 일일 거래 한도, 즉시 kill switch)로 제한되고 자금을 보관하지 않습니다 — 실행은 브로커가 합니다. 주문 실행 도구는 MCP에 노출되지 않습니다(agent + CLI 전용). 리서치 / 백테스트 경로는 구조적으로 모든 실거래 엔드포인트에서 차단됩니다.
| Broker | Markets | Capabilities |
|--------|---------|--------------|
@@ -564,7 +564,7 @@ connector-first 프로필. 대부분의 브로커가 read + 페이퍼 계정 주
| **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 |
-| **Trading 212** | UK / EU | fully read-only — `place_order` / `cancel_order` hard-refuse even paper |
+| **Trading 212** · **Toss Securities** | UK / EU · 한국/US | fully read-only — `place_order` / `cancel_order` hard-refuse even paper (no verified sandbox) |
Paper-vs-live는 **구조적 브로커별 런타임 가드**(account-id 형식, 호스트 분리, demo 플래그, 또는 trade environment)이며, agent가 뒤집을 수 있는 config 플래그가 아닙니다. 그런 구분자를 노출하지 않는 브로커는 페이퍼 + 읽기 전용으로 제한됩니다.
diff --git a/README_zh.md b/README_zh.md
index cbc34ee13..b8c9bff9a 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -562,9 +562,9 @@ 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)。研究 / 回测路径在结构上被隔离,无法触达任何实盘端点。
+连接器优先(connector-first)的配置档。多数连接器支持读取 + 模拟盘下单 —— IBKR 只读,Robinhood 只有实盘(没有模拟盘),Trading 212 与 Toss Securities 连模拟盘下单也一律拒绝;实盘下单受用户定义的 mandate 约束(标的白名单、下单规模 / 敞口上限、每日交易次数上限、即时 kill switch),且从不托管资金——由券商执行。下单类工具不经 MCP 暴露(仅 agent + CLI)。研究 / 回测路径在结构上被隔离,无法触达任何实盘端点。
| Broker | 市场 | 能力 |
|--------|------|------|
@@ -577,7 +577,7 @@ LONGBRIDGE_ACCESS_TOKEN=...
| **eToro** | global | 读取 + 模拟盘 + 受约束实盘(Public API;demo 密钥在结构上只能访问 `/demo` 路径,另支持跟单交易流程) |
| **MetaTrader 5** | forex / CFD | 读取 + 模拟盘 + 受约束实盘(Exness 风格;demo ⇔ 模拟盘身份守卫) |
| **Longbridge** · **Dhan** · **Shoonya** · **Zerodha** | US / HK · India (NSE/BSE) | 仅读取 + 模拟盘——无运行时模拟/实盘判别标识,因此实盘下单被硬拒 |
-| **Trading 212** | UK / EU | 完全只读——`place_order` / `cancel_order` 连模拟盘也硬拒 |
+| **Trading 212** · **Toss Securities** | UK / EU · 韩国/美国 | 完全只读——`place_order` / `cancel_order` 连模拟盘也硬拒(无可验证的沙盒) |
模拟盘与实盘的区分是**每家券商的结构性运行时守卫**(account-id 格式、host 隔离、demo 标志或交易环境),绝非 agent 能翻转的配置开关。不暴露此类判别标识的券商一律封顶为模拟盘 + 只读。
diff --git a/agent/SKILL.md b/agent/SKILL.md
index beaa3950e..8c9c55b17 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). Korea equity trading also has the **Toss Securities** connector (토스증권; KR/US equities, fully read-only — no verified sandbox, so order placement always refuses, same as Trading 212).
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..ab55e7248 100644
--- a/agent/src/live/registry.py
+++ b/agent/src/live/registry.py
@@ -35,6 +35,7 @@ from src.trading.connectors.robinhood.classification import ROBINHOOD_TOOL_CLASS
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.toss.classification import TOSS_TOOL_CLASS
from src.trading.connectors.trading212.classification import TRADING212_TOOL_CLASS
from src.trading.connectors.zerodha.classification import ZERODHA_TOOL_CLASS
@@ -59,6 +60,7 @@ _BROKER_CURATED_MAPS = {
"mt5": MT5_TOOL_CLASS,
"etoro": ETORO_TOOL_CLASS,
"zerodha": ZERODHA_TOOL_CLASS,
+ "toss": TOSS_TOOL_CLASS,
}
diff --git a/agent/src/trading/connectors/toss/__init__.py b/agent/src/trading/connectors/toss/__init__.py
new file mode 100644
index 000000000..a1e8edaa1
--- /dev/null
+++ b/agent/src/trading/connectors/toss/__init__.py
@@ -0,0 +1,11 @@
+"""Toss Securities (토스증권) trading connector.
+
+Read-only account/holdings/quote/history access via the official Toss Invest
+Open API (OAuth2 client-credentials token, no third-party SDK required). A
+``broker_sdk`` transport for Korean (KRX) and US equities.
+
+Toss Securities' Open API launched in 2026 and, like Trading 212, exposes no
+sandbox and no verifiable paper/live discriminator — every credentialed call
+reaches the operator's real brokerage account. Order placement is therefore
+disabled for every profile, following the Trading 212 precedent.
+"""
diff --git a/agent/src/trading/connectors/toss/classification.py b/agent/src/trading/connectors/toss/classification.py
new file mode 100644
index 000000000..75b2ce5c8
--- /dev/null
+++ b/agent/src/trading/connectors/toss/classification.py
@@ -0,0 +1,25 @@
+"""Curated read/write classification for Toss Securities 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.
+``place_order``/``cancel_order`` always refuse (see ``sdk.py``), but stay
+classified WRITE for defense in depth.
+"""
+
+from __future__ import annotations
+
+from src.live.classification import ToolClass
+
+#: Toss Securities REST operation read/write catalog.
+TOSS_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 (always refused, see sdk.place_order/cancel_order)
+ "place_order": ToolClass.WRITE,
+ "cancel_order": ToolClass.WRITE,
+}
diff --git a/agent/src/trading/connectors/toss/profiles.py b/agent/src/trading/connectors/toss/profiles.py
new file mode 100644
index 000000000..786570d65
--- /dev/null
+++ b/agent/src/trading/connectors/toss/profiles.py
@@ -0,0 +1,31 @@
+"""Built-in Toss Securities (토스증권) connector profiles.
+
+Toss Invest's Open API (https://developers.tossinvest.com) documents no
+sandbox and no runtime paper/live discriminator, and applying for API access
+requires a real brokerage account — following the Trading 212 precedent, this
+connector is therefore fully read-only: ``place_order``/``cancel_order``
+hard-refuse for every profile, paper included.
+"""
+
+from __future__ import annotations
+
+from src.trading.types import READ_CAPABILITIES, TradingProfile
+
+TOSS_PROFILES: tuple[TradingProfile, ...] = (
+ TradingProfile(
+ id="toss-live-sdk-readonly",
+ connector="toss",
+ label="Toss Securities · REST Read-Only (Korea)",
+ environment="live",
+ transport="broker_sdk",
+ capabilities=READ_CAPABILITIES,
+ readonly=True,
+ config={"profile": "live-readonly"},
+ notes=(
+ "Reads a live Toss Securities account (holdings, order history, "
+ "quotes, candles) for KR and US equities. Order placement and "
+ "cancellation hard-refuse: Toss documents no sandbox this "
+ "connector can verify."
+ ),
+ ),
+)
diff --git a/agent/src/trading/connectors/toss/sdk.py b/agent/src/trading/connectors/toss/sdk.py
new file mode 100644
index 000000000..03f6c6b94
--- /dev/null
+++ b/agent/src/trading/connectors/toss/sdk.py
@@ -0,0 +1,594 @@
+"""Read-only Toss Securities (토스증권) connector via the public REST API.
+
+Wraps the Toss Invest Open API's account, holdings, order-history, price, and
+candle endpoints. No third-party SDK is required — ``requests`` only.
+
+Paper-vs-live identity guard: none is verifiable. Toss Securities' Open API
+(https://developers.tossinvest.com) requires a live brokerage account to
+apply for API access and documents no sandbox environment, so — following the
+Trading 212 precedent — the configured ``profile`` is operator-declared and
+recorded in every payload as
+``paper_guard="read_only_no_runtime_discriminator"``. Order placement and
+cancellation are disabled for every profile until Toss offers a structural
+paper/demo safety boundary this connector can verify.
+
+Caveat: this connector was authored from the public Open API reference
+(https://developers.tossinvest.com/docs) without a live Toss account to test
+against — exact field names for less-common responses may need adjustment.
+Endpoint paths and the OAuth flow (client-credentials grant) are documented;
+verify response field names against the live API 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 = "toss.json"
+DEFAULT_BASE_URL = "https://openapi.tossinvest.com"
+PAPER_GUARD = "read_only_no_runtime_discriminator"
+
+PROFILE_ENVIRONMENTS = {
+ "paper": "paper",
+ "live-readonly": "live",
+ "live": "live",
+}
+
+#: Safety margin subtracted from the token's reported TTL before it is
+#: treated as expired.
+_TOKEN_REFRESH_MARGIN_SECONDS = 120
+
+
+class TossConfigError(RuntimeError):
+ """Raised when the Toss connector configuration is missing or invalid."""
+
+
+class TossAPIError(RuntimeError):
+ """Raised when Toss returns an auth, HTTP, network, or JSON error."""
+
+
+@dataclass(frozen=True)
+class TossConfig:
+ """Toss Securities connector connection settings.
+
+ Args:
+ client_id: Toss Invest Open API client ID.
+ client_secret: Toss Invest Open API client secret.
+ account_seq: The ``accountSeq`` identifying which brokerage account to
+ read (from ``GET /api/v1/accounts``); required for account-scoped
+ calls via the ``X-Tossinvest-Account`` header.
+ profile: ``paper``, ``live-readonly`` or ``live``. Operator-declared;
+ Toss responses do not prove the account environment.
+ base_url: Public API base URL.
+ timeout: Network timeout in seconds.
+ readonly: Always true for built-in profiles; order methods refuse all
+ requests regardless of this flag.
+ """
+
+ client_id: str = ""
+ client_secret: str = ""
+ account_seq: str = ""
+ profile: str = "live-readonly"
+ base_url: str = DEFAULT_BASE_URL
+ timeout: float = 15.0
+ readonly: bool = True
+
+ @classmethod
+ def from_mapping(cls, data: Mapping[str, Any] | None = None) -> "TossConfig":
+ """Build a config from a JSON-like mapping, normalizing profile/URL."""
+ payload = dict(data or {})
+ profile = str(payload.get("profile") or "live-readonly").strip().lower()
+ if profile not in PROFILE_ENVIRONMENTS:
+ raise TossConfigError("profile must be 'paper', 'live-readonly' or 'live'")
+ base_url = str(payload.get("base_url") or DEFAULT_BASE_URL).strip().rstrip("/")
+ if not base_url.startswith(("http://", "https://")):
+ raise TossConfigError("base_url must start with http:// or https://")
+ return cls(
+ client_id=str(payload.get("client_id") or "").strip(),
+ client_secret=str(payload.get("client_secret") or "").strip(),
+ account_seq=str(payload.get("account_seq") or "").strip(),
+ profile=profile,
+ base_url=base_url,
+ timeout=float(payload.get("timeout") or 15.0),
+ readonly=bool(payload.get("readonly", True)),
+ )
+
+ def with_overrides(
+ self,
+ *,
+ client_id: str | None = None,
+ client_secret: str | None = None,
+ account_seq: str | None = None,
+ profile: str | None = None,
+ base_url: str | None = None,
+ ) -> "TossConfig":
+ """Return a copy with CLI/tool overrides applied."""
+ payload = asdict(self)
+ if client_id is not None:
+ payload["client_id"] = client_id
+ if client_secret is not None:
+ payload["client_secret"] = client_secret
+ if account_seq is not None:
+ payload["account_seq"] = account_seq
+ if profile is not None:
+ payload["profile"] = profile
+ if base_url is not None:
+ payload["base_url"] = base_url
+ return TossConfig.from_mapping(payload)
+
+ @property
+ def environment(self) -> str:
+ """Return ``paper`` or ``live`` for the operator-declared profile."""
+ return PROFILE_ENVIRONMENTS.get(self.profile, "live")
+
+
+_OVERRIDE_KEYS = ("client_id", "client_secret", "account_seq", "profile", "base_url")
+
+
+def build_config(
+ profile_config: Mapping[str, Any] | None = None,
+ overrides: Mapping[str, Any] | None = None,
+) -> TossConfig:
+ """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 = TossConfig.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 the user-level Toss config path."""
+ return get_runtime_root() / CONFIG_FILENAME
+
+
+def load_config() -> TossConfig:
+ """Load Toss settings from ``~/.vibe-trading/toss.json``."""
+ path = config_path()
+ if not path.exists():
+ return TossConfig()
+ try:
+ return TossConfig.from_mapping(json.loads(path.read_text(encoding="utf-8")))
+ except (OSError, ValueError, json.JSONDecodeError) as exc:
+ raise TossConfigError(f"invalid Toss config at {path}: {exc}") from exc
+
+
+def save_config(config: TossConfig) -> Path:
+ """Persist Toss settings with owner-only permissions."""
+ 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 check_status(config: TossConfig | 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},
+ "paper_guard": PAPER_GUARD,
+ "base_url": cfg.base_url,
+ }
+
+ missing = _missing_fields(cfg)
+ if missing:
+ report["status"] = "error"
+ report["error"] = f"Toss connector not configured: missing {', '.join(missing)}."
+ return report
+
+ try:
+ get_account_snapshot(cfg)
+ except (TossConfigError, TossAPIError) as exc:
+ report["status"] = "error"
+ report["error"] = str(exc)
+ return report
+
+ report["account"] = {"profile": cfg.profile, "account_seq": cfg.account_seq}
+ return report
+
+
+def get_account_snapshot(config: TossConfig | None = None) -> dict[str, Any]:
+ """Fetch holdings summary totals for the configured account."""
+ cfg = config or load_config()
+ payload = _get(cfg, "/api/v1/assets", authed=True, account_scoped=True)
+ summary = _mapping_or_raw(_first(payload, ("summary", "accountSummary")))
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "paper_guard": PAPER_GUARD,
+ "account": summary,
+ }
+
+
+def get_positions(config: TossConfig | None = None) -> dict[str, Any]:
+ """Fetch current KR/US equity holdings."""
+ cfg = config or load_config()
+ payload = _get(cfg, "/api/v1/assets", authed=True, account_scoped=True)
+ return {
+ "status": "ok",
+ "profile": cfg.profile,
+ "paper_guard": PAPER_GUARD,
+ "positions": [_position_to_dict(item) for item in _extract_items(payload)],
+ }
+
+
+def get_open_orders(
+ config: TossConfig | None = None,
+ *,
+ include_executions: bool = False,
+) -> dict[str, Any]:
+ """Fetch open Toss orders, optionally with recently closed ones."""
+ cfg = config or load_config()
+ open_payload = _get(cfg, "/api/v1/order-history", authed=True, account_scoped=True, params={"status": "OPEN"})
+ result: dict[str, Any] = {
+ "status": "ok",
+ "profile": cfg.profile,
+ "paper_guard": PAPER_GUARD,
+ "open_orders": [_order_to_dict(item) for item in _extract_items(open_payload)],
+ }
+ if include_executions:
+ closed_payload = _get(
+ cfg, "/api/v1/order-history", authed=True, account_scoped=True, params={"status": "CLOSED"}
+ )
+ result["executions"] = [_order_to_dict(item) for item in _extract_items(closed_payload)]
+ return result
+
+
+def get_quote(symbol: str, *, config: TossConfig | None = None, **_: Any) -> dict[str, Any]:
+ """Fetch the current price for a symbol (KR 6-digit code or US ticker)."""
+ cfg = config or load_config()
+ clean = str(symbol or "").strip().upper()
+ try:
+ payload = _get(cfg, "/api/v1/prices", authed=True, account_scoped=False, params={"symbols": clean})
+ except TossAPIError as exc:
+ return {"status": "error", "error": str(exc), "symbol": clean}
+
+ row = _first_item(payload)
+ return {
+ "status": "ok",
+ "symbol": clean,
+ "quote": {
+ "last": _first(row, ("lastPrice", "price")),
+ "currency": _first(row, ("currency",)),
+ "timestamp": _first(row, ("timestamp",)),
+ },
+ }
+
+
+def get_historical_bars(
+ symbol: str,
+ *,
+ config: TossConfig | None = None,
+ period: str = "1d",
+ limit: int = 200,
+) -> dict[str, Any]:
+ """Fetch OHLCV candles for a symbol.
+
+ ``period`` tokens: ``1m`` → 1-minute candles, ``1d``/``1D`` → daily
+ candles (per the documented ``/api/v1/candles`` granularities). Other
+ periods fail closed instead of silently substituting a different bar size.
+ """
+ cfg = config or load_config()
+ clean = str(symbol or "").strip().upper()
+ token = period.strip()
+ interval = {"1m": "1m", "1d": "1d", "1D": "1d"}.get(token)
+ if interval is None:
+ return {
+ "status": "error",
+ "error": f"unsupported period: {period!r}; supported: ['1m', '1d']",
+ "symbol": clean,
+ }
+
+ capped_limit = min(int(limit), 200) # documented cap: 200 candles per call
+ try:
+ payload = _get(
+ cfg,
+ "/api/v1/candles",
+ authed=True,
+ account_scoped=False,
+ params={"symbol": clean, "interval": interval, "limit": capped_limit},
+ )
+ except TossAPIError as exc:
+ return {"status": "error", "error": str(exc), "symbol": clean}
+
+ bars = [_bar_to_dict(item) for item in _extract_items(payload)]
+ return {"status": "ok", "symbol": clean, "period": period, "bars": bars}
+
+
+_ORDER_DISABLED_ERROR = (
+ "Toss Securities connector is read-only: order placement and cancellation "
+ "are disabled until a structural paper/demo safety boundary is available."
+)
+
+_LIVE_ORDER_ERROR = (
+ "Toss Securities order placement is not supported for live/read-only "
+ "profiles (no runtime paper/live discriminator is available)."
+)
+
+
+def place_order(
+ config: TossConfig | 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]:
+ """Refuse Toss order placement before any REST client is touched."""
+ cfg = config or load_config()
+ # ---- HARD GUARD: no verified live safety boundary (must run first) ----
+ if cfg.environment != "paper":
+ return _order_refused(cfg, _LIVE_ORDER_ERROR, symbol=symbol, side=side)
+ return _order_refused(
+ cfg,
+ _ORDER_DISABLED_ERROR,
+ symbol=symbol,
+ side=side,
+ quantity=quantity,
+ notional=notional,
+ order_type=order_type,
+ limit_price=limit_price,
+ time_in_force=time_in_force,
+ )
+
+
+def cancel_order(
+ config: TossConfig | None = None,
+ order_id: str = "",
+ *,
+ symbol: str | None = None,
+) -> dict[str, Any]:
+ """Refuse Toss order cancellation before any REST client is touched."""
+ cfg = config or load_config()
+ # ---- HARD GUARD: no verified live safety boundary (must run first) ----
+ if cfg.environment != "paper":
+ return _order_refused(cfg, _LIVE_ORDER_ERROR, order_id=order_id, symbol=symbol)
+ return _order_refused(cfg, _ORDER_DISABLED_ERROR, order_id=order_id, symbol=symbol)
+
+
+# ---------------------------------------------------------------------------
+# SDK plumbing
+# ---------------------------------------------------------------------------
+
+
+def _token_cache_path(cfg: TossConfig) -> Path:
+ return get_runtime_root() / "toss-token.json"
+
+
+def _access_token(cfg: TossConfig) -> str:
+ """Return a cached or freshly issued OAuth2 client-credentials token."""
+ path = _token_cache_path(cfg)
+ now = time.time()
+ if path.exists():
+ try:
+ cached = json.loads(path.read_text(encoding="utf-8"))
+ if cached.get("client_id") == cfg.client_id 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/token",
+ data={
+ "grant_type": "client_credentials",
+ "client_id": cfg.client_id,
+ "client_secret": cfg.client_secret,
+ },
+ timeout=cfg.timeout,
+ )
+ except requests.RequestException as exc:
+ raise TossAPIError(f"Toss token request failed: {exc}") from exc
+ if response.status_code >= 400:
+ raise TossAPIError(f"Toss token issuance returned HTTP {response.status_code}: {_error_message(response)}")
+
+ body = response.json()
+ token = str(body.get("access_token") or "")
+ if not token:
+ raise TossAPIError(f"Toss 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({
+ "client_id": cfg.client_id,
+ "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 _get(
+ cfg: TossConfig,
+ path: str,
+ *,
+ authed: bool,
+ account_scoped: bool,
+ params: Mapping[str, Any] | None = None,
+) -> Any:
+ missing = _missing_fields(cfg, account_scoped=account_scoped)
+ if missing:
+ raise TossConfigError(f"Toss connector not configured: missing {', '.join(missing)}.")
+
+ headers = {"Accept": "application/json"}
+ if authed:
+ headers["Authorization"] = f"Bearer {_access_token(cfg)}"
+ if account_scoped:
+ headers["X-Tossinvest-Account"] = cfg.account_seq
+
+ try:
+ response = requests.get(
+ f"{cfg.base_url}{path}",
+ headers=headers,
+ params=dict(params or {}),
+ timeout=cfg.timeout,
+ )
+ except requests.RequestException as exc:
+ raise TossAPIError(f"Toss request failed: {exc}") from exc
+
+ if response.status_code in (401, 403):
+ raise TossAPIError("Toss API authentication failed: check client_id/client_secret/account_seq.")
+ if response.status_code >= 400:
+ raise TossAPIError(f"Toss API returned HTTP {response.status_code}: {_error_message(response)}")
+ if not response.content:
+ return None
+ try:
+ return response.json()
+ except ValueError as exc:
+ raise TossAPIError("Toss 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 ("message", "error", "error_description", "detail"):
+ value = payload.get(key)
+ if value:
+ return str(value)
+ return str(payload)
+
+
+def _missing_fields(cfg: TossConfig, *, account_scoped: bool = True) -> list[str]:
+ missing = []
+ if not cfg.client_id:
+ missing.append("client_id")
+ if not cfg.client_secret:
+ missing.append("client_secret")
+ if account_scoped and not cfg.account_seq:
+ missing.append("account_seq")
+ return missing
+
+
+def _public_config(cfg: TossConfig) -> dict[str, Any]:
+ data = asdict(cfg)
+ if data.get("client_id"):
+ data["client_id"] = data["client_id"][:4] + "***"
+ if data.get("client_secret"):
+ data["client_secret"] = "***redacted***"
+ return data
+
+
+def _order_refused(config: TossConfig, message: str, **extra: Any) -> dict[str, Any]:
+ payload: dict[str, Any] = {
+ "status": "error",
+ "error": message,
+ "profile": config.profile,
+ "paper_guard": PAPER_GUARD,
+ }
+ payload.update({key: value for key, value in extra.items() if value is not None})
+ return payload
+
+
+def _as_iter(value: Any) -> list[Any]:
+ if value is None:
+ return []
+ if isinstance(value, (list, tuple)):
+ return list(value)
+ return [value]
+
+
+def _extract_items(payload: Any) -> list[Any]:
+ if isinstance(payload, list):
+ return payload
+ if isinstance(payload, Mapping):
+ for key in ("items", "data", "holdings", "orders", "candles", "prices", "results"):
+ value = payload.get(key)
+ if isinstance(value, list):
+ return value
+ return _as_iter(payload)
+
+
+def _first_item(payload: Any) -> Any:
+ items = _extract_items(payload)
+ return items[0] if items else {}
+
+
+def _mapping_or_raw(value: Any) -> dict[str, Any]:
+ if isinstance(value, Mapping):
+ return dict(value)
+ if value is None:
+ return {}
+ return {"raw": value}
+
+
+def _obj_get(obj: Any, name: str, default: Any = None) -> Any:
+ if obj is None:
+ return default
+ if isinstance(obj, Mapping):
+ return obj.get(name, default)
+ return getattr(obj, name, default)
+
+
+def _first(obj: Any, names: tuple[str, ...], default: Any = None) -> Any:
+ for name in names:
+ value = _obj_get(obj, name, None)
+ if value is not None:
+ return value
+ return default
+
+
+def _position_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "symbol": _first(item, ("symbol", "productCode")),
+ "name": _first(item, ("name", "productName")),
+ "quantity": _first(item, ("quantity", "qty")),
+ "average_price": _first(item, ("averagePrice", "avgPrice")),
+ "current_price": _first(item, ("currentPrice", "price")),
+ "pnl": _first(item, ("profitLoss", "pnl")),
+ "currency": _first(item, ("currency",)),
+ "market": _first(item, ("market", "exchange")),
+ }
+
+
+def _order_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "order_id": str(_first(item, ("orderId", "id"), "")),
+ "symbol": _first(item, ("symbol", "productCode")),
+ "side": str(_first(item, ("side",), "")),
+ "order_type": str(_first(item, ("orderType", "type"), "")),
+ "status": str(_first(item, ("status",), "")),
+ "quantity": _first(item, ("quantity", "qty")),
+ "filled_quantity": _first(item, ("filledQuantity", "filledQty")),
+ "price": _first(item, ("price", "limitPrice")),
+ "currency": _first(item, ("currency",)),
+ "created_at": _first(item, ("createdAt", "orderedAt")),
+ }
+
+
+def _bar_to_dict(item: Any) -> dict[str, Any]:
+ return {
+ "time": _first(item, ("timestamp", "time")),
+ "open": _first(item, ("openPrice", "open")),
+ "high": _first(item, ("highPrice", "high")),
+ "low": _first(item, ("lowPrice", "low")),
+ "close": _first(item, ("closePrice", "close")),
+ "volume": _first(item, ("volume",)),
+ }
diff --git a/agent/src/trading/onboarding.py b/agent/src/trading/onboarding.py
index a488e3381..ae7543119 100644
--- a/agent/src/trading/onboarding.py
+++ b/agent/src/trading/onboarding.py
@@ -161,6 +161,20 @@ _BUILTIN: dict[str, ConnectorOnboarding] = {
dependency="requests",
install_command="pip install keyring",
),
+ "toss": ConnectorOnboarding(
+ auth_type="api_key",
+ credential_fields=(
+ _field("client_id", "Client ID"),
+ _field("client_secret", "Client Secret"),
+ _field("account_seq", "Account Sequence", secret=False),
+ ),
+ dependency="requests",
+ install_command="pip install keyring",
+ setup_hint=(
+ "Apply via the Toss Securities app (더보기 > Open API), then fetch "
+ "account_seq from GET /api/v1/accounts."
+ ),
+ ),
}
diff --git a/agent/src/trading/profiles.py b/agent/src/trading/profiles.py
index e01ecdc30..a125c83bd 100644
--- a/agent/src/trading/profiles.py
+++ b/agent/src/trading/profiles.py
@@ -18,6 +18,7 @@ from src.trading.connectors.robinhood.profiles import ROBINHOOD_PROFILES
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.toss.profiles import TOSS_PROFILES
from src.trading.connectors.trading212.profiles import TRADING212_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,
+ *TOSS_PROFILES,
)
diff --git a/agent/src/trading/service.py b/agent/src/trading/service.py
index 2d8693cc8..088f2ef8e 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",
+ "toss": "src.trading.connectors.toss.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..6a6083c11 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", "toss"})
# 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..df07abc47 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",
+ "toss": "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..d0489d51b 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",
+ "toss-live-sdk-readonly",
} <= ids
diff --git a/agent/tests/test_sdk_connectors_toss.py b/agent/tests/test_sdk_connectors_toss.py
new file mode 100644
index 000000000..fc532e243
--- /dev/null
+++ b/agent/tests/test_sdk_connectors_toss.py
@@ -0,0 +1,101 @@
+"""Tests for the Toss Securities (토스증권) direct-SDK trading connector.
+
+Mirrors ``test_sdk_connectors.py``: exercises profile registration, the
+fully-read-only guard (Toss documents no verifiable sandbox, following the
+Trading 212 precedent), 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.toss import sdk as toss
+from src.trading.connectors.toss.classification import TOSS_TOOL_CLASS
+
+pytestmark = pytest.mark.unit
+
+
+# --------------------------------------------------------------------------- #
+# Profile registration
+# --------------------------------------------------------------------------- #
+
+
+def test_toss_sdk_profile_registered() -> None:
+ ids = {p.id for p in profiles.list_profiles()}
+ assert "toss-live-sdk-readonly" in ids
+
+
+def test_toss_exposes_no_paper_or_live_trade_profile() -> None:
+ """Toss documents no verifiable sandbox — every profile is read-only,
+ mirroring the Trading 212 precedent (never even a paper-trade profile)."""
+ toss_profiles = [p for p in profiles.list_profiles() if p.connector == "toss"]
+ assert toss_profiles
+ for profile in toss_profiles:
+ assert profile.readonly is True
+ assert not any(".place" in cap for cap in profile.capabilities)
+
+
+# --------------------------------------------------------------------------- #
+# Order refusal (fully read-only, like Trading 212)
+# --------------------------------------------------------------------------- #
+
+
+def test_toss_place_order_always_refused() -> None:
+ cfg = toss.TossConfig(client_id="c", client_secret="s", account_seq="1", profile="live-readonly")
+ result = toss.place_order(cfg, symbol="005930", side="buy", quantity=1)
+ assert result["status"] == "error"
+ assert "read-only" in result["error"]
+ assert result["paper_guard"] == "read_only_no_runtime_discriminator"
+
+
+def test_toss_cancel_order_always_refused() -> None:
+ cfg = toss.TossConfig(client_id="c", client_secret="s", account_seq="1")
+ result = toss.cancel_order(cfg, "ORD1")
+ assert result["status"] == "error"
+ assert "read-only" in result["error"]
+
+
+def test_toss_place_order_refused_even_when_declared_paper() -> None:
+ """No verified sandbox exists, so even a 'paper'-declared profile refuses —
+ unlike Dhan/Upbit, there is no honest local simulation to fall back to."""
+ cfg = toss.TossConfig(client_id="c", client_secret="s", account_seq="1", profile="paper")
+ result = toss.place_order(cfg, symbol="005930", side="buy", quantity=1)
+ assert result["status"] == "error"
+ assert "disabled" in result["error"]
+
+
+def test_toss_invalid_profile_rejected() -> None:
+ with pytest.raises(toss.TossConfigError):
+ toss.TossConfig.from_mapping({"profile": "go-live"})
+
+
+# --------------------------------------------------------------------------- #
+# Redaction / service dispatch / classification
+# --------------------------------------------------------------------------- #
+
+
+def test_toss_redacts_client_secret() -> None:
+ cfg = toss.TossConfig(client_id="client-1234", client_secret="super-secret", account_seq="1")
+ pub = toss._public_config(cfg)
+ assert "super-secret" not in str(pub)
+ assert pub["client_id"].endswith("***")
+ assert pub["client_secret"] == "***redacted***"
+
+
+def test_toss_service_unconfigured(monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(toss, "get_runtime_root", lambda: tmp_path)
+ result = service.check_connection("toss-live-sdk-readonly")
+ assert result["status"] == "error"
+ assert result["connector"] == "toss"
+ assert result["transport"] == "broker_sdk"
+
+
+def test_toss_order_ops_classified_write() -> None:
+ for name in ("place_order", "cancel_order"):
+ assert TOSS_TOOL_CLASS[name] is ToolClass.WRITE
+ for name in ("get_positions", "get_account_snapshot"):
+ assert TOSS_TOOL_CLASS[name] is ToolClass.READ