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