How to close an open trade using API of Interactive brokers

892 views Asked by At

everyone

I'm trying to write a little code using the Interactive brokers API

I opened a trade using the API of Interactive brokers and now let's say after it is profitable I want to sell it

What code do I need to write in Python to sell the open position. And not to open another position in its place, but I emphasize - to sell the open position.

My code looks like this:

    def make_order(self):
        # create a contract for the ES futures
        contract = Future(symbol='ES', exchange='CME', currency='USD', lastTradeDateOrContractMonth='202303')

        # place a market order to buy or sell contract of ES
        order = MarketOrder(action=self.position, totalQuantity=1)
        trade = self.ib.placeOrder(contract, order)
        print(trade.orderStatus.status)

        return order

**

  • Then I call this function like this:

**

contract = InteractiveAPI(ib, duration, interval, position, stop_price_fake)
order_trade = contract.make_order()

ib.closeTrade(order_trade)  # **This line doesn't work**

I would appreciate it if someone knows how to fix the last line in the code.

Thank you very much everyone.

2

There are 2 answers

0
misantroop On

If you want to use the concept of trades and not positions then you must keep track of executions (reqExecutions) internally, daily. Outside of that IB is only aware of positions. Separating strategies is achieved with orderRefs.

0
Django On

The solution is just to open a new deal in the opposite direction and that's how the sale is made.

For example if at first I bought (BUY) then to sell we will execute a SELL command like the following code.

contract = InteractiveAPI(ib, duration, interval, 'SELL')
contract.make_order()  # Sell the trade