Getting Instrument Token of a Scrip Using Python and Zerodha API

The KiteConnect APIs

We shall be using Zerodha’s Kite Connect API to back test the given dataset. We’re a Zerodha Partner and if you’ve signed up with Unofficed, then You’ll get access to the raw file used to make this tutorial. 

Kite Connect offers REST-like HTTP APIs with a wide range of capabilities which will suffice our needs.

Step 1 - Initialization of Kite Object

As You can see from the example of KiteConnect Python API from Zerodha’s GitHub, the Step 1 is to create the Kite object

				
					import logging
from kiteconnect import KiteConnect

logging.basicConfig(level=logging.DEBUG)

kite = KiteConnect(api_key="your_api_key")

# Redirect the user to the login url obtained
# from kite.login_url(), and receive the request_token
# from the registered redirect url after the login flow.
# Once you have the request_token, obtain the access_token
# as follows.

data = kite.generate_session("request_token_here", api_secret="your_secret")
kite.set_access_token(data["access_token"])
				
			

Discussion on Kite Historical Data Syntax

Zerodha’s KiteConnect API gives historical data for free. As per their documentation, We need to use kite.historical_data() function.

The syntax looks like – 
def historical_data(self, instrument_token, from_date, to_date, interval, continuous=False, oi=False)
The documentation says –
Retrieve historical data (candles) for an instrument.
Although the actual response JSON from the API does not have field names such has ‘open’, ‘high’ etc., this function call structures the data into an array of objects with field names. For example:
  • instrument_token is the instrument identifier (retrieved from the instruments()) call.
  • from_date is the From date (datetime object or string in format of yyyy-mm-dd HH:MM:SS.
  • to_date is the To date (datetime object or string in format of yyyy-mm-dd HH:MM:SS).
  • interval is the candle interval (minute, day, 5 minute etc.).
  • continuous is a boolean flag to get continuous data for futures and options instruments.
  • oi is a boolean flag to get open interest. 

Step 2 - Getting Instrument Token of a Scrip Using Zerodha API

So We need to get the instrument_token. Now, there are two methods to get the Instrument Token of a Scrip. 

In this chapter, We will proceed using the Instrument List Method.

First, let’s download the entire instrument list from Zerodha and save it as a portable database. We will use the pandas library for this task, making data manipulation seamless. The instrument list is available at https://api.kite.trade/instruments in CSV format. So, let’s declare a variable named “instrumentList” to harness the power of pandas in managing this crucial trading data.

				
					import pandas as pd

instrumentList = pd.read_csv("https://api.kite.trade/instruments")
print(instrumentList)
				
			

The output will be –

				
					Triggered at	Count	Stocks (new stocks are highlighted)	Trigger Date	Trigger Time
0	Fri Apr 21 2023, 10:07 am	1	APOLLOTYRE	2023-04-21	10:07:00
1	Fri Apr 21 2023, 9:58 am	1	ASIANPAINT	2023-04-21	09:58:00
2	Thu Apr 20 2023, 3:21 pm	1	TATACONSUM	2023-04-20	15:21:00
3	Thu Apr 20 2023, 2:16 pm	1	BAJAJ-AUTO	2023-04-20	14:16:00
4	Thu Apr 20 2023, 12:49 pm	1	CUB	2023-04-20	12:49:00
...	...	...	...	...	...
775	Tue Sep 13 2022, 10:03 am	3	DIXON	2022-09-13	10:03:00
776	Tue Sep 13 2022, 10:03 am	3	DRREDDY	2022-09-13	10:03:00
777	Tue Sep 13 2022, 10:03 am	3	HEROMOTOCO	2022-09-13	10:03:00
778	Tue Sep 13 2022, 10:01 am	2	DRREDDY	2022-09-13	10:01:00
779	Tue Sep 13 2022, 10:01 am	2	HEROMOTOCO	2022-09-13	10:01:00
780 rows × 5 columns
				
			

Step 3 - Checking for Instrument Token

All the instruments are here in this table! Now, how to get the instrument token of Reliance? Lets write this code snippet to filter the rows where trading symbol is Reliance and the exchange is NSE.
				
					tradesymbol = "RELIANCE"
exchange = "NSE"
dataToken = instrumentList[(instrumentList['tradingsymbol'] == tradesymbol)&(instrumentList['exchange']==exchange)]
print(dataToken)
				
			
The output will be –
				
					    instrument_token  exchange_token tradingsymbol                 name  \
93364            738561            2885      RELIANCE  RELIANCE INDUSTRIES   

       last_price expiry  strike  tick_size  lot_size instrument_type segment  \
93364           0    NaN     0.0       0.05         1              EQ     NSE   

      exchange  
93364      NSE 
				
			
It sniped out the exact row that we needed. Now we need to get the instrument_token from it. We can do that by print(dataToken.instrument_token.iloc[0]) So, wrapping this procedure into a function which we can use into our future endevaours.
				
					def get_insToken(tradesymbol,exchange="NFO"):
    if(exchange=="NSE"):
        if(tradesymbol=="NIFTY"):tradesymbol="NIFTY 50"
        if(tradesymbol=="BANKNIFTY"):tradesymbol="NIFTY BANK"
        if(tradesymbol=="FINNIFTY"):tradesymbol="NIFTY FIN SERVICE"
    dataToken = instrumentList[(instrumentList['tradingsymbol'] == tradesymbol)&(instrumentList['exchange']==exchange)]
    return dataToken.instrument_token.iloc[0]
				
			
Now, if we just do –
				
					symbol = "RELIANCE"
token = get_insToken(symbol,"NSE")
print(token)
				
			
It will give us the token – 738561
Post a comment

Leave a Comment

Your email address will not be published. Required fields are marked *

×Close