Introduction
Zerodha's Kite Connect API is arguably the most robust and widely used trading API in India. Designed around REST-like HTTP APIs and WebSockets, it provides retail traders and startups with institutional-grade access to the NSE, BSE, and MCX exchanges. In this tutorial, we will build a complete Python script to authenticate, subscribe to real-time data, and place a bracket order using Kite Connect.
1. App Creation and Authentication
To use Kite Connect, you must first create an app on the Kite developer console and pay the monthly subscription fee. You will receive an api_key and api_secret.
The OAuth Flow
from kiteconnect import KiteConnect
api_key = "your_api_key"
api_secret = "your_api_secret"
kite = KiteConnect(api_key=api_key)
print("Login URL:", kite.login_url())
# User logs in and gets a request token from the redirect URL
request_token = input("Enter the request_token from the URL: ")
data = kite.generate_session(request_token, api_secret)
kite.set_access_token(data["access_token"])
print("Authentication Successful!")
Key Takeaway: The access_token generated is valid for one day and expires at 6:00 AM the next day. Ensure your scripts save this token so you don't have to authenticate manually multiple times a day.
2. Streaming Live Data (Kite Ticker)
The KiteTicker class allows you to stream live ticks via WebSockets. It is highly optimized and can handle thousands of ticks per second.
graph LR;
A[Exchange Data] --> B[Zerodha Servers];
B -->|WebSocket Stream| C[Kite Ticker Python];
C --> D{On_Tick Callback};
D --> E[Strategy Logic];
from kiteconnect import KiteTicker
# Initialize Ticker
kws = KiteTicker(api_key, data["access_token"])
def on_ticks(ws, ticks):
# Callback to receive ticks
for tick in ticks:
print(f"Instrument: {tick['instrument_token']} LTP: {tick['last_price']}")
def on_connect(ws, response):
# Subscribe to an instrument token (e.g., 738561 for Reliance)
ws.subscribe([738561])
ws.set_mode(ws.MODE_FULL, [738561])
kws.on_ticks = on_ticks
kws.on_connect = on_connect
# Connect in the background
kws.connect(threaded=True)
3. Order Placement
Executing an order is straightforward. Here is an example of placing a simple regular market order.
try:
order_id = kite.place_order(
tradingsymbol="RELIANCE",
exchange=kite.EXCHANGE_NSE,
transaction_type=kite.TRANSACTION_TYPE_BUY,
quantity=1,
order_type=kite.ORDER_TYPE_MARKET,
product=kite.PRODUCT_MIS,
validity=kite.VALIDITY_DAY
)
print("Order placed successfully. ID:", order_id)
except Exception as e:
print("Order placement failed:", e)
Conclusion
The Zerodha Kite Connect API is a game-changer for automated trading in India. Its comprehensive documentation and stable infrastructure make it ideal for building algorithmic trading strategies. Combined with Python's data analysis libraries (Pandas, NumPy), the possibilities are endless.
Ready to Automate This?
We can build this exact logic for you, securely hosted on our servers.
Get a Free Quote