CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-python-binance

Unofficial Python wrapper for the Binance cryptocurrency exchange REST API v3 and WebSocket APIs with comprehensive trading, market data, and account management functionality

Pending
Overview
Eval results
Files

rest-clients.mddocs/

REST API Clients

The core synchronous and asynchronous REST API clients provide access to all Binance endpoints. Both clients inherit from BaseClient and implement the same comprehensive method set with different execution patterns.

Capabilities

Client Class (Synchronous)

Synchronous REST API client using the requests library. Best for simple scripts, interactive use, and applications that don't require high concurrency.

class Client(BaseClient):
    def __init__(
        self,
        api_key: Optional[str] = None,
        api_secret: Optional[str] = None,
        requests_params: Optional[Dict[str, Any]] = None,
        tld: str = "com",
        base_endpoint: str = BaseClient.BASE_ENDPOINT_DEFAULT,
        testnet: bool = False,
        private_key: Optional[Union[str, Path]] = None,
        private_key_pass: Optional[str] = None,
        ping: Optional[bool] = True,
        time_unit: Optional[str] = None,
    ): ...

Usage Example

from binance import Client

# Initialize with API credentials
client = Client(
    api_key='your_api_key',
    api_secret='your_api_secret',
    testnet=True  # Use testnet for testing
)

# Basic connectivity test
server_time = client.get_server_time()
print(f"Server time: {server_time['serverTime']}")

# Get account information
account = client.get_account()
balances = {b['asset']: b['free'] for b in account['balances'] if float(b['free']) > 0}
print(f"Non-zero balances: {balances}")

AsyncClient Class (Asynchronous)

Asynchronous REST API client using aiohttp. Provides better performance for high-frequency operations and concurrent request handling.

class AsyncClient(BaseClient):
    def __init__(
        self,
        api_key: Optional[str] = None,
        api_secret: Optional[str] = None,
        requests_params: Optional[Dict[str, Any]] = None,
        tld: str = "com",
        base_endpoint: str = BaseClient.BASE_ENDPOINT_DEFAULT,
        testnet: bool = False,
        loop=None,
        session_params: Optional[Dict[str, Any]] = None,
        private_key: Optional[Union[str, Path]] = None,
        private_key_pass: Optional[str] = None,
        https_proxy: Optional[str] = None,
        time_unit: Optional[str] = None,
    ): ...
    
    @classmethod
    async def create(
        cls,
        api_key: Optional[str] = None,
        api_secret: Optional[str] = None,
        **kwargs
    ) -> 'AsyncClient': ...
    
    async def close_connection(self): ...

Usage Example

import asyncio
from binance import AsyncClient

async def main():
    # Create async client
    client = await AsyncClient.create(
        api_key='your_api_key',
        api_secret='your_api_secret'
    )
    
    try:
        # Concurrent requests for better performance
        tasks = [
            client.get_server_time(),
            client.get_exchange_info(),
            client.get_all_tickers()
        ]
        
        server_time, exchange_info, tickers = await asyncio.gather(*tasks)
        
        print(f"Server time: {server_time['serverTime']}")
        print(f"Total symbols: {len(exchange_info['symbols'])}")
        print(f"Total tickers: {len(tickers)}")
        
    finally:
        # Always close the connection
        await client.close_connection()

asyncio.run(main())

Authentication Options

Both clients support multiple authentication methods:

API Key Authentication

client = Client(api_key='your_api_key', api_secret='your_api_secret')

RSA Private Key Authentication

from pathlib import Path

client = Client(
    api_key='your_api_key',
    private_key=Path('path/to/private_key.pem'),
    private_key_pass='optional_passphrase'
)

EdDSA Private Key Authentication

client = Client(
    api_key='your_api_key',
    private_key='path/to/ed25519_private_key.pem'
)

Configuration Options

Testnet Usage

# Use Binance testnet
client = Client(
    api_key='testnet_api_key',
    api_secret='testnet_api_secret',
    testnet=True
)

Custom TLD and Endpoints

# Use different TLD
client = Client(tld='us')  # For Binance.US

# Use different base endpoint
client = Client(base_endpoint='1')  # Alternative endpoint

Request Configuration

# Custom request parameters
client = Client(
    requests_params={
        'timeout': 30,
        'proxies': {'https': 'https://proxy:8080'}
    }
)

# For AsyncClient
client = await AsyncClient.create(
    session_params={
        'timeout': aiohttp.ClientTimeout(total=30)
    },
    https_proxy='https://proxy:8080'
)

Connection Management

Synchronous Client

# Connection is managed automatically
client = Client(api_key='key', api_secret='secret')

# Optional: Disable initial ping
client = Client(api_key='key', api_secret='secret', ping=False)

Asynchronous Client

# Proper async connection management
async def main():
    client = await AsyncClient.create()
    
    try:
        # Use client for operations
        result = await client.get_account()
    finally:
        # Always close connection
        await client.close_connection()

# Or use as async context manager
async def main():
    async with AsyncClient.create() as client:
        result = await client.get_account()
        # Connection closed automatically

Error Handling

Both clients raise the same exception types:

from binance import Client, BinanceAPIException, BinanceRequestException

client = Client(api_key='key', api_secret='secret')

try:
    order = client.create_order(
        symbol='BTCUSDT',
        side='BUY',
        type='MARKET',
        quantity=0.001
    )
except BinanceAPIException as e:
    print(f"API Error {e.code}: {e.message}")
except BinanceRequestException as e:
    print(f"Request Error: {e.message}")
except Exception as e:
    print(f"Unexpected error: {e}")

Time Synchronization

The clients automatically handle timestamp requirements:

# Automatic timestamp generation
client = Client(api_key='key', api_secret='secret')

# Custom time unit (milliseconds by default)
client = Client(api_key='key', api_secret='secret', time_unit='seconds')

Both clients provide identical method signatures and functionality - the only difference is the execution model (synchronous vs asynchronous).

Install with Tessl CLI

npx tessl i tessl/pypi-python-binance

docs

account.md

convert-api.md

depth-cache.md

futures.md

index.md

margin.md

market-data.md

rest-clients.md

staking-mining.md

trading.md

websockets.md

tile.json