Binance REST API Python Client
An unofficial Python wrapper for the Binance exchange REST API v3, also supporting websockets for real-time data streams. It provides both synchronous and asynchronous client implementations to interact with market data, account information, and trading functionalities. The library is actively maintained with frequent releases, currently at version 1.0.36.
Warnings
- breaking With the v1.0.0 release, all 'wapi' calls were migrated to 'sapi' endpoints, and websocket streams (including DepthCacheManager) were converted to use asynchronous context managers. Code using older 'wapi' endpoints or synchronous websocket implementations will break.
- gotcha Binance API keys should be stored securely and never hardcoded in your application. Treat your secret key like a password; anyone with access to it can trade on your account.
- gotcha Binance enforces strict rate limits on API requests (e.g., 20 requests per second). Exceeding these limits will result in API errors (e.g., HTTP 429 Too Many Requests) and potentially IP bans. While the library handles timestamps, developers must manage their request frequency.
- gotcha Order placement can fail with 'Precision is over the maximum defined for this asset' if the quantity or price has too many decimal places. Each trading pair on Binance has specific precision requirements for quantity, price, and other parameters.
- gotcha Websocket connections to Binance are subject to a 24-hour limit, after which they will be disconnected. Additionally, user data streams require 'listen keys' to be kept alive (renewed) at least once every hour.
- gotcha When calculating annualized yields for perpetual futures funding rates, assuming a fixed 8-hour funding interval for all symbols is a common error. Many Binance perpetual symbols (especially newer or smaller-cap altcoins) operate on 4-hour, 1-hour, or even 24-hour cycles, leading to significant miscalculations.
Install
-
pip install python-binance
Imports
- Client
from binance.client import Client
- AsyncClient
from binance import AsyncClient
- BinanceSocketManager
from binance import BinanceSocketManager
- ThreadedWebsocketManager
from binance.threaded_websocket import ThreadedWebsocketManager
Quickstart
import asyncio
import os
from binance import AsyncClient
async def main():
api_key = os.environ.get('BINANCE_API_KEY', '')
api_secret = os.environ.get('BINANCE_SECRET_KEY', '')
if not api_key or not api_secret:
print("Please set BINANCE_API_KEY and BINANCE_SECRET_KEY environment variables.")
return
client = await AsyncClient.create(api_key, api_secret)
try:
# Get account information
account_info = await client.get_account()
print("Account Status:")
for asset in account_info['balances']:
if float(asset['free']) > 0 or float(asset['locked']) > 0:
print(f" {asset['asset']}: Free {asset['free']}, Locked {asset['locked']}")
# Get latest price for BTCUSDT
btc_price = await client.get_symbol_ticker(symbol='BTCUSDT')
print(f"\nLatest BTCUSDT Price: {btc_price['price']}")
except Exception as e:
print(f"An error occurred: {e}")
finally:
await client.close_connection()
if __name__ == "__main__":
asyncio.run(main())