Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(etoro): align API paths, expand tests, and document MCP companion

Ofek Shaked589dcc647620
diff --git a/agent/SKILL.md b/agent/SKILL.md
index 10cd5464b..0e34e4eb5 100644
--- a/agent/SKILL.md
+++ b/agent/SKILL.md
@@ -254,6 +254,36 @@ can map safely; `mcp.write` requires an explicit tool allowlist and live
order-guard handling. If IBKR issues a pre-registered OAuth client, add
`clientId` and `clientSecret` inside `auth`.
+### Official eToro Public API MCP (discovery + dev)
+
+eToro ships a hosted MCP at `https://mcp.public-api.etoro.com` with live OpenAPI
+route discovery (`get-all-routes`, `get-route-spec`) and optional execution
+(`execute-read`, `execute-write`). Use it for **API exploration and codegen** —
+production agent trading in Vibe-Trading goes through the built-in `etoro-*`
+connector profiles and `trading_*` / `etoro_*` tools (mandate gate on live writes).
+
+Add to `~/.vibe-trading/agent.json` (credentials on the connection, not in chat):
+
+```json
+{
+ "mcpServers": {
+ "etoro-public-api": {
+ "type": "streamableHttp",
+ "url": "https://mcp.public-api.etoro.com",
+ "headers": {
+ "x-api-key": "YOUR_PUBLIC_API_KEY",
+ "x-user-key": "YOUR_USER_KEY"
+ },
+ "enabledTools": ["get-all-routes", "get-route-spec", "execute-read"]
+ }
+ }
+}
+```
+
+Omit `execute-write` unless you want the MCP to place trades directly (bypasses
+Vibe-Trading's live mandate gate). Install skill:
+`https://mcp.public-api.etoro.com/skill`
+
### Trading connector profiles
The public trading surface is connector-first. Choose a connector profile, then
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index fdd247f8f..38440e546 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -1152,6 +1152,8 @@ def trading_history(
bar_size: str = "1 day",
what_to_show: str = "TRADES",
use_rth: bool = True,
+ period: str = "1d",
+ limit: int = 90,
) -> str:
"""Read historical bars from the selected trading connector profile.
@@ -1169,6 +1171,8 @@ def trading_history(
bar_size: IBKR bar size, default 1 day.
what_to_show: Data type, default TRADES.
use_rth: Use regular trading hours.
+ period: Bar interval for SDK connectors (broker_sdk): 1m/5m/1h/1d/1w.
+ limit: Number of bars for SDK connectors.
"""
params = _trading_common_args(connection=connection, host=host, port=port, client_id=client_id, account=account)
params.update(
@@ -1181,6 +1185,8 @@ def trading_history(
"bar_size": bar_size,
"what_to_show": what_to_show,
"use_rth": use_rth,
+ "period": period,
+ "limit": limit,
}
)
registry = _get_registry()
diff --git a/agent/src/trading/connectors/etoro/__init__.py b/agent/src/trading/connectors/etoro/__init__.py
index cb026bd95..04d35df8a 100644
--- a/agent/src/trading/connectors/etoro/__init__.py
+++ b/agent/src/trading/connectors/etoro/__init__.py
@@ -1,6 +1,6 @@
"""eToro Public API connector (demo + real read/write).
-Demo and real accounts are separated structurally: API keys are bound to one
-environment and request paths include an explicit ``demo`` segment for paper
-trading. Live write profiles require mandate enforcement via the live action gate.
+Demo and real share one API key pair; profiles select ``/demo`` vs production
+API paths. Live write profiles require mandate enforcement via the live action
+gate.
"""
diff --git a/agent/src/trading/connectors/etoro/classification.py b/agent/src/trading/connectors/etoro/classification.py
index d7c3a716d..20b5de63f 100644
--- a/agent/src/trading/connectors/etoro/classification.py
+++ b/agent/src/trading/connectors/etoro/classification.py
@@ -11,6 +11,7 @@ from src.live.classification import ToolClass
ETORO_TOOL_CLASS: dict[str, ToolClass] = {
# READ
"check_status": ToolClass.READ,
+ "get_user_profile": ToolClass.READ,
"get_account_snapshot": ToolClass.READ,
"get_positions": ToolClass.READ,
"get_open_orders": ToolClass.READ,
diff --git a/agent/src/trading/connectors/etoro/client.py b/agent/src/trading/connectors/etoro/client.py
index 89293148d..bba48a51a 100644
--- a/agent/src/trading/connectors/etoro/client.py
+++ b/agent/src/trading/connectors/etoro/client.py
@@ -1,4 +1,10 @@
-"""HTTP transport and path builders for the eToro Public API."""
+"""HTTP transport and path builders for the eToro Public API.
+
+Paper-vs-live is structural: ``profile == "paper"`` routes to ``/demo`` API
+paths; live profiles use production paths on the same host. eToro uses one API
+key pair for both environments — the configured profile selects paths, not
+different credentials.
+"""
from __future__ import annotations
@@ -45,7 +51,15 @@ Transport = Callable[..., requests.Response]
@dataclass(frozen=True)
class EtoroConfig:
- """eToro connector connection settings."""
+ """eToro connector connection settings.
+
+ Args:
+ api_key: eToro Public API key (shared across demo and real paths).
+ user_key: eToro user key (shared across demo and real paths).
+ profile: ``paper``, ``live-readonly`` or ``live``.
+ timeout: Network timeout in seconds.
+ readonly: Always true for this layer unless trade profiles call writes.
+ """
api_key: str = ""
user_key: str = ""
@@ -55,6 +69,7 @@ class EtoroConfig:
@classmethod
def from_mapping(cls, data: Mapping[str, Any] | None = None) -> "EtoroConfig":
+ """Build a config from a JSON-like mapping, normalizing the profile."""
payload = dict(data or {})
profile = str(payload.get("profile") or "paper").strip().lower()
if profile not in PROFILE_ENVIRONMENTS:
@@ -74,6 +89,7 @@ class EtoroConfig:
user_key: str | None = None,
profile: str | None = None,
) -> "EtoroConfig":
+ """Return a copy with CLI/tool overrides applied."""
payload = asdict(self)
if api_key is not None:
payload["api_key"] = api_key
@@ -85,10 +101,12 @@ class EtoroConfig:
@property
def environment(self) -> str:
+ """Return ``paper`` or ``live`` for this profile."""
return PROFILE_ENVIRONMENTS.get(self.profile, "paper")
@property
def is_paper(self) -> bool:
+ """Return whether this profile targets demo API paths."""
return self.environment == "paper"
@@ -99,11 +117,27 @@ _ENV_KEY_MAP = {
}
+def build_config(
+ profile_config: Mapping[str, Any] | None = None,
+ overrides: Mapping[str, Any] | None = None,
+) -> EtoroConfig:
+ """Resolve config: saved file ← profile defaults ← CLI overrides."""
+ base = asdict(load_config())
+ for key, value in dict(profile_config or {}).items():
+ if value is not None:
+ base[key] = value
+ cfg = EtoroConfig.from_mapping(base)
+ clean = {k: v for k, v in dict(overrides or {}).items() if k in _OVERRIDE_KEYS and v not in (None, "")}
+ return cfg.with_overrides(**clean) if clean else cfg
+
+
def config_path() -> Path:
+ """Return the user-level eToro config path."""
return get_runtime_root() / CONFIG_FILENAME
def load_config() -> EtoroConfig:
+ """Load eToro settings from ``~/.vibe-trading/etoro.json`` and env fallbacks."""
path = config_path()
base: dict[str, Any] = {}
if path.exists():
@@ -115,10 +149,13 @@ def load_config() -> EtoroConfig:
env_val = os.getenv(env_name, "").strip() # noqa: env-gate — connector credential helper
if env_val:
base[field] = env_val
+ if not base:
+ return EtoroConfig()
return EtoroConfig.from_mapping(base)
def save_config(config: EtoroConfig) -> Path:
+ """Persist eToro settings with owner-only permissions."""
path = config_path()
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(asdict(config), indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
@@ -129,19 +166,6 @@ def save_config(config: EtoroConfig) -> Path:
return path
-def build_config(
- profile_config: Mapping[str, Any] | None = None,
- overrides: Mapping[str, Any] | None = None,
-) -> EtoroConfig:
- base = asdict(load_config())
- for key, value in dict(profile_config or {}).items():
- if value is not None:
- base[key] = value
- cfg = EtoroConfig.from_mapping(base)
- clean = {k: v for k, v in dict(overrides or {}).items() if k in _OVERRIDE_KEYS and v not in (None, "")}
- return cfg.with_overrides(**clean) if clean else cfg
-
-
def _missing_fields(cfg: EtoroConfig) -> list[str]:
missing: list[str] = []
if not cfg.api_key:
@@ -175,6 +199,10 @@ def info_root(cfg: EtoroConfig) -> str:
return "/api/v1/trading/info/demo" if cfg.is_paper else "/api/v1/trading/info"
+def trade_history_root(cfg: EtoroConfig) -> str:
+ return "/api/v1/trading/info/trade/demo" if cfg.is_paper else "/api/v1/trading/info/trade"
+
+
def positions_root(cfg: EtoroConfig) -> str:
return "/api/v2/trading/demo" if cfg.is_paper else "/api/v2/trading"
diff --git a/agent/src/trading/connectors/etoro/profiles.py b/agent/src/trading/connectors/etoro/profiles.py
index d6534fbb7..db447a01b 100644
--- a/agent/src/trading/connectors/etoro/profiles.py
+++ b/agent/src/trading/connectors/etoro/profiles.py
@@ -1,4 +1,9 @@
-"""Built-in eToro connector profiles."""
+"""Built-in eToro connector profiles.
+
+Layer A ships read-only paper and live profiles; the trade profiles add order
+placement, position management, and copy-trading workflows. Demo and real share
+one API key pair — the profile selects ``/demo`` vs production API paths.
+"""
from __future__ import annotations
@@ -6,6 +11,7 @@ from src.trading.types import READ_CAPABILITIES, TradingProfile
ETORO_EXTENDED_CAPABILITIES = READ_CAPABILITIES + (
"orders.place",
+ "orders.cancel",
"positions.close",
"orders.cancel_close",
"positions.edit",
@@ -25,7 +31,7 @@ ETORO_PROFILES: tuple[TradingProfile, ...] = (
capabilities=READ_CAPABILITIES,
readonly=True,
config={"profile": "paper"},
- notes="Reads a demo account via eToro Public API. Demo keys only reach demo paths.",
+ notes="Reads a demo account via eToro Public API demo paths.",
),
TradingProfile(
id="etoro-live-sdk-readonly",
@@ -36,7 +42,7 @@ ETORO_PROFILES: tuple[TradingProfile, ...] = (
capabilities=READ_CAPABILITIES,
readonly=True,
config={"profile": "live-readonly"},
- notes="Reads a real account only. Order placement is not exposed in this profile.",
+ notes="Reads a real account only (production API paths). Order placement is not exposed in this profile.",
),
TradingProfile(
id="etoro-paper-trade",
@@ -61,6 +67,9 @@ ETORO_PROFILES: tuple[TradingProfile, ...] = (
),
readonly=False,
config={"profile": "live"},
- notes="Real trading and copy workflows. Risk-increasing actions require an authorized mandate.",
+ notes=(
+ "Real trading and copy workflows via production API paths. "
+ "Risk-increasing actions require an authorized mandate; the caller enforces it."
+ ),
),
)
diff --git a/agent/src/trading/connectors/etoro/sdk.py b/agent/src/trading/connectors/etoro/sdk.py
index af264345f..8ad1af17e 100644
--- a/agent/src/trading/connectors/etoro/sdk.py
+++ b/agent/src/trading/connectors/etoro/sdk.py
@@ -16,6 +16,7 @@ from src.trading.connectors.etoro.client import (
make_client,
public_config,
save_config,
+ trade_history_root,
)
from src.trading.connectors.etoro.copy_trading import (
copy_close,
@@ -41,6 +42,7 @@ __all__ = [
"load_config",
"save_config",
"check_status",
+ "get_user_profile",
"get_account_snapshot",
"get_positions",
"get_open_orders",
@@ -92,6 +94,7 @@ def check_status(config: EtoroConfig | None = None) -> dict[str, Any]:
report["error"] = f"eToro connector not configured: missing {', '.join(missing_fields)}."
return report
try:
+ me = get_user_profile(cfg)
portfolio = get_account_snapshot(cfg)
except (EtoroConfigError, EtoroAPIError) as exc:
report["status"] = "error"
@@ -104,10 +107,22 @@ def check_status(config: EtoroConfig | None = None) -> dict[str, Any]:
report["account"] = {
"profile": cfg.profile,
"portfolio_status": portfolio.get("status"),
+ "scopes": me.get("scopes"),
+ "real_cid": me.get("realCid") or me.get("realCID"),
+ "demo_cid": me.get("demoCid") or me.get("demoCID"),
}
return report
+def get_user_profile(config: EtoroConfig | None = None) -> dict[str, Any]:
+ """Return authenticated user profile and granted API scopes (`GET /api/v1/me`)."""
+ cfg = config or load_config()
+ payload = _client(cfg).request("GET", "/api/v1/me", allow_retry=True)
+ if isinstance(payload, dict):
+ return payload
+ return {"raw": payload}
+
+
def get_account_snapshot(config: EtoroConfig | None = None) -> dict[str, Any]:
cfg = config or load_config()
client = _client(cfg)
@@ -135,7 +150,7 @@ def get_open_orders(config: EtoroConfig | None = None, *, include_executions: bo
result: dict[str, Any] = {"status": "ok", **_base_payload(cfg), "orders": orders}
if include_executions:
try:
- history = _client(cfg).request("GET", f"{info_root(cfg)}/history", allow_retry=True)
+ history = _client(cfg).request("GET", f"{trade_history_root(cfg)}/history", allow_retry=True)
result["history"] = history
except EtoroAPIError as exc:
result["history_error"] = str(exc)
@@ -415,18 +430,27 @@ def _normalize_candles(payload: Any) -> list[dict[str, Any]]:
candles = raw
elif isinstance(payload, list):
candles = payload
+
rows: list[dict[str, Any]] = []
for candle in candles:
if not isinstance(candle, dict):
continue
- rows.append(
- {
- "timestamp": candle.get("fromDate") or candle.get("timestamp") or candle.get("t"),
- "open": candle.get("open"),
- "high": candle.get("high"),
- "low": candle.get("low"),
- "close": candle.get("close"),
- "volume": candle.get("volume"),
- }
- )
+ nested = candle.get("candles")
+ if isinstance(nested, list) and nested:
+ for inner in nested:
+ if isinstance(inner, dict):
+ rows.append(_normalize_candle_row(inner))
+ continue
+ rows.append(_normalize_candle_row(candle))
return rows
+
+
+def _normalize_candle_row(candle: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "timestamp": candle.get("fromDate") or candle.get("timestamp") or candle.get("t"),
+ "open": candle.get("open"),
+ "high": candle.get("high"),
+ "low": candle.get("low"),
+ "close": candle.get("close"),
+ "volume": candle.get("volume"),
+ }
diff --git a/agent/src/trading/connectors/etoro/trading.py b/agent/src/trading/connectors/etoro/trading.py
index 7886926e9..4fb4e5210 100644
--- a/agent/src/trading/connectors/etoro/trading.py
+++ b/agent/src/trading/connectors/etoro/trading.py
@@ -14,7 +14,7 @@ from src.trading.connectors.etoro.client import (
make_client,
positions_root,
)
-from src.trading.connectors.etoro.instruments import resolve_instrument_id
+from src.trading.connectors.etoro.instruments import resolve_instrument_id, _looks_like_ticker
def _base(cfg: EtoroConfig) -> dict[str, Any]:
@@ -58,14 +58,14 @@ def place_order(
return _order_error(cfg, "order_type must be 'market' or 'limit'", symbol=symbol, side=clean_side)
try:
- instrument_id = resolve_instrument_id(symbol, cfg)
+ instrument_ref = _order_instrument_ref(symbol, cfg)
except EtoroAPIError as exc:
return _order_error(cfg, str(exc), symbol=symbol, side=clean_side)
body: dict[str, Any] = {
"action": "open",
"transaction": clean_side,
- "instrumentId": instrument_id,
+ **instrument_ref,
"orderType": "mkt" if clean_type == "market" else "mit",
"orderCurrency": "usd",
"leverage": 1,
@@ -76,7 +76,7 @@ def place_order(
else:
body["units"] = float(quantity)
if clean_type == "limit" and limit_price is not None:
- body["rate"] = float(limit_price)
+ body["TriggerRate"] = float(limit_price)
req_id = (request_id or str(uuid.uuid4())).strip()
path = f"{execution_root(cfg)}/orders"
@@ -86,6 +86,7 @@ def place_order(
return _order_error(cfg, str(exc), symbol=symbol, side=clean_side, request_id=req_id)
order_id = _extract_order_id(payload)
+ instrument_id = instrument_ref.get("instrumentId")
return {
"status": "ok",
**_base(cfg),
@@ -229,6 +230,17 @@ def edit_position_stops(
return {"status": "ok", **_base(cfg), "position_id": pos_id, "request_id": req_id, "raw": payload}
+def _order_instrument_ref(symbol: str, cfg: EtoroConfig) -> dict[str, Any]:
+ """Build exactly one of ``symbol`` or ``instrumentId`` for open-order bodies."""
+ token = str(symbol or "").strip()
+ if not token:
+ raise EtoroAPIError("symbol is required")
+ if _looks_like_ticker(token):
+ return {"symbol": token}
+ instrument_id = resolve_instrument_id(token, cfg)
+ return {"instrumentId": instrument_id}
+
+
def _extract_order_id(payload: Any) -> str | None:
if not isinstance(payload, dict):
return None
diff --git a/agent/tests/test_etoro_connector.py b/agent/tests/test_etoro_connector.py
index ab1b1d454..604683a12 100644
--- a/agent/tests/test_etoro_connector.py
+++ b/agent/tests/test_etoro_connector.py
@@ -14,14 +14,16 @@ from src.trading.connectors.etoro import sdk as etoro_sdk
from src.trading.connectors.etoro.client import (
EtoroClient,
EtoroConfig,
+ build_config,
+ copy_root,
execution_root,
execution_v1_root,
info_root,
- copy_root,
positions_root,
set_client_factory,
)
from src.trading.connectors.etoro.classification import ETORO_TOOL_CLASS
+from src.trading.connectors.etoro.profiles import ETORO_EXTENDED_CAPABILITIES
pytestmark = pytest.mark.unit
@@ -69,9 +71,15 @@ def test_etoro_profiles_registered() -> None:
assert paper.environment == "paper"
assert live.environment == "live"
assert "orders.place" in paper.capabilities
+ assert "orders.cancel" in paper.capabilities
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_demo_and_real_paths_separated() -> None:
paper = EtoroConfig(profile="paper", api_key="k", user_key="u")
live = EtoroConfig(profile="live", api_key="k", user_key="u")
@@ -82,6 +90,23 @@ def test_demo_and_real_paths_separated() -> None:
assert info_root(paper).endswith("/demo")
assert copy_root(paper).endswith("/demo")
assert positions_root(paper).endswith("/demo")
+ assert paper.api_key == live.api_key
+
+
+def test_shared_credentials_across_paper_and_live_profiles(monkeypatch, tmp_path) -> None:
+ cfg_path = tmp_path / "etoro.json"
+ cfg_path.write_text(
+ json.dumps({"api_key": "shared-key", "user_key": "shared-user", "profile": "paper"}),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr("src.trading.connectors.etoro.client.config_path", lambda: cfg_path)
+ paper_cfg = build_config({"profile": "paper"}, None)
+ live_cfg = build_config({"profile": "live"}, None)
+ assert paper_cfg.api_key == "shared-key"
+ assert live_cfg.api_key == "shared-key"
+ assert live_cfg.user_key == "shared-user"
+ assert paper_cfg.is_paper is True
+ assert live_cfg.is_paper is False
def test_every_request_has_unique_request_id() -> None:
@@ -131,14 +156,56 @@ def test_place_order_uses_demo_execution_path(monkeypatch) -> None:
)
assert result["status"] == "ok"
assert "/execution/demo/orders" in captured["url"]
- assert captured["json"]["instrumentId"] == 1001
+ assert captured["json"]["symbol"] == "AAPL"
assert captured["method"] == "POST"
+def test_limit_place_order_sets_trigger_rate(monkeypatch) -> None:
+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")
+ captured: dict[str, Any] = {}
+
+ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:
+ captured["json"] = kwargs.get("json")
+ return _FakeResponse(200, {"orderID": 7})
+
+ monkeypatch.setattr("src.trading.connectors.etoro.trading.resolve_instrument_id", lambda symbol, c: 100000)
+ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))
+
+ result = etoro_sdk.place_order(
+ cfg,
+ symbol="BTC",
+ side="buy",
+ notional=50.0,
+ order_type="limit",
+ limit_price=10000.0,
+ )
+ assert result["status"] == "ok"
+ assert captured["json"]["orderType"] == "mit"
+ assert captured["json"]["TriggerRate"] == 10000.0
+
+
+def test_cancel_order_uses_demo_delete_path(monkeypatch) -> None:
+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")
+ captured: dict[str, Any] = {}
+
+ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:
+ captured["method"] = method
+ captured["url"] = url
+ return _FakeResponse(200, {})
+
+ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))
+ result = etoro_sdk.cancel_order(cfg, "12345", symbol="BTC")
+ assert result["status"] == "ok"
+ assert captured["method"] == "DELETE"
+ assert captured["url"].endswith("/orders/12345")
+ assert "/execution/demo/" in captured["url"]
+
+
def test_classification_registered() -> None:
curated = registry._BROKER_CURATED_MAPS["etoro"]
assert classify_tool("get_positions", None, curated) is ToolClass.READ
assert classify_tool("place_order", None, curated) is ToolClass.WRITE
+ assert classify_tool("cancel_order", None, curated) is ToolClass.WRITE
assert classify_tool("unknown_etoro_op", None, curated) is ToolClass.UNKNOWN
assert ETORO_TOOL_CLASS["copy_close"] is ToolClass.WRITE
assert ETORO_TOOL_CLASS["get_instrument_metadata"] is ToolClass.READ
@@ -207,14 +274,220 @@ def test_get_open_orders_reads_portfolio_orders(monkeypatch) -> None:
)
set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))
- from src.trading.connectors.etoro import sdk as etoro_sdk
-
result = etoro_sdk.get_open_orders(cfg)
assert result["status"] == "ok"
assert result["orders"][0]["order_id"] == 99
assert result["orders"][0]["order_kind"] == "ordersForOpen"
+def test_get_open_orders_trade_history_path(monkeypatch) -> None:
+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")
+ captured_urls: list[str] = []
+
+ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:
+ captured_urls.append(url)
+ if "/portfolio" in url:
+ return _FakeResponse(200, {"clientPortfolio": {"ordersForOpen": []}})
+ if "/trade/demo/history" in url:
+ return _FakeResponse(200, {"items": []})
+ raise AssertionError(f"unexpected {method} {url}")
+
+ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))
+ result = etoro_sdk.get_open_orders(cfg, include_executions=True)
+ assert result["status"] == "ok"
+ assert "history" in result
+ assert any("/trade/demo/history" in u for u in captured_urls)
+
+
+def test_get_quote_reads_rates(monkeypatch) -> None:
+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")
+
+ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:
+ if "/market-data/search" in url:
+ return _FakeResponse(200, {"items": [{"instrumentId": 100000, "internalSymbolFull": "BTC"}]})
+ if "/instruments/rates" in url:
+ return _FakeResponse(200, {"items": [{"instrumentID": 100000, "bid": 1.0, "ask": 2.0}]})
+ raise AssertionError(f"unexpected {method} {url}")
+
+ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))
+ result = etoro_sdk.get_quote("BTC", config=cfg)
+ assert result["status"] == "ok"
+ assert result["quote"]["bid"] == 1.0
+ assert result["quote"]["ask"] == 2.0
+
+
+def test_get_historical_bars_requests_candles_path(monkeypatch) -> None:
+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")
+ captured_url = ""
+
+ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:
+ nonlocal captured_url
+ captured_url = url
+ if "/market-data/search" in url:
+ return _FakeResponse(200, {"items": [{"instrumentId": 100000, "internalSymbolFull": "BTC"}]})
+ return _FakeResponse(
+ 200,
+ {
+ "candles": [
+ {
+ "instrumentId": 100000,
+ "candles": [{"fromDate": "2026-08-05T00:00:00Z", "open": 1.0, "close": 2.0}],
+ }
+ ]
+ },
+ )
+
+ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))
+ result = etoro_sdk.get_historical_bars("BTC", config=cfg, period="1d", limit=5)
+ assert result["status"] == "ok"
+ assert "/history/candles/desc/OneDay/5" in captured_url
+ assert result["bars"][0]["open"] == 1.0
+
+
+def test_close_position_uses_market_close_path(monkeypatch) -> None:
+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")
+ captured: dict[str, Any] = {}
+
+ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:
+ captured["method"] = method
+ captured["url"] = url
+ return _FakeResponse(200, {"orderID": 55})
+
+ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))
+ result = etoro_sdk.close_position(cfg, position_id=10, instrument_id=100000)
+ assert result["status"] == "ok"
+ assert captured["method"] == "POST"
+ assert "/market-close-orders/positions/10" in captured["url"]
+ assert "/execution/demo/" in captured["url"]
+
+
+def test_cancel_close_order_uses_delete_path(monkeypatch) -> None:
+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")
+ captured: dict[str, Any] = {}
+
+ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:
+ captured["method"] = method
+ captured["url"] = url
+ return _FakeResponse(200, {})
+
+ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))
+ result = etoro_sdk.cancel_close_order(cfg, order_id="77")
+ assert result["status"] == "ok"
+ assert captured["method"] == "DELETE"
+ assert captured["url"].endswith("/market-close-orders/77")
+
+
+def test_edit_position_stops_patches_position(monkeypatch) -> None:
+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")
+ captured: dict[str, Any] = {}
+
+ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:
+ captured["method"] = method
+ captured["url"] = url
+ captured["json"] = kwargs.get("json")
+ return _FakeResponse(200, {})
+
+ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))
+ result = etoro_sdk.edit_position_stops(cfg, position_id=5, stop_loss=90.0, take_profit=110.0)
+ assert result["status"] == "ok"
+ assert captured["method"] == "PATCH"
+ assert "/positions/5" in captured["url"]
+ assert captured["json"]["stopLossRate"] == 90.0
+ assert captured["json"]["takeProfitRate"] == 110.0
+
+
+def test_copy_precheck_posts_eligibility(monkeypatch) -> None:
+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")
+ captured: dict[str, Any] = {}
+
+ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:
+ captured["method"] = method
+ captured["url"] = url
+ captured["json"] = kwargs.get("json")
+ return _FakeResponse(200, {"eligible": True})
+
+ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))
+ result = etoro_sdk.copy_precheck(cfg, parent_cid=123, amount_usd=100.0)
+ assert result["status"] == "ok"
+ assert captured["method"] == "POST"
+ assert captured["url"].endswith("/eligibility")
+ assert captured["json"]["parentCID"] == 123
+
+
+def test_copy_start_posts_copy_root(monkeypatch) -> None:
+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")
+ captured: dict[str, Any] = {}
+
+ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:
+ captured["url"] = url
+ captured["json"] = kwargs.get("json")
+ return _FakeResponse(200, {"referenceID": "ref-1"})
+
+ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))
+ result = etoro_sdk.copy_start_or_adjust(cfg, parent_cid=123, amount_usd=200.0)
+ assert result["status"] == "ok"
+ assert result["reference_id"] == "ref-1"
+ assert copy_root(cfg) in captured["url"]
+ assert captured["json"]["amount"] == 200.0
+
+
+def test_copy_poll_gets_reference(monkeypatch) -> None:
+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")
+ captured_url = ""
+
+ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:
+ nonlocal captured_url
+ captured_url = url
+ return _FakeResponse(200, {"isCompleted": True})
+
+ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))
+ result = etoro_sdk.copy_poll(cfg, reference_id="ref-1")
+ assert result["status"] == "ok"
+ assert captured_url.endswith("/ref-1")
+
+
+def test_copy_close_posts_close(monkeypatch) -> None:
+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")
+ captured: dict[str, Any] = {}
+
+ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:
+ captured["url"] = url
+ captured["json"] = kwargs.get("json")
+ return _FakeResponse(200, {"referenceID": "ref-close"})
+
+ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))
+ result = etoro_sdk.copy_close(cfg, mirror_id=99, unregister_type="Close")
+ assert result["status"] == "ok"
+ assert captured["url"].endswith("/close")
+ assert captured["json"]["mirrorID"] == 99
+
+
+def test_normalize_candles_flattens_nested_instrument_buckets() -> None:
+ from src.trading.connectors.etoro.sdk import _normalize_candles
+
+ payload = {
+ "interval": "OneDay",
+ "candles": [
+ {
+ "instrumentId": 100000,
+ "candles": [
+ {
+ "fromDate": "2026-08-05T00:00:00Z",
+ "open": 64297.8,
+ "high": 64499.9,
+ "low": 63828.87,
+ "close": 63855.8,
+ }
+ ],
+ }
+ ],
+ }
+ rows = _normalize_candles(payload)
+ assert len(rows) == 1
+ assert rows[0]["open"] == 64297.8
+ assert rows[0]["close"] == 63855.8
+
+
def test_service_dispatches_positions(monkeypatch) -> None:
cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")
@@ -228,3 +501,31 @@ def test_service_dispatches_positions(monkeypatch) -> None:
assert result["status"] == "ok"
assert result["connector"] == "etoro"
assert result["positions"][0]["symbol"] == "AAPL"
+
+
+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"):
+ return _FakeResponse(200, {"items": [{"instrumentId": 100000, "internalSymbolFull": "BTC"}]})
+ return _FakeResponse(200, {"items": []})
+
+ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))
+ result = service.search_instruments("BTC", "etoro-paper-sdk", api_key="k", user_key="u")
+ assert result["status"] == "ok"
+ assert result["instruments"][0]["instrument_id"] == 100000
+
+
+def test_service_cancel_order_paper(monkeypatch) -> None:
+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")
+
+ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:
+ if method == "DELETE":
+ return _FakeResponse(200, {})
+ raise AssertionError(f"unexpected {method} {url}")
+
+ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))
+ result = service.cancel_order("42", "etoro-paper-trade", symbol="BTC", api_key="k", user_key="u")
+ assert result["status"] == "ok"
+ assert result["profile_id"] == "etoro-paper-trade"
diff --git a/agent/tests/test_etoro_live_actions.py b/agent/tests/test_etoro_live_actions.py
index 4fa7fa06b..c74449f0d 100644
--- a/agent/tests/test_etoro_live_actions.py
+++ b/agent/tests/test_etoro_live_actions.py
@@ -18,14 +18,33 @@ class _FakeEtoroModule:
def __init__(self):
self.calls: list[str] = []
+ def build_config(self, profile_config, overrides):
+ return None
+
def close_position(self, config, **kwargs):
self.calls.append("close")
return {"status": "ok", "position_id": kwargs.get("position_id")}
+ def cancel_close_order(self, config, order_id="", *, request_id=None, **kwargs):
+ self.calls.append("cancel_close")
+ return {"status": "ok", "order_id": order_id}
+
+ def edit_position_stops(self, config, **kwargs):
+ self.calls.append("edit")
+ return {"status": "ok", "position_id": kwargs.get("position_id")}
+
+ def copy_start_or_adjust(self, config, **kwargs):
+ self.calls.append("copy_start")
+ return {"status": "ok", "reference_id": "ref-1"}
+
def copy_close(self, config, **kwargs):
self.calls.append("copy_close")
return {"status": "ok", "mirror_id": kwargs.get("mirror_id")}
+ def cancel_order(self, config, order_id, **kwargs):
+ self.calls.append("cancel")
+ return {"status": "ok", "order_id": order_id}
+
def get_positions(self, config):
return {"status": "ok", "positions": []}
@@ -110,10 +129,58 @@ def test_risk_increasing_edit_requires_mandate_when_halted(monkeypatch) -> None:
assert result["status"] == "blocked"
+def test_copy_close_allowed_when_halted(monkeypatch) -> None:
+ module = _FakeEtoroModule()
+ _patch_gate(monkeypatch, mandate=_mandate(), halted=True)
+ result = gate.execute_live_action(
+ broker="etoro",
+ connector_module=module,
+ config=None,
+ remote_tool="copy_close",
+ risk_reducing=True,
+ intent=None,
+ execute_fn=lambda: module.copy_close(None, mirror_id=1),
+ audit_request={"mirror_id": 1},
+ )
+ assert result["status"] == "ok"
+ assert module.calls == ["copy_close"]
+
+
def test_service_close_position_paper_bypasses_gate(monkeypatch) -> None:
module = _FakeEtoroModule()
- module.build_config = lambda profile_config, overrides: None # type: ignore[method-assign]
monkeypatch.setattr(service, "_sdk_module", lambda connector: module)
result = service.close_position("99", "etoro-paper-trade")
assert result["status"] == "ok"
assert module.calls == ["close"]
+
+
+def test_service_cancel_close_order_paper_bypasses_gate(monkeypatch) -> None:
+ module = _FakeEtoroModule()
+ monkeypatch.setattr(service, "_sdk_module", lambda connector: module)
+ result = service.cancel_close_order("55", "etoro-paper-trade")
+ assert result["status"] == "ok"
+ assert module.calls == ["cancel_close"]
+
+
+def test_service_edit_position_stops_paper_bypasses_gate(monkeypatch) -> None:
+ module = _FakeEtoroModule()
+ monkeypatch.setattr(service, "_sdk_module", lambda connector: module)
+ result = service.edit_position_stops("7", "etoro-paper-trade", stop_loss=90.0)
+ assert result["status"] == "ok"
+ assert module.calls == ["edit"]
+
+
+def test_service_etoro_copy_start_paper_bypasses_gate(monkeypatch) -> None:
+ module = _FakeEtoroModule()
+ monkeypatch.setattr(service, "_sdk_module", lambda connector: module)
+ result = service.etoro_copy_start(123, 100.0, "etoro-paper-trade")
+ assert result["status"] == "ok"
+ assert module.calls == ["copy_start"]
+
+
+def test_service_cancel_order_paper_bypasses_gate(monkeypatch) -> None:
+ module = _FakeEtoroModule()
+ monkeypatch.setattr(service, "_sdk_module", lambda connector: module)
+ result = service.cancel_order("42", "etoro-paper-trade", symbol="BTC")
+ assert result["status"] == "ok"
+ assert module.calls == ["cancel"]