⚠️ Below script is working as of 19 July 2020, It might break in case Zerodha Kite portal chages its APIs
Why would you want to log in to Zerodha automatically? Well you can automate a lot of activities-
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
Network
tab on developer tools panelZerodha 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)
XHR
to filter out the clutter, Zerodha uses json requests for all data exchangeshttps://kite.zerodha.com/api/login
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.
XHR
requests going out. Let us look at portfolio request closely. You will see each request has some additional request headers-
enctoken
from previous stage2.4.0
sec-fetch
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())
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