Beispiel #1
0
def main():
    SetupLogger()
    logging.info("now is %s", datetime.datetime.now())
    openPosition = getOpenPosition()
    print(openPosition)
    app = TestApp(ib_api_include.ip, ib_api_include.port,
                  ib_api_include.clientId)
    time.sleep(ib_api_include.sleeptime_trading)
    summary = DataFrame(portfolio,
                        columns=[
                            'symbol', 'secType', 'exchange', 'position',
                            'marketPrice', 'marketValue', 'averageCost',
                            'unrealizedPNL', 'realizedPNL', 'accountName'
                        ])
    reqId = 1000
    #watchlist_stock_treshold = pd.read_excel('my_ib_threshold.xlsx', sheet_name = 'watchlist_stock_treshold')
    #watchlist_stock_treshold = DataFrame(watchlist_stock_treshold)
    for i in range(0, len(openPosition)):
        record = openPosition.iloc[i]
        ibcontract = IBcontract()
        ibcontract.secType = record.AssetClass
        ibcontract.symbol = record.UnderlyingSymbol
        ibcontract.exchange = "SMART"
        ibcontract.currency = record.CurrencyPrimary
        ibcontract.lastTradeDateOrContractMonth = record.Expiry
        ibcontract.strike = record.Strike
        ibcontract.multiplier = record.Multiplier
        ibcontract.right = record["Put/Call"]
        app.reqMktData(reqId, ibcontract)

        ibcontract = IBcontract()
        ibcontract.symbol = "MU"
        ibcontract.exchange = "SMART"
        ibcontract.secType = "STK"
        app.reqMktNews(reqId, ibcontract)
        time.sleep(30)
        print(
            DataFrame(marketdataPrice,
                      columns=[
                          "reqId", "tickType", "tickPrice",
                          "CanAutoExecuteOrNot"
                      ]))
        print(
            DataFrame(marketdataSize,
                      columns=["reqId", "tickType", "tickSize"]))
        reqId += 1

    app.disconnect()
Beispiel #2
0
 def getdata(self):
     app = TestApp("0.0.0.0", 4001, 10)
     for com in Configuration().GetData()['CompanyList']:
         ibcontract = IBcontract()
         ibcontract.secType = "STK"
         ibcontract.lastTradeDateOrContractMonth = "201809"
         ibcontract.symbol = com
         ibcontract.exchange = "SMART"
         resolved_ibcontract = app.resolve_ib_contract(ibcontract)
         dataset1 = {
             0: ['20190502  13:30:00', '20190502  16:00:00'],
             1: [209.95, 208.65],
             2: [212.65, 210.29],
             3: [208.13, 208.41],
             4: [208.63, 209.17],
             5: [149612, 100915]
         }
         durationstr = "3600 S"
         # historic_data = app.get_IB_historical_data(resolved_ibcontract, durationstr, bar)
         df = pd.DataFrame(dataset1)
         df.rename(columns={
             0: "date",
             1: "open",
             2: "high",
             3: "low",
             4: "close",
             5: "volume"
         },
                   inplace=True)
         for bar in barSize:
             dataset = self.strategy(df)
             print(com)
             print(bar)
             # MongoStore().Feed_IntraDay(com, bar, dataset)
             print(df)
Beispiel #3
0
    def create_contract(self,
                        symbol,
                        secType=None,
                        exchange=None,
                        primary_exchange=None,
                        currency=None,
                        lastTradeDate=None):
        """
        Returns List with Contract. If multiple contracts are possible, a list with all contracts is returned
        :param secType:
        :param lastTradeDate:
        :param symbol:
        :param exchange:
        :return:
        """
        ibcontract = IBcontract()
        ibcontract.symbol = symbol
        if secType is not None:
            ibcontract.secType = secType
        if currency is not None:
            ibcontract.currency = currency
        if exchange is not None:
            ibcontract.exchange = exchange
        if primary_exchange is not None:
            ibcontract.primaryExchange = primary_exchange
        if lastTradeDate is not None:
            ibcontract.lastTradeDateOrContractMonth = lastTradeDate
        resolved_contract = self.resolve_ib_contract(ibcontract)

        return resolved_contract
Beispiel #4
0
def index_contract(symbol, exg='CBOE', currency='USD'):
    C = IBcontract()
    C.symbol = symbol
    C.secType = 'IND'
    C.currency = currency
    C.exchange = exg
    return C
Beispiel #5
0
def ib_futures_instrument(futures_instrument_object):
    """
    Get an IB contract which is NOT specific to a contract date
    Used for getting expiry chains

    :param futures_instrument_object: instrument with .metadata suitable for IB
    :return: IBcontract
    """

    meta_data = futures_instrument_object.meta_data

    ibcontract = IBcontract()
    ibcontract.secType = "FUT"
    ibcontract.symbol = meta_data['symbol']
    ibcontract.exchange = meta_data['exchange']
    if meta_data['ibMultiplier'] is NOT_REQUIRED:
        pass
    else:
        ibcontract.multiplier = int(meta_data['ibMultiplier'])
    if meta_data['currency'] is NOT_REQUIRED:
        pass
    else:
        ibcontract.currency = meta_data['currency']

    return ibcontract
Beispiel #6
0
def get_metal_data(symbol="XAUUSD",
                   duration="20 D",
                   period="30 mins",
                   is_simulated=False):

    config = config_loader.load()
    ip = config.get("ib-gateway", "ip")
    #ip = "127.0.0.1"

    if (is_simulated):
        app = TestApp(ip, 4002, ClientID.HIST_METAL.value)
    else:
        app = TestApp(ip, 4001, ClientID.HIST_METAL.value)

    ibcontract = IBcontract()
    #ibcontract.lastTradeDateOrContractMonth="201803"
    ibcontract.secType = "CMDTY"
    ibcontract.symbol = symbol
    ibcontract.exchange = "SMART"

    resolved_ibcontract = app.resolve_ib_contract(ibcontract)

    historic_data = app.get_IB_historical_data(resolved_ibcontract, duration,
                                               period)
    #print(historic_data)

    #out_tup = resample.filter_data(historic_data, period)
    #historic_data = out_tup

    try:
        app.disconnect()
    except:
        print("Disconnect with errors (no harm)!")

    return historic_data
Beispiel #7
0
def future_contract(symbol, exchange='NYMEX'):
    C = IBcontract()
    C.secType = 'FUT'
    C.exchange = exchange
    C.currency = 'USD'
    C.localSymbol = symbol
    return C
Beispiel #8
0
def stock_contract(symbol, exchange='SMART', currency='USD'):
    C = IBcontract()
    C.symbol = symbol
    C.secType = 'STK'
    C.currency = currency
    C.exchange = exchange
    return C
Beispiel #9
0
def data_feed():
    app = TestApp("0.0.0.0", 4001, 9)
    for com in Configuration().GetData()['CompanyList']:
        ibcontract = IBcontract()
        ibcontract.secType = "STK"
        ibcontract.lastTradeDateOrContractMonth = "201809"
        ibcontract.symbol = com
        ibcontract.exchange = "SMART"
        resolved_ibcontract = app.resolve_ib_contract(ibcontract)
        durationstr = "1 D"
        for bar in barSize:
            historic_data = app.get_IB_historical_data(resolved_ibcontract,
                                                       durationstr, bar)
            signal = 1
            dataset = pd.DataFrame(historic_data)
            dataset['signal'] = signal
            for index, row in dataset.iterrows():
                if dataset['open'][index] > dataset['close'][index]:
                    signal = 1
                else:
                    signal = 0
                print(signal)
                dataset['signal'][index] = signal
                print(com)
            print(bar)
            Feed_IntraDay(com, bar, dataset)
            print(dataset)
Beispiel #10
0
def forex_contract(symbol):
    C = IBcontract()
    C.symbol = symbol.split('.')[0]
    C.secType = 'CASH'
    C.exchange = 'IDEALPRO'
    C.currency = symbol.split('.')[-1]
    return C
Beispiel #11
0
 def buildContract(self, symbol: str, secType: str, exchange: str,
                   currency: str):
     contract = IBcontract()
     contract.symbol = symbol
     contract.secType = secType
     contract.exchange = exchange
     contract.currency = currency
     return self._client.resolveContract(contract)
Beispiel #12
0
 def testCreateEquityContract(self):
     ibContract = IBcontract()
     ibContract.secType = "STK"
     ibContract.symbol = "AMC"
     ibContract.currency = "USD"
     ibContract.exchange = "SMART"
     ibContract.primaryExchange = "NYSE"
     return (ibContract)
Beispiel #13
0
def cibcontract(symbol):
    ibcontract = IBcontract()
    ibcontract.secType = "STK"
    #ibcontract.lastTradeDateOrContractMonth="201809"
    ibcontract.symbol=symbol
    ibcontract.currency = "USD"
    ibcontract.exchange="ISLAND"
    return ibcontract
Beispiel #14
0
    def create_contract(self, symbol, currency):

        ibcontract = IBcontract()
        ibcontract.symbol = symbol
        ibcontract.secType = "CASH"
        ibcontract.currency = currency
        ibcontract.exchange = "IDEALPRO"

        return ibcontract
Beispiel #15
0
 def testCreateContract(self):
     # functional on TWS 971
     ibContract = IBcontract()
     ibContract.secType = "CONTFUT"
     #ibContract.secType = "FUT"
     #ibContract.lastTradeDateOrContractMonth="201806"
     ibContract.symbol = "ES"
     ibContract.exchange = "GLOBEX"
     ibContract.currency = "USD"
     return (ibContract)
Beispiel #16
0
    def ib_spotfx_contract(self, ccy1, ccy2="USD", log=None):
        ibcontract = IBcontract()
        ibcontract.symbol = ccy1
        ibcontract.secType = 'CASH'
        ibcontract.exchange = 'IDEALPRO'
        ibcontract.currency = ccy2

        ibcontract = self.ib_resolve_unique_contract(ibcontract)

        return ibcontract
Beispiel #17
0
def create_contract(symbol, secType, currency, exchange, expiry):

    contract = IBcontract()
    contract.symbol = symbol
    contract.secType = secType
    contract.currency = currency
    contract.exchange = exchange
    if expiry is not None:
        contract.lastTradeDateOrContractMonth = expiry

    return contract
Beispiel #18
0
    def defineContract(self, symbol, secType, exchange, currency,
                       primaryExchange):

        contract = IBcontract()
        contract.symbol = symbol
        contract.secType = secType
        contract.exchange = exchange
        contract.currency = currency
        contract.primaryExchange = primaryExchange

        return contract
Beispiel #19
0
def main():

    # app = TestApp1("127.0.0.1", 4001, 1)
    app = TestApp1("127.0.0.1", 7497, 17)

    ## lets get prices for this
    ibcontract = IBcontract()
    # ibcontract.secType = "FUT"
    # ibcontract.lastTradeDateOrContractMonth="201812"
    # ibcontract.symbol="GE"
    # ibcontract.exchange="GLOBEX"

    ibcontract.symbol = 'EUR'
    ibcontract.secType = "CASH"
    ibcontract.exchange = "IDEALPRO"
    ibcontract.currency = "USD"

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

    tickerid = app.start_getting_IB_market_data(resolved_ibcontract)

    time.sleep(5)

    ## 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()
    print(market_data1_as_df)

    time.sleep(5)

    ## stops the stream and returns all the data we've got so far
    market_data2 = app.stop_getting_IB_market_data(tickerid)

    ## glue the data together
    market_data2_as_df = market_data2.as_pdDataFrame()
    all_market_data_as_df = pd.concat([market_data1_as_df, market_data2_as_df])

    ## show some quotes
    some_quotes = all_market_data_as_df.resample("1S").last()[[
        "bid_size", "bid_price", "ask_price", "ask_size"
    ]]
    print(some_quotes.head(5))

    ## show some trades
    some_trades = all_market_data_as_df.resample("10L").last()[[
        "last_trade_price", "last_trade_size"
    ]]
    print(some_trades.head(5))

    app.disconnect()
Beispiel #20
0
def streaming():
    app = TestApp("0.0.0.0", 4001, 9)
    contract = IBcontract()
    contract.symbol = 'AAPL'
    contract.secType = "STK"
    contract.exchange = "SMART"
    contract.currency = "USD"
    contract.primaryExchange = "NASDAQ"

    app.reqMarketDataType(4)
    req = app.reqMktData(1, contract, "", False, False, [])
    print(req)
def update(config, symbol):

    conn_cred = config['conn_cred']

    app = TestApp("127.0.0.1", 7497, 1)
    ibcontract = IBcontract()
    ibcontract.secType = "STK"
    # ibcontract.lastTradeDateOrContractMonth="202011"
    ibcontract.symbol = symbol
    ibcontract.exchange = "SMART"
    ibcontract.currency = "USD"
    ibcontract.primaryExchange = "NASDAQ"
    resolved_ibcontract = app.resolve_ib_contract(ibcontract)
    # print(resolved_ibcontract)
    historic_data = app.get_IB_historical_data(resolved_ibcontract,
                                               durationStr="1 W",
                                               barSizeSetting="5 secs")
    print('pulled historical data. converting data to something mysql expects')
    df = pd.DataFrame(
        historic_data,
        columns=['datetime', 'open', 'high', 'low', 'close', 'volume'])
    df['symbol'] = symbol
    df['datetime'] = pd.to_datetime(df['datetime'], format='%Y%m%d  %H:%M:%S')

    df['epoch'] = (df['datetime'] -
                   datetime(1970, 1, 1)).dt.total_seconds() + (480 * 60)
    list_vals = df[[
        'symbol', 'epoch', 'open', 'high', 'low', 'close', 'volume'
    ]].values.tolist()
    # list_vals = (tuple(i) for i in list_vals) # for executemany()

    print('inserting to sql database')
    ## robust one-by-one insertion
    for i in range(len(list_vals)):
        query = "INSERT INTO {dbname}.bar_data (symbol, epoch,\
					open, high,low, close, volume\
					) VALUES ({csv})".format(dbname=conn_cred['dbname'],
                              csv=','.join(
                                  map(lambda x: "'" + str(x) + "'",
                                      list_vals[i])))
        run_query(conn_cred, query)
    ## executemany (supposed to be a gajillion times faster)
    ## dunno how to make this work tho
    # query = "INSERT INTO {dbname}.bar_data (symbol, epoch,\
    #  				open, high,low, close, volume\
    #  				) VALUES (%s)".format(dbname=conn_cred['dbname'],
    #  												symbol=symbol)
    # dbconn, cursor = mysql_conn(conn_cred['dbname'])
    # cursor.executemany(query, list_vals)
    # db_conn_close()
    print('done updating')
    quit()
Beispiel #22
0
def data_feed():
    app = TestApp("0.0.0.0", 4001, 10)
    for com in Configuration().GetData()['CompanyList']:
        ibcontract = IBcontract()
        ibcontract.secType = "STK"
        ibcontract.lastTradeDateOrContractMonth="201809"
        ibcontract.symbol = com
        ibcontract.exchange = "SMART"
        resolved_ibcontract = app.resolve_ib_contract(ibcontract)
        bar='1 sec'
        durationstr = "120 sec"
        historic_data = app.get_IB_historical_data(resolved_ibcontract,durationstr,bar)
        print(com)
        print(bar)
        Feed_IntraDay(com,bar,historic_data)
        print(historic_data)0
Beispiel #23
0
def generate_fundamentals():
    tws = TestApp("127.0.0.1", 7496, 1)

    ibcontract = IBcontract()
    ibcontract.secType = "STK"
    ibcontract.symbol="FB"
    ibcontract.exchange="SMART"
    ibcontract.currency='USD'

    report_type = ['ReportsFinSummary', 'ReportsFinStatements', 'ReportRatios', 'ReportSnapshot', 'RESC']
    tws.reqFundamentalData(1, ibcontract, report_type[3], [])
    #tws.cancelFundamentalData(1)
    try:
        tws.disconnect()
    except:
        pass
    print('done')
    return
Beispiel #24
0
def get_historic_data():
    app = TestApp("127.0.0.1", 7496, 1)

    ibcontract = IBcontract()
    ibcontract.secType = "STK"
    #ibcontract.lastTradeDateOrContractMonth="201809"
    ibcontract.symbol="AAPL"
    ibcontract.exchange="SMART"

    resolved_ibcontract=app.resolve_ib_contract(ibcontract)

    historic_data = app.get_IB_historical_data(resolved_ibcontract)
    df = pd.DataFrame(historic_data)

    print(df.head())
    print(df.tail())

    app.disconnect()
    def get_stock_contract(self, ticker='SNAP', reqId=DEFAULT_HISTORIC_DATA_ID):
        """
        gets resolved IB contract for stocks

        assumes ISLAND exchange for now (NASDAQ and maybe others?)
        """
        # available sec types: https://interactivebrokers.github.io/tws-api/classIBApi_1_1Contract.html#a4f83111c0ea37a19fe1dae98e3b67456
        ibcontract = IBcontract()
        ibcontract.secType = 'STK'
        # get todays date, format as YYYYMMDD -- need to check this is correct
        # today = datetime.datetime.today().strftime('%Y%m%d')
        # ibcontract.lastTradeDateOrContractMonth = '20180711'#today
        ibcontract.symbol = ticker
        ibcontract.exchange = 'ISLAND'

        resolved_ibcontract, contract_details = self.resolve_ib_contract(ibcontract=ibcontract, reqId=reqId)

        return resolved_ibcontract, contract_details
Beispiel #26
0
def get_fx_data(symbol,
                currency,
                duration="2 M",
                period="4 hours",
                is_simulated=False):

    config = config_loader.load()

    ip = config.get("ib-gateway", "ip")
    #ip = "127.0.0.1"

    if (is_simulated):
        app = TestApp(ip, 4002, ClientID.HIST_FX.value)
    else:
        app = TestApp(ip, 4001, ClientID.HIST_FX.value)

    ibcontract = IBcontract()
    #ibcontract.lastTradeDateOrContractMonth="201809"
    #ibcontract.secType = "FUT"
    #ibcontract.symbol="GE"
    #ibcontract.exchange="GLOBEX"
    ibcontract.symbol = symbol
    ibcontract.secType = "CASH"
    ibcontract.currency = currency
    ibcontract.exchange = "IDEALPRO"

    resolved_ibcontract = app.resolve_ib_contract(ibcontract)

    historic_data = app.get_IB_historical_data(resolved_ibcontract, duration,
                                               period)
    #print(historic_data)

    out_tup = resample.filter_data("FX", historic_data, period)
    historic_data = out_tup

    try:
        app.disconnect()
    except:
        print("Disconnect with errors (no harm)!")

    return historic_data
Beispiel #27
0
 def get_IB_historical_close(self, historic_close,
                             security_list,
                             endDateTime=datetime.datetime.today(),
                             durationStr="1 Y",
                             barSizeSetting="1 day",
                             whatToShow="Trades",
                             useRTH=0,
                             formatDate=1,
                             KeepUpToDate=False,
                             tickerid=DEFAULT_HISTORIC_DATA_ID
                             ):
     for index, security in security_list.iterrows():
         ibcontract = IBcontract()
         ibcontract.secType = security.secType
         ibcontract.lastTradeDateOrContractMonth = security.lastTradeDateOrContractMonth
         ibcontract.symbol = security.symbol
         ibcontract.exchange = security.exchange
         ibcontract.currency = security.currency
 
         resolved_ibcontract = IBClient.resolve_ib_contract(self,ibcontract)
         historical_data = IBClient.get_IB_historical_data(self,
                                                         resolved_ibcontract,
                                                         endDateTime,
                                                         durationStr,
                                                         barSizeSetting,
                                                         whatToShow,
                                                         useRTH,
                                                         formatDate,
                                                         KeepUpToDate,
                                                         tickerid)
        
         historical_df = pd.DataFrame(historical_data,columns = ["date","open","high","low","close","volume"])
         historical_df.head()
         historical_df = historical_df[["date", "close"]]
         historical_df.rename(columns={'close':security.symbol}, inplace=True)
         
         historical_df["date"] = pd.to_datetime(historical_df['date'])
         historical_df=historical_df.set_index('date')
         #historical_df.sort_index(inplace=True)
         historic_close = historical_df.combine_first(historic_close)
     return historic_close    
Beispiel #28
0
def get_hkfe_data(contractMonth,
                  symbol="MHI",
                  duration="20 D",
                  period="30 mins",
                  is_simulated=False):

    config = config_loader.load()

    ip = config.get("ib-gateway", "ip")
    #ip = "127.0.0.1"

    if (is_simulated):
        app = TestApp(ip, 4002, ClientID.HIST_HKFE.value)
    else:
        app = TestApp(ip, 4001, ClientID.HIST_HKFE.value)

    ibcontract = IBcontract()
    #YYYYMM
    ibcontract.lastTradeDateOrContractMonth = contractMonth
    ibcontract.secType = "FUT"
    ibcontract.symbol = symbol
    ibcontract.exchange = "HKFE"

    resolved_ibcontract = app.resolve_ib_contract(ibcontract)

    historic_data = app.get_IB_historical_data(resolved_ibcontract, duration,
                                               period, "TRADES")
    #print(historic_data)

    out_tup = resample.filter_data("HKFE", historic_data, period)
    historic_data = out_tup
    #print(historic_data)
    try:
        app.disconnect()
    except:
        print("Disconnect with errors (no harm)!")

    return historic_data
Beispiel #29
0
    def __init__(self, ipaddress, portid, clientid):
        TestWrapper.__init__(self)
        TestClient.__init__(self, wrapper=self)

        self.connect(ipaddress, portid, clientid)

        thread = Thread(target=self.run)
        thread.start()

        setattr(self, "_thread", thread)

        self.init_error()


#if __name__ == '__main__':

app = TestApp("127.0.0.1", 4001, 1)

ibcontract = IBcontract()
ibcontract.secType = "FUT"
ibcontract.lastTradeDateOrContractMonth = "201809"
ibcontract.symbol = "GE"
ibcontract.exchange = "GLOBEX"

resolved_ibcontract = app.resolve_ib_contract(ibcontract)

historic_data = app.get_IB_historical_data(resolved_ibcontract)

print(historic_data)

app.disconnect()
Beispiel #30
0
    def buy6030(self, sym, direction="Bull", exp="", budget=500):

        if direction == "Bull":
            right = "Put"
        else:
            right = "Call"

        if exp == "":
            d = datetime.date.today()
            d += datetime.timedelta(10)
            while d.weekday() != 4:
                d += datetime.timedelta(1)
            exp = d.strftime("%Y%m%d")

        contract1 = IBcontract()
        contract1.secType = "STK"
        contract1.symbol = sym
        contract1.exchange = "ISLAND"

        contract2 = IBcontract()
        contract2.secType = "OPT"
        contract2.symbol = sym
        contract2.exchange = "SMART"
        contract2.lastTradeDateOrContractMonth = exp
        contract2.right = right
        contract2.multiplier = 100

        self.reqMktData(1032, contract1, "", False, False, [])
        contract1.exchange = "SMART"
        self.reqMktData(1033, contract1, "", False, False, [])
        d = self.reqContractDetails(1202, contract2)
        time.sleep(1)
        #print(d)

        print("=" * 40)
        print()
        print("{} Price Details:".format(sym))
        lastPrice = None
        try:
            for k in list(self._my_price_details[1032].queue):
                t = dict(k)
                if t['tickType'] == 4:
                    lastPrice = t['price']
                if t['tickType'] == 9 and lastPrice == None:
                    lastPrice = t['price']
                print(t)
        except:
            try:
                for k in list(self._my_price_details[1033].queue):
                    t = dict(k)
                    if t['tickType'] == 4:
                        lastPrice = t['price']
                    if t['tickType'] == 9 and lastPrice == None:
                        lastPrice = t['price']
                    print(t)
            except:
                print("No stock prices available for {} at this time.".format(
                    sym))
                return

        if lastPrice == None:
            print("No stock prices available for {} at this time.".format(sym))
            return

        # print()
        # print("{0} Last Price: ${1:4.2f}".format(sym, lastPrice))
        # print()

        rID = 1100
        df = DataFrame()
        print("Contract Details:")
        try:
            cDetails = self._my_contract_details[1202].queue
        except:
            print("Contract details for {} are not available at this time.".
                  format(sym))
            return
        for k in list(cDetails):
            t = list(str(k).split(','))
            # print(t)
            try:
                if lastPrice * 1.10 > float(t[4]) > lastPrice * 0.90:
                    df[rID] = t
                    contract3 = IBcontract()
                    contract3.secType = "OPT"
                    contract3.symbol = sym
                    contract3.exchange = "CBOE2"
                    contract3.lastTradeDateOrContractMonth = exp
                    contract3.strike = float(t[4])
                    contract3.right = right
                    contract3.multiplier = 100
                    self.reqMarketDataType(2)
                    self.reqMktData(rID, contract3, "", False, False, [])
                    rID = rID + 1
            except:
                pass
        if rID == 1100:
            print(
                "No option prices available for {} at this time.".format(sym))
            return

        df = df.transpose()
        # print(df)
        # print("Getting option details for {0:2d} strikes:".format(len(df)))
        # print()

        time.sleep(1)

        df['undPrice'] = [""] * len(df)
        df['optPrice'] = [""] * len(df)
        df['delta'] = [""] * len(df)
        df['strike'] = [""] * len(df)
        df['delta60'] = [""] * len(df)
        for s in df.index:
            #self.cancelMktData(s)
            try:
                for k in list(self._my_option_data[s].queue):
                    t = dict(k)
                    #print(s,t)
                    if t['delta']:
                        try:
                            df.loc[s, 'conId'] = int(df.loc[s, 0])
                            df.loc[s, 'strike'] = float(df.loc[s, 4])
                            df.loc[s, 'undPrice'] = t['undPrice']
                            df.loc[s, 'optPrice'] = t['optPrice']
                            df.loc[s, 'delta'] = abs(t['delta'])
                            df.loc[s, 'delta60'] = abs(abs(t['delta']) - 0.60)
                        except:
                            pass
            except:
                print("No option prices available for {} at this time.".format(
                    sym))
                return

        # print(df.loc[:,['conId',3,'strike','undPrice','delta','delta60']].sort_values(['strike']))
        # print()
        d60 = df.loc[df['delta60'] == df['delta60'].min()].index.min()
        # print("Sell a {} with the {:7.2f} strike".format(right,df.strike[d60]))

        t30 = (df.delta[d60] - 0.3)
        p = df.loc[df.delta > t30].delta.min()
        d30plus = df.loc[df.delta == p].index.min()
        m = df.loc[df.delta < t30].delta.max()
        d30min = df.loc[df.delta == m].index.min()
        if abs(df.delta[d30plus] - t30) > abs(df.delta[d30min] - t30):
            d30 = d30min
        else:
            d30 = d30plus

        # Order variables
        #####
        cdelta = df.delta[d60] - df.delta[d30]
        lim = abs(df.strike[d60] - df.strike[d30]) * 0.35
        try:
            cOptPrice = df.optPrice[d60] - df.optPrice[d30]
            if abs(cOptPrice) < abs(lim * 0.95):
                print("Spread Combo price for {} is too low.".format(sym))
                return True
            quantity = int(budget / 100 / cOptPrice)
            if quantity == 0:
                print("Spread Combo for {} is above the budget of ${}".format(
                    sym, budget))
                return True
        except:
            quantity = 1
        takeProfitLimitPrice = lim * 0.
        stopLossPrice = lim * 1.50
        action = "SELL"
        #parentOrderId = 101

        # print("Buy a {} with the  {:7.2f} strike ".format(right,df.strike[d30]))
        # print("Combo delta is {:5.3f}".format(cdelta))
        # print("Combo limit price is ${:7.2f}".format(lim))
        # print("Combo Expiry is {}".format(exp))
        # print()
        print(
            "{} - Price: ${:7.2f} - Sell a {} {:7.2f}/{:7.2f} {} Spread - Limit price: ${:5.2f} - Combo delta: {:5.3f}"
            .format(sym, lastPrice, exp, df.strike[d60], df.strike[d30], right,
                    lim, cdelta))

        #
        #  Send order for the Spread above
        ####

        contract3 = IBcontract()
        contract3.secType = "BAG"
        contract3.symbol = sym
        contract3.exchange = "SMART"
        contract3.currency = "USD"

        leg1 = IBcomboLeg()
        leg1.conId = int(df.conId[d60])  # Sell the delta 60 option
        leg1.ratio = 1
        leg1.action = "SELL" if action == "BUY" else "BUY"
        leg1.exchange = "SMART"

        leg2 = IBcomboLeg()
        leg2.conId = int(
            df.conId[d30])  # Buy the delta 30 option as protection
        leg2.ratio = 1
        leg2.action = "BUY" if action == "BUY" else "SELL"
        leg2.exchange = "SMART"

        contract3.comboLegs = []
        contract3.comboLegs.append(leg1)
        contract3.comboLegs.append(leg2)

        order3 = Order()
        order3.action = action
        order3.orderType = "LMT"
        order3.totalQuantity = quantity
        order3.lmtPrice = lim
        order3.tif = 'DAY'
        order3.transmit = False

        parentOrderId = self.place_new_IB_order(contract3,
                                                order3,
                                                orderid=None)

        takeProfit = Order()
        takeProfit.action = "SELL" if action == "BUY" else "BUY"
        takeProfit.orderType = "LMT"
        takeProfit.totalQuantity = quantity
        takeProfit.lmtPrice = takeProfitLimitPrice
        takeProfit.parentId = parentOrderId
        takeProfit.tif = 'GTC'
        takeProfit.transmit = False
        self.place_new_IB_order(contract3, takeProfit, orderid=None)

        stopLoss = Order()
        stopLoss.action = "SELL" if action == "BUY" else "BUY"
        stopLoss.orderType = "STP"
        # Stop trigger price
        stopLoss.auxPrice = stopLossPrice
        stopLoss.totalQuantity = quantity
        stopLoss.parentId = parentOrderId
        stopLoss.tif = 'GTC'
        # In this case, the low side order will be the last child being sent. Therefore, it needs to set this attribute to True
        # to activate all its predecessors
        stopLoss.transmit = True
        self.place_new_IB_order(contract3, stopLoss, orderid=None)
        time.sleep(1)
        return True