Closed mtech2008 closed 1 year ago
Hey @mtech2008,
The only simple option I can see is to run kws.connect
and chart.show
in separate threads/processes and make sure your code is thread-safe.
Ideally you would want an implementation of the kws
object which uses asyncio, so both show
and connect
could be run in parallel.
Louis
I am receiving in the following error run_forever raise RuntimeError('This event loop is already running') RuntimeError: This event loop is already running
async def main():
kite = Zerodha()
kite.set_session_token()
print(kite.profile())
kws = kite.ticker()
kws.on_connect = on_connect
kws.on_ticks = on_ticks
chart = Chart()
chart.events.new_bar += on_new_bar
chart.topbar.switcher('timeframe', ('1min', '5min'), func=on_timeframe_selection)
df = pd.read_csv('ohlc.csv')
chart.set(df)
await asyncio.gather(chart.show_async(block=True), kws.connect_ws())
if __name__ == '__main__':
asyncio.run(main())
Is is with async implementation of Ticker by https://github.com/ranjanrak/async-ticker
There's a slight issue with their implementation; you'll need to create a child class of MainTicker
, and overwrite the connect_ws
method:
async def connect_ws(self):
"""
Establish ws connection
"""
self.factory = TickerClientFactory(self.ws_url)
self.factory.protocol = TickerClientProtocol
self.ws = self.factory.ws
# Register private callback
self.factory.on_connect = self._on_connect
self.factory.on_message = self._on_message
# Run an infinite loop using asyncio
loop = asyncio.get_event_loop()
await loop.create_connection(self.factory, "ws.kite.trade", 443, ssl=True)
Should work.
Louis
Thank you so very much for this help. It worked perfectly well. Thank you.
Question
I am using Zerodha kiteconnect to receive the live ticks from websocket. I am receiving the ticks but chart events are not firing. I have gone through your asyncio events and tried it but either I get events fired or ticks. I am really stuck and tried every way but did not find the solution. I need your suggetion and help. It has connect() method which runs infinite loop on main thread. Nothing after it will run. so we have to use the pre-defined callbacks to manage the subscription. Ref: https://github.com/zerodha/pykiteconnect/tree/master#websocket-usage Here is a sample code without asyncio:
Code example