"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(toss): correct the read paths, response envelope, and candle param on #1409
heonjinjeong0b8c6bfc1fe0
diff --git a/.gitignore b/.gitignoreindex c0ca11f3a..d3008223a 100644--- a/.gitignore+++ b/.gitignore@@ -84,6 +84,8 @@ agent/uploads//okx.json/shoonya.json/tiger.json+/toss.json+/toss-token.json/trading212.json/zerodha.jsonagent/tests/*_result.jsondiff --git a/agent/SKILL.md b/agent/SKILL.mdindex 8c9c55b17..dcc78ad40 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). 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).+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). Read-only Korea/US equity access is also available via the **Toss Securities** connector (토스증권) — no verified sandbox, so order placement always refuses, same as Trading 212.Example workflow:1. Use `list_skills()` to discover strategy patternsdiff --git a/agent/src/portfolio/compatibility.py b/agent/src/portfolio/compatibility.pyindex 534bdd5d9..06617713b 100644--- a/agent/src/portfolio/compatibility.py+++ b/agent/src/portfolio/compatibility.py@@ -98,6 +98,7 @@ _CONNECTOR_COMPATIBILITY: dict[str, PortfolioCompatibility] = {"open_positions","Account totals and instrument quote resolution require verification.",),+ "toss": PortfolioCompatibility("experimental", 1, "positions", "KRW valuation is not supported yet."),}_EXPERIMENTAL_DEFAULT = PortfolioCompatibility(diff --git a/agent/src/trading/connectors/toss/sdk.py b/agent/src/trading/connectors/toss/sdk.pyindex 03f6c6b94..f6c6b84a6 100644--- a/agent/src/trading/connectors/toss/sdk.py+++ b/agent/src/trading/connectors/toss/sdk.py@@ -12,17 +12,18 @@ recorded in every payload ascancellation are disabled for every profile until Toss offers a structuralpaper/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.+Caveat: this connector was authored and endpoint paths verified against the+published OpenAPI spec (https://openapi.tossinvest.com/openapi-docs/latest/+openapi.json) without a live Toss account to test against. Every response is+wrapped as ``{"result": ...}`` (see :func:`_unwrap`); field names inside that+envelope for less-common responses may still need adjustment against a real+account."""from __future__ import annotationsimport json+import osimport timefrom dataclasses import asdict, dataclassfrom pathlib import Path@@ -203,11 +204,16 @@ def check_status(config: TossConfig | None = None) -> dict[str, Any]:return report+#: Order-status tokens the Toss API is documented to use for a resting order.+#: Anything else observed on a row is treated as closed/executed.+_OPEN_ORDER_STATUSES = frozenset({"OPEN", "PENDING", "PARTIALLY_FILLED", "NEW"})++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")))+ payload = _get(cfg, "/api/v1/holdings", authed=True, account_scoped=True)+ summary = _mapping_or_raw(_first(_unwrap(payload), ("summary", "accountSummary")))return {"status": "ok","profile": cfg.profile,@@ -219,7 +225,7 @@ def get_account_snapshot(config: TossConfig | None = None) -> dict[str, Any]: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)+ payload = _get(cfg, "/api/v1/holdings", authed=True, account_scoped=True)return {"status": "ok","profile": cfg.profile,@@ -233,20 +239,25 @@ def get_open_orders(*,include_executions: bool = False,) -> dict[str, Any]:- """Fetch open Toss orders, optionally with recently closed ones."""+ """Fetch Toss orders, split into still-open vs already-executed.++ Toss exposes one order-reading endpoint rather than separate open/history+ ones, so open vs executed is a client-side split on each row's own status+ field, the same way the Dhan/Trading 212 connectors do it.+ """cfg = config or load_config()- open_payload = _get(cfg, "/api/v1/order-history", authed=True, account_scoped=True, params={"status": "OPEN"})+ payload = _get(cfg, "/api/v1/orders", authed=True, account_scoped=True)+ rows = [_order_to_dict(item) for item in _extract_items(payload)]++ open_orders = [row for row in rows if str(row.get("status") or "").upper() in _OPEN_ORDER_STATUSES]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)],+ "open_orders": open_orders,}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)]+ result["executions"] = [row for row in rows if row not in open_orders]return result@@ -260,11 +271,15 @@ def get_quote(symbol: str, *, config: TossConfig | None = None, **_: Any) -> dicreturn {"status": "error", "error": str(exc), "symbol": clean}row = _first_item(payload)+ last = _first(row, ("lastPrice", "price"))+ if last is None:+ # An empty/unpriced result is a data problem, not a valid quote.+ return {"status": "error", "error": f"Toss returned no price for {clean!r}", "symbol": clean}return {"status": "ok","symbol": clean,"quote": {- "last": _first(row, ("lastPrice", "price")),+ "last": last,"currency": _first(row, ("currency",)),"timestamp": _first(row, ("timestamp",)),},@@ -302,12 +317,14 @@ def get_historical_bars("/api/v1/candles",authed=True,account_scoped=False,- params={"symbol": clean, "interval": interval, "limit": capped_limit},+ params={"symbol": clean, "interval": interval, "count": 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)]+ # A bar with no close price is a data problem, not a zero-priced candle.+ bars = [bar for bar in bars if bar.get("close") is not None]return {"status": "ok", "symbol": clean, "period": period, "bars": bars}@@ -401,23 +418,29 @@ def _access_token(cfg: TossConfig) -> str:if response.status_code >= 400:raise TossAPIError(f"Toss token issuance returned HTTP {response.status_code}: {_error_message(response)}")- body = response.json()+ try:+ body = response.json()+ except ValueError as exc:+ raise TossAPIError("Toss token issuance returned invalid JSON.") from exctoken = str(body.get("access_token") or "")if not token:- raise TossAPIError(f"Toss token issuance returned no access_token: {body}")+ # Never echo the response body here: it is the token endpoint, and a+ # future field could be another secret rather than diagnostic text.+ raise TossAPIError("Toss token issuance returned no access_token.")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",- )+ payload = json.dumps({+ "client_id": cfg.client_id,+ "access_token": token,+ "expires_at": now + max(expires_in - _TOKEN_REFRESH_MARGIN_SECONDS, 0),+ })+ # Create with owner-only permissions from the start -- chmod-ing after+ # write leaves a brief window where the token is world-readable.+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)try:- path.chmod(0o600)+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:+ handle.write(payload)except OSError:passreturn token@@ -515,7 +538,15 @@ def _as_iter(value: Any) -> list[Any]:return [value]+def _unwrap(payload: Any) -> Any:+ """Unwrap the Toss API's ``{"result": ...}`` envelope, present on every response."""+ if isinstance(payload, Mapping) and "result" in payload:+ return payload["result"]+ return payload++def _extract_items(payload: Any) -> list[Any]:+ payload = _unwrap(payload)if isinstance(payload, list):return payloadif isinstance(payload, Mapping):diff --git a/agent/tests/test_sdk_connectors_toss.py b/agent/tests/test_sdk_connectors_toss.pyindex fc532e243..efa3714a6 100644--- a/agent/tests/test_sdk_connectors_toss.py+++ b/agent/tests/test_sdk_connectors_toss.py@@ -9,6 +9,8 @@ redaction, and service dispatch degrading cleanly when nothing is configuredfrom __future__ import annotations+from typing import Any+import pytestfrom src.live.classification import ToolClass@@ -73,6 +75,155 @@ def test_toss_invalid_profile_rejected() -> None:toss.TossConfig.from_mapping({"profile": "go-live"})+# --------------------------------------------------------------------------- #+# Read paths (spec-shaped payloads: every Toss response is {"result": ...})+# --------------------------------------------------------------------------- #+++def test_toss_positions_reads_holdings_and_unwraps_result(monkeypatch) -> None:+ def fake_get(cfg, path, *, authed, account_scoped, params=None):+ assert path == "/api/v1/holdings"+ assert authed is True+ assert account_scoped is True+ return {+ "result": [+ {"symbol": "005930", "quantity": 10, "averagePrice": 70000, "currentPrice": 71500, "currency": "KRW"}+ ]+ }++ monkeypatch.setattr(toss, "_get", fake_get)+ cfg = toss.TossConfig(client_id="c", client_secret="s", account_seq="1")+ result = toss.get_positions(cfg)++ assert result["status"] == "ok"+ assert result["positions"] == [+ {+ "symbol": "005930",+ "name": None,+ "quantity": 10,+ "average_price": 70000,+ "current_price": 71500,+ "pnl": None,+ "currency": "KRW",+ "market": None,+ }+ ]+++def test_toss_open_orders_splits_on_status_from_a_single_endpoint(monkeypatch) -> None:+ def fake_get(cfg, path, *, authed, account_scoped, params=None):+ assert path == "/api/v1/orders"+ return {+ "result": [+ {"orderId": "1", "symbol": "005930", "status": "OPEN", "side": "buy", "quantity": 5},+ {"orderId": "2", "symbol": "005930", "status": "FILLED", "side": "sell", "quantity": 3},+ ]+ }++ monkeypatch.setattr(toss, "_get", fake_get)+ cfg = toss.TossConfig(client_id="c", client_secret="s", account_seq="1")+ result = toss.get_open_orders(cfg, include_executions=True)++ assert [row["order_id"] for row in result["open_orders"]] == ["1"]+ assert [row["order_id"] for row in result["executions"]] == ["2"]+++def test_toss_get_quote_unwraps_result_list(monkeypatch) -> None:+ def fake_get(cfg, path, *, authed, account_scoped, params=None):+ assert path == "/api/v1/prices"+ assert params == {"symbols": "005930"}+ return {"result": [{"symbol": "005930", "lastPrice": "71500", "currency": "KRW", "timestamp": "t"}]}++ monkeypatch.setattr(toss, "_get", fake_get)+ result = toss.get_quote("005930", config=toss.TossConfig(client_id="c", client_secret="s", account_seq="1"))++ assert result["status"] == "ok"+ assert result["quote"]["last"] == "71500"+++def test_toss_get_quote_errors_on_an_unpriced_result_instead_of_returning_ok_with_nulls(monkeypatch) -> None:+ monkeypatch.setattr(toss, "_get", lambda *a, **k: {"result": [{"symbol": "005930"}]})+ result = toss.get_quote("005930", config=toss.TossConfig(client_id="c", client_secret="s", account_seq="1"))+ assert result["status"] == "error"+++def test_toss_get_historical_bars_uses_count_not_limit_and_unwraps_nested_result(monkeypatch) -> None:+ def fake_get(cfg, path, *, authed, account_scoped, params=None):+ assert path == "/api/v1/candles"+ assert params["count"] == 5+ assert "limit" not in params+ return {+ "result": {+ "candles": [+ {"timestamp": "t1", "openPrice": "1", "highPrice": "2", "lowPrice": "1", "closePrice": "1.5"},+ ],+ "nextBefore": None,+ }+ }++ monkeypatch.setattr(toss, "_get", fake_get)+ cfg = toss.TossConfig(client_id="c", client_secret="s", account_seq="1")+ result = toss.get_historical_bars("005930", config=cfg, limit=5)++ assert result["status"] == "ok"+ assert result["bars"] == [{"time": "t1", "open": "1", "high": "2", "low": "1", "close": "1.5", "volume": None}]+++def test_toss_get_historical_bars_drops_bars_with_no_close_price(monkeypatch) -> None:+ monkeypatch.setattr(+ toss,+ "_get",+ lambda *a, **k: {"result": {"candles": [{"timestamp": "t1"}], "nextBefore": None}},+ )+ cfg = toss.TossConfig(client_id="c", client_secret="s", account_seq="1")+ result = toss.get_historical_bars("005930", config=cfg)+ assert result["bars"] == []+++# --------------------------------------------------------------------------- #+# Auth header shape / error surfacing (requests-level, no mocked _get)+# --------------------------------------------------------------------------- #+++class _FakeResponse:+ def __init__(self, status_code: int, json_body: Any, content: bytes = b"{}"):+ self.status_code = status_code+ self._json = json_body+ self.content = content+ self.text = "" if not content else str(content)+ self.reason = "OK" if status_code < 400 else "Unauthorized"++ def json(self):+ return self._json+++def test_toss_request_sends_bearer_and_account_headers(monkeypatch) -> None:+ seen = {}++ def fake_get(url, *, headers, params, timeout):+ seen.update({"url": url, "headers": headers})+ return _FakeResponse(200, {"result": []})++ monkeypatch.setattr(toss.requests, "get", fake_get)+ monkeypatch.setattr(toss, "_access_token", lambda cfg: "tok")++ cfg = toss.TossConfig(client_id="c", client_secret="s", account_seq="acct-1")+ toss._get(cfg, "/api/v1/holdings", authed=True, account_scoped=True)++ assert seen["url"] == "https://openapi.tossinvest.com/api/v1/holdings"+ assert seen["headers"]["Authorization"] == "Bearer tok"+ assert seen["headers"]["X-Tossinvest-Account"] == "acct-1"+++def test_toss_check_connection_surfaces_a_clean_error_on_a_bad_key(monkeypatch) -> None:+ monkeypatch.setattr(toss.requests, "get", lambda *a, **k: _FakeResponse(401, {"message": "invalid token"}))+ monkeypatch.setattr(toss, "_access_token", lambda cfg: "bad-tok")++ result = toss.check_status(toss.TossConfig(client_id="c", client_secret="s", account_seq="1"))+ assert result["status"] == "error"+ assert "authentication failed" in result["error"]++# --------------------------------------------------------------------------- ## Redaction / service dispatch / classification# --------------------------------------------------------------------------- #