I'm very new to python and I'm trying to implement an API for requesting some data from Interactive Brokers Trader Workstation. I'm using Flask and ib_insync.
Here is my code:
import configparser
import json
import logging.config
from flask import Flask
from ib_insync import IB
flask = Flask(__name__)
ib = IB()
config = configparser.ConfigParser()
config.read('settings.ini')
logging.config.fileConfig('logging.conf')
logger = logging.getLogger('ib-custom')
@flask.route('/health', methods=['GET'])
def health():
return 'OK'
@flask.route('/summary', methods=['GET'])
def account_summary():
logger.debug('account_summary called')
summary = ib.accountSummary()
return json.dumps([ob._asdict() for ob in summary])
if __name__ == '__main__':
ib.connect('127.0.0.1', 7497, clientId=1)
logger.info('Application started')
flask.run(debug=True, use_reloader=False)
It raises the error when I'm trying to execute localhost:5000/summary
. Here is the stacktrace:
Traceback (most recent call last):
File "/Users/irusanov/Projects/PycharmProjects/ib-custom/venv/lib/python3.8/site-packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/irusanov/Projects/PycharmProjects/ib-custom/venv/lib/python3.8/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/Users/irusanov/Projects/PycharmProjects/ib-custom/venv/lib/python3.8/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/irusanov/Projects/PycharmProjects/ib-custom/venv/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/Users/irusanov/Projects/PycharmProjects/ib-custom/venv/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/Users/irusanov/Projects/PycharmProjects/ib-custom/venv/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/irusanov/Projects/PycharmProjects/ib-custom/venv/lib/python3.8/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/irusanov/Projects/PycharmProjects/ib-custom/venv/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/Users/irusanov/Projects/PycharmProjects/ib-custom/venv/lib/python3.8/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/irusanov/Projects/PycharmProjects/ib-custom/venv/lib/python3.8/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/irusanov/Projects/PycharmProjects/ib-custom/main.py", line 27, in account_summary
summary = ib.accountSummary()
File "/Users/irusanov/Projects/PycharmProjects/ib-custom/venv/lib/python3.8/site-packages/ib_insync/ib.py", line 405, in accountSummary
return self._run(self.accountSummaryAsync(account))
File "/Users/irusanov/Projects/PycharmProjects/ib-custom/venv/lib/python3.8/site-packages/ib_insync/ib.py", line 310, in _run
return util.run(*awaitables, timeout=self.RequestTimeout)
File "/Users/irusanov/Projects/PycharmProjects/ib-custom/venv/lib/python3.8/site-packages/ib_insync/util.py", line 291, in run
loop = asyncio.get_event_loop()
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/asyncio/events.py", line 639, in get_event_loop
raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'Thread-1'.
Why this error appears? How to fix it?
It appears Flask uses its own internal blocking/callback/threaded model and isn't compatible with Asyncio which this project is built on. Source: https://github.com/erdewit/ib_insync/issues/266
Required behaviour could be implemented using another framework instead of Flask. E.g. Quart.
In the case of using Quart, this code could be rewritten:
import asyncio
import configparser
import json
import logging.config
import nest_asyncio
from quart import Quart
from ib_insync import IB, util
nest_asyncio.apply()
qrt = Quart(__name__)
ib = IB()
config = configparser.ConfigParser()
config.read('settings.ini')
logging.config.fileConfig('logging.conf')
logger = logging.getLogger('ib-custom')
@qrt.route('/health', methods=['GET'])
def health():
return 'OK'
@qrt.route('/summary')
async def summary():
with await IB().connectAsync() as ibi:
acct = ibi.managedAccounts()[0]
summary = ibi.accountSummary(acct)
await ibi.accountSummaryEvent
resp = json.dumps(util.tree(summary))
return resp
@qrt.route('/pnl')
async def pnl():
with await IB().connectAsync() as ibi:
acct = ibi.managedAccounts()[0]
pnl = ibi.reqPnL(acct)
await ibi.pnlEvent
resp = json.dumps(util.tree(pnl))
return resp
if __name__ == '__main__':
# ib.connect('127.0.0.1', 7497, clientId=1)
logger.info('Application started')
qrt.run(debug=True)