コード例 #1
0
async def test_request_error_raised(ib):
    contract = ibi.Stock('MMM', 'SMART', 'USD')
    order = ibi.MarketOrder('BUY', 100)
    orderState = await ib.whatIfOrderAsync(contract, order)
    assert orderState.commission > 0

    ib.RaiseRequestErrors = True
    badContract = ibi.Stock('XXX')
    with pytest.raises(ibi.RequestError) as exc_info:
        await ib.whatIfOrderAsync(badContract, order)
    assert exc_info.value.code == 321
コード例 #2
0
ファイル: feedStocks.py プロジェクト: ajmal017/terrier
def reqMktData(tickerList, client, waitTime):
    ib = insync.IB()
    contractList = []
    ib.connect('127.0.0.1', 7497, clientId=client)

    for ticker in tickerList:
        ticker = ticker.rstrip().upper()
        contract = insync.Stock(ticker, "SMART", "USD")
        ib.qualifyContracts(contract)
        ib.reqMktData(contract, "", False, False)
        contractList.append({"ticker": ticker, "contract": contract})

    ib.sleep(5)

    while True:
        t = copy.copy(dt.datetime.now())
        tWait = copy.copy(t + dt.timedelta(seconds=waitTime))

        for contract in contractList:
            fileName = "{}_mkt.npy".format(contract["ticker"])
            print("{} - STREAMING {}".format(dt.datetime.now(),
                                             contract["ticker"]))
            np.save(fileName, ib.ticker(contract["contract"]))

        t = copy.copy(dt.datetime.now())
        sleepTime = (tWait - t).total_seconds()
        ib.sleep(sleepTime)
コード例 #3
0
    async def find_contract(
        self,
        symbol,
        currency: str = 'USD',
        **kwargs,
    ) -> Contract:
        # use heuristics to figure out contract "type"
        try:
            sym, exch = symbol.upper().rsplit('.', maxsplit=1)
        except ValueError:
            # likely there's an embedded `.` for a forex pair
            await tractor.breakpoint()

        # futes
        if exch in ('GLOBEX', 'NYMEX', 'CME', 'CMECRYPTO'):
            con = await self.get_cont_fute(symbol=sym, exchange=exch)

        elif exch in ('FOREX'):
            currency = ''
            symbol, currency = sym.split('/')
            con = ibis.Forex(
                symbol=symbol,
                currency=currency,
            )
            con.bars_kwargs = {'whatToShow': 'MIDPOINT'}

        # commodities
        elif exch == 'CMDTY':  # eg. XAUUSD.CMDTY
            con_kwargs, bars_kwargs = _adhoc_cmdty_data_map[sym]
            con = ibis.Commodity(**con_kwargs)
            con.bars_kwargs = bars_kwargs

        # stonks
        else:
            # TODO: metadata system for all these exchange rules..
            primaryExchange = ''

            if exch in ('PURE', 'TSE'):  # non-yankee
                currency = 'CAD'
                if exch in ('PURE', 'TSE'):
                    # stupid ib...
                    primaryExchange = exch
                    exch = 'SMART'

            con = ibis.Stock(
                symbol=sym,
                exchange=exch,
                primaryExchange=primaryExchange,
                currency=currency,
            )
        try:
            exch = 'SMART' if not exch else exch
            contract = (await self.ib.qualifyContractsAsync(con))[0]

            # head = await self.get_head_time(contract)
            # print(head)

        except IndexError:
            raise ValueError(f"No contract could be found {con}")
        return contract
コード例 #4
0
ファイル: ibx.py プロジェクト: mcpalmer1980/atrade
    def Buy(self, ticker, shares, limit=None):
        '''
        Buy x [shares] of stock [ticker]
        The purchase will be immediately forwarded to the TWS API if possible
        
        EXPERIMENTAL: Prices automatically limited to 105% of the current cost
        '''
        if not self.connected:
            print(
                f'Service not available: cannot buy {shares} shares of {ticker}'
            )
            return
        #if not limit:
        #    limit = self.GetPrice(ticker) * buy_limit_multi

        print('buying {} shares of {}'.format(shares, ticker))
        contract = ibi.Stock(ticker, 'SMART', self.currency)
        self.ib.qualifyContracts(contract)
        if limit:
            order = ibi.order.LimitOrder('BUY', shares, limit)
        else:
            order = ibi.order.MarketOrder('BUY', shares)
        trade = self.ib.placeOrder(contract, order)
        self.trades.append(trade)
        return trade
コード例 #5
0
def marketOrder(action, size, symbol):
    print("CONTRACT")
    contract = insync.Stock(symbol, 'SMART', 'USD')
    print("ORDER")
    order = insync.MarketOrder(action, size)
    print("QUALIFY")
    ib.qualifyContracts(contract)
    print("PLACE")
    ib.placeOrder(contract, order)
コード例 #6
0
ファイル: ibx.py プロジェクト: kyp0717/yfin
 def Buy(self, ticker, amount, limit=None):
     print('buying {} shares of {}'.format(amount, ticker))
     contract = ibi.Stock(ticker, 'SMART', self.currency)
     self.ib.qualifyContracts(contract)
     if limit:
         order = ibi.order.LimitOrder('BUY', amount, limit)
     else:
         order = ibi.order.MarketOrder('BUY', amount)
     trade = self.ib.placeOrder(contract, order)
     self.trades.append(trade)
     return trade
コード例 #7
0
ファイル: ibx.py プロジェクト: kyp0717/yfin
 def Sell(self, ticker=None, amount=None):
     amount = amount or self.GetShares(ticker)
     if not amount:
         print('have no shares of {} to sell'.format(ticker))
         return None
     print('selling {} shares of {}'.format(amount, ticker))
     contract = ibi.Stock(ticker, 'SMART', self.currency)
     self.ib.qualifyContracts(contract)
     order = ibi.order.MarketOrder('SELL', amount)
     trade = self.ib.placeOrder(contract, order)
     return trade
コード例 #8
0
ファイル: ibx.py プロジェクト: kyp0717/yfin
 def GetPrice(self, ticker):
     contract = self.ib.qualifyContracts(ibi.Stock(ticker, 'SMART', 'USD'))
     r = self.ib.reqMktData(*contract)
     for i in range(100):
         if r.last == r.last:
             print('found price after {} tries'.format(i))
             price = r.last
             break
         self.ib.sleep(.1)
     else:
         print('using close price')
         price = r.close
     return price
コード例 #9
0
ファイル: ibx.py プロジェクト: kyp0717/yfin
 def GetPrices(self, ticks=None):
     import classes
     if not ticks:
         td = TickerData()
         ticks = td[td.get_name(False)]
     start_time = time.time()
     contracts = []
     for tick in ticks:
         contracts.append(ibi.Stock(tick, 'SMART', 'USD'))
     self.ib.qualifyContracts(*contracts)
     prices = self.ib.reqTickers(*contracts)
     elapsed = time.time() - start_time
     print(prices)
     print(elapsed)
コード例 #10
0
ファイル: ibx.py プロジェクト: mcpalmer1980/atrade
 def Sell(self, ticker=None, shares=None, limit=None):
     #if not limit:
     #    limit = self.GetPrice(ticker) * sell_limit_multi
     shares = shares or self.GetShares(ticker)
     if not shares:
         print('have no shares of {} to sell'.format(ticker))
         return None
     print('selling {} shares of {}'.format(shares, ticker))
     contract = ibi.Stock(ticker, 'SMART', self.currency)
     self.ib.qualifyContracts(contract)
     if limit:
         order = ibi.order.LimitOrder('SELL', shares)
     else:
         order = ibi.order.MarketOrder('SELL', shares)
     trade = self.ib.placeOrder(contract, order)
     return trade
コード例 #11
0
ファイル: feedStocks.py プロジェクト: ajmal017/terrier
def reqHistoricalData(tickerList, client, waitTime, duration, barSize,
                      whatToShow):
    ib = insync.IB()
    contractList = []
    ib.connect('127.0.0.1', 7497, clientId=client)

    for ticker in tickerList:
        ticker = ticker.rstrip().upper()
        contract = insync.Stock(ticker, "SMART", "USD")
        ib.qualifyContracts(contract)
        contractList.append({"ticker": ticker, "contract": contract})

    ib.sleep(5)

    while True:
        t = copy.copy(dt.datetime.now())
        tWait = copy.copy(t + dt.timedelta(seconds=waitTime))

        for contract in contractList:
            fileName = "{}_bar.npy".format(contract["ticker"])
            print("{} - STREAMING {}".format(dt.datetime.now(),
                                             contract["ticker"]))

            bars = ib.reqHistoricalData(contract["contract"],
                                        endDateTime="",
                                        durationStr=duration,
                                        barSizeSetting=barSize,
                                        whatToShow=whatToShow,
                                        useRTH=True,
                                        formatDate=1)

            np.save(fileName, bars)

        t = copy.copy(dt.datetime.now())
        sleepTime = (tWait - t).total_seconds()
        ib.sleep(sleepTime)
コード例 #12
0
ファイル: data.py プロジェクト: albertium/CVXPort
 def to_ib_contract(self):
     if self.asset == const.AssetClass.FX:
         return ib.Forex(self.ticker)
     elif self.asset == const.AssetClass.STK:
         return ib.Stock(self.ticker, exchange='SMART', currency='USD')
コード例 #13
0
def branco_strategy1(ib, db, accid):
    try:
        cnt = ibsync.Stock('VXX', 'SMART', 'USD')
        ib.qualifyContracts(cnt)
        pricevxx = ib.reqTickers(cnt)[0].marketPrice()

        chains = ib.reqSecDefOptParams(cnt.symbol, '', cnt.secType, cnt.conId)
        chain = next(c for c in chains if c.tradingClass == cnt.symbol
                     and c.exchange == cf.myprefexchange)

        lexps = []
        for e in chain.expirations:
            lexps.append(int(e))
        desiredexpiration = (date.today() +
                             timedelta(days=15)).strftime('%Y%m%d')
        expiration = min(lexps,
                         key=lambda x: abs(int(x) - int(desiredexpiration)))
        strikes = [
            strike for strike in chain.strikes
            if (pricevxx * 0.9 < strike < pricevxx * 1.1)
        ]

        contracts = [
            ibsync.Option('VXX',
                          expiration,
                          strike,
                          "C",
                          'SMART',
                          tradingClass='VXX') for strike in strikes
        ]
        ib.qualifyContracts(*contracts)
        greeks = [
            ibutil.get_greeks(ib, contract).modelGreeks
            for contract in contracts
        ]
        deltas = [greek.delta for greek in list(filter(None, greeks))]

        ishort = int(
            min(range(len(deltas)), key=lambda i: abs(deltas[i] - 0.7)))
        ilong = int(min(range(len(deltas)),
                        key=lambda i: abs(deltas[i] - 0.3)))

        #combo = ibsync.Contract()
        #combo.symbol = "VXX"
        #combo.secType = "BAG"
        #combo.exchange = "SMART"
        #combo.currency = "USD"

        #leg1 = ibsync.ComboLeg ()
        #leg1.conId = contracts[ishort]
        #leg1.ratio = 1
        #leg1.action = "SELL"
        #leg1.exchange = "SMART"

        #leg2 = ibsync.ComboLeg()
        #leg2.conId = contracts[ilong]
        #leg2.ratio = 1
        #leg2.action = "BUY"
        #leg2.exchange = "SMART"

        #combo.comboLegs = []
        #combo.comboLegs.append(leg1)
        #combo.comboLegs.append(leg2)

        #order = ibsync.order.LimitOrder("BUY", 1, 1, tif="GTC", transmit=False)
        #trade = ib.placeOrder(combo, order)

        combo = ibsync.Contract(symbol='VXX',
                                secType='BAG',
                                exchange='SMART',
                                currency='USD',
                                comboLegs=[
                                    ibsync.ComboLeg(conId=contracts[ishort],
                                                    ratio=1,
                                                    action='SELL',
                                                    exchange='SMART'),
                                    ibsync.ComboLeg(conId=contracts[ilong],
                                                    ratio=1,
                                                    action='BUY',
                                                    exchange='SMART')
                                ])
        trade = tradelimitorder(ib, db, combo, 1, 1, "BRANCO_1")
        order = ibsync.LimitOrder(action='SELL',
                                  totalQuantity=1,
                                  lmtPrice=1,
                                  transmit=False,
                                  account=accid)
        trade = ib.placeOrder(combo, order)
        print(trade)
    except Exception as err:
        # error_handling(err)
        raise
コード例 #14
0
ファイル: market_data.py プロジェクト: braman09/ib_console
 def __init__(self, symbol: str, duration: Duration):
     super().__init__(symbol, duration)
     self.contract = ib.Stock(symbol, exchange='SMART', currency='USD')
コード例 #15
0
def get_real_time_data(steamNum,
                       durationStr,
                       stock_symbol_list,
                       host="127.0.0.1",
                       port=7496,
                       clientId=1,
                       is_insert=True):
    """
    https://interactivebrokers.github.io/tws-api/classIBApi_1_1EClient.html#aad87a15294377608e59aec1d87420594
    :param steamNum:
    :param durationStr: the amount of time for which the data needs to be retrieved:
                        " S (seconds) - " D (days)
                        " W (weeks) - " M (months)
                        " Y (years)
    :param host:
    :param port:
    :param clientId:
    :return:
    """
    ib = ibsy.IB()
    with ib.connect(host, port, clientId=clientId):
        start_time = time.time()
        for counter in range(steamNum):
            for i in stock_symbol_list:
                print("Getting " + i + " real time data...")
                contract = ibsy.Stock(i,
                                      'SMART',
                                      'USD',
                                      primaryExchange='NASDAQ')
                # bars = ib.reqHistoricalData(contract, endDateTime='', durationStr=durationStr,
                #                             barSizeSetting='1 min', whatToShow='MIDPOINT', useRTH=True)
                bars = ib.reqHistoricalData(contract,
                                            endDateTime='',
                                            durationStr=durationStr,
                                            barSizeSetting='1 min',
                                            whatToShow='TRADES',
                                            useRTH=True)

                # convert to pandas dataframe:
                df = ibsy.util.df(bars)

                if is_insert:
                    query = "INSERT IGNORE INTO IB_TODAY_" + i + " VALUES (%s, '" + i + "', %s, %s, %s, %s, %s, %s);"
                    for index, row in df.iterrows():
                        insert_data = (str(row.date.strftime("%Y%m%d")),
                                       str(row.date.strftime("%H:%M:%S")),
                                       str(row.open), str(row.high),
                                       str(row.low), str(row.close),
                                       str(row.volume))
                        try:
                            mydb = DBConnection().db_mysql_connector()
                            mycursor = mydb.cursor()
                            mycursor.execute(query, insert_data)
                            mydb.commit()
                        except Exception as e:
                            print(e)
                            return None
                        finally:
                            mycursor.close()
                            mydb.close()
                else:
                    print(df)
                    print(bars)
            print("End of getting real time data...")
        end_time = time.time()
        sleep_time = time.sleep(max(0, 60 - (end_time - start_time)))
        print("Sleep time: ", sleep_time)
        ib.disconnect()
        ib.waitOnUpdate(timeout=0.1)
コード例 #16
0
ファイル: ib_insync_XL.py プロジェクト: rmalh/ib_insync_XL
def placeOrders():
    wb = xw.Book.caller()
    callingWorksheet = wb.sheets.active.name

    # Get the Excel cell address where "Positions to Close" table begins
    cellAddress = wb.sheets(callingWorksheet).tables[
        callingWorksheet + 'OrderListTable'].data_body_range(1, 1).address

    # Pick up the "Positions to Close"
    ordersFromXL = wb.sheets(callingWorksheet).tables[
        callingWorksheet +
        'OrderListTable'].data_body_range.options(ndim=2).value

    # If the first cell of the "Positions to Close" is empty, raise error
    if ordersFromXL[0][0] == None or ordersFromXL[0][0].strip() == "":
        raise ValueError("No Orders to Submit")

    # Start a new IB connection
    ib = ibi.IB()
    ib.connect('127.0.0.1', getIbConnectionPort(callingWorksheet), clientId=4)

    # Place orders one at a time
    for order in ordersFromXL:
        # Create the entryOrder object
        if order[2].upper() == "LMT":
            entryOrder = ibi.LimitOrder(
                order[1],
                abs(int(order[6])),
                order[5],
                account=getSheetNameDict().get(callingWorksheet))
        elif order[2].upper() == "MKT":
            entryOrder = ibi.MarketOrder(
                order[1],
                abs(int(order[6])),
                account=getSheetNameDict().get(callingWorksheet))
        else:
            raise ValueError("Incorrect Order Type in " + order[0])

        # Create the contract object
        if order[7].upper() == "STK":
            contract = ibi.Stock(order[8],
                                 'SMART',
                                 'USD',
                                 primaryExchange='NYSE')
        elif order[7].upper() == "OPT":
            contract = ibi.Option(order[8],
                                  "20" + order[9].strftime("%y%m%d"),
                                  order[10],
                                  order[11],
                                  'SMART',
                                  multiplier=100,
                                  currency='USD')
            ib.qualifyContracts(contract)
        else:
            raise ValueError("Incorrect instrument type")

        ib.qualifyContracts(contract)
        trade = ib.placeOrder(contract, entryOrder)
        assert trade in ib.trades()

    # Disconnect from IB after placing the orders
    ib.disconnect()
コード例 #17
0
def _stockContract(stock: Stock) -> IB.Contract:
    return IB.Stock(
        symbol=stock.symbol,
        exchange=f"SMART:{stock.exchange}" if stock.exchange else "SMART",
        currency=stock.currency.name,
    )