How to Log into your Zerodha account using Python

⚠️ Below script is working as of 19 July 2020, It might break in case Zerodha Kite portal chages its APIs

What can you do by programatically logging in?

Why would you want to log in to Zerodha automatically? Well you can automate a lot of activities-

Ingredients

You don’t need to be an expert on any of the above, just understand the concept so that you are able to relate to the steps mentioned in this post.

So let’s get started

Recipe

What happens when you request Zerodha’s home page

  1. Open new chrome tab and press Ctrl + Shift + i to launch developer tools
  2. Press on the Network tab on developer tools panel
  3. Now go to https://kite.zerodha.com and observe the requests made by chrome

Zerodha initiates a session with cookies named __cfduid and kf_session. Let us try to replicate this action using python requests-

We will use Session object from requests library instead of using get/post functions directly. This is done in order to preserve the session cookies.

# Run pip install requests from command line before executing this section
from requests import Session
import json
s = Session()

base_url = "https://kite.zerodha.com/"

r = s.get(base_url)
print(s.cookies)

What happens when you provide your credentials

  1. Enter your login details while keeping the network tab open
  2. On Developer->Network tab, press on XHR to filter out the clutter, Zerodha uses json requests for all data exchanges
  3. At this stage, Zerodha is sending the credentials to https://kite.zerodha.com/api/login
  4. You can click on preview tab to see what was the response from Zerodha

Let us try to replicate this action

# Initialize your credentials (This is for demo purpose only, but you should avoid storing credentials in plain text)

user_id = "USERID"
password = "PASSWORD"
twofa = "YOURPIN"

Initiate the post request using your user_id and password

login_url = "https://kite.zerodha.com/api/login"
r = s.post(login_url, data={"user_id": user_id, "password":password})
j = json.loads(r.text)
print(j)

In similar manner, you can observe the network tab when you enter your pin. It uses request_id from previous step. Below is the replicated step-

twofa_url = "https://kite.zerodha.com/api/twofa"
data = {"user_id": user_id, "request_id": j['data']["request_id"], "twofa_value": twofa }
r = s.post(twofa_url, data=data)
j = json.loads(r.text)
print(j)

You can see additional cookie enctoken being added to our session, this is an important

print(s.cookies["enctoken"])

You are now logged in.

We’re in, let’s what’s in the box?

After you login, you will see a lot XHR requests going out. Let us look at portfolio request closely. You will see each request has some additional request headers-

enc_token = s.cookies['enctoken']
h = {}
h['authorization'] = "enctoken {}".format(enc_token)
h['referer'] = 'https://kite.zerodha.com/dashboard'
h['x-kite-version'] = '2.4.0'
h['sec-fetch-site'] = 'same-origin'
h['sec-fetch-mode'] = 'cors'
h['sec-fetch-dest'] = 'empty'
s.headers.update(h) # Update the request session object with headers

Let us fetch the url for holdings

holding_url = "https://kite.zerodha.com/oms/portfolio/holdings"
r = s.get(holding_url)
print(r.json())

What next?

Hope this post gives you an overview of how server-browser interaction happens. You can use this method to automate any other website.

You can now perform various actions with your zerodh account, observe data exchanged and try to replicate from your python code.

You can also checkout the library jugaad-trader, it has already implemened many of the interaction and it has a very similar API to Kiteconnect