how to reuse access_token

shariqasif
i am building an application which will run several times during the day. could you please provide same code which i can use to reuse access_token

from kiteconnect import KiteConnect
api_key="xxxx"
api_secret="xxxx"
kite = KiteConnect(api_key,api_secret)
print(kite.login_url())

user = kite.request_access_token(request_token="xxxxx",secret=api_secret)
kite.set_access_token(user["access_token"])
print(user)

above code gives me access and public token.

now if i have to place order during later part of day what code should be written before below code

try:
order_id = kite.order_place(tradingsymbol="ASHOKLEY",
exchange="NSE",
transaction_type="BUY",
quantity=1,
order_type="MARKET",
product="CNC")

print("Order placed. ID is", order_id)
except Exception as e:
print("Order placement failed", e.message)'''

FYI : I use Liclipse ide for python
  • sujith
    Hi,
    You just need to store access_token and public_token in text file or database and re-use it.
    You just need to make sure request_access_token is not called in subsequent run.
  • shariqasif
    I TRIED various combination and finally found working combination

    kite = KiteConnect("xxxx","xxxxxx")
    kite = KiteConnect(api_key,access_token)

    i don't know why this syntax is not mentioned in any of your doc.
  • sujith
    Hi,
    An access_token is an optional parameter which is mentioned in the documentation.
  • nayana
    hi can any one help me that how to store access_token into an file and reuse it
    thanks in advance
  • Imran
    Hi @nayana
    you can refer to the below code snippet.
    from kiteconnect import KiteConnect
    from kiteconnect import KiteTicker
    import datetime
    import os

    token_file = str(datetime.datetime.now().date()) + ' token' + '.txt'
    if token_file not in os.listdir():
    kite = KiteConnect(api_key=api_k)
    data = kite.generate_session(request_tkn, api_secret=api_s)
    access_token = data["access_token"]
    kite.set_access_token(access_token)

    file = open(token_file, 'w')
    file.write(access_token)
    file.close() # storing token in today's file

    elif token_file in os.listdir(): # reading and reusing token from today's file
    kite = KiteConnect(api_key=api_k)
    file = open(token_file, 'r+')
    access_token = file.read()
    file.close()
    kite.set_access_token(access_token)
  • ankur320
    @Imran nice. I was just going to write the same. You saved a lot of time. Thanks
Sign In or Register to comment.