【TWS API 翻译系列】9、IB和TWS API中的一些高级order
作者:yunjinqi   类别:    日期:2022-01-03 22:12:11    阅读:1116 次   消耗积分:0 分    

高级订单和算法

在基础订单类型的基础上,还可以使用下面的高级订单:

Hedging

对冲订单和一篮子订单比较相似,当使用对冲订单的时候,当主订单被执行之后子订单才会提交。就像在TWS中,对冲订单可以用在外汇交易、贝塔对冲 或者 配对交易中

Hedging Orders in TWS

以外汇对冲为例,当以基础以外的货币购买合约时,您可以附加外汇订单,将基础货币转换为合约货币,以支付交易成本,这要归功于TWS API的附加订单机制。

@staticmethoddef MarketFHedge(parentOrderId:int, action:str):
     
    #FX Hedge orders can only have a quantity of 0
    order = OrderSamples.MarketOrder(action, 0)
    order.parentId = parentOrderId
    order.hedgeType = "F"
    return order
# Parent order on a contract which currency differs from your base currencyparent = OrderSamples.LimitOrder("BUY", 100, 10)parent.orderId = self.nextOrderId()parent.transmit = False# Hedge on the currency conversionhedge = OrderSamples.MarketFHedge(parent.orderId, "BUY")# Place the parent first...self.placeOrder(parent.orderId, ContractSamples.EuropeanStock(), parent)# Then the hedge orderself.placeOrder(self.nextOrderId(), ContractSamples.EurGbpFx(), hedge)

请注意,在某些情况下,在下的主订单进行处理后,在下子订单之前,需要包括 50 毫秒或更短的延迟。否则,将触发错误"10006:缺少主订单"。

Bracket Orders

一篮子订单旨在通过创建一个在主订单上下的止盈单和止损单帮助您限制损失并锁定利润。买入订单由在订单价格上方设定一个卖出限价单和在订单价格下方设定一个卖出止损单。卖出订单反之。请注意一篮子订单如何利用TWS API的附加订单机制。

要记住的一个关键点是准确处理订单传输。由于一篮子由三个订单组成,因此始终存在至少一个订单在发送整个一篮子订单之前被成交的风险。为避免这种情况,请使用IBApi.Order.Transmit标志。当此标志设置为"false"时,TWS 将接收订单,但不会将其发送(传输)到服务器。在下面的示例中,第一个(父级)和第二个(获利)订单将发送到TWS,但不会传输到服务器。但是,当发送最后一个子订单(stopLoss)并假设其IBApi.Order.Transmit标志设置为true时,TWS会将其解释为一个信号,不仅要传输其父订单,还要传输其他兄弟姐妹,从而消除意外执行的风险。

这个和backtrader中的一篮子订单很相似,可以参考我的专栏文章:一篮子订单(Bracket Orders)的创建和撮合机制

@staticmethoddef BracketOrder(parentOrderId:int, action:str, quantity:Decimal, 
                         limitPrice:float, takeProfitLimitPrice:float, 
                          stopLossPrice:float):
         
   #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 = takeProfitLimitPrice
   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
   3stopLoss.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, takeProfit, stopLoss]
   return bracketOrder
bracket = OrderSamples.BracketOrder(self.nextOrderId(), "BUY", 100, 30, 40, 20)
for o in bracket:
    self.placeOrder(o.orderId, ContractSamples.EuropeanStock(), o)
    self.nextOrderId()  # need to advance this we'll skip one extra oid, it's fine

One-Cancels All

一个成交取消全部(OCA)订单类型允许投资者将多个可能不相关的订单分配给一个组。其目的是只完成其中一个订单,这反过来将导致TWS取消剩余的订单。投资者可以提交几份订单,旨在利用集团内最理想的价格。完成一个组订单会导致取消剩余的组订单,而部分完成会导致组重新平衡。投资者可能希望出售1000股股票,其中只有三个头寸中的一个高于现行市场价格。OCA订单组允许投资者在指定的目标水平输入价格,如果一个完成,其他两个将自动取消。或者,投资者可能希望在下跌的市场中持有eMini标准普尔指数期货的多头头寸,或者以更优惠的价格出售美国国债期货。使用OCA订单类型对两个订单进行分组为投资者提供了两次进入类似头寸的机会,同时只冒着承担单个头寸的风险。

@staticmethoddef OneCancelsAll(ocaGroup:str, ocaOrders:ListOfOrder, ocaType:int):
     
    for o in ocaOrders:
       
    	o.ocaGroup = ocaGroup
    	o.ocaType = ocaType         
    return ocaOrders
ocaOrders = [OrderSamples.LimitOrder("BUY", 1, 10), OrderSamples.LimitOrder("BUY", 1, 11),
                      OrderSamples.LimitOrder("BUY", 1, 12)]OrderSamples.OneCancelsAll("TestOCA_" + str(self.nextValidOrderId), ocaOrders, 2)for o in ocaOrders:
    self.placeOrder(self.nextOrderId(), ContractSamples.USStockAtSmart(), o)
OCA的类型

通过IBApi.Order.OcaType属性,可以配置执行后处理剩余订单的方式,如下表所示:

价值描述
1取消所有剩余的订单 with block。
2剩余的订单规模将按比例减小 with block。
3剩余的订单规模将按比例减小,with no block。

注意:如果您使用值"with block",则会为订单提供超额成交保护。这意味着一次只能提交组中的一个订单,以消除超额成交的可能性。点击此处进一步讨论OCA的订单。

Adjustable Stops

您可以对stop, stop limit, trailing stop and trailing stop limit orders附加一次性调整。当您附加调整后的订单时,您可以设置触发价格,该价格将触发对原始(或父)订单的修改,而不是触发订单传输。

给stop订单附加调整
# Attached order is a conventional STP order in opposite directionorder = OrderSamples.Stop("SELL" if parent.action == "BUY" else "BUY",
                      parent.totalQuantity, attachedOrderStopPrice)order.parentId = parent.orderId#When trigger price is penetratedorder.triggerPrice = triggerPrice#The parent order will be turned into a STP orderorder.adjustedOrderType = "STP"#With the given STP priceorder.adjustedStopPrice = adjustStopPrice
给stop limit订单附加调整
#Attached order is a conventional STP orderorder = OrderSamples.Stop("SELL" if parent.action == "BUY" else "BUY",
                                   parent.totalQuantity, attachedOrderStopPrice)order.parentId = parent.orderId#When trigger price is penetratedorder.triggerPrice = triggerPrice#The parent order will be turned into a STP LMT orderorder.adjustedOrderType = "STP LMT"#With the given stop priceorder.adjustedStopPrice = adjustedStopPrice#And the given limit priceorder.adjustedStopLimitPrice = adjustedStopLimitPrice
给跟踪订单附加调整
#Attached order is a conventional STP orderorder = OrderSamples.Stop("SELL" if parent.action == "BUY" else "BUY",
                      parent.totalQuantity, attachedOrderStopPrice)order.parentId = parent.orderId#When trigger price is penetratedorder.triggerPrice = triggerPrice#The parent order will be turned into a TRAIL orderorder.adjustedOrderType = "TRAIL"#With a stop price of...order.adjustedStopPrice = adjustedStopPrice#traling by and amount (0) or a percent (100)...order.adjustableTrailingUnit = trailUnit#of...order.adjustedTrailingAmount = adjustedTrailAmount
订单调整

允许在满足一定条件的情况下激活订单

mkt = OrderSamples.MarketOrder("BUY", 100)# Order will become active if conditioning criteria is metmkt.conditions.append(
            OrderSamples.PriceCondition(PriceCondition.TriggerMethodEnum.Default,
                                        208813720, "SMART", 600, False, False))mkt.conditions.append(OrderSamples.ExecutionCondition("EUR.USD", "CASH", "IDEALPRO", True))mkt.conditions.append(OrderSamples.MarginCondition(30, True, False))mkt.conditions.append(OrderSamples.PercentageChangeCondition(15.0, 208813720, "SMART", True, True))mkt.conditions.append(OrderSamples.TimeCondition("20160118 23:59:59", True, False))mkt.conditions.append(OrderSamples.VolumeCondition(208813720, "SMART", False, 100, True))self.placeOrder(self.nextOrderId(), ContractSamples.EuropeanStock(), mkt)

或者取消他们

lmt = OrderSamples.LimitOrder("BUY", 100, 20)# The active order will be cancelled if conditioning criteria is metlmt.conditionsCancelOrder = Truelmt.conditions.append(
           OrderSamples.PriceCondition(PriceCondition.TriggerMethodEnum.Last,
                                        208813720, "SMART", 600, False, False))self.placeOrder(self.nextOrderId(), ContractSamples.EuropeanStock(), lmt)
价格条件
#Conditions have to be created via the OrderCondition.create priceCondition = order_condition.Create(OrderCondition.Price)#When this contract...priceCondition.conId = conId#traded on this exchangepriceCondition.exchange = exchange#has a price above/belowpriceCondition.isMore = isMore
priceCondition.triggerMethod = triggerMethod#this quantitypriceCondition.price = price#AND | OR next condition (will be ignored if no more conditions are added)priceCondition.isConjunctionConnection = isConjunction

执行订单

execCondition = order_condition.Create(OrderCondition.Execution)#When an execution on symbolexecCondition.symbol = symbol#at exchangeexecCondition.exchange = exchange#for this secTypeexecCondition.secType = secType#AND | OR next condition (will be ignored if no more conditions are added)execCondition.isConjunctionConnection = isConjunction
保证金条件
marginCondition = order_condition.Create(OrderCondition.Margin)#If margin is above/belowmarginCondition.isMore = isMore#given percentmarginCondition.percent = percent#AND | OR next condition (will be ignored if no more conditions are added)marginCondition.isConjunctionConnection = isConjunction
百分比条件
pctChangeCondition = order_condition.Create(OrderCondition.PercentChange)#If there is a price percent change measured against last close price above or below...pctChangeCondition.isMore = isMore#this amount...pctChangeCondition.changePercent = pctChange#on this contractpctChangeCondition.conId = conId#when traded on this exchange...pctChangeCondition.exchange = exchange#AND | OR next condition (will be ignored if no more conditions are added)pctChangeCondition.isConjunctionConnection = isConjunction
时间条件
timeCondition = order_condition.Create(OrderCondition.Time)#Before or after...timeCondition.isMore = isMore#this time..timeCondition.time = time#AND | OR next condition (will be ignored if no more conditions are added)     timeCondition.isConjunctionConnection = isConjunction
成交量条件
volCond = order_condition.Create(OrderCondition.Volume)#Whenever contract...volCond.conId = conId#When traded atvolCond.exchange = exchange#reaches a volume higher/lowervolCond.isMore = isMore#than this...volCond.volume = volume#AND | OR next condition (will be ignored if no more conditions are added)volCond.isConjunctionConnection = isConjunction

算法

通过盈透证券强大的算法策略,订单行为可以进一步增强。为了利用我们的各种算法,请使用IBApi.Order.AlgoStrategyIBApi.Order.AlgoParams


TWS API相关的教程

【TWS API使用教程1】—如何在自己创建的client和TWS之间创建一个连接,并请求当前的时间
【TWS API使用教程2】—如何使用 TWS API在ubuntu和windows上分别设置contract、获取contract详细信息、设置order、下单、获取持仓信息、获取账户信息
【TWS API使用教程3】—如何使用TWS API从盈透证券中设置contract及获取contract的信息?
【TWS API使用教程4】—如何使用TWS API在盈透证券中设置order?
【TWS API使用教程5】—如何使用TWS API在盈透证券中下单(place order)、获取订单信息、获取持仓、获取账户汇总信息?
【TWS API使用教程6】—如何使用TWS API在盈透证券中获取数据?
【TWS API 使用教程7】如何使用TWS API 从盈透证券中筛选满足一定条件的contract?
【TWS API 使用教程8】一个基于TWS API的简单的程序化策略


版权所有,转载本站文章请注明出处:云子量化, http://www.woniunote.com/article/75
上一篇:【TWS API 翻译系列】8、IB和TWS API中的一些基本order
下一篇:【TWS API 翻译系列】10、IB和TWS API中一些常见的关于订单的算法