In algorithmic trading, "latency" is the boogeyman. It is the invisible tax on every trade. If you are seeing a price that is 500 milliseconds old, you are not trading the market; you are trading a ghost.
One of the most common mistakes amateur quant developers make is relying on REST APIs for market data, instead of WebSockets. Let's break down why this choice determines whether your strategy succeeds or fails.
The Analogy: Asking vs. Listening
Imagine you are waiting for a package delivery.
- REST API (Polling): You walk to the door, open it, check if the package is there, close the door, and walk back to the couch. You repeat this every 1 second. Ideally, you might miss the delivery driver by 0.9 seconds.
- WebSocket (Streaming): You install a doorbell. You sit on the couch and wait. As soon as the driver arrives, the bell rings, and you open the door immediately.
REST is "Request-Response." You ask, the server answers.
WebSocket is "Full-Duplex." You open a connection once, and the server pushes data to you whenever
it changes.
The Technical Overhead
Every HTTP request (REST) involves a "handshake." Your computer has to say "Hello," negotiate security (SSL/TLS), send the request headers, wait for the server to process, and get the response.
This handshake takes time—often 50ms to 200ms depending on your internet. If you are polling every 1 second, you are wasting massive bandwidth and CPU cycles just establishing connections.
With a WebSocket, the handshake happens once. After that, the connection stays open. Data frames flow freely with almost zero overhead.
Real World Impact on Slippage
Let's say NIFTY jumps 50 points in 2 seconds (a spike).
Scenario A: REST Polling (1 sec interval)
- 10:00:00: Price 18000. No Signal.
- 10:00:01: Price 18050. Signal Triggered! Order sent.
- Result: You enter at 18052 (including slippage). You missed the entire move.
Scenario B: WebSocket Stream
- 10:00:00.100: Price 18010. Update received.
- 10:00:00.200: Price 18020. Signal Triggered! Order sent.
- Result: You enter at 18022. You captured 28 points of the move that the REST
trader missed.
Code Comparison (Python)
The Wrong Way (REST)
import time
import requests
while True:
price = requests.get("https://api.broker.com/nifty").json()['ltp']
if price > 18000:
buy()
time.sleep(1) # painful delay
The Right Way (WebSocket)
import websockets
import asyncio
async def listen():
async with websockets.connect("wss://api.broker.com/stream") as ws:
async for msg in ws:
data = json.loads(msg)
if data['ltp'] > 18000:
await buy() # Instant reaction
Conclusion
If you are building a scalper or any strategy that relies on price execution, REST is dead. You must upgrade to an event-driven architecture powered by WebSockets.
At AlgoDevStudio, our Quick Scalper and OMS come with pre-built, optimized WebSocket engines that handle connection drops and reconnections automatically. Stop asking for price; let the price come to you.