How to Handle API Token Expiry in Zerodha KiteConnect

To handle API token expiry in Zerodha KiteConnect, you must generate a new access token daily. This process can be automated using scripts with libraries like Selenium to programmatically log in, handle 2FA, and retrieve the new token for your trading algorithm.

TrustyBull Editorial 5 min read

That Awful Feeling: When Your Trading Algorithm Suddenly Stops

Did you know that algorithms now account for over half of all trades placed on Indian stock exchanges? This is the core of what is sebi-regulations">algorithmic trading in India: using computer programs to execute trades at speeds and scales humans cannot match. You have spent weeks building your strategy, testing it, and finally deploying it. It works perfectly. Then, one morning, at 9:17 AM, it just stops. No orders, no updates. Just silence. The culprit is almost always the same: an expired API token.

This daily ritual of generating a new token is a common frustration for every algorithmic trader using Zerodha's KiteConnect API. Your code is perfect, but without a valid key, the door to the exchange is locked. Let's break down why this happens and, more importantly, how you can solve it for good.

What is a Zerodha API Token and Why Must It Expire?

Think of accessing your demat-and-trading-accounts/essential-documents-nri-demat-account-opening">trading account via an API like entering a high-security hotel. You can't just walk in. You need a series of credentials, each with a specific purpose.

  • API Key & API Secret: These are like your permanent identity card and a secret password. You show them to the hotel receptionist to prove who you are. They never change and must be kept extremely secret.
  • Request Token: After verifying your identity, the receptionist gives you a temporary, one-time pass. You take this pass to a special machine to get your room key. This pass is only valid for a few minutes.
  • Access Token: This is your actual room key. It lets you open the door to your room (place trades, get market data) for the rest of the day. But at midnight, it stops working.

The access token is what your algorithm uses for every single API call. Zerodha enforces a strict daily expiry policy on these tokens for a very important reason: security. If your access token were ever accidentally leaked, a malicious actor could control your trading account. By making it expire every day, the window of opportunity for any potential misuse is limited to just a few hours. It’s a security feature, not a bug, even if it feels inconvenient.

The Manual Fix: Your Daily Morning Chore

If you are just starting, you are likely generating your access token manually every morning before the market opens. The process is straightforward but repetitive and prone to error when you're in a hurry.

  1. You construct a special login URL using your API Key.
  2. You open this URL in a browser and log in with your Zerodha username, password, and two-factor authentication (2FA) code.
  3. After a successful login, Zerodha redirects you back to your specified redirect URL. Appended to this URL is a fresh request token.
  4. You must quickly copy this request token from the browser's address bar.
  5. Your code then takes this request token, combines it with your API Key and a hashed version of your API Secret (a checksum), and makes a final API call to Zerodha.
  6. In return, you finally receive the holy grail: a valid access token that works until midnight.

Doing this every single day is tedious. It means you can't run your algorithm if you're away from your computer. It introduces a point of failure right at the most critical time of the trading day.

Automating Your Zerodha Login for Uninterrupted Trading

The real solution to token expiry is automation. You need to write a script that performs the manual login process for you. This is a common practice among developers and involves using tools that can control a web browser programmatically.

The most popular tools for this job are libraries like Selenium or Puppeteer. They allow your code to open a browser, find the username and password fields, type in your credentials, and click the login button, just like a human would.

A High-Level Look at the Automation Script

Your automation script will need to perform these steps in sequence:

  1. Launch a Browser: Use Selenium to open a Chrome or Firefox window and navigate to the KiteConnect login URL.
  2. Enter Credentials: The script finds the HTML elements for the username and password fields and enters your credentials.
  3. Handle 2FA/TOTP: This is the trickiest part. Zerodha uses Time-based One-Time Passwords (TOTP). Your script can't just wait for you to type it in. You need to use a library (like `pyotp` in Python) with your original TOTP secret key to generate the current 6-digit code and enter it automatically.
  4. Capture the Request Token: After the script successfully logs in, it will be redirected. The script needs to wait for this redirection and parse the URL to extract the new request token.
  5. Generate the Access Token: With the request token in hand, the script uses the standard KiteConnect API library functions to exchange it for the final access token.
  6. Store the Token: The script should save the new access token to a simple text file, a database, or another secure location. Your main trading algorithm will then read this token when it starts up.

By scheduling this script to run automatically every morning at, say, 8:30 AM, you ensure a fresh, valid token is always ready before the market opens at 9:15 AM. Your trading algorithm becomes truly autonomous.

Best Practices for Securely Managing Your API Credentials

Automating your login involves handling your most sensitive information. You must do it securely.

  • Never Hardcode Credentials: Do not write your username, password, or API secret directly in your code. Use environment variables or a configuration file that is kept separate and secure.
  • Protect Your TOTP Secret: The secret key for your 2FA is extremely powerful. Store it securely, just like your password. Anyone with this key can generate your login codes.
  • Implement Error Handling: What if the login fails? Zerodha might change its login page, or your internet might be down. Your script should have robust error handling that immediately alerts you (via email, SMS, or a Telegram message) if it fails to generate a new token.
  • Run on a Secure Machine: The computer or server that runs your automation script should be secure, updated, and protected by a firewall.

What is Algorithmic Trading in India: The Rules

When you start automating trading, it's natural to wonder about the rules. Algorithmic trading in India is regulated by the fii-and-dii-flows/sebi-role-regulating-fii-dii-flows">savings-schemes/scss-maximum-investment-limit">investment-decisions-financial-sector-stocks">Securities and Exchange Board of India (SEBI). For large institutions, the rules are very strict, requiring exchange approvals and regular audits.

However, for retail traders like you using a broker's official API like KiteConnect, the situation is much simpler. The broker (Zerodha) is responsible for ensuring that the API infrastructure complies with all of SEBI's and the exchange's regulations. By using their provided API, you are operating within a pre-approved framework. Your main responsibility is to manage your own risk and ensure your credentials are not compromised. For more details on the framework, you can refer to the nifty-and-sensex/nifty-sectoral-indices-constructed-represent">National Stock Exchange's overview on algorithmic trading.

Tackling API token expiry is a rite of passage for every new algo trader. While it seems like a roadblock, it teaches you valuable lessons about security and automation. By building a reliable, automated login script, you remove a major point of failure and make your trading system more robust and truly independent.

Frequently Asked Questions

How long does a Zerodha KiteConnect access token last?
A Zerodha KiteConnect access token is valid only for a single day. It is generated after a successful login and expires at midnight on the same day.
Is it legal to automate the login process for Zerodha?
Yes, automating the login process to fetch an access token is a common practice among algorithmic traders. However, you are fully responsible for the security of your account credentials and the actions your script takes.
Can I use the same access token on multiple computers or scripts?
Yes, an access token is not tied to a specific IP address or machine. Once generated, you can use it in any script or on any computer until it expires. However, for security reasons, it is best to limit its exposure.
What happens if my automation script fails to get a new token?
If your script fails to generate a new access token, your main trading algorithm will not be able to connect to the KiteConnect API. It will fail to place orders, modify positions, or receive market data. It is crucial to have alerts set up to notify you of any such failures.