Hi I want to close position when there’s signal. However, binance future api does not have function such close position. I am trying to open opposite order with the same quantity but it’s not working
Can you help?
def close_position_based_on_signal(symbol, sl_signal):
# Retrieve open orders
open_orders = client.get_open_orders(symbol=symbol)
# Retrieve open positions
open_positions = client.futures_position_information()
for position in open_positions:
if position['symbol'] == symbol:
position_id = position['positionAmt']
# Determine the order ID for the open position
order_id = None
for order in open_orders:
if order['symbol'] == symbol and order['positionSide'] == position['positionSide']:
order_id = order['orderId']
break
if order_id:
# Act based on the signal
if sl_signal == 'close_long' or sl_signal == 'close_short':
# Close the position
client.futures_create_order(
symbol=symbol,
side=("SELL" if position['positionSide'] == "LONG" else "BUY"),
positionSide=position['positionSide'],
type="MARKET",
quantity=position['positionAmt']
)
print("Position closed based on signal")
else:
print("No signal to close position")
else:
print("No open order found for the position")