Zerodha Kite Connect Python SDK
A comprehensive guide to integrating Zerodha's official Kite Connect Python SDK into your trading applications. Learn how to authenticate, place orders, fetch market data, and stream real-time ticks.

What you can build with Kite Connect
The Kite Connect Python SDK provides comprehensive access to Zerodha's trading infrastructure.
Session Management
Authenticate using API key and request token for secure access to trading APIs.
Order Placement
Place, modify, and cancel orders with full control over order parameters.
GTT Orders
Create and manage Good Till Triggered orders for automated trading.
Historical Data
Fetch OHLCV candle data for backtesting and technical analysis.
WebSocket Streaming
Subscribe to real-time tick data with efficient WebSocket streaming.
Portfolio Management
Access holdings, positions, and margins in real-time.
Installation
Install the required packages using pip. Make sure you have Python 3.7+ installed.
# Install the Kite Connect SDK
pip install kiteconnect
# Install optional dependencies for data analysis
pip install pandas
pip install requestskiteconnectOfficial Zerodha Kite Connect SDK
pandasFor data manipulation and analysis
requestsHTTP library for API calls
Authentication & Session
Initialize the SDK with your credentials and create a session using the login flow.
from kiteconnect import KiteConnect
import logging
logging.basicConfig(level=logging.DEBUG)
# Initialize with your API key
api_key = "your_api_key"
api_secret = "your_api_secret"
kite = KiteConnect(api_key=api_key)
# Login flow - Generate login URL
print(kite.login_url())
# After user login, get the request token from redirect URL
# and generate session
request_token = "request_token_from_redirect"
data = kite.generate_session(request_token, api_secret=api_secret)
# Save access token for future use
kite.set_access_token(data["access_token"])
# Get user profile
profile = kite.profile()
print(f"User ID: {profile['user_id']}")
print(f"Email: {profile['email']}")
# Get account margins
margins = kite.margins()
print(f"Available margin: {margins['equity']['available']['live_balance']}")Note: You can get your API key and secret from the Kite Connect developer console. The login flow requires user interaction to authorize your application.
Placing Orders
Execute trades programmatically with full control over order parameters.
# Place a regular market order
try:
order_id = kite.place_order(
variety=kite.VARIETY_REGULAR,
exchange=kite.EXCHANGE_NSE,
tradingsymbol="INFY",
transaction_type=kite.TRANSACTION_TYPE_BUY,
quantity=1,
product=kite.PRODUCT_CNC,
order_type=kite.ORDER_TYPE_MARKET
)
print(f"Order placed successfully. Order ID: {order_id}")
except Exception as e:
print(f"Order placement failed: {e}")
# Place a limit order
try:
order_id = kite.place_order(
variety=kite.VARIETY_REGULAR,
exchange=kite.EXCHANGE_NSE,
tradingsymbol="RELIANCE",
transaction_type=kite.TRANSACTION_TYPE_BUY,
quantity=1,
product=kite.PRODUCT_CNC,
order_type=kite.ORDER_TYPE_LIMIT,
price=2500.00
)
print(f"Limit order placed. Order ID: {order_id}")
except Exception as e:
print(f"Order placement failed: {e}")GTT (Good Till Triggered) Orders
Create automated orders that trigger when your specified price conditions are met.
# Create a GTT (Good Till Triggered) order
try:
# Single trigger GTT
trigger_values = {
"tradingsymbol": "SBIN",
"exchange": "NSE",
"trigger_values": [300],
"last_price": 290,
"orders": [{
"transaction_type": "BUY",
"quantity": 1,
"product": "CNC",
"order_type": "LIMIT",
"price": 301
}]
}
gtt_id = kite.place_gtt(
trigger_type=kite.GTT_TYPE_SINGLE,
tradingsymbol=trigger_values["tradingsymbol"],
exchange=trigger_values["exchange"],
trigger_values=trigger_values["trigger_values"],
last_price=trigger_values["last_price"],
orders=trigger_values["orders"]
)
print(f"GTT Order ID: {gtt_id}")
except Exception as e:
print(f"GTT creation failed: {e}")
# Get all GTT orders
gtts = kite.get_gtts()
print(f"Active GTT orders: {len(gtts)}")Historical Data & Market Quotes
Fetch historical OHLCV data and real-time quotes for analysis.
from datetime import datetime, timedelta
# Fetch historical data
try:
# Get instrument token for the symbol
instruments = kite.instruments("NSE")
instrument_token = None
for instrument in instruments:
if instrument["tradingsymbol"] == "RELIANCE":
instrument_token = instrument["instrument_token"]
break
if instrument_token:
# Fetch OHLC data
from_date = datetime.now() - timedelta(days=7)
to_date = datetime.now()
historical_data = kite.historical_data(
instrument_token=instrument_token,
from_date=from_date,
to_date=to_date,
interval="day"
)
print(f"Fetched {len(historical_data)} candles")
print(historical_data[0]) # First candle
except Exception as e:
print(f"Historical data fetch failed: {e}")
# Get quote for multiple instruments
quotes = kite.quote(["NSE:INFY", "NSE:RELIANCE", "NSE:TCS"])
for symbol, data in quotes.items():
print(f"{symbol}: LTP = {data['last_price']}")WebSocket Streaming
Subscribe to real-time market data using WebSocket for low-latency tick updates.
from kiteconnect import KiteTicker
# Initialize ticker
kws = KiteTicker(api_key, access_token)
def on_ticks(ws, ticks):
# Callback for tick reception
for tick in ticks:
print(f"Symbol: {tick['instrument_token']}")
print(f"LTP: {tick['last_price']}")
print(f"Volume: {tick['volume']}")
def on_connect(ws, response):
# Callback on successful connect
print("Connected to WebSocket")
# Subscribe to instruments
# NSE:INFY, NSE:RELIANCE
ws.subscribe([738561, 2885633])
# Set mode to full (LTP + Market depth + OI)
ws.set_mode(ws.MODE_FULL, [738561, 2885633])
def on_close(ws, code, reason):
print(f"Connection closed: {code} - {reason}")
ws.stop()
def on_error(ws, code, reason):
print(f"Error: {code} - {reason}")
# Assign callbacks
kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.on_close = on_close
kws.on_error = on_error
# Start the WebSocket connection
kws.connect(threaded=True)Portfolio Management
Access your holdings, positions, and order history programmatically.
# Get holdings
holdings = kite.holdings()
for holding in holdings:
print(f"{holding['tradingsymbol']}: {holding['quantity']} shares")
print(f"P&L: ₹{holding['pnl']}")
# Get positions
positions = kite.positions()
# Day positions
for position in positions['day']:
print(f"{position['tradingsymbol']}: {position['quantity']}")
print(f"P&L: ₹{position['pnl']}")
# Net positions
for position in positions['net']:
print(f"{position['tradingsymbol']}: {position['quantity']}")
# Get order history
orders = kite.orders()
for order in orders:
print(f"Order ID: {order['order_id']}")
print(f"Status: {order['status']}")
print(f"Symbol: {order['tradingsymbol']}")Supported Exchanges & Instruments
Trade across multiple exchanges and instrument types using the Kite Connect SDK.
Prerequisites
Zerodha Trading Account
Active trading account with Zerodha
Kite Connect App
Register at Kite Connect for API credentials
Python 3.7+
Compatible Python installation
API Subscription
₹2000/month for Kite Connect access
Ready to start building?
Get your API credentials from the Kite Connect portal and start integrating today.