hey! i am using websocket to fetch real time data ... all was working fine till last friday but from today morning i have been unable to connect to websocket . It is showing 403 forbidden (initialy showed ' closed reason without close code' )for the same code(s) that used to work fine till friday .Tried using the sample code in py documentation but got the same error .
ERROR:kiteconnect.ticker:Connection error: 1006 - connection was closed uncleanly (I dropped the WebSocket TCP connection: close reason without close code) ERROR:kiteconnect.ticker:Connection closed: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (403 - Forbidden)) (above errors while getting tickdata)
Thought maybe access token has expired ... Tried to generate new accestoken(manualy) ,but got the SAME ACCESS_TOKEN everytime for diffferent request_tokens (also tried logging out of kite but for no use). Have been using kite api for some time now, this has happend for the first time . I used kite (android )in the morning before loggingin in kiteconnect , is that where the issues started ? Have checked and rechecked the details(api key,api secret key , request token(s) ) and code (both for acesss_token and websocket ) multiple times .
would really appreiciate if someone can help a not-so-techie in solving this problem @sujith@rakeshr@mag
i use pycharm (but also tried in vscode and py idle bu got same poblem(s)) in ubuntu 22.04 i python kteconnect (pip show kiteconnect) Name: kiteconnect Version: 4.1.0 Summary: The official Python client for the Kite Connect trading API Home-page: https://kite.trade Author: Zerodha Technology Pvt. Ltd. (India) Author-email: [email protected] License: MIT Location: /home/astolisher/.local/lib/python3.10/site-packages Requires: autobahn, enum34, pyOpenSSL, python-dateutil, requests, service-identity, six
This error can only come if you are using an wrong access_token in WebSocket initialization. You need to re-check, if you are sending it as a proper string, without padding any extra string/spaces.
thanx for the reply @rakeshr checked it again but it is giving the same error and also why am i generating the same access token every time ( with different request token) . Is it because I logged in kite (android app) before , i saw in some threads @sujith was saying all kite platforms are interwined due to regulations and logging in (or out) from other platforms can mess with kiteconnect
iam getting this debug along with same acesstoken DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): api.kite.trade:443 DEBUG:urllib3.connectionpool:https://api.kite.trade:443 "POST /session/token HTTP/1.1" 200 None
i had similiiar issues with websocket (403) error weeks ago also , but got sorted out with generating a new accesstoken
@rakeshr in the first message i mentioned a thread with a similiar problem ... but no solution was given in the end plz go through the thread( and my initial messsg i hv explained my problem in detail )
this is the code i use , padding of the string ishighly unlikely bt stll hv stried doing it manualy in various websocket codes (also the sample documentation code with same eror) def update_token(): logging.basicConfig(level=logging.DEBUG) kite = KiteConnect(api_key="hiding from public") x=input('request token here) data = kite.generate_session(x, api_secret="hiding from public") kite.set_access_token(data["access_token"]) accesstoken=data['access_token'] d = {'api_key': 'removed from public', 'api_secret': 'removed from public' , 'access_token': accesstoken} with open('/media/astolisher/data/api/instruments file etc/kite api.txt','w') as file: file.write(json.dumps(d))
def get_acesstoken(): f=open('/media/astolisher/data/api/instruments file etc/kite api.txt','r+') d=json.load(f) acesstoken=['acecss_token'] f.close() return acesstoken # at=get_acesstoken() in websocket codes i highy doubt there is a coding error , its probabaly api functioning error (probably on my end ) or unwareness of dos and donts by a rookie
Would really apprecite if you can pinpoint the reason for error and sol for it asap and once again thanx for your quick reply
lil update , now errors are iterating between (403,closed reason without close code and dropped tcp without previous closing handshake)
this is the code i used with asimiliar one for full data ..was working like butter till friday accesstoken= 'rNmoo8jcMBR20pxUQ2o3IgTzDIm0CBT7' # write acesstoken
tokens=functions.activaten100t() #list of stocks to get apikey='' kws = KiteTicker(apikey, accesstoken) logging.basicConfig(level=logging.DEBUG) def on_connect(ws, response): ws.subscribe(tokens) ws.set_mode(ws.MODE_LTP, tokens) #cahnge mode def on_close(ws, code, reason): logging.info('Websocket connection has been closed') kws.on_connect = on_connect kws.on_close = on_close kws.connect(threaded=True) while True : def on_ticks(ws, ticks): print(ticks) function1(ticks) #function(s) def function1(ticks): for t in ticks: folder='/media/astolisher/data/live data/' # define the folder to store the into i=t['instrument_token'] ts= symbol_fortoken(i) file=initiate_file(tokens=ts,filecolumnslist=['tradingsymbol','instrument_token','last_price','timestamp'],path=folder) # define the columns of the using folder l=t['last_price'] time=datetime.datetime.now() dt=pd.DataFrame({'tradingsymbol':ts ,'instrument_token':i,'last_price':l,'timestamp':[time] }) file=pd.concat([file,dt]) file.to_csv('/media/astolisher/data/live data/'+ts+'.csv')
kws.on_ticks = on_ticks
would appreciate if someone can give it a quick look and help me out @sujith@rakeshr (i stole this code idea from @rakeshr in some thread so full credits (and thanks ) to him for a simple yet efficient code (till today morning it was
I am also facing the same issue as @asto is going through. It was working till yesterday and today i have logged into the kite web application before generating REQUEST_TOKEN and ACCESS_TOKEN. Websocket connection is closing with the same issue as mentioned above by @asto 'Connection closed: 1006 - connection was closed uncleanly (peer dropped the TCP connection without previous WebSocket closing handshake)'.
I have tried generating the both REQUEST_TOKEN and ACCESS_TOKEN multiple times and observed that the ACCESS_TOKEN remained same even when NEW REQUEST_TOKEN is generated.
Have also tried deleting the session token using the call 'DELETE /session/token Logout and invalidate the API session and access_token' call mentioned in 'https://kite.trade/docs/connect/v3/user/' page which was successful.
This time around after deleting the session token, i could generate the NEW REQUEST_TOKEN and NEW ACCESS_TOKEN but still observed that the websocket started failing with the same issue.
I have been using Kite Connect streaming for a quite long time now and it was working fine till yesterday i.e September 19. Today i feel the logging into the application before generating the tokens have something to do with the issues i am observing. I never faced any issue like this before even when i logged into the application before generating the tokens.
Was there any new changes that has been pushed recently or was there any version changes for any of the packages that the platform is using which is breaking the current functionality or is there something else which is effecting the functionality which was working perfectly for last few months.
@sujith@rakeshr@MAG Kindly have a look into the same and let us know the solution with. Would appreciate your time in this regard.
Just a update: Checked out most of the possibilities and have also checked that there are no spaces or tabs being introduced for REQUEST_TOKEN and ACCESS_TOKEN tokens.
And also even tried logging out from all the kite applications, deleted tokens with the request mentioned above and generated new REQUEST_TOKEN and ACCESS_TOKEN tokens and tried too. Seems the issue exists.
Environment: Using Python API to authenticate and access kite connect.
@sujith workin fine now ,it seems it was an exceptional erorr on api part (which probably blocked access to websocket and api.generete_session for some reason ) got sorted out after i generated a new token in the afternoon and sorted out a few rather surprising errors in my codes ( tokens have to defined manully in a list, it isnt working if called by a function and that is still the case @sujith functions have been checked and rechecked many times, the list is same as the one being sent manualy yet its showing 1006 closed uncleanly.. )
@pdommata * try getting a token tomo when tokens get refreshed and do it bedore logging into any other kite instrument ( i logged in kite android yesterday probably that was were the problems started ) *look in you codes for erors (like kws.connect put inside a function )
* try defining tokens manually which worked for me * most imp run a safe ( documentation ) code in the morning , *try changeing Ides
*give it a few tries with different environments ... mine took a dozen attempts( along with couple of changes mentioned above in my code) to start functioning smoothly again
@pdommata try the things above , if you still face the issues feel free to send your code i ( and far more experienced devs than me) would surely look into code
@sujith@rakeshr a humble req to plz look into such unique errors on api's end , kite api is such a usefull tool with such a good broker but such unwanted errors (with no sols found in whole forum) totally spoils the fun (and makes you feel helpless) and also pin this discussion atleast one will get to know that this type of error is posssible and not just god saying f*** u trader
Code to use the generated tokens to initiate the stream below: ---------------------------initiate_stream.py-------------------start------------- from kiteconnect import KiteConnect from kiteconnect import KiteTicker import pandas as pd import datetime import pdb import json, config import numpy as np import pandas as pd import json import asyncio
Please correct me if i am doing something wrong here. If you observe in initiate_stream.py -- i have commented out code (bolded) which i have been using to use the details that are maintained in config file. But today i have directly given the tokens as in the code (Italic) and tried as well. This also is failing.
Usually i generate tokens and then i push my code to run on Google cloud servers.
Update here. Sorry my bad. I have subscribed to only one instrument_token which has expired and it seems to be the issue due to which my websocket has been getting disconnected.
checked it again but it is giving the same error and also
why am i generating the same access token every time ( with different request token) . Is it because I logged in kite (android app) before , i saw in some threads @sujith was saying all kite platforms are interwined due to regulations and logging in (or out) from other platforms can mess with kiteconnect
iam getting this debug along with same acesstoken
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): api.kite.trade:443
DEBUG:urllib3.connectionpool:https://api.kite.trade:443 "POST /session/token HTTP/1.1" 200 None
i had similiiar issues with websocket (403) error weeks ago also , but got sorted out with generating a new accesstoken
plz go through the thread( and my initial messsg i hv explained my problem in detail )
this is the code i use , padding of the string ishighly unlikely bt stll hv stried doing it manualy in various websocket codes (also the sample documentation code with same eror)
def update_token():
logging.basicConfig(level=logging.DEBUG)
kite = KiteConnect(api_key="hiding from public")
x=input('request token here)
data = kite.generate_session(x, api_secret="hiding from public")
kite.set_access_token(data["access_token"])
accesstoken=data['access_token']
d = {'api_key': 'removed from public', 'api_secret': 'removed from public' , 'access_token': accesstoken}
with open('/media/astolisher/data/api/instruments file etc/kite api.txt','w') as file:
file.write(json.dumps(d))
def get_acesstoken():
f=open('/media/astolisher/data/api/instruments file etc/kite api.txt','r+')
d=json.load(f)
acesstoken=['acecss_token']
f.close()
return acesstoken
# at=get_acesstoken() in websocket codes
i highy doubt there is a coding error , its probabaly api functioning error (probably on my end ) or unwareness of dos and donts by a rookie
Would really apprecite if you can pinpoint the reason for error and sol for it asap
and once again thanx for your quick reply
this is the code i used with asimiliar one for full data ..was working like butter till friday
accesstoken= 'rNmoo8jcMBR20pxUQ2o3IgTzDIm0CBT7' # write acesstoken
tokens=functions.activaten100t() #list of stocks to get
apikey=''
kws = KiteTicker(apikey, accesstoken)
logging.basicConfig(level=logging.DEBUG)
def on_connect(ws, response):
ws.subscribe(tokens)
ws.set_mode(ws.MODE_LTP, tokens) #cahnge mode
def on_close(ws, code, reason):
logging.info('Websocket connection has been closed')
kws.on_connect = on_connect
kws.on_close = on_close
kws.connect(threaded=True)
while True :
def on_ticks(ws, ticks):
print(ticks)
function1(ticks)
#function(s)
def function1(ticks):
for t in ticks:
folder='/media/astolisher/data/live data/' # define the folder to store the into
i=t['instrument_token']
ts= symbol_fortoken(i)
file=initiate_file(tokens=ts,filecolumnslist=['tradingsymbol','instrument_token','last_price','timestamp'],path=folder) # define the columns of the using folder
l=t['last_price']
time=datetime.datetime.now()
dt=pd.DataFrame({'tradingsymbol':ts ,'instrument_token':i,'last_price':l,'timestamp':[time] })
file=pd.concat([file,dt])
file.to_csv('/media/astolisher/data/live data/'+ts+'.csv')
kws.on_ticks = on_ticks
would appreciate if someone can give it a quick look and help me out
@sujith @rakeshr
(i stole this code idea from @rakeshr in some thread so full credits (and thanks ) to him for a simple yet efficient code (till today morning it was
iam stuck frrom past two days ...
I am also facing the same issue as @asto is going through. It was working till yesterday and today i have logged into the kite web application before generating REQUEST_TOKEN and ACCESS_TOKEN. Websocket connection is closing with the same issue as mentioned above by @asto 'Connection closed: 1006 - connection was closed uncleanly (peer dropped the TCP connection without previous WebSocket closing handshake)'.
I have tried generating the both REQUEST_TOKEN and ACCESS_TOKEN multiple times and observed that the ACCESS_TOKEN remained same even when NEW REQUEST_TOKEN is generated.
Have also tried deleting the session token using the call 'DELETE /session/token Logout and invalidate the API session and access_token' call mentioned in 'https://kite.trade/docs/connect/v3/user/' page which was successful.
This time around after deleting the session token, i could generate the NEW REQUEST_TOKEN and NEW ACCESS_TOKEN but still observed that the websocket started failing with the same issue.
I have been using Kite Connect streaming for a quite long time now and it was working fine till yesterday i.e September 19. Today i feel the logging into the application before generating the tokens have something to do with the issues i am observing. I never faced any issue like this before even when i logged into the application before generating the tokens.
Was there any new changes that has been pushed recently or was there any version changes for any of the packages that the platform is using which is breaking the current functionality or is there something else which is effecting the functionality which was working perfectly for last few months.
@sujith @rakeshr @MAG Kindly have a look into the same and let us know the solution with. Would appreciate your time in this regard.
Just a update: Checked out most of the possibilities and have also checked that there are no spaces or tabs being introduced for REQUEST_TOKEN and ACCESS_TOKEN tokens.
And also even tried logging out from all the kite applications, deleted tokens with the request mentioned above and generated new REQUEST_TOKEN and ACCESS_TOKEN tokens and tried too. Seems the issue exists.
Environment: Using Python API to authenticate and access kite connect.
Thanks & Regards
got sorted out after i generated a new token in the afternoon and sorted out a few rather surprising errors in my codes ( tokens have to defined manully in a list, it isnt working if called by a function and that is still the case @sujith functions have been checked and rechecked many times, the list is same as the one being sent manualy yet its showing 1006 closed uncleanly.. )
@pdommata
* try getting a token tomo when tokens get refreshed and do it bedore logging into any other kite instrument ( i logged in kite android yesterday probably that was were the problems started )
*look in you codes for erors (like kws.connect put inside a function )
* try defining tokens manually which worked for me
* most imp run a safe ( documentation ) code in the morning ,
*try changeing Ides
*give it a few tries with different environments ... mine took a dozen attempts( along with couple of changes mentioned above in my code) to start functioning smoothly again
@pdommata try the things above , if you still face the issues feel free to send your code i ( and far more experienced devs than me) would surely look into code
@sujith @rakeshr a humble req to plz look into such unique errors on api's end , kite api is such a usefull tool with such a good broker but such unwanted errors (with no sols found in whole forum) totally spoils the fun (and makes you feel helpless)
and also pin this discussion atleast one will get to know that this type of error is posssible and not just god saying f*** u trader
I generally do generate tokens manually. (Correct me if i am wrong if i am not doing so with the below code pasted below.)
Code to generate tokens:
---------------------------- authenticate_app.py----------start----------------------
from kiteconnect import KiteConnect
from kiteconnect import KiteTicker
import pandas as pd
import datetime
import pdb
import json, config
import numpy as np
import pandas as pd
import json
import asyncio
kws = ""
kite = ""
api_key = config.API_KEY
api_secret = config.API_SECRET
request_token = config.REQUEST_TOKEN
access_token = config.ACCESS_TOKEN
def get_login(api_key, api_secret):
global kws, kite
kite = KiteConnect(api_key=api_key)
print("[*] Generate access Token : ", kite.login_url())
request_token = input("[*] Enter Your Request Token Here : ")
data = kite.generate_session(request_token, api_secret=api_secret)
print(data)
get_login(api_key, api_secret)
--------------------------------authenticate_app.py---------End---------------
Code to use the generated tokens to initiate the stream below:
---------------------------initiate_stream.py-------------------start-------------
from kiteconnect import KiteConnect
from kiteconnect import KiteTicker
import pandas as pd
import datetime
import pdb
import json, config
import numpy as np
import pandas as pd
import json
import asyncio
kws = ""
kite = ""
api_key = config.API_KEY
api_secret = config.API_SECRET
request_token = config.REQUEST_TOKEN
access_token = config.ACCESS_TOKEN
tokens = [61307911]
def get_login(api_key, api_secret):
global kws, kite
kite = KiteConnect(api_key=api_key)
kite.set_access_token(access_token)
kws = KiteTicker(api_key, access_token)
def on_ticks(ws, ticks):
for tick in ticks:
print(str(tick))
def on_close(ws):
print("Connection closed")
def on_connect(ws, response):
ws.subscribe(tokens)
ws.set_mode(ws.MODE_FULL, tokens) # MODE_FULL , MODE_LTP, MODE_QUOTE
# get_login(api_key, api_secret)
# kws.on_ticks = on_ticks
# kws.on_connect = on_connect
# kws.connect()
kite = KiteConnect(api_key='')
kite.set_access_token('')
kws = KiteTicker('', '')
kws.on_ticks = on_ticks
kws.on_connect = on_connect
kws.connect()
--------------------------------------initiate_stream.py--------------end----------------------
Please correct me if i am doing something wrong here. If you observe in initiate_stream.py -- i have commented out code (bolded) which i have been using to use the details that are maintained in config file. But today i have directly given the tokens as in the code (Italic) and tried as well. This also is failing.
Usually i generate tokens and then i push my code to run on Google cloud servers.
Your time would be appreciated.
Thanks and Regards
Update here. Sorry my bad. I have subscribed to only one instrument_token which has expired and it seems to be the issue due to which my websocket has been getting disconnected.
Thanks again.