kiteconnect.exceptions.TokenException: Token is invalid or has expired.

Shabari
I'm getting below error while trying to connect API. Followed exact steps mentioned in the API documentation but getting same error every time. Generated new token on every attempt, not used same. Cleared chrome cache, cleaned temporary files, generated new token, written new test.py file, but still same error.
Python version : 3.13
Kiteconnect 5.0.1

EBUG:urllib3.connectionpool:Starting new HTTPS connection (1): api.kite.trade:443
DEBUG:urllib3.connectionpool:https://api.kite.trade:443 "POST /session/token HTTP/11" 403 None
Traceback (most recent call last):
File "D:\Stocks\PythonProject\PythonProject\PythonProject\testapi\apitet.py", line 7, in
data = kite.generate_session("SHOWS CORRECT NEW TOKEN", api_secret="SHOWS CORRECT SECRET")
File "D:\Stocks\PythonProject\PythonProject\PythonProject\testapi\.venv\Lib\site-packages\kiteconnect\connect.py", line 263, in generate_session
resp = self._post("api.token", params={
"api_key": self.api_key,
"request_token": request_token,
"checksum": checksum
})
File "D:\Stocks\PythonProject\PythonProject\PythonProject\testapi\.venv\Lib\site-packages\kiteconnect\connect.py", line 865, in _post
return self._request(route, "POST", url_args=url_args, params=params, is_json=is_json, query_params=query_params)
~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Stocks\PythonProject\PythonProject\PythonProject\testapi\.venv\Lib\site-packages\kiteconnect\connect.py", line 937, in _request
raise exp(data["message"], code=r.status_code)
kiteconnect.exceptions.TokenException: Token is invalid or has expired.

Please help..
  • sujith
    You may refer to this thread.
  • Shabari
    Hi Sujit,
    Still no success, last video in your reference thread is not opening.
    I tried to run a simple code to test the API connection & execute one order, below is the script
    ---------------
    import logging
    from kiteconnect import KiteConnect
    from datetime import datetime, timedelta

    # Configure API credentials
    api_key = ""
    api_secret = ""
    access_token = ""

    # Logger setup
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')

    def get_nifty_atm_strike(option_type='PE'):
    """Fetch NIFTY ATM strike price for a given option type (CE/PE)."""
    try:
    nifty_ltp = kite.ltp(["NSE:NIFTY 50"])["NSE:NIFTY 50"]["last_price"]
    atm_strike = round(nifty_ltp / 50) * 50 # Nearest strike
    expiry = get_nearest_weekly_expiry()

    instruments = kite.instruments("NFO")
    nifty_options = [i for i in instruments if i['tradingsymbol'].startswith("NIFTY")]

    atm_option = next(
    (opt for opt in nifty_options if
    opt['strike'] == atm_strike and
    opt['expiry'] == expiry and
    opt['instrument_type'] == 'OPT' and
    opt['option_type'] == option_type),
    None
    )
    if atm_option:
    return atm_option['tradingsymbol']
    else:
    logging.error("Failed to fetch NIFTY ATM option symbol.")
    return None
    except Exception as e:
    logging.error(f"Error in fetching ATM strike: {e}")
    return None

    def get_nearest_weekly_expiry():
    """Get the nearest weekly expiry date."""
    today = datetime.now()
    weekday = today.weekday()
    if weekday >= 3: # If Thursday or later, pick next Thursday
    expiry = today + timedelta(days=(7 - weekday + 3))
    else:
    expiry = today + timedelta(days=(3 - weekday))
    return expiry.strftime('%Y-%m-%d')

    try:
    # Initialize Kite API
    kite = KiteConnect(api_key=api_key)
    kite.set_access_token(access_token)
    logging.info("Successfully connected to Zerodha Kite API.")

    # Get NIFTY ATM PE symbol
    nifty_atm_pe = get_nifty_atm_strike(option_type='PE')
    if not nifty_atm_pe:
    raise Exception("NIFTY ATM PE strike could not be determined.")

    # Fetch the LTP of the option
    ltp_data = kite.ltp([f"NFO:{nifty_atm_pe}"])
    ltp = ltp_data[f"NFO:{nifty_atm_pe}"]['last_price']
    logging.info(f"Live LTP for {nifty_atm_pe}: {ltp}")

    # Define stop loss and target
    stop_loss_price = ltp - 10
    target_price = ltp + 30

    # Place GTT order
    gtt_id = kite.place_gtt(
    trigger_type="single",
    tradingsymbol=nifty_atm_pe,
    exchange="NFO",
    trigger_values=[target_price, stop_loss_price],
    last_price=ltp,
    orders=[
    {
    "transaction_type": "SELL",
    "quantity": 50,
    "price": target_price,
    "order_type": "LIMIT",
    "product": "MIS"
    },
    {
    "transaction_type": "SELL",
    "quantity": 50,
    "price": stop_loss_price,
    "order_type": "LIMIT",
    "product": "MIS"
    }
    ]
    )
    logging.info(f"GTT order placed successfully. GTT ID: {gtt_id}")

    except Exception as e:
    logging.error(f"Error: {e}")
    --------------

    Below is the error log
    2024-12-06 11:15:55,887 - Successfully connected to Zerodha Kite API.
    2024-12-06 11:15:55,981 - Error in fetching ATM strike: Incorrect `api_key` or `access_token`.
    2024-12-06 11:15:55,981 - Error: NIFTY ATM PE strike could not be determined.

    --------
    It shows connect to Kite API, then says incorrect API_key

    Please help..
  • sujith
    Can you private message the api_key? We will check and get back to you.
  • Shabari
    can someone please help. my zerodha API subscription is getting useless.
  • Shabari


    i used the request token only once. when it shown error I'm generating the new request token to run the generatesession.
  • sujith
    Your app seems fine at our end. You can enabled debug logs of pykiteconnect and check what are the tokens sent exactly. Check for the characters mismatch like O and 0 or trailing or beginning space characters.
Sign In or Register to comment.