It looks like you're new here. If you want to get involved, click one of these buttons!
def get_request_token(credentials: dict) -> str:
kite = KiteConnect(api_key=credentials["api_key"])
session = requests.Session()
login_url = kite.login_url()
response = session.get(login_url)
login_payload = {
"user_id": credentials["username"],
"password": credentials["password"],
}
login_response = session.post("https://kite.zerodha.com/api/login", data=login_payload)
login_response_data = login_response.json()
if "data" not in login_response_data or "request_id" not in login_response_data["data"]:
raise Exception("Login failed. Please check your credentials.")
totp_payload = {
"user_id": credentials["username"],
"request_id": login_response_data["data"]["request_id"],
"twofa_value": otp.get_totp(credentials["totp_key"]),
"twofa_type": "totp",
"skip_session": True,
}
totp_response = session.post("https://kite.zerodha.com/api/twofa", data=totp_payload)
totp_response_data = totp_response.json()
if "data" in totp_response_data and "request_token" in totp_response_data["data"]:
request_token = totp_response_data["data"]["request_token"]
else:
try:
response = session.get(login_url)
parse_result = urlparse(response.url)
query_params = parse_qs(parse_result.query)
request_token = query_params["request_token"][0]
except Exception as e:
pattern = r"request_token=[A-Za-z0-9]+"
match = re.search(pattern, str(e))
if not match:
raise Exception("Failed to extract request token.")
request_token = match.group(0).split("=")[1]
return request_token
def retry_get_request_token(credentials, cur_cnt=1):
try:
cur_cnt += 1
return get_request_token(credentials)
except Exception as e:
if cur_cnt < 5:
return retry_get_request_token(credentials, cur_cnt=cur_cnt)
To generate the access token, you need to copy the request token from the redirect URL and use it to generate the session. Please note that the access token is valid for one day, and you can use it for all API requests throughout that day. A request token, however, is valid for only a few minutes and can be used just once. Ensure that you do not request a new access token for every run. Once you have generated the access token, store it in a file or app preferences for reuse.
We recommend following the login flow as outlined in the Kite Connect API documentation. Additionally, you can refer to this webinar for a detailed walkthrough.
You can also explore our Quantinsti course on Algorithmic trading with Zerodha Kite Connect API and Python.