python-binance
python-binance copied to clipboard
How to close all margin positions via API ?
The web interface has an option that says "close all positions". How can I perform this action via the API? Calling open orders does not return to me the order I want to close, and get_all_margin_orders() gives me all orders even the ones that are no longer active.

If you want to close all the positions you can use this code:
def determine_short_or_long(position):
mark_price = float(position['markPrice'])
entry_price = float(position['entryPrice'])
if mark_price != entry_price:
profit = float(position['unRealizedProfit']) >= 0
if entry_price < mark_price and profit:
return 'LONG'
elif entry_price < mark_price and not profit:
return 'SHORT'
elif entry_price > mark_price and profit:
return 'SHORT'
elif entry_price > mark_price and not profit:
return 'LONG'
else:
return False
data = client.futures_position_information
for position in data:
if float(position['positionAmt']) != 0:
# then it means that the position is open
side = "BUY" if determine_short_or_long(position)=="SHORT" else "SELL"
if not side:
symbol = position['symbol']
print(f'Could not determine side of the {symbol} position !')
continue
client.futures_create_order(...)
in the end of the code you can close the position using a MARKET order or a LIMIT order with the price of position["markPrice"]
If you want to close all the positions you can use this code:
def determine_short_or_long(position): mark_price = float(position['markPrice']) entry_price = float(position['entryPrice']) if mark_price != entry_price: profit = float(position['unRealizedProfit']) >= 0 if entry_price < mark_price and profit: return 'LONG' elif entry_price < mark_price and not profit: return 'SHORT' elif entry_price > mark_price and profit: return 'SHORT' elif entry_price > mark_price and not profit: return 'LONG' else: return False data = client.futures_position_information for position in data: if float(position['positionAmt']) != 0: # then it means that the position is open side = "BUY" if determine_short_or_long(position)=="SHORT" else "SELL" if not side: symbol = position['symbol'] print(f'Could not determine side of the {symbol} position !') continue client.futures_create_order(...)in the end of the code you can close the position using a MARKET order or a LIMIT order with the price of
position["markPrice"]
Can Example Code of Close All Position, oh Sorry I'm Newbie Ex. (in the end of your code) client.futures_create_order(symbol = symbol, side = side, type = 'MARKET', quantity = qty_close) How Can i add -- position["markPrice"] -- in this code