async. How to wait for async function to complete

Andrew Z formisc at gmail.com
Fri Sep 8 00:04:58 EDT 2017


Hello,
 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 ):
        TWSClient.__init__(self)
        self.Contracts = {}
        self.ContractsUpdatedEnd = False

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

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

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

            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 = '127.0.0.1', port = 7497, clientId = 1)
    tws.subscribe()
    loop = asyncio.get_event_loop()
    loop.run_forever()



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.



More information about the Python-list mailing list