Kite Connect Python Client
The `kiteconnect` library is the official Python client for the Kite Connect trading API by Zerodha. It provides comprehensive access to all Kite Connect APIs, including real-time market data, order placement, and portfolio management. Currently at version 5.1.0, it maintains an active release cadence with frequent minor and patch updates to support new API features and address bug fixes.
Common errors
-
kiteconnect.exceptions.TokenException: Invalid `request_token` or `api_key`.
cause The `request_token` provided to `generate_session` is invalid, expired, or already used. Alternatively, the `api_key` used to initialize `KiteConnect` is incorrect.fixEnsure you have the correct `api_key` from your Kite Connect app dashboard. Obtain a fresh `request_token` by redirecting the user through the `kc.login_url()` flow and ensure it's used only once. -
kiteconnect.exceptions.InputException: Invalid `api_key` or `api_secret`.
cause The `api_key` used during `KiteConnect` initialization or the `api_secret` passed to `generate_session` is incorrect or malformed.fixDouble-check your `api_key` and `api_secret` in your Kite Connect developer dashboard. Ensure there are no leading/trailing spaces or typos. -
KeyError: 'access_token' (when calling generate_session)
cause This usually indicates that `generate_session` failed, but the exception was caught, and the `session_data` dictionary doesn't contain the 'access_token' key. Common reasons include invalid `request_token`, `api_key`, or `api_secret`.fixHandle exceptions from `generate_session` more specifically (e.g., `TokenException`, `InputException`). Ensure all authentication parameters are correct and the `request_token` is fresh and unused. -
kiteconnect.exceptions.TokenException: Session expired. Please login again.
cause The `access_token` you are using to make API calls has expired. Access tokens typically have a limited lifespan (e.g., 24 hours).fixYou need to re-authenticate. This involves generating a new `request_token` via the `kc.login_url()` (user interaction) and then exchanging it for a new `access_token` using `kc.generate_session()`.
Warnings
- gotcha Access tokens generated via `generate_session` have a limited validity period (typically 24 hours). After expiration, API calls will fail with `TokenException`. You must re-authenticate to obtain a new `request_token` and then generate a new `access_token`.
- gotcha The `generate_session` method should only be called once per `request_token`. The `request_token` itself is single-use. After successfully generating an `access_token`, you should store it securely and use `kc.set_access_token(access_token)` for all subsequent API calls until the token expires.
- gotcha Kite Connect APIs have rate limits. Hitting these limits frequently can result in `TooManyRequestsException` or temporary IP blocking. Be mindful of your request frequency, especially for market data or bulk operations.
- breaking Older versions (pre-v3 or v3.x) might have slightly different constructor signatures or API method names. For example, direct passing of `api_secret` to `KiteConnect` constructor might have been removed, or specific parameters for `instruments()` changed.
Install
-
pip install kiteconnect
Imports
- KiteConnect
from kiteconnect import KiteConnect
- KiteTicker
from kiteconnect import KiteTicker
- TokenException
from kiteconnect import TokenException
from kiteconnect.exceptions import TokenException
Quickstart
import os
from kiteconnect import KiteConnect
# Retrieve API credentials and tokens from environment variables for security
# In a real application, you'd securely fetch and store these.
api_key = os.environ.get("KITE_API_KEY", "YOUR_API_KEY")
api_secret = os.environ.get("KITE_API_SECRET", "YOUR_API_SECRET")
# The request_token is obtained after the user logs in via the login_url.
request_token = os.environ.get("KITE_REQUEST_TOKEN", "YOUR_REQUEST_TOKEN")
# The access_token is generated once per request_token and can be reused until expiry.
access_token = os.environ.get("KITE_ACCESS_TOKEN", "YOUR_GENERATED_ACCESS_TOKEN")
# Initialize KiteConnect client
kc = KiteConnect(api_key=api_key)
# --- Authentication Flow ---
# 1. Get login URL (one-time step for user login)
# login_url = kc.login_url()
# print(f"Please login to Kite via this URL: {login_url}")
# User logs in, gets redirected with a request_token in the URL parameters.
# 2. Generate session (one-time step per request_token)
# try:
# # This exchanges the request_token for an access_token
# session_data = kc.generate_session(request_token, api_secret=api_secret)
# access_token = session_data["access_token"]
# print(f"New Access Token generated: {access_token}")
# # Store this access_token securely for future use
# kc.set_access_token(access_token)
# except Exception as e:
# print(f"Error generating session: {e}")
# print("Ensure KITE_API_KEY, KITE_API_SECRET, and KITE_REQUEST_TOKEN are correct.")
# --- Example API Calls (assuming access_token is already valid) ---
# For a quick run, ensure KITE_ACCESS_TOKEN is set in your environment
if access_token and access_token != "YOUR_GENERATED_ACCESS_TOKEN":
kc.set_access_token(access_token)
try:
profile = kc.profile()
print(f"Successfully authenticated. User: {profile['user_name']}")
# Fetch user's holdings
holdings = kc.holdings()
print(f"Fetched {len(holdings)} holdings.")
# Fetch instruments
instruments = kc.instruments("NSE")
print(f"Fetched {len(instruments)} NSE instruments (first 5):\n{instruments[:5]}")
except Exception as e:
print(f"API call failed. Ensure KITE_ACCESS_TOKEN is valid and not expired: {e}")
else:
print("Please set KITE_API_KEY and KITE_ACCESS_TOKEN environment variables,")
print("or uncomment the authentication flow to generate a new access token.")