It looks like you're new here. If you want to get involved, click one of these buttons!
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
kite_ws.on_close = on_close
. It will auto re-connect.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.