为了账号安全,请及时绑定邮箱和手机立即绑定

6.2. TWS API v9.72 在线文档 ——高级订单及算法【翻译】

标签:
算法 区块链

Advanced Orders and Algos(高级订单及算法)

On top of the basic order types, it is possible to make use of the following advanced features:

【译】基于基础订单类型,我们可以使用以下高级特性

  • Hedging(对冲交易)

  • Bracket Orders(交叉交易)

  • One Cancels All(OCA)

  • Adjustable stops(可调控的暂停订单)

  • Conditioning(训练)

  • IB Algos(盈透算法)

Hedging(对冲交易)

Hedging orders are similar to Bracket Orders. With hedging order, a child order is submitted only on execution of the parent. Orders can be hedged by an attached forex trade, Beta hedge, or Pair Trade, just as in TWS:

【译】对冲交易类似交叉交易。在对冲交易中,子订单只有当父订单执行时才会提交。外汇交易、Beta对冲,组合交易都可以在TWS中,跟对冲交易搭配一起:

Hedging Orders in TWS

For an example of a forex hedge, when buying a contract on a currency other than your base, you can attach an FX order to convert base currency to the currency of the contract to cover the cost of the trade thanks to the TWS API’s Attaching Orders mechanism.

【译】以外汇对冲为例,当买入某种外汇货币合约的同时,你也可以在TWS API中提交基于本币的另外的外汇合约进行对冲,以避免由于价格波动带来的损失。

(注:例如以人民币为本币,可以买入人民币-美元合约的同时,买入人民币-日元,或人民币-欧元合约,因为美元汇率与日元,欧元的汇率经常表现对冲性质,这样当人民币-美元合约因汇率下跌造成影响时,人民币-日元合约则会因为对冲,而获得收益。TWS支持的对冲合约类型,您可以通过“Hedging orders in TWS”进行查看。)

    public static Order MarketFHedge(int parentOrderId, String action)
    {
        //FX Hedge orders can only have a quantity of 0
        Order order = MarketOrder(action, 0);
        order.parentId(parentOrderId);
        order.hedgeType("F");
        return order;
    }
    
    ...
    
    //Parent order on a contract which currency 
    //differs from your base currency
    Order parent = OrderSamples.LimitOrder("BUY", 100, 10);
    parent.orderId(nextOrderId++);
    //Hedge on the currency conversion
    Order hedge = OrderSamples.MarketFHedge(parent.orderId(), "BUY");
    //Place the parent first...
    client.placeOrder(parent.orderId(),
        ContractSamples.EuropeanStock(), parent);
    //Then the hedge order
    client.placeOrder(nextOrderId++, 
        ContractSamples.EurGbpFx(), hedge);

Note that in some cases it will be necessary to include a small delay of 50 ms or less after placing the parent order for processing, before placing the child order. Otherwise the error 10006: Missing parent order will be triggered.

【译】注:在某些情况,在提交子订单前,您需要设置大约50ms左右的延迟时间,先提交父合约。否则可能会出现10006的错误:“Missing parent order"。

Bracket Orders(交叉交易)

Bracket Orders are designed to help limit your loss and lock in a profit by bracketing an order with two opposite-side orders. A BUY order is bracketed by a high-side sell limit order and a low-side sell stop order. A SELL order is bracketed by a high-side buy stop order and a low side buy limit order. Note how bracket orders make use of the TWS API’s Attaching Orders mechanism.

【译】交叉交易是一种同时买入某个合约相反方向的交易类型,可帮助用户锁定收益和损失的一种“交叉”命令。“买入”订单会与一个高价限价卖出单及一个低价卖出暂停单交叉。“卖出”订单会跟一个高价买入暂停单和一个低价买入限价单交叉。需要注意的是TWS中,“交叉交易”的提交机制,及如何使用。

One key thing to keep in mind is to handle the order transmission accurately. Since a Bracket consists of three orders, there is always a risk that at least one of the orders gets filled before the entire bracket is sent. To avoid it, make use of the IBApi.Order.Transmit flag. When this flag is set to ‘false’, the TWS will receive the order but it will not send (transmit) it to the servers. In the example below, the first (parent) and second (takeProfit) orders will be send to the TWS but not transmitted to the servers. When the last child order (stopLoss) is sent however and given that its IBApi.Order.Transmit flag is set to true, the TWS will interpret this as a signal to transmit not only its parent order but also the rest of siblings, removing the risks of an accidental execution.

【译】需要记住的一点是准确的提交订单(顺序)。当提交了一个交叉订单(包含三个基本订单)存在一定的风险,就是其中一个订单可能会先于另外两个订单提交之前成交。为避免这种事,需要使用 IBApi.Order.Transmit 标记。当该标记设置为“false”时,TWS不会立即向服务器发送订单。在以下示例中,第一(父订单)以及第二(获利)订单会提交给TWS,但不会立即发送给服务器。当最后一个订单(暂停亏损)发送给TWS后,“IBApi.Order.Transmit”被设置为“true”。TWS将会把三个订单一起发送给服务器,避免这样的风险。

    public static List<Order> BracketOrder(int parentOrderId, 
        String action, 
        double quantity, double limitPrice, 
        double takeProfitLimitPrice, double stopLossPrice) 
    {
        //This will be our main or "parent" order
        Order parent = new 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);
        
        Order takeProfit = new Order();
        takeProfit.orderId(parent.orderId() + 1);
        takeProfit.action(action.equals("BUY") ? "SELL" : "BUY");
        takeProfit.orderType("LMT");
        takeProfit.totalQuantity(quantity);
        takeProfit.lmtPrice(takeProfitLimitPrice);
        takeProfit.parentId(parentOrderId);
        takeProfit.transmit(false);
        
        Order stopLoss = new Order();
        stopLoss.orderId(parent.orderId() + 2);
        stopLoss.action(action.equals("BUY") ? "SELL" : "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);
        
        List<Order> bracketOrder = new ArrayList<>();
        bracketOrder.add(parent);
        bracketOrder.add(takeProfit);
        bracketOrder.add(stopLoss);
        
        return bracketOrder;
    }

    ...

    List<Order> bracket = OrderSamples.BracketOrder(nextOrderId++, 
        "BUY", 100, 30, 40, 20);
        
    for(Order o : bracket)
    {
        client.placeOrder(o.orderId(), 
        ContractSamples.EuropeanStock(), o);
    }

One Cancels All

The One-Cancels All (OCA) order type allows an investor to place multiple and possibly unrelated orders assigned to a group. The aim is to complete just one of the orders, which in turn will cause TWS to cancel the remaining orders. The investor may submit several orders aimed at taking advantage of the most desirable price within the group. Completion of one piece of the group order causes cancellation of the remaining group orders while partial completion causes the group to re-balance. An investor might desire to sell 1000 shares of only ONE of three positions held above prevailing market prices. The OCA order group allows the investor to enter prices at specified target levels and if one is completed, the other two will automatically cancel. 

Alternatively, an investor may wish to take a LONG position in eMini S&P stock index futures in a falling market or else SELL US treasury futures at a more favorable price. Grouping the two orders using an OCA order type offers the investor two chances to enter a similar position, while only running the risk of taking on a single position.

【译】OCA类型命令,允许投资者同时提交一组没有关联性的订单。在其中一个订单被执行后,立即撤销其他订单。利用OCA订单,投资者可以设置多个不同心理价位的订单。如果组合内的订单部分成交,那么整个组合会重新平衡。例如,当投资者希望在市场上卖出1000股,其中1/3高于市价。OCA订单允许投资者针对不同的订单设定特定的价格,而其中只要一份成交,其他两份订单会立即取消。又或是,投资者希望在下跌行情中长期持有 eMini S&P 股指期货,或者以更好的价格卖出国债期货。将这两份订单组合成OCA订单,同时提交希望交易的仓位,但只承担其中一部分的风险。

    public static List<Order> OneCancelsAll(String ocaGroup, 
        List<Order> ocaOrders, int ocaType) 
    {
        
        for (Order o : ocaOrders) 
        {
            o.ocaGroup(ocaGroup);
            o.ocaType(ocaType);
        }
        return ocaOrders;
    }

    ...
    
    List<Order> OcaOrders = new ArrayList<>();
    OcaOrders.add(OrderSamples.LimitOrder("BUY", 1, 10));
    OcaOrders.add(OrderSamples.LimitOrder("BUY", 1, 11));
    OcaOrders.add(OrderSamples.LimitOrder("BUY", 1, 12));
    OcaOrders = OrderSamples.OneCancelsAll(
        "TestOCA_" + nextOrderId, OcaOrders, 2);
        
    for (Order o : OcaOrders) 
    {
        client.placeOrder(nextOrderId++,
        ContractSamples.USStock(), o);
    }

OCA Types(OCA类型)

Via the IBApi.Order.OcaType attribute, the way in which remaining orders should be handled after an execution can be configured as indicated in the table below:

【译】通过 IBApi.Order.OcaType 标签,可以指定OCA订单执行之后的操作,具体如下:

ValueDescription
1Cancel all remaining orders with block(以块的形式,执行取消剩余订单的操作).*
2Remaining orders are proportionately reduced in size with block(不以块的形式,部分保留剩余的订单).*
3Remaining orders are proportionately reduced in size with no block(以块的形式,部分保留剩余的订单).

Note: if you use a value with block gives your order has overfill protection. This means that only one order in the group will be routed at a time to remove the possibility of an overfill.

【译】当您使用带有“块”的命令,将为您的订单提供“过成交”保护的功能。也就是说,在组合内的订单,只会在同一时间内,依次的提交,避免被“过成交”。

Adjustable Stops(可调整的暂停订单)

You can attach one-time adjustments to stop, stop limit, trailing stop and trailing stop limit orders. When you attach an adjusted order, you set a trigger price that triggers a modification of the original (or parent) order, instead of triggering order transmission.

【译】您可以为暂停订单、限价暂停、暂停跟随以及限价暂停跟随订单添加一次性的调整命令。当您试图调整订单时,需要设置一个激活价位,以便修改原订单。

Adjusted to Stop(对暂停订单的修改)

        Order order = new Order();
        //Attached order is a conventional STP order in opposite direction
        order.action("BUY".equals(parent.getAction()) ? "SELL" : "BUY");
        order.totalQuantity(parent.totalQuantity());
        order.auxPrice(attachedOrderStopPrice);
        order.parentId(parent.orderId());
        //When trigger price is penetrated
        order.triggerPrice(triggerPrice);
        //The parent order will be turned into a STP order
        order.adjustedOrderType(OrderType.STP);
        //With the given STP price
        order.adjustedStopPrice(adjustStopPrice);

Adjusted to Stop Limit(对限价暂停单的修改)

        Order order = new Order();
        //Attached order is a conventional STP order
        order.action("BUY".equals(parent.getAction()) ? "SELL" : "BUY");
        order.totalQuantity(parent.totalQuantity());
        order.auxPrice(attachedOrderStopPrice);
        order.parentId(parent.orderId());
        //When trigger price is penetrated
        order.triggerPrice(triggerPrice);
        //The parent order will be turned into a STP LMT order
        order.adjustedOrderType(OrderType.STP_LMT);
        //With the given stop price
        order.adjustedStopPrice(adjustStopPrice);
        //And the given limit price
        order.adjustedStopLimitPrice(adjustedStopLimitPrice);

Adjusted to Trail(对跟随订单的修改)

        Order order = new Order();
        //Attached order is a conventional STP order
        order.action("BUY".equals(parent.getAction()) ? "SELL" : "BUY");
        order.totalQuantity(parent.totalQuantity());
        order.auxPrice(attachedOrderStopPrice);
        order.parentId(parent.orderId());
        //When trigger price is penetrated
        order.triggerPrice(triggerPrice);
        //The parent order will be turned into a TRAIL order
        order.adjustedOrderType(OrderType.TRAIL);
        //With a stop price of...
        order.adjustedStopPrice(adjustStopPrice);
        //trailing by and amount (0) or a percent (1)...
        order.adjustableTrailingUnit(trailUnit);
        //of...
        order.adjustedTrailingAmount(adjustedTrailAmount);

Order Conditioning(订单条件)

Conditions allow to activate orders given a certain criteria…

【译】允许用户设定在某些条件下,激活订单的条件。

        Order mkt = OrderSamples.MarketOrder("BUY", 100);
        //Order will become active if conditioning criteria is met
        mkt.conditionsCancelOrder(true);
        mkt.conditions().add(OrderSamples.PriceCondition(208813720, "SMART", 600, false, false));
        mkt.conditions().add(OrderSamples.ExecutionCondition("EUR.USD", "CASH", "IDEALPRO", true));
        mkt.conditions().add(OrderSamples.MarginCondition(30, true, false));
        mkt.conditions().add(OrderSamples.PercentageChangeCondition(15.0, 208813720, "SMART", true, true));
        mkt.conditions().add(OrderSamples.TimeCondition("20160118 23:59:59", true, false));
        mkt.conditions().add(OrderSamples.VolumeCondition(208813720, "SMART", false, 100, true));
        client.placeOrder(nextOrderId++, ContractSamples.EuropeanStock(), mkt);

Or cancel them

【译】又或者取消它们

        Order lmt = OrderSamples.LimitOrder("BUY", 100, 20);
        //The active order will be cancelled if conditioning criteria is met
        lmt.conditionsCancelOrder(true);
        lmt.conditions().add(OrderSamples.PriceCondition(208813720, "SMART", 600, false, false));
        client.placeOrder(nextOrderId++, ContractSamples.EuropeanStock(), lmt);

Price Conditions(价格条件)

        //Conditions have to be created via the OrderCondition.Create
        PriceCondition priceCondition = (PriceCondition)OrderCondition.create(OrderConditionType.Price);
        //When this contract...
        priceCondition.conId(conId);
        //traded on this exchange
        priceCondition.exchange(exchange);
        //has a price above/below
        priceCondition.isMore(isMore);
        //this quantity
        priceCondition.price(price);
        //AND | OR next condition (will be ignored if no more conditions are added)
        priceCondition.conjunctionConnection(isConjunction);

Execution Conditions(执行条件)

        ExecutionCondition execCondition = (ExecutionCondition)OrderCondition.create(OrderConditionType.Execution);
        //When an execution on symbol
        execCondition.symbol(symbol);
        //at exchange
        execCondition.exchange(exchange);
        //for this secType
        execCondition.secType(secType);
        //AND | OR next condition (will be ignored if no more conditions are added)
        execCondition.conjunctionConnection(isConjunction);

Margin Conditions(利润条件)

        MarginCondition marginCondition = (MarginCondition)OrderCondition.create(OrderConditionType.Margin);
        //If margin is above/below
        marginCondition.isMore(isMore);
        //given percent
        marginCondition.percent(percent);
        //AND | OR next condition (will be ignored if no more conditions are added)
        marginCondition.conjunctionConnection(isConjunction);

Percentage Conditions(百分比条件)

        PercentChangeCondition pctChangeCondition = (PercentChangeCondition)OrderCondition.create(OrderConditionType.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 contract
        pctChangeCondition.conId(conId);
        //when traded on this exchange...
        pctChangeCondition.exchange(exchange);
        //AND | OR next condition (will be ignored if no more conditions are added)
        pctChangeCondition.conjunctionConnection(isConjunction);

Time Conditions(时间条件)

        TimeCondition timeCondition = (TimeCondition)OrderCondition.create(OrderConditionType.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.conjunctionConnection(isConjunction);

Volume Conditions(成交量条件)

        VolumeCondition volCon = (VolumeCondition)OrderCondition.create(OrderConditionType.Volume);
        //Whenever contract...
        volCon.conId(conId);
        //When traded at
        volCon.exchange(exchange);
        //reaches a volume higher/lower
        volCon.isMore(isMore);
        //than this...
        volCon.volume(volume);
        //AND | OR next condition (will be ignored if no more conditions are added)
        volCon.conjunctionConnection(isConjunction);

(译者注:本章节《高级订单及算法》,还包含有一节算法内容还未翻译,内容比较多,而且比较复杂,因此计划在下周单独完成这小节,届时再post到CSDN上。此外,如果您发现了翻译中有什么错误或者疏漏的地方,也请指正,以便共同为中文TWS开发圈做贡献~~)

译文出处

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消