DeveloperBreeze

Snippets Programming Tutorials, Guides & Best Practices

Explore 196+ expertly crafted snippets tutorials, components, and code examples. Stay productive and build faster with proven implementation strategies and design patterns from DeveloperBreeze.

Close Futures Hedge Positions on Binance with CCXT Library.

Code January 26, 2024
python


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',
                },
            )
  • Added a check to ensure amount > 0 before attempting to close a position.