How to Automate Request Token Generation with Python
Generating the request_token in the Zerodha KiteConnect API is not only a mandatory daily step for accessing trading APIs but also crucial for automating stock market strategies and integrating seamlessly with Zerodha’s brokerage platform. However, doing it manually every single day can quickly become time-consuming for algo traders. Therefore, in this guide, we’ll clearly explain how to automate the entire process using Python and Selenium. Moreover, we will walk you through each step — from logging into Zerodha automatically to extracting the request_token from the redirect URL. Finally, by the end of this tutorial, you will have a fully working script that speeds up your trading setup and makes your workflow far more efficient.

Enable TOTP in Zerodha Account to Strengthen Login Security
- Log in to kite.zerodha.com.
- Click on your Client ID (top right) → My Profile → Password & Security.
- Click Enable External TOTP.
- Enter the OTP sent to your registered email and click Verify.
- You’ll see a QR code and a setup key.
- Use an authenticator app like Google Authenticator, Authy, or Microsoft Authenticator.
- First, secure your account with two-factor authentication; then, either scan the QR code or, alternatively, enter the setup key manually in your authentication app. Moreover, this extra security step ensures better protection against unauthorized access and, consequently, keeps your trading account safe.
- Enter the 6-digit TOTP from the app and your Kite login password.
- Click Enable.
Example :
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from kiteconnect import KiteConnect
from selenium.webdriver.common.by import By
from urllib.parse import urlparse, parse_qs
from selenium import webdriver
import time
import os
import pyotp
cwd=os.chdir("D:\GenAi\python\python basic")
token_path="api_key.txt"
key_secret=open(token_path,'r').read().split()
kite=KiteConnect(api_key=key_secret[0])
url=kite.login_url()
print(url)
driver = webdriver.Chrome()
driver.get("https://kite.zerodha.com/connect/login?api_key=5rn2z0mnye&v=3")
time.sleep(3)
userId_field = driver.find_element(By.ID, 'userid')
password_field = driver.find_element(By.ID, 'password')
userId_field.send_keys("XXXXXXXX")
password_field.send_keys("XXXXXXXXX")
time.sleep(3)
# Click Login
driver.find_element(By.XPATH, "//button[@type='submit']").click()
time.sleep(2)
totp_secret = 'ERUWEHHWEIIWIEINJCJKVJKDUDBVBBV'
totp = pyotp.TOTP(totp_secret)
app_code = totp.now()
print("Your Zerodha App Code:", app_code)
appcode_field = driver.find_element(By.ID, 'userid')
appcode_field.send_keys(app_code)
try:
continue_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Continue')]"))
)
continue_button.click()
print("Clicked the Continue button.")
except Exception as e:
print("Error:", e)
# Replace with your actual TOTP secret key from Zerodha
WebDriverWait(driver, 10).until(lambda d: d.current_url != "https://kite.zerodha.com/connect/login?api_key=5rn2z0mnyewewqeqw&v=3")
# Get the redirected URL
redirected_url = driver.current_url
parsed_url = urlparse(redirected_url)
query_params = parse_qs(parsed_url.query)
request_token = query_params.get("request_token", [None])[0]
print("Request Token:", request_token)
Explanation of above code
1. Importing Required Libraries
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from kiteconnect import KiteConnect
from selenium.webdriver.common.by import By
from urllib.parse import urlparse, parse_qs
from selenium import webdriver
import time
import os
import pyotp
These libraries handle:
- Web automation (
selenium
) - API connection (
kiteconnect
) - URL parsing (
urllib
) - TOTP generation (
pyotp
) - File and time operations (
os
,time
)
2. Set Working Directory & Read API Key
cwd = os.chdir("D:\GenAi\python\python basic")
token_path = "api_key.txt"
key_secret = open(token_path, 'r').read().split()
- Changes the current working directory.
- Reads the API key and secret from a file (
api_key.txt
) and splits them into a list.
3. Initialize KiteConnect and Get Login URL
kite = KiteConnect(api_key=key_secret[0])
url = kite.login_url()
print(url)
- Initializes the KiteConnect object using the API key.
- Retrieves the login URL required for authentication.
4. Launch Chrome and Open Login Page
driver = webdriver.Chrome()
driver.get("https://kite.zerodha.com/connect/login?api_key=5rn2z0mnye&v=3")
time.sleep(3)
- Opens a Chrome browser and navigates to the Zerodha login page.
- Waits 3 seconds for the page to load.
5. Enter User Credentials
userId_field = driver.find_element(By.ID, 'userid')
password_field = driver.find_element(By.ID, 'password')
userId_field.send_keys("XXXXXXXX")
password_field.send_keys("XXXXXXXXX")
time.sleep(3)
- Finds the input fields for user ID and password.
- Fills them with your credentials (replace
"XXXXXXXX"
with actual values).
6. Click Login Button
driver.find_element(By.XPATH, "//button[@type='submit']").click()
time.sleep(2)
- Clicks the login button to proceed to the TOTP screen.
7. Generate and Enter TOTP
totp_secret = 'AR2321asdUWEHHWEII2WIEINJCJKV232JKDUDBVBBV'
totp = pyotp.TOTP(totp_secret)
app_code = totp.now()
print("Your Zerodha App Code:", app_code)
appcode_field = driver.find_element(By.ID, 'userid')
appcode_field.send_keys(app_code)
- Uses the TOTP secret to generate a 6-digit code.
- Next, the script enters the code into the designated field; however, it mistakenly uses the ‘userid’ field again. Instead, this should, in fact, be the TOTP field ID. Moreover, correcting this step ensures that the two-factor authentication process runs smoothly and, consequently, improves the overall reliability of your Zerodha KiteConnect automation
8. Click Continue After TOTP
try:
continue_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Continue')]"))
)
continue_button.click()
print("Clicked the Continue button.")
except Exception as e:
print("Error:", e)
- Waits for the “Continue” button to become clickable.
- Clicks it to complete login.
9. Wait for Redirect
WebDriverWait(driver, 10).until(lambda d: d.current_url != "https://kite.zerodha.com/connect/login?api_key=5rn2z0mnyewewqeqw&v=3")
- After submitting the login details, the script then waits for the URL to change; consequently, this step helps validate a successful login and, moreover, confirms the page redirection during automated browser testing.
10. Extract Request Token
redirected_url = driver.current_url
parsed_url = urlparse(redirected_url)
query_params = parse_qs(parsed_url.query)
request_token = query_params.get("request_token", [None])[0]
print("Request Token:", request_token)
- Parses the redirected URL.
- Extracts the
request_token
from the query parameters. - This token is needed to generate the access token for API calls.
- Style Name : Western Dress, Material Composition: Georgette Swiss Dot
- Occasion: Travelling, suits in spring summer, Dating, Party, Evening, Casual, Home, Office, Vacation, Night out , Shopping, Birthday Party, Kitty Party , College Functions etc., Suitable for : All Season[Winter/Summer/Monsoon]