コード例 #1
0
                                 initial_stop=stoploss,
                                 trail_stop_at=0,
                                 trail_stop_by=0,
                                 expiry=5
                                 )

                # record action
                self.record(take_action=1)

    # ---------------------------------------
    def on_bar(self, instrument):
        # nothing exiting here...
        bar = instrument.get_bars(lookback=1, as_dict=True)
        print("BAR:", bar)



# ===========================================
if __name__ == "__main__":
    # get most active ES contract to trade
    ACTIVE_MONTH = futures.get_active_contract("ES")
    print("Active month for ES is:", ACTIVE_MONTH)

    strategy = TestStrategy(
        instruments=[("ES", "FUT", "GLOBEX", "USD", ACTIVE_MONTH, 0.0, "")],
        resolution="1T",
        tick_window=10,
        bar_window=10
    )
    strategy.run()
コード例 #2
0
ファイル: tools.py プロジェクト: Greenwicher/qtpylib
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
コード例 #3
0
ファイル: broker.py プロジェクト: ErnstTmp/qtpylib
    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)
コード例 #4
0
ファイル: tools.py プロジェクト: tarekpython/qtpylib
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
コード例 #5
0
ファイル: strategy.py プロジェクト: Greenwicher/qtpylib
                        trail_stop_at = 0,
                        trail_stop_by = 0,
                        expiry=5
                    )

                # record action
                self.record(take_action=1)


    # ---------------------------------------
    def on_bar(self, instrument):
        # nothing exiting here...
        bar = instrument.get_bars(lookback=1, as_dict=True)
        print("BAR:", bar)



# ===========================================
if __name__ == "__main__":
    # get most active ES contract to trade
    ACTIVE_MONTH = futures.get_active_contract("ES")
    print("Active month for ES is:", ACTIVE_MONTH)

    strategy = TestStrategy(
        instruments = [ ("ES", "FUT", "GLOBEX", "USD", ACTIVE_MONTH, 0.0, "") ],
        resolution  = "1T",
        tick_window = 10,
        bar_window  = 10
    )
    strategy.run()