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"}
# 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 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}")
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.
# 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")
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
PS: Make sure to remove app and client specific tokens.
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.
# 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
)
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