Reputation: 21
When I try using Flask / Quart, I keep getting the error, 'This event loop is already running', and I can't seem to find a workaround for this issue.
I have successfully opened a new order in IBKR through their API, after finally managing to do so with this Python script:
# Connect to IB Gateway/TWS
ib = IB()
ib.connect('127.0.0.1', 7496, clientId=1)
# Define the contract (stock)
contract = Stock('AMD', 'SMART', 'USD')
# Define the order (limit order to buy 1 share of AMD at $90)
order = LimitOrder('BUY', 1, 161.31)
try:
# Place the order and wait for it to be filled
trade = ib.placeOrder(contract, order)
ib.sleep(2) # Sleep for a few seconds to give time for order status update
ib.reqExecutions() # Request execution details
print("Trade placed successfully.")
print(trade)
except Exception as e:
print("Error placing the trade:", e)
# Disconnect from IB Gateway/TWS
ib.disconnect()
I tried to implement this script in Flask / Quart so I will be able to open new orders through POST Requests. that did NOT work since trying to use asynchronous features is not possible inside Flask or Quart.
I also tried finding different code languages but the only working one for this library is Python. I have reached a dead end here so I decided to ask around here.
My end goal is pretty simple, This is it:
Handling a POST request, which will open a new order on IBKR according to the data inside of the POST Request.
I hope I am not missing any crucial details here.
Upvotes: 1
Views: 345
Reputation: 56
ib_insync, now ib_async works with python asyncio, any "blocking" code will not work well with it.
On Flask documentation you will find an explanation on how to make it work with Flask.
Regarding Quart, it is an async framework and it will work well with ib_async.
As per Quart github repo
An async Python micro framework for building web applications.
ib_async documentation has examples to integrate it with other frameworks loop. Like pyqt5, Tkinter and pygame, you should be able to apply the same principles to a Quart app.
Upvotes: 1