Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(toss): match the real /orders and /holdings schemas from the spec

heonjinjeong039721044069
diff --git a/agent/src/trading/connectors/toss/sdk.py b/agent/src/trading/connectors/toss/sdk.py
index f6c6b84a6..29e81cdce 100644
--- a/agent/src/trading/connectors/toss/sdk.py
+++ b/agent/src/trading/connectors/toss/sdk.py
@@ -206,19 +206,28 @@ def check_status(config: TossConfig | None = None) -> dict[str, Any]:
#: 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."""
+ """Fetch holdings summary totals for the configured account.
+
+ Per-total values (``market_value``, ``profit_loss``) are passed through as
+ the API's own ``{"krw": ..., "usd": ...}``-wrapped objects rather than
+ flattened into one number, since flattening would mean guessing which
+ currency the caller wants.
+ """
cfg = config or load_config()
payload = _get(cfg, "/api/v1/holdings", authed=True, account_scoped=True)
- summary = _mapping_or_raw(_first(_unwrap(payload), ("summary", "accountSummary")))
+ result = _unwrap(payload)
+ result = result if isinstance(result, Mapping) else {}
return {
"status": "ok",
"profile": cfg.profile,
"paper_guard": PAPER_GUARD,
- "account": summary,
+ "account": {
+ "total_purchase_amount": result.get("totalPurchaseAmount"),
+ "market_value": result.get("marketValue"),
+ "profit_loss": result.get("profitLoss"),
+ "daily_profit_loss": result.get("dailyProfitLoss"),
+ },
}
@@ -239,25 +248,26 @@ def get_open_orders(
*,
include_executions: bool = False,
) -> dict[str, Any]:
- """Fetch Toss orders, split into still-open vs already-executed.
+ """Fetch open Toss orders, optionally with recently closed ones.
- 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.
+ ``status`` is a required query parameter on ``/api/v1/orders`` -- it is
+ not something to derive client-side from each row, so open and closed are
+ two separate calls, the same as the original design. ``CLOSED`` is
+ paginated by the API (``limit``/``cursor``); this fetches one page.
"""
cfg = config or load_config()
- 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]
+ open_payload = _get(cfg, "/api/v1/orders", authed=True, account_scoped=True, params={"status": "OPEN"})
result: dict[str, Any] = {
"status": "ok",
"profile": cfg.profile,
"paper_guard": PAPER_GUARD,
- "open_orders": open_orders,
+ "open_orders": [_order_to_dict(item) for item in _extract_items(open_payload)],
}
if include_executions:
- result["executions"] = [row for row in rows if row not in open_orders]
+ closed_payload = _get(
+ cfg, "/api/v1/orders", authed=True, account_scoped=True, params={"status": "CLOSED"}
+ )
+ result["executions"] = [_order_to_dict(item) for item in _extract_items(closed_payload)]
return result
@@ -323,8 +333,9 @@ def get_historical_bars(
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]
+ # A bar with no close price is a data problem, not a gap to drop silently.
+ if any(bar.get("close") is None for bar in bars):
+ return {"status": "error", "error": f"Toss returned a candle with no close price for {clean!r}", "symbol": clean}
return {"status": "ok", "symbol": clean, "period": period, "bars": bars}
@@ -562,14 +573,6 @@ def _first_item(payload: Any) -> Any:
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
@@ -586,16 +589,24 @@ def _first(obj: Any, names: tuple[str, ...], default: Any = None) -> Any:
return default
+def _nested(obj: Any, key: str, subkey: str, default: Any = None) -> Any:
+ """Read ``obj[key][subkey]``, e.g. an order's ``execution.filledQuantity``."""
+ value = _obj_get(obj, key)
+ if isinstance(value, Mapping):
+ return value.get(subkey, default)
+ 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")),
+ "average_price": _first(item, ("averagePurchasePrice", "averagePrice", "avgPrice")),
+ "current_price": _first(item, ("lastPrice", "currentPrice", "price")),
+ "pnl": _nested(item, "profitLoss", "amount"),
"currency": _first(item, ("currency",)),
- "market": _first(item, ("market", "exchange")),
+ "market": _first(item, ("marketCountry", "market", "exchange")),
}
@@ -607,10 +618,10 @@ def _order_to_dict(item: Any) -> dict[str, Any]:
"order_type": str(_first(item, ("orderType", "type"), "")),
"status": str(_first(item, ("status",), "")),
"quantity": _first(item, ("quantity", "qty")),
- "filled_quantity": _first(item, ("filledQuantity", "filledQty")),
+ "filled_quantity": _nested(item, "execution", "filledQuantity"),
"price": _first(item, ("price", "limitPrice")),
"currency": _first(item, ("currency",)),
- "created_at": _first(item, ("createdAt", "orderedAt")),
+ "created_at": _first(item, ("orderedAt", "createdAt")),
}
diff --git a/agent/tests/test_sdk_connectors_toss.py b/agent/tests/test_sdk_connectors_toss.py
index efa3714a6..90603d6b0 100644
--- a/agent/tests/test_sdk_connectors_toss.py
+++ b/agent/tests/test_sdk_connectors_toss.py
@@ -80,16 +80,44 @@ def test_toss_invalid_profile_rejected() -> None:
# --------------------------------------------------------------------------- #
-def test_toss_positions_reads_holdings_and_unwraps_result(monkeypatch) -> None:
+#: A single holdings item shaped exactly like GET /api/v1/holdings per the
+#: openapi.json v1.2.15 spec (confirmed by review on #1409).
+_HOLDINGS_PAYLOAD = {
+ "result": {
+ "totalPurchaseAmount": {"krw": 700000, "usd": None},
+ "marketValue": {"amount": {"krw": 715000, "usd": None}, "amountAfterCost": {"krw": 714000, "usd": None}},
+ "profitLoss": {
+ "amount": {"krw": 15000, "usd": None},
+ "amountAfterCost": {"krw": 14000, "usd": None},
+ "rate": 2.14,
+ "rateAfterCost": 2.0,
+ },
+ "dailyProfitLoss": {"krw": 1500, "usd": None},
+ "items": [
+ {
+ "symbol": "005930",
+ "name": "Samsung Electronics",
+ "marketCountry": "KR",
+ "currency": "KRW",
+ "quantity": 10,
+ "lastPrice": "71500",
+ "averagePurchasePrice": "70000",
+ "marketValue": {"purchaseAmount": "700000", "amount": "715000", "amountAfterCost": "714000"},
+ "profitLoss": {"amount": "15000", "amountAfterCost": "14000", "rate": "2.14", "rateAfterCost": "2.0"},
+ "dailyProfitLoss": "1500",
+ "cost": "1000",
+ }
+ ],
+ }
+}
+
+
+def test_toss_positions_reads_holdings_and_unwraps_nested_items(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"}
- ]
- }
+ return _HOLDINGS_PAYLOAD
monkeypatch.setattr(toss, "_get", fake_get)
cfg = toss.TossConfig(client_id="c", client_secret="s", account_seq="1")
@@ -99,33 +127,79 @@ def test_toss_positions_reads_holdings_and_unwraps_result(monkeypatch) -> None:
assert result["positions"] == [
{
"symbol": "005930",
- "name": None,
+ "name": "Samsung Electronics",
"quantity": 10,
- "average_price": 70000,
- "current_price": 71500,
- "pnl": None,
+ "average_price": "70000",
+ "current_price": "71500",
+ "pnl": "15000",
"currency": "KRW",
- "market": None,
+ "market": "KR",
}
]
-def test_toss_open_orders_splits_on_status_from_a_single_endpoint(monkeypatch) -> None:
+def test_toss_account_snapshot_reads_holdings_totals_without_flattening_currency(monkeypatch) -> None:
+ monkeypatch.setattr(toss, "_get", lambda *a, **k: _HOLDINGS_PAYLOAD)
+ cfg = toss.TossConfig(client_id="c", client_secret="s", account_seq="1")
+ result = toss.get_account_snapshot(cfg)
+
+ assert result["status"] == "ok"
+ assert result["account"]["total_purchase_amount"] == {"krw": 700000, "usd": None}
+ assert result["account"]["market_value"]["amount"] == {"krw": 715000, "usd": None}
+ assert result["account"]["profit_loss"]["rate"] == 2.14
+
+
+def test_toss_open_orders_calls_status_open_and_closed_separately(monkeypatch) -> None:
+ """status is a required query param on /api/v1/orders, not something to
+ derive by inspecting each row -- two calls, matching the spec."""
+ calls = []
+
def fake_get(cfg, path, *, authed, account_scoped, params=None):
+ calls.append(params)
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},
- ]
- }
+ if params == {"status": "OPEN"}:
+ return {
+ "result": {
+ "orders": [
+ {
+ "orderId": "1",
+ "symbol": "005930",
+ "side": "BUY",
+ "orderType": "LIMIT",
+ "status": "PARTIAL_FILLED",
+ "price": "70000",
+ "quantity": 5,
+ "currency": "KRW",
+ "orderedAt": "t1",
+ "execution": {"filledQuantity": 2, "averageFilledPrice": "70000"},
+ }
+ ],
+ "hasNext": False,
+ "nextCursor": None,
+ }
+ }
+ return {"result": {"orders": [], "hasNext": False, "nextCursor": None}}
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"]
+ assert calls == [{"status": "OPEN"}, {"status": "CLOSED"}]
+ assert result["open_orders"] == [
+ {
+ "order_id": "1",
+ "symbol": "005930",
+ "side": "BUY",
+ "order_type": "LIMIT",
+ "status": "PARTIAL_FILLED",
+ "quantity": 5,
+ "filled_quantity": 2,
+ "price": "70000",
+ "currency": "KRW",
+ "created_at": "t1",
+ }
+ ]
+ assert result["executions"] == []
def test_toss_get_quote_unwraps_result_list(monkeypatch) -> None:
@@ -169,7 +243,9 @@ def test_toss_get_historical_bars_uses_count_not_limit_and_unwraps_nested_result
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:
+def test_toss_get_historical_bars_errors_on_a_bar_with_no_close_price(monkeypatch) -> None:
+ """A missing close is a data problem -- silently dropping it would leave a
+ gap in the series with no signal that anything was wrong."""
monkeypatch.setattr(
toss,
"_get",
@@ -177,7 +253,7 @@ def test_toss_get_historical_bars_drops_bars_with_no_close_price(monkeypatch) ->
)
cfg = toss.TossConfig(client_id="c", client_secret="s", account_seq="1")
result = toss.get_historical_bars("005930", config=cfg)
- assert result["bars"] == []
+ assert result["status"] == "error"
# --------------------------------------------------------------------------- #