"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(etoro): reject copy trading on demo with a clear error
Ofek Shaked218653f00f2e
diff --git a/agent/src/tools/trading_connector_tool.py b/agent/src/tools/trading_connector_tool.pyindex d72d8f16a..b3fda5bb4 100644--- a/agent/src/tools/trading_connector_tool.py+++ b/agent/src/tools/trading_connector_tool.py@@ -740,7 +740,10 @@ class EtoroEditPositionStopsTool(BaseTool):class EtoroCopyPrecheckTool(BaseTool):name = "etoro_copy_precheck"- description = "Dry-run whether the account can copy an investor with an account-currency amount."+ description = (+ "Dry-run whether the account can copy an investor with an account-currency amount. "+ "Live accounts only — not supported on demo (paper) profiles."+ )parameters = {"type": "object","properties": {@@ -777,7 +780,10 @@ class EtoroCopyPrecheckTool(BaseTool):class EtoroCopyStartTool(BaseTool):name = "etoro_copy_start"- description = "Start copying an investor or adjust an existing copy allocation."+ description = (+ "Start copying an investor or adjust an existing copy allocation. "+ "Live accounts only — not supported on demo (paper) profiles."+ )parameters = {"type": "object","properties": {@@ -822,7 +828,10 @@ class EtoroCopyStartTool(BaseTool):class EtoroCopyPollTool(BaseTool):name = "etoro_copy_poll"- description = "Poll the outcome of an asynchronous eToro copy operation."+ description = (+ "Poll the outcome of an asynchronous eToro copy operation. "+ "Live accounts only — not supported on demo (paper) profiles."+ )parameters = {"type": "object","properties": {@@ -855,7 +864,10 @@ class EtoroCopyPollTool(BaseTool):class EtoroCopyCloseTool(BaseTool):name = "etoro_copy_close"- description = "Close or detach an eToro copy relationship by mirror id."+ description = (+ "Close or detach an eToro copy relationship by mirror id. "+ "Live accounts only — not supported on demo (paper) profiles."+ )parameters = {"type": "object","properties": {diff --git a/agent/src/trading/connectors/etoro/copy_trading.py b/agent/src/trading/connectors/etoro/copy_trading.pyindex ea23b6676..198c69726 100644--- a/agent/src/trading/connectors/etoro/copy_trading.py+++ b/agent/src/trading/connectors/etoro/copy_trading.py@@ -13,6 +13,11 @@ from src.trading.connectors.etoro.client import EtoroAPIError, EtoroConfig, copy_REFERENCE_ID_RE = re.compile(r"^[A-Za-z0-9._~-]{1,35}$")+COPY_TRADING_PAPER_UNSUPPORTED = (+ "eToro Public API copy trading is not available on demo (paper) accounts. "+ "Use a live profile (e.g. etoro-live-trade) with a real account."+)+def _base(cfg: EtoroConfig) -> dict[str, Any]:return {@@ -26,6 +31,16 @@ def _error(cfg: EtoroConfig, message: str, **extra: Any) -> dict[str, Any]:return {"status": "error", "error": message, **_base(cfg), **extra}+def _reject_copy_on_paper(cfg: EtoroConfig) -> dict[str, Any] | None:+ if cfg.is_paper:+ return _error(+ cfg,+ COPY_TRADING_PAPER_UNSUPPORTED,+ error_code="copy_unavailable_on_paper",+ )+ return None++def copy_precheck(config: EtoroConfig | None = None,*,@@ -36,6 +51,9 @@ def copy_precheck(from src.trading.connectors.etoro.client import load_configcfg = config or load_config()+ blocked = _reject_copy_on_paper(cfg)+ if blocked is not None:+ return blockedtry:clean_amount = float(amount)except (TypeError, ValueError, OverflowError):@@ -65,6 +83,9 @@ def copy_start_or_adjust(from src.trading.connectors.etoro.client import load_configcfg = config or load_config()+ blocked = _reject_copy_on_paper(cfg)+ if blocked is not None:+ return blockedtry:clean_amount = float(amount)except (TypeError, ValueError, OverflowError):@@ -111,6 +132,9 @@ def copy_poll(from src.trading.connectors.etoro.client import load_configcfg = config or load_config()+ blocked = _reject_copy_on_paper(cfg)+ if blocked is not None:+ return blockedref = str(reference_id or "").strip()if not ref:return _error(cfg, "reference_id is required")@@ -135,6 +159,9 @@ def copy_close(from src.trading.connectors.etoro.client import load_configcfg = config or load_config()+ blocked = _reject_copy_on_paper(cfg)+ if blocked is not None:+ return blockedaction = str(unregister_type or "Close").strip()if action not in ("Close", "Detach"):return _error(cfg, "unregister_type must be 'Close' or 'Detach'")@@ -168,6 +195,9 @@ def copy_poll_until_complete(from src.trading.connectors.etoro.client import load_configcfg = config or load_config()+ blocked = _reject_copy_on_paper(cfg)+ if blocked is not None:+ return blockeddeadline = time.monotonic() + max(1.0, float(timeout_s))last: dict[str, Any] = {}while time.monotonic() < deadline:diff --git a/agent/src/trading/connectors/etoro/profiles.py b/agent/src/trading/connectors/etoro/profiles.pyindex db447a01b..bd4cb712a 100644--- a/agent/src/trading/connectors/etoro/profiles.py+++ b/agent/src/trading/connectors/etoro/profiles.py@@ -9,12 +9,15 @@ from __future__ import annotationsfrom src.trading.types import READ_CAPABILITIES, TradingProfile-ETORO_EXTENDED_CAPABILITIES = READ_CAPABILITIES + (+ETORO_PAPER_TRADE_CAPABILITIES = READ_CAPABILITIES + ("orders.place","orders.cancel","positions.close","orders.cancel_close","positions.edit",+)++ETORO_EXTENDED_CAPABILITIES = ETORO_PAPER_TRADE_CAPABILITIES + ("copy.precheck","copy.start","copy.poll",@@ -50,10 +53,13 @@ ETORO_PROFILES: tuple[TradingProfile, ...] = (label="eToro Demo · Public API Trade",environment="paper",transport="broker_sdk",- capabilities=ETORO_EXTENDED_CAPABILITIES,+ capabilities=ETORO_PAPER_TRADE_CAPABILITIES,readonly=False,config={"profile": "paper"},- notes="Full demo trading and copy workflows via eToro Public API demo paths.",+ notes=(+ "Demo trading via eToro Public API demo paths. "+ "Copy trading is not available on demo accounts — use etoro-live-trade."+ ),),TradingProfile(id="etoro-live-trade",diff --git a/agent/src/trading/service.py b/agent/src/trading/service.pyindex a9d88d391..73966d683 100644--- a/agent/src/trading/service.py+++ b/agent/src/trading/service.py@@ -422,6 +422,21 @@ def _etoro_error(message: str) -> dict[str, Any]:return {"status": "error", "error": message}+def _etoro_copy_unavailable_on_paper(profile: TradingProfile) -> dict[str, Any] | None:+ if profile.environment != "paper":+ return None+ from src.trading.connectors.etoro.copy_trading import COPY_TRADING_PAPER_UNSUPPORTED++ return _with_profile(+ profile,+ {+ "status": "error",+ "error": COPY_TRADING_PAPER_UNSUPPORTED,+ "error_code": "copy_unavailable_on_paper",+ },+ )++def _close_etoro_position(module: Any,config: Any,@@ -655,6 +670,9 @@ def etoro_copy_precheck(profile = profile_by_id(profile_id)if profile.connector != "etoro":return _unsupported_etoro(profile, "copy.precheck")+ blocked = _etoro_copy_unavailable_on_paper(profile)+ if blocked is not None:+ return blockedmodule = _sdk_module(profile.connector)config = module.build_config(profile.config, overrides)return _with_profile(@@ -681,6 +699,9 @@ def etoro_copy_start(profile = profile_by_id(profile_id)if profile.connector != "etoro":return _unsupported_etoro(profile, "copy.start")+ blocked = _etoro_copy_unavailable_on_paper(profile)+ if blocked is not None:+ return blockedoverrides = dict(overrides)overrides.pop("session_id", None)module = _sdk_module(profile.connector)@@ -759,6 +780,9 @@ def etoro_copy_poll(profile = profile_by_id(profile_id)if profile.connector != "etoro":return _unsupported_etoro(profile, "copy.poll")+ blocked = _etoro_copy_unavailable_on_paper(profile)+ if blocked is not None:+ return blockedmodule = _sdk_module(profile.connector)config = module.build_config(profile.config, overrides)return _with_profile(profile, module.copy_poll(config, reference_id=reference_id, request_id=request_id))@@ -776,6 +800,9 @@ def etoro_copy_close(profile = profile_by_id(profile_id)if profile.connector != "etoro":return _unsupported_etoro(profile, "copy.close")+ blocked = _etoro_copy_unavailable_on_paper(profile)+ if blocked is not None:+ return blockedoverrides = dict(overrides)overrides.pop("session_id", None)module = _sdk_module(profile.connector)diff --git a/agent/tests/test_etoro_connector.py b/agent/tests/test_etoro_connector.pyindex 1d52a0d29..7111fe46e 100644--- a/agent/tests/test_etoro_connector.py+++ b/agent/tests/test_etoro_connector.py@@ -24,14 +24,18 @@ from src.trading.connectors.etoro.client import (set_client_factory,)from src.trading.connectors.etoro.classification import ETORO_TOOL_CLASS-from src.trading.connectors.etoro.profiles import ETORO_EXTENDED_CAPABILITIES+from src.trading.connectors.etoro.profiles import ETORO_EXTENDED_CAPABILITIES, ETORO_PAPER_TRADE_CAPABILITIESpytestmark = pytest.mark.unit@pytest.fixture(autouse=True)def _reset_etoro_client_factory() -> None:+ from src.trading.connectors.etoro.instruments import reset_instrument_type_cache++ reset_instrument_type_cache()yield+ reset_instrument_type_cache()set_client_factory(None)@@ -76,9 +80,14 @@ def test_etoro_profiles_registered() -> None:assert "orders.place.requires_mandate" in live.capabilities-def test_trade_profile_lists_all_extended_capabilities() -> None:- trade = profiles.profile_by_id("etoro-paper-trade")- assert set(ETORO_EXTENDED_CAPABILITIES) <= set(trade.capabilities)+def test_trade_profile_lists_capabilities_by_environment() -> None:+ paper = profiles.profile_by_id("etoro-paper-trade")+ live = profiles.profile_by_id("etoro-live-trade")+ assert set(ETORO_PAPER_TRADE_CAPABILITIES) <= set(paper.capabilities)+ assert "copy.start" not in paper.capabilities+ assert "orders.place" in paper.capabilities+ assert "copy.start" in live.capabilities+ assert "orders.place.requires_mandate" in live.capabilitiesdef test_demo_and_real_paths_separated() -> None:@@ -91,7 +100,8 @@ def test_demo_and_real_paths_separated() -> None:assert info_root(paper).endswith("/demo")assert aggregate_portfolio_path(paper).endswith("/demo/aggregate-portfolio")assert aggregate_portfolio_path(live) == "/api/v1/trading/info/aggregate-portfolio"- assert copy_root(paper).endswith("/demo")+ assert copy_root(paper) == "/api/v2/trading/copy"+ assert copy_root(live) == "/api/v2/trading/copy"assert positions_root(paper).endswith("/demo")assert paper.api_key == live.api_key@@ -245,6 +255,7 @@ def test_classification_registered() -> None:assert classify_tool("unknown_etoro_op", None, curated) is ToolClass.UNKNOWNassert ETORO_TOOL_CLASS["copy_close"] is ToolClass.WRITEassert ETORO_TOOL_CLASS["get_instrument_metadata"] is ToolClass.READ+ assert ETORO_TOOL_CLASS["get_instrument_types"] is ToolClass.READassert ETORO_TOOL_CLASS["list_instruments_by_type"] is ToolClass.READ@@ -304,6 +315,13 @@ def test_crypto_query_browses_instrument_type_catalog(monkeypatch) -> None:def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:captured.append((url, dict(kwargs.get("params") or {})))+ if "/instrument-types" in url:+ return _FakeResponse(+ 200,+ {"instrumentTypes": [{"instrumentTypeID": 10, "instrumentTypeDescription": "Crypto"}]},+ )+ if "/market-data/search" in url:+ return _FakeResponse(200, {"items": []})if "/market-data/instruments" in url and kwargs.get("params", {}).get("instrumentTypeIds") == 10:return _FakeResponse(200,@@ -335,16 +353,87 @@ def test_crypto_query_browses_instrument_type_catalog(monkeypatch) -> None:assert result["instrument_type_id"] == 10assert result["instruments"][0]["symbol"] == "BTC"assert all(row.get("instrument_type_id") == 10 for row in result["instruments"])- assert not any("/market-data/search" in url for url, _ in captured)assert any(params.get("instrumentTypeIds") == 10 for _, params in captured)+def test_stocks_query_uses_dynamic_type_catalog(monkeypatch) -> None:+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")++ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:+ if "/instrument-types" in url:+ return _FakeResponse(+ 200,+ {+ "instrumentTypes": [+ {"instrumentTypeID": 5, "instrumentTypeDescription": "Stocks"},+ {"instrumentTypeID": 10, "instrumentTypeDescription": "Crypto"},+ ],+ },+ )+ if "/market-data/search" in url:+ return _FakeResponse(200, {"items": []})+ if kwargs.get("params", {}).get("instrumentTypeIds") == 5:+ return _FakeResponse(+ 200,+ {+ "instrumentDisplayDatas": [+ {+ "instrumentID": 1111,+ "symbolFull": "AAPL",+ "instrumentTypeID": 5,+ },+ ],+ },+ )+ raise AssertionError(f"unexpected request {method} {url}")++ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))+ from src.trading.connectors.etoro.instruments import search_instruments++ result = search_instruments("equities", cfg, limit=5)+ assert result["status"] == "ok"+ assert result["instrument_type_id"] == 5+ assert result["instruments"][0]["symbol"] == "AAPL"+++def test_get_instrument_types_reads_catalog(monkeypatch) -> None:+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")++ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:+ if "/instrument-types" in url:+ return _FakeResponse(+ 200,+ {+ "instrumentTypes": [+ {"instrumentTypeID": 1, "instrumentTypeDescription": "Forex"},+ {"instrumentTypeID": 10, "instrumentTypeDescription": "Crypto"},+ ],+ },+ )+ raise AssertionError(f"unexpected request {method} {url}")++ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))+ from src.trading.connectors.etoro.instruments import get_instrument_types++ result = get_instrument_types(cfg)+ assert result["status"] == "ok"+ assert {row["instrument_type_id"] for row in result["instrument_types"]} == {1, 10}+ assert result["instrument_types"][0]["label"] == "forex"++def test_crypto_browse_can_attach_flat_market_data_rates(monkeypatch) -> None:cfg = EtoroConfig(profile="live-readonly", api_key="k", user_key="u")captured_urls: list[str] = []def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:captured_urls.append(url)+ if "/instrument-types" in url:+ return _FakeResponse(+ 200,+ {"instrumentTypes": [{"instrumentTypeID": 10, "instrumentTypeDescription": "Crypto"}]},+ )+ if "/market-data/search" in url:+ return _FakeResponse(200, {"items": []})if "/market-data/instruments" in url and "rates" not in url:return _FakeResponse(200,@@ -601,8 +690,18 @@ def test_edit_position_stops_supports_clear_contract(monkeypatch) -> None:}-def test_copy_precheck_posts_eligibility(monkeypatch) -> None:+def test_copy_rejected_on_paper_account() -> None:cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")+ from src.trading.connectors.etoro.copy_trading import COPY_TRADING_PAPER_UNSUPPORTED++ result = etoro_sdk.copy_precheck(cfg, parent_cid=123, amount=100.0)+ assert result["status"] == "error"+ assert result["error_code"] == "copy_unavailable_on_paper"+ assert COPY_TRADING_PAPER_UNSUPPORTED in result["error"]+++def test_copy_precheck_posts_eligibility(monkeypatch) -> None:+ cfg = EtoroConfig(profile="live", api_key="k", user_key="u")captured: dict[str, Any] = {}def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:@@ -620,7 +719,7 @@ def test_copy_precheck_posts_eligibility(monkeypatch) -> None:def test_copy_start_posts_copy_root(monkeypatch) -> None:- cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")+ cfg = EtoroConfig(profile="live", api_key="k", user_key="u")captured: dict[str, Any] = {}def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:@@ -645,7 +744,7 @@ def test_copy_start_posts_copy_root(monkeypatch) -> None:@pytest.mark.parametrize("reference_id", ["contains/slash", "x" * 36, ""])def test_copy_start_rejects_invalid_reference_id(reference_id: str) -> None:- cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")+ cfg = EtoroConfig(profile="live", api_key="k", user_key="u")result = etoro_sdk.copy_start_or_adjust(cfg,@@ -659,7 +758,7 @@ def test_copy_start_rejects_invalid_reference_id(reference_id: str) -> None:def test_copy_poll_gets_reference(monkeypatch) -> None:- cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")+ cfg = EtoroConfig(profile="live", api_key="k", user_key="u")captured_url = ""def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:@@ -674,7 +773,7 @@ def test_copy_poll_gets_reference(monkeypatch) -> None:def test_copy_close_posts_close(monkeypatch) -> None:- cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")+ cfg = EtoroConfig(profile="live", api_key="k", user_key="u")captured: dict[str, Any] = {}def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:@@ -735,7 +834,10 @@ def test_service_search_instruments(monkeypatch) -> None:cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:- if kwargs.get("params", {}).get("search"):+ params = kwargs.get("params") or {}+ if params.get("internalSymbolFull") == "BTC":+ return _FakeResponse(200, {"items": [{"instrumentId": 100000, "internalSymbolFull": "BTC"}]})+ if params.get("search"):return _FakeResponse(200, {"items": [{"instrumentId": 100000, "internalSymbolFull": "BTC"}]})return _FakeResponse(200, {"items": []})diff --git a/agent/tests/test_etoro_live_actions.py b/agent/tests/test_etoro_live_actions.pyindex 3e92852aa..5c6d3c09e 100644--- a/agent/tests/test_etoro_live_actions.py+++ b/agent/tests/test_etoro_live_actions.py@@ -301,7 +301,7 @@ def test_service_edit_position_stops_live_fails_closed(monkeypatch) -> None:assert module.calls == []-def test_service_etoro_copy_start_paper_bypasses_gate(monkeypatch) -> None:+def test_service_etoro_copy_start_paper_returns_unavailable(monkeypatch) -> None:module = _FakeEtoroModule()monkeypatch.setattr(service, "_sdk_module", lambda connector: module)result = service.etoro_copy_start(@@ -310,8 +310,9 @@ def test_service_etoro_copy_start_paper_bypasses_gate(monkeypatch) -> None:"etoro-paper-trade",reference_id="ref-1",)- assert result["status"] == "ok"- assert module.calls == ["copy_start"]+ assert result["status"] == "error"+ assert result["error_code"] == "copy_unavailable_on_paper"+ assert module.calls == []def test_service_etoro_copy_increase_non_usd_live_account_fails_closed(