Handling websocket errors

nkmrao
For some weird reason, I keep getting the 'Connection error: 1006 - connection was closed uncleanly' error with websockets on my EC2 instance. My code works fine on my personal computer, but this error keeps occurring on the VM frequently.

I read live prices for some instruments and write them to a file as and when they are received. This writing of data is done in the on_ticks callback through a helper_method. I managed to figure out that writing to the file is causing the connection error, perhaps because the computer is still writing the previous data when a new tick is received?

Anyway, I am now resigned to the fact that this error will keep occurring and not really concerned about why it might be happening. What I want to know is how to handle this error and restart the websocket automatically when it occurs. Typically, an on_error callback is provided with websockets, but in case of kiteconnect, this method is not available. So, how would one go about handling these websocket errors as standard try...except does not work?

An example code will be much appreciated.
Here is part of my code for reference -
def on_ticks(ws, ticks):
# Callback to receive ticks
logging.debug('Tick: {}'.format(ticks))

def on_connect(ws, response):
# Callback on successful connect.
ws.subscribe(instr_token_list)
ws.set_mode(ws.MODE_FULL, instr_token_list)

def on_close(ws, code, reason):
# On connection close stop the main loop
# Reconnection will not happen after executing `ws.stop()`
ws.stop()

# Assign the callbacks.
kite_ws.on_ticks = on_ticks
kite_ws.on_connect = on_connect
kite_ws.on_close = on_close

# Infinite loop on the main thread. Nothing after this will run.
# You have to use the pre-defined callbacks to manage subscriptions.
kite_ws.connect(threaded=True)

while True:
def on_ticks(ws, ticks):
helper_method(ticks)

def helper_method(ticks):
save_in_folder = 'Live Data'
filenames = [save_in_folder+'\\'+s+'_'+date_today+'.txt' for s in symbols]

print('Extracting data')

instr1 = [x for x in ticks if x['instrument_token'] == instr_token_list[0]]
instr2 = [x for x in ticks if x['instrument_token'] == instr_token_list[1]]
instr3 = [x for x in ticks if x['instrument_token'] == instr_token_list[2]]
instr4 = [x for x in ticks if x['instrument_token'] == instr_token_list[3]]
instr5 = [x for x in ticks if x['instrument_token'] == instr_token_list[4]]
instr6 = [x for x in ticks if x['instrument_token'] == instr_token_list[5]]

print('Data extracted')

quote_list = [instr1, instr2, instr3, instr4, instr5, instr6]

for i in range(len(quote_list)):
symbol = symbols[i]
if len(quote_list[i]) > 0:
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
_open = quote_list[i][0]['ohlc']['open']
high = quote_list[i][0]['ohlc']['high']
low = quote_list[i][0]['ohlc']['low']
ltp = quote_list[i][0]['last_price']

print('Writing to file...')

### This is the part causing the connection error. Without these lines, it works fine with no interruption
file = filenames[i]
append_row = '\n' + timestamp + ',' + symbol + ',' + str(_open) + ',' + str(high) + ',' + str(low) + ',' + str(ltp)
with open(file, 'a+') as f:
f.write(append_row)

print('Writing complete')

kite_ws.on_ticks=on_ticks
  • rakeshr
    @nkmrao
    What I want to know is how to handle this error and restart the websocket automatically when it occurs
    You can just remove the def on_close(ws, code, reason) method callback i.e . kite_ws.on_close = on_close. It will auto re-connect.
  • sujith
    If you are getting this error then you are blocking the main thread and you might be missing a few ticks.
    You can refer to the python FAQs to know the solution.

    on_error callback is to listen to the error messages sent from the server error.
Sign In or Register to comment.