pythonbinance-api-client

How close position in Binance by API


I am looking for possibility of closing position regardless of whether at a profit or loss via API.

I tried something like that:

stop_order = self.client.futures_create_order(
            symbol=symbol,
            side=stop_side, #SELL if I have long position or BUY if short
            type=FUTURE_ORDER_TYPE_STOP_MARKET,
            closePosition=True,
            stopPrice=stop_price, #it is required but I would prefer "Market" price in this case
            test=True
        )

but I'm receiving error like that: "Error canceling order: APIError(code=-2021): Order would immediately trigger."

or if I change to FUTURE_ORDER_TYPE_MARKET: "Error canceling order: APIError(code=-4136): Target strategy invalid for orderType MARKET,closePosition true"

it's seems like binance API doesn't allow what I want.. but via page we can simply click "Market" and position would be close...


Solution

  • The error messages you’re encountering arise because Binance’s API handles closing positions differently than the web interface.

    Order would immediately trigger (-2021) happens because FUTURE_ORDER_TYPE_STOP_MARKET is a stop order, which requires a stopPrice. However, the stop price cannot be immediately triggered by the current market price.

    Target strategy invalid (-4136) occurs because FUTURE_ORDER_TYPE_MARKET does not support closePosition=True. That parameter is only valid for stop orders or take-profit orders.

    You can use FUTURE_ORDER_TYPE_MARKET without closePosition. You can create a market order with the correct quantity and side to close the position. Here’s how to do it-

    positions = self.client.futures_account()['positions']
    position = next((p for p in positions if p['symbol'] == symbol), None)
    
    if position and float(position['positionAmt']) != 0:
        side = 'SELL' if float(position['positionAmt']) > 0 else 'BUY'  
        quantity = abs(float(position['positionAmt']))  
    
        close_order = self.client.futures_create_order(
            symbol=symbol,
            side=side,
            type='MARKET',
            quantity=quantity
        )
        print(f"Position closed: {close_order}")
    else:
        print(f"No position found for {symbol}")