fetching data erro

pk2369
i am trying to login to the zerodha via api and fetch the data it is getting logged in but then this error pops up



MY CODE:

import pandas as pd
import time
import requests
import os
import logging
from kiteconnect import KiteConnect

logging.basicConfig(level=logging.DEBUG)

api_key = 'xxxxxxxxx'
zerodha_id = 'xxxxxxxx'
zerodha_password = 'xxxxxxxxx'
zerodha_pin = 'xxxxxxxxxxxx'
api_secret = 'xxxxxxxxxxxxxxxx'

def connect_kite():
access_token = get_access_token(api_key, zerodha_id, zerodha_password, zerodha_pin)
if access_token:
kite = KiteConnect(api_key=api_key)
kite.set_access_token(access_token)
print('Login SUCCESS')
return kite
else:
print('Login FAILED')
return None

def get_access_token(api_key, zerodha_id, zerodha_password, zerodha_pin):
# Step 1: Get the request token
kite_url = "https://kite.zerodha.com/api/login"
kite_data = {
"user_id": zerodha_id,
"password": zerodha_password
}
response = requests.post(kite_url, data=kite_data)

# Step 2: Extract request_id
request_id = response.json()["data"]["request_id"]

# Step 3: Use request token to get access token
headers = {
"X-Kite-Version": "3",
"Referer": "https://kite.zerodha.com/"
}
kite_data = {
"user_id": zerodha_id,
"request_id": request_id,
"twofa_value": zerodha_pin
}
response = requests.post("https://kite.zerodha.com/api/twofa", data=kite_data, headers=headers)
enctoken = response.cookies.get("enctoken")

return enctoken

access_token = get_access_token(api_key, zerodha_id, zerodha_password, zerodha_pin)
print("Access Token:", access_token)

def get_live_data(kite, symbol):
instrument_token = kite.ltp(symbol)['NSE:' + symbol]['instrument_token']
live_data = kite.quote([instrument_token])

# Extracting required data
ohlc_data = live_data['NSE:' + symbol]['ohlc']
vwap_data = live_data['NSE:' + symbol]['depth']['vwap']

data = {
'open': ohlc_data['open'],
'high': ohlc_data['high'],
'low': ohlc_data['low'],
'close': ohlc_data['close'],
'vwap': vwap_data
}

df = pd.DataFrame(data, index=[0])

filename = f"{symbol}_live_data.csv"
if os.path.exists(filename):
df.to_csv(filename, mode='a', index=False, header=False)
else:
df.to_csv(filename, index=False)

print(f"Live data for {symbol} fetched and saved successfully.")

def main():
kite = connect_kite()
if kite:
symbol = 'INFY'
while True:
get_live_data(kite, symbol)
time.sleep(10) # Check for data every 10 seconds
else:
print("Login failed. Exiting.")

if __name__ == "__main__":
main()


ERROR :
DEBUG:urllib3.connectionpool:https://kite.zerodha.com:443 "POST /api/twofa HTTP/1.1" 200 42
Login SUCCESS
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): api.kite.trade:443
DEBUG:urllib3.connectionpool:https://api.kite.trade:443 "GET /quote/ltp?i=INFY HTTP/1.1" 403 None
Traceback (most recent call last):
File "c:\Users\prith\OneDrive\Desktop\algo_trade\Kite_Zerodha-main\zerodha_data_login.py", line 94, in
main()
File "c:\Users\prith\OneDrive\Desktop\algo_trade\Kite_Zerodha-main\zerodha_data_login.py", line 88, in main
get_live_data(kite, symbol)
File "c:\Users\prith\OneDrive\Desktop\algo_trade\Kite_Zerodha-main\zerodha_data_login.py", line 58, in get_live_data
instrument_token = kite.ltp(symbol)['NSE:' + symbol]['instrument_token']
^^^^^^^^^^^^^^^^
File "c:\Users\prith\AppData\Local\Programs\Python\Python311\Lib\site-packages\kiteconnect\connect.py", line 610, in ltp
return self._get("market.quote.ltp", params={"i": ins})
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\prith\AppData\Local\Programs\Python\Python311\Lib\site-packages\kiteconnect\connect.py", line 851, in _get
return self._request(route, "GET", url_args=url_args, params=params, is_json=is_json)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\prith\AppData\Local\Programs\Python\Python311\Lib\site-packages\kiteconnect\connect.py", line 927, in _request
raise exp(data["message"], code=r.status_code)
kiteconnect.exceptions.TokenException: Incorrect `api_key` or `access_token`.
  • rakeshr
    # Step 1: Get the request token
    kite_url = "https://kite.zerodha.com/api/login"
    kite_data = {
    "user_id": zerodha_id,
    "password": zerodha_password
    }
    response = requests.post(kite_url, data=kite_data)
    You need to login manually to generate request token. Go through the documentation here and login FAQs.
  • pk2369
    i have this which gives me the access token

    import requests
    import os

    def get_access_token(api_key, zerodha_id, zerodha_password, zerodha_pin):
    # Step 1: Get the request token
    kite_url = "https://kite.zerodha.com/api/login"
    kite_data = {
    "user_id": zerodha_id,
    "password": zerodha_password
    }
    response = requests.post(kite_url, data=kite_data)

    # Step 2: Extract request_id
    request_id = response.json()["data"]["request_id"]

    # Step 3: Use request token to get access token
    headers = {
    "X-Kite-Version": "3",
    "Referer": "https://kite.zerodha.com/"
    }
    kite_data = {
    "user_id": zerodha_id,
    "request_id": request_id,
    "twofa_value": zerodha_pin
    }
    response = requests.post("https://kite.zerodha.com/api/twofa", data=kite_data, headers=headers)
    enctoken = response.cookies.get("enctoken")

    return enctoken

    api_key = 'xxxxx'
    zerodha_id = 'xxxx'
    zerodha_password = 'xxxxx'
    zerodha_pin = 'xxxxxx'

    access_token = get_access_token(api_key, zerodha_id, zerodha_password, zerodha_pin)
    print("Access Token:", access_token)




    and i have this code which can fetch the data will this work havent tried it yet

    import logging
    from kiteconnect import KiteTicker, KiteConnect

    logging.basicConfig(level=logging.DEBUG)

    api_key = "7vg092t26a9aqjx7"
    access_token = "your_access_token"

    kite = KiteConnect(api_key=api_key)
    kite.set_access_token(access_token)

    # Fetch the instrument token for NIFTY24050922600
    NIFTY24050922600_INSTRUMENT_TOKEN = kite.ltp("NIFTY24050922600")["NSE:NIFTY24050922600"]["instrument_token"]
    print("Instrument Token:", NIFTY24050922600_INSTRUMENT_TOKEN)

    # Initialize OHLCV dictionary
    ohlc_data = {}

    def on_ticks(ws, ticks):
    global ohlc_data

    for tick in ticks:
    instrument_token = tick['instrument_token']
    ohlc_data[instrument_token] = {
    'open': tick['ohlc']['open'],
    'high': tick['ohlc']['high'],
    'low': tick['ohlc']['low'],
    'close': tick['ohlc']['close'],
    'vwap': tick['ohlc']['volume_weighted_average_price']
    }

    print("OHLCV data:", ohlc_data)

    def on_connect(ws, response):
    # Callback on successful connect.
    # Subscribe to a list of instrument_tokens (NIFTY24050922600 here).
    ws.subscribe([NIFTY24050922600_INSTRUMENT_TOKEN])

    # Set NIFTY24050922600 to tick in `full` mode.
    ws.set_mode(ws.MODE_FULL, [NIFTY24050922600_INSTRUMENT_TOKEN])

    def on_close(ws, code, reason):
    # On connection close stop the main loop
    # Reconnection will not happen after executing `ws.stop()`
    ws.stop()

    # Assign the callbacks.
    kws = KiteTicker(api_key, access_token)
    kws.on_ticks = on_ticks
    kws.on_connect = on_connect
    kws.on_close = on_close

    # Infinite loop on the main thread. Nothing after this will run.
    # You have to use the pre-defined callbacks to manage subscriptions.
    kws.connect()



    so basically i ll just get the access token i put it in the second code so i wouldnt have to manually get the token
  • pk2369
    well i tried it and it work now i have the following issue

    code:
    from kiteconnect import KiteConnect
    from kiteconnect import KiteTicker
    import datetime

    # Initialize your API key and access token
    api_key = "xxxxxxxxxxxxx"
    access_token = "xxxxxxxxxxxxxxxxxx"

    # Initialize KiteConnect
    kite = KiteConnect(api_key=api_key)
    kite.set_access_token(access_token)

    # Token number of the instrument
    token = 12020482

    def on_ticks(ws, ticks):
    print(ticks)

    def on_connect(ws, response):
    # Subscribe to the instrument token
    ws.subscribe([token])
    ws.set_mode(ws.MODE_FULL, [token])

    def on_close(ws, code, reason):
    ws.stop()

    def on_error(ws, code, reason):
    print(code, reason)

    # Initialize KiteTicker
    kws = KiteTicker("your_api_key", "your_access_token")

    # Assign event handlers
    kws.on_ticks = on_ticks
    kws.on_connect = on_connect
    kws.on_close = on_close
    kws.on_error = on_error

    # Start the WebSocket connection
    kws.connect(threaded=True)

    # Fetch historical data
    def fetch_historical_data():
    from_date = datetime.datetime.now() - datetime.timedelta(minutes=15)
    to_date = datetime.datetime.now()
    historical_data = kite.historical_data(token, from_date, to_date, "15minute")
    print_historical_data(historical_data)

    def print_historical_data(historical_data):
    for data in historical_data:
    print("Timestamp:", data['date'])
    print("Open:", data['open'])
    print("High:", data['high'])
    print("Low:", data['low'])
    print("Close:", data['close'])
    print("Volume:", data['volume'])
    print("OI:", data['oi'])
    print()

    fetch_historical_data()




    error : kiteconnect.exceptions.PermissionException: Insufficient permission for that call.
  • rakeshr
    historical_data = kite.historical_data(token, from_date, to_date, "15minute")
    error : kiteconnect.exceptions.PermissionException: Insufficient permission for that call.
    You will need to subscribe to historical data APIs. Go through the FAQs here.
  • pk2369
    pk2369 edited May 8
    well lets say i need live data

    the code i used:
    import logging
    import csv
    from kiteconnect import KiteTicker

    logging.basicConfig(level=logging.DEBUG)

    # Initialize
    kws = KiteTicker("xxxx", "xxxx")

    # Token number of the instrument
    token = 12020482

    # CSV file name
    csv_file = "instrument_data.csv"

    def on_ticks(ws, ticks):
    for tick in ticks:
    ohlc = tick['ohlc']
    avg_traded_price = tick['average_traded_price']
    logging.debug(f"open:{ohlc['open']}, high:{ohlc['high']}, low:{ohlc['low']}, close:{ohlc['close']}, vwap: {avg_traded_price},")
    save_to_csv(ohlc['open'], ohlc['high'], ohlc['low'], ohlc['close'], avg_traded_price)

    def on_connect(ws, response):
    ws.subscribe([token])
    ws.set_mode(ws.MODE_QUOTE, [token])

    def on_close(ws, code, reason):
    ws.stop()


    it works to fetch live data but the issue is
    it fetches ticks in 1 day time frame that is the open and high low close remains same until changed it doest fetch a min data of the candle
  • sujith
    The OHLC in the Websocket API is the day OHLC. You can refer to the documentation here.
    For intraday OHLC candles, you need to generate candles at your end using the same API. You can refer to this thread to know more about it.
    For backtesting, you can use historical data API. It also has current day's data.
Sign In or Register to comment.