Unofficial Python wrapper for the Binance cryptocurrency exchange REST API v3 and WebSocket APIs with comprehensive trading, market data, and account management functionality
npx @tessl/cli install tessl/pypi-python-binance@1.0.0An unofficial Python wrapper for the Binance cryptocurrency exchange REST API v3 and WebSocket APIs. This library provides comprehensive access to Binance's trading, market data, wallet, and account management endpoints through both synchronous and asynchronous implementations with built-in authentication, error handling, and connection management.
pip install python-binancefrom binance import Client, AsyncClientFor WebSocket streaming:
from binance import BinanceSocketManager, ThreadedWebsocketManagerFor depth caching:
from binance import DepthCacheManager, ThreadedDepthCacheManagerFor constants and enums:
from binance import * # Imports all constants, enums, and exceptionsfrom binance import Client
# Initialize client with API credentials
client = Client(api_key='your_api_key', api_secret='your_api_secret')
# Get account information
account = client.get_account()
print(f"Account balances: {account['balances']}")
# Get current market price
ticker = client.get_symbol_ticker(symbol="BTCUSDT")
print(f"BTC price: {ticker['price']}")
# Place a test order (no actual trade)
order = client.create_test_order(
symbol='BTCUSDT',
side='BUY',
type='MARKET',
quantity=0.001
)
# Get recent trades
trades = client.get_recent_trades(symbol='BTCUSDT', limit=10)import asyncio
from binance import AsyncClient
async def main():
# Initialize async client
client = await AsyncClient.create(api_key='your_api_key', api_secret='your_api_secret')
# Get market data
tickers = await client.get_all_tickers()
print(f"Total symbols: {len(tickers)}")
# Close the client
await client.close_connection()
# Run async function
asyncio.run(main())import asyncio
from binance import AsyncClient, BinanceSocketManager
async def handle_socket_message(msg):
print(f"Received: {msg}")
async def main():
client = await AsyncClient.create()
bm = BinanceSocketManager(client)
# Start kline (candlestick) stream
ts = bm.kline_socket(symbol='BTCUSDT', interval='1m')
async with ts as tscm:
while True:
res = await tscm.recv()
await handle_socket_message(res)
asyncio.run(main())Python-binance follows a layered architecture:
The library supports all Binance API endpoints across spot, margin, futures, and options trading, with consistent interfaces and automatic timestamp management.
Core synchronous and asynchronous REST API clients for interacting with all Binance endpoints. Provides 760+ methods covering spot trading, futures, margin, options, and account management with built-in authentication and error handling.
class Client:
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,
): ...
class AsyncClient:
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,
): ...Comprehensive market data access including tickers, order books, trade history, klines/candlesticks, and price statistics. Supports both spot and derivatives markets with real-time and historical data retrieval.
def get_exchange_info(self) -> Dict: ...
def get_all_tickers(self) -> List[Dict[str, str]]: ...
def get_order_book(self, **params) -> Dict: ...
def get_recent_trades(self, **params) -> Dict: ...
def get_klines(self, **params) -> Dict: ...
def get_historical_klines(
self,
symbol: str,
interval: str,
start_str: str,
end_str: Optional[str] = None,
limit: int = 1000,
klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT,
) -> List[List]: ...Complete trading functionality including order placement, management, and execution across spot, margin, futures, and options markets. Supports all order types with comprehensive status tracking and modification capabilities.
def create_order(self, **params): ...
def order_limit(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params): ...
def order_market(self, **params): ...
def create_oco_order(self, **params): ...
def get_order(self, **params): ...
def cancel_order(self, **params): ...
def get_open_orders(self, **params): ...Account information, balance management, trade history, and API permissions. Includes wallet operations, asset transfers, and comprehensive account status monitoring.
def get_account(self, **params): ...
def get_asset_balance(self, asset=None, **params): ...
def get_my_trades(self, **params): ...
def get_account_status(self, version=1, **params): ...
def get_account_api_trading_status(self, **params): ...
def get_account_api_permissions(self, **params): ...Real-time market data and account update streaming with automatic connection management, reconnection logic, and message queuing. Supports all Binance WebSocket streams including user data, market data, and futures streams.
class BinanceSocketManager:
def __init__(
self,
client: AsyncClient,
user_timeout=KEEPALIVE_TIMEOUT,
max_queue_size: int = 100,
): ...
def symbol_ticker_socket(self, symbol: str): ...
def all_ticker_socket(self): ...
def kline_socket(self, symbol: str, interval: str): ...
def depth_socket(self, symbol: str, depth: Optional[str] = None): ...
def user_socket(self): ...
class ThreadedWebsocketManager:
def start(self): ...
def stop(self): ...
def start_symbol_ticker_socket(self, callback, symbol: str): ...
def start_kline_socket(self, callback, symbol: str, interval: str): ...Efficient real-time order book management with automatic synchronization from WebSocket streams. Provides sorted bid/ask access and maintains consistent order book state with configurable precision and conversion types.
class DepthCacheManager:
def __init__(
self,
client: AsyncClient,
symbol: str,
refresh_interval: Optional[int] = None,
bm: Optional[BinanceSocketManager] = None,
limit: int = 500,
conv_type: Callable = float
): ...
class DepthCache:
def __init__(self, symbol, conv_type: Callable = float): ...
def add_bid(self, bid): ...
def add_ask(self, ask): ...
def get_bids(self): ...
def get_asks(self): ...
def get_top_bids(self, k: int): ...
def get_top_asks(self, k: int): ...Complete futures trading functionality for both USD-margined and coin-margined futures. Includes position management, leverage control, funding rate information, and specialized futures order types.
def futures_get_exchange_info(self): ...
def futures_create_order(self, **params): ...
def futures_account(self, **params): ...
def futures_account_balance(self, **params): ...
def futures_position_information(self, **params): ...
def futures_change_leverage(self, **params): ...
def futures_change_margin_type(self, **params): ...Cross-margin and isolated margin trading with loan management, interest calculations, and margin-specific order types. Supports margin asset transfers and comprehensive margin account monitoring.
def get_margin_account(self, **params): ...
def get_isolated_margin_account(self, **params): ...
def create_margin_order(self, **params): ...
def create_margin_loan(self, **params): ...
def repay_margin_loan(self, **params): ...
def get_margin_interest_history(self, **params): ...Asset conversion functionality for instant and limit conversions between cryptocurrencies. Provides quote-based conversions, limit order conversions, and comprehensive conversion history tracking across spot, margin, and futures accounts.
def convert_request_quote(self, **params): ...
def convert_accept_quote(self, **params): ...
def get_convert_trade_history(self, **params): ...
def margin_v1_get_convert_exchange_info(self, **params): ...
def margin_v1_post_convert_limit_place_order(self, **params): ...
def futures_v1_post_convert_get_quote(self, **params): ...Comprehensive staking and mining functionality including DeFi staking, ETH/SOL staking, locked staking products, and mining operations. Provides access to staking rewards, mining statistics, and portfolio management across various blockchain networks.
def get_staking_product_list(self, **params): ...
def purchase_staking_product(self, **params): ...
def redeem_staking_product(self, **params): ...
def get_staking_position(self, **params): ...
def margin_v2_post_eth_staking_eth_stake(self, **params): ...
def margin_v1_post_sol_staking_sol_stake(self, **params): ...# Order Types
ORDER_TYPE_LIMIT = "LIMIT"
ORDER_TYPE_MARKET = "MARKET"
ORDER_TYPE_STOP_LOSS = "STOP_LOSS"
ORDER_TYPE_STOP_LOSS_LIMIT = "STOP_LOSS_LIMIT"
ORDER_TYPE_TAKE_PROFIT = "TAKE_PROFIT"
ORDER_TYPE_TAKE_PROFIT_LIMIT = "TAKE_PROFIT_LIMIT"
ORDER_TYPE_LIMIT_MAKER = "LIMIT_MAKER"
# Futures Order Types
FUTURE_ORDER_TYPE_LIMIT = "LIMIT"
FUTURE_ORDER_TYPE_MARKET = "MARKET"
FUTURE_ORDER_TYPE_STOP = "STOP"
FUTURE_ORDER_TYPE_STOP_MARKET = "STOP_MARKET"
FUTURE_ORDER_TYPE_TAKE_PROFIT = "TAKE_PROFIT"
FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET = "TAKE_PROFIT_MARKET"
FUTURE_ORDER_TYPE_LIMIT_MAKER = "LIMIT_MAKER"
FUTURE_ORDER_TYPE_TRAILING_STOP_MARKET = "TRAILING_STOP_MARKET"
# Time in Force
TIME_IN_FORCE_GTC = "GTC" # Good till cancelled
TIME_IN_FORCE_IOC = "IOC" # Immediate or cancel
TIME_IN_FORCE_FOK = "FOK" # Fill or kill
TIME_IN_FORCE_GTX = "GTX" # Post only order
TIME_IN_FORCE_GTD = "GTD" # Good till date
# Order Sides
SIDE_BUY = "BUY"
SIDE_SELL = "SELL"
# Order Status
ORDER_STATUS_NEW = "NEW"
ORDER_STATUS_PARTIALLY_FILLED = "PARTIALLY_FILLED"
ORDER_STATUS_FILLED = "FILLED"
ORDER_STATUS_CANCELED = "CANCELED"
ORDER_STATUS_PENDING_CANCEL = "PENDING_CANCEL"
ORDER_STATUS_REJECTED = "REJECTED"
ORDER_STATUS_EXPIRED = "EXPIRED"
# Order Response Types
ORDER_RESP_TYPE_ACK = "ACK"
ORDER_RESP_TYPE_RESULT = "RESULT"
ORDER_RESP_TYPE_FULL = "FULL"
# Side Effect Types
NO_SIDE_EFFECT_TYPE = "NO_SIDE_EFFECT"
MARGIN_BUY_TYPE = "MARGIN_BUY"
AUTO_REPAY_TYPE = "AUTO_REPAY"
# Kline Intervals
KLINE_INTERVAL_1SECOND = "1s"
KLINE_INTERVAL_1MINUTE = "1m"
KLINE_INTERVAL_3MINUTE = "3m"
KLINE_INTERVAL_5MINUTE = "5m"
KLINE_INTERVAL_15MINUTE = "15m"
KLINE_INTERVAL_30MINUTE = "30m"
KLINE_INTERVAL_1HOUR = "1h"
KLINE_INTERVAL_2HOUR = "2h"
KLINE_INTERVAL_4HOUR = "4h"
KLINE_INTERVAL_6HOUR = "6h"
KLINE_INTERVAL_8HOUR = "8h"
KLINE_INTERVAL_12HOUR = "12h"
KLINE_INTERVAL_1DAY = "1d"
KLINE_INTERVAL_3DAY = "3d"
KLINE_INTERVAL_1WEEK = "1w"
KLINE_INTERVAL_1MONTH = "1M"
# WebSocket Depth Levels
WEBSOCKET_DEPTH_5 = "5"
WEBSOCKET_DEPTH_10 = "10"
WEBSOCKET_DEPTH_20 = "20"
class HistoricalKlinesType(Enum):
SPOT = 1
FUTURES = 2
FUTURES_COIN = 3
FUTURES_MARK_PRICE = 4
FUTURES_INDEX_PRICE = 5
FUTURES_COIN_MARK_PRICE = 6
FUTURES_COIN_INDEX_PRICE = 7
class FuturesType(Enum):
USD_M = 1
COIN_M = 2
class ContractType(Enum):
PERPETUAL = "perpetual"
CURRENT_QUARTER = "current_quarter"
NEXT_QUARTER = "next_quarter"
class BinanceSocketType(str, Enum):
SPOT = "Spot"
USD_M_FUTURES = "USD_M_Futures"
COIN_M_FUTURES = "Coin_M_Futures"
OPTIONS = "Vanilla_Options"
ACCOUNT = "Account"class BinanceAPIException(Exception):
def __init__(self, response, status_code, text): ...
class BinanceRequestException(Exception):
def __init__(self, message): ...
class BinanceOrderException(Exception):
def __init__(self, code, message): ...
class BinanceOrderMinAmountException(BinanceOrderException): ...
class BinanceOrderMinPriceException(BinanceOrderException): ...
class BinanceOrderMinTotalException(BinanceOrderException): ...
class BinanceOrderUnknownSymbolException(BinanceOrderException): ...
class BinanceOrderInactiveSymbolException(BinanceOrderException): ...
class BinanceWebsocketUnableToConnect(Exception): ...
class BinanceWebsocketQueueOverflow(Exception): ...
class BinanceWebsocketClosed(Exception): ...
class NotImplementedException(Exception): ...
class UnknownDateFormat(Exception): ...def date_to_milliseconds(date_str: str) -> int: ...
def interval_to_milliseconds(interval: str) -> Optional[int]: ...
def convert_ts_str(ts_str): ...
def convert_list_to_json_array(list_items): ...
def get_loop(): ...