The Binance Public API Connector for Python is a lightweight library designed to facilitate seamless interaction with the Binance public API. This powerful tool supports a wide range of functionalities, making it essential for developers working with cryptocurrency data and trading.
Overview of Features
The Binance connector library offers comprehensive support for various Binance API services. It allows developers to integrate market data, trading operations, and account management into their applications efficiently.
Key supported features include:
- Access to
/api/*and/sapi/*RESTful endpoints - Real-time Spot Websocket Market Stream connections
- Secure Spot User Data Stream handling
- Interactive Spot WebSocket API capabilities
The library also includes extensive test cases, practical examples, and flexible configuration options for base URLs, request timeouts, and HTTP proxies. Additionally, developers can choose to display response metadata for debugging and monitoring purposes.
Installation Process
Installing the Binance connector is straightforward using Python's package manager. Simply execute the following command in your terminal:
pip install binance-connectorThis command will download and install the latest version of the library along with its dependencies, preparing your development environment for Binance API integration.
Comprehensive Documentation
Complete documentation for the Binance connector is available through ReadTheDocs. The documentation provides detailed information about all classes, methods, parameters, and return values, helping developers understand and implement the library effectively.
👉 Explore comprehensive API documentation
Working with RESTful APIs
The library simplifies interaction with Binance's RESTful APIs through intuitive method calls. Here are some common usage examples:
from binance.spot import Spot
# Initialize client without authentication for public endpoints
client = Spot()
# Retrieve server timestamp
print(client.time())
# Access BTCUSDT klines at 1-minute interval
print(client.klines("BTCUSDT", "1m"))
# Get last 10 klines of BNBUSDT at 1-hour interval
print(client.klines("BNBUSDT", "1h", limit=10))For endpoints requiring authentication, you'll need to provide your API credentials:
# Initialize client with API credentials for private endpoints
client = Spot(api_key='your_api_key', api_secret='your_api_secret')
# Access account information and balances
print(client.account())
# Place a new order with specified parameters
order_params = {
'symbol': 'BTCUSDT',
'side': 'SELL',
'type': 'LIMIT',
'timeInForce': 'GTC',
'quantity': 0.002,
'price': 9500
}
order_response = client.new_order(**order_params)
print(order_response)The examples folder contains additional implementations for various endpoints. To use these examples, create a configuration file with your API keys:
# examples/config.ini
[keys]
api_key=your_actual_api_key
api_secret=your_actual_secret_keyAPI Authentication Methods
Binance supports multiple authentication mechanisms for enhanced security:
# HMAC authentication (most common)
client = Client(api_key, api_secret)
print(client.account())
# RSA key authentication
client = Client(api_key=api_key, private_key=private_key)
print(client.account())
# ED25519 key authentication
api_key = "your_api_key"
private_key = "./private_key.pem"
private_key_pass = "your_password"
with open(private_key, 'rb') as f:
private_key_data = f.read()
spot_client = Client(api_key=api_key, private_key=private_key_data, private_key_pass=private_key_pass)
# Encrypted RSA key authentication
client = Client(api_key=api_key, private_key=private_key, private_key_pass='password')
print(client.account())Testnet Environment
Binance provides a Spot Testnet for developers to test their implementations without using real funds:
from binance.spot import Spot as Client
# Connect to testnet environment
testnet_client = Client(base_url='https://testnet.binance.vision')
print(testnet_client.time())Important testnet considerations:
- Only
/api/*endpoints are available (no/sapi/*endpoints) - No graphical user interface provided
- Requires separate testnet API key registration
Configuration Options
The library offers several configuration parameters to customize API interactions:
Base URL Configuration:
While the library defaults to api.binance.com, you can specify alternative endpoints for better performance:
# Using alternative Binance API endpoints
client = Client(base_url='https://api1.binance.com')
# Or: https://api2.binance.com, https://api3.binance.comParameter Naming Convention:
Method parameters must match the exact naming used in the official API documentation:
# Correct parameter naming (matches API docs)
response = client.cancel_oco_order('BTCUSDT', orderListId=1)
# Incorrect parameter naming (will not work)
response = client.cancel_oco_order('BTCUSDT', order_list_id=1)Receive Window Setting:
The recvWindow parameter specifies the time window for request validity:
from binance.spot import Spot as Client
client = Client(api_key, api_secret)
# Set custom receive window of 10 seconds (default is 5 seconds)
response = client.get_order('BTCUSDT', orderId=11, recvWindow=10000)Timeout Configuration:
Set appropriate timeout values for server responses:
from binance.spot import Spot as Client
# Set timeout to 1 second
client = Client(timeout=1)Time Unit Specification:
Customize timestamp formats in responses:
from binance.spot import Spot as Client
# Retrieve timestamps in microseconds
client = Client(time_unit="microsecond")Proxy Support:
Configure HTTP proxies for API requests:
from binance.spot import Spot as Client
proxies = { 'https': 'http://1.2.3.4:8080' }
client = Client(proxies=proxies)Response Metadata
The library can display API rate limit usage and response headers:
from binance.spot import Spot as Client
# Display rate limit usage information
client = Client(show_limit_usage=True)
print(client.time())
# Display full response headers
client = Client(show_header=True)
print(client.time())Error Handling
The library provides structured error handling for API issues:
Client Errors (4XX responses):
from binance.error import ClientError
try:
client.account()
except ClientError as error:
print(f"Status code: {error.status_code}")
print(f"Error code: {error.error_code}")
print(f"Error message: {error.error_message}")
print(f"Response header: {error.header}")
print(f"Additional data: {error.error_data}")Server Errors (5XX responses):
Server errors indicate issues on Binance's infrastructure and should be handled with appropriate retry logic.
WebSocket Implementation
Connector v3
The latest WebSocket implementation supports both WebSocket API and WebSocket Stream connections:
WebSocket API Client:
from binance.websocket.spot.websocket_api import SpotWebsocketAPIClient
import logging
import time
def message_handler(_, message):
logging.info(message)
# Initialize WebSocket API client
my_client = SpotWebsocketAPIClient(on_message=message_handler)
# Request ticker information
my_client.ticker(symbol="BNBBUSD", type="FULL")
time.sleep(5)
logging.info("Closing WebSocket connection")
my_client.stop()WebSocket Stream Client:
from binance.websocket.spot.websocket_stream import SpotWebsocketStreamClient
import logging
import time
def message_handler(_, message):
logging.info(message)
# Initialize WebSocket Stream client
my_client = SpotWebsocketStreamClient(on_message=message_handler)
# Subscribe to aggregated trade stream
my_client.agg_trade(symbol="bnbusdt")
time.sleep(5)
logging.info("Closing WebSocket connection")
my_client.stop()Advanced WebSocket Features
Time Unit Configuration:
# WebSocket API with microsecond timestamps
my_client = SpotWebsocketAPIClient(on_message=message_handler, time_unit='microsecond')
# WebSocket Stream with microsecond timestamps
my_client = SpotWebsocketStreamClient(on_message=message_handler, time_unit="microsecond")Proxy Support for WebSockets:
# Configure proxy for WebSocket connections
proxies = { 'http': 'http://1.2.3.4:8080' }
# WebSocket API with proxy
my_client = SpotWebsocketAPIClient(on_message=message_handler, proxies=proxies, timeout=10)
# WebSocket Stream with proxy
my_client = SpotWebsocketStreamClient(on_message=message_handler, proxies=proxies, timeout=10)Request Identification:
# Custom request ID
my_client.ping_connectivity(id="my_custom_request_id")
# Auto-generated request ID
my_client.ping_connectivity()Combined Streams:
# Enable combined streams
my_client = SpotWebsocketStreamClient(on_message=message_handler, is_combined=True)Legacy WebSocket Clients (v1 and v2)
from binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient
def message_handler(message):
print(message)
ws_client = WebsocketClient()
ws_client.start()
# Subscribe to mini ticker stream
ws_client.mini_ticker(
symbol='bnbusdt',
id=1,
callback=message_handler,
)
# Combine multiple streams
ws_client.instant_subscribe(
stream=['bnbusdt@bookTicker', 'ethusdt@bookTicker'],
callback=message_handler,
)
ws_client.stop()WebSocket Testnet Connection
from binance.websocket.spot.websocket_client import SpotWebsocketClient as WebsocketClient
# Connect to testnet WebSocket
ws_client = WebsocketClient(stream_url='wss://stream.testnet.binance.vision')Testing and Quality Assurance
The library includes comprehensive test cases to ensure reliability:
# Install test requirements
pip install -r requirements/requirements-test.txt
# Execute test suite
python -m pytest tests/Current Limitations
While the library offers extensive Spot market functionality, it does not currently support:
- Futures APIs (
/fapi/*) - Delivery APIs (
/dapi/*) - Vanilla Options APIs (
/vapi/*) - Associated WebSocket streams for these products
Developers working with these products will need to implement custom solutions or seek alternative libraries.
Contribution Guidelines
The Binance connector project welcomes contributions from the developer community. If you identify bugs or have improvement suggestions, please open an issue on the project repository.
For API-related issues, consider discussing them on the Binance Developer Community forum where Binance's technical team can provide assistance.
👉 Access advanced development tools
Frequently Asked Questions
What is the Binance API Connector for Python?
The Binance API Connector is a lightweight Python library that provides a convenient interface for interacting with Binance's various API services. It simplifies the process of making REST API calls, establishing WebSocket connections, and handling authentication for both public market data and private account operations.
How do I handle authentication with the Binance API?
Binance supports multiple authentication methods including HMAC signatures, RSA keys, and ED25519 cryptography. The library provides straightforward implementations for all these methods. You'll need to generate API keys through your Binance account and then initialize the client with your credentials using your preferred authentication method.
What's the difference between REST API and WebSocket in this library?
The REST API components are used for request-response operations like placing orders or retrieving account information. The WebSocket functionality provides real-time data streams for market updates and user data changes. The library supports both WebSocket API for interactive operations and WebSocket Streams for market data subscriptions.
Can I use this library with the Binance testnet?
Yes, the library fully supports the Binance testnet environment. You can configure the client to connect to testnet endpoints for both REST and WebSocket APIs. This allows you to test your application without using real funds or affecting your production account.
How do I handle API rate limits with this connector?
The library provides built-in functionality to monitor rate limits through response metadata. You can enable the display of limit usage information, which shows how many requests you've made and how close you are to hitting Binance's API rate limits. This helps in implementing appropriate rate-limiting strategies in your application.
What should I do when I encounter errors?
The library categorizes errors into client errors (4XX responses) and server errors (5XX responses). Client errors typically indicate issues with your request parameters or authentication, while server errors suggest temporary issues on Binance's infrastructure. The error objects provide detailed information to help diagnose and resolve these issues.