Market Data & Web Scraping Intermediate

Automate Zerodha Kite Connect Daily Access Token & TOTP Generation in Python (pyotp)

Generate time-based 2FA TOTP codes using pyotp and manage daily Zerodha Kite Connect API `access_token` persistence in Python for headless cloud bots.

#pyotp#kiteconnect

Problem Statement

Exchange regulations mandate daily token expiry at 6:00 AM IST. Headless trading bots running on cloud servers need automated TOTP generation (`pyotp`) and local token caching so scripts can share the daily `access_token` without manual copy-pasting.

Formula / Core Logic

Uses pyotp.TOTP(totp_secret).now() to generate the 6-digit RFC 6238 authenticator token and exchanges `request_token` for `access_token`.

Installation

pip install pyotp kiteconnect
zerodha-kite-connect-totp-auto-login-session-python.py
import pyotp
import json
from datetime import date
from kiteconnect import KiteConnect

def get_totp_pin(totp_base32_secret: str) -> str:
    return pyotp.TOTP(totp_base32_secret).now()

def init_kite_session(api_key, api_secret, request_token=None, token_file='kite_token.json'):
    kite = KiteConnect(api_key=api_key)
    today_str = date.today().isoformat()
    
    if request_token:
        session_data = kite.generate_session(request_token, api_secret=api_secret)
        access_token = session_data['access_token']
        with open(token_file, 'w') as f:
            json.dump({'date': today_str, 'access_token': access_token}, f)
        kite.set_access_token(access_token)
        return kite
        
    with open(token_file, 'r') as f:
        saved = json.load(f)
    if saved.get('date') != today_str:
        raise RuntimeError('Token expired! Generate fresh request_token for today.')
    kite.set_access_token(saved['access_token'])
    return kite

Get the Complete 100+ Python Quant & Automation Bundle

Instant lifetime access to all production-ready scripts, valuation models, and trading bots ($19).

Buy Full Bundle on Gumroad ($19) →

Frequently Asked Questions

Q: Where do I find my TOTP Base32 Secret key?

In your broker's 2FA/App Security settings, click 'Can't scan QR code?' when enabling external TOTP to copy the 32-character alphanumeric secret string.