"Should my trading bot use WebSockets or REST?" gets asked a lot. Most answers online are unhelpful because they assume you are building an HFT system. Most retail trading bots are not HFT systems. Different rules apply.
Quick refresher on the difference:
REST is request-response. Your bot asks "what is the BTC-PERP price?" and the exchange responds. Each request opens a connection, transfers data, closes the connection. Easy to debug. Round-trip overhead means typical latencies of 50-200ms depending on geography.
WebSockets are streaming. Your bot opens one persistent connection and the exchange pushes data when it changes. Faster — typically sub-50ms from the event to your bot — and more efficient at scale. Harder to debug. Harder to handle when things go wrong, which they will.
That is the simple version. Real life is messier.
Most retail trading bots should use REST. Specifically:
If your strategy operates on candle closes or longer — 1 minute, 5 minutes, 1 hour — the 100ms latency difference between REST and WebSocket is completely irrelevant. The simpler approach wins.
For account state queries (position, balance, open orders), REST polling every few seconds works fine. These do not change tick-by-tick. Setting up WebSocket subscriptions just for these adds complexity for no benefit.
One-off operations — placing an order, cancelling, querying historical data — are inherently request-response. WebSocket here is more complex with zero upside.
And if you cannot guarantee server uptime, REST will save you weeks. WebSocket bots need disconnect handling, missed message recovery, snapshot reconciliation. REST bots just retry the failed request and move on.
A few cases where WebSocket is genuinely the better choice:
**Order book strategies that need every tick.** Market making, microstructure trades, order book imbalance — these need the book state current. Polling REST every 100ms misses ticks and gets rate-limited fast.
**Latency-sensitive momentum strategies.** Your strategy fires on a specific price level and the next 50ms matters. WebSocket is required.
**Many simultaneous market subscriptions.** Real-time data for 50 markets is 50 REST requests per second minimum. WebSocket bundles it over one connection.
**Real-time dashboards.** Anything human-facing where stale data feels wrong.
Serious trading systems use both. REST for what REST is good at, WebSocket for what WebSocket is good at:
The complexity of managing both is real but worth it. Fast where speed matters. Simple where simplicity matters.
If you are going to use WebSockets, do it properly. The minimum viable structure:
\`\`\`python
import websocket
import json
import threading
import time
class LMEXWebSocket:
def __init__(self, on_data):
self.on_data = on_data
self.ws = None
self.subscriptions = []
self.reconnect_delay = 1
self.running = True
def connect(self):
self.ws = websocket.WebSocketApp(
'wss://ws.lmex.io/ws/futures',
on_open=self.on_open,
on_message=self.on_message,
on_close=self.on_close,
on_error=self.on_error,
)
threading.Thread(target=self.ws.run_forever, daemon=True).start()
def on_open(self, ws):
self.reconnect_delay = 1
for sub in self.subscriptions:
ws.send(json.dumps({'op': 'subscribe', 'args': [sub]}))
def on_message(self, ws, message):
data = json.loads(message)
if 'topic' in data:
self.on_data(data)
def on_close(self, ws, code, reason):
if self.running:
time.sleep(self.reconnect_delay)
self.reconnect_delay = min(self.reconnect_delay * 2, 60)
self.connect()
def on_error(self, ws, error):
print(f'WS error: {error}')
def subscribe(self, topic):
self.subscriptions.append(topic)
if self.ws:
self.ws.send(json.dumps({'op': 'subscribe', 'args': [topic]}))
\`\`\`
The exponential backoff on reconnect (line 27) and resubscribe on connect (line 21) are the two things amateur implementations always miss. Without them, your bot silently stops receiving data after the first network blip and you do not notice for hours.
Q: Do I get rate-limited the same way on WebSocket and REST?
No. REST has per-second and per-minute request limits. WebSocket has subscription limits (how many topics per connection) and publish rate limits. For most bots, REST limits bite first.
Q: What happens when my WebSocket disconnects?
You stop receiving data. If your bot makes decisions assuming data is current, it will trade on stale information. Always check connection health before placing orders. If the last heartbeat is more than 5 seconds old, treat your data as stale and pause until reconnected.
Q: Can I place orders via WebSocket?
Yes, LMEX supports it. Slightly faster than REST. Debugging WebSocket order placement is harder. Stick with REST for orders unless you genuinely need the speed.
Q: How do I know if I am missing WebSocket messages?
Track sequence numbers. LMEX includes a sequence number on order book updates — if you receive N+2 without N+1, you missed a message. Recovery is to fetch a fresh snapshot via REST and reset local state. Bots that skip this gradually drift out of sync with reality and start making bad decisions.