Access Token problems

DS4769
I have the following python code snippet.

====================================
# Initialise
my_api_key = "?????????" (masked)
my_api_secret = "?????????????????????????"

# login url https://kite.trade/connect/login?api_key=????
# CHANGE THE VALUE HERE
postback = "?????????????????"
#

try:
kite = KiteConnect(api_key = my_api_key)
token = kite.request_access_token(postback, my_api_secret)
print(token)
kite.set_access_token(token["access_token"])
except Exception as e:
print ("Authentication failed", e)
raise
=============================

Until here, login works and the token is printed. set_access_token also goes through

But when I use an API call like
pos = kite.positions()["net"]
it fails with the following
==============================
File "xxx.py", line nnn, in
pos = kite.positions()["net"]
File "C:\Users\S\Personal\Apps\Python34\lib\site-packages\kiteconnect\__init__.py", line 363, in positions
return self._get("portfolio.positions")
File "C:\Users\S\Personal\Apps\Python34\lib\site-packages\kiteconnect\__init__.py", line 463, in _get
return self._request(route, "GET", params)
File "C:\Users\S\Personal\Apps\Python34\lib\site-packages\kiteconnect\__init__.py", line 554, in _request
raise(exp(data["message"], code=r.status_code))
kiteconnect.exceptions.TokenException: Invalid token
==============================

Even if I use a new token from the redirect URL and paste in the code, the same error happens. The other point is that this occurs only during market hours. Till pre-opening, the script works with one issue - every time the script is executed, the token has to be refreshed!

Please note that I am NOT logged in to any other app - PI or NEST or kite or even Q.

I have seen several threads where it is mentioned that this is not required and if this happens, session has to be cleaned. Please let me know how to do this.
  • sujith
    Hi,
    You don't need to make call for request access token every time you run script. You should make call once and store access token and use the same next time you run script.

    PS: You should only request access token only when it is expired.
  • DS4769
    Resolved the invalid token problem, deleted all the cookies and temp files.

    But it still requires me to provide a fresh token on every running of the script. Without a fresh token, the kiteconnect.exceptions.TokenException: Invalid token repeats.

    Please let me know if there is anything I can do to check.
  • sujith
    @DS4769,
    Once you have access token, don't make this call
    token = kite.request_access_token(postback, my_api_secret)
    instead directly use kite.set_access_token()
  • DS4769
    Thank you, Sujith.
This discussion has been closed.