Binance REST API Python Client

1.0.36 · active · verified Tue Apr 14

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

Install

Imports

Quickstart

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())

view raw JSON →