ib_insync - How to handle errors

532 Views Asked by At

I moved from IB official API to ib_insync, and with the second one I don't see a way to handle errors like IB API. Is there any way in ib_insync to handle also the errors like this?

def error(self, reqId, errorCode, errorString):

    if(errorCode == 502) or (errorCode == 504): 
        print("ERROR: Fallo de conexión - Comprobar sockets TWS")
        exit()
    elif(errorCode not in self.goodErrors): 
        print("Error {} {} {}".format(reqId,errorCode,errorString))
        #self.disconnect()

# Errores no importantes:
# - 2104: Market Data Farm OK
# - 2106: Historical Data Farm OK
# - 2158: Sec-Def Data Farm OK
goodErrors = (2104, 2106, 2158)`

This works for IBAPI but not in ib_insync

1

There are 1 best solutions below

6
TradingDerivatives.eu On

Two steps. First, an error event handler function must be written. Second, it must be registered. Here are some snippets of my own code that may get you started. I wrote a Logger class for obvious reasons.

    def OnErrorEvent(self, aReqId:int, aErrorCode:int, aErrorString:str, aContract):
    logger:Logger.CLogger = Logger.CLogger(
        sys._getframe().f_code.co_name,
        "TWS API ERROR. aReqId", aReqId,
        "aErrorCode", aErrorCode,
        "aErrorString", aErrorString,
        "aContract", aContract)

Create your ib_insync object:

        self.iIbInsync = ib_insync.IB()

        # Callback registration
        self.iIbInsync.errorEvent          += self.OnErrorEvent

Hope this helps.