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_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 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 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
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)