"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(etoro): add full Public API connector with demo/real profiles
Ofek Shaked9d6a43e08d5d
diff --git a/agent/.env.example b/agent/.env.exampleindex 5ee40304d..6bb05330a 100644--- a/agent/.env.example+++ b/agent/.env.example@@ -307,3 +307,9 @@ TUSHARE_TOKEN=your-tushare-token# TAP_ALPACA_CREDENTIAL=alpaca# Seconds to wait for a human approval decision (default: 300)# TAP_APPROVAL_TIMEOUT=300++# ============================================================================+# eToro Public API (optional connector credentials)+# ============================================================================+# ETORO_API_KEY=your_public_api_key+# ETORO_USER_KEY=your_user_keydiff --git a/agent/src/config/env_schema.py b/agent/src/config/env_schema.pyindex 660fc2bcd..5cc459482 100644--- a/agent/src/config/env_schema.py+++ b/agent/src/config/env_schema.py@@ -190,6 +190,8 @@ class DataConfig(_EnvBase):longbridge_app_key: str = Field(alias="LONGBRIDGE_APP_KEY", default="")longbridge_app_secret: str = Field(alias="LONGBRIDGE_APP_SECRET", default="")longbridge_access_token: str = Field(alias="LONGBRIDGE_ACCESS_TOKEN", default="")+ etoro_api_key: str = Field(alias="ETORO_API_KEY", default="")+ etoro_user_key: str = Field(alias="ETORO_USER_KEY", default="")# ---------------------------------------------------------------------------diff --git a/agent/src/live/registry.py b/agent/src/live/registry.pyindex 81f9ba366..8102bfbd2 100644--- a/agent/src/live/registry.py+++ b/agent/src/live/registry.py@@ -34,6 +34,7 @@ from src.trading.connectors.okx.classification import OKX_TOOL_CLASSfrom src.trading.connectors.robinhood.classification import ROBINHOOD_TOOL_CLASSfrom src.trading.connectors.shoonya.classification import SHOONYA_TOOL_CLASSfrom src.trading.connectors.tiger.classification import TIGER_TOOL_CLASS+from src.trading.connectors.etoro.classification import ETORO_TOOL_CLASSfrom src.trading.connectors.trading212.classification import TRADING212_TOOL_CLASSlogger = logging.getLogger(__name__)@@ -55,6 +56,7 @@ _BROKER_CURATED_MAPS = {"shoonya": SHOONYA_TOOL_CLASS,"trading212": TRADING212_TOOL_CLASS,"mt5": MT5_TOOL_CLASS,+ "etoro": ETORO_TOOL_CLASS,}diff --git a/agent/src/live/sdk_order_gate.py b/agent/src/live/sdk_order_gate.pyindex 2fdc27dc2..7cdc4470b 100644--- a/agent/src/live/sdk_order_gate.py+++ b/agent/src/live/sdk_order_gate.py@@ -133,6 +133,159 @@ def execute_live_order(return _deny_breach(broker, session_id, breach, mandate, intent, reauth)+def execute_live_action(+ *,+ broker: str,+ connector_module: Any,+ config: Any,+ remote_tool: str,+ risk_reducing: bool,+ intent: OrderIntent | None,+ execute_fn: Any,+ audit_request: dict[str, Any] | None = None,+ session_id: str = "",+) -> dict[str, Any]:+ """Run the live mandate gate around a direct-SDK write that is not ``place_order``.++ Risk-reducing actions (cancel, full close, copy detach) skip halt and mandate+ checks but are still audit-logged. Risk-increasing actions follow the same+ ceremony as :func:`execute_live_order`.+ """+ broker = (broker or "").strip().lower()+ mandate = load_mandate(broker)++ if not risk_reducing:+ if mandate is None or mandate.schema_version != MANDATE_SCHEMA_VERSION:+ return _deny(broker, session_id, "no valid mandate on file", ["mandate"], mandate, intent=intent)++ if _is_expired(mandate):+ return _deny(+ broker,+ session_id,+ "mandate expired — re-authorize",+ ["mandate", "expiry"],+ mandate,+ intent=None,+ reauth=True,+ )++ if halt_flag_set(broker):+ return _deny(+ broker,+ session_id,+ "live trading halted",+ ["mandate", "expiry", "halt_flag"],+ mandate,+ intent=None,+ )+ if intent is None:+ return _deny(+ broker,+ session_id,+ "live action missing risk intent (fail-closed)",+ ["mandate", "intent"],+ mandate,+ intent=None,+ )+ normalized = _normalize_notional(intent, connector_module, config)+ if normalized is None:+ return _deny(+ broker,+ session_id,+ "quantity order notional could not be priced (fail-closed)",+ ["mandate", "expiry", "halt_flag", "quote"],+ mandate,+ intent=intent,+ )+ intent = normalized+ positions = _safe_read(connector_module, "get_positions", config)+ balance = _safe_read(connector_module, "get_account_snapshot", config)+ try:+ with daily_order_lock(broker):+ daily_count = read_daily_count(broker)+ breach = check_mandate(+ mandate,+ intent,+ positions,+ balance,+ broker=broker,+ remote_tool=remote_tool,+ daily_count=daily_count,+ )+ if breach is not None:+ reauth = breach.kind not in (BREACH_KIND_UNIVERSE, BREACH_KIND_INSTRUMENT)+ return _deny_breach(broker, session_id, breach, mandate, intent, reauth)+ except DailyOrderLockUnavailable as exc:+ return _deny(+ broker,+ session_id,+ str(exc),+ ["mandate", "expiry", "halt_flag", "daily_order_lock"],+ mandate,+ intent=intent,+ )++ try:+ result = execute_fn()+ except Exception as exc: # noqa: BLE001+ logger.warning("live %s raised for %s: %s", remote_tool, broker, exc)+ result = {"status": "error", "error": str(exc)}++ is_error = not isinstance(result, dict) or str(result.get("status", "")).lower() != "ok"+ checked = ["mandate", "expiry"]+ if not risk_reducing:+ checked.extend(+ [+ "halt_flag",+ "exclude_symbols",+ "allowed_instruments",+ "asset_classes",+ "max_order_notional_usd",+ "max_total_exposure_usd",+ "max_leverage",+ "max_trades_per_day",+ "account_funding_usd",+ "universe_floors",+ ]+ )+ else:+ checked.append("risk_reducing")++ if is_error:+ record = _audit_action(+ broker,+ session_id,+ remote_tool=remote_tool,+ kind="order_rejected",+ outcome="error",+ mandate=mandate,+ intent=intent,+ broker_request=audit_request,+ broker_response=result if isinstance(result, dict) else {"raw": result},+ gate_decision={"allowed": True, "decision": _DECISION_ALLOW, "checked_limits": checked},+ error=_error_message(result),+ )+ else:+ if not risk_reducing:+ increment_daily_count(broker)+ record = _audit_action(+ broker,+ session_id,+ remote_tool=remote_tool,+ kind="order_placed",+ outcome="accepted",+ mandate=mandate,+ intent=intent,+ broker_request=audit_request,+ broker_response=result,+ gate_decision={"allowed": True, "decision": _DECISION_ALLOW, "checked_limits": checked},+ )++ if isinstance(result, dict) and record is not None:+ result = {**result, LIVE_ACTION_RESULT_KEY: record}+ return result if isinstance(result, dict) else {"status": "error", "error": "non-dict broker result"}++# --------------------------------------------------------------------------- ## Decision helpers# --------------------------------------------------------------------------- #@@ -340,6 +493,35 @@ def _safe_read(connector_module: Any, fn_name: str, config: Any) -> object:def _audit(broker, session_id, *, kind, outcome, mandate, intent, broker_request, broker_response, gate_decision, error=None) -> dict | None:+ return _audit_action(+ broker,+ session_id,+ remote_tool=_REMOTE_TOOL,+ kind=kind,+ outcome=outcome,+ mandate=mandate,+ intent=intent,+ broker_request=broker_request,+ broker_response=broker_response,+ gate_decision=gate_decision,+ error=error,+ )+++def _audit_action(+ broker,+ session_id,+ *,+ remote_tool: str,+ kind,+ outcome,+ mandate,+ intent,+ broker_request,+ broker_response,+ gate_decision,+ error=None,+) -> dict | None:consent = mandate.consent if mandate is not None else Nonetry:event = LiveActionEvent(@@ -347,7 +529,7 @@ def _audit(broker, session_id, *, kind, outcome, mandate, intent, broker_requestsession_id=session_id,outcome=outcome, # type: ignore[arg-type]server=broker,- remote_tool=_REMOTE_TOOL,+ remote_tool=remote_tool,intent_normalized=_describe_intent(intent),mandate_snapshot_ref=consent.consent_token_sha256 if consent else None,consent_record_ref=consent.account_ref if consent else None,diff --git a/agent/src/tools/trading_connector_tool.py b/agent/src/tools/trading_connector_tool.pyindex af637a392..1ad6bc500 100644--- a/agent/src/tools/trading_connector_tool.py+++ b/agent/src/tools/trading_connector_tool.py@@ -18,8 +18,15 @@ from src.trading.profiles import (save_selected_profile_id,)from src.trading.service import (+ cancel_close_order,cancel_order,check_connection,+ close_position,+ edit_position_stops,+ etoro_copy_close,+ etoro_copy_poll,+ etoro_copy_precheck,+ etoro_copy_start,get_account,get_history,get_open_orders,@@ -149,6 +156,14 @@ TRADING_COMMON_PARAMETERS = {"type": "string","description": "Optional account code filter when supported by the connector.",},+ "api_key": {+ "type": "string",+ "description": "Optional eToro Public API key override.",+ },+ "user_key": {+ "type": "string",+ "description": "Optional eToro user key override.",+ },}@@ -171,6 +186,8 @@ def _overrides(kwargs: dict[str, Any]) -> dict[str, Any]:"port": _int_or_none(kwargs.get("port"), "port"),"client_id": _int_or_none(kwargs.get("client_id"), "client_id"),"account": _connection(kwargs.get("account")),+ "api_key": _connection(kwargs.get("api_key")),+ "user_key": _connection(kwargs.get("user_key")),}@@ -506,3 +523,265 @@ class TradingCancelOrderTool(BaseTool):)except Exception as exc: # noqa: BLE001return _json_result({"status": "error", "error": str(exc)})+++class EtoroClosePositionTool(BaseTool):+ """Close or partially close an eToro position."""++ name = "etoro_close_position"+ description = "Close or partially close an open eToro position by position id."+ parameters = {+ "type": "object",+ "properties": {+ **TRADING_COMMON_PARAMETERS,+ "position_id": {"type": "string", "description": "eToro position id."},+ "instrument_id": {"type": "integer", "description": "Optional instrument id."},+ "units_to_close": {"type": "number", "description": "Units to close; omit to close entire position."},+ "request_id": {"type": "string", "description": "Optional idempotency request id (UUID)."},+ },+ "required": ["position_id"],+ }+ repeatable = False+ is_readonly = False++ def execute(self, **kwargs: Any) -> str:+ try:+ overrides = _overrides(kwargs)+ units = _num_or_none(kwargs.get("units_to_close"), "units_to_close")+ except InvalidTradingArgument as exc:+ return _json_result({"status": "error", "error": str(exc)})+ try:+ return _json_result(+ close_position(+ kwargs["position_id"],+ _connection(kwargs.get("connection")),+ instrument_id=_int_or_none(kwargs.get("instrument_id"), "instrument_id"),+ units_to_close=units,+ request_id=_connection(kwargs.get("request_id")),+ **overrides,+ )+ )+ except Exception as exc: # noqa: BLE001+ return _json_result({"status": "error", "error": str(exc)})+++class EtoroCancelCloseOrderTool(BaseTool):+ name = "etoro_cancel_close_order"+ description = "Cancel a pending eToro market close order by order id."+ parameters = {+ "type": "object",+ "properties": {+ **TRADING_COMMON_PARAMETERS,+ "order_id": {"type": "string", "description": "Pending close order id."},+ "request_id": {"type": "string", "description": "Optional idempotency request id (UUID)."},+ },+ "required": ["order_id"],+ }+ repeatable = False+ is_readonly = False++ def execute(self, **kwargs: Any) -> str:+ try:+ overrides = _overrides(kwargs)+ except InvalidTradingArgument as exc:+ return _json_result({"status": "error", "error": str(exc)})+ try:+ return _json_result(+ cancel_close_order(+ str(kwargs["order_id"]),+ _connection(kwargs.get("connection")),+ request_id=_connection(kwargs.get("request_id")),+ **overrides,+ )+ )+ except Exception as exc: # noqa: BLE001+ return _json_result({"status": "error", "error": str(exc)})+++class EtoroEditPositionStopsTool(BaseTool):+ name = "etoro_edit_position_stops"+ description = "Modify stop-loss, take-profit, or trailing stop on an open eToro position."+ parameters = {+ "type": "object",+ "properties": {+ **TRADING_COMMON_PARAMETERS,+ "position_id": {"type": "string", "description": "eToro position id."},+ "stop_loss": {"type": "number", "description": "New stop-loss rate."},+ "take_profit": {"type": "number", "description": "New take-profit rate."},+ "trailing_stop_loss": {"type": "boolean", "description": "Enable trailing stop-loss."},+ "request_id": {"type": "string", "description": "Optional idempotency request id (UUID)."},+ },+ "required": ["position_id"],+ }+ repeatable = False+ is_readonly = False++ def execute(self, **kwargs: Any) -> str:+ try:+ overrides = _overrides(kwargs)+ stop_loss = _num_or_none(kwargs.get("stop_loss"), "stop_loss")+ take_profit = _num_or_none(kwargs.get("take_profit"), "take_profit")+ except InvalidTradingArgument as exc:+ return _json_result({"status": "error", "error": str(exc)})+ trailing = kwargs.get("trailing_stop_loss")+ try:+ return _json_result(+ edit_position_stops(+ kwargs["position_id"],+ _connection(kwargs.get("connection")),+ stop_loss=stop_loss,+ take_profit=take_profit,+ trailing_stop_loss=bool(trailing) if trailing is not None else None,+ request_id=_connection(kwargs.get("request_id")),+ **overrides,+ )+ )+ except Exception as exc: # noqa: BLE001+ return _json_result({"status": "error", "error": str(exc)})+++class EtoroCopyPrecheckTool(BaseTool):+ name = "etoro_copy_precheck"+ description = "Dry-run whether the account can copy an investor with a given USD amount."+ parameters = {+ "type": "object",+ "properties": {+ **TRADING_COMMON_PARAMETERS,+ "parent_cid": {"type": "integer", "description": "Investor parent CID."},+ "amount_usd": {"type": "number", "description": "USD amount to copy or adjust."},+ "request_id": {"type": "string", "description": "Optional request id (UUID)."},+ },+ "required": ["parent_cid", "amount_usd"],+ }+ repeatable = True+ is_readonly = True++ def execute(self, **kwargs: Any) -> str:+ try:+ overrides = _overrides(kwargs)+ amount = _finite_float(kwargs["amount_usd"], "amount_usd")+ parent_cid = _int_or_none(kwargs["parent_cid"], "parent_cid")+ except InvalidTradingArgument as exc:+ return _json_result({"status": "error", "error": str(exc)})+ try:+ return _json_result(+ etoro_copy_precheck(+ parent_cid,+ amount,+ _connection(kwargs.get("connection")),+ request_id=_connection(kwargs.get("request_id")),+ **overrides,+ )+ )+ except Exception as exc: # noqa: BLE001+ return _json_result({"status": "error", "error": str(exc)})+++class EtoroCopyStartTool(BaseTool):+ name = "etoro_copy_start"+ description = "Start copying an investor or adjust an existing copy allocation."+ parameters = {+ "type": "object",+ "properties": {+ **TRADING_COMMON_PARAMETERS,+ "parent_cid": {"type": "integer", "description": "Investor parent CID."},+ "amount_usd": {"type": "number", "description": "USD amount to add (negative to reduce)."},+ "request_id": {"type": "string", "description": "Optional request id (UUID)."},+ },+ "required": ["parent_cid", "amount_usd"],+ }+ repeatable = False+ is_readonly = False++ def execute(self, **kwargs: Any) -> str:+ try:+ overrides = _overrides(kwargs)+ amount = _finite_float(kwargs["amount_usd"], "amount_usd")+ parent_cid = _int_or_none(kwargs["parent_cid"], "parent_cid")+ except InvalidTradingArgument as exc:+ return _json_result({"status": "error", "error": str(exc)})+ try:+ return _json_result(+ etoro_copy_start(+ parent_cid,+ amount,+ _connection(kwargs.get("connection")),+ request_id=_connection(kwargs.get("request_id")),+ **overrides,+ )+ )+ except Exception as exc: # noqa: BLE001+ return _json_result({"status": "error", "error": str(exc)})+++class EtoroCopyPollTool(BaseTool):+ name = "etoro_copy_poll"+ description = "Poll the outcome of an asynchronous eToro copy operation."+ parameters = {+ "type": "object",+ "properties": {+ **TRADING_COMMON_PARAMETERS,+ "reference_id": {"type": "string", "description": "Copy operation reference id."},+ "request_id": {"type": "string", "description": "Optional request id (UUID)."},+ },+ "required": ["reference_id"],+ }+ repeatable = True+ is_readonly = True++ def execute(self, **kwargs: Any) -> str:+ try:+ overrides = _overrides(kwargs)+ except InvalidTradingArgument as exc:+ return _json_result({"status": "error", "error": str(exc)})+ try:+ return _json_result(+ etoro_copy_poll(+ str(kwargs["reference_id"]),+ _connection(kwargs.get("connection")),+ request_id=_connection(kwargs.get("request_id")),+ **overrides,+ )+ )+ except Exception as exc: # noqa: BLE001+ return _json_result({"status": "error", "error": str(exc)})+++class EtoroCopyCloseTool(BaseTool):+ name = "etoro_copy_close"+ description = "Close or detach an eToro copy relationship by mirror id."+ parameters = {+ "type": "object",+ "properties": {+ **TRADING_COMMON_PARAMETERS,+ "mirror_id": {"type": "integer", "description": "Copy mirror id."},+ "unregister_type": {+ "type": "string",+ "enum": ["Close", "Detach"],+ "description": "Close liquidates copy; Detach moves positions to main portfolio.",+ },+ "request_id": {"type": "string", "description": "Optional request id (UUID)."},+ },+ "required": ["mirror_id"],+ }+ repeatable = False+ is_readonly = False++ def execute(self, **kwargs: Any) -> str:+ try:+ overrides = _overrides(kwargs)+ mirror_id = _int_or_none(kwargs["mirror_id"], "mirror_id")+ except InvalidTradingArgument as exc:+ return _json_result({"status": "error", "error": str(exc)})+ try:+ return _json_result(+ etoro_copy_close(+ mirror_id,+ _connection(kwargs.get("connection")),+ unregister_type=str(kwargs.get("unregister_type") or "Close"),+ request_id=_connection(kwargs.get("request_id")),+ **overrides,+ )+ )+ except Exception as exc: # noqa: BLE001+ return _json_result({"status": "error", "error": str(exc)})diff --git a/agent/src/trading/connectors/etoro/__init__.py b/agent/src/trading/connectors/etoro/__init__.pynew file mode 100644index 000000000..cb026bd95--- /dev/null+++ b/agent/src/trading/connectors/etoro/__init__.py@@ -0,0 +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.+"""diff --git a/agent/src/trading/connectors/etoro/classification.py b/agent/src/trading/connectors/etoro/classification.pynew file mode 100644index 000000000..70c722aa2--- /dev/null+++ b/agent/src/trading/connectors/etoro/classification.py@@ -0,0 +1,27 @@+"""Curated read/write classification for eToro Public API operations."""++from __future__ import annotations++from src.live.classification import ToolClass++ETORO_TOOL_CLASS: dict[str, ToolClass] = {+ # READ+ "check_status": ToolClass.READ,+ "get_account_snapshot": ToolClass.READ,+ "get_positions": ToolClass.READ,+ "get_open_orders": ToolClass.READ,+ "get_quote": ToolClass.READ,+ "get_historical_bars": ToolClass.READ,+ "search_instruments": ToolClass.READ,+ "copy_poll": ToolClass.READ,+ "copy_precheck": ToolClass.READ,+ # WRITE — trading+ "place_order": ToolClass.WRITE,+ "cancel_order": ToolClass.WRITE,+ "close_position": ToolClass.WRITE,+ "cancel_close_order": ToolClass.WRITE,+ "edit_position_stops": ToolClass.WRITE,+ # WRITE — copy+ "copy_start_or_adjust": ToolClass.WRITE,+ "copy_close": ToolClass.WRITE,+}diff --git a/agent/src/trading/connectors/etoro/client.py b/agent/src/trading/connectors/etoro/client.pynew file mode 100644index 000000000..89293148d--- /dev/null+++ b/agent/src/trading/connectors/etoro/client.py@@ -0,0 +1,287 @@+"""HTTP transport and path builders for the eToro Public API."""++from __future__ import annotations++import json+import logging+import os+import time+import uuid+from dataclasses import asdict, dataclass+from pathlib import Path+from typing import Any, Callable, Mapping+from urllib.parse import urljoin++import requests++from src.config.paths import get_runtime_root++logger = logging.getLogger(__name__)++CONFIG_FILENAME = "etoro.json"+BASE_URL = "https://public-api.etoro.com"+PAPER_GUARD = "path_separated_key_bound"++PROFILE_ENVIRONMENTS = {+ "paper": "paper",+ "live-readonly": "live",+ "live": "live",+}++READ_BACKOFF: tuple[float, ...] = (0.5, 1.5, 4.0)+MAX_READ_RETRIES = 3+++class EtoroConfigError(RuntimeError):+ """Raised when eToro connector configuration is missing or invalid."""+++class EtoroAPIError(RuntimeError):+ """Raised when eToro returns an auth, HTTP, network, or JSON error."""+++Transport = Callable[..., requests.Response]+++@dataclass(frozen=True)+class EtoroConfig:+ """eToro connector connection settings."""++ api_key: str = ""+ user_key: str = ""+ profile: str = "paper"+ timeout: float = 15.0+ readonly: bool = True++ @classmethod+ def from_mapping(cls, data: Mapping[str, Any] | None = None) -> "EtoroConfig":+ payload = dict(data or {})+ profile = str(payload.get("profile") or "paper").strip().lower()+ if profile not in PROFILE_ENVIRONMENTS:+ raise EtoroConfigError("profile must be 'paper', 'live-readonly' or 'live'")+ return cls(+ api_key=str(payload.get("api_key") or "").strip(),+ user_key=str(payload.get("user_key") or "").strip(),+ profile=profile,+ timeout=float(payload.get("timeout") or 15.0),+ readonly=bool(payload.get("readonly", True)),+ )++ def with_overrides(+ self,+ *,+ api_key: str | None = None,+ user_key: str | None = None,+ profile: str | None = None,+ ) -> "EtoroConfig":+ payload = asdict(self)+ if api_key is not None:+ payload["api_key"] = api_key+ if user_key is not None:+ payload["user_key"] = user_key+ if profile is not None:+ payload["profile"] = profile+ return EtoroConfig.from_mapping(payload)++ @property+ def environment(self) -> str:+ return PROFILE_ENVIRONMENTS.get(self.profile, "paper")++ @property+ def is_paper(self) -> bool:+ return self.environment == "paper"+++_OVERRIDE_KEYS = ("api_key", "user_key", "profile")+_ENV_KEY_MAP = {+ "api_key": "ETORO_API_KEY",+ "user_key": "ETORO_USER_KEY",+}+++def config_path() -> Path:+ return get_runtime_root() / CONFIG_FILENAME+++def load_config() -> EtoroConfig:+ path = config_path()+ base: dict[str, Any] = {}+ if path.exists():+ try:+ base = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError, json.JSONDecodeError) as exc:+ raise EtoroConfigError(f"invalid eToro config at {path}: {exc}") from exc+ for field, env_name in _ENV_KEY_MAP.items():+ env_val = os.getenv(env_name, "").strip() # noqa: env-gate — connector credential helper+ if env_val:+ base[field] = env_val+ return EtoroConfig.from_mapping(base)+++def save_config(config: EtoroConfig) -> Path:+ 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")+ try:+ path.chmod(0o600)+ except OSError:+ pass+ 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:+ missing.append("api_key")+ if not cfg.user_key:+ missing.append("user_key")+ return missing+++def public_config(cfg: EtoroConfig) -> dict[str, Any]:+ return {+ "profile": cfg.profile,+ "environment": cfg.environment,+ "readonly": cfg.readonly,+ "timeout": cfg.timeout,+ "api_key_configured": bool(cfg.api_key),+ "user_key_configured": bool(cfg.user_key),+ "paper_guard": PAPER_GUARD,+ }+++def execution_root(cfg: EtoroConfig) -> str:+ return "/api/v2/trading/execution/demo" if cfg.is_paper else "/api/v2/trading/execution"+++def execution_v1_root(cfg: EtoroConfig) -> str:+ return "/api/v1/trading/execution/demo" if cfg.is_paper else "/api/v1/trading/execution"+++def info_root(cfg: EtoroConfig) -> str:+ return "/api/v1/trading/info/demo" if cfg.is_paper else "/api/v1/trading/info"+++def positions_root(cfg: EtoroConfig) -> str:+ return "/api/v2/trading/demo" if cfg.is_paper else "/api/v2/trading"+++def copy_root(cfg: EtoroConfig) -> str:+ return "/api/v2/trading/copy/demo" if cfg.is_paper else "/api/v2/trading/copy"+++class EtoroClient:+ """Thin REST client for eToro Public API."""++ def __init__(self, cfg: EtoroConfig, transport: Transport | None = None):+ self.cfg = cfg+ self._transport = transport or requests.request++ def request(+ self,+ method: str,+ path: str,+ *,+ params: Mapping[str, Any] | None = None,+ json_body: Mapping[str, Any] | None = None,+ request_id: str | None = None,+ allow_retry: bool = False,+ ) -> Any:+ missing = _missing_fields(self.cfg)+ if missing:+ raise EtoroConfigError(f"missing {', '.join(missing)}")++ req_id = (request_id or str(uuid.uuid4())).strip()+ url = urljoin(BASE_URL + "/", path.lstrip("/"))+ headers = {+ "x-api-key": self.cfg.api_key,+ "x-user-key": self.cfg.user_key,+ "x-request-id": req_id,+ "Accept": "application/json",+ }+ if json_body is not None:+ headers["Content-Type"] = "application/json"++ attempts = MAX_READ_RETRIES if allow_retry else 1+ backoff = READ_BACKOFF+ last_exc: Exception | None = None++ for attempt in range(attempts):+ try:+ response = self._transport(+ method.upper(),+ url,+ headers=headers,+ params=dict(params or {}),+ json=json_body,+ timeout=self.cfg.timeout,+ )+ except requests.RequestException as exc:+ last_exc = exc+ if allow_retry and attempt + 1 < attempts:+ time.sleep(backoff[min(attempt, len(backoff) - 1)])+ continue+ raise EtoroAPIError(f"network error: {exc}") from exc++ if response.status_code == 429 and allow_retry and attempt + 1 < attempts:+ retry_after = response.headers.get("Retry-After")+ delay = float(retry_after) if retry_after else backoff[min(attempt, len(backoff) - 1)]+ time.sleep(delay)+ continue++ if response.status_code >= 400:+ detail = _response_error_body(response)+ raise EtoroAPIError(f"HTTP {response.status_code}: {detail}")++ if not response.content:+ return {}+ try:+ return response.json()+ except ValueError as exc:+ raise EtoroAPIError(f"invalid JSON response: {exc}") from exc++ if last_exc is not None:+ raise EtoroAPIError(f"network error: {last_exc}")+ raise EtoroAPIError("request failed without response")+++_default_client_factory: Callable[[EtoroConfig], EtoroClient] = lambda cfg: EtoroClient(cfg)+++def make_client(cfg: EtoroConfig) -> EtoroClient:+ """Build the REST client for a config (tests may override via ``set_client_factory``)."""+ return _default_client_factory(cfg)+++def set_client_factory(+ factory: Callable[[EtoroConfig], EtoroClient] | None = None,+) -> None:+ """Override or reset the connector client factory (used by unit tests)."""+ global _default_client_factory+ _default_client_factory = factory or (lambda cfg: EtoroClient(cfg))+++def _response_error_body(response: requests.Response) -> str:+ try:+ payload = response.json()+ except ValueError:+ return (response.text or "").strip()[:500]+ if isinstance(payload, dict):+ for key in ("errorMessage", "message", "detail", "error"):+ value = payload.get(key)+ if isinstance(value, str) and value.strip():+ return value.strip()+ return json.dumps(payload)[:500]diff --git a/agent/src/trading/connectors/etoro/copy_trading.py b/agent/src/trading/connectors/etoro/copy_trading.pynew file mode 100644index 000000000..5b983a107--- /dev/null+++ b/agent/src/trading/connectors/etoro/copy_trading.py@@ -0,0 +1,189 @@+"""eToro copy-trading workflows."""++from __future__ import annotations++import time+import uuid+from typing import Any++from src.trading.connectors.etoro.client import EtoroAPIError, EtoroConfig, copy_root, make_client+++def _base(cfg: EtoroConfig) -> dict[str, Any]:+ return {+ "profile": cfg.profile,+ "environment": cfg.environment,+ "paper_guard": "path_separated_key_bound",+ }+++def _error(cfg: EtoroConfig, message: str, **extra: Any) -> dict[str, Any]:+ return {"status": "error", "error": message, **_base(cfg), **extra}+++def copy_precheck(+ config: EtoroConfig | None = None,+ *,+ parent_cid: int,+ amount_usd: float,+ request_id: str | None = None,+) -> dict[str, Any]:+ from src.trading.connectors.etoro.client import load_config++ cfg = config or load_config()+ if amount_usd <= 0:+ return _error(cfg, "amount_usd must be positive")++ body = {"parentCID": int(parent_cid), "amount": float(amount_usd)}+ req_id = (request_id or str(uuid.uuid4())).strip()+ path = f"{copy_root(cfg)}/eligibility"+ try:+ payload = make_client(cfg).request("POST", path, json_body=body, request_id=req_id)+ except EtoroAPIError as exc:+ return _error(cfg, str(exc), request_id=req_id)++ return {"status": "ok", **_base(cfg), "request_id": req_id, "result": payload}+++def copy_start_or_adjust(+ config: EtoroConfig | None = None,+ *,+ parent_cid: int,+ amount_usd: float,+ request_id: str | None = None,+) -> dict[str, Any]:+ from src.trading.connectors.etoro.client import load_config++ cfg = config or load_config()+ if amount_usd == 0:+ return _error(cfg, "amount_usd must be non-zero")++ body = {"parentCID": int(parent_cid), "amount": float(amount_usd)}+ req_id = (request_id or str(uuid.uuid4())).strip()+ path = copy_root(cfg)+ try:+ payload = make_client(cfg).request("POST", path, json_body=body, request_id=req_id)+ except EtoroAPIError as exc:+ return _error(cfg, str(exc), request_id=req_id)++ reference_id = _extract_reference_id(payload)+ return {+ "status": "ok",+ **_base(cfg),+ "parent_cid": int(parent_cid),+ "amount_usd": float(amount_usd),+ "request_id": req_id,+ "reference_id": reference_id,+ "raw": payload,+ }+++def copy_poll(+ config: EtoroConfig | None = None,+ *,+ reference_id: str,+ request_id: str | None = None,+) -> dict[str, Any]:+ from src.trading.connectors.etoro.client import load_config++ cfg = config or load_config()+ ref = str(reference_id or "").strip()+ if not ref:+ return _error(cfg, "reference_id is required")++ req_id = (request_id or str(uuid.uuid4())).strip()+ path = f"{copy_root(cfg)}/{ref}"+ try:+ payload = make_client(cfg).request("GET", path, request_id=req_id, allow_retry=True)+ except EtoroAPIError as exc:+ return _error(cfg, str(exc), reference_id=ref, request_id=req_id)++ return {"status": "ok", **_base(cfg), "reference_id": ref, "request_id": req_id, "result": payload}+++def copy_close(+ config: EtoroConfig | None = None,+ *,+ mirror_id: int,+ unregister_type: str = "Close",+ request_id: str | None = None,+) -> dict[str, Any]:+ from src.trading.connectors.etoro.client import load_config++ cfg = config or load_config()+ action = str(unregister_type or "Close").strip()+ if action not in ("Close", "Detach"):+ return _error(cfg, "unregister_type must be 'Close' or 'Detach'")++ req_id = (request_id or str(uuid.uuid4())).strip()+ path = f"{copy_root(cfg)}/close"+ body = {"mirrorID": int(mirror_id), "unregisterType": action}+ try:+ payload = make_client(cfg).request("POST", path, json_body=body, request_id=req_id)+ except EtoroAPIError as exc:+ return _error(cfg, str(exc), mirror_id=mirror_id, request_id=req_id)++ reference_id = _extract_reference_id(payload)+ return {+ "status": "ok",+ **_base(cfg),+ "mirror_id": int(mirror_id),+ "unregister_type": action,+ "request_id": req_id,+ "reference_id": reference_id,+ "raw": payload,+ }+++def copy_poll_until_complete(+ config: EtoroConfig | None = None,+ *,+ reference_id: str,+ timeout_s: float = 30.0,+ interval_s: float = 1.0,+) -> dict[str, Any]:+ from src.trading.connectors.etoro.client import load_config++ cfg = config or load_config()+ deadline = time.monotonic() + max(1.0, float(timeout_s))+ last: dict[str, Any] = {}+ while time.monotonic() < deadline:+ last = copy_poll(cfg, reference_id=reference_id)+ if last.get("status") != "ok":+ return last+ result = last.get("result")+ if isinstance(result, dict) and _is_copy_complete(result):+ last["completed"] = True+ return last+ time.sleep(max(0.2, float(interval_s)))+ last["completed"] = False+ last["status"] = "error"+ last["error"] = "copy operation polling timed out"+ return last+++def _extract_reference_id(payload: Any) -> str | None:+ if not isinstance(payload, dict):+ return None+ for key in ("referenceID", "referenceId", "reference_id"):+ value = payload.get(key)+ if value is not None:+ return str(value)+ data = payload.get("data")+ if isinstance(data, dict):+ for key in ("referenceID", "referenceId", "reference_id"):+ value = data.get(key)+ if value is not None:+ return str(value)+ return None+++def _is_copy_complete(payload: dict[str, Any]) -> bool:+ for key in ("isCompleted", "isSuccess", "completed"):+ value = payload.get(key)+ if isinstance(value, bool):+ return value+ status = payload.get("status")+ if isinstance(status, str):+ return status.lower() in ("completed", "success", "done")+ return Falsediff --git a/agent/src/trading/connectors/etoro/instruments.py b/agent/src/trading/connectors/etoro/instruments.pynew file mode 100644index 000000000..e04a7edf8--- /dev/null+++ b/agent/src/trading/connectors/etoro/instruments.py@@ -0,0 +1,68 @@+"""Instrument search and symbol resolution for eToro."""++from __future__ import annotations++from typing import Any++from src.trading.connectors.etoro.client import EtoroAPIError, EtoroConfig, make_client+++def _base_payload(cfg: EtoroConfig) -> dict[str, Any]:+ return {+ "profile": cfg.profile,+ "environment": cfg.environment,+ "paper_guard": "path_separated_key_bound",+ }+++def search_instruments(+ query: str,+ config: EtoroConfig | None = None,+ *,+ limit: int = 10,+) -> dict[str, Any]:+ from src.trading.connectors.etoro.client import load_config++ cfg = config or load_config()+ payload = make_client(cfg).request(+ "GET",+ "/api/v1/market-data/search",+ params={"search": query, "limit": max(1, min(limit, 50))},+ allow_retry=True,+ )+ return {"status": "ok", **_base_payload(cfg), "instruments": _extract_items(payload)}+++def resolve_instrument_id(symbol: str, cfg: EtoroConfig) -> int:+ token = str(symbol or "").strip()+ if token.isdigit():+ return int(token)+ result = search_instruments(token, cfg, limit=5)+ items = result.get("instruments") or []+ if not items:+ raise EtoroAPIError(f"instrument not found for symbol {token!r}")+ for item in items:+ if not isinstance(item, dict):+ continue+ display = str(item.get("displayName") or item.get("symbolFull") or item.get("symbol") or "").upper()+ if display == token.upper() or token.upper() in display:+ instrument_id = item.get("instrumentId") or item.get("instrumentID")+ if instrument_id is not None:+ return int(instrument_id)+ first = items[0]+ if isinstance(first, dict):+ instrument_id = first.get("instrumentId") or first.get("instrumentID")+ if instrument_id is not None:+ return int(instrument_id)+ raise EtoroAPIError(f"could not resolve instrument id for {token!r}")+++def _extract_items(payload: Any) -> list[Any]:+ if isinstance(payload, list):+ return payload+ if isinstance(payload, dict):+ for key in ("items", "data", "instruments", "results"):+ value = payload.get(key)+ if isinstance(value, list):+ return value+ return []diff --git a/agent/src/trading/connectors/etoro/profiles.py b/agent/src/trading/connectors/etoro/profiles.pynew file mode 100644index 000000000..1043cd036--- /dev/null+++ b/agent/src/trading/connectors/etoro/profiles.py@@ -0,0 +1,67 @@+"""Built-in eToro connector profiles."""++from __future__ import annotations++from src.trading.types import READ_CAPABILITIES, TradingProfile++ETORO_EXTENDED_CAPABILITIES = READ_CAPABILITIES + (+ "orders.place",+ "positions.close",+ "orders.cancel_close",+ "positions.edit",+ "copy.precheck",+ "copy.start",+ "copy.adjust",+ "copy.poll",+ "copy.close",+)++ETORO_PROFILES: tuple[TradingProfile, ...] = (+ TradingProfile(+ id="etoro-paper-sdk",+ connector="etoro",+ label="eToro Demo · Public API Read-Only",+ environment="paper",+ transport="broker_sdk",+ capabilities=READ_CAPABILITIES,+ readonly=True,+ config={"profile": "paper"},+ notes="Reads a demo account via eToro Public API. Demo keys only reach demo paths.",+ ),+ TradingProfile(+ id="etoro-live-sdk-readonly",+ connector="etoro",+ label="eToro Real · Public API Read-Only",+ environment="live",+ transport="broker_sdk",+ capabilities=READ_CAPABILITIES,+ readonly=True,+ config={"profile": "live-readonly"},+ notes="Reads a real account only. Order placement is not exposed in this profile.",+ ),+ TradingProfile(+ id="etoro-paper-trade",+ connector="etoro",+ label="eToro Demo · Public API Trade",+ environment="paper",+ transport="broker_sdk",+ capabilities=ETORO_EXTENDED_CAPABILITIES,+ readonly=False,+ config={"profile": "paper"},+ notes="Full demo trading and copy workflows via eToro Public API demo paths.",+ ),+ TradingProfile(+ id="etoro-live-trade",+ connector="etoro",+ label="eToro Real · Public API Trade",+ environment="live",+ transport="broker_sdk",+ capabilities=tuple(+ cap if cap != "orders.place" else "orders.place.requires_mandate"+ for cap in ETORO_EXTENDED_CAPABILITIES+ ),+ readonly=False,+ config={"profile": "live"},+ notes="Real trading and copy workflows. Risk-increasing actions require an authorized mandate.",+ ),+)diff --git a/agent/src/trading/connectors/etoro/sdk.py b/agent/src/trading/connectors/etoro/sdk.pynew file mode 100644index 000000000..eda323fc8--- /dev/null+++ b/agent/src/trading/connectors/etoro/sdk.py@@ -0,0 +1,337 @@+"""Read adapters and generic broker_sdk entry points for eToro."""++from __future__ import annotations++from typing import Any++from src.trading.connectors.etoro.client import (+ BASE_URL,+ EtoroAPIError,+ EtoroConfig,+ EtoroConfigError,+ PAPER_GUARD,+ build_config,+ info_root,+ load_config,+ make_client,+ public_config,+ save_config,+)+from src.trading.connectors.etoro.copy_trading import (+ copy_close,+ copy_poll,+ copy_precheck,+ copy_start_or_adjust,+)+from src.trading.connectors.etoro.instruments import resolve_instrument_id, search_instruments+from src.trading.connectors.etoro.trading import (+ cancel_close_order,+ cancel_order as cancel_open_order,+ close_position,+ edit_position_stops,+ place_order as place_open_order,+)++__all__ = [+ "build_config",+ "load_config",+ "save_config",+ "check_status",+ "get_account_snapshot",+ "get_positions",+ "get_open_orders",+ "get_quote",+ "get_historical_bars",+ "place_order",+ "cancel_order",+ "close_position",+ "cancel_close_order",+ "edit_position_stops",+ "copy_precheck",+ "copy_start_or_adjust",+ "copy_poll",+ "copy_close",+ "search_instruments",+ "EtoroConfig",+ "EtoroConfigError",+ "EtoroAPIError",+]+++def _client(cfg: EtoroConfig):+ return make_client(cfg)+++def _base_payload(cfg: EtoroConfig) -> dict[str, Any]:+ return {+ "profile": cfg.profile,+ "environment": cfg.environment,+ "paper_guard": PAPER_GUARD,+ }+++def check_status(config: EtoroConfig | None = None) -> dict[str, Any]:+ from src.trading.connectors.etoro.client import _missing_fields++ cfg = config or load_config()+ report: dict[str, Any] = {+ "status": "ok",+ "config": public_config(cfg),+ "sdk": {"package": "requests", "installed": True},+ "paper_guard": PAPER_GUARD,+ "base_url": BASE_URL,+ }+ missing_fields = _missing_fields(cfg)+ if missing_fields:+ report["status"] = "error"+ report["error"] = f"eToro connector not configured: missing {', '.join(missing_fields)}."+ return report+ try:+ portfolio = get_account_snapshot(cfg)+ except (EtoroConfigError, EtoroAPIError) as exc:+ report["status"] = "error"+ report["error"] = str(exc)+ return report+ except Exception as exc: # noqa: BLE001+ report["status"] = "error"+ report["error"] = f"eToro connector check failed: {exc}"+ return report+ report["account"] = {+ "profile": cfg.profile,+ "portfolio_status": portfolio.get("status"),+ }+ return report+++def get_account_snapshot(config: EtoroConfig | None = None) -> dict[str, Any]:+ cfg = config or load_config()+ client = _client(cfg)+ portfolio = client.request("GET", f"{info_root(cfg)}/portfolio", allow_retry=True)+ pnl = client.request("GET", f"{info_root(cfg)}/pnl", allow_retry=True)+ return {+ "status": "ok",+ **_base_payload(cfg),+ "account": {"portfolio": portfolio, "pnl": pnl},+ }+++def get_positions(config: EtoroConfig | None = None) -> dict[str, Any]:+ cfg = config or load_config()+ payload = _client(cfg).request("GET", f"{info_root(cfg)}/portfolio", allow_retry=True)+ positions = _extract_positions(payload)+ return {"status": "ok", **_base_payload(cfg), "positions": positions}+++def get_open_orders(config: EtoroConfig | None = None, *, include_executions: bool = False) -> dict[str, Any]:+ cfg = config or load_config()+ client = _client(cfg)+ orders_payload = client.request("GET", f"{info_root(cfg)}/pendingOrders", allow_retry=True)+ orders = _extract_orders(orders_payload)+ result: dict[str, Any] = {"status": "ok", **_base_payload(cfg), "orders": orders}+ if include_executions:+ try:+ history = client.request("GET", f"{info_root(cfg)}/history", allow_retry=True)+ result["history"] = history+ except EtoroAPIError as exc:+ result["history_error"] = str(exc)+ return result+++def get_quote(symbol: str, *, config: EtoroConfig | None = None, **_: Any) -> dict[str, Any]:+ cfg = config or load_config()+ instrument_id = resolve_instrument_id(symbol, cfg)+ payload = _client(cfg).request(+ "GET",+ "/api/v1/market-data/instruments/rates",+ params={"instrumentIds": instrument_id},+ allow_retry=True,+ )+ quote = _first_rate(payload, instrument_id)+ return {+ "status": "ok",+ **_base_payload(cfg),+ "symbol": symbol,+ "instrument_id": instrument_id,+ "quote": quote,+ }+++def get_historical_bars(+ symbol: str,+ *,+ config: EtoroConfig | None = None,+ period: str = "1d",+ limit: int = 90,+ **_: Any,+) -> dict[str, Any]:+ cfg = config or load_config()+ instrument_id = resolve_instrument_id(symbol, cfg)+ interval = _map_interval(period)+ count = max(1, min(int(limit), 1000))+ path = f"/api/v1/market-data/instruments/{instrument_id}/history/candles/desc/{interval}/{count}"+ payload = _client(cfg).request("GET", path, allow_retry=True)+ bars = _normalize_candles(payload)+ return {+ "status": "ok",+ **_base_payload(cfg),+ "symbol": symbol,+ "instrument_id": instrument_id,+ "period": period,+ "bars": bars,+ }+++def place_order(+ config: EtoroConfig | None = None,+ *,+ symbol: str,+ side: str,+ quantity: float | None = None,+ notional: float | None = None,+ order_type: str = "market",+ limit_price: float | None = None,+ time_in_force: str = "day",+ request_id: str | None = None,+) -> dict[str, Any]:+ return place_open_order(+ config,+ symbol=symbol,+ side=side,+ quantity=quantity,+ notional=notional,+ order_type=order_type,+ limit_price=limit_price,+ time_in_force=time_in_force,+ request_id=request_id,+ )+++def cancel_order(+ config: EtoroConfig | None = None,+ order_id: str = "",+ *,+ symbol: str | None = None,+ request_id: str | None = None,+) -> dict[str, Any]:+ return cancel_open_order(config, order_id, symbol=symbol, request_id=request_id)+++def _map_interval(period: str) -> str:+ token = str(period or "1d").strip().lower()+ mapping = {+ "1m": "OneMinute",+ "5m": "FiveMinutes",+ "15m": "FifteenMinutes",+ "30m": "ThirtyMinutes",+ "1h": "OneHour",+ "4h": "FourHours",+ "1d": "OneDay",+ "1w": "OneWeek",+ }+ if token in mapping:+ return mapping[token]+ raise EtoroAPIError(f"unsupported period {period!r}")+++def _extract_positions(payload: Any) -> list[dict[str, Any]]:+ if isinstance(payload, dict):+ for key in ("positions", "clientPortfolio", "portfolio", "data"):+ value = payload.get(key)+ if isinstance(value, list):+ return [_position_row(item) for item in value if isinstance(item, dict)]+ if isinstance(value, dict):+ nested = value.get("positions")+ if isinstance(nested, list):+ return [_position_row(item) for item in nested if isinstance(item, dict)]+ if isinstance(payload, list):+ return [_position_row(item) for item in payload if isinstance(item, dict)]+ return []+++def _position_row(item: dict[str, Any]) -> dict[str, Any]:+ return {+ "position_id": item.get("positionID") or item.get("positionId") or item.get("id"),+ "instrument_id": item.get("instrumentID") or item.get("instrumentId"),+ "symbol": item.get("instrumentDisplayName") or item.get("symbol") or item.get("instrumentName"),+ "units": item.get("units") or item.get("amountInUnits"),+ "open_rate": item.get("openRate") or item.get("openPrice"),+ "pnl": item.get("profit") or item.get("pnl"),+ "is_buy": item.get("isBuy"),+ "raw": item,+ }+++def _extract_orders(payload: Any) -> list[dict[str, Any]]:+ items: list[Any] = []+ if isinstance(payload, list):+ items = payload+ elif isinstance(payload, dict):+ for key in ("items", "data", "orders", "pendingOrders"):+ value = payload.get(key)+ if isinstance(value, list):+ items = value+ break+ return [+ {+ "order_id": item.get("orderID") or item.get("orderId") or item.get("id"),+ "instrument_id": item.get("instrumentID") or item.get("instrumentId"),+ "status": item.get("statusID") or item.get("status"),+ "raw": item,+ }+ for item in items+ if isinstance(item, dict)+ ]+++def _first_rate(payload: Any, instrument_id: int) -> dict[str, Any]:+ items: list[Any] = []+ if isinstance(payload, list):+ items = payload+ elif isinstance(payload, dict):+ for key in ("items", "data", "rates"):+ value = payload.get(key)+ if isinstance(value, list):+ items = value+ break+ for item in items:+ if not isinstance(item, dict):+ continue+ item_id = item.get("instrumentID") or item.get("instrumentId")+ if item_id is not None and int(item_id) == instrument_id:+ return {+ "bid": item.get("bid") or item.get("bidRate"),+ "ask": item.get("ask") or item.get("askRate"),+ "last": item.get("lastExecution") or item.get("last") or item.get("rate"),+ }+ if isinstance(payload, dict):+ return {+ "bid": payload.get("bid"),+ "ask": payload.get("ask"),+ "last": payload.get("lastExecution") or payload.get("last"),+ }+ return {}+++def _normalize_candles(payload: Any) -> list[dict[str, Any]]:+ candles: list[Any] = []+ if isinstance(payload, dict):+ raw = payload.get("candles") or payload.get("data")+ if isinstance(raw, list):+ 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"),+ }+ )+ return rowsdiff --git a/agent/src/trading/connectors/etoro/trading.py b/agent/src/trading/connectors/etoro/trading.pynew file mode 100644index 000000000..7886926e9--- /dev/null+++ b/agent/src/trading/connectors/etoro/trading.py@@ -0,0 +1,250 @@+"""eToro trading write operations (open, close, cancel, edit)."""++from __future__ import annotations++import uuid+from decimal import Decimal, InvalidOperation+from typing import Any++from src.trading.connectors.etoro.client import (+ EtoroAPIError,+ EtoroConfig,+ execution_root,+ execution_v1_root,+ make_client,+ positions_root,+)+from src.trading.connectors.etoro.instruments import resolve_instrument_id+++def _base(cfg: EtoroConfig) -> dict[str, Any]:+ return {+ "profile": cfg.profile,+ "environment": cfg.environment,+ "paper_guard": "path_separated_key_bound",+ }+++def _order_error(cfg: EtoroConfig, message: str, **extra: Any) -> dict[str, Any]:+ return {"status": "error", "error": message, **_base(cfg), **extra}+++def place_order(+ config: EtoroConfig | None = None,+ *,+ symbol: str,+ side: str,+ quantity: float | None = None,+ notional: float | None = None,+ order_type: str = "market",+ limit_price: float | None = None,+ time_in_force: str = "day",+ request_id: str | None = None,+) -> dict[str, Any]:+ from src.trading.connectors.etoro.client import load_config++ cfg = config or load_config()+ clean_side = str(side or "").strip().lower()+ if clean_side not in ("buy", "sell"):+ return _order_error(cfg, "side must be 'buy' or 'sell'", symbol=symbol)++ has_qty = quantity is not None+ has_notional = notional is not None+ if has_qty == has_notional:+ return _order_error(cfg, "exactly one of quantity or notional is required", symbol=symbol, side=clean_side)++ clean_type = str(order_type or "market").strip().lower()+ if clean_type not in ("market", "limit"):+ return _order_error(cfg, "order_type must be 'market' or 'limit'", symbol=symbol, side=clean_side)++ try:+ instrument_id = resolve_instrument_id(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,+ "orderType": "mkt" if clean_type == "market" else "mit",+ "orderCurrency": "usd",+ "leverage": 1,+ "stopLossType": "fixed",+ }+ if has_notional:+ body["amount"] = float(notional)+ else:+ body["units"] = float(quantity)+ if clean_type == "limit" and limit_price is not None:+ body["rate"] = float(limit_price)++ req_id = (request_id or str(uuid.uuid4())).strip()+ path = f"{execution_root(cfg)}/orders"+ try:+ payload = make_client(cfg).request("POST", path, json_body=body, request_id=req_id)+ except EtoroAPIError as exc:+ return _order_error(cfg, str(exc), symbol=symbol, side=clean_side, request_id=req_id)++ order_id = _extract_order_id(payload)+ return {+ "status": "ok",+ **_base(cfg),+ "symbol": symbol,+ "instrument_id": instrument_id,+ "side": clean_side,+ "order_type": clean_type,+ "time_in_force": time_in_force,+ "order_id": order_id,+ "request_id": req_id,+ "raw": payload,+ }+++def cancel_order(+ config: EtoroConfig | None = None,+ order_id: str = "",+ *,+ symbol: str | None = None,+ request_id: str | None = None,+) -> dict[str, Any]:+ from src.trading.connectors.etoro.client import load_config++ cfg = config or load_config()+ clean_id = str(order_id or "").strip()+ if not clean_id:+ return _order_error(cfg, "order_id is required", symbol=symbol)++ req_id = (request_id or str(uuid.uuid4())).strip()+ path = f"{execution_root(cfg)}/orders/{clean_id}"+ try:+ payload = make_client(cfg).request("DELETE", path, request_id=req_id)+ except EtoroAPIError as exc:+ return _order_error(cfg, str(exc), order_id=clean_id, symbol=symbol, request_id=req_id)++ return {+ "status": "ok",+ **_base(cfg),+ "order_id": clean_id,+ "symbol": symbol,+ "request_id": req_id,+ "raw": payload,+ }+++def close_position(+ config: EtoroConfig | None = None,+ *,+ position_id: int | str,+ instrument_id: int | None = None,+ units_to_close: float | None = None,+ request_id: str | None = None,+) -> dict[str, Any]:+ from src.trading.connectors.etoro.client import load_config++ cfg = config or load_config()+ pos_id = str(position_id).strip()+ if not pos_id:+ return _order_error(cfg, "position_id is required")++ body: dict[str, Any] = {}+ if instrument_id is not None:+ body["InstrumentID"] = int(instrument_id)+ if units_to_close is not None:+ body["UnitsToDeduct"] = float(units_to_close)++ req_id = (request_id or str(uuid.uuid4())).strip()+ path = f"{execution_v1_root(cfg)}/market-close-orders/positions/{pos_id}"+ try:+ payload = make_client(cfg).request("POST", path, json_body=body or None, request_id=req_id)+ except EtoroAPIError as exc:+ return _order_error(cfg, str(exc), position_id=pos_id, request_id=req_id)++ return {+ "status": "ok",+ **_base(cfg),+ "position_id": pos_id,+ "units_to_close": units_to_close,+ "request_id": req_id,+ "order_id": _extract_order_id(payload),+ "raw": payload,+ }+++def cancel_close_order(+ config: EtoroConfig | None = None,+ order_id: str = "",+ *,+ request_id: str | None = None,+) -> dict[str, Any]:+ from src.trading.connectors.etoro.client import load_config++ cfg = config or load_config()+ clean_id = str(order_id or "").strip()+ if not clean_id:+ return _order_error(cfg, "order_id is required")++ req_id = (request_id or str(uuid.uuid4())).strip()+ path = f"{execution_v1_root(cfg)}/market-close-orders/{clean_id}"+ try:+ payload = make_client(cfg).request("DELETE", path, request_id=req_id)+ except EtoroAPIError as exc:+ return _order_error(cfg, str(exc), order_id=clean_id, request_id=req_id)++ return {"status": "ok", **_base(cfg), "order_id": clean_id, "request_id": req_id, "raw": payload}+++def edit_position_stops(+ config: EtoroConfig | None = None,+ *,+ position_id: int | str,+ stop_loss: float | None = None,+ take_profit: float | None = None,+ trailing_stop_loss: bool | None = None,+ request_id: str | None = None,+) -> dict[str, Any]:+ from src.trading.connectors.etoro.client import load_config++ cfg = config or load_config()+ pos_id = str(position_id).strip()+ if not pos_id:+ return _order_error(cfg, "position_id is required")+ if stop_loss is None and take_profit is None and trailing_stop_loss is None:+ return _order_error(cfg, "at least one of stop_loss, take_profit, trailing_stop_loss is required")++ body: dict[str, Any] = {}+ if stop_loss is not None:+ body["stopLossRate"] = float(stop_loss)+ if take_profit is not None:+ body["takeProfitRate"] = float(take_profit)+ if trailing_stop_loss is not None:+ body["isTslEnabled"] = bool(trailing_stop_loss)++ req_id = (request_id or str(uuid.uuid4())).strip()+ path = f"{positions_root(cfg)}/positions/{pos_id}"+ try:+ payload = make_client(cfg).request("PATCH", path, json_body=body, request_id=req_id)+ except EtoroAPIError as exc:+ return _order_error(cfg, str(exc), position_id=pos_id, request_id=req_id)++ return {"status": "ok", **_base(cfg), "position_id": pos_id, "request_id": req_id, "raw": payload}+++def _extract_order_id(payload: Any) -> str | None:+ if not isinstance(payload, dict):+ return None+ for key in ("orderID", "orderId", "order_id", "id"):+ value = payload.get(key)+ if value is not None:+ return str(value)+ data = payload.get("data")+ if isinstance(data, dict):+ for key in ("orderID", "orderId", "order_id", "id"):+ value = data.get(key)+ if value is not None:+ return str(value)+ order_for_close = payload.get("orderForClose")+ if isinstance(order_for_close, dict):+ value = order_for_close.get("orderID") or order_for_close.get("orderId")+ if value is not None:+ return str(value)+ return Nonediff --git a/agent/src/trading/profiles.py b/agent/src/trading/profiles.pyindex 10a3faf19..5cc5cd3db 100644--- a/agent/src/trading/profiles.py+++ b/agent/src/trading/profiles.py@@ -17,6 +17,7 @@ from src.trading.connectors.okx.profiles import OKX_PROFILESfrom src.trading.connectors.robinhood.profiles import ROBINHOOD_PROFILESfrom src.trading.connectors.shoonya.profiles import SHOONYA_PROFILESfrom src.trading.connectors.tiger.profiles import TIGER_PROFILES+from src.trading.connectors.etoro.profiles import ETORO_PROFILESfrom src.trading.connectors.trading212.profiles import TRADING212_PROFILESfrom src.trading.types import TradingProfile@@ -36,6 +37,7 @@ BUILTIN_PROFILES: tuple[TradingProfile, ...] = (*SHOONYA_PROFILES,*TRADING212_PROFILES,*MT5_PROFILES,+ *ETORO_PROFILES,)diff --git a/agent/src/trading/service.py b/agent/src/trading/service.pyindex 634999e57..bf6ae7f98 100644--- a/agent/src/trading/service.py+++ b/agent/src/trading/service.py@@ -24,6 +24,7 @@ _SDK_CONNECTOR_MODULES = {"shoonya": "src.trading.connectors.shoonya.sdk","trading212": "src.trading.connectors.trading212.sdk","mt5": "src.trading.connectors.mt5.sdk",+ "etoro": "src.trading.connectors.etoro.sdk",}@@ -212,6 +213,7 @@ _CONNECTOR_INSTRUMENT = {"longbridge": ("equity", None),"futu": ("equity", None),"trading212": ("equity", None),+ "etoro": ("equity", None),}@@ -343,6 +345,285 @@ def cancel_order(return _with_profile(profile, result)+def _unsupported_etoro(profile: TradingProfile, capability: str) -> dict[str, Any]:+ return _unsupported(profile, capability)+++def _route_sdk_write(+ profile: TradingProfile,+ *,+ remote_tool: str,+ risk_reducing: bool,+ intent: Any | None,+ audit_request: dict[str, Any],+ execute: Any,+ overrides: dict[str, Any],+ unsupported_capability: str,+) -> dict[str, Any]:+ if profile.transport != "broker_sdk":+ return _unsupported(profile, unsupported_capability)+ if profile.readonly:+ return _unsupported(profile, unsupported_capability)+ module = _sdk_module(profile.connector)+ config = module.build_config(profile.config, overrides)+ if profile.environment == "paper":+ return _with_profile(profile, execute(config))+ from src.live.sdk_order_gate import execute_live_action++ return _with_profile(+ profile,+ execute_live_action(+ broker=profile.connector,+ connector_module=module,+ config=config,+ remote_tool=remote_tool,+ risk_reducing=risk_reducing,+ intent=intent,+ execute_fn=lambda: execute(config),+ audit_request=audit_request,+ session_id=str(overrides.get("session_id") or ""),+ ),+ )+++def close_position(+ position_id: str | int,+ profile_id: str | None = None,+ *,+ instrument_id: int | None = None,+ units_to_close: float | None = None,+ request_id: str | None = None,+ session_id: str = "",+ **overrides: Any,+) -> dict[str, Any]:+ """Close or partially close a position (eToro connector)."""+ profile = profile_by_id(profile_id)+ if profile.connector != "etoro":+ return _unsupported_etoro(profile, "positions.close")+ overrides = dict(overrides)+ overrides.pop("session_id", None)+ module = _sdk_module(profile.connector)+ audit = {+ "position_id": str(position_id),+ "instrument_id": instrument_id,+ "units_to_close": units_to_close,+ "request_id": request_id,+ }+ full_close = units_to_close is None+ return _route_sdk_write(+ profile,+ remote_tool="close_position",+ risk_reducing=full_close,+ intent=None,+ audit_request=audit,+ execute=lambda cfg: module.close_position(+ cfg,+ position_id=position_id,+ instrument_id=instrument_id,+ units_to_close=units_to_close,+ request_id=request_id,+ ),+ overrides={**overrides, "session_id": session_id},+ unsupported_capability="positions.close",+ )+++def cancel_close_order(+ order_id: str,+ profile_id: str | None = None,+ *,+ request_id: str | None = None,+ session_id: str = "",+ **overrides: Any,+) -> dict[str, Any]:+ """Cancel a pending market close order (eToro connector)."""+ profile = profile_by_id(profile_id)+ if profile.connector != "etoro":+ return _unsupported_etoro(profile, "orders.cancel_close")+ overrides = dict(overrides)+ overrides.pop("session_id", None)+ module = _sdk_module(profile.connector)+ audit = {"order_id": order_id, "request_id": request_id}+ return _route_sdk_write(+ profile,+ remote_tool="cancel_close_order",+ risk_reducing=True,+ intent=None,+ audit_request=audit,+ execute=lambda cfg: module.cancel_close_order(cfg, order_id, request_id=request_id),+ overrides={**overrides, "session_id": session_id},+ unsupported_capability="orders.cancel_close",+ )+++def edit_position_stops(+ position_id: str | int,+ profile_id: str | None = None,+ *,+ stop_loss: float | None = None,+ take_profit: float | None = None,+ trailing_stop_loss: bool | None = None,+ request_id: str | None = None,+ session_id: str = "",+ **overrides: Any,+) -> dict[str, Any]:+ """Modify SL/TP on an open position (eToro connector)."""+ profile = profile_by_id(profile_id)+ if profile.connector != "etoro":+ return _unsupported_etoro(profile, "positions.edit")+ overrides = dict(overrides)+ overrides.pop("session_id", None)+ module = _sdk_module(profile.connector)+ audit = {+ "position_id": str(position_id),+ "stop_loss": stop_loss,+ "take_profit": take_profit,+ "trailing_stop_loss": trailing_stop_loss,+ "request_id": request_id,+ }+ from src.live.enforcement import OrderIntent++ intent = OrderIntent(+ symbol=str(position_id),+ side="sell",+ notional_usd=0.0,+ quantity=None,+ instrument_type=_order_classification(profile.connector, str(position_id))[0],+ asset_class=_order_classification(profile.connector, str(position_id))[1],+ )+ return _route_sdk_write(+ profile,+ remote_tool="edit_position_stops",+ risk_reducing=False,+ intent=intent,+ audit_request=audit,+ execute=lambda cfg: module.edit_position_stops(+ cfg,+ position_id=position_id,+ stop_loss=stop_loss,+ take_profit=take_profit,+ trailing_stop_loss=trailing_stop_loss,+ request_id=request_id,+ ),+ overrides={**overrides, "session_id": session_id},+ unsupported_capability="positions.edit",+ )+++def etoro_copy_precheck(+ parent_cid: int,+ amount_usd: float,+ profile_id: str | None = None,+ *,+ request_id: str | None = None,+ **overrides: Any,+) -> dict[str, Any]:+ profile = profile_by_id(profile_id)+ if profile.connector != "etoro":+ return _unsupported_etoro(profile, "copy.precheck")+ module = _sdk_module(profile.connector)+ config = module.build_config(profile.config, overrides)+ return _with_profile(+ profile,+ module.copy_precheck(config, parent_cid=parent_cid, amount_usd=amount_usd, request_id=request_id),+ )+++def etoro_copy_start(+ parent_cid: int,+ amount_usd: float,+ profile_id: str | None = None,+ *,+ request_id: str | None = None,+ session_id: str = "",+ **overrides: Any,+) -> dict[str, Any]:+ profile = profile_by_id(profile_id)+ if profile.connector != "etoro":+ return _unsupported_etoro(profile, "copy.start")+ overrides = dict(overrides)+ overrides.pop("session_id", None)+ module = _sdk_module(profile.connector)+ audit = {"parent_cid": parent_cid, "amount_usd": amount_usd, "request_id": request_id}+ from src.live.enforcement import OrderIntent++ risk_reducing = float(amount_usd) < 0+ intent = None+ if not risk_reducing:+ instrument_type, asset_class = _order_classification(profile.connector, str(parent_cid))+ intent = OrderIntent(+ symbol=f"COPY:{parent_cid}",+ side="buy",+ notional_usd=abs(float(amount_usd)),+ quantity=None,+ instrument_type=instrument_type,+ asset_class=asset_class,+ )+ return _route_sdk_write(+ profile,+ remote_tool="copy_start_or_adjust",+ risk_reducing=risk_reducing,+ intent=intent,+ audit_request=audit,+ execute=lambda cfg: module.copy_start_or_adjust(+ cfg,+ parent_cid=parent_cid,+ amount_usd=amount_usd,+ request_id=request_id,+ ),+ overrides={**overrides, "session_id": session_id},+ unsupported_capability="copy.start",+ )+++def etoro_copy_poll(+ reference_id: str,+ profile_id: str | None = None,+ *,+ request_id: str | None = None,+ **overrides: Any,+) -> dict[str, Any]:+ profile = profile_by_id(profile_id)+ if profile.connector != "etoro":+ return _unsupported_etoro(profile, "copy.poll")+ module = _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))+++def etoro_copy_close(+ mirror_id: int,+ profile_id: str | None = None,+ *,+ unregister_type: str = "Close",+ request_id: str | None = None,+ session_id: str = "",+ **overrides: Any,+) -> dict[str, Any]:+ profile = profile_by_id(profile_id)+ if profile.connector != "etoro":+ return _unsupported_etoro(profile, "copy.close")+ overrides = dict(overrides)+ overrides.pop("session_id", None)+ module = _sdk_module(profile.connector)+ audit = {"mirror_id": mirror_id, "unregister_type": unregister_type, "request_id": request_id}+ return _route_sdk_write(+ profile,+ remote_tool="copy_close",+ risk_reducing=True,+ intent=None,+ audit_request=audit,+ execute=lambda cfg: module.copy_close(+ cfg,+ mirror_id=mirror_id,+ unregister_type=unregister_type,+ request_id=request_id,+ ),+ overrides={**overrides, "session_id": session_id},+ unsupported_capability="copy.close",+ )++def _audit_live_cancel(profile, order_id, symbol, result, session_id) -> None:"""Write a live-action audit record for a live order cancellation (best-effort)."""try:diff --git a/agent/tests/test_etoro_connector.py b/agent/tests/test_etoro_connector.pynew file mode 100644index 000000000..3b5acd279--- /dev/null+++ b/agent/tests/test_etoro_connector.py@@ -0,0 +1,158 @@+"""Tests for the eToro Public API connector."""++from __future__ import annotations++import json+from typing import Any++import pytest++from src.live import registry+from src.live.classification import ToolClass, classify_tool+from src.trading import profiles, service+from src.trading.connectors.etoro import sdk as etoro_sdk+from src.trading.connectors.etoro.client import (+ EtoroClient,+ EtoroConfig,+ execution_root,+ execution_v1_root,+ info_root,+ copy_root,+ positions_root,+ set_client_factory,+)+from src.trading.connectors.etoro.classification import ETORO_TOOL_CLASS++pytestmark = pytest.mark.unit++[email protected](autouse=True)+def _reset_etoro_client_factory() -> None:+ yield+ set_client_factory(None)+++class _FakeResponse:+ def __init__(self, status_code: int, payload: Any = None, headers: dict[str, str] | None = None):+ self.status_code = status_code+ self._payload = payload+ self.headers = headers or {}+ self.content = b"{}" if payload is not None else b""++ def json(self) -> Any:+ return self._payload+++def _transport_factory(responses: dict[tuple[str, str], _FakeResponse]):+ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:+ key = (method.upper(), url.split("public-api.etoro.com", 1)[-1])+ if key not in responses:+ raise AssertionError(f"unexpected request {key}")+ return responses[key]++ return _transport+++def test_etoro_profiles_registered() -> None:+ ids = {profile.id for profile in profiles.list_profiles()}+ assert {+ "etoro-paper-sdk",+ "etoro-paper-trade",+ "etoro-live-sdk-readonly",+ "etoro-live-trade",+ } <= ids++ paper = profiles.profile_by_id("etoro-paper-trade")+ live = profiles.profile_by_id("etoro-live-trade")+ assert paper.connector == "etoro"+ assert live.connector == "etoro"+ assert paper.environment == "paper"+ assert live.environment == "live"+ assert "orders.place" in paper.capabilities+ assert "orders.place.requires_mandate" in live.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")+ assert execution_root(paper) == "/api/v2/trading/execution/demo"+ assert execution_root(live) == "/api/v2/trading/execution"+ assert execution_v1_root(paper).endswith("/demo")+ assert "/demo" not in execution_v1_root(live)+ assert info_root(paper).endswith("/demo")+ assert copy_root(paper).endswith("/demo")+ assert positions_root(paper).endswith("/demo")+++def test_every_request_has_unique_request_id() -> None:+ seen: list[str] = []+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")++ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:+ seen.append(kwargs["headers"]["x-request-id"])+ return _FakeResponse(200, {})++ client = EtoroClient(cfg, transport=_transport)+ client.request("GET", "/api/v1/market-data/search", params={"search": "AAPL"}, allow_retry=True)+ client.request("GET", "/api/v1/market-data/search", params={"search": "MSFT"}, allow_retry=True)+ assert len(seen) == 2+ assert seen[0] != seen[1]+++def test_credentials_redacted_in_public_config() -> None:+ cfg = EtoroConfig(profile="paper", api_key="secret-key", user_key="secret-user")+ from src.trading.connectors.etoro.client import public_config++ payload = public_config(cfg)+ assert "secret-key" not in json.dumps(payload)+ assert payload["api_key_configured"] is True+++def test_place_order_uses_demo_execution_path(monkeypatch) -> None:+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u", readonly=False)+ 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, {"orderID": 42})++ monkeypatch.setattr("src.trading.connectors.etoro.trading.resolve_instrument_id", lambda symbol, c: 1001)+ client = EtoroClient(cfg, transport=_transport)+ set_client_factory(lambda c: client)++ result = etoro_sdk.place_order(+ cfg,+ symbol="AAPL",+ side="buy",+ notional=100.0,+ request_id="fixed-request-id",+ )+ assert result["status"] == "ok"+ assert "/execution/demo/orders" in captured["url"]+ assert captured["json"]["instrumentId"] == 1001+ assert captured["method"] == "POST"+++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("unknown_etoro_op", None, curated) is ToolClass.UNKNOWN+ assert ETORO_TOOL_CLASS["copy_close"] is ToolClass.WRITE+++def test_service_dispatches_positions(monkeypatch) -> None:+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")++ def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:+ assert method == "GET"+ assert info_root(cfg) + "/portfolio" in url+ return _FakeResponse(200, {"positions": [{"positionID": 1, "instrumentDisplayName": "AAPL"}]})++ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))+ result = service.get_positions("etoro-paper-sdk", api_key="k", user_key="u")+ assert result["status"] == "ok"+ assert result["connector"] == "etoro"+ assert result["positions"][0]["symbol"] == "AAPL"diff --git a/agent/tests/test_etoro_live_actions.py b/agent/tests/test_etoro_live_actions.pynew file mode 100644index 000000000..4fa7fa06b--- /dev/null+++ b/agent/tests/test_etoro_live_actions.py@@ -0,0 +1,119 @@+"""Live action gate tests for eToro-specific writes."""++from __future__ import annotations++from contextlib import nullcontext++import pytest++from src.live import sdk_order_gate as gate+from src.live.enforcement import OrderIntent+from src.live.mandate.model import AssetClass, ConsentMeta, HardCaps, InstrumentType, Mandate, UniverseConstraint+from src.trading import service++pytestmark = pytest.mark.unit+++class _FakeEtoroModule:+ def __init__(self):+ self.calls: list[str] = []++ def close_position(self, config, **kwargs):+ self.calls.append("close")+ return {"status": "ok", "position_id": kwargs.get("position_id")}++ def copy_close(self, config, **kwargs):+ self.calls.append("copy_close")+ return {"status": "ok", "mirror_id": kwargs.get("mirror_id")}++ def get_positions(self, config):+ return {"status": "ok", "positions": []}++ def get_account_snapshot(self, config):+ return {"status": "ok", "account": {}}+++def _mandate():+ return Mandate(+ schema_version=1,+ hard_caps=HardCaps(+ account_funding_usd=1_000_000.0,+ max_order_notional_usd=1_000_000.0,+ max_total_exposure_usd=1_000_000.0,+ max_leverage=2.0,+ allowed_instruments=(InstrumentType.EQUITY,),+ max_trades_per_day=100,+ ),+ universe=UniverseConstraint(+ asset_classes=(AssetClass.US_EQUITY,),+ min_market_cap_usd=None,+ min_avg_daily_volume_usd=None,+ exclude_symbols=(),+ ),+ consent=ConsentMeta(+ created_at="2026-01-01T00:00:00+00:00",+ consent_token_sha256="deadbeef",+ broker="etoro",+ account_ref="acct-1",+ expires_at="2999-01-01T00:00:00+00:00",+ ),+ )+++def _patch_gate(monkeypatch, *, mandate, halted=False):+ monkeypatch.setattr(gate, "load_mandate", lambda broker: mandate)+ monkeypatch.setattr(gate, "halt_flag_set", lambda broker: halted)+ monkeypatch.setattr(gate, "write_live_action", lambda *a, **k: {"audited": True})+ monkeypatch.setattr(gate, "read_daily_count", lambda broker: 0)+ monkeypatch.setattr(gate, "increment_daily_count", lambda broker: 1)+ monkeypatch.setattr(gate, "daily_order_lock", lambda broker: nullcontext())+++def test_risk_reducing_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="close_position",+ risk_reducing=True,+ intent=None,+ execute_fn=lambda: module.close_position(None, position_id="123"),+ audit_request={"position_id": "123"},+ )+ assert result["status"] == "ok"+ assert module.calls == ["close"]+++def test_risk_increasing_edit_requires_mandate_when_halted(monkeypatch) -> None:+ module = _FakeEtoroModule()+ _patch_gate(monkeypatch, mandate=_mandate(), halted=True)+ intent = OrderIntent(+ symbol="POS:1",+ side="sell",+ notional_usd=0.0,+ quantity=None,+ instrument_type=InstrumentType.EQUITY,+ asset_class=AssetClass.US_EQUITY,+ )+ result = gate.execute_live_action(+ broker="etoro",+ connector_module=module,+ config=None,+ remote_tool="edit_position_stops",+ risk_reducing=False,+ intent=intent,+ execute_fn=lambda: {"status": "ok"},+ audit_request={"position_id": "1"},+ )+ assert result["status"] == "blocked"+++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"]diff --git a/agent/tests/test_sdk_connectors.py b/agent/tests/test_sdk_connectors.pyindex f02a8d482..3c123a14f 100644--- a/agent/tests/test_sdk_connectors.py+++ b/agent/tests/test_sdk_connectors.py@@ -54,6 +54,8 @@ def test_sdk_profiles_registered() -> None:"futu-paper-sdk", "futu-live-sdk-readonly","dhan-paper-sdk", "dhan-live-sdk-readonly","shoonya-paper-sdk", "shoonya-live-sdk-readonly",+ "etoro-paper-sdk", "etoro-paper-trade",+ "etoro-live-sdk-readonly", "etoro-live-trade",} <= ids@@ -89,6 +91,8 @@ def test_no_discriminator_brokers_expose_no_live_trade_profile() -> None:("dhan-live-sdk-readonly", "dhan", "live"),("shoonya-paper-sdk", "shoonya", "paper"),("shoonya-live-sdk-readonly", "shoonya", "live"),+ ("etoro-paper-sdk", "etoro", "paper"),+ ("etoro-live-sdk-readonly", "etoro", "live"),],)def test_sdk_profiles_are_readonly_broker_sdk(profile_id, connector, environment) -> None: