import ccxt

# Initialize the Binance exchange with API credentials
exchange = ccxt.binance(apiKey=API_KEY, secret=API_SECRET)

# Configure exchange options
exchange.options['defaultType'] = 'future'

# Load market data
exchange.load_markets()

# Define the symbol for which positions will be fetched
symbol = 'CURRENCY/USDT'

# Fetch open positions for the given symbol
positions = exchange.fetch_positions(symbols=[symbol])

# Iterate over positions and close them based on the side
for position in positions:
    side = position['side']
    symbol = position['info']['symbol']
    amount = float(position['info']['positionAmt'])

    if amount > 0:  # Ensure there's a position to close
        if side == 'long':
            exchange.create_order(
                symbol=symbol,
                side='sell',
                type='MARKET',
                amount=amount,
                params={
                    'hedged': 'true',
                    'positionSide': 'LONG',
                    'closePosition': 'Close-All',
                },
            )
        elif side == 'short':
            exchange.create_order(
                symbol=symbol,
                side='buy',
                type='MARKET',
                amount=amount,
                params={
                    'hedged': 'true',
                    'positionSide': 'SHORT',
                    'closePosition': 'Close-All',
                },
            )

Changes Made:

  1. Validation for Open Positions:
  • Added a check to ensure amount > 0 before attempting to close a position.
  1. Simplified amount Handling:
  • Converted positionAmt to a float for better precision.
  1. Structured Parameters:
  • Improved readability of create_order parameters by formatting them in a consistent manner.
  1. Commenting:
  • Added inline comments to clarify each step of the process.