"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(trading): a simulated paper cancel only acknowledges orders the simulator issued
Haozhe Wuec31c826c694
diff --git a/agent/src/trading/connectors/dhan/sdk.py b/agent/src/trading/connectors/dhan/sdk.pyindex 83ed14eea..a2159b6b6 100644--- a/agent/src/trading/connectors/dhan/sdk.py+++ b/agent/src/trading/connectors/dhan/sdk.py@@ -32,6 +32,10 @@ DHAN_API_URL = "https://api.dhan.co"#: no runtime paper/live discriminator (same token reads the same account), so —#: following the Longbridge precedent — the connector is structurally capped at#: paper and never opens a live order path.+#: Prefix of every order id the local paper simulator issues. ``cancel_order``+#: refuses any other id, because only these orders exist in the simulation.+_PAPER_ORDER_PREFIX = "PAPER-"+_PAPER_ONLY_ERROR = ("Dhan connector is paper-only: it exposes no runtime paper/live ""discriminator, so live order placement is not supported. Use a "@@ -492,7 +496,7 @@ def place_order(# Paper-only: simulate locally (Dhan has no sandbox).return {"status": "ok",- "order_id": f"PAPER-{sec_id}-{side_token}-{qty}",+ "order_id": f"{_PAPER_ORDER_PREFIX}{sec_id}-{side_token}-{qty}","symbol": clean_symbol,"security_id": sec_id,"side": side_token.lower(),@@ -528,6 +532,17 @@ def cancel_order(clean_id = str(order_id or "").strip()if not clean_id:return {"status": "error", "error": "order_id is required"}+ if not clean_id.startswith(_PAPER_ORDER_PREFIX):+ # The paper profile reads the real account, so a live order's id can+ # arrive here; acknowledging it would report a cancel that never+ # happened while the real order keeps working.+ return {+ "status": "error",+ "error": (+ f"order {clean_id!r} was not issued by this paper simulator, so it "+ "cannot be cancelled here; cancel a real order with the broker"+ ),+ }return {"status": "ok",diff --git a/agent/src/trading/connectors/shoonya/sdk.py b/agent/src/trading/connectors/shoonya/sdk.pyindex 44c76472b..d96e84721 100644--- a/agent/src/trading/connectors/shoonya/sdk.py+++ b/agent/src/trading/connectors/shoonya/sdk.py@@ -40,6 +40,10 @@ SHOONYA_API_URL = "https://api.shoonya.com/NorenWClientTP"#: exposes no runtime paper/live discriminator (TOTP login reaches the same real#: account), so — following the Longbridge precedent — the connector is#: structurally capped at paper and never opens a live order path.+#: Prefix of every order id the local paper simulator issues. ``cancel_order``+#: refuses any other id, because only these orders exist in the simulation.+_PAPER_ORDER_PREFIX = "PAPER-"+_PAPER_ONLY_ERROR = ("Shoonya connector is paper-only: it exposes no runtime paper/live ""discriminator, so live order placement is not supported. Use a "@@ -475,7 +479,7 @@ def place_order(# Paper-only: simulate locally (Shoonya has no sandbox).return {"status": "ok",- "order_id": f"PAPER-{clean_symbol}-{buy_or_sell}-{qty}",+ "order_id": f"{_PAPER_ORDER_PREFIX}{clean_symbol}-{buy_or_sell}-{qty}","symbol": clean_symbol,"side": side_token.lower(),"profile": cfg.profile,@@ -506,6 +510,17 @@ def cancel_order(clean_id = str(order_id or "").strip()if not clean_id:return {"status": "error", "error": "order_id is required"}+ if not clean_id.startswith(_PAPER_ORDER_PREFIX):+ # The paper profile reads the real account, so a live order's id can+ # arrive here; acknowledging it would report a cancel that never+ # happened while the real order keeps working.+ return {+ "status": "error",+ "error": (+ f"order {clean_id!r} was not issued by this paper simulator, so it "+ "cannot be cancelled here; cancel a real order with the broker"+ ),+ }return {"status": "ok",diff --git a/agent/src/trading/connectors/zerodha/sdk.py b/agent/src/trading/connectors/zerodha/sdk.pyindex 9edf92ac5..ae9948ae5 100644--- a/agent/src/trading/connectors/zerodha/sdk.py+++ b/agent/src/trading/connectors/zerodha/sdk.py@@ -48,6 +48,10 @@ KITE_HIST_BASE = "https://api.kite.trade"#: India Standard Time (Kite timestamps are IST)._IST = timezone(timedelta(hours=5, minutes=30))+#: Prefix of every order id the local paper simulator issues. ``cancel_order``+#: refuses any other id, because only these orders exist in the simulation.+_PAPER_ORDER_PREFIX = "PAPER-"+_PAPER_ONLY_ERROR = ("Zerodha connector is paper-only: Kite exposes no runtime paper/live ""discriminator (a live token reaches the real account), so live order "@@ -593,7 +597,7 @@ def place_order(return {"status": "ok",- "order_id": f"PAPER-{clean_symbol}-{buy_or_sell}-{qty}",+ "order_id": f"{_PAPER_ORDER_PREFIX}{clean_symbol}-{buy_or_sell}-{qty}","symbol": clean_symbol,"side": side_token.lower(),"profile": cfg.profile,@@ -627,6 +631,17 @@ def cancel_order(clean_id = str(order_id or "").strip()if not clean_id:return {"status": "error", "error": "order_id is required"}+ if not clean_id.startswith(_PAPER_ORDER_PREFIX):+ # The paper profile reads the real account, so a live order's id can+ # arrive here; acknowledging it would report a cancel that never+ # happened while the real order keeps working.+ return {+ "status": "error",+ "error": (+ f"order {clean_id!r} was not issued by this paper simulator, so it "+ "cannot be cancelled here; cancel a real order with the broker"+ ),+ }return {"status": "ok",diff --git a/agent/tests/test_paper_sim_cancel_ids.py b/agent/tests/test_paper_sim_cancel_ids.pynew file mode 100644index 000000000..b96747999--- /dev/null+++ b/agent/tests/test_paper_sim_cancel_ids.py@@ -0,0 +1,47 @@+"""A locally simulated paper cancel may only acknowledge orders the simulator issued.++Zerodha, Dhan and Shoonya expose no sandbox, so their paper profiles simulate+orders locally — but their reads (``get_open_orders``, ``get_positions``) hit+the real account. A real open order's id can therefore reach the paper+``cancel_order``, which used to answer ``cancelled: True`` for any id while+never calling the broker: the agent was told a live order was gone while it+kept working. Both directions are pinned per connector, and the accepted id is+taken from ``place_order`` so the issuing and the checking side cannot drift+apart.+"""++from __future__ import annotations++import pytest++from src.trading.connectors.dhan import sdk as dhan_sdk+from src.trading.connectors.shoonya import sdk as shoonya_sdk+from src.trading.connectors.zerodha import sdk as zerodha_sdk++_CONNECTORS = [+ pytest.param(zerodha_sdk, zerodha_sdk.ZerodhaConfig, id="zerodha"),+ pytest.param(dhan_sdk, dhan_sdk.DhanConfig, id="dhan"),+ pytest.param(shoonya_sdk, shoonya_sdk.ShoonyaConfig, id="shoonya"),+]++[email protected]("mod, Config", _CONNECTORS)+def test_the_id_place_order_issued_can_be_cancelled(mod, Config) -> None:+ placed = mod.place_order(Config(profile="paper"), symbol="RELIANCE", side="buy", quantity=1)+ assert placed["status"] == "ok"++ cancelled = mod.cancel_order(Config(profile="paper"), placed["order_id"])++ assert cancelled["status"] == "ok"+ assert cancelled["cancelled"] is True+ assert cancelled["order_id"] == placed["order_id"]++[email protected]("mod, Config", _CONNECTORS)[email protected]("foreign_id", ["250911000123456", "ORD1", "paper-RELIANCE-B-1", " 1234 "])+def test_an_id_the_simulator_never_issued_is_refused(mod, Config, foreign_id) -> None:+ result = mod.cancel_order(Config(profile="paper"), foreign_id)++ assert result["status"] == "error"+ assert "cancelled" not in result+ assert "not issued by this paper simulator" in result["error"]diff --git a/agent/tests/test_sdk_connectors.py b/agent/tests/test_sdk_connectors.pyindex 8fc398695..15fdb9351 100644--- a/agent/tests/test_sdk_connectors.py+++ b/agent/tests/test_sdk_connectors.py@@ -874,12 +874,24 @@ def test_in_broker_paper_place_order_simulated_locally(mod, Config) -> None:@pytest.mark.parametrize("mod, Config", [(dh, dh.DhanConfig), (sh, sh.ShoonyaConfig)])def test_in_broker_paper_cancel_order_simulated(mod, Config) -> None:- result = mod.cancel_order(Config(profile="paper"), "ORD1")+ placed = mod.place_order(Config(profile="paper"), symbol="RELIANCE", side="buy", quantity=10)+ result = mod.cancel_order(Config(profile="paper"), placed["order_id"])assert result["status"] == "ok"assert result["cancelled"] is Trueassert result["is_paper"] is True[email protected]("mod, Config", [(dh, dh.DhanConfig), (sh, sh.ShoonyaConfig)])+def test_in_broker_paper_cancel_refuses_an_order_it_never_issued(mod, Config) -> None:+ """The paper profile reads the real account, so a live order id can reach+ the simulated cancel; acknowledging it would report a cancel that never+ happened while the real order keeps working."""+ result = mod.cancel_order(Config(profile="paper"), "ORD1")+ assert result["status"] == "error"+ assert "cancelled" not in result+ assert "not issued by this paper simulator" in result["error"]++def test_in_broker_order_ops_classified_write() -> None:for name in ("place_order", "modify_order", "cancel_order"):assert DHAN_TOOL_CLASS[name] is ToolClass.WRITE