"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(upbit): a paper fill always needs a real price, and other review follow-ups
heonjinjeong5dd9b626643c
diff --git a/agent/src/trading/connectors/upbit/sdk.py b/agent/src/trading/connectors/upbit/sdk.pyindex 619cbdf05..efa1eebc2 100644--- a/agent/src/trading/connectors/upbit/sdk.py+++ b/agent/src/trading/connectors/upbit/sdk.py@@ -205,7 +205,7 @@ def check_status(config: UpbitConfig | None = None) -> dict[str, Any]:if not report["sdk"]["installed"]:report["status"] = "error"- report["error"] = "Optional dependency missing: install with `pip install PyJWT`."+ report["error"] = "Optional dependency missing: install with `pip install \"vibe-trading-ai[upbit]\"`."return reporttry:@@ -258,7 +258,11 @@ def get_positions(config: UpbitConfig | None = None) -> dict[str, Any]:"quantity": quantity,"available": _as_float(item.get("balance")),"locked": _as_float(item.get("locked")),+ # avg_buy_price is a price per unit of `currency`, denominated in+ # `unit_currency` (e.g. a KRW price for a BTC position) -- not in+ # `currency` itself, which is what `average_cost` alone would imply."average_cost": _as_float(item.get("avg_buy_price")),+ "average_cost_currency": unit_currency,"unit_currency": unit_currency,})@@ -381,6 +385,12 @@ def place_order(``environment`` is not ``paper``. There is therefore no live order pathhere, by design.+ Every order looks up the current live price and refuses if none is+ available. A market order fills at that price. A limit order fills only+ if it is immediately marketable against it -- a buy at ``min(limit,+ last)``, a sell at ``max(limit, last)`` -- and is refused otherwise, since+ this simulator has no order book to rest a non-marketable order on.+Args:symbol: Market code, e.g. ``KRW-BTC``.side: ``buy`` or ``sell``.@@ -420,26 +430,47 @@ def place_order(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).- # A quantity-sized order needs no price at all, so it never makes the- # network call -- only notional sizing (converting a KRW spend into a- # quantity) does, and only when no limit_price was given to use instead.- fill_price = float(limit_price) if limit_price is not None else None-- if has_notional:- 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 not fill_price:- # An unpriced fill here would silently fabricate a null quantity.- 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+ # Paper-only: simulate locally against a live quote (Upbit has no+ # sandbox). Every order looks up the current price and refuses when none+ # is available -- a simulated fill with no price is not a fill; any+ # position or P&L built on it would be invented.+ quote = get_quote(market, config=cfg)+ last = _as_float(quote.get("quote", {}).get("last")) if quote.get("status") == "ok" else None+ if not last:+ return {+ "status": "error",+ "error": f"could not resolve a live quote for {market!r}; Upbit may not recognize this market",+ "symbol": market,+ }++ if type_token == "limit":+ limit = float(limit_price) # type: ignore[arg-type]+ if side_token == "buy":+ if limit < last:+ return {+ "status": "error",+ "error": (+ f"limit price {limit} would not fill against the current price {last}; "+ "this simulator only fills orders that are immediately marketable"+ ),+ "symbol": market,+ }+ fill_price = min(limit, last)+ else:+ if limit > last:+ return {+ "status": "error",+ "error": (+ f"limit price {limit} would not fill against the current price {last}; "+ "this simulator only fills orders that are immediately marketable"+ ),+ "symbol": market,+ }+ fill_price = max(limit, last)else:- filled_qty = float(quantity)+ fill_price = last++ filled_qty = float(notional) / fill_price if has_notional else float(quantity) # type: ignore[arg-type]return {"status": "ok",@@ -451,7 +482,7 @@ def place_order("paper_guard": "simulated_locally","order_type": type_token,"quantity": filled_qty,- "limit_price": fill_price if type_token == "limit" else None,+ "limit_price": float(limit_price) if type_token == "limit" else None, # type: ignore[arg-type]"fill_price": fill_price,"order_status": "simulated_fill",}@@ -509,7 +540,7 @@ def _require_jwt() -> ModuleType:import jwt # type: ignoreexcept ModuleNotFoundError as exc:raise UpbitDependencyError(- "PyJWT is not installed; run `pip install PyJWT`."+ "PyJWT is not installed; run `pip install \"vibe-trading-ai[upbit]\"`.") from excreturn jwtdiff --git a/agent/src/trading/onboarding.py b/agent/src/trading/onboarding.pyindex 01031cddf..007c71349 100644--- a/agent/src/trading/onboarding.py+++ b/agent/src/trading/onboarding.py@@ -168,7 +168,7 @@ _BUILTIN: dict[str, ConnectorOnboarding] = {_field("secret_key", "Secret Key"),),dependency="PyJWT",- install_command="pip install PyJWT keyring",+ install_command='pip install "vibe-trading-ai[upbit]" keyring',setup_hint="Create a read-only key; do not grant withdrawal permission.",),}diff --git a/agent/tests/test_paper_sim_cancel_ids.py b/agent/tests/test_paper_sim_cancel_ids.pyindex ee1136630..a8cab065d 100644--- a/agent/tests/test_paper_sim_cancel_ids.py+++ b/agent/tests/test_paper_sim_cancel_ids.py@@ -23,15 +23,22 @@ _CONNECTORS = [pytest.param(zerodha_sdk, zerodha_sdk.ZerodhaConfig, {"symbol": "RELIANCE"}, id="zerodha"),pytest.param(dhan_sdk, dhan_sdk.DhanConfig, {"symbol": "RELIANCE"}, id="dhan"),pytest.param(shoonya_sdk, shoonya_sdk.ShoonyaConfig, {"symbol": "RELIANCE"}, id="shoonya"),- # quantity-based sizing needs no live quote, so Upbit's place_order takes- # the same no-network path as the other three here; a notional-sized- # order would call get_quote and needs a mocked one instead.+ # Upbit's place_order always looks up a live quote (a fill needs a real+ # price), so its case here needs one mocked -- see the monkeypatch below.pytest.param(upbit_sdk, upbit_sdk.UpbitConfig, {"symbol": "KRW-BTC"}, id="upbit"),]+def _mock_upbit_quote_if_needed(monkeypatch, mod) -> None:+ if mod is upbit_sdk:+ monkeypatch.setattr(+ upbit_sdk, "get_quote", lambda *a, **k: {"status": "ok", "quote": {"last": 150_000_000}}+ )++@pytest.mark.parametrize("mod, Config, order_kwargs", _CONNECTORS)-def test_the_id_place_order_issued_can_be_cancelled(mod, Config, order_kwargs) -> None:+def test_the_id_place_order_issued_can_be_cancelled(monkeypatch, mod, Config, order_kwargs) -> None:+ _mock_upbit_quote_if_needed(monkeypatch, mod)placed = mod.place_order(Config(profile="paper"), side="buy", quantity=1, **order_kwargs)assert placed["status"] == "ok"diff --git a/agent/tests/test_sdk_connectors_upbit.py b/agent/tests/test_sdk_connectors_upbit.pyindex d4fe166bb..95a1cedba 100644--- a/agent/tests/test_sdk_connectors_upbit.py+++ b/agent/tests/test_sdk_connectors_upbit.py@@ -52,9 +52,14 @@ def test_upbit_exposes_no_live_trade_profile() -> None:# --------------------------------------------------------------------------- #-def test_upbit_paper_place_order_simulated_locally() -> None:+def _mock_quote(monkeypatch, last: float) -> None:+ monkeypatch.setattr(up, "get_quote", lambda *a, **k: {"status": "ok", "quote": {"last": last}})+++def test_upbit_paper_market_order_fills_at_the_live_quote(monkeypatch) -> None:+ _mock_quote(monkeypatch, 50_000_000)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)+ result = up.place_order(cfg, symbol="KRW-BTC", side="buy", quantity=0.01)assert result["status"] == "ok"assert result["is_paper"] is Trueassert result["order_status"] == "simulated_fill"@@ -62,7 +67,45 @@ def test_upbit_paper_place_order_simulated_locally() -> None:assert result["fill_price"] == 50_000_000-def test_upbit_paper_cancel_order_simulated() -> None:+def test_upbit_market_order_refused_when_upbit_does_not_recognize_the_ticker(monkeypatch) -> None:+ monkeypatch.setattr(up, "get_quote", lambda *a, **k: {"status": "error", "error": "not found"})+ cfg = up.UpbitConfig(access_key="ak", secret_key="sk", profile="paper")+ result = up.place_order(cfg, symbol="KRW-NOSUCHCOIN", side="buy", quantity=1)+ assert result["status"] == "error"+++def test_upbit_marketable_buy_limit_fills_at_the_better_of_limit_and_last(monkeypatch) -> None:+ _mock_quote(monkeypatch, 100)+ cfg = up.UpbitConfig(access_key="ak", secret_key="sk", profile="paper")+ result = up.place_order(cfg, symbol="KRW-BTC", side="buy", quantity=1, order_type="limit", limit_price=120)+ assert result["status"] == "ok"+ assert result["fill_price"] == 100 # min(limit, last)+++def test_upbit_non_marketable_buy_limit_is_refused(monkeypatch) -> None:+ _mock_quote(monkeypatch, 100)+ cfg = up.UpbitConfig(access_key="ak", secret_key="sk", profile="paper")+ result = up.place_order(cfg, symbol="KRW-BTC", side="buy", quantity=1, order_type="limit", limit_price=80)+ assert result["status"] == "error"+++def test_upbit_marketable_sell_limit_fills_at_the_better_of_limit_and_last(monkeypatch) -> None:+ _mock_quote(monkeypatch, 100)+ cfg = up.UpbitConfig(access_key="ak", secret_key="sk", profile="paper")+ result = up.place_order(cfg, symbol="KRW-BTC", side="sell", quantity=1, order_type="limit", limit_price=80)+ assert result["status"] == "ok"+ assert result["fill_price"] == 100 # max(limit, last)+++def test_upbit_non_marketable_sell_limit_is_refused(monkeypatch) -> None:+ _mock_quote(monkeypatch, 100)+ cfg = up.UpbitConfig(access_key="ak", secret_key="sk", profile="paper")+ result = up.place_order(cfg, symbol="KRW-BTC", side="sell", quantity=1, order_type="limit", limit_price=120)+ assert result["status"] == "error"+++def test_upbit_paper_cancel_order_simulated(monkeypatch) -> None:+ _mock_quote(monkeypatch, 150_000_000)cfg = up.UpbitConfig(access_key="ak", secret_key="sk", profile="paper")placed = up.place_order(cfg, symbol="KRW-BTC", side="buy", quantity=1)result = up.cancel_order(cfg, placed["order_id"])diff --git a/pyproject.toml b/pyproject.tomlindex e04df17bc..37d6d5edd 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -129,6 +129,12 @@ zerodha = [# stays False (loader falls through to Shoonya/Dhan) until installed."kiteconnect>=4.0.0",]+upbit = [+ # Upbit (Korea, KRW crypto) broker connector JWT signing. Lazy-imported+ # with a named error naming this extra; upbit_jwt_available() stays False+ # until installed.+ "PyJWT>=2.8.0",+]deepseek = ["langchain-deepseek>=1.0.0,<2",]