erdewit / ib_insync

Python sync/async framework for Interactive Brokers API
BSD 2-Clause "Simplified" License
2.8k stars 743 forks source link

Error using ib_insync with Streamlit.io - 'There is no current event loop' #563

Closed d416 closed 1 year ago

d416 commented 1 year ago

There is a whole thread of people trying to get ib_insync to work within Streamlit without success. Error is 'There is no current event loop.' https://github.com/streamlit/streamlit/issues/744

Maybe we can get a code recipe for doing this in the ib_insync docs? (hopefully it's this simple)

Anton-Filimoncev commented 1 year ago

Add this code before import ib_insync:

import asyncio

def get_or_create_eventloop():
    try:
        return asyncio.get_event_loop()
    except RuntimeError as ex:
        if "There is no current event loop in thread" in str(ex):
            loop = asyncio.new_event_loop()
            asyncio.set_event_loop(loop)
            return asyncio.get_event_loop()

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
erdewit commented 1 year ago

This is not specific to ib_insync but to any asyncio application.