def bracketOrder(parentOrderId: int, action: str, quantity: float, limitPrice: float, stopLossPrice: float): #This will be our main or "parent" order parent = Order() parent.orderId = parentOrderId parent.action = action parent.orderType = "STP LMT" parent.totalQuantity = quantity parent.lmtPrice = limitPrice parent.auxPrice = limitPrice #The parent and children orders will need this attribute set to False to prevent accidental executions. #The LAST CHILD will have it set to True, parent.transmit = False stopLoss = Order() stopLoss.orderId = parent.orderId + 2 stopLoss.action = "SELL" if action == "BUY" else "BUY" stopLoss.orderType = "STP" #Stop trigger price stopLoss.auxPrice = stopLossPrice stopLoss.totalQuantity = quantity stopLoss.parentId = parentOrderId #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 bracketOrder = [parent, stopLoss] return bracketOrder
def _constructContractAndOrder(aat_order): contract = _constructContract(aat_order.instrument) order = Order() order.action = aat_order.side.value if aat_order.order_type == OrderType.MARKET: order.orderType = "MKT" order.totalQuantity = aat_order.volume elif aat_order.order_type == OrderType.LIMIT: order.orderType = "LMT" order.totalQuantity = aat_order.volume order.lmtPrice = aat_order.price elif aat_order.order_type == OrderType.STOP: if aat_order.stop_target.order_type == OrderType.MARKET: order.orderType = "STP" order.auxPrice = aat_order.price order.totalQuantity = aat_order.stop_target.volume elif aat_order.stop_target.order_type == OrderType.LIMIT: order.orderType = "STP LMT" order.totalQuantity = aat_order.stop_target.volume order.lmtPrice = aat_order.stop_target.price order.auxPrice = aat_order.price else: raise NotImplementedError() else: raise NotImplementedError() return contract, order
def PeggedToMarket(action: str, quantity: float, marketOffset: float): order = Order() order.action = action order.orderType = "PEG MKT" order.totalQuantity = quantity order.auxPrice = marketOffset # Offset price return order
def PassiveRelative(action: str, quantity: float, offset: float): order = Order() order.action = action order.orderType = "PASSV REL" order.totalQuantity = quantity order.auxPrice = offset return order
def Stop(action: str, quantity: float, stopPrice: float): order = Order() order.action = action order.orderType = "STP" order.auxPrice = stopPrice order.totalQuantity = quantity return order
def StopWithProtection(action: str, quantity: float, stopPrice: float): order = Order() order.totalQuantity = quantity order.action = action order.orderType = "STP PRT" order.auxPrice = stopPrice return order
def MarketIfTouched(action: str, quantity: float, price: float): order = Order() order.action = action order.orderType = "MIT" order.totalQuantity = quantity order.auxPrice = price return order
def _create_order(action, qty, order_type, limit_price, stop_price): order = Order() order.action = action order.totalQuantity = qty order.auxPrice = stop_price order.lmtPrice = limit_price order.orderType = order_type return order
def stop_order(action: str, quantity: float, stop_price: float): order = Order() order.action = action order.orderType = "STP" order.totalQuantity = quantity order.tif = "GTC" order.auxPrice = stop_price return order
def RelativePeggedToPrimary(action: str, quantity: float, priceCap: float, offsetAmount: float): order = Order() order.action = action order.orderType = "REL" order.totalQuantity = quantity order.lmtPrice = priceCap order.auxPrice = offsetAmount return order
def stop_order(order_id, action, size, stopPrice): app.reqIds(-1) order = Order() order.action = action order.orderType = "STP" order.auxPrice = stopPrice order.totalQuantity = size app.placeOrder(order_id, contract(), order) log(f'stop order placed {order_id, action, size, stopPrice}')
def LimitIfTouched(action: str, quantity: float, limitPrice: float, triggerPrice: float): order = Order() order.action = action order.orderType = "LIT" order.totalQuantity = quantity order.lmtPrice = limitPrice order.auxPrice = triggerPrice return order
def PeggedToMidpoint(action: str, quantity: float, offset: float, limitPrice: float): order = Order() order.action = action order.orderType = "PEG MID" order.totalQuantity = quantity order.auxPrice = offset order.lmtPrice = limitPrice return order
def StopLimit(action: str, quantity: float, limitPrice: float, stopPrice: float): order = Order() order.action = action order.orderType = "STP LMT" order.totalQuantity = quantity order.lmtPrice = limitPrice order.auxPrice = stopPrice return order
def place_order(client, con, price): # Get an order ID client.reqIds(1000) time.sleep(2) # Calculate prices qty = 100 if client.sentiment == Sentiment.BULLISH: action = 'BUY' lmt_price = price * 1.25 lmt_action = 'SELL' stop_price = price * 0.90 stop_action = 'SELL' elif client.sentiment == Sentiment.BEARISH: action = 'SELL' lmt_price = price * 0.75 lmt_action = 'BUY' stop_price = price * 1.10 stop_action = 'BUY' # Create the bracket order main_order = Order() main_order.orderId = client.order_id main_order.action = action main_order.orderType = 'MKT' main_order.totalQuantity = qty main_order.transmit = False # Limit order child lmt_child = Order() lmt_child.orderId = client.order_id + 1 lmt_child.action = lmt_action lmt_child.orderType = 'LMT' lmt_child.totalQuantity = qty lmt_child.lmtPrice = lmt_price lmt_child.parentId = client.order_id lmt_child.transmit = False # Stop order child stop_child = Order() stop_child.orderId = client.order_id + 2 stop_child.action = stop_action stop_child.orderType = 'STP' stop_child.totalQuantity = qty stop_child.auxPrice = stop_price stop_child.parentId = client.order_id stop_child.transmit = False # Place the order client.placeOrder(client.order_id, con, main_order) time.sleep(2) # Request positions client.reqPositions() time.sleep(2)
def create_stop_limit_orders(self, req_orders=None): """ Create a trailing stop order. Arguments: req_orders (list): list of dictionaries - keys are: symbol (str): Equity ticker symbol. instruction (str): "BUY" | "SELL" quantity (float): Order quantity. stop_price (float): stop price limit_price (float): limit price. outside_rth (bool): outside regular trading hours tif (str): Time in force "DAY" | "GTC" profit_price (float): Profit taking price. """ # If only a single contract (dict) is passed convert it # to a list with a single item. if not isinstance(req_orders, list): req_orders = [req_orders] for req_order in req_orders: contract = self.make_contract(symbol=req_order['symbol']) # Create the order order_id = self._get_next_order_id() order = Order() order.orderId = order_id order.action = req_order['instruction'] order.orderType = "STP LMT" order.totalQuantity = req_order['quantity'] order.lmtPrice = req_order['limit_price'] order.auxPrice = req_order['stop_price'] order.outsideRth = req_order['outside_rth'] order.tif = req_order['tif'] order.transmit = False self._saved_orders[order_id] = { "order": order, "contract": contract } # Create the profit taker order if req_order['profit_price'] is not None: profit_taker_order_id = self._get_next_order_id() profit_taker = Order() profit_taker.orderId = profit_taker_order_id profit_taker.action = "SELL"\ if req_order['instruction'] == "BUY" else "BUY" profit_taker.orderType = "LMT" profit_taker.totalQuantity = req_order['quantity'] profit_taker.lmtPrice = req_order['profit_price'] profit_taker.parentId = order.orderId profit_taker.transmit = False self._saved_orders[profit_taker_order_id] = { "order": profit_taker, "contract": contract }
def stop_limit_order(action, size, limitPrice, stopPrice): app.reqIds(-1) order = Order() order.action = action order.orderType = "STP LMT" order.totalQuantity = size order.lmtPrice = limitPrice order.auxPrice = stopPrice app.placeOrder(app.nextValidOrderId, contract(), order) log(f'stop limit order placed {action, size, limitPrice, stopPrice}')
def AuctionRelative(action: str, quantity: float, offset: float): #! [auction_relative] order = Order() order.action = action order.orderType = "REL" order.totalQuantity = quantity order.auxPrice = offset #! [auction_relative] return order
def getOrder(self, orderType, action, quantity, price=None): order = Order() order.action = action order.orderType = orderType order.totalQuantity = quantity if orderType == 'LMT': order.lmtPrice = price elif orderType == 'STP': order.auxPrice = price return order
def TrailingStopLimit(action: str, quantity: float, lmtPriceOffset: float, trailingAmount: float, trailStopPrice: float): order = Order() order.action = action order.orderType = "TRAIL LIMIT" order.totalQuantity = quantity order.trailStopPrice = trailStopPrice order.lmtPriceOffset = lmtPriceOffset order.auxPrice = trailingAmount return order
def PeggedToMidpoint(action: str, quantity: float, offset: float): # ! [pegged_midpoint] order = Order() order.action = action order.orderType = "PEG MID" order.totalQuantity = quantity order.auxPrice = offset # ! [pegged_midpoint] return order
def stop(action: str, quantity: float, stopPrice: float): # ! [stop] order = Order() order.action = action order.orderType = "STP LMT" order.lmtPrice = stopPrice order.auxPrice = stopPrice order.totalQuantity = quantity order.tif = 'GTC' # ! [stop] return order
def TrailingStop(action: str, quantity: float, trailingPercent: float, trailStopPrice: float): # ! [trailingstop] order = Order() order.action = action order.orderType = "TRAIL" order.totalQuantity = quantity # order.trailingPercent = trailingPercent order.auxPrice = trailingPercent order.trailStopPrice = trailStopPrice # ! [trailingstop] return order
def TrailingStopLimit(action: str, quantity: float, limitPrice: float, trailingAmount: float, trailStopPrice: float): # ! [trailingstoplimit] order = Order() order.action = action order.orderType = "TRAIL LIMIT" order.totalQuantity = quantity order.trailStopPrice = trailStopPrice order.lmtPrice = limitPrice order.auxPrice = trailingAmount # ! [trailingstoplimit] return order
def _get_stp_lmt_parent(self) -> Order: _order = Order() _order.action = "BUY" if self.market_is_rising else "SELL" _order.totalQuantity = self.order_size _order.orderType = "STP LMT" _order.auxPrice = (self.parent_price - self.dollar) \ if self.market_is_rising else (self.parent_price + self.dollar) _order.lmtPrice = self.parent_price _order.triggerMethod = 3 _order.tif = "GTC" _order.outsideRth = True _order.transmit = False return _order
def Stop(action: str, quantity: float, stopPrice: float): """ Action: BUY or SELL Quantity StopPrice """ # ! [stop] order = Order() order.action = action order.orderType = "STP" order.auxPrice = stopPrice order.totalQuantity = quantity # ! [stop] return order
def ScaleBracketOrder(parentOrderId: int, action: str, quantity: float, limitPrice: float, takeProfitLimitPrice1: float, takeProfitLimitPrice2: float, stopLossPrice: float, triggerPrice: float, adjustedStopPrice: float): print('Bracket Order parentOrderId: {}'.format(parentOrderId)) #This will be our main or "parent" order parent = Order() parent.orderId = parentOrderId parent.action = action parent.orderType = "LMT" parent.totalQuantity = quantity parent.lmtPrice = limitPrice #The parent and children orders will need this attribute set to False to prevent accidental executions. #The LAST CHILD will have it set to True, parent.transmit = False takeProfit = Order() takeProfit.orderId = parent.orderId + 1 takeProfit.action = "SELL" if action == "BUY" else "BUY" takeProfit.orderType = "LMT" takeProfit.totalQuantity = quantity takeProfit.lmtPrice = takeProfitLimitPrice1 takeProfit.scaleInitLevelSize = 40 # Quantity for profit target 1 takeProfit.scaleSubsLevelSize = 60 # Quantity for profit target 2 takeProfit.scalePriceIncrement = (takeProfitLimitPrice2 - takeProfitLimitPrice1) takeProfit.parentId = parentOrderId takeProfit.transmit = False stopLoss = Order() stopLoss.orderId = parent.orderId + 2 stopLoss.action = "SELL" if action == "BUY" else "BUY" stopLoss.orderType = "STP" #Stop trigger price stopLoss.auxPrice = stopLossPrice stopLoss.totalQuantity = quantity stopLoss.triggerPrice = triggerPrice stopLoss.adjustedStopPrice = adjustedStopPrice stopLoss.parentId = parentOrderId #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 ScaleBracketOrder = [parent, takeProfit, stopLoss] return ScaleBracketOrder
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 create_trailing_stop_orders(self, req_orders=None): """ Create a trailing stop order. Arguments: req_orders (list): list of dictionaries - keys are: symbol (str): Equity ticker symbol. instruction (str): "BUY" | "SELL" quantity (float): Order quantity. trail_stop_price (float): Trailing stop price trail_amount (float): Trailing amount in dollars. limit_offset (float): Offset of limit price for sell - limit offset is greater than trailing amount for buy - limit offset is less than trailing amount outside_rth (bool): outside regular trading hours tif (str): Time in force "DAY" | "GTC" parent_id (int): Id of parent trade. """ # If only a single contract (dict) is passed convert it # to a list with a single item. if not isinstance(req_orders, list): req_orders = [req_orders] for req_order in req_orders: contract = self.make_contract(symbol=req_order['symbol']) # Create the order order_id = self._get_next_order_id() order = Order() order.orderId = order_id order.action = req_order['instruction'] order.orderType = "TRAIL LIMIT" order.totalQuantity = req_order['quantity'] order.trailStopPrice = req_order['trail_stop_price'] order.auxPrice = req_order['trail_amount'] order.lmtPriceOffset = req_order['limit_offset'] order.outsideRth = req_order['outside_rth'] order.tif = req_order['tif'] order.transmit = False # TODO parent_id self._saved_orders[order_id] = { "order": order, "contract": contract }
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 "" ib_contract = generate_ib_contract(req.symbol, req.exchange) if not ib_contract: return "" ib_order = Order() ib_order.clientId = self.clientid ib_order.action = DIRECTION_VT2IB[req.direction] ib_order.orderType = ORDERTYPE_VT2IB[req.type] ib_order.totalQuantity = req.volume ib_order.outsideRth = True ib_order.orderRef = req.orderRef ib_order.account = self.account if req.type == OrderType.LIMIT: ib_order.lmtPrice = req.price elif req.type == OrderType.STOP: ib_order.auxPrice = req.price self.orderLock.acquire() self.orderid += 1 ib_order.orderId = self.orderid 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.orderLock.release() self.gateway.on_order(order) return order.vt_orderid