HKUDS/Vibe-Trading · error · Trading212APIError

Trading 212 request failed

Error message

Trading 212 request failed: {exc}

What it means

Raised by _request when the underlying requests HTTP call raises RequestException — DNS failure, connection refused, timeout (config.timeout), TLS errors, etc. The original exception is chained for diagnosis.

Solutions

  1. Check the chained exception message for the concrete cause (DNS, refused, timeout)
  2. Verify config.base_url is correct and reachable (curl it from the same host)
  3. Increase config.timeout if the cause is a timeout
  4. Fix proxy/firewall/VPN rules if connectivity is blocked; add retry with backoff for transient failures

Example fix

# before
config = load_config()  # base_url = "https://api.trading212.example"
# after: set the correct base_url and a larger timeout
config = replace(config, base_url="https://api.trading212.com", timeout=30)
save_config(config)
Defensive patterns

Strategy: retry

Validate before calling

import socket
from urllib.parse import urlsplit

def base_url_reachable(base_url: str, timeout: float = 5.0) -> bool:
    parts = urlsplit(base_url)
    try:
        socket.create_connection((parts.hostname, parts.port or 443), timeout=timeout).close()
    except OSError:
        return False
    return True

Try / catch

try:
    data = get_account_snapshot(config)
except Trading212APIError as exc:
    if not str(exc).startswith("Trading 212 request failed"):
        raise  # not a transport error
    logger.warning("transport error, retrying: %s", exc)
    data = get_account_snapshot(config)  # or backoff loop

Prevention

When it happens

Trigger: Any _get call when config.base_url is unreachable or wrong (DNS failure, wrong host, https vs http mismatch), the network is down, a proxy blocks the request, or the server takes longer than config.timeout to respond.

Common situations: Typo in base_url in the saved config; corporate proxy/VPN blocking api.trading212.com; sandbox vs production URL mix-up; timeout too small for slow account endpoints; intermittent connectivity in CI.

Related errors


AI-assisted analysis of HKUDS/Vibe-Trading@80ffdda44c (2026-08-28). Data as JSON: /api/errors/17a0bc0621075cfa. Report an issue: GitHub.

Appendix: source

Thrown at agent/src/trading/connectors/trading212/sdk.py:427

    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"

View on GitHub (pinned to 80ffdda44c)