Пример #1
0
    def processPositionMultiMsg(self, fields):
        sMsgId = next(fields)

        version = decode(int, fields)
        reqId = decode(int, fields)
        account = decode(str, fields)

        # decode contract fields
        contract = Contract()
        contract.conId = decode(int, fields)
        contract.symbol = decode(str, fields)
        contract.secType = decode(str, fields)
        contract.lastTradeDateOrContractMonth = decode(str, fields)
        contract.strike = decode(float, fields)
        contract.right = decode(str, fields)
        contract.multiplier = decode(str, fields)
        contract.exchange = decode(str, fields)
        contract.currency = decode(str, fields)
        contract.localSymbol = decode(str, fields)
        contract.tradingClass = decode(str, fields)
        position = decode(float, fields)
        avgCost = decode(float, fields)
        modelCode = decode(str, fields)
 
        self.wrapper.positionMulti(reqId, account, modelCode, contract, position, avgCost)
Пример #2
0
def make_contract(symbol='',
                  conID=0,
                  secType='STK',
                  currency='USD',
                  exchange='',
                  primaryExchange='',
                  multiplier=100,
                  tradingClass='',
                  localSymbol='',
                  right='',
                  lastTradeDateOrContractMonth='',
                  strike=0):
    contract = Contract()
    contract.symbol = symbol
    contract.conId = conID
    contract.secType = secType
    contract.currency = currency
    contract.exchange = exchange
    contract.primaryExchange = primaryExchange
    contract.multiplier = multiplier
    contract.tradingClass = tradingClass
    if tradingClass == '':
        contract.tradingClass = symbol
    contract.localSymbol = localSymbol
    contract.right = right
    contract.lastTradeDateOrContractMonth = lastTradeDateOrContractMonth
    contract.strike = strike
    return contract
Пример #3
0
    def send_order(self, req: OrderRequest):
        """
        Send a new order.
        """
        if not self.status:
            return ""

        if req.exchange not in EXCHANGE_VT2IB:
            self.gateway.write_log(f"不支持的交易所:{req.exchange}")
            return ""

        if req.type not in ORDERTYPE_VT2IB:
            self.gateway.write_log(f"不支持的价格类型:{req.type}")
            return ""

        self.orderid += 1

        ib_contract = Contract()
        ib_contract.conId = str(req.symbol)
        ib_contract.exchange = EXCHANGE_VT2IB[req.exchange]

        ib_order = Order()
        ib_order.orderId = self.orderid
        ib_order.clientId = self.clientid
        ib_order.action = DIRECTION_VT2IB[req.direction]
        ib_order.orderType = ORDERTYPE_VT2IB[req.type]
        ib_order.lmtPrice = req.price
        ib_order.totalQuantity = req.volume

        self.client.placeOrder(self.orderid, ib_contract, ib_order)
        self.client.reqIds(1)

        order = req.create_order_data(str(self.orderid), self.gateway_name)
        self.gateway.on_order(order)
        return order.vt_orderid
Пример #4
0
    def send_order(self, req: OrderRequest):
        """
        Send a new order.
        """
        if not self.status:
            return ""

        if req.exchange not in EXCHANGE_VT2IB:
            self.gateway.write_log(f"不支持的交易所:{req.exchange}")
            return ""

        if req.type not in ORDERTYPE_VT2IB:
            self.gateway.write_log(f"不支持的价格类型:{req.type}")
            return ""

        self.orderid += 1

        ib_contract = Contract()
        ib_contract.conId = str(req.symbol)
        ib_contract.exchange = EXCHANGE_VT2IB[req.exchange]

        ib_order = Order()
        ib_order.orderId = self.orderid
        ib_order.clientId = self.clientid
        ib_order.action = DIRECTION_VT2IB[req.direction]
        ib_order.orderType = ORDERTYPE_VT2IB[req.type]
        ib_order.lmtPrice = req.price
        ib_order.totalQuantity = req.volume

        self.client.placeOrder(self.orderid, ib_contract, ib_order)
        self.client.reqIds(1)

        order = req.create_order_data(str(self.orderid), self.gateway_name)
        self.gateway.on_order(order)
        return order.vt_orderid
Пример #5
0
    def subscribe(self, req: SubscribeRequest):
        """
        Subscribe tick data update.
        """
        if not self.status:
            return

        if req.exchange not in EXCHANGE_VT2IB:
            self.gateway.write_log(f"不支持的交易所{req.exchange}")
            return

        ib_contract = Contract()
        ib_contract.conId = str(req.symbol)
        ib_contract.exchange = EXCHANGE_VT2IB[req.exchange]

        # Get contract data from TWS.
        self.reqid += 1
        self.client.reqContractDetails(self.reqid, ib_contract)

        # Subscribe tick data and create tick object buffer.
        self.reqid += 1
        self.client.reqMktData(self.reqid, ib_contract, "", False, False, [])

        tick = TickData(
            symbol=req.symbol,
            exchange=req.exchange,
            datetime=datetime.now(),
            gateway_name=self.gateway_name,
        )
        self.ticks[self.reqid] = tick
        self.tick_exchange[self.reqid] = req.exchange
Пример #6
0
    def subscribe(self, req: SubscribeRequest):
        """
        Subscribe tick data update.
        """
        if not self.status:
            return

        if req.exchange not in EXCHANGE_VT2IB:
            self.gateway.write_log(f"不支持的交易所{req.exchange}")
            return

        ib_contract = Contract()
        ib_contract.conId = str(req.symbol)
        ib_contract.exchange = EXCHANGE_VT2IB[req.exchange]

        # Get contract data from TWS.
        self.reqid += 1
        self.client.reqContractDetails(self.reqid, ib_contract)

        # Subscribe tick data and create tick object buffer.
        self.reqid += 1
        self.client.reqMktData(self.reqid, ib_contract, "", False, False, [])

        tick = TickData(
            symbol=req.symbol,
            exchange=req.exchange,
            datetime=datetime.now(),
            gateway_name=self.gateway_name,
        )
        self.ticks[self.reqid] = tick
        self.tick_exchange[self.reqid] = req.exchange
Пример #7
0
def index_contract():
    spx_contract = Contract()
    spx_contract.conId = "416904"
    spx_contract.symbol = 'SPX'
    spx_contract.secType = "IND"
    spx_contract.exchange = "CBOE"
    return spx_contract
Пример #8
0
    def processPositionDataMsg(self, fields):
        sMsgId = next(fields)
        version = decode(int, fields)

        account = decode(str, fields)

        # decode contract fields
        contract = Contract()
        contract.conId = decode(int, fields)
        contract.symbol = decode(str, fields)
        contract.secType = decode(str, fields)
        contract.lastTradeDateOrContractMonth = decode(str, fields)
        contract.strike = decode(float, fields)
        contract.right = decode(str, fields)
        contract.multiplier = decode(str, fields)
        contract.exchange = decode(str, fields)
        contract.currency = decode(str, fields)
        contract.localSymbol = decode(str, fields)
        if version >= 2:
            contract.tradingClass = decode(str, fields)

        if self.serverVersion >= MIN_SERVER_VER_FRACTIONAL_POSITIONS:
            position = decode(float, fields)
        else:
            position = decode(int, fields)

        avgCost = 0.
        if version >= 3:
            avgCost = decode(float, fields)

        self.wrapper.position(account, contract, position, avgCost)
def run(args):
    _logger = logging.getLogger('quanttrader')
    _logger.setLevel(logging.DEBUG)
    handler1 = logging.StreamHandler()
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler1.setFormatter(formatter)
    _logger.addHandler(handler1)

    events_engine = LiveEventEngine()
    tick_event_engine = LiveEventEngine()
    broker = InteractiveBrokers(events_engine, tick_event_engine, 'DU0001')
    broker.reqid = 5000
    # events_engine.register_handler(EventType.LOG, log_event_handler)
    events_engine.start()
    tick_event_engine.start()

    broker.connect('127.0.0.1', 7497, 0)
    time.sleep(5)  # 5 seconds

    contract = Contract()
    contract.conId = args.conid

    broker.api.reqContractDetails(broker.reqid, contract)

    broker.disconnect()
    events_engine.stop()
    tick_event_engine.stop()
Пример #10
0
    def processExecutionDataMsg(self, fields):
        sMsgId = next(fields)
        version = decode(int, fields)

        reqId = -1
        if version >= 7:
            reqId = decode(int, fields)

        orderId = decode(int, fields)

        # decode contract fields
        contract = Contract()
        contract.conId = decode(int, fields) # ver 5 field
        contract.symbol = decode(str, fields)
        contract.secType = decode(str, fields)
        contract.lastTradeDateOrContractMonth = decode(str, fields)
        contract.strike = decode(float, fields)
        contract.right = decode(str, fields)
        if version >= 9:
            contract.multiplier = decode(str, fields)
        contract.exchange = decode(str, fields)
        contract.currency = decode(str, fields)
        contract.localSymbol = decode(str, fields)
        if version >= 10:
            contract.tradingClass = decode(str, fields)

        # decode execution fields
        exec = Execution()
        exec.orderId = orderId
        exec.execId = decode(str, fields)
        exec.time = decode(str, fields)
        exec.acctNumber = decode(str, fields)
        exec.exchange = decode(str, fields)
        exec.side = decode(str, fields)

        if self.serverVersion >= MIN_SERVER_VER_FRACTIONAL_POSITIONS:
                exec.shares = decode(float, fields)
        else:
                exec.shares = decode(int, fields)

        exec.price = decode(float, fields)
        exec.permId = decode(int, fields) # ver 2 field
        exec.clientId = decode(int, fields)  # ver 3 field
        exec.liquidation = decode(int, fields) # ver 4 field

        if version >= 6:
            exec.cumQty = decode(float, fields)
            exec.avgPrice = decode(float, fields)

        if version >= 8:
            exec.orderRef = decode(str, fields)

        if version >= 9:
            exec.evRule = decode(str, fields)
            exec.evMultiplier = decode(float, fields)
        if self.serverVersion >= MIN_SERVER_VER_MODELS_SUPPORT:
            exec.modelCode = decode(str, fields)

        self.wrapper.execDetails(reqId, contract, exec)
Пример #11
0
 def WrongContract():
     contract = Contract()
     contract.symbol = " IJR "
     contract.conId = 9579976
     contract.secType = "STK"
     contract.exchange = "SMART"
     contract.currency = "USD"
     return contract
Пример #12
0
 def get_contract(self, code: str) -> Contract:
     contract = Contract()
     ss = code.split("_")
     contract.symbol = ss[0]
     contract.secType = ss[1]
     contract.currency = ss[2]
     contract.exchange = ss[3]
     contract_detail: ContractDetails = self.sync_get_contract_detail(contract)
     contract.conId = contract_detail.contract.conId
     return contract
Пример #13
0
def Dict_to_Contract(data: dict):
    con = Contract()
    con.symbol = data['symbol']
    con.conId = data['conID']
    con.secType = data['secType']
    con.currency = data['currency']
    con.exchange = data['exchange']
    con.primaryExchange = data['primaryExchange']
    con.multiplier = data['multiplier']
    con.tradingClass = data['tradingClass']
    con.localSymbol = data['localSymbol']
    con.right = data['right']
    con.lastTradeDateOrContractMonth = data['lastTradeDateOrContractMonth']
    con.strike = data['strike']
    return con
Пример #14
0
    def from_string(cls, contract_str: str) -> "IBContract":
        """ Create IBContract object from the corresponding string. """

        params, combo_legs = contract_str.split("combo:")
        ib_contract = Contract()
        [ib_contract.conId, ib_contract.symbol, ib_contract.secType, ib_contract.lastTradeDateOrContractMonth,
         ib_contract.strike, ib_contract.right, ib_contract.multiplier, ib_contract.exchange,
         ib_contract.primaryExchange, ib_contract.currency, ib_contract.localSymbol, ib_contract.tradingClass,
         ib_contract.includeExpired, ib_contract.secIdType, ib_contract.secId] = params.split(",")

        ib_contract.conId = int(ib_contract.conId)
        ib_contract.strike = float(ib_contract.strike)
        ib_contract.includeExpired = bool(ib_contract.includeExpired == "True")

        combo_legs = combo_legs.split(";")
        combo_legs = [c for c in combo_legs if len(c) > 0]

        if len(combo_legs) > 0:
            if len(combo_legs[-1].split(",")) == 3:
                delta_neutral_contract = combo_legs[-1].split(",")
                combo_legs = combo_legs[:-1]

                ib_contract.deltaNeutralContract = DeltaNeutralContract()
                ib_contract.deltaNeutralContract.conId = int(delta_neutral_contract[0])
                ib_contract.deltaNeutralContract.delta = float(delta_neutral_contract[1])
                ib_contract.deltaNeutralContract.price = float(delta_neutral_contract[2])

            ib_contract.comboLegs = [] if len(combo_legs) > 0 else None
            if ib_contract.comboLegs is not None:
                for params in combo_legs:
                    params = params.split(",")
                    combo_leg = ComboLeg()
                    combo_leg.conId = int(params[0])
                    combo_leg.ratio = int(params[1])
                    combo_leg.action = params[2]
                    combo_leg.exchange = params[3]
                    combo_leg.openClose = int(params[4])
                    combo_leg.shortSaleSlot = int(params[5])
                    combo_leg.designatedLocation = params[6]
                    combo_leg.exemptCode = int(params[7])
                    ib_contract.comboLegs.append(combo_leg)

        return cls.from_ib_contract(ib_contract)
Пример #15
0
    def processPortfolioValueMsg(self, fields):

        sMsgId = next(fields)
        version = decode(int, fields)

        # read contract fields
        contract = Contract()
        contract.conId = decode(int, fields) # ver 6 field
        contract.symbol = decode(str, fields)
        contract.secType = decode(str, fields)
        contract.lastTradeDateOrContractMonth = decode(str, fields)
        contract.strike = decode(float, fields)
        contract.right = decode(str, fields)

        if version >= 7:
            contract.multiplier = decode(str, fields)
            contract.primaryExchange = decode(str, fields)

        contract.currency = decode(str, fields)
        contract.localSymbol = decode(str, fields) # ver 2 field
        if version >= 8:
            contract.tradingClass = decode(str, fields)

        if self.serverVersion >= MIN_SERVER_VER_FRACTIONAL_POSITIONS:
            position = decode(float, fields)
        else:
            position = decode(int, fields)

        marketPrice = decode(float, fields)
        marketValue = decode(float, fields)
        averageCost = decode(float, fields) # ver 3 field
        unrealizedPNL = decode(float, fields) # ver 3 field
        realizedPNL = decode(float, fields) # ver 3 field

        accountName = decode(str, fields) # ver 4 field

        if version == 6 and self.serverVersion == 39:
            contract.primaryExchange = decode(str, fields)

        self.wrapper.updatePortfolio( contract,
            position, marketPrice, marketValue, averageCost,
            unrealizedPNL, realizedPNL, accountName)
Пример #16
0
    def query_history(self, req: HistoryRequest):
        """"""
        self.history_req = req

        self.reqid += 1

        ib_contract = Contract()
        ib_contract.conId = str(req.symbol)
        ib_contract.exchange = EXCHANGE_VT2IB[req.exchange]

        if req.end:
            end = req.end
            end_str = end.strftime("%Y%m%d %H:%M:%S")
        else:
            end = datetime.now()
            end_str = ""

        delta = end - req.start
        days = min(delta.days, 180)  # IB only provides 6-month data
        duration = f"{days} D"
        bar_size = INTERVAL_VT2IB[req.interval]

        if req.exchange == Exchange.IDEALPRO:
            bar_type = "MIDPOINT"
        else:
            bar_type = "TRADES"

        self.client.reqHistoricalData(self.reqid, ib_contract, end_str,
                                      duration, bar_size, bar_type, 1, 1,
                                      False, [])

        self.history_condition.acquire()  # Wait for async data return
        self.history_condition.wait()
        self.history_condition.release()

        history = self.history_buf
        self.history_buf = []  # Create new buffer list
        self.history_req = None

        return history
Пример #17
0
def gen_contract_id_only(contract_id):
    result_contract = Contract()
    result_contract.conId = contract_id
    return result_contract
Пример #18
0
 def Bond():
     contract = Contract()
     contract.conId = 267433416
     contract.exchange = "SMART"
     return contract
Пример #19
0
 def ByConId():
     contract = Contract()
     contract.secType = "CASH"
     contract.conId = 12087792
     contract.exchange = "IDEALPRO"
     return contract
Пример #20
0
def get_data(symbol=None,
             secType='STK',
             exch=None,
             curr=None,
             duration=None,
             enddate=None,
             barsize=None,
             conid=None):
    app = TestApp("127.0.0.1", port, 20)
    ibcontract = Contract()

    if conid == None:

        ibcontract.symbol = symbol
        ibcontract.secType = secType
        ibcontract.exchange = exch
        ibcontract.currency = curr

        # resolved_ibcontract=app.resolve_ib_contract(ibcontract)
        #
        # historic_data = app.get_IB_historical_data(resolved_ibcontract,durationStr=duration,enddate=enddate,barSizeSetting=barsize)
    elif exch == None:
        ibcontract.conId = conid
    else:
        ibcontract.conId = conid
        ibcontract.exchange = exch
    resolved_ibcontract = app.resolve_ib_contract(ibcontract)
    historic_data = app.get_IB_historical_data(resolved_ibcontract,
                                               durationStr=duration,
                                               enddate=enddate,
                                               barSizeSetting=barsize)

    time.sleep(1)
    print(app.isConnected())
    app.disconnect()
    # app.waitOnUpdate(timeout=0.1)
    print(app.isConnected())
    print('HD Disconnected')

    df = pd.DataFrame(
        data=historic_data,
        columns=['date', 'open', 'high', 'low', 'close', 'volume'])

    return df


# today = datetime.today().strftime("%Y%m%d %H:%M:%S %Z")  # endDateTime,
# #
# data = get_data('SPY','STK','SMART','USD',duration ="1 D",enddate = datetime.today().strftime("%Y%m%d %H:%M:%S %Z"),barsize='1 day')
# # #
# #
# data = get_data("EQIX",'STK','SMART','USD',duration ="1 D",enddate = datetime.today().strftime("%Y%m%d %H:%M:%S %Z"),barsize='1 day')
# #
# print(data)

# data = get_data(conid=11054,exch ='TGATE',duration ="1 D",enddate = datetime.today().strftime("%Y%m%d %H:%M:%S %Z"),barsize='1 day')
# # #
# print(data)

# print(df)
#
#
# import matplotlib.pyplot as plt
#
# plt.plot(df['date'],df['close'])
# plt.show()
Пример #21
0
    def connect(self):
        self.app.reqIds(-1)
        with self.app.msg_queue.mutex:
            self.app.msg_queue.queue.clear()
        self.app.msgs.clear()
        self.app.ret.clear()
        self.context.clear()
        if self.app.globalCancelOnly:
            print("Executing GlobalCancel only")
            self.app.reqGlobalCancel()
        else:
            print("Executing requests")
            self.app.reqMarketDataType(3)
            # delayed
            time.sleep(self.WTime)
            self.app.reqManagedAccts()
            time.sleep(self.WTime)
            self.app.run()

            self.app.reqAccountSummary(
                self.app.nextOrderId(), "All",
                "AvailableFunds, NetLiquidation, BuyingPower")
            #AccountSummaryTags.AllTags)
            time.sleep(self.WTime)
            self.app.cancelAccountSummary(self.app.nextValidOrderId - 1)
            time.sleep(self.WTime)
            self.app.run()
            time.sleep(self.WTime)
            for account in self.app.ret["Account_list"]:
                self.app.accountMap[self.app.nextValidOrderId] = account
                self.app.reqPnL(self.app.nextOrderId(), account, "")
                time.sleep(5 * self.WTime)
                self.app.cancelPnL(self.app.nextValidOrderId - 1)
                self.app.run()

            time.sleep(self.WTime)
            self.app.reqPositions()
            self.app.run()
            time.sleep(self.WTime)
            self.app.cancelPositions()
            time.sleep(self.WTime)
            self.app.run()
            if False:  #len(self.app.ret['Error']) > 0:
                #print(self.app.ret['Error'])
                #    self.app.disconnect()
                pass
            else:
                temp_daily_pnls = set()
                for daily_pnl in self.app.ret["Daily_PnL"]:
                    temp_daily_pnls.add(daily_pnl)
                    for reqId, account in self.app.accountMap.items():
                        if reqId == daily_pnl['ReqId']:
                            temp_daily_pnls.remove(daily_pnl)
                            daily_pnl.update({'Account': account})
                            temp_daily_pnls.add(daily_pnl)
                del self.app.ret["Daily_PnL"]
                self.app.ret["Daily_PnL"] = temp_daily_pnls

                for positions in self.app.ret["Positions"]:
                    contract = Contract()
                    contract.symbol = positions['Symbol']
                    contract.secType = positions['SecType']
                    contract.currency = positions['Currency']
                    contract.conId = positions['ConId']
                    contract.exchange = "SMART"
                    self.app.callMap[
                        self.app.nextValidOrderId] = positions['ConId']
                    time.sleep(self.WTime)
                    self.app.reqPnLSingle(self.app.nextOrderId(),
                                          positions['Account'], "",
                                          positions['ConId'])
                    time.sleep(self.WTime)
                    self.app.cancelPnLSingle(self.app.nextValidOrderId - 1)
                    time.sleep(self.WTime)
                    self.app.callMap[
                        self.app.nextValidOrderId] = positions['ConId']
                    self.app.reqMktData(self.app.nextOrderId(), contract,
                                        "104,106,258", False, False, [])
                    time.sleep(self.WTime)
                    self.app.cancelMktData(self.app.nextValidOrderId - 1)
                self.app.run()
                temp_Positions = set()
                for positions in self.app.ret["Positions"]:
                    temp_Positions.add(positions)
                    for daily_PnL_Single in self.app.ret['Daily_PnL_Single']:
                        for reqId, ConId in self.app.callMap.items():
                            if reqId == daily_PnL_Single[
                                    'ReqId'] and ConId == positions[
                                        'ConId'] and positions[
                                            'Account'] == self.app.account:
                                temp_Positions.remove(positions)
                                for key, value in daily_PnL_Single.items():
                                    if (value > 1e20):
                                        daily_PnL_Single[key] = 0
                                positions.update(daily_PnL_Single)
                                temp_Positions.add(positions)
                del self.app.ret["Positions"]
                self.app.ret["Positions"] = temp_Positions

                temp_Positions = set()
                for positions in self.app.ret["Positions"]:
                    temp_Positions.add(positions)
                    for tickGeneric in self.app.ret['TickGeneric']:
                        #for reqId, contract in self.app.callMap.items():
                        for reqId, ConId in self.app.callMap.items():
                            if reqId == tickGeneric[
                                    'TickerId'] and ConId == positions[
                                        'ConId'] and tickGeneric[
                                            'TickType'] == 24 and positions[
                                                'Account'] == self.app.account:
                                temp_Positions.remove(positions)
                                positions.update(
                                    {'ImpVol': tickGeneric['Value']})
                                temp_Positions.add(positions)

                del self.app.ret["Positions"]
                self.app.ret["Positions"] = temp_Positions
                self.app.reqAllOpenOrders()
                time.sleep(self.WTime)
                # ! [clientrun]
                self.app.run()
                print("Executing requests ... finished")
                # ! [clientrun]
        self.get_msg()
Пример #22
0
#                  strike = 2775,
#                  right = "C",
#                  local="EW2M8 C2775",
#                  multiplier = 50)
from ibapi.contract import Contract as IBcontract
ibcontract = IBcontract()
ibcontract.secType = "FOP"
ibcontract.symbol = "ES"
ibcontract.exchange = "GLOBEX"
#ibcontract.primaryExchange = "CME"
ibcontract.currency = "USD"
ibcontract.lastTradeDateOrContractMonth = "20180608"
ibcontract.strike = 2775
ibcontract.right = "C"
ibcontract.multiplier = "50"
ibcontract.conId = 317012336
ibcontract.localSymbol = "EW2M8 C2775"

## resolve the contract
resolved_ibcontract = app.resolve_ib_contract(ibcontract)

tickerid = app.start_getting_IB_market_data(resolved_ibcontract)

time.sleep(10)

## What have we got so far?
market_data1 = app.get_IB_market_data(tickerid)

print(market_data1[0])

market_data1_as_df = market_data1.as_pdDataFrame()
Пример #23
0
def main():
    ### DEVELOPMENT ONLY
    #Timer(10, shutdown).start()

    while True:
        debug("connecting to Gateway and Database...")
        myApi = ibapihandle(gwcnx(), sqlcnx())
        myApi.database.debugSqlhandle = 0

        if myApi.isConnected() == True and myApi.database.isConnected(
        ) == True:
            debug('Gateway and Database are connected.')

            run = Timer(0, myApi.run).start()
            myApi.initDb()

            # define your search and download
            contract = Contract()
            contract.symbol = 'ADBE'
            contract.currency = 'USD'
            contract.lastTradeDateOrContractMonth = '20200327'
            myApi.downloadOptionChain(contract)

            dfContract = myApi.database.tblReadToDataFrame('*',
                                                           'general.contract',
                                                           index='conId')
            dfFilter = dfContract[(dfContract['symbol'] == contract.symbol)
                                  & (dfContract['lastTradeDateOrContractMonth']
                                     == contract.lastTradeDateOrContractMonth)]

            print('[Found]', len(dfFilter), 'of', len(dfContract),
                  'contracts in Database matching Filter settings')

            cnt_all = len(dfFilter.index)
            cnt = 1
            start = datetime.now()
            print(cnt_all, 'Packages to download. Starting at', start)
            errList = []

            myApi.debugibapihandle = 0
            myApi.database.debugSqlhandle = 0

            for conId in dfFilter.index:
                histContract = Contract()
                histContract.conId = conId
                histContract.exchange = 'CBOE'

                histBarData = myApi.getHistoricalBarData(histContract,
                                                         '20200320 00:00:00',
                                                         '6 M',
                                                         '1 hour',
                                                         'TRADES',
                                                         timeout=20)
                if type(histBarData) == list:
                    myApi.tblHistoricalBarDataAppend(histContract, histBarData)
                else:
                    errList.append(conId)
                print('[{}]'.format(conId),
                      '{}% |'.format(round(cnt / cnt_all * 100, 2)), cnt, 'of',
                      cnt_all, 'Packages requested. Error List: {}.'.format(
                          len(errList)), 'Running:',
                      datetime.now() - start, 'Remaining Time:',
                      (datetime.now() - start) / cnt *
                      (cnt_all -
                       cnt))  #(cnt_all - cnt)*(datetime.now()-start)/(cnt+1))
                cnt += 1
            end = datetime.now()
            print('All Packages downloaded at', end)
            print('Total time:', end - start)

            print('Packages Lost {lost} out of {max} | {pct}%'.format(
                lost=len(errList),
                max=cnt_all,
                pct=round(len(errList) / cnt_all * 100, 2)))
            print('Packages Lost:', errList)

            Timer(0, shutdown).start()

        # wait to re create object
        time.sleep(10)
Пример #24
0
    def processOpenOrder(self, fields):

        sMsgId = next(fields)
        version = decode(int, fields)

        order = Order()
        order.orderId = decode(int, fields)

        contract = Contract()

        contract.conId = decode(int, fields) # ver 17 field
        contract.symbol = decode(str, fields) 
        contract.secType = decode(str, fields) 
        contract.lastTradeDateOrContractMonth = decode(str, fields) 
        contract.strike = decode(float, fields)
        contract.right = decode(str, fields) 
        if version >= 32:
            contract.multiplier = decode(str, fields) 
        contract.exchange = decode(str, fields) 
        contract.currency = decode(str, fields) 
        contract.localSymbol = decode(str, fields)  # ver 2 field
        if version >= 32:
            contract.tradingClass = decode(str, fields) 

        # read order fields
        order.action = decode(str, fields)  

        if self.serverVersion >= MIN_SERVER_VER_FRACTIONAL_POSITIONS:
            order.totalQuantity = decode(float, fields)  
        else:
            order.totalQuantity = decode(int, fields)

        order.orderType = decode(str, fields) 
        if version < 29:
            order.lmtPrice = decode(float, fields)
        else:
            order.lmtPrice = decode(float, fields, SHOW_UNSET)
        if version < 30:
            order.auxPrice = decode(float, fields)
        else:
            order.auxPrice = decode(float, fields, SHOW_UNSET)
        order.tif = decode(str, fields)
        order.ocaGroup = decode(str, fields)
        order.account = decode(str, fields)
        order.openClose = decode(str, fields)

        order.origin = decode(int, fields)

        order.orderRef = decode(str, fields)
        order.clientId = decode(int, fields) # ver 3 field
        order.permId = decode(int, fields)   # ver 4 field

        order.outsideRth = decode(bool, fields) # ver 18 field
        order.hidden = decode(bool, fields) # ver 4 field
        order.discretionaryAmt = decode(float, fields) # ver 4 field
        order.goodAfterTime = decode(str, fields) # ver 5 field

        order.sharesAllocation = decode(str, fields) # deprecated ver 6 field

        order.faGroup = decode(str, fields) # ver 7 field
        order.faMethod = decode(str, fields) # ver 7 field
        order.faPercentage = decode(str, fields) # ver 7 field
        order.faProfile = decode(str, fields) # ver 7 field

        if self.serverVersion >= MIN_SERVER_VER_MODELS_SUPPORT:
            order.modelCode = decode(str, fields)

        order.goodTillDate = decode(str, fields) # ver 8 field

        order.rule80A = decode(str, fields) # ver 9 field
        order.percentOffset = decode(float, fields, SHOW_UNSET) # ver 9 field
        order.settlingFirm = decode(str, fields) # ver 9 field
        order.shortSaleSlot = decode(int, fields) # ver 9 field
        order.designatedLocation = decode(str, fields) # ver 9 field
        if self.serverVersion == MIN_SERVER_VER_SSHORTX_OLD:
            exemptCode = decode(int, fields)
        elif version >= 23:
            order.exemptCode = decode(int, fields)
        order.auctionStrategy = decode(int, fields) # ver 9 field
        order.startingPrice = decode(float, fields, SHOW_UNSET) # ver 9 field
        order.stockRefPrice = decode(float, fields, SHOW_UNSET) # ver 9 field
        order.delta = decode(float, fields, SHOW_UNSET) # ver 9 field
        order.stockRangeLower = decode(float, fields, SHOW_UNSET) # ver 9 field
        order.stockRangeUpper = decode(float, fields, SHOW_UNSET) # ver 9 field
        order.displaySize = decode(int, fields) # ver 9 field

        #if( version < 18) {
        #		# will never happen
        #		/* order.rthOnly = */ readBoolFromInt()
        #}

        order.blockOrder = decode(bool, fields) # ver 9 field
        order.sweepToFill = decode(bool, fields) # ver 9 field
        order.allOrNone = decode(bool, fields) # ver 9 field
        order.minQty = decode(int, fields, SHOW_UNSET) # ver 9 field
        order.ocaType = decode(int, fields) # ver 9 field
        order.eTradeOnly = decode(bool, fields) # ver 9 field
        order.firmQuoteOnly = decode(bool, fields) # ver 9 field
        order.nbboPriceCap = decode(float, fields, SHOW_UNSET) # ver 9 field

        order.parentId = decode(int, fields) # ver 10 field
        order.triggerMethod = decode(int, fields) # ver 10 field

        order.volatility = decode(float, fields, SHOW_UNSET) # ver 11 field
        order.volatilityType = decode(int, fields) # ver 11 field
        order.deltaNeutralOrderType = decode(str, fields) # ver 11 field (had a hack for ver 11)
        order.deltaNeutralAuxPrice = decode(float, fields, SHOW_UNSET) # ver 12 field

        if version >= 27 and order.deltaNeutralOrderType:
            order.deltaNeutralConId = decode(int, fields)
            order.deltaNeutralSettlingFirm = decode(str, fields)
            order.deltaNeutralClearingAccount = decode(str, fields)
            order.deltaNeutralClearingIntent = decode(str, fields)

        if version >= 31 and order.deltaNeutralOrderType:
            order.deltaNeutralOpenClose = decode(str, fields)
            order.deltaNeutralShortSale = decode(bool, fields)
            order.deltaNeutralShortSaleSlot = decode(int, fields)
            order.deltaNeutralDesignatedLocation = decode(str, fields)

        order.continuousUpdate = decode(bool, fields) # ver 11 field

        # will never happen
        #if( self.serverVersion == 26) {
        #	order.stockRangeLower = readDouble()
        #	order.stockRangeUpper = readDouble()
        #}

        order.referencePriceType = decode(int, fields) # ver 11 field

        order.trailStopPrice = decode(float, fields, SHOW_UNSET) # ver 13 field

        if version >= 30:
            order.trailingPercent = decode(float, fields, SHOW_UNSET)

        order.basisPoints = decode(float, fields, SHOW_UNSET) # ver 14 field
        order.basisPointsType = decode(int, fields, SHOW_UNSET) # ver 14 field
        contract.comboLegsDescrip = decode(str, fields) # ver 14 field

        if version >= 29:
            contract.comboLegsCount = decode(int, fields)

            if contract.comboLegsCount > 0:
                contract.comboLegs = []
                for idxLeg in range(contract.comboLegsCount):
                    comboLeg = ComboLeg()
                    comboLeg.conId = decode(int, fields)
                    comboLeg.ratio = decode(int, fields)
                    comboLeg.action = decode(str, fields)
                    comboLeg.exchange = decode(str, fields)
                    comboLeg.openClose = decode(int, fields)
                    comboLeg.shortSaleSlot = decode(int, fields)
                    comboLeg.designatedLocation = decode(str, fields)
                    comboLeg.exemptCode = decode(int, fields)
                    contract.comboLegs.append(comboLeg)

            order.orderComboLegsCount = decode(int, fields)
            if order.orderComboLegsCount > 0:
                order.orderComboLegs = []
                for idxOrdLeg in range(order.orderComboLegsCount):
                    orderComboLeg = OrderComboLeg()
                    orderComboLeg.price = decode(float, fields, SHOW_UNSET)
                    order.orderComboLegs.append(orderComboLeg)

        if version >= 26:
            order.smartComboRoutingParamsCount = decode(int, fields)
            if order.smartComboRoutingParamsCount > 0:
                order.smartComboRoutingParams = []
                for idxPrm in range(order.smartComboRoutingParamsCount):
                    tagValue = TagValue()
                    tagValue.tag = decode(str, fields)
                    tagValue.value = decode(str, fields)
                    order.smartComboRoutingParams.append(tagValue)

        if version >= 20:
            order.scaleInitLevelSize = decode(int, fields, SHOW_UNSET)
            order.scaleSubsLevelSize = decode(int, fields, SHOW_UNSET)
        else:
            # ver 15 fields
            order.notSuppScaleNumComponents = decode(int, fields, SHOW_UNSET)
            order.scaleInitLevelSize = decode(int, fields, SHOW_UNSET) # scaleComponectSize

        order.scalePriceIncrement = decode(float, fields, SHOW_UNSET) # ver 15 field

        if version >= 28 and order.scalePriceIncrement != UNSET_DOUBLE \
                and order.scalePriceIncrement > 0.0:
            order.scalePriceAdjustValue = decode(float, fields, SHOW_UNSET)
            order.scalePriceAdjustInterval = decode(int, fields, SHOW_UNSET)
            order.scaleProfitOffset = decode(float, fields, SHOW_UNSET)
            order.scaleAutoReset = decode(bool, fields)
            order.scaleInitPosition = decode(int, fields, SHOW_UNSET)
            order.scaleInitFillQty = decode(int, fields, SHOW_UNSET)
            order.scaleRandomPercent = decode(bool, fields)

        if version >= 24:
            order.hedgeType = decode(str, fields)
            if order.hedgeType:
                order.hedgeParam = decode(str, fields)

        if version >= 25:
            order.optOutSmartRouting = decode(bool, fields)

        order.clearingAccount = decode(str, fields) # ver 19 field
        order.clearingIntent = decode(str, fields) # ver 19 field

        if version >= 22:
            order.notHeld = decode(bool, fields)

        if version >= 20:
            contract.underCompPresent = decode(bool, fields)
            if contract.underCompPresent:
                contract.underComp = UnderComp()
                contract.underComp.conId = decode(int, fields)
                contract.underComp.delta = decode(float, fields)
                contract.underComp.price = decode(float, fields)

        if version >= 21:
            order.algoStrategy = decode(str, fields)
            if order.algoStrategy:
                order.algoParamsCount = decode(int, fields)
                if order.algoParamsCount > 0:
                    order.algoParams = []
                    for idxAlgoPrm in range(order.algoParamsCount):
                        tagValue = TagValue()
                        tagValue.tag = decode(str, fields)
                        tagValue.value = decode(str, fields)
                        order.algoParams.append(tagValue)

        if version >= 33:
            order.solicited = decode(bool, fields)

        orderState = OrderState()

        order.whatIf = decode(bool, fields) # ver 16 field

        orderState.status = decode(str, fields) # ver 16 field
        orderState.initMargin = decode(str, fields) # ver 16 field
        orderState.maintMargin = decode(str, fields) # ver 16 field
        orderState.equityWithLoan = decode(str, fields) # ver 16 field
        orderState.commission = decode(float, fields, SHOW_UNSET) # ver 16 field
        orderState.minCommission = decode(float, fields, SHOW_UNSET) # ver 16 field
        orderState.maxCommission = decode(float, fields, SHOW_UNSET) # ver 16 field
        orderState.commissionCurrency = decode(str, fields) # ver 16 field
        orderState.warningText = decode(str, fields) # ver 16 field

        if version >= 34:
            order.randomizeSize = decode(bool, fields)
            order.randomizePrice = decode(bool, fields)

        if self.serverVersion >= MIN_SERVER_VER_PEGGED_TO_BENCHMARK:
            if order.orderType == "PEG BENCH":
                order.referenceContractId = decode(int, fields)
                order.isPeggedChangeAmountDecrease = decode(bool, fields)
                order.peggedChangeAmount = decode(float, fields)
                order.referenceChangeAmount = decode(float, fields)
                order.referenceExchangeId = decode(str, fields)

            order.conditionsSize = decode(int, fields)
            if order.conditionsSize > 0:
                order.conditions = []
                for idxCond in range(order.conditionsSize):
                    order.conditionType = decode(int, fields)
                    condition = order_condition.Create(order.conditionType)
                    condition.decode(fields)
                    order.conditions.append(condition)

                order.conditionsIgnoreRth = decode(bool, fields)
                order.conditionsCancelOrder = decode(bool, fields)

            order.adjustedOrderType = decode(str, fields)
            order.triggerPrice = decode(float, fields)
            order.trailStopPrice = decode(float, fields)
            order.lmtPriceOffset = decode(float, fields)
            order.adjustedStopPrice = decode(float, fields)
            order.adjustedStopLimitPrice = decode(float, fields)
            order.adjustedTrailingAmount = decode(float, fields)
            order.adjustableTrailingUnit = decode(int, fields)

        if self.serverVersion >= MIN_SERVER_VER_SOFT_DOLLAR_TIER:
            name = decode(str, fields)
            value = decode(str, fields)
            displayName = decode(str, fields)
            order.softDollarTier = SoftDollarTier(name, value, displayName)

        self.wrapper.openOrder(order.orderId, contract, order, orderState)