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.
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.