def run(self): # Simple contract for GOOG contract = Contract() #contract.conId = 114376112 contract.exchange = "SMART" contract.symbol = "ATK" contract.secType = "STK" #contract.right = "PUT" contract.currency = "USD" #contract.secType = 'OPT' #contract.strike = 24 #contract.expiry = '20121116' today = datetime.today() order = Order() order.orderId = 89 order.clientId = 44 order.action = "BUY" order.totalQuantity = 1 # may have to calculate a smarter number order.orderType = "MKT" order.tif = "DAY" order.transmit = True order.sweepToFill = True order.outsideRth = True contract.symbol = "alkjdf" self.callback.askPrice = None self.tws.reqMktData(2, contract, "", 1) max_wait = timedelta(seconds=30) + datetime.now() while self.callback.askPrice is None: if datetime.now() > max_wait: print "max wait giving up" break print self.callback.askPrice
def createOrderBuy(self): order = Order() order.orderId = self.orderIdCount self.orderIdCount += 1 order.clientId = self.socketnum order.action = "BUY" order.orderType = "MKT" order.tif = "DAY" order.transmit = True order.sweepToFill = True order.outsideRth = True return order
def place_new_IB_order(self, ibcontract, trade, px, orderType, orderid=None, startTime=None, endTime=None): """ Places an order Returns brokerorderid raises exception if fails """ iborder = IBOrder() iborder.action = bs_resolve(trade) if orderType == 'STOP': iborder.auxPrice = px else: iborder.lmtPrice = px iborder.orderType = orderType iborder.totalQuantity = abs(trade) iborder.tif='DAY' iborder.transmit=True #compute time zone info # ib doesn't work if you have startTime and endTime # if startTime: # startTime_tz = local_tz.localize(startTime) # startTime_est = startTime_tz.astimezone(EST) # iborder.goodAfterTime = startTime_est.strftime("%Y%m%d %H:%M:%S EST") if endTime and orderType is not 'MKT': print 'here' iborder.tif = 'GTD' endTime_tz = local_tz.localize(endTime) endTime_est = endTime_tz.astimezone(EST) iborder.goodTillDate = endTime_est.strftime("%Y%m%d %H:%M:%S EST") ## We can eithier supply our own ID or ask IB to give us the next valid one if orderid is None: print "Getting orderid from IB" orderid=self.get_next_brokerorderid() print "Using order id of %d" % orderid # Place the order self.tws.placeOrder( orderid, # orderId, ibcontract, # contract, iborder # order ) return orderid
def place_order(self, contract): print('Waiting for valid order id') order_id = self.order_ids.get(timeout=WAIT_TIME) if not order_id: raise RuntimeError('Failed to receive order id after %ds' % WAIT_TIME) # Order details algoParams = TagValueList() algoParams.append(TagValue("componentSize", "3")) algoParams.append(TagValue("timeBetweenOrders", "60")) algoParams.append(TagValue("randomizeTime20", "1")) algoParams.append(TagValue("randomizeSize55", "1")) algoParams.append(TagValue("giveUp", "1")) algoParams.append(TagValue("catchUp", "1")) algoParams.append(TagValue("waitForFill", "1")) algoParams.append(TagValue("startTime", "20110302-14:30:00 GMT")) algoParams.append(TagValue("endTime", "20110302-21:00:00 GMT")) order = Order() order.action = 'BUY' order.lmtPrice = 140 order.orderType = 'LMT' order.totalQuantity = 10 order.algoStrategy = "AD" order.tif = 'DAT' order.algoParams = algoParams # order.transmit = False print("Placing order for %d %s's (id: %d)" % (order.totalQuantity, contract.symbol, order_id)) # Place the order self.tws.placeOrder( order_id, # orderId, contract, # contract, order # order ) print("\n====================================================================") print(" Order placed, waiting %ds for TWS responses" % WAIT_TIME) print("====================================================================\n") print("Waiting for order to be filled..") try: self.order_filled.wait(WAIT_TIME) except KeyboardInterrupt: pass finally: if not self.order_filled.is_set(): print('Failed to fill order')
def get_limit_order(self, sid, amt, lmtPrice): order = Order() order.action = self.order_action(amt) order.totalQuantity = abs(amt) order.orderType = 'LMT' order.tif = 'DAY' order.outsideRth = False order.lmtPrice = lmtPrice return order
def place_new_IB_order(self, ibcontract, trade, lmtPrice, orderType, orderid=None): """ Places an order Returns brokerorderid raises exception if fails """ iborder = IBOrder() iborder.action = bs_resolve(trade) iborder.lmtPrice = lmtPrice iborder.orderType = orderType iborder.totalQuantity = abs(trade) iborder.tif = 'DAY' iborder.transmit = True # We can eithier supply our own ID or ask IB to give us the next valid # one if orderid is None: print("Getting orderid from IB") orderid = self.get_next_brokerorderid() print("Using order id of %d" % orderid) # Place the order self.tws.placeOrder( orderid, # orderId, ibcontract, # contract, iborder # order ) return orderid
def get_market_order(self, sid, amt): order = Order() order.action = self.order_action(amt) order.totalQuantity = abs(amt) order.orderType = 'MKT' order.tif = 'DAY' order.outsideRth = False return order
def get_limit_order(self, sid, amt, lmtPrice): order = Order(); order.action = self.order_action(amt) order.totalQuantity = abs(amt) order.orderType = 'LMT' order.tif = 'DAY' order.outsideRth = False order.lmtPrice = lmtPrice return order
def get_market_order(self, sid, amt): order = Order(); order.action = self.order_action(amt) order.totalQuantity = abs(amt) order.orderType = 'MKT' order.tif = 'DAY' order.outsideRth = False return order
def execute_order(self, order): contract = self._ewrapper.symbol_contract_dict[order.symbol] ib_order = Order() ib_order.orderType = order.type ib_order.action = order.direction ib_order.totalQuantity = order.quantity ib_order.transmit = True ib_order.tif = 'DAY' if order.type == 'LMT': ib_order.lmtPrice = order.limit_price self.placeOrder(self._ewrapper.next_valid_order_id, contract, ib_order) self._ewrapper.order_dict[ self._ewrapper.next_valid_order_id] = ib_order self._ewrapper.next_valid_order_id += 1
def place_new_IB_order(self, ibcontract, trade, lmtPrice, orderType, orderid=None): """ Places an order Returns brokerorderid raises exception if fails """ global iserror global brokerorderid global finished global getting_executions global order_structure iborder = IBOrder() iborder.action = bs_resolve(trade) iborder.lmtPrice = lmtPrice iborder.orderType = orderType iborder.totalQuantity = abs(trade) iborder.tif = 'DAY' iborder.transmit = True getting_executions = False order_structure = [] ## We can eithier supply our own ID or ask IB to give us the next valid one if orderid is None: print "Getting orderid from IB" orderid = self.get_next_brokerorderid() print "Using order id of %d" % orderid # Place the order self.tws.placeOrder( orderid, # orderId, ibcontract, # contract, iborder # order ) return orderid
def execute_order(self, order): contract = self._ewrapper.symbol_contract_dict[order.symbol] ib_order = Order() ib_order.orderType = order.type ib_order.action = order.direction ib_order.totalQuantity = order.quantity ib_order.transmit=True ib_order.tif='DAY' if order.type == 'LMT': ib_order.lmtPrice = order.limit_price self.placeOrder(self._ewrapper.next_valid_order_id, contract, ib_order) self._ewrapper.order_dict[self._ewrapper.next_valid_order_id] = ib_order self._ewrapper.next_valid_order_id += 1
def place_new_IB_order(self, ibcontract, trade, lmtPrice, orderType, orderid=None): """ Places an order Returns brokerorderid raises exception if fails """ global iserror global brokerorderid global finished global getting_executions global order_structure iborder = IBOrder() iborder.action = bs_resolve(trade) iborder.lmtPrice = lmtPrice iborder.orderType = orderType iborder.totalQuantity = abs(trade) iborder.tif='DAY' iborder.transmit=True getting_executions=False order_structure=[] ## We can eithier supply our own ID or ask IB to give us the next valid one if orderid is None: print "Getting orderid from IB" orderid=self.get_next_brokerorderid() print "Using order id of %d" % orderid # Place the order self.tws.placeOrder( orderid, # orderId, ibcontract, # contract, iborder # order ) return orderid
def place_plain_order(expiry, symbol, right, strike, orderType, quantity, lmtPrice, orderId): """ Place a sinlge option order orderType="LMT" """ if orderId <= 0: orderId = None client, log_order = init_func() log_order.info("placing order ") ibcontract = IBcontract() ibcontract.secType = get_contract_details(symbol)["secType"] ibcontract.expiry = expiry ibcontract.symbol = symbol ibcontract.exchange = get_contract_details(symbol)["exchange"] ibcontract.right = right ibcontract.strike = strike ibcontract.multiplier = get_contract_details(symbol)["multiplier"] ibcontract.currency = get_contract_details(symbol)["currency"] iborder = IBOrder() iborder.action = bs_resolve(quantity) iborder.lmtPrice = lmtPrice iborder.orderType = orderType iborder.totalQuantity = abs(quantity) iborder.tif = get_order_defaults()["tif"] iborder.transmit = get_order_defaults()["transmit"] order_structure = client.place_new_IB_order(ibcontract, iborder, orderid=orderId) df1 = pd.DataFrame() for idx, x in order_structure.items(): temp = pd.DataFrame.from_dict(x, orient='index').transpose() df1 = df1.append(temp) if not df1.empty: df1 = df1.set_index(['orderid'], drop=True) print(df1) end_func(client=client)
def enterPositions(self, weights, execution_sleep=True): print "----------------------MAKING TRADES ON IB---------------------------" # Instantiate our callback object callback = self.PlaceOrderExample() # Instantiate a socket object, allowing us to call TWS directly. Pass our # callback object so TWS can respond. tws = EPosixClientSocket(callback) # Connect to tws running on localhost tws.eConnect("", 7496, 42) # account updates tws.reqAccountUpdates(True, self.accountNumber) sleep(1) print "available funds: %s" % (self.availableFunds) print "net liquidation value: %s" % (self.netLiquidationValue) ###DELAY UNTIL MARKET HOURS if execution_sleep: day_of_week = datetime.now().isoweekday() # if weekday, and we scanned after midnight, set execution time to this morning at 10:30 am time_now = datetime.now() if ( day_of_week in range(1, 6) and (time_now.hour >= 0 and time_now.hour < 10) and (time_now.minute >= 0 and time_now.minute < 30) ): execution_time = datetime( year=time_now.year, month=time_now.month, day=time_now.day, hour=10, minute=30 ) # otherwise, set to next trading day, morning at 10:30am else: execution_time = datetime.now() execution_time = execution_time + dt.timedelta(days=1) while execution_time.isoweekday() > 5: execution_time = execution_time + dt.timedelta(days=1) execution_time = datetime( year=execution_time.year, month=execution_time.month, day=execution_time.day, hour=10, minute=30 ) to_sleep = (execution_time - datetime.now()).total_seconds() print "----------sleeping until execution time of %s---------------" % (execution_time) # sleep until that time sleep(to_sleep) for stock in weights: print ("\n=====================================================================") print (" Trading " + stock) print ("=====================================================================\n") stock_price = Trader.get_quote([stock])[0][self.QUOTE_LAST] print "%s last stock price: %s" % (stock, stock_price) contract = Contract() contract.symbol = stock contract.secType = "STK" contract.exchange = "SMART" contract.currency = "USD" if self.orderId is None: print ("Waiting for valid order id") sleep(1) while self.orderId is None: print ("Still waiting for valid order id...") sleep(1) # Order details order = Order() order.action = "BUY" # order.lmtPrice = 140 order.orderType = "MKT" dollar_value = self.availableFunds * weights[stock] order.totalQuantity = int(round(dollar_value / stock_price, 0)) # order.algoStrategy = "AD" order.tif = "DAY" # order.algoParams = algoParams order.transmit = True print ( "Placing order for %d %s's, dollar value $%s (id: %d)" % (order.totalQuantity, contract.symbol, dollar_value, self.orderId) ) # Place the order tws.placeOrder(self.orderId, contract, order) # orderId, # contract, # order print ("\n=====================================================================") print (" Order placed, waiting for TWS responses") print ("=====================================================================\n") sleep(3) # reset orderid for next self.orderId = self.orderId + 1 print ("\n=====================================================================") print (" Trade done.") print ("=====================================================================\n") print ("******************* Press ENTER to quit when done *******************\n") input() print ("\nDisconnecting...") tws.eDisconnect()
print('Still waiting for valid order id...') sleep(1) # Order details algoParams = TagValueList() algoParams.append(TagValue("componentSize","3")) algoParams.append(TagValue("timeBetweenOrders","60")) algoParams.append(TagValue("randomizeTime20","1")) algoParams.append(TagValue("randomizeSize55","1")) algoParams.append(TagValue("giveUp","1")) algoParams.append(TagValue("catchUp","1")) algoParams.append(TagValue("waitForFill","1")) algoParams.append(TagValue("startTime","20110302-14:30:00 GMT")) algoParams.append(TagValue("endTime","20110302-21:00:00 GMT")) order = Order() order.action = 'BUY' order.lmtPrice = 140 order.orderType = 'LMT' order.totalQuantity = 10 order.algoStrategy = "AD" order.tif = 'DAT' order.algoParams = algoParams #order.transmit = False print("Placing order for %d %s's (id: %d)" % (order.totalQuantity, contract.symbol, orderId)) # Place the order tws.placeOrder(
print('Still waiting for valid order id...') sleep(1) # Order details algoParams = TagValueList() algoParams.append(TagValue("componentSize", "3")) algoParams.append(TagValue("timeBetweenOrders", "60")) algoParams.append(TagValue("randomizeTime20", "1")) algoParams.append(TagValue("randomizeSize55", "1")) algoParams.append(TagValue("giveUp", "1")) algoParams.append(TagValue("catchUp", "1")) algoParams.append(TagValue("waitForFill", "1")) algoParams.append(TagValue("startTime", "20110302-14:30:00 GMT")) algoParams.append(TagValue("endTime", "20110302-21:00:00 GMT")) order = Order() order.action = 'BUY' order.lmtPrice = 140 order.orderType = 'LMT' order.totalQuantity = 10 order.algoStrategy = "AD" order.tif = 'DAT' order.algoParams = algoParams #order.transmit = False print("Placing order for %d %s's (id: %d)" % (order.totalQuantity, contract.symbol, orderId)) # Place the order tws.placeOrder( orderId, # orderId,
# Simple contract for GOOG contract = Contract() contract.exchange = "SMART" contract.symbol = "DELL" contract.secType = "STK" contract.currency = "USD" if orderId is None: print 'Waiting for valid order id' sleep(1) while orderId is None: print 'Still waiting for valid order id...' sleep(1) # Order details order = Order() order.action = 'BUY' order.lmtPrice = 0 order.auxPrice = 0 order.orderType = 'MTL' order.totalQuantity = 1 print "Placing order for %d %s's (id: %d)" % (order.totalQuantity, contract.symbol, orderId) # Place the order tws.placeOrder( orderId, # orderId, contract, # contract, order # order )
def place_or_modif_spread_order(expiry, symbol, right, strike_l, strike_s, orderType, quantity, lmtPrice, orderId): """ Place new option spread order or modify existing order orderType="LMT" Put orderId <= 0 if new order """ """ Modification of an open order through the API can be achieved by the same client which placed the original order. In the case of orders placed manually in TWS, the order can be modified by the client with ID 0. To modify an order, simply call the IBApi.EClient.placeOrder function again with the same parameters used to place the original order, except for the changed parameter. This includes the IBApi.Order.OrderId, which must match the IBApi.Order.OrderId of the original. It is not generally recommended to try to change order parameters other than the order price and order size. To change other parameters, it might be preferable to cancel the original order and place a new order. """ # http://interactivebrokers.github.io/tws-api/modifying_orders.html#gsc.tab=0 if orderId <= 0: orderId = None client, log_order = init_func() log_order.info("placing order ") underl = { 1001: RequestOptionData(symbol, get_contract_details(symbol)["secType"], expiry, strike_l, right, get_contract_details(symbol)["multiplier"], get_contract_details(symbol)["exchange"], get_contract_details(symbol)["currency"], 1001), 1002: RequestOptionData(symbol, get_contract_details(symbol)["secType"], expiry, strike_s, right, get_contract_details(symbol)["multiplier"], get_contract_details(symbol)["exchange"], get_contract_details(symbol)["currency"], 1002) } action1 = {1001: "BUY", 1002: "SELL"} list_results = client.getOptionsChain(underl) legs = [] log_order.info("Number of requests [%d]" % (len(list_results))) for reqId, request in list_results.items(): log_order.info( "Requestid [%d]: Option[%s] Results [%d]" % (reqId, str(request.get_in_data()), len(request.optionsChain))) for opt1 in request.optionsChain: leg1 = sy.ComboLeg() leg1.conId = opt1['conId'] leg1.ratio = get_order_defaults()["ratio"] leg1.action = action1[reqId] leg1.exchange = opt1['exchange'] legs.append(leg1) #sy.Contract.comboLegs ibcontract = IBcontract() ibcontract.comboLegs = sy.ComboLegList(legs) ibcontract.symbol = symbol ibcontract.secType = "BAG" # BAG is the security type for COMBO order ibcontract.exchange = get_contract_details(symbol)["exchange"] ibcontract.currency = get_contract_details(symbol)["currency"] iborder = IBOrder() iborder.action = bs_resolve(quantity) iborder.lmtPrice = lmtPrice iborder.orderType = orderType iborder.totalQuantity = abs(quantity) iborder.tif = get_order_defaults()["tif"] iborder.transmit = get_order_defaults()["transmit"] order_structure = client.place_new_IB_order(ibcontract, iborder, orderid=orderId) df1 = pd.DataFrame() for idx, x in order_structure.items(): temp = pd.DataFrame.from_dict(x, orient='index').transpose() df1 = df1.append(temp) if not df1.empty: df1 = df1.set_index(['orderid'], drop=True) print(df1) end_func(client=client)
def place_new_IB_order(self, ibcontract, trade, lmtPrice, orderType, orderid=None, stopPrice=None, trailStopPrice=None): """ Places an order Returns brokerorderid raises exception if fails """ iborder = IBOrder() iborder.account = self.accountid iborder.action = bs_resolve(trade) self.logger.debug( "Placing an order for %s:%s:%s" % (ibcontract.exchange, ibcontract.symbol, ibcontract.secType)) #if orderType == "LMT": # iborder.lmtPrice = lmtPrice iborder.orderType = orderType iborder.totalQuantity = abs(trade) iborder.tif = 'GTC' iborder.transmit = False ## We can eithier supply our own ID or ask IB to give us the next valid one if orderid is None: #print "Getting orderid from IB" orderid = self.get_next_brokerorderid() if stopPrice: stoporder = IBOrder() stoporder.account = self.accountid stoporder.action = bs_resolve((-1) * trade) stoporder.orderType = "STP" stoporder.totalQuantity = abs(trade) stoporder.tif = 'GTC' stoporder.transmit = False stoporder.auxPrice = stopPrice stoporder.parentId = orderid self.logger.debug("Setup StopPrice %s" % stoporder.auxPrice) if trailStopPrice: limitorder = IBOrder() limitorder.account = self.accountid limitorder.action = bs_resolve((-1) * trade) limitorder.orderType = "LMT" limitorder.totalQuantity = abs(trade) limitorder.tif = 'GTC' limitorder.transmit = False limitorder.lmtPrice = trailStopPrice limitorder.parentId = orderid self.logger.debug("Setup TrailPrice %s" % limitorder.lmtPrice) # Place the order #self.tws.placeOrder( orderid, ibcontract,iborder ) if stopPrice and trailStopPrice: #limitorder.transmit=True self.logger.debug("Place Order Stop and TrailPrice") self.tws.placeOrder(orderid, ibcontract, iborder) self.tws.placeOrder(orderid + 1, ibcontract, stoporder) self.tws.placeOrder(orderid + 2, ibcontract, limitorder) elif stopPrice: #stoporder.transmit=True self.logger.debug("Place Order Stop") self.tws.placeOrder(orderid, ibcontract, iborder) self.tws.placeOrder(orderid + 1, ibcontract, stoporder) elif trailStopPrice: #limitorder.transmit=True self.logger.debug("Place Order trailStop") self.tws.placeOrder(orderid, ibcontract, iborder) self.tws.placeOrder(orderid + 2, ibcontract, limitorder) else: #iborder.transmit=True self.logger.debug("Place Single Order") self.tws.placeOrder(orderid, ibcontract, iborder) return orderid
callback.Strikes = [] #tws.reqContractDetails(1, contract) #while not callback.contractDataEnd: # pass #for i in range(0, len(sorted(callback.Strikes))): # if sorted(callback.Strikes)[i] > askPrice: # callStrikePrice = sorted(callback.Strikes)[i-1] # callConId = callback.StrikesHash[callStrikePrice][0] # callMultiplier = callback.StrikesHash[callStrikePrice][1] # putStrikePrice = sorted(callback.Strikes)[i] # putConId = callback.StrikesHash[putStrikePrice][0] # putMultiplier = callback.StrikesHash[putStrikePrice][1] # break order = Order() order.orderId = 7 order.clientId = 46 order.action = "SELL" order.totalQuantity = 78 # may have to calculate a smarter number order.orderType = "MKT" order.tif = "DAY" order.transmit = True order.sweepToFill = False order.outsideRth = True callback.accountEnd = False portfolioList = [] callback.portfolioContract = None callback.portfolioPosition = None
# Simple contract for GOOG contract = Contract() contract.exchange = "SMART" contract.symbol = "DELL" contract.secType = "STK" contract.currency = "USD" if orderId is None: print 'Waiting for valid order id' sleep(1) while orderId is None: print 'Still waiting for valid order id...' sleep(1) # Order details order = Order() order.action = 'BUY' order.lmtPrice = 0 order.auxPrice = 0 order.orderType = 'MTL' order.totalQuantity = 1 print "Placing order for %d %s's (id: %d)" % (order.totalQuantity, contract.symbol, orderId) # Place the order tws.placeOrder( orderId, # orderId, contract, # contract, order # order