"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(etoro): close live-trading safety gaps
warren618f69065480775
diff --git a/README.md b/README.mdindex ad1780df4..10b8ce9bd 100644--- a/README.md+++ b/README.md@@ -1290,7 +1290,7 @@ vibe-trading connector quote BTCSymbol lookup uses eToro's `internalSymbolFull` search (e.g. `BTC` → instrument id `100000`). Use the `etoro_search_instruments` agent tool to resolve tickers before trading.-Safety boundary: demo and real are path-separated and key-bound (`paper_guard: path_separated_key_bound`). Live risk-increasing actions (open, copy-start/increase, risk-increasing edits) require an authorized mandate and a clear halt state. Risk-reducing actions (cancel, full close, copy close) remain available when halted and are audit-logged. eToro-specific write tools (`etoro_close_position`, `etoro_copy_*`, etc.) are agent tools only — not exposed via MCP or CLI. Rollback: revert the connector commit(s) or disable profiles; halt blocks new live risk-increasing actions.+Safety boundary: demo and real are path-separated and key-bound (`paper_guard: path_separated_key_bound`). Live risk-increasing actions (open and copy-start/increase) require an authorized mandate, a clear halt state, and a verified USD account for copy-notional enforcement. Validated full and partial position closes, open-order cancellation, and copy close remain available when halted and are audit-logged. Cancelling a pending close or editing position stops is paper-only: the live path fails closed because those operations can increase exposure or transfer extra margin without enough API data to quantify the incremental USD risk. Copy amounts are denominated in the eToro account currency, and every copy start/adjust requires a caller-supplied 1-35 character URL-safe reference id for polling. eToro-specific write tools (`etoro_close_position`, `etoro_copy_*`, etc.) are agent tools only — not exposed via MCP or CLI. Rollback: revert the connector commit(s) or disable profiles; halt blocks new live risk-increasing actions.---diff --git a/agent/src/live/sdk_order_gate.py b/agent/src/live/sdk_order_gate.pyindex 7cdc4470b..4cb498e30 100644--- a/agent/src/live/sdk_order_gate.py+++ b/agent/src/live/sdk_order_gate.py@@ -90,16 +90,30 @@ def execute_live_order(return _deny(broker, session_id, "no valid mandate on file", ["mandate"], mandate, intent=None)if _is_expired(mandate):- return _deny(broker, session_id, "mandate expired — re-authorize", ["mandate", "expiry"], mandate, intent=None, reauth=True)+ 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)+ return _deny(+ broker, session_id, "live trading halted", ["mandate", "expiry", "halt_flag"], 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,+ broker,+ session_id,+ "quantity order notional could not be priced (fail-closed)",+ ["mandate", "expiry", "halt_flag", "quote"],+ mandate,+ intent=intent,)intent = normalized@@ -110,14 +124,24 @@ def execute_live_order(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,+ mandate,+ intent,+ positions,+ balance,+ broker=broker,+ remote_tool=_REMOTE_TOOL,+ daily_count=daily_count,)if breach is None:return _allow(- broker, session_id, connector_module, config,- intent, place_kwargs, mandate,+ broker,+ session_id,+ connector_module,+ config,+ intent,+ place_kwargs,+ mandate,)except DailyOrderLockUnavailable as exc:return _deny(@@ -144,87 +168,165 @@ def execute_live_action(execute_fn: Any,audit_request: dict[str, Any] | None = None,session_id: str = "",+ structural_reason: str | None = None,) -> 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`.+ Risk-reducing actions skip halt and mandate checks but are still+ audit-logged. Risk-increasing actions follow the same ceremony as+ :func:`execute_live_order`. The daily-count lock covers the final state+ reads, broker execution, successful count increment, and audit write so two+ concurrent actions cannot both consume the same last daily slot."""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 structural_reason:+ return _deny(+ broker,+ session_id,+ structural_reason,+ ["structural_contract"],+ mandate,+ intent=intent,+ )- if _is_expired(mandate):- return _deny(- broker,- session_id,- "mandate expired — re-authorize",- ["mandate", "expiry"],- mandate,- intent=None,- reauth=True,- )+ if risk_reducing:+ return _execute_and_audit_live_action(+ broker=broker,+ session_id=session_id,+ remote_tool=remote_tool,+ mandate=mandate,+ intent=intent,+ execute_fn=execute_fn,+ audit_request=audit_request,+ checked=["risk_reducing"],+ consume_daily_count=False,+ )- 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"],+ 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 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", "quote"],+ mandate,+ intent=intent,+ )+ intent = normalized+ checked = [+ "mandate",+ "expiry",+ "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",+ ]+ try:+ with daily_order_lock(broker):+ if _is_expired(mandate):+ return _deny(+ broker,+ session_id,+ "mandate expired — re-authorize",+ ["mandate", "expiry"],+ mandate,+ intent=intent,+ reauth=True,+ )+ if halt_flag_set(broker):+ return _deny(+ broker,+ session_id,+ "live trading halted",+ ["mandate", "expiry", "halt_flag"],+ mandate,+ intent=intent,+ )+ positions = _safe_read(connector_module, "get_positions", config)+ balance = _safe_read(connector_module, "get_account_snapshot", config)+ breach = check_mandate(mandate,- intent=intent,+ intent,+ positions,+ balance,+ broker=broker,+ remote_tool=remote_tool,+ daily_count=read_daily_count(broker),)- 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(+ 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,- positions,- balance,- broker=broker,- remote_tool=remote_tool,- daily_count=daily_count,+ reauth,)- 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,+ return _execute_and_audit_live_action(+ broker=broker,+ session_id=session_id,+ remote_tool=remote_tool,+ mandate=mandate,intent=intent,+ execute_fn=execute_fn,+ audit_request=audit_request,+ checked=checked,+ consume_daily_count=True,)+ except DailyOrderLockUnavailable as exc:+ return _deny(+ broker,+ session_id,+ str(exc),+ ["mandate", "expiry", "halt_flag", "daily_order_lock"],+ mandate,+ intent=intent,+ )++def _execute_and_audit_live_action(+ *,+ broker: str,+ session_id: str,+ remote_tool: str,+ mandate: Mandate | None,+ intent: OrderIntent | None,+ execute_fn: Any,+ audit_request: dict[str, Any] | None,+ checked: list[str],+ consume_daily_count: bool,+) -> dict[str, Any]:+ """Execute one approved action and atomically account for its success."""try:result = execute_fn()except Exception as exc: # noqa: BLE001@@ -232,25 +334,6 @@ def execute_live_action(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,@@ -262,11 +345,15 @@ def execute_live_action(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},+ gate_decision={+ "allowed": True,+ "decision": _DECISION_ALLOW,+ "checked_limits": checked,+ },error=_error_message(result),)else:- if not risk_reducing:+ if consume_daily_count:increment_daily_count(broker)record = _audit_action(broker,@@ -278,12 +365,18 @@ def execute_live_action(intent=intent,broker_request=audit_request,broker_response=result,- gate_decision={"allowed": True, "decision": _DECISION_ALLOW, "checked_limits": checked},+ 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"}+ if isinstance(result, dict):+ return result+ return {"status": "error", "error": "non-dict broker result"}# --------------------------------------------------------------------------- #@@ -301,22 +394,43 @@ def _allow(broker, session_id, connector_module, config, intent, place_kwargs, mis_error = not isinstance(result, dict) or str(result.get("status", "")).lower() != "ok"checked = [- "mandate", "expiry", "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",+ "mandate",+ "expiry",+ "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",]if is_error:record = _audit(- broker, session_id, kind="order_rejected", outcome="error", mandate=mandate, intent=intent,- broker_request=dict(place_kwargs), broker_response=result if isinstance(result, dict) else {"raw": result},+ broker,+ session_id,+ kind="order_rejected",+ outcome="error",+ mandate=mandate,+ intent=intent,+ broker_request=dict(place_kwargs),+ 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:increment_daily_count(broker)record = _audit(- broker, session_id, kind="order_placed", outcome="accepted", mandate=mandate, intent=intent,- broker_request=dict(place_kwargs), broker_response=result,+ broker,+ session_id,+ kind="order_placed",+ outcome="accepted",+ mandate=mandate,+ intent=intent,+ broker_request=dict(place_kwargs),+ broker_response=result,gate_decision={"allowed": True, "decision": _DECISION_ALLOW, "checked_limits": checked},)if isinstance(result, dict) and record is not None:@@ -327,8 +441,14 @@ def _allow(broker, session_id, connector_module, config, intent, place_kwargs, mdef _deny(broker, session_id, reason, checked, mandate, *, intent, reauth=False) -> dict[str, Any]:"""Audit + return a refusal for a pre-check / structural DENY."""record = _audit(- broker, session_id, kind="order_rejected", outcome="blocked", mandate=mandate, intent=intent,- broker_request=None, broker_response=None,+ broker,+ session_id,+ kind="order_rejected",+ outcome="blocked",+ mandate=mandate,+ intent=intent,+ broker_request=None,+ broker_response=None,gate_decision={"allowed": False, "decision": _DECISION_DENY, "checked_limits": checked},error=reason,)@@ -339,17 +459,31 @@ def _deny_breach(broker, session_id, breach, mandate, intent, reauth) -> dict[st"""Audit + return a refusal for a ``check_mandate`` breach."""decision = _DECISION_PAUSE if reauth else _DECISION_DENYrecord = _audit(- broker, session_id, kind="breach", outcome="blocked", mandate=mandate, intent=intent,- broker_request=None, broker_response=None,+ broker,+ session_id,+ kind="breach",+ outcome="blocked",+ mandate=mandate,+ intent=intent,+ broker_request=None,+ broker_response=None,gate_decision={- "allowed": False, "decision": decision, "limit": breach.limit, "kind": breach.kind,- "limit_value": breach.limit_value, "attempted_value": breach.attempted_value,+ "allowed": False,+ "decision": decision,+ "limit": breach.limit,+ "kind": breach.kind,+ "limit_value": breach.limit_value,+ "attempted_value": breach.attempted_value,},error=breach.detail or f"order breaches {breach.limit}",)return _refusal(- broker, decision=decision, reason=breach.detail or f"order breaches {breach.limit}",- reauth=reauth, breach=breach, record=record,+ broker,+ decision=decision,+ reason=breach.detail or f"order breaches {breach.limit}",+ reauth=reauth,+ breach=breach,+ record=record,)@@ -365,12 +499,18 @@ def _refusal(broker, *, decision, reason, reauth, breach=None, record=None) -> dpayload[LIVE_ACTION_RESULT_KEY] = recordif breach is not None:payload["breach"] = {- "broker": breach.broker, "limit": breach.limit, "limit_value": breach.limit_value,- "attempted_value": breach.attempted_value, "overage": breach.overage,- "kind": breach.kind, "detail": breach.detail,+ "broker": breach.broker,+ "limit": breach.limit,+ "limit_value": breach.limit_value,+ "attempted_value": breach.attempted_value,+ "overage": breach.overage,+ "kind": breach.kind,+ "detail": breach.detail,"proposed_action": {- "symbol": breach.proposed_action.symbol, "side": breach.proposed_action.side,- "notional_usd": breach.proposed_action.notional_usd, "quantity": breach.proposed_action.quantity,+ "symbol": breach.proposed_action.symbol,+ "side": breach.proposed_action.side,+ "notional_usd": breach.proposed_action.notional_usd,+ "quantity": breach.proposed_action.quantity,"instrument_type": breach.proposed_action.instrument_type.value,},}@@ -399,8 +539,12 @@ def _normalize_notional(intent: OrderIntent, connector_module: Any, config: Any)explicit = intent.notional_usd if intent.notional_usd is not None else 0.0enforced = max(float(explicit), implied)return OrderIntent(- symbol=intent.symbol, side=intent.side, notional_usd=enforced,- quantity=intent.quantity, instrument_type=intent.instrument_type, asset_class=intent.asset_class,+ symbol=intent.symbol,+ side=intent.side,+ notional_usd=enforced,+ quantity=intent.quantity,+ instrument_type=intent.instrument_type,+ asset_class=intent.asset_class,)@@ -492,7 +636,9 @@ 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:+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,@@ -571,8 +717,10 @@ def _describe_intent(intent: OrderIntent | None) -> str | None:if intent is None:return Nonesize = (- f"${intent.notional_usd:g}" if intent.notional_usd is not None- else f"{intent.quantity:g} units" if intent.quantity is not None+ f"${intent.notional_usd:g}"+ if intent.notional_usd is not None+ else f"{intent.quantity:g} units"+ if intent.quantity is not Noneelse "?")return f"{intent.side} {size} {intent.symbol} ({intent.instrument_type.value})"diff --git a/agent/src/tools/trading_connector_tool.py b/agent/src/tools/trading_connector_tool.pyindex 58a88e60e..1b2e5f1d5 100644--- a/agent/src/tools/trading_connector_tool.py+++ b/agent/src/tools/trading_connector_tool.py@@ -450,8 +450,14 @@ class TradingPlaceOrderTool(BaseTool):**TRADING_COMMON_PARAMETERS,"symbol": {"type": "string", "description": "Symbol, e.g. AAPL, BTC-USDT, 700.HK, HK.00700."},"side": {"type": "string", "enum": ["buy", "sell"]},- "quantity": {"type": "number", "description": "Order size in units/shares/contracts. Exactly one of quantity/notional."},- "notional": {"type": "number", "description": "Order size as an account-currency amount. Exactly one of quantity/notional."},+ "quantity": {+ "type": "number",+ "description": "Order size in units/shares/contracts. Exactly one of quantity/notional.",+ },+ "notional": {+ "type": "number",+ "description": "Order size as an account-currency amount. Exactly one of quantity/notional.",+ },"order_type": {"type": "string", "enum": ["market", "limit"], "default": "market"},"limit_price": {"type": "number", "description": "Required for limit orders."},"time_in_force": {"type": "string", "enum": ["day", "gtc"], "default": "day"},@@ -595,7 +601,10 @@ class EtoroClosePositionTool(BaseTool):"properties": {**ETORO_TOOL_PARAMETERS,"position_id": {"type": "string", "description": "eToro position id."},- "instrument_id": {"type": "integer", "description": "Optional instrument id."},+ "instrument_id": {+ "type": "integer",+ "description": "Optional instrument id; always resolved and verified against the open position.",+ },"units_to_close": {"type": "number", "description": "Units to close; omit to close entire position."},"request_id": {"type": "string", "description": "Optional idempotency request id (UUID)."},},@@ -627,7 +636,10 @@ class EtoroClosePositionTool(BaseTool):class EtoroCancelCloseOrderTool(BaseTool):name = "etoro_cancel_close_order"- description = "Cancel a pending eToro market close order by order id."+ description = (+ "Cancel a pending eToro market close order by order id (paper only; "+ "live is fail-closed because this reinstates exposure)."+ )parameters = {"type": "object","properties": {@@ -660,7 +672,10 @@ class EtoroCancelCloseOrderTool(BaseTool):class EtoroEditPositionStopsTool(BaseTool):name = "etoro_edit_position_stops"- description = "Modify stop-loss, take-profit, or trailing stop on an open eToro position."+ description = (+ "Modify or clear stop-loss/take-profit on an open eToro position "+ "(paper only; live edits are fail-closed until incremental funding can be quantified)."+ )parameters = {"type": "object","properties": {@@ -668,7 +683,12 @@ class EtoroEditPositionStopsTool(BaseTool):"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."},+ "trailing_stop_loss": {+ "type": "boolean",+ "description": "true selects trailing; false selects fixed stop-loss type.",+ },+ "clear_stop_loss": {"type": "boolean", "description": "Remove the stop-loss."},+ "clear_take_profit": {"type": "boolean", "description": "Remove the take-profit."},"request_id": {"type": "string", "description": "Optional idempotency request id (UUID)."},},"required": ["position_id"],@@ -692,6 +712,8 @@ class EtoroEditPositionStopsTool(BaseTool):stop_loss=stop_loss,take_profit=take_profit,trailing_stop_loss=bool(trailing) if trailing is not None else None,+ clear_stop_loss=bool(kwargs.get("clear_stop_loss", False)),+ clear_take_profit=bool(kwargs.get("clear_take_profit", False)),request_id=_connection(kwargs.get("request_id")),**overrides,)@@ -702,16 +724,16 @@ class EtoroEditPositionStopsTool(BaseTool):class EtoroCopyPrecheckTool(BaseTool):name = "etoro_copy_precheck"- description = "Dry-run whether the account can copy an investor with a given USD amount."+ description = "Dry-run whether the account can copy an investor with an account-currency amount."parameters = {"type": "object","properties": {**ETORO_TOOL_PARAMETERS,"parent_cid": {"type": "integer", "description": "Investor parent CID."},- "amount_usd": {"type": "number", "description": "USD amount to copy or adjust."},+ "amount": {"type": "number", "description": "Positive amount in the account currency."},"request_id": {"type": "string", "description": "Optional request id (UUID)."},},- "required": ["parent_cid", "amount_usd"],+ "required": ["parent_cid", "amount"],}repeatable = Trueis_readonly = True@@ -719,7 +741,7 @@ class EtoroCopyPrecheckTool(BaseTool):def execute(self, **kwargs: Any) -> str:try:overrides = _etoro_overrides(kwargs)- amount = _finite_float(kwargs["amount_usd"], "amount_usd")+ amount = _finite_float(kwargs["amount"], "amount")parent_cid = _int_or_none(kwargs["parent_cid"], "parent_cid")except InvalidTradingArgument as exc:return _json_result({"status": "error", "error": str(exc)})@@ -745,10 +767,17 @@ class EtoroCopyStartTool(BaseTool):"properties": {**ETORO_TOOL_PARAMETERS,"parent_cid": {"type": "integer", "description": "Investor parent CID."},- "amount_usd": {"type": "number", "description": "USD amount to add (negative to reduce)."},+ "amount": {+ "type": "number",+ "description": "Account-currency amount to add (negative to reduce). Live increases require a verified USD account.",+ },+ "reference_id": {+ "type": "string",+ "description": "Required caller reference: 1-35 URL-safe characters, used for polling.",+ },"request_id": {"type": "string", "description": "Optional request id (UUID)."},},- "required": ["parent_cid", "amount_usd"],+ "required": ["parent_cid", "amount", "reference_id"],}repeatable = Falseis_readonly = False@@ -756,7 +785,7 @@ class EtoroCopyStartTool(BaseTool):def execute(self, **kwargs: Any) -> str:try:overrides = _etoro_overrides(kwargs)- amount = _finite_float(kwargs["amount_usd"], "amount_usd")+ amount = _finite_float(kwargs["amount"], "amount")parent_cid = _int_or_none(kwargs["parent_cid"], "parent_cid")except InvalidTradingArgument as exc:return _json_result({"status": "error", "error": str(exc)})@@ -766,6 +795,7 @@ class EtoroCopyStartTool(BaseTool):parent_cid,amount,_connection(kwargs.get("connection")),+ reference_id=str(kwargs["reference_id"]),request_id=_connection(kwargs.get("request_id")),**overrides,)diff --git a/agent/src/trading/connectors/etoro/client.py b/agent/src/trading/connectors/etoro/client.pyindex e44b53f59..e1234bd52 100644--- a/agent/src/trading/connectors/etoro/client.py+++ b/agent/src/trading/connectors/etoro/client.py@@ -290,7 +290,12 @@ class EtoroClient:raise EtoroAPIError("request failed without response")-_default_client_factory: Callable[[EtoroConfig], EtoroClient] = lambda cfg: EtoroClient(cfg)+def _build_default_client(cfg: EtoroConfig) -> EtoroClient:+ """Build the production HTTP client for one eToro configuration."""+ return EtoroClient(cfg)+++_default_client_factory: Callable[[EtoroConfig], EtoroClient] = _build_default_clientdef make_client(cfg: EtoroConfig) -> EtoroClient:@@ -303,7 +308,7 @@ def set_client_factory() -> 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))+ _default_client_factory = factory or _build_default_clientdef _response_error_body(response: requests.Response) -> str:diff --git a/agent/src/trading/connectors/etoro/copy_trading.py b/agent/src/trading/connectors/etoro/copy_trading.pyindex 5b983a107..ea23b6676 100644--- a/agent/src/trading/connectors/etoro/copy_trading.py+++ b/agent/src/trading/connectors/etoro/copy_trading.py@@ -2,6 +2,8 @@from __future__ import annotations+import math+import reimport timeimport uuidfrom typing import Any@@ -9,6 +11,9 @@ from typing import Anyfrom src.trading.connectors.etoro.client import EtoroAPIError, EtoroConfig, copy_root, make_client+_REFERENCE_ID_RE = re.compile(r"^[A-Za-z0-9._~-]{1,35}$")++def _base(cfg: EtoroConfig) -> dict[str, Any]:return {"profile": cfg.profile,@@ -25,16 +30,20 @@ def copy_precheck(config: EtoroConfig | None = None,*,parent_cid: int,- amount_usd: float,+ amount: float,request_id: str | None = None,) -> dict[str, Any]:from src.trading.connectors.etoro.client import load_configcfg = config or load_config()- if amount_usd <= 0:- return _error(cfg, "amount_usd must be positive")+ try:+ clean_amount = float(amount)+ except (TypeError, ValueError, OverflowError):+ return _error(cfg, "amount must be a finite positive number in account currency")+ if not math.isfinite(clean_amount) or clean_amount <= 0:+ return _error(cfg, "amount must be a finite positive number in account currency")- body = {"parentCID": int(parent_cid), "amount": float(amount_usd)}+ body = {"parentCID": int(parent_cid), "amount": clean_amount}req_id = (request_id or str(uuid.uuid4())).strip()path = f"{copy_root(cfg)}/eligibility"try:@@ -49,16 +58,31 @@ def copy_start_or_adjust(config: EtoroConfig | None = None,*,parent_cid: int,- amount_usd: float,+ amount: float,+ reference_id: str,request_id: str | None = None,) -> dict[str, Any]:from src.trading.connectors.etoro.client import load_configcfg = 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)}+ try:+ clean_amount = float(amount)+ except (TypeError, ValueError, OverflowError):+ return _error(cfg, "amount must be a finite non-zero number in account currency")+ if not math.isfinite(clean_amount) or clean_amount == 0:+ return _error(cfg, "amount must be a finite non-zero number in account currency")+ ref = str(reference_id or "").strip()+ if not _REFERENCE_ID_RE.fullmatch(ref):+ return _error(+ cfg,+ "reference_id must be 1-35 URL-safe characters (letters, digits, '.', '_', '~', '-')",+ )++ body = {+ "parentCID": int(parent_cid),+ "amount": clean_amount,+ "referenceID": ref,+ }req_id = (request_id or str(uuid.uuid4())).strip()path = copy_root(cfg)try:@@ -66,14 +90,14 @@ def copy_start_or_adjust(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),+ "amount": clean_amount,"request_id": req_id,- "reference_id": reference_id,+ "reference_id": ref,+ "token": _extract_token(payload),"raw": payload,}@@ -123,14 +147,13 @@ def copy_close(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,+ "token": _extract_token(payload),"raw": payload,}@@ -162,16 +185,16 @@ def copy_poll_until_complete(return last-def _extract_reference_id(payload: Any) -> str | None:+def _extract_token(payload: Any) -> str | None:if not isinstance(payload, dict):return None- for key in ("referenceID", "referenceId", "reference_id"):+ for key in ("token", "Token"):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"):+ for key in ("token", "Token"):value = data.get(key)if value is not None:return str(value)diff --git a/agent/src/trading/connectors/etoro/trading.py b/agent/src/trading/connectors/etoro/trading.pyindex 4fb4e5210..cf09729fd 100644--- a/agent/src/trading/connectors/etoro/trading.py+++ b/agent/src/trading/connectors/etoro/trading.py@@ -2,8 +2,8 @@from __future__ import annotations+import mathimport uuid-from decimal import Decimal, InvalidOperationfrom typing import Anyfrom src.trading.connectors.etoro.client import (@@ -147,16 +147,33 @@ def close_position(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 instrument_id is None:+ return _order_error(+ cfg,+ "instrument_id is required by the eToro close-position contract",+ position_id=pos_id,+ )+ try:+ clean_instrument_id = int(instrument_id)+ except (TypeError, ValueError, OverflowError):+ return _order_error(cfg, "instrument_id must be a positive integer", position_id=pos_id)+ if clean_instrument_id <= 0:+ return _order_error(cfg, "instrument_id must be a positive integer", position_id=pos_id)++ body: dict[str, Any] = {"InstrumentId": clean_instrument_id}if units_to_close is not None:- body["UnitsToDeduct"] = float(units_to_close)+ try:+ clean_units = float(units_to_close)+ except (TypeError, ValueError, OverflowError):+ return _order_error(cfg, "units_to_close must be a finite positive number", position_id=pos_id)+ if not math.isfinite(clean_units) or clean_units <= 0:+ return _order_error(cfg, "units_to_close must be a finite positive number", position_id=pos_id)+ body["UnitsToDeduct"] = clean_unitsreq_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)+ payload = make_client(cfg).request("POST", 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)@@ -201,6 +218,8 @@ def edit_position_stops(stop_loss: float | None = None,take_profit: float | None = None,trailing_stop_loss: bool | None = None,+ clear_stop_loss: bool = False,+ clear_take_profit: bool = False,request_id: str | None = None,) -> dict[str, Any]:from src.trading.connectors.etoro.client import load_config@@ -209,16 +228,45 @@ def edit_position_stops(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")+ if (+ stop_loss is None+ and take_profit is None+ and trailing_stop_loss is None+ and not clear_stop_loss+ and not clear_take_profit+ ):+ return _order_error(+ cfg,+ "at least one stop-loss/take-profit update is required",+ )+ if stop_loss is not None and clear_stop_loss:+ return _order_error(cfg, "stop_loss and clear_stop_loss are mutually exclusive")+ if take_profit is not None and clear_take_profit:+ return _order_error(cfg, "take_profit and clear_take_profit are mutually exclusive")body: dict[str, Any] = {}if stop_loss is not None:- body["stopLossRate"] = float(stop_loss)+ try:+ value = float(stop_loss)+ except (TypeError, ValueError, OverflowError):+ return _order_error(cfg, "stop_loss must be a finite positive rate")+ if not math.isfinite(value) or value <= 0:+ return _order_error(cfg, "stop_loss must be a finite positive rate")+ body["stopLossRate"] = valueif take_profit is not None:- body["takeProfitRate"] = float(take_profit)+ try:+ value = float(take_profit)+ except (TypeError, ValueError, OverflowError):+ return _order_error(cfg, "take_profit must be a finite positive rate")+ if not math.isfinite(value) or value <= 0:+ return _order_error(cfg, "take_profit must be a finite positive rate")+ body["takeProfitRate"] = valueif trailing_stop_loss is not None:- body["isTslEnabled"] = bool(trailing_stop_loss)+ body["stopLossType"] = "trailing" if trailing_stop_loss else "fixed"+ if clear_stop_loss:+ body["clearStopLoss"] = True+ if clear_take_profit:+ body["clearTakeProfit"] = Truereq_id = (request_id or str(uuid.uuid4())).strip()path = f"{positions_root(cfg)}/positions/{pos_id}"diff --git a/agent/src/trading/service.py b/agent/src/trading/service.pyindex 5ba44c47b..ce21bb04d 100644--- a/agent/src/trading/service.py+++ b/agent/src/trading/service.py@@ -2,6 +2,7 @@from __future__ import annotations+import mathfrom typing import Anyfrom src.trading.profiles import list_profiles, profile_by_id@@ -383,6 +384,7 @@ def _route_sdk_write(execute: Any,overrides: dict[str, Any],unsupported_capability: str,+ structural_reason: str | None = None,) -> dict[str, Any]:if profile.transport != "broker_sdk":return _unsupported(profile, unsupported_capability)@@ -406,10 +408,107 @@ def _route_sdk_write(execute_fn=lambda: execute(config),audit_request=audit_request,session_id=str(overrides.get("session_id") or ""),+ structural_reason=structural_reason,),)+def _etoro_error(message: str) -> dict[str, Any]:+ """Return a connector-shaped fail-closed error before any broker write."""+ return {"status": "error", "error": message}+++def _close_etoro_position(+ module: Any,+ config: Any,+ *,+ position_id: str | int,+ instrument_id: int | None,+ units_to_close: float | None,+ request_id: str | None,+) -> dict[str, Any]:+ """Resolve and validate an eToro position before a full or partial close."""+ try:+ snapshot = module.get_positions(config)+ except Exception as exc: # noqa: BLE001+ return _etoro_error(f"could not verify position before close: {exc}")+ if not isinstance(snapshot, dict) or snapshot.get("status") != "ok":+ detail = snapshot.get("error") if isinstance(snapshot, dict) else None+ return _etoro_error(f"could not verify position before close: {detail or 'invalid positions response'}")+ rows = snapshot.get("positions")+ if not isinstance(rows, list):+ return _etoro_error("could not verify position before close: positions are missing")+ requested_position_id = str(position_id).strip()+ position = next(+ (+ row+ for row in rows+ if isinstance(row, dict) and str(row.get("position_id", "")).strip() == requested_position_id+ ),+ None,+ )+ if position is None:+ return _etoro_error(f"position {requested_position_id!r} was not found")++ try:+ resolved_instrument_id = int(position.get("instrument_id"))+ except (TypeError, ValueError, OverflowError):+ return _etoro_error("position instrument_id is missing or invalid (fail-closed)")+ if resolved_instrument_id <= 0:+ return _etoro_error("position instrument_id is missing or invalid (fail-closed)")+ if instrument_id is not None:+ try:+ supplied_instrument_id = int(instrument_id)+ except (TypeError, ValueError, OverflowError):+ return _etoro_error("supplied instrument_id is invalid")+ if supplied_instrument_id != resolved_instrument_id:+ return _etoro_error("supplied instrument_id does not match the open position (fail-closed)")++ clean_units: float | None = None+ if units_to_close is not None:+ try:+ clean_units = float(units_to_close)+ open_units = abs(float(position.get("units")))+ except (TypeError, ValueError, OverflowError):+ return _etoro_error("position units or units_to_close are invalid")+ if not math.isfinite(clean_units) or clean_units <= 0:+ return _etoro_error("units_to_close must be a finite positive number")+ if not math.isfinite(open_units) or open_units <= 0:+ return _etoro_error("open position units are unavailable (fail-closed)")+ tolerance = max(1e-12, open_units * 1e-12)+ if clean_units > open_units + tolerance:+ return _etoro_error(f"units_to_close ({clean_units}) exceeds open position units ({open_units})")++ return module.close_position(+ config,+ position_id=position_id,+ instrument_id=resolved_instrument_id,+ units_to_close=clean_units,+ request_id=request_id,+ )+++def _etoro_account_currency(snapshot: Any) -> str | None:+ """Extract the account currency from a normalized eToro account snapshot."""+ if not isinstance(snapshot, dict) or snapshot.get("status") != "ok":+ return None+ account = snapshot.get("account")+ if not isinstance(account, dict):+ return None+ pnl = account.get("pnl")+ aggregated = account.get("aggregated_portfolio")+ candidates = [+ pnl.get("account_currency") if isinstance(pnl, dict) else None,+ aggregated.get("accountCurrency") if isinstance(aggregated, dict) else None,+ account.get("accountCurrency"),+ ]+ for value in candidates:+ token = str(value or "").strip().upper()+ if token:+ return token+ return None++def close_position(position_id: str | int,profile_id: str | None = None,@@ -433,14 +532,14 @@ def close_position("units_to_close": units_to_close,"request_id": request_id,}- full_close = units_to_close is Nonereturn _route_sdk_write(profile,remote_tool="close_position",- risk_reducing=full_close,+ risk_reducing=True,intent=None,audit_request=audit,- execute=lambda cfg: module.close_position(+ execute=lambda cfg: _close_etoro_position(+ module,cfg,position_id=position_id,instrument_id=instrument_id,@@ -471,12 +570,17 @@ def cancel_close_order(return _route_sdk_write(profile,remote_tool="cancel_close_order",- risk_reducing=True,+ risk_reducing=False,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",+ structural_reason=(+ "live eToro close-order cancellation is disabled because cancelling "+ "a pending reduction can increase exposure and the reinstated risk "+ "cannot be quantified from the current API response (fail-closed)"+ ),)@@ -487,6 +591,8 @@ def edit_position_stops(stop_loss: float | None = None,take_profit: float | None = None,trailing_stop_loss: bool | None = None,+ clear_stop_loss: bool = False,+ clear_take_profit: bool = False,request_id: str | None = None,session_id: str = "",**overrides: Any,@@ -503,23 +609,15 @@ def edit_position_stops("stop_loss": stop_loss,"take_profit": take_profit,"trailing_stop_loss": trailing_stop_loss,+ "clear_stop_loss": clear_stop_loss,+ "clear_take_profit": clear_take_profit,"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,+ intent=None,audit_request=audit,execute=lambda cfg: module.edit_position_stops(cfg,@@ -527,16 +625,24 @@ def edit_position_stops(stop_loss=stop_loss,take_profit=take_profit,trailing_stop_loss=trailing_stop_loss,+ clear_stop_loss=clear_stop_loss,+ clear_take_profit=clear_take_profit,request_id=request_id,),overrides={**overrides, "session_id": session_id},unsupported_capability="positions.edit",+ structural_reason=(+ "live eToro stop edits are disabled because loosening a stop can "+ "transfer additional account funds into position margin and the "+ "incremental USD funding cannot be quantified before execution "+ "(fail-closed)"+ ),)def etoro_copy_precheck(parent_cid: int,- amount_usd: float,+ amount: float,profile_id: str | None = None,*,request_id: str | None = None,@@ -549,15 +655,21 @@ def etoro_copy_precheck(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),+ module.copy_precheck(+ config,+ parent_cid=parent_cid,+ amount=amount,+ request_id=request_id,+ ),)def etoro_copy_start(parent_cid: int,- amount_usd: float,+ amount: float,profile_id: str | None = None,*,+ reference_id: str,request_id: str | None = None,session_id: str = "",**overrides: Any,@@ -568,17 +680,48 @@ def etoro_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}+ try:+ amount_value = float(amount)+ except (TypeError, ValueError, OverflowError):+ return _with_profile(+ profile,+ _etoro_error("amount must be a finite non-zero number"),+ )+ if not math.isfinite(amount_value) or amount_value == 0:+ return _with_profile(+ profile,+ _etoro_error("amount must be a finite non-zero number"),+ )+ account_currency: str | None = None+ structural_reason: str | None = None+ if profile.environment == "live" and amount_value > 0:+ config = module.build_config(profile.config, overrides)+ try:+ account_currency = _etoro_account_currency(module.get_account_snapshot(config))+ except Exception as exc: # noqa: BLE001+ structural_reason = f"could not verify eToro account currency before copy allocation: {exc}"+ if structural_reason is None and account_currency != "USD":+ structural_reason = (+ "live eToro copy increases are supported only for verified USD "+ f"accounts; received {account_currency or 'unknown'} (fail-closed)"+ )+ audit = {+ "parent_cid": parent_cid,+ "amount": amount_value,+ "account_currency": account_currency,+ "reference_id": reference_id,+ "request_id": request_id,+ }from src.live.enforcement import OrderIntent- risk_reducing = float(amount_usd) < 0+ risk_reducing = amount_value < 0intent = None- if not risk_reducing:+ if not risk_reducing and structural_reason is None: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)),+ notional_usd=abs(amount_value),quantity=None,instrument_type=instrument_type,asset_class=asset_class,@@ -592,11 +735,13 @@ def etoro_copy_start(execute=lambda cfg: module.copy_start_or_adjust(cfg,parent_cid=parent_cid,- amount_usd=amount_usd,+ amount=amount_value,+ reference_id=reference_id,request_id=request_id,),overrides={**overrides, "session_id": session_id},unsupported_capability="copy.start",+ structural_reason=structural_reason,)diff --git a/agent/tests/test_etoro_connector.py b/agent/tests/test_etoro_connector.pyindex 180e7af9d..109b5afad 100644--- a/agent/tests/test_etoro_connector.py+++ b/agent/tests/test_etoro_connector.py@@ -260,7 +260,11 @@ def test_resolve_btc_uses_internal_symbol_full(monkeypatch) -> None:{"items": [{"instrumentId": 100134, "internalSymbolFull": "BTCA"},- {"instrumentId": 100000, "internalSymbolFull": "BTC", "internalInstrumentDisplayName": "Bitcoin"},+ {+ "instrumentId": 100000,+ "internalSymbolFull": "BTC",+ "internalInstrumentDisplayName": "Bitcoin",+ },],},)@@ -387,6 +391,7 @@ def test_close_position_uses_market_close_path(monkeypatch) -> None:def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:captured["method"] = methodcaptured["url"] = url+ captured["json"] = kwargs.get("json")return _FakeResponse(200, {"orderID": 55})set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))@@ -395,6 +400,40 @@ def test_close_position_uses_market_close_path(monkeypatch) -> None:assert captured["method"] == "POST"assert "/market-close-orders/positions/10" in captured["url"]assert "/execution/demo/" in captured["url"]+ assert captured["json"] == {"InstrumentId": 100000}+++def test_partial_close_uses_required_wire_contract(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, {"orderForClose": {"orderID": 56}})++ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))++ result = etoro_sdk.close_position(+ cfg,+ position_id=10,+ instrument_id=100000,+ units_to_close=2.5,+ )++ assert result["status"] == "ok"+ assert captured["json"] == {+ "InstrumentId": 100000,+ "UnitsToDeduct": 2.5,+ }+++def test_close_position_refuses_missing_instrument_id() -> None:+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")++ result = etoro_sdk.close_position(cfg, position_id=10)++ assert result["status"] == "error"+ assert "instrument_id is required" in result["error"]def test_cancel_close_order_uses_delete_path(monkeypatch) -> None:@@ -424,12 +463,44 @@ def test_edit_position_stops_patches_position(monkeypatch) -> None: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)+ result = etoro_sdk.edit_position_stops(+ cfg,+ position_id=5,+ stop_loss=90.0,+ take_profit=110.0,+ trailing_stop_loss=True,+ )assert result["status"] == "ok"assert captured["method"] == "PATCH"assert "/positions/5" in captured["url"]assert captured["json"]["stopLossRate"] == 90.0assert captured["json"]["takeProfitRate"] == 110.0+ assert captured["json"]["stopLossType"] == "trailing"+ assert "isTslEnabled" not in captured["json"]+++def test_edit_position_stops_supports_clear_contract(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(202, {"operationId": "op-1"})++ set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))++ result = etoro_sdk.edit_position_stops(+ cfg,+ position_id=5,+ clear_stop_loss=True,+ clear_take_profit=True,+ )++ assert result["status"] == "ok"+ assert captured["json"] == {+ "clearStopLoss": True,+ "clearTakeProfit": True,+ }def test_copy_precheck_posts_eligibility(monkeypatch) -> None:@@ -443,7 +514,7 @@ def test_copy_precheck_posts_eligibility(monkeypatch) -> None: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)+ result = etoro_sdk.copy_precheck(cfg, parent_cid=123, amount=100.0)assert result["status"] == "ok"assert captured["method"] == "POST"assert captured["url"].endswith("/eligibility")@@ -457,14 +528,36 @@ def test_copy_start_posts_copy_root(monkeypatch) -> None:def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:captured["url"] = urlcaptured["json"] = kwargs.get("json")- return _FakeResponse(200, {"referenceID": "ref-1"})+ return _FakeResponse(200, {"token": "ack-token"})set_client_factory(lambda c: EtoroClient(cfg, transport=_transport))- result = etoro_sdk.copy_start_or_adjust(cfg, parent_cid=123, amount_usd=200.0)+ result = etoro_sdk.copy_start_or_adjust(+ cfg,+ parent_cid=123,+ amount=200.0,+ reference_id="ref-1",+ )assert result["status"] == "ok"assert result["reference_id"] == "ref-1"+ assert result["token"] == "ack-token"assert copy_root(cfg) in captured["url"]assert captured["json"]["amount"] == 200.0+ assert captured["json"]["referenceID"] == "ref-1"++[email protected]("reference_id", ["contains/slash", "x" * 36, ""])+def test_copy_start_rejects_invalid_reference_id(reference_id: str) -> None:+ cfg = EtoroConfig(profile="paper", api_key="k", user_key="u")++ result = etoro_sdk.copy_start_or_adjust(+ cfg,+ parent_cid=123,+ amount=200.0,+ reference_id=reference_id,+ )++ assert result["status"] == "error"+ assert "reference_id" in result["error"]def test_copy_poll_gets_reference(monkeypatch) -> None:@@ -489,11 +582,12 @@ def test_copy_close_posts_close(monkeypatch) -> None:def _transport(method: str, url: str, **kwargs: Any) -> _FakeResponse:captured["url"] = urlcaptured["json"] = kwargs.get("json")- return _FakeResponse(200, {"referenceID": "ref-close"})+ return _FakeResponse(200, {"token": "close-token"})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 result["token"] == "close-token"assert captured["url"].endswith("/close")assert captured["json"]["mirrorID"] == 99diff --git a/agent/tests/test_etoro_live_actions.py b/agent/tests/test_etoro_live_actions.pyindex c74449f0d..3e92852aa 100644--- a/agent/tests/test_etoro_live_actions.py+++ b/agent/tests/test_etoro_live_actions.py@@ -2,7 +2,7 @@from __future__ import annotations-from contextlib import nullcontext+from contextlib import contextmanager, nullcontextimport pytest@@ -15,14 +15,17 @@ pytestmark = pytest.mark.unitclass _FakeEtoroModule:- def __init__(self):+ def __init__(self, *, account_currency: str = "USD"):self.calls: list[str] = []+ self.close_kwargs: dict = {}+ self.account_currency = account_currencydef build_config(self, profile_config, overrides):return Nonedef close_position(self, config, **kwargs):self.calls.append("close")+ self.close_kwargs = dict(kwargs)return {"status": "ok", "position_id": kwargs.get("position_id")}def cancel_close_order(self, config, order_id="", *, request_id=None, **kwargs):@@ -46,10 +49,23 @@ class _FakeEtoroModule:return {"status": "ok", "order_id": order_id}def get_positions(self, config):- return {"status": "ok", "positions": []}+ return {+ "status": "ok",+ "positions": [+ {+ "position_id": 99,+ "instrument_id": 100000,+ "symbol": "AAPL",+ "units": 10.0,+ }+ ],+ }def get_account_snapshot(self, config):- return {"status": "ok", "account": {}}+ return {+ "status": "ok",+ "account": {"pnl": {"account_currency": self.account_currency}},+ }def _mandate():@@ -129,6 +145,58 @@ def test_risk_increasing_edit_requires_mandate_when_halted(monkeypatch) -> None:assert result["status"] == "blocked"+def test_risk_increasing_action_executes_and_counts_inside_daily_lock(+ monkeypatch,+) -> None:+ module = _FakeEtoroModule()+ state = {"inside": False, "executed": False, "incremented": False}+ _patch_gate(monkeypatch, mandate=_mandate())+ monkeypatch.setattr(gate, "check_mandate", lambda *args, **kwargs: None)++ @contextmanager+ def _lock(_broker):+ state["inside"] = True+ try:+ yield+ finally:+ state["inside"] = False++ def _execute():+ assert state["inside"] is True+ state["executed"] = True+ return {"status": "ok"}++ def _increment(_broker):+ assert state["inside"] is True+ assert state["executed"] is True+ state["incremented"] = True+ return 1++ monkeypatch.setattr(gate, "daily_order_lock", _lock)+ monkeypatch.setattr(gate, "increment_daily_count", _increment)+ intent = OrderIntent(+ symbol="AAPL",+ side="buy",+ notional_usd=100.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="copy_start_or_adjust",+ risk_reducing=False,+ intent=intent,+ execute_fn=_execute,+ )++ assert result["status"] == "ok"+ assert state == {"inside": False, "executed": True, "incremented": True}++def test_copy_close_allowed_when_halted(monkeypatch) -> None:module = _FakeEtoroModule()_patch_gate(monkeypatch, mandate=_mandate(), halted=True)@@ -152,6 +220,41 @@ def test_service_close_position_paper_bypasses_gate(monkeypatch) -> None:result = service.close_position("99", "etoro-paper-trade")assert result["status"] == "ok"assert module.calls == ["close"]+ assert module.close_kwargs["instrument_id"] == 100000+++def test_service_partial_close_is_validated_and_risk_reducing_when_halted(+ monkeypatch,+) -> None:+ module = _FakeEtoroModule()+ monkeypatch.setattr(service, "_sdk_module", lambda connector: module)+ _patch_gate(monkeypatch, mandate=_mandate(), halted=True)++ result = service.close_position(+ "99",+ "etoro-live-trade",+ units_to_close=4.0,+ )++ assert result["status"] == "ok"+ assert module.calls == ["close"]+ assert module.close_kwargs["instrument_id"] == 100000+ assert module.close_kwargs["units_to_close"] == 4.0+++def test_service_partial_close_refuses_units_above_open_position(monkeypatch) -> None:+ module = _FakeEtoroModule()+ monkeypatch.setattr(service, "_sdk_module", lambda connector: module)++ result = service.close_position(+ "99",+ "etoro-paper-trade",+ units_to_close=11.0,+ )++ assert result["status"] == "error"+ assert "exceeds open position units" in result["error"]+ assert module.calls == []def test_service_cancel_close_order_paper_bypasses_gate(monkeypatch) -> None:@@ -162,6 +265,18 @@ def test_service_cancel_close_order_paper_bypasses_gate(monkeypatch) -> None:assert module.calls == ["cancel_close"]+def test_service_cancel_close_order_live_fails_closed(monkeypatch) -> None:+ module = _FakeEtoroModule()+ monkeypatch.setattr(service, "_sdk_module", lambda connector: module)+ _patch_gate(monkeypatch, mandate=_mandate())++ result = service.cancel_close_order("55", "etoro-live-trade")++ assert result["status"] == "blocked"+ assert "reinstated risk" in result["reason"]+ assert module.calls == []++def test_service_edit_position_stops_paper_bypasses_gate(monkeypatch) -> None:module = _FakeEtoroModule()monkeypatch.setattr(service, "_sdk_module", lambda connector: module)@@ -170,14 +285,54 @@ def test_service_edit_position_stops_paper_bypasses_gate(monkeypatch) -> None:assert module.calls == ["edit"]+def test_service_edit_position_stops_live_fails_closed(monkeypatch) -> None:+ module = _FakeEtoroModule()+ monkeypatch.setattr(service, "_sdk_module", lambda connector: module)+ _patch_gate(monkeypatch, mandate=_mandate())++ result = service.edit_position_stops(+ "99",+ "etoro-live-trade",+ stop_loss=90.0,+ )++ assert result["status"] == "blocked"+ assert "incremental USD funding" in result["reason"]+ assert module.calls == []++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")+ result = service.etoro_copy_start(+ 123,+ 100.0,+ "etoro-paper-trade",+ reference_id="ref-1",+ )assert result["status"] == "ok"assert module.calls == ["copy_start"]+def test_service_etoro_copy_increase_non_usd_live_account_fails_closed(+ monkeypatch,+) -> None:+ module = _FakeEtoroModule(account_currency="EUR")+ monkeypatch.setattr(service, "_sdk_module", lambda connector: module)+ _patch_gate(monkeypatch, mandate=_mandate())++ result = service.etoro_copy_start(+ 123,+ 100.0,+ "etoro-live-trade",+ reference_id="ref-1",+ )++ assert result["status"] == "blocked"+ assert "verified USD accounts" in result["reason"]+ assert module.calls == []++def test_service_cancel_order_paper_bypasses_gate(monkeypatch) -> None:module = _FakeEtoroModule()monkeypatch.setattr(service, "_sdk_module", lambda connector: module)diff --git a/agent/tests/test_paper_capped_connectors_refuse_live.py b/agent/tests/test_paper_capped_connectors_refuse_live.pyindex fb26d5d07..b1f6ec833 100644--- a/agent/tests/test_paper_capped_connectors_refuse_live.py+++ b/agent/tests/test_paper_capped_connectors_refuse_live.py@@ -35,7 +35,17 @@ _PAPER_CAPPED = frozenset({"longbridge", "dhan", "shoonya", "trading212"})# through the mandate gate — which `test_backtest_runner_security.py` and the# order-guard suites cover; this gate deliberately does not re-assert it._LIVE_CAPABLE = frozenset(- {"alpaca", "binance", "futu", "okx", "tiger", "robinhood", "ibkr", "mt5"}+ {+ "alpaca",+ "binance",+ "etoro",+ "futu",+ "okx",+ "tiger",+ "robinhood",+ "ibkr",+ "mt5",+ })_ORDER_ENTRY_POINTS = ("place_order", "cancel_order")@@ -51,11 +61,7 @@ _MAX_STATEMENTS_BEFORE_GUARD = 1def _connector_names() -> list[str]:"""Return every connector package name found on disk."""- return sorted(- path.name- for path in _CONNECTOR_ROOT.iterdir()- if path.is_dir() and not path.name.startswith("__")- )+ return sorted(path.name for path in _CONNECTOR_ROOT.iterdir() if path.is_dir() and not path.name.startswith("__"))def _order_functions(sdk_path: Path) -> dict[str, tuple[ast.FunctionDef, str]]:@@ -71,11 +77,7 @@ def _order_functions(sdk_path: Path) -> dict[str, tuple[ast.FunctionDef, str]]:def _executable_body(func: ast.FunctionDef) -> list[ast.stmt]:"""Return the function body with the docstring removed."""- return [- stmt- for stmt in func.body- if not (isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant))- ]+ return [stmt for stmt in func.body if not (isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Constant))]def test_every_connector_is_classified() -> None: