Kite Connect Python Client

5.1.0 · active · verified Fri Apr 17

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `KiteConnect` client and perform basic API calls. It highlights the authentication flow, which involves obtaining a `request_token` from a login URL (user interaction) and then exchanging it for an `access_token` using `generate_session`. For subsequent API calls, only the `access_token` is needed. For runnable simplicity, it suggests setting `KITE_ACCESS_TOKEN` directly via environment variables if you have an already-generated valid token.

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.")

view raw JSON →