Unofficial Python wrapper for the Binance cryptocurrency exchange REST API v3 and WebSocket APIs with comprehensive trading, market data, and account management functionality
—
Cross-margin and isolated margin trading with loan management, interest calculations, and margin-specific order types. Supports margin asset transfers and comprehensive margin account monitoring.
Get margin account details and trading capabilities.
def get_margin_account(self, **params): ...
def get_isolated_margin_account(self, **params): ...
def get_margin_asset(self, **params): ...
def get_margin_symbol(self, **params): ...
def get_margin_all_assets(self, **params): ...
def get_margin_all_pairs(self, **params): ...
def get_isolated_margin_symbol(self, **params): ...
def get_isolated_margin_all_symbols(self, **params): ...# Get cross margin account information
margin_account = client.get_margin_account()
print(f"Total asset of BTC: {margin_account['totalAssetOfBtc']}")
print(f"Total liability of BTC: {margin_account['totalLiabilityOfBtc']}")
print(f"Total net asset of BTC: {margin_account['totalNetAssetOfBtc']}")
print(f"Margin level: {margin_account['marginLevel']}")
print(f"Index price: {margin_account['indexPrice']}")
# Check specific asset balances
for balance in margin_account['userAssets']:
if float(balance['netAsset']) != 0:
print(f"{balance['asset']}: Free={balance['free']}, Locked={balance['locked']}, Borrowed={balance['borrowed']}, Interest={balance['interest']}")
# Get isolated margin account info
isolated_account = client.get_isolated_margin_account()
for asset in isolated_account['assets']:
if asset['symbol'] in ['BTCUSDT', 'ETHUSDT']: # Check specific symbols
base_asset = asset['baseAsset']
quote_asset = asset['quoteAsset']
print(f"Symbol: {asset['symbol']}")
print(f"Isolated: {asset['isolated']}")
print(f"Margin level: {asset['marginLevel']}")
print(f"Margin ratio: {asset['marginRatio']}")
print(f"Index price: {asset['indexPrice']}")
print(f"Liquidate price: {asset['liquidatePrice']}")
print(f"Base asset ({base_asset['asset']}): Free={base_asset['free']}, Locked={base_asset['locked']}, Borrowed={base_asset['borrowed']}")
print(f"Quote asset ({quote_asset['asset']}): Free={quote_asset['free']}, Locked={quote_asset['locked']}, Borrowed={quote_asset['borrowed']}")
# Get margin asset information
btc_margin_asset = client.get_margin_asset(asset='BTC')
print(f"BTC borrowable: {btc_margin_asset['isBorrowable']}")
print(f"BTC mortgageable: {btc_margin_asset['isMortgageable']}")
# Get margin trading pair information
btcusdt_margin = client.get_margin_symbol(symbol='BTCUSDT')
print(f"BTCUSDT margin trading: {btcusdt_margin['isMarginTrade']}")
print(f"Is buy allowed: {btcusdt_margin['isBuyAllowed']}")
print(f"Is sell allowed: {btcusdt_margin['isSellAllowed']}")Place and manage margin trading orders.
def create_margin_order(self, **params): ...
def cancel_margin_order(self, **params): ...
def get_margin_order(self, **params): ...
def get_open_margin_orders(self, **params): ...
def get_all_margin_orders(self, **params): ...
def get_margin_trades(self, **params): ...# Place margin buy order (borrows automatically if needed)
margin_buy = client.create_margin_order(
symbol='BTCUSDT',
side='BUY',
type='MARKET',
quantity=0.001,
isIsolated='FALSE' # Cross margin
)
# Place isolated margin order
isolated_order = client.create_margin_order(
symbol='BTCUSDT',
side='BUY',
type='LIMIT',
timeInForce='GTC',
quantity=0.001,
price='45000',
isIsolated='TRUE' # Isolated margin
)
# Place margin sell order
margin_sell = client.create_margin_order(
symbol='BTCUSDT',
side='SELL',
type='LIMIT',
timeInForce='GTC',
quantity=0.001,
price='55000'
)
# Get margin order status
margin_order = client.get_margin_order(
symbol='BTCUSDT',
orderId=12345678,
isIsolated='FALSE'
)
# Get all open margin orders
open_orders = client.get_open_margin_orders(symbol='BTCUSDT')
# Get margin trading history
margin_trades = client.get_margin_trades(symbol='BTCUSDT', limit=100)
for trade in margin_trades:
print(f"Trade ID: {trade['id']}")
print(f"Price: {trade['price']}, Qty: {trade['qty']}")
print(f"Commission: {trade['commission']} {trade['commissionAsset']}")
print(f"Is isolated: {trade['isIsolated']}")Borrow and repay assets for margin trading.
def create_margin_loan(self, **params): ...
def repay_margin_loan(self, **params): ...
def get_margin_loan_details(self, **params): ...
def get_margin_repay_details(self, **params): ...
def get_margin_interest_history(self, **params): ...
def get_margin_force_liquidation_record(self, **params): ...# Borrow USDT for cross margin
loan_result = client.create_margin_loan(
asset='USDT',
amount=1000,
isIsolated='FALSE' # Cross margin
)
print(f"Loan transaction ID: {loan_result['tranId']}")
# Borrow for isolated margin
isolated_loan = client.create_margin_loan(
asset='USDT',
amount=500,
symbol='BTCUSDT', # Required for isolated margin
isIsolated='TRUE'
)
# Repay loan
repay_result = client.repay_margin_loan(
asset='USDT',
amount=100,
isIsolated='FALSE'
)
# Repay isolated margin loan
isolated_repay = client.repay_margin_loan(
asset='USDT',
amount=50,
symbol='BTCUSDT',
isIsolated='TRUE'
)
# Get loan details
loan_details = client.get_margin_loan_details(
asset='USDT',
isolatedSymbol='BTCUSDT', # Optional, for isolated margin
limit=100
)
for loan in loan_details['rows']:
print(f"Loan ID: {loan['txId']}")
print(f"Amount: {loan['principal']} {loan['asset']}")
print(f"Timestamp: {loan['timestamp']}")
print(f"Status: {loan['status']}") # PENDING, CONFIRMED, FAILED
# Get repayment history
repay_details = client.get_margin_repay_details(
asset='USDT',
limit=100
)
# Get interest history
interest_history = client.get_margin_interest_history(
asset='USDT',
limit=100
)
for interest in interest_history['rows']:
print(f"Interest: {interest['interest']} {interest['asset']}")
print(f"Interest rate: {interest['interestRate']}")
print(f"Type: {interest['type']}") # PERIODIC (daily), ON_BORROW
print(f"Time: {interest['interestAccuredTime']}")
# Get liquidation records
liquidation_records = client.get_margin_force_liquidation_record(limit=100)Transfer assets between spot and margin accounts.
def margin_stream_get_listen_key(self): ...
def margin_stream_keepalive(self, **params): ...
def margin_stream_close(self, **params): ...
def transfer_spot_to_margin(self, **params): ...
def transfer_margin_to_spot(self, **params): ...
def transfer_isolated_margin_to_spot(self, **params): ...
def transfer_spot_to_isolated_margin(self, **params): ...# Transfer from spot to cross margin
spot_to_margin = client.transfer_spot_to_margin(
asset='USDT',
amount=100
)
# Transfer from cross margin to spot
margin_to_spot = client.transfer_margin_to_spot(
asset='USDT',
amount=50
)
# Transfer from spot to isolated margin
spot_to_isolated = client.transfer_spot_to_isolated_margin(
asset='USDT',
symbol='BTCUSDT',
amount=200
)
# Transfer from isolated margin to spot
isolated_to_spot = client.transfer_isolated_margin_to_spot(
asset='USDT',
symbol='BTCUSDT',
amount=100
)Calculate maximum borrowable amounts and transferable quantities.
def get_max_margin_loan(self, **params): ...
def get_max_margin_transfer(self, **params): ...
def get_margin_price_index(self, **params): ...
def get_margin_fee(self, **params): ...
def get_isolated_margin_fee(self, **params): ...# Get maximum borrowable amount
max_borrow = client.get_max_margin_loan(
asset='USDT',
isolatedSymbol='BTCUSDT' # Optional, for isolated margin
)
print(f"Max borrowable USDT: {max_borrow['amount']}")
# Get maximum transferable amount
max_transfer = client.get_max_margin_transfer(
asset='USDT',
isolatedSymbol='BTCUSDT' # Optional
)
print(f"Max transferable USDT: {max_transfer['amount']}")
# Get margin price index
price_index = client.get_margin_price_index(symbol='BTCUSDT')
print(f"BTCUSDT price index: {price_index['price']}")
# Get margin trading fees
margin_fee = client.get_margin_fee()
for fee in margin_fee:
print(f"VIP level {fee['vipLevel']}: Maker={fee['makerCommission']}, Taker={fee['takerCommission']}")
# Get isolated margin trading fees
isolated_fee = client.get_isolated_margin_fee(symbol='BTCUSDT')
print(f"BTCUSDT isolated margin fees: Maker={isolated_fee['makerCommission']}, Taker={isolated_fee['takerCommission']}")isIsolated='FALSE' or omit parameter# Cross margin examples
cross_account = client.get_margin_account()
cross_loan = client.create_margin_loan(asset='USDT', amount=1000)
cross_order = client.create_margin_order(
symbol='BTCUSDT',
side='BUY',
type='MARKET',
quantity=0.001
)isIsolated='TRUE' and symbol for most operations# Isolated margin examples
isolated_account = client.get_isolated_margin_account()
isolated_loan = client.create_margin_loan(
asset='USDT',
amount=500,
symbol='BTCUSDT',
isIsolated='TRUE'
)
isolated_order = client.create_margin_order(
symbol='BTCUSDT',
side='BUY',
type='MARKET',
quantity=0.001,
isIsolated='TRUE'
)Monitor margin levels and liquidation risks.
def get_margin_dribblet(self, **params): ...
def margin_dust_log(self, **params): ...
def get_cross_margin_collateral_ratio(self, **params): ...
def get_margin_interest_rate_history(self, **params): ...# Monitor margin levels
margin_account = client.get_margin_account()
margin_level = float(margin_account['marginLevel'])
if margin_level < 1.3:
print("WARNING: Margin level is low, risk of liquidation!")
print(f"Current margin level: {margin_level}")
print("Consider adding more collateral or reducing positions")
# Get interest rate history
interest_rates = client.get_margin_interest_rate_history(
asset='USDT',
vipLevel=0,
limit=100
)
for rate in interest_rates:
print(f"Date: {rate['timestamp']}")
print(f"Daily interest rate: {rate['dailyInterestRate']}")
# Get collateral ratio information
collateral_ratio = client.get_cross_margin_collateral_ratio()
for ratio in collateral_ratio:
print(f"Collaterals: {ratio['collaterals']}")
print(f"Asset names: {ratio['assetNames']}")Convert small margin balances to BNB.
def get_margin_dribblet(self, **params): ...
def margin_dust_log(self, **params): ...# Get margin dust assets
margin_dust = client.get_margin_dribblet()
print(f"Total transferable BTC: {margin_dust['totalTransferBtc']}")
for detail in margin_dust['details']:
print(f"Asset: {detail['asset']}")
print(f"Amount: {detail['amount']}")
print(f"From BNB: {detail['fromBNB']}")
print(f"To BNB: {detail['toBNB']}")
# Get margin dust conversion history
dust_log = client.margin_dust_log()
for entry in dust_log['userAssetDribblets']:
print(f"Conversion time: {entry['operateTime']}")
print(f"Total transferred: {entry['totalTransferedAmount']} BNB")
print(f"Total service charge: {entry['totalServiceChargeAmount']} BNB")This comprehensive margin trading functionality provides complete control over both cross-margin and isolated margin trading with advanced loan management, risk monitoring, and account optimization features.
Install with Tessl CLI
npx tessl i tessl/pypi-python-binance