def __init__(self, *args, **kwargs): Object.__init__(self, *args, **kwargs) assert self.controller assert self.retryDelay > 0 self.ib = IB() self.ib.client.apiError = self.onApiError self.ib.setCallback('error', self.onError) self._watcher = asyncio.ensure_future(self.watchAsync()) self._logger = logging.getLogger('ib_insync.Watchdog')
def start(self): self._logger.info('Starting') self.controller.start() IB.sleep(self.appStartupTime) try: self.ib.connect(self.host, self.port, self.clientId, self.connectTimeout) self.ib.setTimeout(self.appTimeout) except: # a connection failure will be handled by the apiError callback pass
def start(self): self.startingEvent.emit(self) self._logger.info('Starting') self.controller.start() IB.sleep(self.appStartupTime) try: self.ib.connect(self.host, self.port, self.clientId, self.connectTimeout) self.ib.setTimeout(self.appTimeout) self.startedEvent.emit(self) except: self.flush()
def start(self): self._logger.info('Starting') self._isRunning = True self.startingEvent.emit(self) self.controller.start() IB.sleep(self.appStartupTime) try: self._connect() self.ib.setTimeout(self.appTimeout) self.startedEvent.emit(self) except: self.controller.terminate() self._scheduleRestart()
if not bars: self.hardTimeoutEvent.emit(self) raise Warning('Hard timeout') self.ib.setTimeout(self.appTimeout) except ConnectionRefusedError: pass except Warning as w: self._logger.warning(w) except Exception as e: self._logger.exception(e) finally: self.ib.timeoutEvent -= onTimeout self.ib.errorEvent -= onError self.ib.disconnectedEvent -= onDisconnected await self.controller.terminateAsync() self.stoppedEvent.emit(self) if self._runner: await asyncio.sleep(self.retryDelay) if __name__ == '__main__': asyncio.get_event_loop().set_debug(True) util.logToConsole(logging.DEBUG) ibc = IBC(976, gateway=True, tradingMode='paper') # userid='edemo', password='******') ib = IB() app = Watchdog(ibc, ib, port=4002, appStartupTime=15, appTimeout=10) app.start() IB.run()
class Watchdog(Object): """ Start, connect and watch over the TWS or gateway app to keep it running in the face of crashes, freezes and network outages. The idea is to wait until there is no traffic coming from the app for a certain amount of time (the ``appTimeout`` parameter). This triggers a historical request to be placed just to see if the app is still alive and well. If yes, then continue, if no then restart the whole app and reconnect. Restarting will also occur directly on error 1100. Arguments: * ``controller``: IBC or IBController instance; * ``host``, ``port``, ``clientId`` and ``connectTimeout``: Used for connecting to the app; * ``appStartupTime``: Time (in seconds) that the app is given to start up. Make sure that it is given ample time; * ``appTimeout``: Timeout (in seconds) for network traffic idle time; * ``retryDelay``: Time (in seconds) to restart app after a previous failure. Note: ``util.patchAsyncio()`` must have been called before. Example usage: .. code-block:: python util.patchAsyncio() ibc = IBC(969, gateway=True, tradingMode='paper') app = Watchdog(ibc, port=4002) app.start() IB.run() """ defaults = dict(controller=None, host='127.0.0.1', port='7497', clientId=1, connectTimeout=2, ib=None, appStartupTime=30, appTimeout=20, retryDelay=1) __slots__ = list(defaults.keys()) + ['_watcher', '_logger'] def __init__(self, *args, **kwargs): Object.__init__(self, *args, **kwargs) assert self.controller assert 0 < self.appTimeout < 60 assert self.retryDelay > 0 if self.ib is None: self.ib = IB() self.ib.client.apiError = self.onApiError self.ib.setCallback('error', self.onError) self._watcher = asyncio.ensure_future(self.watchAsync()) self._logger = logging.getLogger('ib_insync.Watchdog') def start(self): self._logger.info('Starting') self.controller.start() IB.sleep(self.appStartupTime) try: self.ib.connect(self.host, self.port, self.clientId, self.connectTimeout) self.ib.setTimeout(self.appTimeout) except: # a connection failure will be handled by the apiError callback pass def stop(self): self._logger.info('Stopping') self.ib.disconnect() self.controller.terminate() def scheduleRestart(self): self._logger.info(f'Schedule restart in {self.retryDelay}s') loop = asyncio.get_event_loop() loop.call_later(self.retryDelay, self.start) def onApiError(self, msg): self.stop() self.scheduleRestart() def onError(self, reqId, errorCode, errorString, contract): if errorCode == 1100: self._logger.info(f'Error 1100: {errorString}') self.stop() self.scheduleRestart() async def watchAsync(self): while True: await self.ib.wrapper.timeoutEvent.wait() # soft timeout, probe the app with a historical request contract = Forex('EURUSD') probe = self.ib.reqHistoricalDataAsync(contract, '', '30 S', '5 secs', 'MIDPOINT', False) try: bars = await asyncio.wait_for(probe, 4) if not bars: raise Exception() self.ib.setTimeout(self.appTimeout) except: # hard timeout, flush everything and start anew self._logger.error('Hard timeout') self.stop() self.scheduleRestart()
self.stop() self.scheduleRestart() async def watchAsync(self): while True: await self.ib.wrapper.timeoutEvent.wait() # soft timeout, probe the app with a historical request contract = Forex('EURUSD') probe = self.ib.reqHistoricalDataAsync(contract, '', '30 S', '5 secs', 'MIDPOINT', False) try: bars = await asyncio.wait_for(probe, 4) if not bars: raise Exception() self.ib.setTimeout(self.appTimeout) except: # hard timeout, flush everything and start anew self._logger.error('Hard timeout') self.stop() self.scheduleRestart() if __name__ == '__main__': util.logToConsole() util.patchAsyncio() ibc = IBC(969, gateway=True, tradingMode='live') # userid='edemo', password='******') app = Watchdog(ibc, port=4002) app.start() IB.run()
@author: ilia """ from ib_insync.ib import IB from optopus.ib_adapter import IBBrokerAdapter from optopus.optopus import Optopus from optopus.utils import to_df, notify from optopus.taco import Taco #import logging host = '127.0.0.1' #port = 4002 # gateway port = 7497 # TWS PAPER TRADING #port = 7496 # TWS LIVE TRADING client = 11 ib = IB() opt = Optopus(IBBrokerAdapter(ib, host, port, client)) #notify('strategy_opened', 'FXI', 'cara', 'cola') #algo = Taco(opt) algo = Taco(opt) opt.register_algorithm(algo.execute) #logging.getLogger('ib_insync.wrapper').disabled = True opt.start() #breadth_indicator='TRIN-NYSE' #time = opt.history(breadth_indicator, "time") #value = opt.history(breadth_indicator, "value")