Invalid 'api_key' or 'access_token'

shashankm8
shashankm8 edited July 2020 in Python client
Hi,

i have written a python client which gets historical data from zerodha, and checks for sma crossover. If the buy condition is satisfied an order needs to be placed.
from kiteconnect import KiteTicker,KiteConnect
import pandas as pd
from datetime import datetime, timedelta
import talib

if __name__ == '__main__':
api_key=open('api_key.txt','r').read()
api_secret = open('api_secret.txt','r').read()

kite = KiteConnect(api_key=api_key)

access_token = open('access_token.txt', 'r').read()

kite.set_access_token(access_token)

# print(kite.login_url())
# data = kite.generate_session("p0g6JdwUlrEqBAyruSTBfynE512nJULK", api_secret=api_secret)
# print(data['access_token'])
# kite.set_access_token(data['access_token'])
# with open('access_token.txt', 'w') as ak:
# ak.write(data['access_token'])
#
#

# # Dates between which we need historical data
from_date = datetime.strftime(datetime.now() - timedelta(100), '%Y-%m-%d')
to_date = datetime.today().strftime('%Y-%m-%d')

# Interval(minute, day, 3 minute, 5 minute...)
interval = "5minute"
current_signal = ''
tokens = {738561: 'RELIANCE', 341249: 'HDFCBANK'}

#following line is just to check if kite,place_order is working or not

kite.place_order(tradingsymbol=tokens[token], variety="REGULAR",exchange="NSE", quantity=1, transaction_type="BUY",order_type="MARKET", product="CNC")

while True:
# if (datetime.now().second == 0) and ((datetime.now().minute) % 5 == 0):
for token in tokens:
records = kite.historical_data(token,from_date=from_date,to_date=to_date,interval=interval)
df = pd.DataFrame(records)
df.drop(df.tail(1).index, inplace=True)
# print(df)
open = df['open'].values
high = df['high'].values
low = df['low'].values
close = df['close'].values
volume = df['volume'].values

sma5 = talib.SMA(close,5)
sma20 = talib.SMA(close,20)
print(sma5[-1])
print(sma20[-1])

#following line is just to check if kite,place_order is working or not

kite.place_order(tradingsymbol=tokens[token], variety="REGULAR",exchange="NSE", quantity=1, transaction_type="BUY",order_type="MARKET", product="CNC")

#actual buy and sell logic
if (sma5[-2] < sma20[-2]) and (sma5[-1] > sma20[-1]):
buy_order_id = kite.place_order(tradingsymbol=tokens[token], exchange="NSE", quantity=1,transaction_type="BUY", order_type="MARKET", product="CNC")
# current_signal = 'buy'

if (sma5[-2] > sma20[-2]) and (sma5[-1] < sma20[-1]):
sell_order_id = kite.place_order(tradingsymbol=tokens[token], exchange="NSE", quantity=1,transaction_type="SELL", order_type="MARKET", product="CNC")
# current_signal = 'sell'
If the kite.place_order is placed ooutside the while loop i.e before calling historical data api, it is working fine otherwise invalid access_token error us thrown

Following is the output
1759.3900000000133
1750.2950000000012
Traceback (most recent call last):
File "C:/Users/My/PycharmProjects/bhavcopy/zerodha_strategy.py", line 54, in <module>
kite.place_order(tradingsymbol=tokens[token], variety="REGULAR",exchange="NSE", quantity=1, transaction_type="BUY",order_type="MARKET", product="CNC")
File "C:\Users\My\AppData\Local\Programs\Python\Python37\lib\site-packages\kiteconnect\connect.py", line 346, in place_order
return self._post("order.place", params)["order_id"]
File "C:\Users\My\AppData\Local\Programs\Python\Python37\lib\site-packages\kiteconnect\connect.py", line 821, in _post
return self._request(route, "POST", params)
File "C:\Users\My\AppData\Local\Programs\Python\Python37\lib\site-packages\kiteconnect\connect.py", line 886, in _request
raise exp(data["message"], code=r.status_code)
kiteconnect.exceptions.InputException: Invalid `api_key` or `access_token`.

As seen above, SMA values are being printed that means i'm successfully getting historical data. But not able to place order
  • sujith
    It seems like you are not sending proper auth header. I would suggest running pykiteconnect with debug logs on and check if you are sending proper auth headers.
  • shashankm8
    In that case, it shouldn't work outside the while loop as well right? only when i combine historical data and placing order it's not working
  • shashankm8
    replaced the kite.place_order(tradingsymbol=tokens[token], variety="REGULAR",exchange="NSE", quantity=1, transaction_type="BUY",order_type="MARKET", product="CNC") with

    order_id = kite.place_order(tradingsymbol=tokens[token],
    exchange=kite.EXCHANGE_NSE,
    transaction_type=kite.TRANSACTION_TYPE_BUY,
    quantity=1,
    order_type=kite.ORDER_TYPE_MARKET,
    product=kite.PRODUCT_MIS)

    and it worked..
This discussion has been closed.