How to reconnect websocket on disconnect or on close

gautam_s60
gautam_s60 edited April 2017 in Python client
How to reconnect websocket on disconnect or on close in Python?
Many times it's getting closed.
I read that it auto reconnect in Python but not getting reconnected in my case...
code optimization and suggestions are welcome but my major concern is intermittent disconnet of websocket.

my code as below (converts tick data to ohcl for half hour and update sqlite3 db for multiple stock)


#!/usr/bin/python
from kiteconnect import WebSocket
import pandas as pd
import requests
from pandas.io import sql
import io
import time
import sqlite3
import sqlalchemy as sa
import json
import csv
import time
import pandas_datareader.data as rd
from datetime import datetime
atho="c://xampp//htdocs//dashboard//tkns1.txt"

def on_tick(tick, ws):
#impo=0rt json
global dtf,r_reset,isexported
#print("b4",r_reset)
#print(len(tick))
if(r_reset==0):
print('r_reset reset',r_reset)
#isexported=0
tbl="""SELECT instrument_token, tradingsymbol FROM nfc"""
result=ghg.execute(tbl)
#print(len(result.fetchall()))
i=1
text1=''
text2=''
for row in result:
text1=text1+"""'in"""+str(i)+"""':"""+str(row[0])+','
text2=text2+"""'"""+str(row[0])+"""':{'o':0,'h':0,'l':100000,'c':0},"""
fno_ohcl[eval("""'"""+str(row[0])+"""'""")]={'o':0,'h':0,'l':100000,'c':0}
i=i+1
k=len(tick)
for i in range(0,len(tick)):
ltp1=tick[i]['last_price']
fno_ohcl[eval("""'"""+str(tick[i]['instrument_token'])+"""'""")]['o']=ltp1 if fno_ohcl[eval("""'"""+str(tick[i]['instrument_token'])+"""'""")]['o']==0 else fno_ohcl[eval("""'"""+str(tick[i]['instrument_token'])+"""'""")]['o']
fno_ohcl[eval("""'"""+str(tick[i]['instrument_token'])+"""'""")]['h']=ltp1 if fno_ohcl[eval("""'"""+str(tick[i]['instrument_token'])+"""'""")]['h']ltp1 else fno_ohcl[eval("""'"""+str(tick[i]['instrument_token'])+"""'""")]['l']
fno_ohcl[eval("""'"""+str(tick[i]['instrument_token'])+"""'""")]['c']=ltp1
name1=str(tick[i]['instrument_token'])
r_reset=1
now = datetime.now()
seconds_since_midnight = (now - now.replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds()
if((int(seconds_since_midnight/60) % dtf)==0.0 and isexported==0):
tbl="""SELECT instrument_token, tradingsymbol FROM nfc"""
result1=ghg.execute(tbl)
result=result1.fetchall()
print(fno_ohcl[eval("""'"""+str(result[0][0])+"""'""")]['o'])
for row in result:
if fno_ohcl[eval("""'"""+str(row[0])+"""'""")]['o']>0:
insert2="""INSERT INTO '"""+ str(row[1]) +"""' (name, open, high, low, close, timestamp) VALUES ('"""+str(row[1] )+"""',"""+str(fno_ohcl[eval("""'"""+str(row[0])+"""'""")]['o'])+""","""+str(fno_ohcl[eval("""'"""+str(row[0])+"""'""")]['h'] )+""","""+str(fno_ohcl[eval("""'"""+str(row[0])+"""'""")]['l'] )+""","""+str( fno_ohcl[eval("""'"""+str(row[0])+"""'""")]['c'] )+""",'"""+str( time.strftime('%Y%m%d-%H%M%S'))+"""')"""
print(insert2)
ghg.execute(insert2)
conn.commit()
r_reset=0
print(datetime.now())
isexported=1
print("---------------------------------------------------")
now1 = datetime.now()
seconds_since_midnight1 = (now1 - now1.replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds()
if((int(seconds_since_midnight1/60) % dtf)>0.0 and isexported==1):
isexported=0
print(datetime.now())

# Callback for successful connection.
def on_connect(ws):
tbl="""SELECT instrument_token, tradingsymbol FROM nfc"""
result=ghg.execute(tbl).fetchall()
i=1
text3=''
for row in result:
text3=text3+str(row[0])+','
print("text3: ",text3)
# Subscribe to a list of instrument_tokens (RELIANCE and ACC here).
ws.subscribe(eval("""["""+text3[:-1]+"""]"""))
# Set RELIANCE to tick in `full` mode.
ws.set_mode(ws.MODE_LTP,eval("""["""+text3[:-1]+"""]"""))

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

# Infinite loop on the main thread. Nothing after this will run.
# You have to use the pre-defined callbacks to manage subscriptions.
def on_disconnect():
print('on disconnect reconnecting')
kws.connect()
def on_error():
print('on error reconnecting',error)
kws.connect()
def on_colse():
print('on close reconnecting',"closed")
kws.connect()

instruments_update()
create_data_tables()
kws.connect()
if not kws.is_connected():
kws.connect()
kws.is_connected=is_connected
kws.on_disconnect=on_disconnect
kws.on_colse=on_colse
  • sujith
    Hi @gautam_s60,
    Reconnection is not yet available on pykiteconnect. We will release it soon.
    Please make a gist of code or use code tag available in format option so that it will be readable.

    I guess above code is not complete, Can you paste complete code with kws declaration also.
  • gautam_s60
    Charactar limitations can't post complete code!
  • sujith
    @gautam_s60,
    Make a gist and paste the link here.
  • gautam_s60
    gautam_s60 edited April 2017
    https://gist.github.com/anonymous/3afdde33a027c8377ef6004aeae44847

    consider this
    I am mechanical engineer not programmer :dizzy: didnt know gist..
  • sujith
    Hi @gautam_s60,
    In the above code, it seems like you are connecting again but not subscribing for tokens.

    The problem with this approach is onerror or onclose will not be triggered when there is a network connection drop or abrupt change in the network. So callback will not be called. So better approach would be to keep checking for lastTickArrivedTime every second and if ticker has not received any tick for like 5 seconds, you should reconnect.
    For reference, you can take look at javakiteconnect or kiteconnectjs repositories. We have provided this feature on these clients.
  • naz
    Hi @sujith ,
    will it be possible to include a standard python code snippet for the reconnection using monitoring of lastTickArrived. I am also facing frequent disconnections and have been using ws.reconnect (on callback of on_close). I guess this will help many other python users as well.
  • sujith
    Hi @naz,
    We will update pykiteconnect soon with reconnection feature.
  • sujith
    @naz,
    We will push update by end of this week or by next week.
  • naz
    @sujith : Thanks a tonne.
Sign In or Register to comment.