[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

async. How to wait for async function to complete

 i need to wait for the callback function (contractDetailsEnd) to finish before i can continue with the logic ( in subscribe) further. For that i check the flag (ContractsUpdatedEnd) in the "while" loop.

Here is the simplified code:

import asyncio
import ibapi
from tws_async import TWSClient

class TWS(TWSClient):

    def __init__( self ):
        self.Contracts = {}
        self.ContractsUpdatedEnd = False

    def sleep(self, secs):
        loop = asyncio.get_event_loop()

    def subscribe( self ):
        for forex in ['EURUSD', 'USDJPY', 'GBPUSD']:

            self.reqContractDetails(reqId ,c)
            while not self.ContractsUpdatedEnd:

            self.reqMktData(reqId, c, genericTickList = '', snapshot = False,
                        regulatorySnapshot = False, mktDataOptions = [])

    def contractDetails(self, reqId, contractDetails):
        self.Contracts[reqId]= contractDetails.summary
        print("Contract is {}".format(contractDetails.summary))

    def contractDetailsEnd(self, reqId):
        print("End for contract details")
        self.ContractsUpdatedEnd = True

if __name__ == '__main__':
    tws = TWS()
    tws.connect(host = '', port = 7497, clientId = 1)
    loop = asyncio.get_event_loop()

Unfortunately, this throws the :
File "/usr/lib64/python3.5/asyncio/base_events.py", line 408, in run_forever
    raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running

will greatly appreciate your advise.