Unable to retrieve historical data

adityahsharma
I cannot retrieve the historical data even after subscribing to add-on.
This is the error- Error: Failed to fetch historical data: {"status":"error","message":"Route not found","data":null,"error_type":"GeneralException"}
  • sujith
    Can you enable debug logs for pykiteconnect and share the complete stacktrace?

    PS: Make sure to remove app and client specific tokens.
  • adityahsharma
    adityahsharma edited December 20
    This is the code I have used:
    import requests
    import pandas as pd
    import datetime

    # API credentials
    api_key = "API_key" # Replace with your actual API key
    access_token = "access_token" # Replace with your actual access token

    base_url = "https://api.kite.trade"
    authorization = f"token {api_key}:{access_token}"

    # Function to fetch instrument token
    def get_instrument_token(symbol):
    url = f"{base_url}/instruments"
    headers = {
    "X-Kite-Version": "3",
    "Authorization": authorization
    }

    response = requests.get(url, headers=headers)
    if response.status_code == 200:
    instruments = response.text.splitlines()
    for line in instruments[1:]: # Skip the header line
    columns = line.split(",")
    if len(columns) > 2 and columns[2] == symbol: # Match tradingsymbol
    return int(columns[0]) # Return instrument token
    raise ValueError(f"Instrument {symbol} not found!")
    else:
    raise Exception(f"Failed to fetch instruments: {response.text}")

    # Function to fetch historical data
    def get_historical_data(symbol, from_date, to_date, interval="day"):
    instrument_token = get_instrument_token(symbol)
    url = f"{base_url}/historical/{instrument_token}/{interval}"
    headers = {
    "X-Kite-Version": "3",
    "Authorization": authorization
    }
    params = {
    "from": from_date,
    "to": to_date
    }

    response = requests.get(url, headers=headers, params=params)
    if response.status_code == 200:
    data = response.json()
    candles = data.get("data", {}).get("candles", [])
    if not candles:
    raise Exception("No historical data returned.")
    return pd.DataFrame(candles, columns=["date", "open", "high", "low", "close", "volume"])
    else:
    raise Exception(f"Failed to fetch historical data: {response.text}")

    # Function to analyze trades
    def analyze_trades(symbol, from_date, to_date):
    df = get_historical_data(symbol, from_date, to_date)
    df["SMA_50"] = df["close"].rolling(window=50).mean()
    df["SMA_200"] = df["close"].rolling(window=200).mean()

    df["Signal"] = 0
    df.loc[df["SMA_50"] > df["SMA_200"], "Signal"] = 1
    df.loc[df["SMA_50"] < df["SMA_200"], "Signal"] = -1

    df["Returns"] = df["close"].pct_change()
    df["Trade_Return"] = df["Signal"].shift(1) * df["Returns"]

    win_ratio = len(df[df["Trade_Return"] > 0]) / len(df[df["Signal"] != 0]) if len(df[df["Signal"] != 0]) > 0 else 0
    loss_ratio = len(df[df["Trade_Return"] < 0]) / len(df[df["Signal"] != 0]) if len(df[df["Signal"] != 0]) > 0 else 0

    print(f"Win Ratio: {win_ratio}")
    print(f"Loss Ratio: {loss_ratio}")

    return df

    # Function to display or save analysis
    def display_analysis(symbol, from_date, to_date):
    analysis_df = analyze_trades(symbol, from_date, to_date)
    print(analysis_df.tail())
    analysis_df.to_csv(f"{symbol}_trade_analysis_{from_date}_{to_date}.csv", index=False)

    # Main usage
    if __name__ == "__main__":
    symbol = "TATAMOTORS" # Example: Tata Motors
    from_date = "2023-01-01" # Start date
    to_date = "2023-12-19" # End date

    try:
    display_analysis(symbol, from_date, to_date)
    except Exception as e:
    print(f"Error: {e}")
  • sujith
    The instruments master is a very huge file. You should be downloading it only once in a day and cache it.
    Use the local source to fetch the instruments data.
    You seem to be using wrong url for fetching historical data. You can check out documentation to know the correct url.
  • adityahsharma
    from kiteconnect import KiteConnect

    # Initialize Kite Connect
    api_key = 'api_key'
    access_token = 'access_token'

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


    # Fetch and save the instrument list
    instruments = kite.instruments()
    with open("instruments.csv", "w") as f:
    for instrument in instruments:
    f.write(",".join(str(value) for value in instrument.values()) + "\n")

    # Load instrument data from CSV for future reference
    import pandas as pd
    instrument_df = pd.read_csv("instruments.csv")


    from datetime import datetime, timedelta

    # Example: Fetch historical data for an instrument
    instrument_token = 256265 # Replace with the actual instrument token
    from_date = (datetime.now() - timedelta(days=7)).strftime("%Y-%m-%d")
    to_date = datetime.now().strftime("%Y-%m-%d")

    historical_data = kite.historical_data(
    instrument_token=instrument_token,
    from_date=from_date,
    to_date=to_date,
    interval="15minute" # Options: minute, day, 3minute, etc.
    )

    # Display the fetched data
    for data in historical_data:
    print(data)


    # Place an order
    kite.place_order(
    tradingsymbol="RELIANCE",
    exchange="NSE",
    transaction_type="BUY",
    quantity=1,
    order_type="MARKET",
    product="CNC" # Options: CNC, MIS, NRML
    )
  • adityahsharma
    This is the error:
    Traceback (most recent call last):
    File "/Applications/PyCharm.app/Contents/plugins/python-ce/helpers/pydev/pydevd.py", line 1570, in _exec
    pydev_imports.execfile(file, globals, locals) # execute the script
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/Applications/PyCharm.app/Contents/plugins/python-ce/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
    File "/Users/adityasharma/Documents/TradeAP/TradeAP.py", line 29, in
    historical_data = kite.historical_data(
    ^^^^^^^^^^^^^^^^^^^^^
    File "/Users/adityasharma/Documents/TradeAP/.venv/lib/python3.12/site-packages/kiteconnect/connect.py", line 632, in historical_data
    data = self._get("market.historical",
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/Users/adityasharma/Documents/TradeAP/.venv/lib/python3.12/site-packages/kiteconnect/connect.py", line 861, in _get
    return self._request(route, "GET", url_args=url_args, params=params, is_json=is_json)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "/Users/adityasharma/Documents/TradeAP/.venv/lib/python3.12/site-packages/kiteconnect/connect.py", line 937, in _request
    raise exp(data["message"], code=r.status_code)
    kiteconnect.exceptions.PermissionException: Insufficient permission for that call.
    python-BaseException
  • sujith
    You need an add-on subscription to use historical data API. You can know more on FAQs.
Sign In or Register to comment.