API and Access Token Invalid

caabhijain1995
I am tryin to create a automatic boat for intraday trade but everytime i run it shows API and Access token is wrong. below is the code please check why the issue is coming up

import pandas as pd
import numpy as np
from kiteconnect import KiteConnect
import requests
import time
from datetime import datetime, timedelta

# Zerodha Kite API setup
api_key = "API_KEY"
access_token = "Access_Token"

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

# Telegram bot setup
TELEGRAM_TOKEN = "Token"
TELEGRAM_CHAT_ID = "Chat_ID"

# Fetch historical or real-time 5-minute data
def fetch_data(symbol_token, interval="5minute", duration_days=15):
start = datetime.now() - timedelta(days=duration_days)
end = datetime.now()
data = kite.historical_data(symbol_token, start, end, interval)
df = pd.DataFrame(data)
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
return df

# Calculate Bollinger Bands using pandas
def calc_bollinger(df, window=20, num_std=2):
df['middle_band'] = df['close'].rolling(window).mean()
df['std'] = df['close'].rolling(window).std()
df['upper_band'] = df['middle_band'] + num_std * df['std']
df['lower_band'] = df['middle_band'] - num_std * df['std']
return df

# Calculate ATR manually
def calc_atr(df, period=14):
df['H-L'] = df['high'] - df['low']
df['H-PC'] = abs(df['high'] - df['close'].shift())
df['L-PC'] = abs(df['low'] - df['close'].shift())
df['TR'] = df[['H-L', 'H-PC', 'L-PC']].max(axis=1)
df['ATR'] = df['TR'].rolling(window=period).mean()
return df

# Liquidity score calculation
def liquidity_factor(df):
df['volume_ma'] = df['volume'].rolling(window=20).mean()
if pd.isna(df['volume_ma'].iloc[-1]):
return 0
return df['volume'].iloc[-1] / df['volume_ma'].iloc[-1]

# Entry/exit signal logic
def apply_strategy(df):
df = calc_bollinger(df)
df = calc_atr(df)

df['buy_signal'] = (df['close'] < df['lower_band']) & (df['close'].shift(1) >= df['lower_band'].shift(1))
df['sell_signal'] = (df['close'] > df['upper_band']) & (df['close'].shift(1) <= df['upper_band'].shift(1))

df['stop_loss'] = df['close'] - 2 * df['ATR']
df['target'] = df['close'] + 2 * df['ATR']
return df

# Send message to Telegram
def send_telegram_message(message):
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage?chat_id={TELEGRAM_CHAT_ID}&text={message}"
requests.get(url)

# Main function to execute strategy
def main(symbol, symbol_token):
df = fetch_data(symbol_token)
liquidity = liquidity_factor(df)
print(f"Liquidity Score for {symbol}: {liquidity:.2f}")

if liquidity > 2:
df = apply_strategy(df)
latest = df.iloc[-1]

if latest['buy_signal']:
msg = (
f"???? *Buy Signal* for {symbol}\n"
f"Price: ₹{latest['close']:.2f}\n"
f"SL: ₹{latest['stop_loss']:.2f}\n"
f"Target: ₹{latest['target']:.2f}"
)
print(msg)
send_telegram_message(msg)

elif latest['sell_signal']:
msg = (
f"???? *Sell Signal* for {symbol}\n"
f"Price: ₹{latest['close']:.2f}\n"
f"SL: ₹{latest['stop_loss']:.2f}\n"
f"Target: ₹{latest['target']:.2f}"
)
print(msg)
send_telegram_message(msg)
else:
print(f"{symbol} is not liquid enough. Skipping.")

# Example live execution loop
while True:
try:
main("RELIANCE", 738561) # Use correct instrument_token for real
except Exception as e:
print(f"Error: {e}")
time.sleep(300) # Wait 5 minutes

  • vaibhavsharma13
    vaibhavsharma13 edited April 14
    Put apikey and access token here:
    # Zerodha Kite API setup
    api_key = "API_KEY"
    access_token = "Access_Token"
Sign In or Register to comment.