API Integration Guide: Connecting Python to Indian Brokers (Zerodha/Angel)"
API Integration Guide: Connecting Python to Indian Brokers (Zerodha/Angel)
For algorithmic traders in India, the ecosystem has exploded in the last 5 years.
Gone are the days of hacking together web scrapers.
Today, major brokers like Zerodha (Kite Connect), Angel One (SmartAPI), and Fyers offer robust REST APIs.
But connecting to them is not just about copying the sample code.
Sample code is for testing. Production code requires robust error handling, token management, and WebSocket resilience.
This guide covers the best practices for integrating Python bots with Indian broker APIs.
1. Authentication: The TOTP Challenge
Most Indian brokers now enforce 2FA (Two-Factor Authentication) using TOTP (Time-based One-Time Password) for login.
You cannot just send your password.
The Solution: pyotp library.
You need to extract the TOTP secret key (usually a QR code text) from your broker profile settings.
import pyotp
totp = pyotp.TOTP("YOURSECRETKEY")
current_otp = totp.now()
Send this OTP to the login endpoint
- li> Warning: Never hardcode your Secret Key. Store it in an environment variable or a
.env file.2. Token Management: The Daily Ritual
Indian broker APIs typically issue a access_token that is valid for one day only.
It expires every morning at around 7:30 AM or 8:30 AM.
The Mistake:
Manually logging in every morning to update the token in your code.
The Fix: Automated Login Script.
Your bot should have a startup routine that runs at 8:45 AM.
- li> Logs in using Selenium (headless browser) or the Login API.
- Generates a new
access_token.
- Saves the token to a local database (Redis/SQLite).
- All other scripts read the token from the database.
3. WebSocket Handling: The Heartbeat
REST APIs are for orders. WebSockets are for data.
You cannot poll the REST API for prices every second (you will hit rate limits). You must subscribe to the WebSocket stream.
Best Practice: The Reconnection Loop
WebSockets are unstable. They will disconnect.
If your code looks like this, it will fail:
def on_close(ws):
print("Closed")
It should look like this:
def on_close(ws):
print("Connection closed. Reconnecting in 5s...")
time.sleep(5)
connect() # Recursive reconnectionUse a library like
rel (Robust Event Loop) or asyncio to manage the connection state.
4. Rate Limiting: Respect the Traffic Light
Zerodha Kite: 3 requests / second.
Angel One: 10 requests / second.
If you blast 10 orders at once, 7 will be rejected.
The implementation:
Use a "Leaky Bucket" algorithm or a simple queue processing using Python's queue module.
Every API call goes into a queue. A separate worker thread consumes the queue at a fixed rate (e.g., time.sleep(0.34) between requests for Zerodha).
This guarantees zero 429 Too Many Requests errors.
5. Order Updates: Push vs. Pull
How do you know if your order was filled?
The Amateur Way:
Loop every second and call kite.orders(). This wastes your rate limit.
The Pro Way:
Use the Postback / Webhook feature.
Most brokers allow you to set A "Postback URL". When an order fills, their server sends a JSON payload to your server.
You need a small Flask/FastAPI server to listen for these updates.
Broker Server -> POST /webhook -> Your Bot Update
This is instant and uses zero API quota.
6. Multi-Broker Architecture?
Advanced setups often use multiple brokers.
- li> Zerodha for manual investing.
- Finvasia/Shoonya for API trading (Zero Brokerage).
Your strategy shouldn't know it's trading on Zerodha. It should send a generic order, which the Connectivity Layer translates into the Zerodha-specific API call.
Conclusion
APIs are powerful, but they are fragile.
Building a robust wrapper around the broker's API is the first step in building a reliable trading bot.
If you don't want to spend weeks handling TOTP secrets and WebSocket reconnects, consider hiring a specialist.
Internal Links:
- li> Service: Custom Development – We have pre-built wrappers for all Indian brokers.
- Technical: Python vs C++ – Language choices.
- Next step: Consultation – Get help with your API integration.
Need This Logic in Your Portfolio?
We don't just write about algorithms; we build them. Hire **Virexan Capital** to engineer your custom trading infrastructure.