REST APIs work fine for most trading bot operations. WebSocket is what you need when fine-grained order book or trade data matters in real time. This article walks through what WebSocket is, when to use it on LMEX, and how to build a reliable Python client that survives the inevitable disconnections.
For most retail strategies, REST is sufficient. You poll the order book every few seconds, place orders when conditions trigger, and check positions periodically. Total latency: 100-300ms per cycle. Fine for trend following, mean reversion, DCA, grid trading.
WebSocket becomes necessary for:
If your strategy doesn't fit one of those categories, WebSocket adds complexity without meaningful benefit. Stick with REST.
LMEX exposes WebSocket endpoints at `wss://ws.lmex.io` (production) and `wss://testnet.lmex.io/ws` (testnet). The protocol is JSON-based: send subscription messages, receive streaming updates.
Available channels:
For most use cases, you want `orderBookL2` + `trade` (for market data) and `userInfo` (for your own state).
The simplest path is using `ccxt.pro` (the async version of CCXT) which handles the protocol details. The bare-bones version:
This prints the best bid/ask spread every time the order book updates — typically 5-20 times per second on active markets.
For a more useful real implementation, subscribe to multiple streams simultaneously:
Three concurrent subscriptions, all running until the process stops. `latest_book` and `latest_trade` are always current; your strategy logic reads from these instead of polling REST.
The example above looks robust because of the try/except blocks. In practice, those catch transient errors but not all of them. A few failure modes to plan for:
**Silent disconnections.** The TCP connection is still open but the server stopped sending data. Detection: track the timestamp of the last message. If more than 30 seconds elapse without an update on an active channel, treat it as disconnected and force a reconnect.
**Authentication expiry.** Auth tokens have lifetimes. After ~24 hours, you may need to re-authenticate. ccxt.pro handles this automatically for most exchanges, but verify by leaving the bot running for 48 hours and checking it still receives data.
**Order book gaps.** With L2 streaming, you receive a snapshot followed by incremental deltas. If a delta gets lost, your local book diverges from the exchange's. Solution: periodically refresh by re-subscribing (effectively forcing a new snapshot). Once a minute is reasonable for non-HFT use.
**Exchange downtime.** LMEX occasionally has maintenance windows. Your bot should detect this (no order book updates, or specific error codes) and pause new orders until service resumes.
The skeleton above is the foundation. Production code needs:
**Persistent state.** Save the latest order book and recent trades to disk periodically. On restart, restore state so the bot doesn't start completely blind.
**Health monitoring.** Track latency between exchange events and local processing. If latency creeps up past expected thresholds, alert.
**Proper logging.** Every order placed, fill received, error encountered. Structured JSON logging makes post-mortem analysis tractable.
**Graceful shutdown.** Cancel open orders on shutdown, save state, close connections cleanly. The default behaviour on Ctrl+C leaves orders open and disconnects abruptly.
These together add another 500-1000 lines of code. The 50-line skeleton is for proving the concept. The 1500-line production version is what runs real money.
For a market-making strategy on BTC-PERP:
The WebSocket version reacts ~16x faster. For market making, that translates to better fills, less adverse selection, and meaningfully higher returns. For trend following, it translates to almost nothing useful.
Q: Can I run WebSocket from a residential connection?
Yes, but expect occasional reconnects from your ISP's NAT behaviour. Production WebSocket strategies generally run from VPS instances with stable connections.
Q: Does LMEX charge for WebSocket usage?
No additional charges. The same API key works for both REST and WebSocket. Rate limits are generally generous — you'd have to deliberately abuse the connection to hit them.
Q: Is ccxt.pro a free library?
It's a paid commercial library, but there's a free public version of CCXT (without `.pro`) that handles REST only. For WebSocket without ccxt.pro, you can use libraries like `websockets` or `websocket-client` directly with LMEX's WebSocket protocol.
Q: Should I use one connection for multiple symbols or separate?
One connection with multiple subscriptions is more efficient than parallel connections. ccxt.pro handles this transparently — just call `watch_*` on different symbols and they share the underlying connection.