"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat: read-only Trading 212 broker connector
Matt Van Horneb1c23db4836
diff --git a/agent/src/live/registry.py b/agent/src/live/registry.pyindex 75c6d02a6..b24e8f96c 100644--- a/agent/src/live/registry.py+++ b/agent/src/live/registry.py@@ -33,6 +33,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.trading212.classification import TRADING212_TOOL_CLASSlogger = logging.getLogger(__name__)@@ -51,6 +52,7 @@ _BROKER_CURATED_MAPS = {"futu": FUTU_TOOL_CLASS,"dhan": DHAN_TOOL_CLASS,"shoonya": SHOONYA_TOOL_CLASS,+ "trading212": TRADING212_TOOL_CLASS,}@@ -138,9 +140,7 @@ def has_cached_oauth_token(url: str, cache_dir: str) -> bool:return False-def should_register_live_channel(- *, interactive: bool, url: str, cache_dir: str | None-) -> bool:+def should_register_live_channel(*, interactive: bool, url: str, cache_dir: str | None) -> bool:"""Decide whether to register a live channel given session interactivity.SPEC Transport §4 (headless / no-token-yet): a non-interactive@@ -203,6 +203,7 @@ def wrap_live_broker_tools(broker = _broker_for(server_name, url)curated = _BROKER_CURATED_MAPS.get(broker)halted = halt_flag_set(broker)+result: list[MCPRemoteTool] = []for tool in wrappers:spec = tool._spec # internal seam: the gate is constructed from the same spec/adapter@@ -213,8 +214,7 @@ def wrap_live_broker_tools(elif halted:# WRITE/UNKNOWN + halt tripped -> do not even hand it to the model.logger.warning(- "live kill switch tripped for broker '%s' — omitting order tool "- "'%s' from the registry",+ "live kill switch tripped for broker '%s' — omitting order tool '%s' from the registry",broker,spec.remote_name,)diff --git a/agent/src/trading/connectors/trading212/__init__.py b/agent/src/trading/connectors/trading212/__init__.pynew file mode 100644index 000000000..93df2ab0d--- /dev/null+++ b/agent/src/trading/connectors/trading212/__init__.py@@ -0,0 +1,7 @@+"""Trading 212 broker connector.++Read-only account, portfolio, order, order-history, and instrument-metadata+access through Trading 212's public REST API. The public API does not expose a+runtime paper/live discriminator that this connector can verify, so order+placement and cancellation are intentionally disabled.+"""diff --git a/agent/src/trading/connectors/trading212/classification.py b/agent/src/trading/connectors/trading212/classification.pynew file mode 100644index 000000000..9afafc158--- /dev/null+++ b/agent/src/trading/connectors/trading212/classification.py@@ -0,0 +1,40 @@+"""Curated read/write classification for Trading 212 REST operations.++Keys are the connector's public operation names and the Trading 212 REST+operation names they wrap. Mutating order operations are pinned WRITE even+though this read-only connector refuses them at runtime, so the live gate never+treats a future Trading 212 order surface as a plain read.+"""++from __future__ import annotations++from src.live.classification import ToolClass++TRADING212_TOOL_CLASS: dict[str, ToolClass] = {+ # READ+ "get_account_snapshot": ToolClass.READ,+ "get_account_cash": ToolClass.READ,+ "get_account_metadata": ToolClass.READ,+ "get_positions": ToolClass.READ,+ "get_open_orders": ToolClass.READ,+ "get_order_history": ToolClass.READ,+ "get_instrument_metadata": ToolClass.READ,+ "get_exchanges": ToolClass.READ,+ "get_quote": ToolClass.READ,+ "get_historical_bars": ToolClass.READ,+ "equity_account_cash": ToolClass.READ,+ "equity_account_info": ToolClass.READ,+ "equity_portfolio": ToolClass.READ,+ "equity_orders": ToolClass.READ,+ "equity_history_orders": ToolClass.READ,+ "equity_metadata_instruments": ToolClass.READ,+ "equity_metadata_exchanges": ToolClass.READ,+ # WRITE+ "place_order": ToolClass.WRITE,+ "cancel_order": ToolClass.WRITE,+ "equity_order_market": ToolClass.WRITE,+ "equity_order_limit": ToolClass.WRITE,+ "equity_order_stop": ToolClass.WRITE,+ "equity_order_stop_limit": ToolClass.WRITE,+ "equity_order_cancel": ToolClass.WRITE,+}diff --git a/agent/src/trading/connectors/trading212/profiles.py b/agent/src/trading/connectors/trading212/profiles.pynew file mode 100644index 000000000..0d1886eec--- /dev/null+++ b/agent/src/trading/connectors/trading212/profiles.py@@ -0,0 +1,52 @@+"""Built-in Trading 212 connector profiles.++Trading 212's public REST API is registered here as read-only only. The API key+selects whatever account Trading 212 has bound to it; this connector has no+runtime paper/live discriminator it can independently verify, so order+placement is not exposed by any built-in profile.+"""++from __future__ import annotations++from src.trading.types import TradingProfile++TRADING212_READ_CAPABILITIES = (+ "account.read",+ "positions.read",+ "orders.read",+ "order_history.read",+ "instruments.read",+)++TRADING212_PROFILES: tuple[TradingProfile, ...] = (+ TradingProfile(+ id="trading212-paper-sdk",+ connector="trading212",+ label="Trading 212 Practice · REST Read-Only",+ environment="paper",+ transport="broker_sdk",+ capabilities=TRADING212_READ_CAPABILITIES,+ readonly=True,+ config={"profile": "paper", "base_url": "https://demo.trading212.com"},+ notes=(+ "Reads a Trading 212 account through the public REST API. Paper vs "+ "live is operator-declared from the configured API key; order "+ "placement is disabled because the API response does not provide a "+ "runtime discriminator this connector can verify."+ ),+ ),+ TradingProfile(+ id="trading212-live-sdk-readonly",+ connector="trading212",+ label="Trading 212 Live · REST Read-Only",+ environment="live",+ transport="broker_sdk",+ capabilities=TRADING212_READ_CAPABILITIES,+ readonly=True,+ config={"profile": "live-readonly", "base_url": "https://live.trading212.com"},+ notes=(+ "Reads a Trading 212 live account through the public REST API. "+ "Order placement is not exposed in this profile."+ ),+ ),+)diff --git a/agent/src/trading/connectors/trading212/sdk.py b/agent/src/trading/connectors/trading212/sdk.pynew file mode 100644index 000000000..7e6489443--- /dev/null+++ b/agent/src/trading/connectors/trading212/sdk.py@@ -0,0 +1,586 @@+"""Read-only Trading 212 connector via the public REST API.++Wraps Trading 212's account cash/info, portfolio, open-order, order-history,+and metadata endpoints. Market quotes and OHLCV bars are not exposed by the+public API, so the generic quote/history entry points return a clear unsupported+payload instead of fabricating market data from account state.++Paper-vs-live identity guard: none is verifiable from the response body. The+configured ``profile`` is operator-declared from the API key and recorded in+every payload as ``paper_guard="read_only_no_runtime_discriminator"``. Order+placement and cancellation are disabled for every profile until Trading 212+offers a structural paper/demo safety boundary this connector can verify.+"""++from __future__ import annotations++import json+from dataclasses import asdict, dataclass+from pathlib import Path+from typing import Any, Mapping+from urllib.parse import urljoin++import requests++from src.config.paths import get_runtime_root++CONFIG_FILENAME = "trading212.json"+DEFAULT_BASE_URL = "https://live.trading212.com"+PAPER_GUARD = "read_only_no_runtime_discriminator"++PROFILE_ENVIRONMENTS = {+ "paper": "paper",+ "live-readonly": "live",+ "live": "live",+}+++class Trading212ConfigError(RuntimeError):+ """Raised when the Trading 212 connector configuration is missing/invalid."""+++class Trading212APIError(RuntimeError):+ """Raised when Trading 212 returns an auth, HTTP, network, or JSON error."""+++@dataclass(frozen=True)+class Trading212Config:+ """Trading 212 connector connection settings.++ Args:+ api_key: Trading 212 API key.+ api_secret: Optional Trading 212 API secret. When present, requests use+ HTTP Basic auth as described by the current Trading 212 API docs.+ When omitted, the connector falls back to the legacy+ ``Authorization`` API-key header.+ profile: ``paper``, ``live-readonly`` or ``live``. This is+ operator-declared; Trading 212 responses do not prove the account+ environment.+ base_url: Public API base URL.+ timeout: Network timeout in seconds.+ readonly: Always true for built-in profiles; order methods refuse all+ requests regardless of this flag.+ """++ api_key: str = ""+ api_secret: str = ""+ profile: str = "live-readonly"+ base_url: str = DEFAULT_BASE_URL+ timeout: float = 15.0+ readonly: bool = True++ @classmethod+ def from_mapping(cls, data: Mapping[str, Any] | None = None) -> "Trading212Config":+ """Build a config from a JSON-like mapping, normalizing profile/URL."""+ payload = dict(data or {})+ profile = str(payload.get("profile") or "live-readonly").strip().lower()+ if profile not in PROFILE_ENVIRONMENTS:+ raise Trading212ConfigError("profile must be 'paper', 'live-readonly' or 'live'")+ base_url = str(payload.get("base_url") or DEFAULT_BASE_URL).strip().rstrip("/")+ if not base_url.startswith(("http://", "https://")):+ raise Trading212ConfigError("base_url must start with http:// or https://")+ return cls(+ api_key=str(payload.get("api_key") or "").strip(),+ api_secret=str(payload.get("api_secret") or "").strip(),+ profile=profile,+ base_url=base_url,+ timeout=float(payload.get("timeout") or 15.0),+ readonly=bool(payload.get("readonly", True)),+ )++ def with_overrides(+ self,+ *,+ api_key: str | None = None,+ api_secret: str | None = None,+ profile: str | None = None,+ base_url: str | None = None,+ ) -> "Trading212Config":+ """Return a copy with CLI/tool overrides applied."""+ payload = asdict(self)+ if api_key is not None:+ payload["api_key"] = api_key+ if api_secret is not None:+ payload["api_secret"] = api_secret+ if profile is not None:+ payload["profile"] = profile+ if base_url is not None:+ payload["base_url"] = base_url+ return Trading212Config.from_mapping(payload)++ @property+ def environment(self) -> str:+ """Return ``paper`` or ``live`` for the operator-declared profile."""+ return PROFILE_ENVIRONMENTS.get(self.profile, "live")+++_OVERRIDE_KEYS = ("api_key", "api_secret", "profile", "base_url")+++def build_config(+ profile_config: Mapping[str, Any] | None = None,+ overrides: Mapping[str, Any] | None = None,+) -> Trading212Config:+ """Resolve config: saved file ← profile defaults ← CLI overrides."""+ base = asdict(load_config())+ for key, value in dict(profile_config or {}).items():+ if value is not None:+ base[key] = value+ cfg = Trading212Config.from_mapping(base)+ clean = {k: v for k, v in dict(overrides or {}).items() if k in _OVERRIDE_KEYS and v not in (None, "")}+ return cfg.with_overrides(**clean) if clean else cfg+++def config_path() -> Path:+ """Return the user-level Trading 212 config path."""+ return get_runtime_root() / CONFIG_FILENAME+++def load_config() -> Trading212Config:+ """Load Trading 212 settings from ``~/.vibe-trading/trading212.json``."""+ path = config_path()+ if not path.exists():+ return Trading212Config()+ try:+ return Trading212Config.from_mapping(json.loads(path.read_text(encoding="utf-8")))+ except (OSError, ValueError, json.JSONDecodeError) as exc:+ raise Trading212ConfigError(f"invalid Trading 212 config at {path}: {exc}") from exc+++def save_config(config: Trading212Config) -> Path:+ """Persist Trading 212 settings with owner-only permissions."""+ path = config_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(asdict(config), indent=2, ensure_ascii=False) + "\n", encoding="utf-8")+ try:+ path.chmod(0o600)+ except OSError:+ pass+ return path+++def check_status(config: Trading212Config | None = None) -> dict[str, Any]:+ """Check REST readiness and config completeness without mutating broker state."""+ 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": cfg.base_url,+ }++ missing = _missing_fields(cfg)+ if missing:+ report["status"] = "error"+ report["error"] = f"Trading 212 connector not configured: missing {', '.join(missing)}."+ return report++ try:+ snapshot = get_account_snapshot(cfg)+ except (Trading212ConfigError, Trading212APIError) as exc:+ report["status"] = "error"+ report["error"] = str(exc)+ return report+ except Exception as exc: # noqa: BLE001 - health endpoint reports cleanly+ report["status"] = "error"+ report["error"] = f"Trading 212 connector check failed: {exc}"+ return report++ report["account"] = {+ "profile": cfg.profile,+ "cash_currency": _first(snapshot.get("cash"), ("currencyCode", "currency")),+ "account_type": _first(snapshot.get("metadata"), ("type", "accountType")),+ }+ return report+++def get_account_snapshot(config: Trading212Config | None = None) -> dict[str, Any]:+ """Fetch account cash and account metadata for the configured API key."""+ cfg = config or load_config()+ cash = get_account_cash(cfg)["cash"]+ metadata = get_account_metadata(cfg)["metadata"]+ return {+ "status": "ok",+ "profile": cfg.profile,+ "paper_guard": PAPER_GUARD,+ "cash": cash,+ "metadata": metadata,+ }+++def get_account_cash(config: Trading212Config | None = None) -> dict[str, Any]:+ """Fetch account cash balances."""+ cfg = config or load_config()+ payload = _get(cfg, "/api/v0/equity/account/cash")+ return {+ "status": "ok",+ "profile": cfg.profile,+ "paper_guard": PAPER_GUARD,+ "cash": _mapping_or_raw(payload),+ }+++def get_account_metadata(config: Trading212Config | None = None) -> dict[str, Any]:+ """Fetch account metadata/info."""+ cfg = config or load_config()+ payload = _get(cfg, "/api/v0/equity/account/info")+ return {+ "status": "ok",+ "profile": cfg.profile,+ "paper_guard": PAPER_GUARD,+ "metadata": _mapping_or_raw(payload),+ }+++def get_positions(config: Trading212Config | None = None) -> dict[str, Any]:+ """Fetch current portfolio positions."""+ cfg = config or load_config()+ payload = _get(cfg, "/api/v0/equity/portfolio")+ return {+ "status": "ok",+ "profile": cfg.profile,+ "paper_guard": PAPER_GUARD,+ "positions": [_position_to_dict(item) for item in _extract_items(payload)],+ }+++def get_open_orders(config: Trading212Config | None = None, *, include_executions: bool = False) -> dict[str, Any]:+ """Fetch currently open Trading 212 equity orders."""+ cfg = config or load_config()+ payload = _get(cfg, "/api/v0/equity/orders")+ result: dict[str, Any] = {+ "status": "ok",+ "profile": cfg.profile,+ "paper_guard": PAPER_GUARD,+ "open_orders": [_order_to_dict(item) for item in _extract_items(payload)],+ }+ if include_executions:+ history = get_order_history(cfg)+ result["executions"] = history["orders"]+ return result+++def get_order_history(+ config: Trading212Config | None = None,+ *,+ cursor: str | None = None,+ limit: int = 50,+) -> dict[str, Any]:+ """Fetch historical orders for the configured account."""+ cfg = config or load_config()+ params: dict[str, Any] = {"limit": int(limit)}+ if cursor:+ params["cursor"] = cursor+ payload = _get(cfg, "/api/v0/equity/history/orders", params=params)+ return {+ "status": "ok",+ "profile": cfg.profile,+ "paper_guard": PAPER_GUARD,+ "orders": [_order_to_dict(item) for item in _extract_items(payload)],+ "next_page_path": _first(payload, ("nextPagePath", "next_page_path")),+ }+++def get_instrument_metadata(+ config: Trading212Config | None = None,+ *,+ ticker: str | None = None,+) -> dict[str, Any]:+ """Fetch Trading 212 instrument metadata, optionally filtered by ticker."""+ cfg = config or load_config()+ payload = _get(cfg, "/api/v0/equity/metadata/instruments")+ rows = [_instrument_to_dict(item) for item in _extract_items(payload)]+ if ticker:+ clean = ticker.strip().upper()+ rows = [row for row in rows if str(row.get("ticker") or "").upper() == clean]+ return {+ "status": "ok",+ "profile": cfg.profile,+ "paper_guard": PAPER_GUARD,+ "instruments": rows,+ }+++def get_exchanges(config: Trading212Config | None = None) -> dict[str, Any]:+ """Fetch Trading 212 exchange metadata."""+ cfg = config or load_config()+ payload = _get(cfg, "/api/v0/equity/metadata/exchanges")+ return {+ "status": "ok",+ "profile": cfg.profile,+ "paper_guard": PAPER_GUARD,+ "exchanges": [_mapping_or_raw(item) for item in _extract_items(payload)],+ }+++def get_quote(symbol: str, *, config: Trading212Config | None = None, **_: Any) -> dict[str, Any]:+ """Return a clear unsupported payload; Trading 212 exposes no quote endpoint."""+ cfg = config or load_config()+ return _unsupported_market_data(cfg, "quotes.read", symbol=symbol)+++def get_historical_bars(+ symbol: str,+ *,+ config: Trading212Config | None = None,+ period: str = "1d",+ limit: int = 90,+ **_: Any,+) -> dict[str, Any]:+ """Return a clear unsupported payload; Trading 212 exposes no OHLCV endpoint."""+ cfg = config or load_config()+ result = _unsupported_market_data(cfg, "history.read", symbol=symbol)+ result["period"] = period+ result["limit"] = int(limit)+ return result+++_ORDER_DISABLED_ERROR = (+ "Trading 212 connector is read-only: order placement and cancellation are "+ "disabled until a structural paper/demo safety boundary is available."+)++_LIVE_ORDER_ERROR = (+ "Trading 212 order placement is not supported for live/read-only profiles "+ "(no runtime paper/live discriminator is available)."+)+++def place_order(+ config: Trading212Config | 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",+) -> dict[str, Any]:+ """Refuse Trading 212 order placement before any REST client is touched."""+ cfg = config or load_config()+ # ---- HARD GUARD: no verified live safety boundary (must run first) ----+ if cfg.environment != "paper":+ return _order_refused(cfg, _LIVE_ORDER_ERROR, symbol=symbol, side=side)+ return _order_refused(+ cfg,+ _ORDER_DISABLED_ERROR,+ symbol=symbol,+ side=side,+ quantity=quantity,+ notional=notional,+ order_type=order_type,+ limit_price=limit_price,+ time_in_force=time_in_force,+ )+++def cancel_order(+ config: Trading212Config | None = None,+ order_id: str = "",+ *,+ symbol: str | None = None,+) -> dict[str, Any]:+ """Refuse Trading 212 order cancellation before any REST client is touched."""+ cfg = config or load_config()+ # ---- HARD GUARD: no verified live safety boundary (must run first) ----+ if cfg.environment != "paper":+ return _order_refused(cfg, _LIVE_ORDER_ERROR, order_id=order_id, symbol=symbol)+ return _order_refused(cfg, _ORDER_DISABLED_ERROR, order_id=order_id, symbol=symbol)+++def _get(config: Trading212Config, path: str, *, params: Mapping[str, Any] | None = None) -> Any:+ """Perform a read-only GET request against the Trading 212 REST API."""+ return _request(config, "GET", path, params=params)+++def _request(+ config: Trading212Config,+ method: str,+ path: str,+ *,+ params: Mapping[str, Any] | None = None,+) -> Any:+ """Run an HTTP request and normalize Trading 212 failure modes."""+ missing = _missing_fields(config)+ if missing:+ raise Trading212ConfigError(f"Trading 212 connector not configured: missing {', '.join(missing)}.")++ url = urljoin(f"{config.base_url.rstrip('/')}/", path.lstrip("/"))+ headers = {"Accept": "application/json"}+ auth = None+ if config.api_secret:+ auth = (config.api_key, config.api_secret)+ else:+ headers["Authorization"] = config.api_key+ try:+ response = requests.request(+ method.upper(),+ url,+ headers=headers,+ auth=auth,+ params=dict(params or {}),+ timeout=config.timeout,+ )+ except requests.RequestException as exc:+ raise Trading212APIError(f"Trading 212 request failed: {exc}") from exc++ if response.status_code in (401, 403):+ raise Trading212APIError("Trading 212 API authentication failed: check api_key/api_secret.")+ if response.status_code >= 400:+ raise Trading212APIError(f"Trading 212 API returned HTTP {response.status_code}: {_error_message(response)}")+ if not response.content:+ return None+ try:+ return response.json()+ except ValueError as exc:+ raise Trading212APIError("Trading 212 API returned invalid JSON.") from exc+++def _error_message(response: requests.Response) -> str:+ try:+ payload = response.json()+ except ValueError:+ return response.text.strip() or response.reason or "request failed"+ if isinstance(payload, Mapping):+ for key in ("message", "error", "detail", "title"):+ value = payload.get(key)+ if value:+ return str(value)+ return str(payload)+++def _missing_fields(config: Trading212Config) -> list[str]:+ missing = []+ if not config.api_key:+ missing.append("api_key")+ return missing+++def _public_config(config: Trading212Config) -> dict[str, Any]:+ """Config snapshot with the API key redacted."""+ data = asdict(config)+ if data.get("api_key"):+ data["api_key"] = data["api_key"][:4] + "***"+ if data.get("api_secret"):+ data["api_secret"] = "***redacted***"+ return data+++def _unsupported_market_data(config: Trading212Config, capability: str, *, symbol: str) -> dict[str, Any]:+ return {+ "status": "error",+ "profile": config.profile,+ "paper_guard": PAPER_GUARD,+ "symbol": str(symbol or "").strip().upper(),+ "error": f"Trading 212 public API does not expose {capability} market data.",+ }+++def _order_refused(config: Trading212Config, message: str, **extra: Any) -> dict[str, Any]:+ payload: dict[str, Any] = {+ "status": "error",+ "error": message,+ "profile": config.profile,+ "paper_guard": PAPER_GUARD,+ }+ payload.update({key: value for key, value in extra.items() if value is not None})+ return payload+++def _as_iter(value: Any) -> list[Any]:+ if value is None:+ return []+ if isinstance(value, (list, tuple)):+ return list(value)+ return [value]+++def _extract_items(payload: Any) -> list[Any]:+ if isinstance(payload, list):+ return payload+ if isinstance(payload, Mapping):+ for key in ("items", "data", "orders", "instruments", "exchanges", "results"):+ value = payload.get(key)+ if isinstance(value, list):+ return value+ return _as_iter(payload)+++def _mapping_or_raw(value: Any) -> dict[str, Any]:+ if isinstance(value, Mapping):+ return dict(value)+ if value is None:+ return {}+ return {"raw": value}+++def _obj_get(obj: Any, name: str, default: Any = None) -> Any:+ if obj is None:+ return default+ if isinstance(obj, Mapping):+ return obj.get(name, default)+ return getattr(obj, name, default)+++def _first(obj: Any, names: tuple[str, ...], default: Any = None) -> Any:+ for name in names:+ value = _obj_get(obj, name, None)+ if value is not None:+ return value+ return default+++def _position_to_dict(item: Any) -> dict[str, Any]:+ return {+ "symbol": _first(item, ("ticker", "symbol")),+ "ticker": _first(item, ("ticker",)),+ "quantity": _first(item, ("quantity",)),+ "average_price": _first(item, ("averagePrice", "average_price")),+ "current_price": _first(item, ("currentPrice", "current_price")),+ "pnl": _first(item, ("ppl", "pnl")),+ "fx_pnl": _first(item, ("fxPpl", "fx_pnl")),+ "currency": _first(item, ("currencyCode", "currency")),+ "initial_fill_date": _first(item, ("initialFillDate", "initial_fill_date")),+ "max_buy": _first(item, ("maxBuy", "max_buy")),+ "max_sell": _first(item, ("maxSell", "max_sell")),+ "cash_invested": _first(item, ("cashInvested", "cash_invested")),+ }+++def _order_to_dict(item: Any) -> dict[str, Any]:+ return {+ "order_id": str(_first(item, ("id", "orderId", "order_id"), "")),+ "symbol": _first(item, ("ticker", "symbol")),+ "ticker": _first(item, ("ticker",)),+ "side": str(_first(item, ("side",), "")),+ "order_type": str(_first(item, ("type", "orderType", "order_type"), "")),+ "status": str(_first(item, ("status",), "")),+ "quantity": _first(item, ("quantity",)),+ "filled_quantity": _first(item, ("filledQuantity", "filled_quantity")),+ "limit_price": _first(item, ("limitPrice", "limit_price")),+ "stop_price": _first(item, ("stopPrice", "stop_price")),+ "price": _first(item, ("price",)),+ "value": _first(item, ("value",)),+ "currency": _first(item, ("currencyCode", "currency")),+ "time_validity": _first(item, ("timeValidity", "time_validity")),+ "created_at": _first(item, ("creationTime", "createdAt", "dateCreated", "created_at")),+ "executed_at": _first(item, ("dateExecuted", "executedAt", "executed_at")),+ }+++def _instrument_to_dict(item: Any) -> dict[str, Any]:+ return {+ "ticker": _first(item, ("ticker",)),+ "name": _first(item, ("name",)),+ "short_name": _first(item, ("shortName", "short_name")),+ "isin": _first(item, ("isin",)),+ "type": _first(item, ("type",)),+ "currency": _first(item, ("currencyCode", "currency")),+ "exchange": _first(item, ("exchange", "exchangeCode", "exchange_code")),+ "working_schedule_id": _first(item, ("workingScheduleId", "working_schedule_id")),+ "max_open_quantity": _first(item, ("maxOpenQuantity", "max_open_quantity")),+ "min_trade_quantity": _first(item, ("minTradeQuantity", "min_trade_quantity")),+ "added_on": _first(item, ("addedOn", "added_on")),+ }diff --git a/agent/src/trading/profiles.py b/agent/src/trading/profiles.pyindex 6723ce46e..5aa795209 100644--- a/agent/src/trading/profiles.py+++ b/agent/src/trading/profiles.py@@ -16,6 +16,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.trading212.profiles import TRADING212_PROFILESfrom src.trading.types import TradingProfileCONFIG_FILENAME = "trading-connections.json"@@ -32,6 +33,7 @@ BUILTIN_PROFILES: tuple[TradingProfile, ...] = (*FUTU_PROFILES,*DHAN_PROFILES,*SHOONYA_PROFILES,+ *TRADING212_PROFILES,)diff --git a/agent/src/trading/service.py b/agent/src/trading/service.pyindex a8ae9f7c2..3cc7ef873 100644--- a/agent/src/trading/service.py+++ b/agent/src/trading/service.py@@ -22,6 +22,7 @@ _SDK_CONNECTOR_MODULES = {"futu": "src.trading.connectors.futu.sdk","dhan": "src.trading.connectors.dhan.sdk","shoonya": "src.trading.connectors.shoonya.sdk",+ "trading212": "src.trading.connectors.trading212.sdk",}@@ -106,7 +107,9 @@ def get_open_orders(module = _sdk_module(profile.connector)return _with_profile(profile,- module.get_open_orders(module.build_config(profile.config, overrides), include_executions=include_executions),+ module.get_open_orders(+ module.build_config(profile.config, overrides), include_executions=include_executions+ ),)return _call_remote(profile, "orders", {})@@ -204,6 +207,7 @@ _CONNECTOR_INSTRUMENT = {"tiger": ("equity", None),"longbridge": ("equity", None),"futu": ("equity", None),+ "trading212": ("equity", None),}@@ -258,6 +262,8 @@ def place_order(profile = profile_by_id(profile_id)if profile.transport != "broker_sdk":return _unsupported(profile, "orders.place")+ if profile.readonly:+ return _unsupported(profile, "orders.place")module = _sdk_module(profile.connector)config = module.build_config(profile.config, overrides)@@ -316,6 +322,8 @@ def cancel_order(profile = profile_by_id(profile_id)if profile.transport != "broker_sdk":return _unsupported(profile, "orders.cancel")+ if profile.readonly:+ return _unsupported(profile, "orders.cancel")module = _sdk_module(profile.connector)config = module.build_config(profile.config, overrides)result = module.cancel_order(config, order_id, symbol=symbol)diff --git a/agent/tests/test_trading212_connector.py b/agent/tests/test_trading212_connector.pynew file mode 100644index 000000000..a959c1e18--- /dev/null+++ b/agent/tests/test_trading212_connector.py@@ -0,0 +1,251 @@+"""Tests for the read-only Trading 212 connector."""++from __future__ import annotations++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.trading212 import sdk as t212+from src.trading.connectors.trading212.classification import TRADING212_TOOL_CLASS++pytestmark = pytest.mark.unit+++def test_trading212_profiles_registered_readonly() -> None:+ ids = {profile.id for profile in profiles.list_profiles()}+ assert {"trading212-paper-sdk", "trading212-live-sdk-readonly"} <= ids++ for profile_id, environment in (+ ("trading212-paper-sdk", "paper"),+ ("trading212-live-sdk-readonly", "live"),+ ):+ profile = profiles.profile_by_id(profile_id)+ assert profile.connector == "trading212"+ assert profile.environment == environment+ assert profile.transport == "broker_sdk"+ assert profile.readonly is True+ assert "orders.place" not in profile.capabilities+ assert "orders.place.requires_mandate" not in profile.capabilities+ assert "instruments.read" in profile.capabilities+ assert "order_history.read" in profile.capabilities+++def test_trading212_profiles_use_official_hosts() -> None:+ paper = profiles.profile_by_id("trading212-paper-sdk")+ live = profiles.profile_by_id("trading212-live-sdk-readonly")++ paper_cfg = t212.build_config(paper.config, {"api_key": "key"})+ live_cfg = t212.build_config(live.config, {"api_key": "key"})++ assert paper_cfg.base_url == "https://demo.trading212.com"+ assert live_cfg.base_url == "https://live.trading212.com"+++def test_trading212_read_write_classification_registered() -> None:+ curated = registry._BROKER_CURATED_MAPS["trading212"]++ for name in (+ "get_account_cash",+ "get_positions",+ "get_open_orders",+ "get_order_history",+ "get_instrument_metadata",+ "equity_metadata_instruments",+ ):+ assert TRADING212_TOOL_CLASS[name] is ToolClass.READ+ assert classify_tool(name, None, curated) is ToolClass.READ++ for name in ("place_order", "cancel_order", "equity_order_market", "equity_order_cancel"):+ assert TRADING212_TOOL_CLASS[name] is ToolClass.WRITE+ assert classify_tool(name, None, curated) is ToolClass.WRITE++ assert classify_tool("brand_new_trading212_operation", None, curated) is ToolClass.UNKNOWN+++def test_trading212_service_dispatches_positions(monkeypatch) -> None:+ def fake_request(config, method, path, *, params=None):+ assert method == "GET"+ assert path == "/api/v0/equity/portfolio"+ assert config.api_key == "key"+ return [+ {+ "ticker": "AAPL_US_EQ",+ "quantity": 2,+ "averagePrice": 150.0,+ "currentPrice": 151.25,+ "currencyCode": "USD",+ }+ ]++ monkeypatch.setattr(t212, "_request", fake_request)++ result = service.get_positions("trading212-live-sdk-readonly", api_key="key")+ assert result["status"] == "ok"+ assert result["connector"] == "trading212"+ assert result["environment"] == "live"+ assert result["positions"] == [+ {+ "symbol": "AAPL_US_EQ",+ "ticker": "AAPL_US_EQ",+ "quantity": 2,+ "average_price": 150.0,+ "current_price": 151.25,+ "pnl": None,+ "fx_pnl": None,+ "currency": "USD",+ "initial_fill_date": None,+ "max_buy": None,+ "max_sell": None,+ "cash_invested": None,+ }+ ]+++def test_trading212_check_connection_missing_api_key(monkeypatch, tmp_path) -> None:+ monkeypatch.setattr(t212, "get_runtime_root", lambda: tmp_path)+ result = service.check_connection("trading212-live-sdk-readonly")+ assert result["status"] == "error"+ assert "missing api_key" in result["error"]+ assert result["connector"] == "trading212"+ assert result["transport"] == "broker_sdk"+++def test_trading212_check_connection_invalid_api_key_surfaces_clean_error(monkeypatch) -> None:+ def invalid_auth(config, method, path, *, params=None):+ raise t212.Trading212APIError("Trading 212 API authentication failed: check api_key.")++ monkeypatch.setattr(t212, "_request", invalid_auth)++ result = service.check_connection("trading212-live-sdk-readonly", api_key="bad")+ assert result["status"] == "error"+ assert "authentication failed" in result["error"]+ assert result["connector"] == "trading212"+++class _FakeResponse:+ status_code = 200+ content = b"{}"+ text = ""+ reason = "OK"++ def json(self):+ return {}+++def test_trading212_request_uses_basic_auth_when_api_secret_is_present(monkeypatch) -> None:+ seen = {}++ def fake_request(method, url, *, headers, auth, params, timeout):+ seen.update(+ {+ "method": method,+ "url": url,+ "headers": headers,+ "auth": auth,+ "params": params,+ "timeout": timeout,+ }+ )+ return _FakeResponse()++ monkeypatch.setattr(t212.requests, "request", fake_request)++ t212._request(+ t212.Trading212Config(api_key="key", api_secret="secret"),+ "GET",+ "/api/v0/equity/account/cash",+ params={"limit": 1},+ )++ assert seen == {+ "method": "GET",+ "url": "https://live.trading212.com/api/v0/equity/account/cash",+ "headers": {"Accept": "application/json"},+ "auth": ("key", "secret"),+ "params": {"limit": 1},+ "timeout": 15.0,+ }+++def test_trading212_request_uses_legacy_authorization_without_api_secret(monkeypatch) -> None:+ seen = {}++ def fake_request(method, url, *, headers, auth, params, timeout):+ seen.update({"headers": headers, "auth": auth})+ return _FakeResponse()++ monkeypatch.setattr(t212.requests, "request", fake_request)++ t212._request(t212.Trading212Config(api_key="legacy-key"), "GET", "/api/v0/equity/account/cash")++ assert seen["headers"] == {"Accept": "application/json", "Authorization": "legacy-key"}+ assert seen["auth"] is None+++def test_trading212_public_config_redacts_api_secret() -> None:+ pub = t212._public_config(t212.Trading212Config(api_key="KEY12345", api_secret="SECRET"))+ assert pub["api_key"] == "KEY1***"+ assert pub["api_secret"] == "***redacted***"+ assert "SECRET" not in str(pub)+++def test_trading212_nonpaper_order_attempts_refused_before_config_checks() -> None:+ cfg = t212.Trading212Config(profile="live-readonly")++ placed = t212.place_order(cfg, symbol="AAPL_US_EQ", side="buy", quantity=1)+ cancelled = t212.cancel_order(cfg, "order-1", symbol="AAPL_US_EQ")++ assert placed["status"] == "error"+ assert cancelled["status"] == "error"+ assert "not supported for live/read-only profiles" in placed["error"]+ assert "not supported for live/read-only profiles" in cancelled["error"]+ assert "not configured" not in placed["error"]+ assert "not configured" not in cancelled["error"]+++def test_trading212_service_order_attempts_refuse_readonly_profile() -> None:+ placed = service.place_order("AAPL_US_EQ", "trading212-live-sdk-readonly", side="buy", quantity=1)+ cancelled = service.cancel_order("order-1", "trading212-live-sdk-readonly", symbol="AAPL_US_EQ")++ assert placed["status"] == "error"+ assert cancelled["status"] == "error"+ assert "does not support orders.place" in placed["error"]+ assert "does not support orders.cancel" in cancelled["error"]+++def test_trading212_paper_order_attempts_still_readonly() -> None:+ cfg = t212.Trading212Config(profile="paper", api_key="practice-key")+ result = t212.place_order(cfg, symbol="AAPL_US_EQ", side="buy", quantity=1)+ assert result["status"] == "error"+ assert "read-only" in result["error"]+++def test_trading212_instrument_metadata_filter(monkeypatch) -> None:+ def fake_request(config, method, path, *, params=None):+ assert path == "/api/v0/equity/metadata/instruments"+ return [+ {"ticker": "AAPL_US_EQ", "name": "Apple", "currencyCode": "USD", "isin": "US0378331005"},+ {"ticker": "VODl_EQ", "name": "Vodafone", "currencyCode": "GBP", "isin": "GB00BH4HKS39"},+ ]++ monkeypatch.setattr(t212, "_request", fake_request)++ result = t212.get_instrument_metadata(t212.Trading212Config(api_key="key"), ticker="aapl_us_eq")+ assert result["status"] == "ok"+ assert result["instruments"] == [+ {+ "ticker": "AAPL_US_EQ",+ "name": "Apple",+ "short_name": None,+ "isin": "US0378331005",+ "type": None,+ "currency": "USD",+ "exchange": None,+ "working_schedule_id": None,+ "max_open_quantity": None,+ "min_trade_quantity": None,+ "added_on": None,+ }+ ]