{"id":9870,"library":"kiteconnect","title":"Kite Connect Python Client","description":"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.","status":"active","version":"5.1.0","language":"en","source_language":"en","source_url":"https://github.com/zerodha/pykiteconnect","tags":["trading","fintech","stocks","zerodha","api-client"],"install":[{"cmd":"pip install kiteconnect","lang":"bash","label":"Install latest version"}],"dependencies":[{"reason":"Used for making HTTP requests to the Kite Connect API.","package":"requests","optional":false}],"imports":[{"symbol":"KiteConnect","correct":"from kiteconnect import KiteConnect"},{"symbol":"KiteTicker","correct":"from kiteconnect import KiteTicker"},{"note":"Exceptions are in `kiteconnect.exceptions` submodule, not directly under `kiteconnect`.","wrong":"from kiteconnect import TokenException","symbol":"TokenException","correct":"from kiteconnect.exceptions import TokenException"}],"quickstart":{"code":"import os\nfrom kiteconnect import KiteConnect\n\n# Retrieve API credentials and tokens from environment variables for security\n# In a real application, you'd securely fetch and store these.\napi_key = os.environ.get(\"KITE_API_KEY\", \"YOUR_API_KEY\")\napi_secret = os.environ.get(\"KITE_API_SECRET\", \"YOUR_API_SECRET\")\n# The request_token is obtained after the user logs in via the login_url.\nrequest_token = os.environ.get(\"KITE_REQUEST_TOKEN\", \"YOUR_REQUEST_TOKEN\")\n# The access_token is generated once per request_token and can be reused until expiry.\naccess_token = os.environ.get(\"KITE_ACCESS_TOKEN\", \"YOUR_GENERATED_ACCESS_TOKEN\")\n\n# Initialize KiteConnect client\nkc = KiteConnect(api_key=api_key)\n\n# --- Authentication Flow --- \n# 1. Get login URL (one-time step for user login)\n# login_url = kc.login_url()\n# print(f\"Please login to Kite via this URL: {login_url}\")\n# User logs in, gets redirected with a request_token in the URL parameters.\n\n# 2. Generate session (one-time step per request_token)\n# try:\n#     # This exchanges the request_token for an access_token\n#     session_data = kc.generate_session(request_token, api_secret=api_secret)\n#     access_token = session_data[\"access_token\"]\n#     print(f\"New Access Token generated: {access_token}\")\n#     # Store this access_token securely for future use\n#     kc.set_access_token(access_token)\n# except Exception as e:\n#     print(f\"Error generating session: {e}\")\n#     print(\"Ensure KITE_API_KEY, KITE_API_SECRET, and KITE_REQUEST_TOKEN are correct.\")\n\n# --- Example API Calls (assuming access_token is already valid) ---\n# For a quick run, ensure KITE_ACCESS_TOKEN is set in your environment\nif access_token and access_token != \"YOUR_GENERATED_ACCESS_TOKEN\":\n    kc.set_access_token(access_token)\n    try:\n        profile = kc.profile()\n        print(f\"Successfully authenticated. User: {profile['user_name']}\")\n        # Fetch user's holdings\n        holdings = kc.holdings()\n        print(f\"Fetched {len(holdings)} holdings.\")\n        # Fetch instruments\n        instruments = kc.instruments(\"NSE\")\n        print(f\"Fetched {len(instruments)} NSE instruments (first 5):\\n{instruments[:5]}\")\n    except Exception as e:\n        print(f\"API call failed. Ensure KITE_ACCESS_TOKEN is valid and not expired: {e}\")\nelse:\n    print(\"Please set KITE_API_KEY and KITE_ACCESS_TOKEN environment variables,\")\n    print(\"or uncomment the authentication flow to generate a new access token.\")","lang":"python","description":"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."},"warnings":[{"fix":"Implement a robust re-authentication mechanism in your application, which might involve redirecting the user to the login URL or managing token refreshes if supported by the API.","message":"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`.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Avoid repeatedly calling `generate_session` with the same `request_token` or storing a `request_token` for reuse. Store and reuse the `access_token` instead.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Implement proper rate limiting and exponential backoff mechanisms in your client code. Use `KiteTicker` for real-time data instead of repeatedly polling API endpoints for quotes.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always refer to the official `kiteconnect` documentation for the version you are using. Upgrade to the latest version (5.x.x) for the most current API and follow its documentation.","message":"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.","severity":"breaking","affected_versions":"< 5.0.0"}],"env_vars":null,"last_verified":"2026-04-17T00:00:00.000Z","next_check":"2026-07-16T00:00:00.000Z","problems":[{"fix":"Ensure 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.","cause":"The `request_token` provided to `generate_session` is invalid, expired, or already used. Alternatively, the `api_key` used to initialize `KiteConnect` is incorrect.","error":"kiteconnect.exceptions.TokenException: Invalid `request_token` or `api_key`."},{"fix":"Double-check your `api_key` and `api_secret` in your Kite Connect developer dashboard. Ensure there are no leading/trailing spaces or typos.","cause":"The `api_key` used during `KiteConnect` initialization or the `api_secret` passed to `generate_session` is incorrect or malformed.","error":"kiteconnect.exceptions.InputException: Invalid `api_key` or `api_secret`."},{"fix":"Handle exceptions from `generate_session` more specifically (e.g., `TokenException`, `InputException`). Ensure all authentication parameters are correct and the `request_token` is fresh and unused.","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`.","error":"KeyError: 'access_token' (when calling generate_session)"},{"fix":"You 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()`.","cause":"The `access_token` you are using to make API calls has expired. Access tokens typically have a limited lifespan (e.g., 24 hours).","error":"kiteconnect.exceptions.TokenException: Session expired. Please login again."}]}