2

Is there a specific binance futures API endpoint with which you automatically close all positions? There is such an option in the GUI. Right now I can only imagine getting amounts of all positions and than selling that amount, but is there an easier way?

Preferably I would like to be able to call in either the ccxt library or the python-binance library.

Borut Flis
  • 15,715
  • 30
  • 92
  • 119

2 Answers2

6

It depends on the position side, whether it's One-way" (default) or "Hedged" in terms of Binance:

Afaik, there is no endpoint that would close all your positions in one call. However, you can close your positions one by one.

In order to close a single one-way position (a position having side: "BOTH") you just place the order of the opposite side for an amount equal to your position with a reduceOnly flag.

So, if you have an open long position of size 1 (you bought 1 contract), then to close that position you place the opposite order to sell 1 contract. And vice versa, if you have an open short position of size 1, you buy 1 contract to close that position.

import ccxt
from pprint import pprint

# make sure it's 1.51+
print('CCXT Version:', ccxt.__version__)


exchange = ccxt.binanceusdm({
    'apiKey': 'YOUR_API_KEY',
    'secret': 'YOUR_SECRET',
})

markets = exchange.load_markets()

# exchange.verbose = True  # uncomment for debugging purposes

symbol = 'BTC/USDT'
type = 'market'  # market order
side = 'sell'  # if your position is long, otherwise 'buy'
amount = THE_SIZE_OF_YOUR_POSITION  # in contracts
price = None  # required for limit orders
params = {'reduceOnly': 'true'}

try:
    closing_order = exchange.create_order(symbol, type, side, amount, price, params)
    pprint(closing_order)
except Exception as e:
    print(type(e).__name__, str(e))
Igor Kroitor
  • 1,548
  • 13
  • 16
  • Thanks. Why do you even need reduce only in this case? – Borut Flis Jun 12 '21 at 12:20
  • 1
    @BorutFlis if you attempt to sell more than you have in your position with One-way position (`positionSide == 'BOTH'`), then you may close your position and open a new counter-position. So, if you had an open long position for 1 BTC, then if you sell 2 BTC, that will close the long position for 1 BTC and will open a short position for the remaining 1 BTC. The `reduceOnly` flag prevents that and only allows your position to shrink, not to grow... – Igor Kroitor Jun 13 '21 at 13:12
2

Binance API has a DELETE /fapi/v1/allOpenOrders endpoint that requires a pair symbol.

ccxt wraps this endpoint in the cancel_all_orders() function, which requires a pair symbol as well.

So at least you don't have to loop through all positions. But you'll need to loop through all pairs. Or just the pairs with open orders, if you have this information.

Petr Hejda
  • 40,554
  • 8
  • 72
  • 100