{"id":5814,"library":"python-binance","title":"Binance REST API Python Client","description":"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.","status":"active","version":"1.0.36","language":"en","source_language":"en","source_url":"https://github.com/sammchardy/python-binance","tags":["binance","crypto","trading","api","websocket","asyncio","rest","exchange"],"install":[{"cmd":"pip install python-binance","lang":"bash","label":"Install latest version"}],"dependencies":[{"reason":"Used for synchronous HTTP requests to the Binance REST API.","package":"requests"},{"reason":"Used for asynchronous HTTP requests to the Binance REST API.","package":"aiohttp","optional":false},{"reason":"Core dependency for managing real-time websocket connections to Binance.","package":"websockets","optional":false},{"reason":"Required for cryptographic operations, specifically HMAC SHA256 for API signature generation.","package":"pycryptodome"},{"reason":"Utility for parsing various date formats, often used in API responses.","package":"dateparser"},{"reason":"Python 2 and 3 compatibility utilities.","package":"six"}],"imports":[{"note":"For synchronous REST API interactions.","symbol":"Client","correct":"from binance.client import Client"},{"note":"AsyncClient is imported directly from the top-level 'binance' package, not 'binance.client'. Forgetting 'await' on AsyncClient.create() is also a common error.","wrong":"from binance.client import AsyncClient","symbol":"AsyncClient","correct":"from binance import AsyncClient"},{"note":"For asynchronous WebSocket stream management. Requires an AsyncClient instance.","symbol":"BinanceSocketManager","correct":"from binance import BinanceSocketManager"},{"note":"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`.","wrong":"from binance.ws.threaded_stream import ThreadedApiManager","symbol":"ThreadedWebsocketManager","correct":"from binance.threaded_websocket import ThreadedWebsocketManager"}],"quickstart":{"code":"import asyncio\nimport os\nfrom binance import AsyncClient\n\nasync def main():\n    api_key = os.environ.get('BINANCE_API_KEY', '')\n    api_secret = os.environ.get('BINANCE_SECRET_KEY', '')\n\n    if not api_key or not api_secret:\n        print(\"Please set BINANCE_API_KEY and BINANCE_SECRET_KEY environment variables.\")\n        return\n\n    client = await AsyncClient.create(api_key, api_secret)\n\n    try:\n        # Get account information\n        account_info = await client.get_account()\n        print(\"Account Status:\")\n        for asset in account_info['balances']:\n            if float(asset['free']) > 0 or float(asset['locked']) > 0:\n                print(f\"  {asset['asset']}: Free {asset['free']}, Locked {asset['locked']}\")\n\n        # Get latest price for BTCUSDT\n        btc_price = await client.get_symbol_ticker(symbol='BTCUSDT')\n        print(f\"\\nLatest BTCUSDT Price: {btc_price['price']}\")\n\n    except Exception as e:\n        print(f\"An error occurred: {e}\")\n    finally:\n        await client.close_connection()\n\nif __name__ == \"__main__\":\n    asyncio.run(main())","lang":"python","description":"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."},"warnings":[{"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.","message":"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.","severity":"breaking","affected_versions":">=1.0.0"},{"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()`.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"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.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-14T00:00:00.000Z","next_check":"2026-07-13T00:00:00.000Z"}