Python - use api.list_orders() to cancel stop loss before selling profit

I am submitting OTO bracket orders that uses a limit buy with a stop loss. I use another strategy indicator to trigger when to sell therefore a simple Bracket take_profit will not be appropriate for my solution.

My understanding is that I cannot liquidate a position (DELETE/v2/positions/{symbol} ) with an open stop_loss order? For this reason I am trying to get a list of open orders and parse through the list returned by the API to find the order id for my symbol, and then cancel the order using the order id.

How do I parse through the orders list? Can anyone include a good code example? I imagine this requires json.dumps or similar.

Pseudocode of what i’m trying to do:
#Need to sell ‘symbol’: ‘AAPL’
check_orders = api.list_orders(status=‘open’)
print(check_orders)

#Parse order data returned by API, look for open orders matching ‘AAPL’, return order_id
api.cancel_order(order_id)
api.submit_order(‘sell’, ‘AAPL’)

Something like this couuld do.

#Need to sell ‘symbol’: ‘AAPL’
check_orders = api.list_orders(status=‘open’)
print(check_orders)

for o in check_orders:
  if o.symbol == 'AAPL':
    api.cancel_order(o.id)
api.submit_order('AAPL', side='sell', ...)

You can also use api.close_position('AAPL') if market order works for you.

Thank you @hitoshi !!! This is exactly what I was looking for. For Market orders, will api.close_position(‘AAPL’) still work even if I have a pending stop_loss order from OTO?

No, you still need to cancel the order first.