def generate_ib_contract(symbol: str, exchange: Exchange) -> Optional[Contract]: """""" try: fields = symbol.split(JOIN_SYMBOL) ib_contract = Contract() ib_contract.exchange = EXCHANGE_VT2IB[exchange] ib_contract.secType = fields[-1] ib_contract.currency = fields[-2] ib_contract.symbol = fields[0] if ib_contract.secType in ["FUT", "OPT", "FOP"]: ib_contract.lastTradeDateOrContractMonth = fields[1] if ib_contract.secType == "FUT": if len(fields) == 5: ib_contract.multiplier = int(fields[2]) if ib_contract.secType in ["OPT", "FOP"]: ib_contract.right = fields[2] ib_contract.strike = float(fields[3]) ib_contract.multiplier = int(fields[4]) except IndexError: ib_contract = None return ib_contract
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
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 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)
def make_contract(symbol, secType, exchange, primaryExchange, currency, lastTradeDateOrContractMonth=None, strike=None, right=None, multiplier=None, tradingClass=None): contract = Contract() contract.symbol = symbol contract.secType = secType contract.exchange = exchange contract.primaryExchange = primaryExchange contract.currency = currency if lastTradeDateOrContractMonth is not None: contract.lastTradeDateOrContractMonth = lastTradeDateOrContractMonth if strike is not None: contract.strike = strike if right is not None: contract.right = strike if multiplier is not None: contract.multiplier = multiplier if tradingClass is not None: contract.tradingClass = tradingClass return contract
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
def get_instrument(inst: str, tbl: str) -> (Contract, dict): """ Retrieves an instrument metadata from Dynamo DB :param inst: symbol string :param tbl: Dynamo DB name :return: """ db = boto3.resource( 'dynamodb', region_name='us-east-1', endpoint_url="https://dynamodb.us-east-1.amazonaws.com") table = db.Table(tbl) response = table.get_item(Key={"symbol": inst}) r = response["Item"] c = Contract() c.symbol = r["symbol"] c.secType = r["type"] c.currency = r["currency"] c.exchange = r["exchange"] c.tradingClass = r["class"] c.multiplier = r["mult"] return { "cont": c, "add_d": { "mon_step": r["mon_step"], "strike_step": r["strike_step"] } }
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)
def FutureWithMultiplier(): contract = Contract() contract.symbol = "DAX" contract.secType = "FUT" contract.exchange = "DTB" contract.currency = "EUR" contract.lastTradeDateOrContractMonth = "201609" contract.multiplier = "5" return contract
def createOptionContract(self, symbol, currency, exchange): contract = Contract() contract.symbol = symbol contract.secType = "OPT" contract.exchange = exchange contract.currency = currency contract.lastTradeDateOrContractMonth = "201901" contract.strike = 150 contract.right = "C" contract.multiplier = "100" return contract
def FuturesOnOptions(): contract = Contract() contract.symbol = "SPX" contract.secType = "FOP" contract.exchange = "GLOBEX" contract.currency = "USD" contract.lastTradeDateOrContractMonth = "20180315" contract.strike = 1025 contract.right = "C" contract.multiplier = "250" return contract
def optContract(): contract = Contract() contract.symbol = 'GOOG' contract.secType = 'OPT' contract.exchange = 'SMART' contract.currency = 'USD' contract.lastTradeDateOrContractMonth = '20190823' contract.strike = 1190 contract.right = 'C' contract.multiplier = '100' return contract
def OptionAtBOX(): contract = Contract() contract.symbol = "GOOG" contract.secType = "OPT" contract.exchange = "BOX" contract.currency = "USD" contract.lastTradeDateOrContractMonth = "20170120" contract.strike = 615 contract.right = "C" contract.multiplier = "100" return contract
def OptionAtIse(): contract = Contract() contract.symbol = "BPX" contract.secType = "OPT" contract.currency = "USD" contract.exchange = "ISE" contract.lastTradeDateOrContractMonth = "20160916" contract.right = "C" contract.strike = 65 contract.multiplier = "100" return contract
def contract_bidu_option(self): # ! [optcontract] contract = Contract() contract.symbol = "BIDU" contract.secType = "OPT" contract.exchange = "SMART" contract.currency = "USD" contract.lastTradeDateOrContractMonth = "20190322" contract.strike = 165 contract.right = "PUT" contract.multiplier = "100" # ! [optcontract] return contract
def OptionWithTradingClass(): contract = Contract() contract.symbol = "SPX" contract.secType = "OPT" contract.exchange = "SMART" contract.primaryExchange = "SMART" contract.currency = "USD" contract.lastTradeDateOrContractMonth = "20190219" contract.strike = 2520 contract.right = "C" contract.multiplier = "100" contract.tradingClass = "SPX" return contract
def OptionAtBOX(): #! [optcontract] contract = Contract() contract.symbol = "AMZN" contract.secType = "OPT" contract.exchange = "SMART" contract.currency = "USD" contract.lastTradeDateOrContractMonth = "20190125" contract.strike = 1570 contract.right = "C" contract.multiplier = "100" #! [optcontract] return contract
def getRolledOption(self, r): option = Contract() option.symbol = self.statData.buyWrite["underlyer"]["@tickerSymbol"] option.avPrice = r["sellprice"] option.secType = "OPT" option.exchange = "SMART" option.currency = "USD" option.lastTradeDateOrContractMonth = r['to'] option.strike = r['strike'] option.right = "Call" option.multiplier = "100" return option
def option(self): option = Contract() option.symbol = self.statData.buyWrite["underlyer"]["@tickerSymbol"] option.avPrice = self.statData.inioptprice option.secType = "OPT" option.exchange = "SMART" option.currency = "USD" option.lastTradeDateOrContractMonth = self.statData.expiry option.strike = self.statData.strike option.right = "Call" option.multiplier = "100" return option
def OptionWithTradingClass(): # ! [optcontract_tradingclass] contract = Contract() contract.symbol = "SANT" contract.secType = "OPT" contract.exchange = "MEFFRV" contract.currency = "EUR" contract.lastTradeDateOrContractMonth = "20190621" contract.strike = 7.5 contract.right = "C" contract.multiplier = "100" contract.tradingClass = "SANEU" # ! [optcontract_tradingclass] return contract
def make_contract(symbol: str, sec_type: str, currency: str, exchange: str, expiry: str, strike: str) -> Contract: contract = Contract() contract.symbol = symbol contract.secType = sec_type contract.currency = currency if sec_type == "OPT": contract.lastTradeDateOrContractMonth = expiry contract.strike = strike contract.right = "Call" contract.multiplier = "100" contract.exchange = exchange return contract
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
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()
def createCallOpt(symbol, strike, contractMonth, sec_type="OPT", currency="INR", exchange="NSE"): contract = Contract() contract.symbol = symbol contract.secType = sec_type contract.currency = currency contract.exchange = exchange contract.right = "C" contract.strike = strike contract.multiplier = 1 contract.tradingClass = 'BANKNIFTY' contract.lastTradeDateOrContractMonth = contractMonth return contract
def create_contract(self, symbol, contract_type): if contract_type == "FX": contract = Contract() contract.symbol = contract_dict[symbol][0] #FOAT DEC 17 contract.secType = "CASH" #FUT contract.currency = contract_dict[symbol][1] #EUR contract.exchange = "IDEALPRO" #DTP return contract elif contract_type == 'FUTURE': contract = Contract() contract.symbol = futures_dict[symbol][0] contract.secType = "FUT" contract.currency = futures_dict[symbol][1] contract.exchange = futures_dict[symbol][2] contract.lastTradeDateOrContractMonth = futures_dict[symbol][3] contract.multiplier = futures_dict[symbol][4] return contract
def test_futures_ibcontract_from_ib_contract(self): contract = Contract() contract.symbol = "ES" contract.secType = "FUT" contract.exchange = "GLOBEX" contract.currency = "USD" contract.lastTradeDateOrContractMonth = "20190307" contract.multiplier = "5" ibcontract = IBContract.from_ib_contract(contract) self.assertEqual(ibcontract.symbol, "ES") self.assertEqual(ibcontract.secType, "FUT") self.assertEqual(ibcontract.security_type, SecurityType.FUTURE) self.assertEqual(ibcontract.exchange, "GLOBEX") self.assertEqual(ibcontract.currency, "USD") self.assertEqual(ibcontract.lastTradeDateOrContractMonth, "20190307") self.assertEqual(ibcontract.last_trade_date, datetime(2019, 3, 7)) self.assertEqual(ibcontract.multiplier, "5")
def create_options_contract(symbol, exp, strike, right, exchange='SMART', currency='USD', multiplier='100'): # opt_spy = create_options_contract('SPY', '20210319', '400', 'C') contract = Contract() contract.symbol = symbol contract.lastTradeDateOrContractMonth = exp contract.strike = strike contract.right = right contract.secType = 'OPT' contract.exchange = exchange contract.currency = currency contract.multiplier = multiplier return contract
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)
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
while True: if isinstance(app.nextorderId, int): print('connected') print() break else: print('waiting for connection') time.sleep(1) #Create contract contract = Contract() contract.symbol = 'TSLA' contract.secType = 'OPT' contract.exchange = 'SMART' contract.lastTradeDateOrContractMonth = '20201002' contract.strike = 424 contract.right = 'C' contract.multiplier = '100' #Create order object order = Order() order.action = 'BUY' order.totalQuantity = 1 order.orderType = 'MKT' #Place order app.placeOrder(app.nextorderId, contract, order) time.sleep(3) app.disconnect()