CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-python-binance

Unofficial Python wrapper for the Binance cryptocurrency exchange REST API v3 and WebSocket APIs with comprehensive trading, market data, and account management functionality

Pending
Overview
Eval results
Files

futures.mddocs/

Futures Trading

Complete futures trading functionality for both USD-margined and coin-margined futures. Includes position management, leverage control, funding rate information, and specialized futures order types.

Capabilities

Futures Exchange Information

Get trading rules and symbol information for futures markets.

def futures_get_exchange_info(self): ...
def futures_coin_get_exchange_info(self): ...

Usage Examples

# Get USD-M futures exchange info
futures_info = client.futures_get_exchange_info()

# Find symbols and their trading rules
for symbol in futures_info['symbols']:
    if symbol['symbol'] == 'BTCUSDT':
        print(f"Status: {symbol['status']}")
        print(f"Base asset: {symbol['baseAsset']}")
        print(f"Quote asset: {symbol['quoteAsset']}")
        print(f"Filters: {symbol['filters']}")

# Get coin-margined futures exchange info
coin_futures_info = client.futures_coin_get_exchange_info()

Futures Market Data

Access futures-specific market data including funding rates and open interest.

def futures_get_all_tickers(self): ...
def futures_get_symbol_ticker(self, **params): ...
def futures_get_orderbook_ticker(self, **params): ...
def futures_get_order_book(self, **params): ...
def futures_get_klines(self, **params): ...
def futures_funding_rate(self, **params): ...
def futures_top_longshort_account_ratio(self, **params): ...
def futures_top_longshort_position_ratio(self, **params): ...
def futures_global_longshort_ratio(self, **params): ...

Usage Examples

# Get all futures tickers
futures_tickers = client.futures_get_all_tickers()
btc_ticker = next(t for t in futures_tickers if t['symbol'] == 'BTCUSDT')
print(f"BTC Futures price: {btc_ticker['price']}")

# Get funding rate information
funding_rate = client.futures_funding_rate(symbol='BTCUSDT')
print(f"Current funding rate: {funding_rate['fundingRate']}")
print(f"Next funding time: {funding_rate['fundingTime']}")

# Get long/short ratio data
longshort_ratio = client.futures_top_longshort_account_ratio(
    symbol='BTCUSDT',
    period='5m',
    limit=30
)

for ratio in longshort_ratio:
    print(f"Time: {ratio['timestamp']}")
    print(f"Long account ratio: {ratio['longAccount']}")
    print(f"Short account ratio: {ratio['shortAccount']}")

Futures Trading

Place and manage futures orders with leverage control.

def futures_create_order(self, **params): ...
def futures_place_batch_order(self, **params): ...
def futures_get_order(self, **params): ...
def futures_get_open_orders(self, **params): ...
def futures_get_all_orders(self, **params): ...
def futures_cancel_order(self, **params): ...
def futures_cancel_all_open_orders(self, **params): ...
def futures_cancel_orders(self, **params): ...
def futures_modify_order(self, **params): ...

Usage Examples

from binance import FUTURE_ORDER_TYPE_LIMIT, FUTURE_ORDER_TYPE_MARKET

# Place futures market order
futures_order = client.futures_create_order(
    symbol='BTCUSDT',
    side='BUY',
    type=FUTURE_ORDER_TYPE_MARKET,
    quantity=0.001
)

# Place futures limit order
limit_order = client.futures_create_order(
    symbol='BTCUSDT',
    side='BUY',
    type=FUTURE_ORDER_TYPE_LIMIT,
    timeInForce='GTC',
    quantity=0.001,
    price='45000'
)

# Place stop market order
stop_order = client.futures_create_order(
    symbol='BTCUSDT',
    side='SELL',
    type='STOP_MARKET',
    quantity=0.001,
    stopPrice='48000'
)

# Place batch orders (up to 5 orders)
batch_orders = [
    {
        'symbol': 'BTCUSDT',
        'side': 'BUY',
        'type': 'LIMIT',
        'timeInForce': 'GTC',
        'quantity': '0.001',
        'price': '45000'
    },
    {
        'symbol': 'BTCUSDT',
        'side': 'SELL',
        'type': 'LIMIT',
        'timeInForce': 'GTC',
        'quantity': '0.001',
        'price': '55000'
    }
]

batch_result = client.futures_place_batch_order(batchOrders=batch_orders)

# Get futures order status
order_status = client.futures_get_order(
    symbol='BTCUSDT',
    orderId=12345678
)

# Cancel futures order
cancel_result = client.futures_cancel_order(
    symbol='BTCUSDT',
    orderId=12345678
)

# Modify existing order
modify_result = client.futures_modify_order(
    symbol='BTCUSDT',
    orderId=12345678,
    side='BUY',
    quantity='0.002',  # New quantity
    price='46000'      # New price
)

Account and Position Management

Manage futures account, positions, and leverage settings.

def futures_account(self, **params): ...
def futures_account_balance(self, **params): ...
def futures_position_information(self, **params): ...
def futures_change_leverage(self, **params): ...
def futures_change_margin_type(self, **params): ...
def futures_change_position_margin(self, **params): ...
def futures_position_margin_history(self, **params): ...

Usage Examples

# Get futures account information
futures_account = client.futures_account()

print(f"Total wallet balance: {futures_account['totalWalletBalance']} USDT")
print(f"Total unrealized PNL: {futures_account['totalUnrealizedProfit']} USDT")
print(f"Total margin balance: {futures_account['totalMarginBalance']} USDT")
print(f"Available balance: {futures_account['availableBalance']} USDT")

# Get account balance breakdown
account_balance = client.futures_account_balance()
for balance in account_balance:
    if float(balance['balance']) > 0:
        print(f"{balance['asset']}: {balance['balance']} (Available: {balance['withdrawAvailable']})")

# Get position information
positions = client.futures_position_information()
for position in positions:
    if float(position['positionAmt']) != 0:
        print(f"Symbol: {position['symbol']}")
        print(f"Position: {position['positionAmt']} (Side: {position['positionSide']})")
        print(f"Entry price: {position['entryPrice']}")
        print(f"Mark price: {position['markPrice']}")
        print(f"Unrealized PNL: {position['unRealizedProfit']}")
        print(f"Leverage: {position['leverage']}x")

# Change leverage for symbol
leverage_result = client.futures_change_leverage(
    symbol='BTCUSDT',
    leverage=10
)

# Change margin type (ISOLATED or CROSSED)
margin_type_result = client.futures_change_margin_type(
    symbol='BTCUSDT',
    marginType='ISOLATED'
)

# Adjust position margin
margin_result = client.futures_change_position_margin(
    symbol='BTCUSDT',
    amount=100,
    type=1  # 1: Add margin, 2: Reduce margin
)

Futures Order Types and Parameters

# Futures-specific order types
FUTURE_ORDER_TYPE_LIMIT = "LIMIT"
FUTURE_ORDER_TYPE_MARKET = "MARKET"
FUTURE_ORDER_TYPE_STOP = "STOP"
FUTURE_ORDER_TYPE_STOP_MARKET = "STOP_MARKET"
FUTURE_ORDER_TYPE_TAKE_PROFIT = "TAKE_PROFIT"
FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET = "TAKE_PROFIT_MARKET"
FUTURE_ORDER_TYPE_TRAILING_STOP_MARKET = "TRAILING_STOP_MARKET"

# Position sides (for hedge mode)
POSITION_SIDE_BOTH = "BOTH"
POSITION_SIDE_LONG = "LONG"
POSITION_SIDE_SHORT = "SHORT"

# Working type for stop orders
WORKING_TYPE_MARK_PRICE = "MARK_PRICE"
WORKING_TYPE_CONTRACT_PRICE = "CONTRACT_PRICE"

Advanced Order Examples

# Trailing stop order
trailing_stop = client.futures_create_order(
    symbol='BTCUSDT',
    side='SELL',
    type='TRAILING_STOP_MARKET',
    quantity=0.001,
    callbackRate=1.0  # 1% callback rate
)

# Stop limit order with working type
stop_limit = client.futures_create_order(
    symbol='BTCUSDT',
    side='SELL',
    type='STOP',
    timeInForce='GTC',
    quantity=0.001,
    price='47000',      # Limit price
    stopPrice='48000',  # Stop price
    workingType='MARK_PRICE'  # Use mark price for trigger
)

# Hedge mode position (requires hedge mode enabled)
long_position = client.futures_create_order(
    symbol='BTCUSDT',
    side='BUY',
    positionSide='LONG',
    type='MARKET',
    quantity=0.001
)

short_position = client.futures_create_order(
    symbol='BTCUSDT',
    side='SELL',
    positionSide='SHORT',
    type='MARKET',
    quantity=0.001
)

Trading History and Statistics

Access futures trading history and performance metrics.

def futures_account_trades(self, **params): ...
def futures_income_history(self, **params): ...
def futures_adl_quantile(self, **params): ...
def futures_force_orders(self, **params): ...

Usage Examples

# Get futures trading history
trades = client.futures_account_trades(symbol='BTCUSDT', limit=100)

for trade in trades:
    print(f"Trade ID: {trade['id']}")
    print(f"Price: {trade['price']}, Qty: {trade['qty']}")
    print(f"Quote qty: {trade['quoteQty']}")
    print(f"Commission: {trade['commission']} {trade['commissionAsset']}")
    print(f"Realized PnL: {trade['realizedPnl']}")

# Get income history (funding fees, realized PnL, etc.)
income_history = client.futures_income_history(
    incomeType='FUNDING_FEE',  # TRANSFER, WELCOME_BONUS, REALIZED_PNL, FUNDING_FEE, COMMISSION, etc.
    limit=100
)

for income in income_history:
    print(f"Income: {income['income']} {income['asset']}")
    print(f"Type: {income['incomeType']}")
    print(f"Time: {income['time']}")

# Get ADL (Auto-Deleveraging) quantile
adl_quantile = client.futures_adl_quantile()
for position in adl_quantile:
    print(f"Symbol: {position['symbol']}")
    print(f"ADL quantile: {position['adlQuantile']}")

# Get force liquidation orders
force_orders = client.futures_force_orders(limit=100)

Coin-Margined Futures

All USD-margined futures methods have coin-margined equivalents with _coin suffix.

def futures_coin_create_order(self, **params): ...
def futures_coin_account(self, **params): ...
def futures_coin_account_balance(self, **params): ...
def futures_coin_position_information(self, **params): ...
def futures_coin_change_leverage(self, **params): ...

Coin-Margined Examples

# Place coin-margined futures order
coin_order = client.futures_coin_create_order(
    symbol='BTCUSD_PERP',  # Note: different symbol format
    side='BUY',
    type='MARKET',
    quantity=1  # In contracts, not BTC
)

# Get coin-margined account info
coin_account = client.futures_coin_account()
print(f"Total wallet balance: {coin_account['totalWalletBalance']}")

# Get coin-margined positions
coin_positions = client.futures_coin_position_information()
for position in coin_positions:
    if float(position['positionAmt']) != 0:
        print(f"Symbol: {position['symbol']}")
        print(f"Position: {position['positionAmt']} contracts")
        print(f"Unrealized PNL: {position['unRealizedProfit']} {position['asset']}")

Portfolio Margin (PAPI)

Comprehensive portfolio margin functionality for institutional and high-volume traders with unified margin across spot, futures, and options.

def papi_get_balance(self, **params): ...
def papi_get_account(self, **params): ...
def papi_get_margin_max_borrowable(self, **params): ...
def papi_get_margin_max_withdraw(self, **params): ...
def papi_get_um_position_risk(self, **params): ...
def papi_get_cm_position_risk(self, **params): ...
def papi_set_um_leverage(self, **params): ...
def papi_set_cm_leverage(self, **params): ...
def papi_get_um_account(self, **params): ...
def papi_get_cm_account(self, **params): ...
def papi_create_um_order(self, **params): ...
def papi_create_cm_order(self, **params): ...
def papi_get_margin_margin_loan(self, **params): ...
def papi_get_margin_repay_loan(self, **params): ...

Portfolio Margin Account Management

# Get portfolio margin balance
papi_balance = client.papi_get_balance()
total_usd_value = 0

for balance in papi_balance:
    if float(balance['balance']) > 0:
        print(f"{balance['asset']}: {balance['balance']}")
        total_usd_value += float(balance['usdValue'])

print(f"Total portfolio value: ${total_usd_value:.2f}")

# Get comprehensive portfolio account info
papi_account = client.papi_get_account()
print(f"Total net value: ${papi_account['totalNetValueOfPortfolio']}")
print(f"Portfolio margin ratio: {papi_account['portfolioMarginRatio']}")
print(f"Total maintenance margin: ${papi_account['totalMaintenanceMargin']}")
print(f"Available balance: ${papi_account['availableBalance']}")

# Get USD-M futures account info
um_account = client.papi_get_um_account()
print(f"Total wallet balance: {um_account['totalWalletBalance']}")
print(f"Available balance: {um_account['availableBalance']}")

# Get Coin-M futures account info
cm_account = client.papi_get_cm_account()
print(f"Total wallet balance: {cm_account['totalWalletBalance']}")

Portfolio Trading Operations

# Create USD-M futures order in portfolio margin
um_order = client.papi_create_um_order(
    symbol='BTCUSDT',
    side='BUY',
    type='MARKET',
    quantity=0.001
)

print(f"Order ID: {um_order['orderId']}")
print(f"Status: {um_order['status']}")

# Create Coin-M futures order in portfolio margin
cm_order = client.papi_create_cm_order(
    symbol='BTCUSD_PERP',
    side='BUY',
    type='MARKET',
    quantity=1  # In contracts
)

# Set leverage for USD-M futures
um_leverage = client.papi_set_um_leverage(
    symbol='BTCUSDT',
    leverage=10
)

# Set leverage for Coin-M futures
cm_leverage = client.papi_set_cm_leverage(
    symbol='BTCUSD_PERP',
    leverage=5
)

Portfolio Margin Operations

# Get maximum borrowable amount
max_borrow = client.papi_get_margin_max_borrowable(
    asset='USDT',
    isolatedSymbol='BTCUSDT'  # Optional for isolated margin
)
print(f"Max borrowable USDT: {max_borrow['amount']}")

# Get maximum withdrawable amount
max_withdraw = client.papi_get_margin_max_withdraw(asset='USDT')
print(f"Max withdrawable USDT: {max_withdraw['amount']}")

# Execute margin loan
margin_loan = client.papi_get_margin_margin_loan(
    asset='USDT',
    amount=1000
)

# Repay margin loan
repay_loan = client.papi_get_margin_repay_loan(
    asset='USDT',
    amount=500
)

This comprehensive futures trading functionality provides complete control over both USD-margined and coin-margined futures positions with advanced order types, leverage management, and portfolio margin support.

Install with Tessl CLI

npx tessl i tessl/pypi-python-binance

docs

account.md

convert-api.md

depth-cache.md

futures.md

index.md

margin.md

market-data.md

rest-clients.md

staking-mining.md

trading.md

websockets.md

tile.json