def testCreateEquityContract(self): ibContract = IBcontract() ibContract.secType = "STK" ibContract.symbol = "AMC" ibContract.currency = "USD" ibContract.exchange = "SMART" ibContract.primaryExchange = "NYSE" return (ibContract)
def stock_order(symbol): contract = Contract() contract.symbol = symbol contract.secType = "STK" contract.currency = "USD" contract.exchange = "SMART" contract.primaryExchange = "ISLAND" return contract
def get_contract(self, symdct): ibcontract = Contract() ibcontract.symbol = symdct['symbol'].upper() ibcontract.secType = symdct['sectype'].upper() ibcontract.exchange = symdct['exchange'].upper() ibcontract.currency = symdct['currency'].upper() ibcontract.primaryExchange = symdct['priexg'].upper() return ibcontract
def create_nasdaq_contract(ticker): contract = Contract() contract.symbol = row['ticker'] contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" contract.primaryExchange = "NASDAQ" return contract
def ASX_contract(ticker): contract = Contract() contract.symbol = ticker contract.secType = 'STK' contract.exchange = 'SMART' contract.currency = 'AUD' contract.primaryExchange = 'ASX' return contract
def start(self): contract = Contract() contract.symbol = "TGP" contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" contract.primaryExchange = "NASDAQ" self.reqMarketDataType(4) self.reqMktData(1, contract, '258,456', False, False, [])
def basic_contract(symbol, sec_type, exch, prim_exch, curr): contract = Contract() contract.symbol = symbol contract.secType = sec_type contract.exchange = exch contract.primaryExchange = exch contract.currency = curr return contract
def OptionWithLocalSymbol(): contract = Contract() contract.localSymbol = "C SPX JAN 16 2450" contract.secType = "OPT" contract.exchange = "SMART" contract.primaryExchange = "SMART" contract.currency = "USD" return contract
def AAPLStockContract(): # ! [usstockcfd_conract] contract = Contract() contract.symbol = "AMZN" contract.secType = "STK" contract.currency = "USD" contract.exchange = "SMART" contract.primaryExchange = "SMART" # ! [usstockcfd_conract] return contract
def defineContract(self, symbol, secType, exchange, currency, primaryExchange): contract = Contract() contract.symbol = symbol contract.secType = secType contract.exchange = exchange contract.currency = currency contract.primaryExchange = primaryExchange return contract
def USStockWithPrimaryExch(): contract = Contract() contract.symbol = "MSFT" contract.secType = "STK" contract.currency = "USD" contract.exchange = "SMART" # Specify the Primary Exchange attribute to avoid contract ambiguity # (there is an ambiguity because there is also a MSFT contract with primary exchange = "AEB") contract.primaryExchange = "ISLAND" return contract
def start(self): contract = Contract() contract.symbol = "TGP PRb" contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" contract.primaryExchange = "NASDAQ" self.reqHistoricalData(1, contract, "", "26 W", "1 day", "MIDPOINT", 0, 1, False, [])
def make_contract(symbol, exchange): if symbol.startswith('US.'): symbol = ''.join(symbol[3:]) contract = Contract() contract.symbol = symbol contract.secType = "STK" contract.currency = "USD" contract.exchange = exchange contract.primaryExchange = "ISLAND" 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 main(): app = TestApp() app.connect("127.0.0.1", 4002, 0) # 7497 live # Crete a contract contract = Contract() contract.symbol = "AAPL" contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" contract.primaryExchange = "NASDAQ"
def contract_spx_option(self): contract = Contract() contract.symbol = 'SPX' contract.secType = "OPT" contract.exchange = "SMART" contract.primaryExchange = "SMART" contract.currency = "USD" contract.strike = 2800 contract.lastTradeDateOrContractMonth = "20190329" contract.right = "C" return contract
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 get_contract_object(symbol: str, security_type: "SecurityType") -> Contract: contract = Contract() contract.symbol = symbol contract.secType = security_type.value contract.exchange = "SMART" contract.currency = "USD" from ibkr.models import SecurityType if security_type == SecurityType.STOCK: contract.primaryExchange = "NASDAQ" return contract
def start(self): contract = Contract() contract.symbol = "TGP" contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" contract.primaryExchange = "NASDAQ" wb = Workbook.load_workbook( 'D:\\TWS API\\source\\pythonclient\\ibapi\\Accounting Info TGP.xlsx' ) range = wb['Accounting Info'] wb_1 = Workbook.load_workbook( 'D:\\TWS API\\source\\pythonclient\\ibapi\\StockPrice TGP.xlsx') range_1 = wb_1['stock yield TGP'] wb_2 = Workbook.load_workbook( 'D:\\TWS API\\source\\pythonclient\\ibapi\\Dividend Info TGP.xlsx') range_2 = wb_2['Dividend Info'] wb_3 = Workbook.load_workbook( 'D:\\TWS API\\source\\pythonclient\\ibapi\\StockPrice TGP PRa.xlsx' ) range_3 = wb_3['stock yield TGP PRa'] wb_4 = Workbook.load_workbook( 'D:\\TWS API\\source\\pythonclient\\ibapi\\YTC TGP.xlsx') range_4 = wb_4['YTC TGP'] TGP_Dividend_PRa = float(input('please enter Dividend of TGP PRa')) TGP_Dividend_PRb = float(input('please enter Dividend of TGP PRb')) Outstanding_share = float( input('please enter Outstanding share of PRa')) condition_1 = TGP_Dividend_PRa > TGP_Dividend_PRb condition_2 = float(str(range_4['A1'].value)) > 0.7 condition_3 = float(str(range_3['A1'].value)) < float( str(range_1['A1'].value)) condition_4 = (float(str(range['A1'].value)) - float(str(range_2['B1'].value)) * Outstanding_share) / ( TGP_Dividend_PRa + TGP_Dividend_PRb) > 2.0 if condition_1: if condition_2 and condition_3 and condition_4: order = Order() order.action = "BUY" order.orderType = "LMT" order.totalQuantity = 400 order.lmtPrice = 210 if not (condition_1 and condition_2 and condition_3 and condition_4): print('doesnt meet criteria cant place order') else: self.placeOrder(self.nextOrderId, contract, order)
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()
def main(): app=TestApp() app.connect("127.0.0.1",7497,0) contract= Contract() contract.symbol= "AAPL" contract.secType= "STK" contract.exchange="SMART" contract.currency= "USD" contract.primaryExchange="NASDAQ" app.reqMarketDataType(4) app.reqMktData(1, contract, "",False,False, []) app.run()
def main(): app = TestApp() app.connect("127.0.0.1", 7497, 0) contract = Contract() contract.symbol = "AAPL" contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" contract.primaryExchange = "NASDAQ" app.reqMarketDataType(1) # switch to delayed-frozen data if live is not available app.reqMktData(1, contract, "", False, False, []) app.run()
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 basicContract(symbol, secType='STK', exchange='SMART', currency='USD', primaryExchange='NASDAQ'): # for the most part, the stock of interest share the same basic details, # so just setting a bunch of defaults contract = Contract() contract.symbol = symbol contract.secType = secType contract.exchange = exchange contract.currency = currency contract.primaryExchange = primaryExchange return contract
def start(self): contract = Contract() contract.symbol = self.sec_id contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" contract.primaryExchange = "NASDAQ" order = Order() order.action = self.buy_or_sell order.totalQuantity = self.qty order.orderType = "MKT" self.placeOrder(self.nextOrderId, contract, order)
def ib_stock_api(stocks, action): if action == RUN_API: print(f"*************** START API RUN ****************") global app app = TestApp() app.connect("127.0.0.1", 4004, clientId=0) # app.connect("127.0.0.1", 7497, clientId=17) thread1App = myThread(app, 1, "T1") # define thread for running app thread1App.start( ) # start app.run(] as infitnite loop in separate thread elif action == UPADATE_STOCKS: global contract for c in range(len(stocks)): app.cancelMktData(c) contract = Contract() rStatus = 200 for i in range(len(stocks)): contract.symbol = stocks[i] print(f"*************** UPDATE: {stocks[i]} ****************") contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" contract.primaryExchange = "NASDAQ" app.reqStatus[rStatus] = 'Sent' app.reqMktData(i, contract, "", False, False, []) # app.done = True # this stops app.run() loop return elif action == STOP_API: print(f"***************Stopping app****************") app.stop() # app.disconnect() return else: print('ERROR: Wrong action entered.') return
def main1(): global app1 global var1 global var2 global myList print("Se supone que elimine conexion del objeto anterior de la clase TestApp que es global") myList.remove(myList[0]) myList.remove(myList[0]) if len(myList) == 0: print("Termine todos los contratos") #self.disconnect()#Da error el codigo # app.disconnect() app1.disconnect()##ESTE ESTARIA BIEN ESO CREO # app.cancelMktData(0) # app1.cancelMktData(0) #del app# local variable 'app' referenced before assignment #del app1 #Que pasa si no borro este objeto##NADA EL CODIGO SIGUE CORRIENDO # sys.exit(1) #ME LLEVAN A OTRO SITIO # sys.exit() # quit() # exit(0) exitContratos() #return #ESTE ES EL QUE ME REGRESA A "otroContrato"##SI FUNCIONA PARA EL REGRESO A LA OTRA FUNCION var1 = myList[0] var2 = myList[1] print(myList) print("La lista que se muestra en pantalla ya tiene menos dos elementos") print("Se supone que voy a crear un nuevo contrato, por eso vuelvo a llamar a la clase,Inicio nueva conexion") app1 = TestApp() app1.connect("127.0.0.1", 7497, 0) time.sleep(3) contract = Contract() contract.symbol = var2 #variable 2 contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" contract.primaryExchange = var1 #variable 1 app1.reqMarketDataType(4) app1.reqMktData(0,contract,"",False,False,[]) app1.run() app1.disconnect()##ESTA LINEA SE VE AFECTADA POR EL IF DE == 0 #self.disconnect() # self is not defined print("Termino el objeto de la clase app1")# Pasa por aqui luego de que termino todos los contratos, No deberia
def main(): # Create the client and Connect to TWS API client = TestLimitOrder('127.0.0.1', 7497, 7) time.sleep(3) client.orderId = None # Define a Contract contract = Contract() contract.symbol = 'SBIN' contract.secType = 'STK' contract.exchange = 'SMART' contract.currency = 'INR' contract.primaryExchange = "NSE" # Define the Limit Order for BUY/SELL order = Order() order.action = 'BUY' order.totalQuantity = 42 order.orderType = 'LMT' order.lmtPrice = '10.2' # Place the limit order far off from the actaul market price. For Test #order.transmit = False # when set to false, the order wont actually be executed when the program is run # Request from TWS, the next valid ID for the order client.reqIds(1) time.sleep(3) # Place the order if client.orderId: client.placeOrder(client.orderId, contract, order) time.sleep(3) else: print ('Order ID not received. Terminating Application') sys.exit() # Obtain information about open positions client.reqPositions() time.sleep(3) # Obtain information about Account client.reqAccountSummary(7, 'All', 'AccountType') time.sleep(3) # Cancel Order print ('Cancelling the Order') client.cancelOrder(client.orderId) # Cancel the above order which has been placed # Disconnect from TWS time.sleep(3) client.disconnect()
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 make_contract(self, symbol): """Create a contract for the given symbol. Arguments: symbol (str): Ticker symbol """ contract_info = self.get_contract_details(symbol) contract = Contract() contract.symbol = symbol contract.currency = contract_info['currency'] contract.exchange = contract_info['exchange'] contract.primaryExchange = contract_info['primaryExchange'] contract.secType = contract_info['secType'] contract.secId = contract_info['secId'] return contract