def __init__(self, instruments, ibclient=998, ibport=4001, ibserver="localhost"): # detect running strategy self.strategy = str(self.__class__).split('.')[-1].split("'")[0] # initilize class logger self.log_broker = logging.getLogger(__name__) # default params (overrided in algo) self.timezone = "UTC" self.last_price = {} self.tick_window = 1000 self.bar_window = 100 # ----------------------------------- # connect to IB self.ibclient = int(ibclient) self.ibport = int(ibport) self.ibserver = str(ibserver) self.ibConn = ezibpy.ezIBpy() self.ibConn.ibCallback = self.ibCallback self.ibConnect() # ----------------------------------- # create contracts instrument_tuples_dict = {} for instrument in instruments: try: if isinstance(instrument, ezibpy.utils.Contract): instrument = self.ibConn.contract_to_tuple(instrument) else: instrument = tools.create_ib_tuple(instrument) contractString = self.ibConn.contractString(instrument) instrument_tuples_dict[contractString] = instrument self.ibConn.createContract(instrument) except Exception as e: pass self.instruments = instrument_tuples_dict self.symbols = list(self.instruments.keys()) self.instrument_combos = {} # ----------------------------------- # track orders & trades self.active_trades = {} self.trades = [] # shortcut self.account = self.ibConn.account # use: self.orders.pending... self.orders = tools.make_object( by_tickerid=self.ibConn.orders, by_symbol=self.ibConn.symbol_orders, pending_ttls={}, pending={}, filled={}, active={}, history={}, nextId=1, recent={} ) # ----------------------------------- self.dbcurr = None self.dbconn = None # ----------------------------------- # assign default vals if not propogated from algo if not hasattr(self, 'backtest'): self.backtest = False if not hasattr(self, 'sms_numbers'): self.sms_numbers = [] if not hasattr(self, 'trade_log_dir'): self.trade_log_dir = None if not hasattr(self, 'blotter_name'): self.blotter_name = None # ----------------------------------- # load blotter settings self.blotter_args = load_blotter_args( self.blotter_name, logger=self.log_broker) self.blotter = Blotter(**self.blotter_args) # connect to mysql using blotter's settings if not self.blotter_args['dbskip']: self.dbconn = pymysql.connect( host=str(self.blotter_args['dbhost']), port=int(self.blotter_args['dbport']), user=str(self.blotter_args['dbuser']), passwd=str(self.blotter_args['dbpass']), db=str(self.blotter_args['dbname']), autocommit=True ) self.dbcurr = self.dbconn.cursor() # ----------------------------------- # do stuff on exit atexit.register(self._on_exit)
def __init__(self, instruments, ibclient=999, ibport=4001, ibserver="localhost", **kwargs): # ----------------------------------- # detect running strategy self.strategy = str(self.__class__).split('.')[-1].split("'")[0] # ----------------------------------- # connect to IB self.ibclient = int(ibclient) self.ibport = int(ibport) self.ibserver = str(ibserver) self.ibConn = ezibpy.ezIBpy() self.ibConn.ibCallback = self.ibCallback self.ibConnect() # ----------------------------------- # create contracts instrument_tuples_dict = {} for instrument in instruments: try: # signgle string if isinstance(instrument, str): instrument = instrument.upper() if "FUT." not in instrument: # symbol stock instrument = (instrument, "STK", "SMART", "USD", "", 0.0, "") else: # future contract try: symdata = instrument.split(".") # is this a CME future? if symdata[ 1] not in futures.futures_contracts.keys(): raise ValueError( "Un-supported symbol. Please use full contract tuple." ) # auto get contract details spec = futures.get_ib_futures(symdata[1]) if not isinstance(spec, dict): raise ValueError("Un-parsable contract tuple") # expiry specified? if len(symdata) == 3 and symdata[2] != '': expiry = symdata[2] else: # default to most active expiry = futures.get_active_contract( symdata[1]) instrument = (spec['symbol'].upper(), "FUT", spec['exchange'].upper(), spec['currency'].upper(), int(expiry), 0.0, "") except: raise ValueError("Un-parsable contract tuple") # tuples without strike/right elif len(instrument) <= 7: instrument_list = list(instrument) if len(instrument_list) < 3: instrument_list.append("SMART") if len(instrument_list) < 4: instrument_list.append("USD") if len(instrument_list) < 5: instrument_list.append("") if len(instrument_list) < 6: instrument_list.append(0.0) if len(instrument_list) < 7: instrument_list.append("") try: instrument_list[4] = int(instrument_list[4]) except: pass instrument_list[5] = 0. if isinstance(instrument_list[5], str) \ else float(instrument_list[5]) instrument = tuple(instrument_list) contractString = self.ibConn.contractString(instrument) instrument_tuples_dict[contractString] = instrument self.ibConn.createContract(instrument) except: pass self.instruments = instrument_tuples_dict self.symbols = list(self.instruments.keys()) # ----------------------------------- # track orders & trades self.active_trades = {} self.trades = [] # shortcut self.account = self.ibConn.account # use: self.orders.pending... self.orders = tools.make_object(by_tickerid=self.ibConn.orders, by_symbol=self.ibConn.symbol_orders, pending_ttls={}, pending={}, filled={}, active={}, history={}, nextId=1, recent={}) # ----------------------------------- self.dbcurr = None self.dbconn = None # ----------------------------------- # assign default vals if not propogated from algo if not hasattr(self, 'backtest'): self.backtest = False if not hasattr(self, 'sms_numbers'): self.sms_numbers = [] if not hasattr(self, 'trade_log_dir'): self.trade_log_dir = None if not hasattr(self, 'blotter_name'): self.blotter_name = None # ----------------------------------- # load blotter settings self.blotter_args = {} self.load_blotter_args(self.blotter_name) # ----------------------------------- # do stuff on exit atexit.register(self._on_exit)