Connection error: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (403 -

AkashTawade
KiteTicker is not working today.
Is it the issue or kiteconnect does not work on market holidays.
  • sujith
    403 means your session is expired and you need to log in again and generate another access token.
  • neerleo88
    @sujith I am also facing similar problem. connection is closing and re establishing very frequently in every 5-10 minutes. Please find below details

    0 2019-01-14 09:34:45 27253.6
    ERROR:kiteconnect.ticker:Connection error: 1006 - connection was closed uncleanly (None)
    ERROR:root:closed connection on error: 1006 connection was closed uncleanly (None)
    ERROR:kiteconnect.ticker:Connection closed: 1006 - connection was closed uncleanly (None)
    0 2019-01-14 09:35:03 27251.95


    Below it took more than 1 min
    0 2019-01-14 09:38:03 27265.35
    ERROR:kiteconnect.ticker:Connection error: 1006 - connection was closed uncleanly (None)
    ERROR:root:closed connection on error: 1006 connection was closed uncleanly (None)
    ERROR:kiteconnect.ticker:Connection closed: 1006 - connection was closed uncleanly (None)
    ERROR:kiteconnect.ticker:Retrying connection. Retry attempt count: 1. Next retry in around: 3 seconds
    ERROR:kiteconnect.ticker:Retrying connection. Retry attempt count: 2. Next retry in around: 10 seconds
    0 2019-01-14 09:39:15 27264.55


    0 2019-01-14 10:00:29 27231.05
    ERROR:kiteconnect.ticker:Connection error: 1006 - connection was closed uncleanly (None)
    ERROR:root:closed connection on error: 1006 connection was closed uncleanly (None)
    ERROR:kiteconnect.ticker:Connection closed: 1006 - connection was closed uncleanly (None)
    0 2019-01-14 10:00:36 27228.7

    0 2019-01-14 10:12:54 27231.85
    ERROR:kiteconnect.ticker:Connection error: 1006 - connection was closed uncleanly (None)
    ERROR:root:closed connection on error: 1006 connection was closed uncleanly (None)
    ERROR:kiteconnect.ticker:Connection closed: 1006 - connection was closed uncleanly (None)
    ERROR:kiteconnect.ticker:Retrying connection. Retry attempt count: 1. Next retry in around: 3 seconds
    0 2019-01-14 10:13:23 27224.65

    0 2019-01-14 10:26:03 27231.6
    ERROR:kiteconnect.ticker:Connection error: 1006 - connection was closed uncleanly (None)
    ERROR:root:closed connection on error: 1006 connection was closed uncleanly (None)
    ERROR:kiteconnect.ticker:Connection closed: 1006 - connection was closed uncleanly (None)
    ERROR:kiteconnect.ticker:Retrying connection. Retry attempt count: 1. Next retry in around: 2 seconds
    0 2019-01-14 10:26:33 27233.7
  • neerleo88
    Please note : I am NOT getting error 403.
  • sujith
    @neerleo88,
    You can try the link suggested by @zartimus here.
  • neerleo88
    @sujith I have already gone through the link but there was no solution provided there. Can you please let me know if I am missing something
  • neerleo88
    @sujith Can you please provide me the solution. I need to run my strategies in order to place trades.
  • neerleo88
    @sujith Is there any update on this issue ??
  • rakeshr
    @neerleo88
    Can you paste your Websocket code here? We will once debug the same at our end.
  • neerleo88
    neerleo88 edited January 2019
    import win32com.client
    import time
    import logging
    from kiteconnect import KiteConnect
    from kiteconnect import KiteTicker
    import datetime
    from datetime import timedelta
    #from datetime import time
    import pandas as pd
    import numpy as np
    import logging
    import pymysql

    db=pymysql.connect(host='localhost',user='root',password='*********',database='ticker_value')
    insert_query='insert into nifty_bank_2(date,last_price) values(%(date)s,%(last_price)s)'

    def insert_ticks(ticks):
    db_cursor=db.cursor()
    for tick in ticks:
    db_cursor.execute(insert_query,{'date':tick['timestamp'],'last_price':tick['last_price']})
    try:
    db.commit()
    except Exception:
    db.rollback()

    api_key="**********"
    api_secret="**************************"
    kite=KiteConnect(api_key=api_key)

    data = kite.generate_session("*****", api_secret=api_secret)
    access_token=data["access_token"]
    kite.set_access_token(access_token)
    tokens=[260105]
    kws=KiteTicker(api_key, access_token)
    def on_ticks(ws,ticks):

    data1 = pd.DataFrame(ticks)
    print(data1[["timestamp","last_price"]].to_string(header=False))
    insert_tick=insert_ticks(ticks)
    def on_connect(ws,response):
    ws.subscribe(tokens)
    ws.set_mode(ws.MODE_FULL,[260105])
    def on_close(ws,code,reason):
    ws.stop()
    def on_order_update(ws, data):
    print("order update: ", data)
    def on_noreconnect(ws):
    logging.error("Reconnecting the websocket failed")
    def on_error(ws, code, reason):
    logging.error("closed connection on error: {} {}".format(code, reason))
    def on_reconnect(ws, attempt_count):
    logging.debug("Reconnecting the websocket: {}".format(attempt_count))

    kws.on_ticks = on_ticks
    kws.on_connect = on_connect
    kws.on_error = on_error
    kws.on_noreconnect = on_noreconnect
    kws.on_reconnect = on_reconnect
    kws.on_order_update = on_order_update
    kws.connect()

  • neerleo88
    @rakeshr @sujith Can you please check the above.
    Today also same kind of behavior is happening.

    0 2019-01-15 09:42:42 27394.4
    ERROR:kiteconnect.ticker:Connection error: 1006 - connection was closed uncleanly (None)
    ERROR:root:closed connection on error: 1006 connection was closed uncleanly (None)
    ERROR:kiteconnect.ticker:Connection closed: 1006 - connection was closed uncleanly (None)
    0 2019-01-15 09:43:03 27394.8
    0 2019-01-15 09:43:04 27394.3
    0 2019-01-15 09:43:05 27394.1
  • rakeshr
    @neerleo88
    def on_ticks(ws,ticks):
    data1 = pd.DataFrame(ticks)
    print(data1[["timestamp","last_price"]].to_string(header=False))
    insert_tick=insert_ticks(ticks)
    You are blocking main thread by using insert_ticks() in same thread, you need to kws.connect(threaded=True) and then pass on the value to another thread.You can check an example of mult-threading here.
  • zartimus
    zartimus edited January 2019
    @neerleo88 As @rakeshr said you are doing db ops inside ticks functions.

    We do not give coding support, but because this query is being repeated multiple times. Here is bare minimum program to delegate such intensive task to another thread.

    python 2 (queue import is slightly different in python 3)
    import sys
    import time
    import sqlite3
    import logging
    from Queue import Queue
    from threading import Thread

    from kiteconnect import KiteTicker

    logging.basicConfig(level=logging.DEBUG)

    DB_NAME = "sample.db"

    class QueueSQLWrapper(Thread):

    def __init__(self, db_name):
    super(QueueSQLWrapper, self).__init__()
    self.db_name = db_name
    self.q = Queue()

    # Start consumer thread
    self.start()

    def run(self):
    """Consumer function
    """
    conn = sqlite3.connect(self.db_name)
    cursor = conn.cursor()

    while True:
    req, arg, res = self.q.get()
    if req == "kill":
    break

    cursor.execute(req, arg)

    # Commiting because i want to see the records right away
    conn.commit()

    conn.close()

    def execute(self, req, arg=None, res=None):
    self.q.put((req, arg or tuple(), res))

    def close(self):
    self.execute("kill")


    # Create our special sql instance
    sql = QueueSQLWrapper(db_name=DB_NAME)
    sql.execute("create table nifty_schwifty(date TEXT, last_price REAL)")


    def on_ticks(ws, ticks):
    """Producer function
    """
    try:
    for tick in ticks:
    sql.execute(
    "insert into nifty_schwifty values(?,?)",
    (str(tick['timestamp']), tick['last_price'])
    )
    except KeyboardInterrupt:
    sql.close()
    sys.exit(1)


    def on_connect(ws, response):
    ws.subscribe([341249])
    ws.set_mode(ws.MODE_FULL, [341249])


    if __name__ == "__main__":
    kws1 = KiteTicker("<API-KEY>", "<ACCESS-TOKEN>", debug=True)

    kws1.on_ticks = on_ticks
    kws1.on_connect = on_connect

    try:
    kws1.connect()
    except KeyboardInterrupt:
    sql.close()
    sys.exit(1)
  • neerleo88
    @rakeshr
    I have made the changes you suggested But now I am not getting any ticker
    Please find below the code
    kws.on_ticks = on_ticks
    kws.on_connect = on_connect
    #kws.on_close = on_close
    kws.on_error = on_error
    kws.on_noreconnect = on_noreconnect
    kws.on_reconnect = on_reconnect
    kws.on_order_update = on_order_update
    #kws.enable_reconnect(reconnect_interval=1, reconnect_tries=50)
    kws.connect(threaded=True)

    process is finishing before giving any ticker value
  • neerleo88
    neerleo88 edited January 2019
    @zartimus
    As you and @rakeshr suggested ,there might be a problem with db operation which I was doing within on_ticks(). So I removed the db operation and just print the ticks value. This time also I got the same error.

    0 2019-01-15 12:48:01 27379.3
    0 2019-01-15 12:48:02 27379.9
    Connection error: 1006 - connection was closed uncleanly (None)
    ERROR:root:closed connection on error: 1006 connection was closed uncleanly (None)
    ERROR:kiteconnect.ticker:Connection closed: 1006 - connection was closed uncleanly (None)
    0 2019-01-15 12:48:11 27379.95
    0 2019-01-15 12:48:12 27380.35

    Can you provide me the right solution. Can you please identify if there is any problem from you side?

    According to me there is some issue within kws.connect() that's why it is closing and reconnecting in every few minutes.

  • neerleo88
    @zartimus @rakeshr CAn you please look into this issue and provide me the solution. Due to data issue I am unable to place trades.
  • zartimus
    @neerleo88 Did you try with sample examples provided with pykiteconnect ?https://github.com/zerodhatech/pykiteconnect/blob/master/examples/ticker.py.

    No issues here.
  • neerleo88
    neerleo88 edited January 2019
    @zartimus @rakeshr

    Please check my code I provided above . I have used the same code as Example.
    How can you say no issues here where I and other members have been providing you the evidence.

    Please find more evidence below.

    0 2019-01-15 15:10:21 27407.25
    0 2019-01-15 15:10:22 27408.55
    ERROR:kiteconnect.ticker:Connection error: 1006 - connection was closed uncleanly (None)
    ERROR:root:closed connection on error: 1006 connection was closed uncleanly (None)
    ERROR:kiteconnect.ticker:Connection closed: 1006 - connection was closed uncleanly (None)
    ERROR:kiteconnect.ticker:Connection error: 1006 - connection was closed uncleanly (WebSocket opening handshake timeout (peer did not finish the opening handshake in time))
    ERROR:root:closed connection on error: 1006 connection was closed uncleanly (WebSocket opening handshake timeout (peer did not finish the opening handshake in time))
    ERROR:kiteconnect.ticker:Connection closed: 1006 - connection was closed uncleanly (WebSocket opening handshake timeout (peer did not finish the opening handshake in time))
    ERROR:kiteconnect.ticker:Connection error: 1006 - connection was closed uncleanly (WebSocket opening handshake timeout (peer did not finish the opening handshake in time))
    ERROR:root:closed connection on error: 1006 connection was closed uncleanly (WebSocket opening handshake timeout (peer did not finish the opening handshake in time))
    ERROR:kiteconnect.ticker:Connection closed: 1006 - connection was closed uncleanly (WebSocket opening handshake timeout (peer did not finish the opening handshake in time))
    0 2019-01-15 15:11:18 27406.05
    0 2019-01-15 15:11:19 27406.75
    0 2019-01-15 15:11:20 27403.55
    0 2019-01-15 15:11:21 27402.4
    0 2019-01-15 15:11:22 27402.15
    0 2019-01-15 15:11:23 27402.45
  • sujith
    @neerleo88,
    The library is being used on many production apps which includes our own products as well.
    We don't see any issue.
    I would suggest going through API documentation and pykiteconnect documentation to know more insights about the Kite Connect.

    Please do note that we don't provide solutions or support for writing strategies.
  • neerleo88
    neerleo88 edited January 2019
    @sujith
    With all due respect I want you to understand below points
    1. I didn't ask any code or solution for my personal strategies .
    2. I have used all the methods and done all the coding according to API docs only .
    3. I haven't included my strategies in it yet. I am simply fetching data from ticker and that too only for Nifty Bank
    4. I know, you guys are now biggest broker in India and library is being used on many places BUT at the same time I have seen many issues in API which have been raised by other member too.
    5. For two days I am continuously providing you the evidence of connection and re connection but instead of looking into the issue , every time you guys are putting a comment which is not at all providing the solution , instead , I feel you guys are just trying to avoid the issue any how.

    Other Issues.

    1. Your 5 min historical data provides wrong data on 5 min chart. In other discussion you guys told no to use historical data for live trading.So that means now we are depended on your ticker
    2. Your ticker values lacks at-least 2-3 seconds. Which I haven't raised it yet

    Since you have told me there is no issue with your libraries , just provide me the bare minimum code here in which you have confidence that no similar error will occur. I will run as it is on my side (with my api key and access token), and if I don't get similar error from 9:15 to 3:30. I won't disturb you guys again and please note here, I am not asking you to write any strategies for me . Its only to fetch ticker values that it,which is the core purpose of providing API to customer. Which will only be 5 minute job for you guys
  • zartimus
    @neerleo88 This "evidence" you are showing is not helping. The code you had provided is buggy because it was blocking on_tick callback.

    Unclean closure of a websocket can happen for several different reasons starting from having a bad network connection.

    We do not get any error with the bare minimum examples. How do you expect us to debug if we don't get such errors / fail to replicate one on our end?
  • neerleo88
    @zartimus @rakeshr @sujith
    Please don't play the developer tester game here i.e. its working in my machine and not working in your machine.

    below is the code to print ticker only and it is based on your documentation itself . No additional logic implemented. Please let me know where blocking in on_tick() callback because this time also , within 30 min I am getting the same error message.

    If the code(which is exactly like your documentation) is buggy the provide me the exact code line which has bug and why

    Please Note : I didn't use on_close() on purpose because I don't want the execution to stop. And that is too according to your suggestion provided in different discussion thread.

    import time
    import logging
    from kiteconnect import KiteConnect
    from kiteconnect import KiteTicker
    import pandas as pd
    api_key="************"
    api_secret="************************"
    kite=KiteConnect(api_key=api_key)
    access_token="******************"
    kite.set_access_token(access_token)
    tokens=[260105]
    kws=KiteTicker(api_key, access_token)

    def on_ticks(ws,ticks):
    data1 = pd.DataFrame(ticks)
    print(data1[["timestamp", "last_price"]])

    def on_connect(ws,response):
    ws.subscribe(tokens)
    ws.set_mode(ws.MODE_FULL,[260105])

    def on_close(ws,code,reason):
    ws.stop()

    kws.on_ticks = on_ticks
    kws.on_connect = on_connect
    kws.connect()

    Below are the are the error messages occurs at different time
    0 2019-01-16 09:25:39    27503.35
    timestamp last_price
    0 2019-01-16 09:25:40 27501.5
    Connection error: 1006 - connection was closed uncleanly (None)
    Connection closed: 1006 - connection was closed uncleanly (None)
    timestamp last_price
    0 2019-01-16 09:25:52 27499.3
    timestamp last_price
    0 2019-01-16 09:25:53 27501.2
    0 2019-01-16 09:59:39    27522.95
    timestamp last_price
    0 2019-01-16 09:59:40 27523.65
    timestamp last_price
    0 2019-01-16 09:59:41 27523.55
    Connection error: 1006 - connection was closed uncleanly (None)
    Connection closed: 1006 - connection was closed uncleanly (None)
    Connection error: 1006 - connection was closed uncleanly (WebSocket opening handshake timeout (peer did not finish the opening handshake in time))
    Connection closed: 1006 - connection was closed uncleanly (WebSocket opening handshake timeout (peer did not finish the opening handshake in time))
    timestamp last_price
    0 2019-01-16 10:00:43 27533.15
    timestamp last_price
    0 2019-01-16 10:00:44 27531.1
    timestamp last_price
    0 2019-01-16 10:00:45 27532.75
    0 2019-01-16 10:37:10    27532.95
    timestamp last_price
    0 2019-01-16 10:37:11 27533.2
    timestamp last_price
    0 2019-01-16 10:37:12 27530.6
    Connection error: 1006 - connection was closed uncleanly (None)
    Connection closed: 1006 - connection was closed uncleanly (None)
    timestamp last_price
    0 2019-01-16 10:37:28 27531.65
    timestamp last_price
    0 2019-01-16 10:37:29 27534.15
    timestamp last_price
    0 2019-01-16 10:37:30 27534.05
    Please do not say here that these error only occurring at my side and everywhere its working fine BECAUSE below is the link for another discussion thread where someone else has faced the same issue and there also you guys didn't provide the solution

    https://kite.trade/forum/discussion/5426/error-while-live-streaming-data#latest

    If these evidence are not enough then please let me know what else is required and how I can provide them
This discussion has been closed.