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
def newTrade(self, contractSymbol:str, entryPrice:float, stopPrice:float ): # TEMP contractSymbol="EURUSD" contract = Contract() contract.symbol = "EUR" contract.secType = "CASH" contract.currency = "GBP" contract.exchange = "IDEALPRO" contract.tickSize = 0.00005 contract.lotSize = 20000 # TEMP #if( self.trades[contractSymbol] ) ''' contractDetails = s.getContractDetails( contractSymbol ) contract = Contract() contract.exchange = contractDetails.exchange contract.secType = contractDetails.secType contract.symbol = contractSymbol contract.lastTradeDateOrContractMonth = contractDetails.expiry contract.tickSize = contractDetails.tickSize # Custom field contract.lotSize = contractDetails.lotSize # Custom field ''' diff = abs(entryPrice-stopPrice) qty = self.capital * s.RiskPerTrade / diff t = trade.Trade( self.ib, contract ) t.placeNewTrade( qty, entryPrice, stopPrice ) self.trades[contractSymbol] = t
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
def _fetchFutureMonth(self): contract = Contract() ''' contract.secType = "CONTFUT" #contract.lastTradeDateOrContractMonth="201812" # CONTFUT can be used to get details of contract from which we can get month for order contract.symbol="SBIN" contract.exchange="NSE" ''' contract.secType = "FUT" contract.lastTradeDateOrContractMonth="201805" contract.symbol="SBIN" contract.exchange="NSE" ## resolve the contract self.ib.reqContractDetails(213, contract)
def start(self):#Esta funcion genera un contrato y objeto order print("\n") contract = Contract() contract.symbol = varcSym #"AMZN" contract.secType = "STK" contract.currency = "USD" #In the API side, NASDAQ is always defined as ISLAND in the exchange field contract.exchange = varcMer #"ISLAND" order = Order() order.action = varoOp #"BUY" #"SELL" order.totalQuantity = varoVoSo #100 order.orderType = "LMT" order.lmtPrice = varoMax #347.02 self.placeOrder(self.nextOrderId,contract,order)#places or modifies an order. #id,contract, order
def main(): app = TestApp() app.connect("127.0.0.1", 7497, 0) contract = Contract() contract.symbol = "EUR" contract.secType = "CASH" contract.exchange = "IDEALPRO" #Este contrato no corre si estoy en la sesion de tfm2020le, pero si corre en la sesion "demo TWS" contract.currency = "USD" #yyyymmdd HH:mm:ss ttt #idRequest,contract,EndDay(Se puede especificar el dia que queremos data)",Duration,Bar(size),typeData(BID,ASK,etc),0(trading hours),1(format data), Bool,Attribute #app.reqHistoricalData(1,contract,"20200801 23:59:59 GMT","1 D","1 min","MIDPOINT",0,1,False,[]) app.reqHistoricalData(1,contract,"","1 D","1 min","MIDPOINT",0,1,False,[]) app.run()
def main(): global app app = TestApp() app.connect("127.0.0.1", 7497, 0) print("serverVersion:%s connectionTime:%s" % (app.serverVersion(),app.twsConnectionTime())) global var1 global var2 global myList myList = [] # Lista # var1 = 'NASDAQ' #Con estas variables pude generar los contratos # var2 = 'AAPL' #Faltaria ingresar que los capture desde la lectura y regese al contrato with open('paraLeer.txt','r') as file: # reading each line for line in file: # reading each word #for word in line.split(",",1): #Si hago esplit de 1 me devuelve una lista de 2 elementos for word in line.split(): #Con el separador de espacio por defecto me devuelve lo que necesito # displaying the words print(word) myList.append(word) print("Termine leer todas las lineas") print("Asigno Posicion primer contrato") var1 = myList[0] var2 = myList[1] print(myList) print("Termine el bucle de for y lectura del archivo.txt / Tengo un array de contratos") time.sleep(3) contract = Contract() contract.symbol = var2 #variable 2 contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" contract.primaryExchange = var1 #variable 1 #Esto son metodos de la clase EClient app.reqMarketDataType(4) # Este 4 es para delayed-frozen data #(tickrId, contract, genericTickList(GenericTickTypes), snapshot, regulatorySnaphsot,mkdDataOptions) app.reqMktData(0,contract,"",False,False,[]) app.run()
def start(self): # global contract # global order # global orderState contract = Contract() contract.symbol = "AAPL" contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" contract.primaryExchange = "NASDAQ" order = Order() order.action = "BUY" order.totalQuantity = 10 order.orderType = "LMT" order.lmtPrice = 330 self.placeOrder(self.nextOrderId, contract, order)
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 start(self): #Esta funcion genera un contrato y objeto order contract = Contract() contract.symbol = "AMZN" contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" contract.primaryExchange = "NASDAQ" order = Order() order.action = "BUY" #"SELL" order.totalQuantity = 100 order.orderType = "LMT" order.lmtPrice = 347.02 self.placeOrder( self.nextOrderId, contract, order) #places or modifies an order. #id,contract, order
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 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
def main(): app = TestApp() app.nextOrderId = 0 app.connect('127.0.0.1', 4002, 0) contract = Contract() contract.symbol = "EUR" contract.secType = "CASH" contract.currency = "USD" contract.exchange = "IDEALPRO" #request historical data app.reqHistoricalData(1, contract, '', '1 D', '1 min', 'MIDPOINT', 0, 1, True, []) # Call stop() after 3 seconds to disconnect the program Timer(720, app.stop).start() 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(4) app.reqMktData(1, contract, "", False, False, []) app.run()
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 main(): app = TestApp() app.connect("127.0.0.1", 7497, 0) contract = Contract() contract.symbol = "AMZN" contract.secType = "STK" contract.exchange = "SMART" Contract.currency = "USD" contract.primaryExchange = "NASDAQ" #Esto son metodos de la clase EClient app.reqMarketDataType(4) # Este 4 es para delayed-frozen data #(tickrId, contract, genericTickList(GenericTickTypes), snapshot, regulatorySnaphsot,mkdDataOptions) app.reqMktData(0, contract, "", False, False, []) app.run()
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
def order(self, asset, amount, style): ib_symbol = self._asset_symbol(asset) contract = Contract() contract.symbol = ib_symbol contract.exchange = 'SMART' primaryExchange = 'ISLAND' contract.secType = 'STK' contract.currency = self.currency order = Order() order.totalQuantity = int(fabs(amount)) order.action = "BUY" if amount > 0 else "SELL" is_buy = (amount > 0) order.lmtPrice = style.get_limit_price(is_buy) or 0 order.auxPrice = style.get_stop_price(is_buy) or 0 if isinstance(style, MarketOrder): order.orderType = "MKT" order.tif = "DAY" order.algoStrategy = "Adaptive" order.algoParams = [] order.algoParams.append(TagValue("adaptivePriority", "Patient")) elif isinstance(style, LimitOrder): order.orderType = "LMT" order.tif = "GTC" elif isinstance(style, StopOrder): order.orderType = "STP" order.tif = "GTC" elif isinstance(style, StopLimitOrder): order.orderType = "STP LMT" order.tif = "GTC" order.orderRef = self._create_order_ref(order) ib_order_id = self._tws.next_order_id zp_order = self._get_or_create_zp_order(ib_order_id, order, contract) self.log_order(contract, ib_order_id, order) self._tws.placeOrder(ib_order_id, contract, order) return zp_order
def main(): app = DemoApp() app.connect("127.0.0.1", 7496, 0) # id = app.reqIds(0) contract = Contract() contract.symbol = "AAPL" contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" # contract.primaryExchange = "NYSE" app.reqContractDetails(1, contract) app.run() print()
def start(self): queryTime = (datetime.datetime.today() - datetime.timedelta(days=3)).strftime("%Y%m%d %H:%M:%S") contract = Contract() contract.secType = "CASH" contract.symbol = "USD" contract.currency = "JPY" contract.exchange = "IDEALPRO" # contract = Contract() # contract.symbol = "FB" # contract.secType = "STK" # contract.currency = "USD" # contract.exchange = "SMART" # contract.primaryExchange = 'NASDAQ' #6 request data, using fx data because its free on demo self.reqHistoricalData(1004, contract, queryTime, "1 D", "1 day", "MIDPOINT", 1, 1, False, [])
def main(): app = TestApp() # cause API running on same computer as TWS, host is localhost = 127.0.0.1 app.connect("127.0.0.1", 7497, clientId=4) con_thread = threading.Thread(target=app.run, daemon=True) con_thread.start() contract = Contract() contract.symbol = "AAPL" contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" contract.primaryExchange = "ISLAND" app.reqContractDetails(10, contract) app.reqHistoricalData(11, contract, '20210101 01:00:00', '1 M', '5 mins', 'MIDPOINT', 1, 1, False, []) app.run()
def start_getting_mkt_depth_data(self, contract, reqId): self._market_depth_q_dict[reqId] = self.wrapper.init_market_depth_queue(reqId) # def marketDepthOperations_req(self): # Requesting the Deep Book # ! [reqmarketdepth] # self.reqMktDepth(reqId, contract, 5, []) contract = Contract() contract.symbol = "EUR" contract.secType = "CASH" contract.currency = "GBP" contract.exchange = "IDEALPRO" self.reqMktDepth(2001, contract, 5, []) # ! [reqmarketdepth] # Request list of exchanges sending market depth to UpdateMktDepthL2() # ! [reqMktDepthExchanges] self.reqMktDepthExchanges()
def getContracts(self): self.got_contracts = True #remove already current tickers to_remove = [] for reqId, info in self.newTickers.items(): if info['symbol'] in self.allCurrentTickers: to_remove.append(reqId) ''' for reqId in to_remove: self.newTickers.pop(reqId) ''' for reqId, info in self.newTickers.items(): contract = Contract() contract.symbol = info["symbol"] contract.currency = "USD" contract.secType = "STK" contract.exchange = "SMART" self.reqContractDetails(reqId, 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 main(): app.connect('127.0.0.1', 7496, 123) api_thread = threading.Thread(target=run_loop, daemon=True) api_thread.start() time.sleep(1) usdcad_contract = Contract() usdcad_contract.symbol = 'USD' usdcad_contract.secType = 'CASH' usdcad_contract.exchange = 'IDEALPRO' usdcad_contract.currency = 'CAD' requestID = 100 app.reqHistoricalData(requestID, usdcad_contract, '', '10 D', '1 hour', 'BID', 0, 2, True, []) try: while True: time.sleep(3) if app.isDirty(): candles = [] ts = datetime.fromtimestamp(int(app.data[1][0])) print('checking for big shadow for candle @', ts.strftime('%b %d %Y %H:%M:%S')) for i in range(1, config.BS_NUMCANDLES + 1): candles.append( Candle(app.data[i][1], app.data[i][2], app.data[i][3], app.data[i][4])) cg = CandleGroup(candles) if cg.bigShadow(maxBodyRatio=config.BS_BODYRATIO, wickPercent=config.BS_WICKPERCENTAGE): print('big shadow found for candle @', ts.strftime('%b %d %Y %H:%M:%S')) sendtext(('found big shadow on USDCAD 1H @', ts.strftime('%b %d %Y %H:%M:%S'))) except KeyboardInterrupt: pass app.disconnect()
def get_data(symbol, secType, exch, curr, duration, enddate, barsize=None): app = TestApp("127.0.0.1", 4001, 1) ibcontract = Contract() 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) app.disconnect() return historic_data
def order(self, instrument, direction, quantity): """ function to allow market orders to be created and placed :param instrument: the instrument's symbol :param direction: i.e BUY or SELL :param quantity: number of shares :return: True/False for order PLACED (not necessarily successful just placed) """ contract = Contract() if len(instrument) == 6: # if it is a forex pair sec_type = "CASH" symbol = instrument.upper()[0:3] currency = instrument.upper()[3:6] exchange = "IDEALPRO" elif len(instrument) <= 5: # if it is a stock sec_type = "STK" currency = "USD" contract.primaryExchange = "ISLAND" exchange = "SMART" else: # if it is neither stock or forex pair refuse to place order, return False for failed order. return False # creates Contract object and fills necessary data contract.symbol = symbol contract.secType = sec_type contract.currency = currency contract.exchange = exchange # creates order and fills out details order = Order() order.action = direction order.orderType = "MKT" order.totalQuantity = quantity # gets latest order id old_val = self.nextValidOrderId self.reqIds(-1) while self.nextValidOrderId == old_val and self.orderMade: # waits until order id updated. pass # places the order and returns True since no errors would have been raised by this point. self.placeOrder(self.nextValidOrderId, contract, order) self.orderMade = True return True
def main(): print(datetime.fromtimestamp(int(datetime.now().timestamp())),'main() run') app=TestApp() app.nextOrderId=0 # app.connect('127.0.0.1',7497,0) # IB TWS app.connect('127.0.0.1',4002,0) # IB Gateway contract = Contract() contract.symbol = "EUR" contract.secType = "CASH" contract.currency = "USD" contract.exchange = "IDEALPRO" #request historical data app.reqHistoricalData(1,contract,'','2 D','3 mins','MIDPOINT',0,2,True,[]) t = threading.Thread(target = app.ifDataDelay,name='CheckDelay') t.setDaemon(True) t.start() app.run()
def doOrder(self, action, instrument: OneStock): contract = Contract() contract.symbol = instrument.contract.symbol contract.secType = instrument.contract.sectype contract.currency = instrument.contract.currency contract.exchange = instrument.contract.exchange contract.lastTradeDateOrContractMonth = instrument.contract.expire #print(contract.symbol, contract.secType, contract.currency, contract.exchange, # contract.lastTradeDateOrContractMonth) order = Order() #order.action = "BUY" order.action = action # order.orderType = "LMT" order.orderType = "MKT" #order.totalQuantity = 1 ordersize = int(instrument.contract.ordersize) if instrument.order['Position'] == 0: order.totalQuantity = ordersize if action == 'BUY': instrument.order['Position'] = ordersize else: instrument.order['Position'] = -ordersize elif instrument.order['Position'] == ordersize and action == 'SELL': order.totalQuantity = ordersize * 2 instrument.order['Position'] = -ordersize elif instrument.order['Position'] == -ordersize and action == 'BUY': order.totalQuantity = ordersize * 2 instrument.order['Position'] = ordersize else: return #nothing to do # order.lmtPrice = 100 # order.account="U146642" print("action=", action, "size=", order.totalQuantity, ordersize, "symbol=", contract.symbol, 'Position=', instrument.order['Position']) toTWS = toMessage('PlaceOrder', ['Nothing', contract, order]) # print(self.dbLite.getDateTimeToDownload()) self.toTws.put(toTWS)
def main(): app = TestApp() #POR LOS DATOS QUE TENGO DEBERIA TRAERME PRECIO DE LAS ACCCIONES DEL INSTRUMENTO DECLARADO EN EL CONTRATO 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" #Esto son metodos de la clase EClient app.reqMarketDataType(4) # Este 4 es para delayed-frozen data #221= mark price (Precio de marca) #Identificador de la peticion = tickrId #(tickrId, contract, genericTickList(GenericTickTypes), snapshot, regulatorySnaphsot,mkdDataOptions) app.reqMktData(1, contract, "", False, False, []) app.run()
def buy_stock(self): print(self.bidPrice) contract = Contract() contract.symbol = "TSLA" contract.secType = "STK" contract.currency = "USD" contract.exchange = "ISLAND" order = Order() order.action = "BUY" order.orderType = "LMT" order.totalQuantity = 10 order.lmtPrice = self.bidPrice + 0.01 #order.orderType = "MTL" #order.totalQuantity = 10 print("place an order", self.oID) self.placeOrder(self.oID, contract, order) self.playBuyOrderTime = datetime.now() self.oID = self.oID + 1
def main(): app = TestApp() app.nextOrderId = 0 app.connect('127.0.0.1', 4002, 0) #request Real-time data contract = Contract() contract.symbol = "EUR" #for real-time data contract.secType = "CFD" contract.currency = "USD" contract.exchange = "SMART" app.reqMarketDataType( 4) #if live not available,switch to delayed-forzen data. app.reqMktData(1, contract, "", False, False, []) # Call stop() after 3 seconds to disconnect the program #Timer(60,app.stop).start() app.run()
def start(self): contract = Contract() wb = Workbook.load_workbook('StockTickers.xlsx') sheet_ranges = wb['Sheet1'] empty_list = [] for row in range(1, sheet_ranges.max_row + 1): for column in "A": cell_name = "{}{}".format(column, row) empty_list.append(sheet_ranges[cell_name].value) contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" contract.primaryExchange = "NASDAQ" for i in empty_list: contract.symbol = str(i) print(i) self.reqHistoricalData(1, contract, "", "26 W", "1 day", "MIDPOINT", 0, 1, False, []) self.tickerId = +1
def main(): app = TestApp() app.connect("127.0.0.1", 7497, 0) print("serverVersion:%s connectionTime:%s" % (app.serverVersion(), app.twsConnectionTime())) contract = Contract() contract.symbol = "EUR" contract.secType = "CASH" contract.exchange = "IDEALPRO" contract.currency = "USD" #contract.primaryExchange = "ISLAND" #"NASDAQ",SE PUEDE USAR ISLAND INSTEAD NASDAQ #Esto son metodos de la clase EClient app.reqMarketDataType(4) # Este 4 es para delayed-frozen data #(tickrId, contract, genericTickList(GenericTickTypes), snapshot, regulatorySnaphsot,mkdDataOptions) app.reqMktData(0, contract, "", False, False, []) app.run()