예제 #1
0
    def bracketOrder(self, action: str, quantity: float,
            limitPrice:float, takeProfitPrice: float,
            stopLossPrice: float) -> BracketOrder:
        """
        Create a limit order that is bracketed by a take-profit order and
        a stop-loss order. Submit the bracket like:

        .. code-block:: python

            for o in bracket:
                ib.placeOrder(contract, o)

        https://interactivebrokers.github.io/tws-api/bracket_order.html
        """
        assert action in ('BUY', 'SELL')
        reverseAction = 'BUY' if action == 'SELL' else 'SELL'
        parent = LimitOrder(
                action, quantity, limitPrice,
                orderId=self.client.getReqId(),
                transmit=False)
        takeProfit = LimitOrder(
                reverseAction, quantity, takeProfitPrice,
                orderId=self.client.getReqId(),
                transmit=False,
                parentId=parent.orderId)
        stopLoss = StopOrder(
                reverseAction, quantity, stopLossPrice,
                orderId=self.client.getReqId(),
                transmit=True,
                parentId=parent.orderId)
        return BracketOrder(parent, takeProfit, stopLoss)
예제 #2
0
    def set_stop_loss(self, right):
        self.console_log("Check stop loss conditions")
        total_position = self.get_total_position(right)
        buy_limit = (self.config["nope"]["call_limit"]
                     if right == "C" else self.config["nope"]["put_limit"])
        if total_position >= buy_limit:
            existing_stop_orders = self.get_open_stop_orders()
            held_contracts_info_no_stop_order = filter(
                lambda c: c["contract"].conId not in existing_stop_orders,
                self.get_held_contracts_info(right),
            )
            for contract_info in held_contracts_info_no_stop_order:
                position = contract_info["position"]
                avg_price = contract_info["avg"] / 100
                contract = contract_info["contract"]
                qualified_contracts = self.ib.qualifyContracts(contract)
                order_price = stop_order_price(
                    avg_price, self.config["nope"]["stop_loss_percentage"])

                if len(qualified_contracts) > 0:
                    stop_loss_order = StopOrder(
                        "SELL",
                        position,
                        order_price,
                        tif="DAY",
                    )
                    qualified_contract = qualified_contracts[0]
                    trade = self.ib.placeOrder(qualified_contract,
                                               stop_loss_order)
                    trade.filledEvent += log_fill
                    self.log_order(qualified_contract, position, order_price,
                                   "STOP")
                    self.cancel_stop_loss_task()