WebSocket stopping after sometime.

sachinkumarg
Hi,

I am using WebSocket and it is working continuously but at times I am getting error and i=I need to end the session and start a new session. can someone help on this. This is happening when I am using API key and Secret.

Code:

kite.set_access_token() # loads the session from config folder
kws = kite.ticker()

file = (f'{cp.basepath}logs/ws_log_{today1}.txt')
if(os.path.exists(file) and os.path.isfile(file)):
os.remove(file)
LOG_FILENAME = (file)

logging.basicConfig(
filename=LOG_FILENAME,
level=logging.INFO,
format="%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)

print(datetime.now(), " WS Started")

def on_ticks(ws, ticks):
logging.debug("Ticks: {}".format(ticks))
# insert_tick(ticks)
def on_connect(ws, response):
logging.info("Successfully connected. Response: {}".format(response))
subscribed_instruments = cp.r4.get(cp.keyname)
subscribed_instruments = subscribed_instruments.split(",")
subscribed_instruments = [eval(i) for i in subscribed_instruments]
ws.subscribe(subscribed_instruments)

def on_close(ws, code, reason):
logging.info("Connection closed: {code} - {reason}".format(code=code, reason=reason))
# ws.stop()

# Callback when connection closed with error.
def on_error(ws, code, reason):
logging.info("Connection error: {code} - {reason}".format(code=code, reason=reason))


# Callback when reconnect is on progress
def on_reconnect(ws, attempts_count):
logging.info("Reconnecting: {}".format(attempts_count))


# Callback when all reconnect failed (exhausted max retries)
def on_noreconnect(ws):
logging.info("Reconnect failed.")
try:
kws.on_ticks = on_ticks
kws.on_close = on_close
kws.on_error = on_error
kws.on_connect = on_connect
kws.on_reconnect = on_reconnect
kws.on_noreconnect = on_noreconnect

kws.connect(threaded=True)

except Exception as Argument:
logging.exception("Got exception on WebSocket handler:")
kws.on_ticks = on_ticks
kws.on_close = on_close
kws.on_error = on_error
kws.on_connect = on_connect
kws.on_reconnect = on_reconnect
kws.on_noreconnect = on_noreconnect

kws.connect(threaded=True)

while True:
try:
def on_ticks(ws, ticks):
update_redis(ticks)

def update_redis(ticks):
# print(ticks)
data = {}
for tick in ticks:
data[tick["instrument_token"]] = str(tick["last_price"])
print(datetime.now(), data)
r.mset(data)
# print(tick["instrument_token"], tick["last_price"])
# now = datetime.now()
if kws.is_connected(): # and now > next_update
subscribed_instruments = cp.r4.get(cp.keyname)
subscribed_instruments = subscribed_instruments.split(",")
subscribed_instruments = [eval(i) for i in subscribed_instruments]
kws.subscribe(subscribed_instruments)

# updated_sec = now
# next_update = now + timedelta(seconds=1)

except Exception as Argument:
f = open(f'{cp.basepath}logs/ws_log_{today1}.txt', "a")
f.write("\n" + str(datetime.now()) + "\n")
f.close()
logging.exception('Got exception on WebSocket handler')
continue

kws.on_ticks=on_ticks

if datetime.now() >= today:
print('I''m tired. Day is also over, lemme recharge for next run')

break
time.sleep(.5)


================ERROR================

Unhandled Error
Traceback (most recent call last):
File "/usr/lib/python3.11/threading.py", line 1045, in _bootstrap_inner
self.run()
File "/usr/lib/python3.11/threading.py", line 982, in run
self._target(*self._args, **self._kwargs)
File "/home/sachin/Application/automated_trader/venv/lib/python3.11/site-packages/twisted/internet/base.py", line 693, in run
self.mainLoop()
File "/home/sachin/Application/automated_trader/venv/lib/python3.11/site-packages/twisted/internet/base.py", line 703, in mainLoop
self.runUntilCurrent()
--- ---
File "/home/sachin/Application/automated_trader/venv/lib/python3.11/site-packages/twisted/internet/base.py", line 1088, in runUntilCurrent
call.func(*call.args, **call.kw)
File "/home/sachin/Application/automated_trader/venv/lib/python3.11/site-packages/kiteconnect/ticker.py", line 136, in _loop_pong_check
self.dropConnection(abort=True)
File "/home/sachin/Application/automated_trader/venv/lib/python3.11/site-packages/autobahn/websocket/protocol.py", line 875, in dropConnection
self._closeConnection(abort)
File "/home/sachin/Application/automated_trader/venv/lib/python3.11/site-packages/autobahn/twisted/websocket.py", line 295, in _closeConnection
self.transport.abortConnection()
File "/home/sachin/Application/automated_trader/venv/lib/python3.11/site-packages/twisted/protocols/tls.py", line 430, in abortConnection
self.transport.abortConnection()
File "/home/sachin/Application/automated_trader/venv/lib/python3.11/site-packages/twisted/internet/tcp.py", line 199, in abortConnection
self.stopWriting()
File "/home/sachin/Application/automated_trader/venv/lib/python3.11/site-packages/twisted/internet/abstract.py", line 434, in stopWriting
self.reactor.removeWriter(self)
File "/home/sachin/Application/automated_trader/venv/lib/python3.11/site-packages/twisted/internet/epollreactor.py", line 189, in removeWriter
self._remove(
File "/home/sachin/Application/automated_trader/venv/lib/python3.11/site-packages/twisted/internet/epollreactor.py", line 168, in _remove
self._poller.unregister(fd)
builtins.FileNotFoundError: [Errno 2] No such file or directory
  • rakeshr
    self._poller.unregister(fd)
    builtins.FileNotFoundError: [Errno 2] No such file or directory
    This error comes when you are not handling twisted threads properly. Here is a thread, explaining the same.
Sign In or Register to comment.