Registry / http-networking / python-binance

python-binance

JSON →
library1.0.37pypypi✓ verified 21d ago

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.

pip install python-binance
INSTALL
IMPORT
SIG · PYTHON-BINANCE
P
python-binance
http-networkingpythonv1.0.37
Install
6.7s avg
Import
1903ms
Disk
53MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.0.37 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 1.986s · 51.4MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 6.7s · import 1.820s · 55MB
53MB installed
● package 53MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Client
from binance.client import Client
For synchronous REST API interactions.
AsyncClient
from binance import AsyncClient
from binance.client import AsyncClient
AsyncClient is imported directly from the top-level 'binance' package, not 'binance.client'. Forgetting 'await' on AsyncClient.create() is also a common error.
BinanceSocketManager
from binance import BinanceSocketManager
For asynchronous WebSocket stream management. Requires an AsyncClient instance.
ThreadedWebsocketManager
from binance.threaded_websocket import ThreadedWebsocketManager
from binance.ws.threaded_stream import ThreadedApiManager
While 'ThreadedApiManager' exists, 'ThreadedWebsocketManager' is the commonly used class for a simpler, threaded (non-asyncio) websocket approach. Note that the direct path from search was `binance.ws.threaded_stream`, but `binance.threaded_websocket` is the correct top-level import for `ThreadedWebsocketManager`.

This quickstart demonstrates how to initialize an `AsyncClient` with API keys from environment variables, fetch account balances, and retrieve a symbol's latest price. It uses `asyncio.run` to execute the asynchronous operations. Remember to replace placeholder API keys with your actual Binance API key and secret, ensuring they are stored securely as environment variables.

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())
Debug
Known issues
breakingWith 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.
fix
Update API calls to use the new 'sapi' endpoints (if directly calling internal methods) and refactor websocket stream handling to use `async with` for `BinanceSocketManager` or `DepthCacheManager`. Refer to the official documentation for updated examples.
affects: >=1.0.0
gotchaBinance 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.
fix
Store API keys as environment variables, use a secrets management service, or load them from a secure configuration file. The quickstart example demonstrates using `os.environ.get()`.
affects: All versions
gotchaBinance 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.
fix
Implement proper rate-limiting strategies in your application, such as delays between requests or using a token bucket algorithm. Check Binance's official API documentation for specific rate limits on different endpoints. The `X-MBX-USED-WEIGHT` headers can help monitor usage.
affects: All versions
gotchaOrder 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.
fix
Before placing orders, retrieve exchange information using `client.get_exchange_info()` to determine the correct `stepSize` (for quantity) and `tickSize` (for price) for the specific symbol. Format your order parameters to adhere to these precision rules, typically by rounding down.
affects: All versions
gotchaWebsocket 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.
fix
Implement robust reconnection logic for all websocket streams. For user data streams, ensure a 'keep-alive' mechanism is in place to periodically send a ping or renew the listen key before it expires.
affects: All versions
gotchaWhen 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.
fix
Do not hardcode `3 * 365` or `1095` for annualization. Query Binance's exchange information or specific funding rate endpoints to determine the actual funding interval for each symbol. If an endpoint only returns non-default intervals, assume 8-hour for symbols not listed.
affects: All versions
Errors
Common errors & fixes
APIError(code=-1021): Timestamp for this request is outside of the recvWindow.
Your local system's time is not synchronized with Binance's server time, or the `recvWindow` parameter is too small.
fix
Synchronize your computer's system clock, preferably using an NTP server; if the issue persists, you can try increasing the `recvWindow` parameter in your client calls (e.g., `client.get_all_orders(symbol='BNBUSDT', recvWindow=60000)`).
binance.exceptions.BinanceAPIException: APIError(code=-2015): Invalid API-key, IP, or permissions for action.
The provided API key or secret key is incorrect, lacks the necessary permissions on Binance, or the IP address from which the request originates is not whitelisted for that API key.
fix
Double-check your API key and secret for typos, ensure the API key on Binance has the required permissions (e.g., 'Enable Reading', 'Enable Spot & Margin Trading'), and verify if IP restrictions are enabled and correctly configured for your access IP.
ModuleNotFoundError: No module named 'binance.client'
The `python-binance` library is either not installed in your environment or the import statement is incorrect.
fix
Install the library using `pip install python-binance` and ensure your import statement is `from binance.client import Client` (or `from binance.async_client import AsyncClient` for the async version).
AttributeError: 'BinanceClient' object has no attribute 'create_test_order'
You are attempting to call a method that either does not exist in the `BinanceClient` class, or you've made a typo in the method name (e.g., using `create_test_order` instead of the correct `create_order_test`).
fix
Consult the official `python-binance` documentation for the correct method names (e.g., use `client.create_order_test` for testing orders) and ensure your installed library version supports the method you are trying to call.
Upgrade
Version history
1.0.37latest on PyPI · released Jun 8, 2026
Audit
Dependencies
requestsrequiredUsed for synchronous HTTP requests to the Binance REST API.
aiohttprequiredUsed for asynchronous HTTP requests to the Binance REST API.
websocketsrequiredCore dependency for managing real-time websocket connections to Binance.
pycryptodomerequiredRequired for cryptographic operations, specifically HMAC SHA256 for API signature generation.
dateparserrequiredUtility for parsing various date formats, often used in API responses.
sixrequiredPython 2 and 3 compatibility utilities.
Agent activity
45 hits · last 30 days
node
42
Resources
python-binance — pip install python-binance · libregistry