Take a look

Tech

How to generate Request token and Access token in kiteconnect?

Getting Started with Kiteconnect. First of all, go-to kite.trade and signup for the KITE APIS, it costs 2000 rupees for live and historical data each. Create a new app by providing the necessary details.

Once you create the app you will receive an API key and API secret

Steps to follow

  • You will initialize an instance of the Kite client
  • Redirect the user to the login_url()
  • At the redirect URL endpoint, obtain the request_token from the query parameters
  • Initialize a new instance of Kite client, use generate_session() to obtain the access_token along with authenticated user data
  • Store this response in a session and use the stored access_token and initialize instances of the Kite client for subsequent API calls.

The above API key and API secret can be used to generate a request token and using the request token we can generate an access token and register it to start login and execute orders in our zerodha trading account.

The life of a request token generated is a few minutes and an access token generated is 24 hrs.

Also to start to execute orders in the kite you need to enable TOTP i.e time based one-time passwords with the help of third-party apps like Microsoft or google authenticator.

For generating the request token please follow the below code snippets

Pip install kiteconnect

Import the API key and API secret generated while creating the APP to a python file from a text file and try to execute the below snippet.

from kiteconnect import KiteTicker, KiteConnect

if __name__ == '__main__':
    api_key = open("api_key.txt", "r").read()
    api_secret = open("api_secret.txt", "r").read()

    kite = KiteConnect(api_key=api_key)

    # Need to generate access token once a day expiration is daily   for AT
    print(kite.login_url())
    request_token = input("enter request token")

    def generate_access_token(request):
        try:
            data = kite.generate_session(request_token=request, api_secret=api_secret)
            kite.set_access_token(data['access_token'])

            with open("access_token.txt", 'w') as at:
                at.write(data['access_token'])
                print("write_successful")
            at.close()
        except Exception as err:
            print(str(err))

    generate_access_token(request_token)

You will get a URL on your terminal like https://kite.trade/connect/login?api_key=8766jeys9lxjpfgs&v=3

Click on the URL and you will get the request token from the header

Copy the request token to the terminal and click enter. The access token is generated and written to the access_token.txt file.

Leave a Reply