Ejemplo n.º 1
0
    def get_margin_requirement(self):
        """ Get margin requirements for intrument (futures only)

        :Retruns:
            margin : dict
                margin requirements for instrument (all values are ``None`` for non-futures instruments)
        """
        contract = self.get_contract()

        if contract.m_secType == "FUT":
            return futures.get_ib_futures(contract.m_symbol,
                                          contract.m_exchange)

        # else...
        return {
            "exchange": None,
            "symbol": None,
            "description": None,
            "class": None,
            "intraday_initial": None,
            "intraday_maintenance": None,
            "overnight_initial": None,
            "overnight_maintenance": None,
            "currency": None,
            "has_options": None
        }
Ejemplo n.º 2
0
    def get_margin_requirement(self):
        """ Get margin requirements for intrument (futures only)

        :Retruns:
            margin : dict
                margin requirements for instrument (all values are ``None`` for non-futures instruments)
        """
        contract = self.get_contract()

        if contract.m_secType == "FUT":
            return futures.get_ib_futures(contract.m_symbol, contract.m_exchange)

        # else...
        return {
            "exchange": None,
            "symbol": None,
            "description": None,
            "class": None,
            "intraday_initial": None,
            "intraday_maintenance": None,
            "overnight_initial": None,
            "overnight_maintenance": None,
            "currency": None,
            "has_options": None
        }
Ejemplo n.º 3
0
def create_ib_tuple(instrument):
    """ create ib contract tuple """
    from qtpylib import futures

    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)

    return instrument
Ejemplo n.º 4
0
def create_ib_tuple(instrument):
    """ create ib contract tuple """
    from qtpylib import futures

    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)

    return instrument
Ejemplo n.º 5
0
    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)