{"record":{"id":"00a7569718cfb4b2","repo":"nautechsystems/nautilus_trader","slug":"failed-to-connect-binance-futures-market-websocket","errorCode":null,"errorMessage":"failed to connect Binance Futures market WebSocket: {e}","messagePattern":"failed to connect Binance Futures market WebSocket: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"critical","filePath":"crates/adapters/binance/src/futures/data.rs","lineNumber":1533,"sourceCode":"        self.cancellation_token = CancellationToken::new();\n\n        Self::refresh_instrument_catalogue(\n            &self.http_client,\n            &self.config.instrument_provider,\n            &self.instruments,\n            &self.status_cache,\n            &self.ws_client,\n            &self.ws_public_client,\n            &self.data_sender,\n            self.clock,\n            false,\n        )\n        .await?;\n\n        log::info!(\"Connecting to Binance Futures market WebSocket...\");\n        self.ws_client.connect().await.map_err(|e| {\n            log::error!(\"Binance Futures market WebSocket connection failed: {e:?}\");\n            anyhow::anyhow!(\"failed to connect Binance Futures market WebSocket: {e}\")\n        })?;\n        log::info!(\"Binance Futures market WebSocket connected\");\n\n        log::info!(\"Connecting to Binance Futures public WebSocket...\");\n        self.ws_public_client.connect().await.map_err(|e| {\n            log::error!(\"Binance Futures public WebSocket connection failed: {e:?}\");\n            anyhow::anyhow!(\"failed to connect Binance Futures public WebSocket: {e}\")\n        })?;\n        log::info!(\"Binance Futures public WebSocket connected\");\n\n        // Spawn market stream handler\n        let stream = self.ws_client.stream();\n        let sender = self.data_sender.clone();\n        let insts = self.instruments.clone();\n        let ws_insts = self.ws_client.instruments_cache();\n        let buffers = self.book_buffers.clone();\n        let book_subs = self.book_subscriptions.clone();\n        let l1_book_subs = self.l1_book_subscriptions.clone();","sourceCodeStart":1515,"sourceCodeEnd":1551,"githubUrl":"https://github.com/nautechsystems/nautilus_trader/blob/a4b06ed870971b5671d12754ea138a3ab99b1dec/crates/adapters/binance/src/futures/data.rs#L1515-L1551","documentation":"Raised during `connect()` when the Binance Futures market WebSocket client fails to establish its connection; the underlying transport error is wrapped with anyhow and also logged at ERROR level (`Binance Futures market WebSocket connection failed: {e:?}`) just above. Because this sits in the data client's connect sequence (after the instrument catalogue refresh), the whole connect fails and no streams start. The real cause is in the wrapped error: DNS/TLS/network failure, a firewall or proxy blocking wss, Binance rejecting the handshake, region-restricted access, or an endpoint/credential mismatch such as production keys against a testnet URL.","triggerScenarios":"Engine connect with the Binance Futures data client while: the host (fstream.binance.com / testnet stream.binancefuture.com) is unreachable or DNS fails; a corporate firewall blocks outbound wss; the client IP is in a region Binance blocks for futures; an authenticated handshake fails (invalid API key/secret, key without futures permission, clock skew breaking signature); the `testnet` flag does not match the configured keys.","commonSituations":"US-based developer hitting Binance global futures endpoints (geo-blocked); testnet flag flipped but production keys kept; keys created for spot only; running in Docker/CI without network egress; transient Binance WebSocket outage or maintenance.","solutions":["Read the wrapped `{e}` in the log line above to identify the true cause (DNS vs TLS vs HTTP 401/403 vs timeout)","Fix environment: ensure wss://fstream.binance.com (or the testnet host) is reachable from the host, open firewall/proxy, set HTTPS_PROXY if a proxy is required","If the error is auth/region related (401/403): verify api_key/api_secret, enable futures permission on the key, and make sure testnet=True matches testnet keys","Retry connect with exponential backoff for transient outages instead of crashing the node"],"exampleFix":"# before: single connect attempt, any hiccup kills startup\nawait node.run()  # connect raises: failed to connect Binance Futures market WebSocket: {e}\n\n# after: correct environment matching + retry with backoff, abort on auth errors\nconfig = BinanceFuturesDataClientConfig(\n    api_key=os.environ['BINANCE_API_KEY'],\n    api_secret=os.environ['BINANCE_API_SECRET'],\n    testnet=True,  # must match the environment your keys belong to\n)\nfor attempt in range(6):\n    try:\n        await node.run()\n        break\n    except Exception as e:\n        msg = str(e)\n        if '401' in msg or '403' in msg or 'signature' in msg.lower():\n            raise RuntimeError('Binance auth/region problem: check keys, futures permission, testnet flag') from e\n        await asyncio.sleep(min(2 ** attempt, 30))","handlingStrategy":"retry","validationCode":"import socket\n\ndef binance_ws_reachable(host: str = 'fstream.binance.com', port: int = 443, timeout: float = 5.0) -> bool:\n    \"\"\"Preflight: can this host open a TCP connection to the WS endpoint?\"\"\"\n    try:\n        with socket.create_connection((host, port), timeout=timeout):\n            return True\n    except OSError:\n        return False\n\nif not binance_ws_reachable():\n    raise RuntimeError('fstream.binance.com unreachable — fix network/firewall/region before starting the client')","typeGuard":null,"tryCatchPattern":"# transient WS failures: retry the full connect with backoff; abort on auth/region causes\nlast = None\nfor attempt in range(6):\n    try:\n        await node.run()  # data client connect happens here\n        break\n    except Exception as e:\n        if 'failed to connect Binance Futures market WebSocket' not in str(e):\n            raise\n        last = e\n        if any(tok in str(e) for tok in ('401', '403', 'signature', 'Unauthorized')):\n            raise RuntimeError('Binance rejected the WS handshake: check keys, futures permission, testnet flag, region access') from e\n        await asyncio.sleep(min(2 ** attempt, 30))\nelse:\n    raise last","preventionTips":["Match the testnet flag to the environment your API keys belong to before starting the node","Verify the API key has futures enabled and the system clock is NTP-synced (skew breaks signatures)","Check egress to fstream.binance.com:443 (wss) from the runtime host — containers and CI often block it","Log the wrapped {e:?} line — it distinguishes DNS/TLS failures from Binance handshake rejections"],"tags":["binance","futures","websocket","connection","network"],"backgroundTag":"websocket-connection-failed","analyzedSha":"a4b06ed870971b5671d12754ea138a3ab99b1dec","analyzedAt":"2026-08-16T22:54:50.089Z","schemaVersion":2},"datasetVersion":"2026-08-16T23:17:17.608Z"}