ccxt

FTX CCXT cancel SL / TP after position closes


I already have the code to send orders to FTX (with TP and SL).

But since TP and SL are not 'attached' to the position and the positions are aggregated it makes a mess with orders.

I have seen people suggest cancelling all orders before opening a new one: https://stackoverflow.com/a/69371405/6014804 Which is a nice idea but unusable in my case.

I regularly have several current positions at the same time.

So I can't cancel all pending orders as soon as I open a new position. Because some orders are still active and relevant.

The only option I guess is to fetch closed orders/positions (when a TP / SL is hit) to individually cancel the remaining order to this position (the opposite order, either TP / SL). Right?

Even if it's the right solution, I don't know how to do that. Has anyone ever experienced that? Thanks in advance.


Solution

  • I'm citing the solution CCXT team has come up with, on their dedicated GitHub issues platform: https://github.com/ccxt/ccxt/issues/15214

    Very rough example:

    tp_order = await exchange.create_order(...)
    sl_order = await exchange.create_order(...)
    
        while True:
            if tp_status == 'open' and sl_status == 'closed':
                # cancel tp order
                cancel_tp_order = await exchange.cancel_order(tp_order['id'])
                break
            
            if sl_status == 'open' and tp_status == 'closed':
                # cancel sl order
                cancel_sl_order = await exchange.cancel_order(sl_order['id'])
                break
           asyncio.sleep(5) # sleep 5 seconds before trying again
    

    Alternatively, you could use WS (they're free now) to detect in real-time which order was filled and immediately close the other.