I am trying to write basic Websocket code, using code from official site, but facing "ReactorNotRestartable" error. Not sure what went wrong. Can someone help me?
def on_ticks(ws, ticks): # Callback to receive ticks. logging.debug("Ticks: {}".format(ticks))
def on_connect(ws, response): # Callback on successful connect. # Subscribe to a list of instrument_tokens (RELIANCE and ACC here). ws.subscribe([738561, 5633])
# Set RELIANCE to tick in `full` mode. ws.set_mode(ws.MODE_FULL, [738561])
def on_close(ws, code, reason): # On connection close stop the event loop. # Reconnection will not happen after executing `ws.stop()` ws.stop()
File "C:\Users\anilk\anaconda3\lib\site-packages\kiteconnect\ticker.py", line 532, in connect reactor.run(**opts)
File "C:\Users\anilk\anaconda3\lib\site-packages\twisted\internet\base.py", line 1422, in run self.startRunning(installSignalHandlers=installSignalHandlers)
File "C:\Users\anilk\anaconda3\lib\site-packages\twisted\internet\base.py", line 1404, in startRunning ReactorBase.startRunning(cast(ReactorBase, self))
File "C:\Users\anilk\anaconda3\lib\site-packages\twisted\internet\base.py", line 843, in startRunning raise error.ReactorNotRestartable()
@sujith and all, almost all websocket syntax/examples are talking till ticker.connect() but i want to close and reinitiate based on my strategy, without hurting the environment. There must be some way as people already using it but not able to find, Can you help me how to call on_close manually.
how to close connection from my end? (call on_close, if i want to close connection after my strategy completed).
Yes, you need to gracefully exit WebSocket using ws.close() based on your condition. Something like:
def close_websocket(self): self.ws.stop() # Call close_websocket, based on condition when you want to close/stop websocket eg: if (current_timestamp > your time based condition or net P&L > some value): self.close_websocket()
(i have to restart for each run).
Connection closed: None - None
Process finished with exit code 0.
Am i doing anything wrong or Websocket works with command line and not with any IDES? this is the code i'm using.
def on_ticks(ws, ticks):
print("on_ticks")
print("Ticks: {}".format(ticks))
ws.close()
def on_connect(ws, response):
ws.subscribe([738561, 5633])
ws.set_mode(ws.MODE_FULL, [738561])
def on_close(ws, code, reason):
ws.close()
ticker.on_ticks = on_ticks
ticker.on_connect = on_connect
ticker.on_close = on_close
ticker.connect()
You can check the Websocket example code here.