Connection Error 1006

chiragkeswani
Hello everyone,
For past few days, I am continuously facing web socket disconnection issue. I am generating candles using the web socket data. But as web socket gets disconnected, it is not able to collect all the ticks and create correct candle. Below is the error:

Connection closed: 1006 - connection was closed uncleanly (None)
Connection error: 1006 - connection was closed uncleanly (None)

Whole log file is filled with this only. I have been trying to find the solution for the same on the forum but it's not working.
I would really appreciate the help. Thanks in advance.

Thanks, Regards,
Chirag Keswani
  • rakeshr
    @chiragkeswani
    Can you check if you are not blocking on_tick method in any condition? If you are performing any additional calculation on on_tick method, you need to pass it to a different thread to prevent blocking of the on_tick method.
  • chiragkeswani
    @rakeshr
    Yes, I checked that. It is not blocking on_tick method at all. I am just initiating a new thread once I receive the tick.
    It was working fine for long time but once I setup it on a new system, it has started giving this issue. Any chance there is any problem in configuration?
  • rakeshr
    @chiragkeswani
    Can you paste here your WebSocket code,we will look to it?
  • gkaranam
    gkaranam edited July 2019
    Hi @rakeshr

    i am also facing the same issue where i continuously get the below errors.

    Connection closed: 1006 - connection was closed uncleanly (None)
    Connection error: 1006 - connection was closed uncleanly (None)

    Pasting my websocket and connection code for your reference.
    ----------------------------------------------------------------------------------------------------------------------
    def on_ticks(ws, ticks):  # retrieve continuous ticks in JSON format
    global ohlc_final_1min, RENKO_Final, final_position, order_quantity
    try:
    for company_data in ticks:
    if (company_data['last_trade_time'].time()) > datetime.time(9, 15,00) and (company_data['last_trade_time'].time()) < datetime.time(15, 31,00):
    calculate_ohlc_one_minute(company_data)
    RENKO_TRIMA(company_data)
    except Exception as e:
    traceback.print_exc()


    def on_connect(ws, response):
    ws.subscribe([x for x in trd_portfolio])
    ws.set_mode(ws.MODE_FULL, [x for x in trd_portfolio])


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

    Can you please look into this, as i am not using the historical data and am using the ticks to form my analysis and decision.
  • rakeshr
    @gkaranam
    You are blocking on_tick method by calling internal methods within.You need to pass it as thread without blocking it, check multi-threading example here.
  • gagneetkalsi
    gagneetkalsi edited June 2019
    Hi @rakeshr ,

    I have the same error.

    Without fail, it gives me an error at 9:16 when I try to do some computations in a different thread, but then it runs rather smoothly throughout rest of the day.
    Just when I try to do some calculations at 9:16, it fails. And it happens everyday at the same time. If there was a problem with the ticker code, I should face this issue throughout the day, but I can't figure out why it is always at the same time.


    My ticker code is as follows:

    def on_ticks(ws, ticks):
    global TICKS
    TICKS = TICKS.append(pd.DataFrame(ticks)[['instrument_token','timestamp,'last_price']],ignore_index=True)

    def on_connect(ws, response):
    ws.subscribe(Data.instrument_token.tolist())
    ws.set_mode(ws.MODE_FULL,(Data.instrument_token.tolist())

    # Assign the callbacks.
    kws.on_ticks = on_ticks
    kws.on_connect = on_connect

    kws.connect(threaded=True)
  • rakeshr
    @gagneetkalsi
    Can you implement on_error method and paste the complete error log here?
    Also, we will check the same at our end for threading error at 09:16 AM.
  • chiragkeswani
    @rakeshr
    Below is my websocket part. I believe it is not blocking the on_tick module but can you please share your view.
        def check_entry(self, thread_name, ticks, ws):

    for _tick in ticks:
    """processing ticks"""
    pass # some other stuff in actual code

    def on_ticks(self, ws, ticks):
    thread_name = "Thread-" + str(KiteWebSocket.thread_count + 1)
    try:
    _thread.start_new_thread(self.check_entry, (thread_name, ticks, ws))
    except Exception as e:
    print(e)

    def on_connect(self, ws, response):
    try:
    ws.subscribe(sd.instrument_list)
    ws.set_mode(ws.MODE_FULL, sd.instrument_list)
    KiteWebSocket.instrument_list = []
    except Exception as e:
    print(e)

    def on_error(self, ws, code, reason):
    sd.error_log(code, reason)

    def on_noreconnect(self, ws):
    sd.error_log_2("Reconnecting the websocket failed")

    def start(self):
    sd.pprint('Starting websocket...')
    self.kws.on_ticks = self.on_ticks
    self.kws.on_connect = self.on_connect
    self.kws.on_error = self.on_error
    self.kws.on_noreconnect = self.on_noreconnect
    self.kws.connect(threaded=True)
  • guptak03
    Hi @rakeshr ,

    We all are having a similar error it would be great if someone looks into this issue and help us.

    Thanks in advance
  • chiragkeswani
    Hi @rakeshr, did you get a chance to look at the code snippet?
  • chiragkeswani
    Any updates guys?
  • sujith
    You can check out this thread.
  • chiragkeswani
    @sujith, implementing multiple instances is not feasible for retail traders like us. If the disconnection issue happens once or twice for a couple of seconds, then we can ignore it, but this error continues for almost whole day. The purpose of automation itself gets flawed due to this.
    1.png 90.2K
  • rakeshr
    @chiragkeswani
    We tried same your above code and it's working fine at our end.Can you recheck if processing tick operation of check_entry is not throwing any local error? May be test check_entry method operation seperately by passing dummy value of params(thread_name, ticks,ws).
    def on_ticks(self,ws,ticks):
    _thread.start_new_thread(self.check_entry,('thread_name', ticks, ws))
    def check_entry(self,thread_name, ticks,ws):
    #Print statement
    print(ticks)
  • sujith
    If there is some heavy operation done after getting ticks which blocks main thread might cause this issue. So it is very important to make sure you do the threading things properly.

    We listen to ticks on all our platforms using the same Kite Ticker. We don't see any disconnections.
  • chiragkeswani
    Hi @sujith and @rakeshr,

    I have already checked operation of check_entry and it's not throwing any local error. I have passed the dummy value as well. it's not giving any issue.
    But when I am running it live with API, it is continuously giving issue.

    If it is running fine at your end, then please try to detect why the issue is happening at our end. It's not just me facing issue but many people are facing the same issue. There could be configuration issue or any dependency which we need to install.

    Looking forward to your help. Thanks in advance.
  • guptak03
    Yes , even I got the issue again.
    Please help us..
  • aceBox
    Facing a similar issue of frequent disconnection. Was this ever resolved?
  • rakeshr
    @aceBox
    As stated above, there is no dependency issue at our end. You need to make sure, main thread of on_ticks method is not blocked at your end because of heavy computation on same method.
  • gkaranam
    gkaranam edited December 2019
    Hi @sujith, @rakeshr ..

    I have followed the blog and modified the on_ticks method to thread the other methods which i was calling for other stuff. Still getting the below list of error messages.
    ---------------------------------------------------------------------------------------------------------
    Connection error: 1006 - connection was closed uncleanly (peer dropped the TCP connection without previous WebSocket closing handshake)
    Connection closed: 1006 - connection was closed uncleanly (peer dropped the TCP connection without previous WebSocket closing handshake)

    Connection error: 1006 - connection was closed uncleanly (None)
    Connection closed: 1006 - connection was closed uncleanly (None)

    Connection error: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (502 - BadGateway))
    Connection closed: 1006 - connection was closed uncleanly (WebSocket connection upgrade failed (502 - BadGateway))
    -----------------------------------------------------------------------------------------------------
    And below is the code which i modified.
    -----------------------------------------------------------------------------------------------------
    def on_ticks(ws, ticks): # retrieve continuous ticks in JSON format
    global ohlc_final_1min, RENKO_Final, final_position, order_quantity, ohlc_temp, candle_thread_running, renko_thread_running
    try:
    for company_data in ticks:
    if (candle_thread_running != "YES") and (renko_thread_running != "YES"):
    if (company_data['last_trade_time'].time()) > datetime.time(9,15,00) and (company_data['last_trade_time'].time()) < datetime.time(15,20,00):
    candle = threading.Thread(target=calculate_ohlc_one_minute, args=(company_data,))
    candle.start()
    renko = threading.Thread(target=RENKO_TRIMA, args=(company_data,))
    renko.start()
    else:
    pass
    except Exception as e:
    traceback.print_exc()
    ------------------------------------------------------------------------------------------------------
    What else would be the issue?
  • rakeshr
    @gkaranam
    We just tested your above threading code at our end and it worked perfectly fine. We created the dummy method for calculate_ohlc_one_minute and RENKO_TRIMA.
    Make sure that there is no error inside calculate_ohlc_one_minute and RENKO_TRIMA method. May be debug them individually by passing dummy ticks.
  • gkaranam
    that helps @rakeshr . Will look into it if there's any issue in the other issues with my methods. thanks a lot
This discussion has been closed.