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

market-data.mddocs/

Market Data

Comprehensive market data access including exchange information, tickers, order books, trade history, and kline/candlestick data. All methods work with both synchronous and asynchronous clients.

Capabilities

Exchange Information

Get trading rules, symbols, and exchange metadata.

def get_exchange_info(self) -> Dict: ...
def get_symbol_info(self, symbol) -> Optional[Dict]: ...
def get_products(self) -> Dict: ...

Usage Example

# Get complete exchange information
exchange_info = client.get_exchange_info()

# Filter for USDT pairs
usdt_symbols = [s for s in exchange_info['symbols'] if s['quoteAsset'] == 'USDT']
print(f"USDT pairs: {len(usdt_symbols)}")

# Get specific symbol information
btc_info = client.get_symbol_info('BTCUSDT')
if btc_info:
    print(f"BTC filters: {btc_info['filters']}")

Price Tickers

Current price information and 24hr statistics.

def get_all_tickers(self) -> List[Dict[str, str]]: ...
def get_ticker(self, **params): ...
def get_symbol_ticker(self, **params): ...
def get_symbol_ticker_window(self, **params): ...
def get_orderbook_ticker(self, **params): ...
def get_orderbook_tickers(self, **params) -> Dict: ...

Usage Example

# Get all 24hr price tickers
all_tickers = client.get_all_tickers()
btc_ticker = next(t for t in all_tickers if t['symbol'] == 'BTCUSDT')
print(f"BTC price: {btc_ticker['price']}")

# Get specific symbol ticker with 24hr stats
btc_stats = client.get_ticker(symbol='BTCUSDT')
print(f"24hr change: {btc_stats['priceChangePercent']}%")

# Get order book ticker (best bid/ask)
orderbook_ticker = client.get_orderbook_ticker(symbol='BTCUSDT')
print(f"Best bid: {orderbook_ticker['bidPrice']}, Best ask: {orderbook_ticker['askPrice']}")

# Get custom window ticker
window_ticker = client.get_symbol_ticker_window(symbol='BTCUSDT', windowSize='1d')

Order Book Data

Market depth and order book information.

def get_order_book(self, **params) -> Dict: ...
def get_avg_price(self, **params): ...

Usage Example

# Get order book with default depth (100)
order_book = client.get_order_book(symbol='BTCUSDT')
print(f"Top bid: {order_book['bids'][0]}")
print(f"Top ask: {order_book['asks'][0]}")

# Get order book with specific depth
deep_book = client.get_order_book(symbol='BTCUSDT', limit=1000)

# Get average price over last 5 minutes
avg_price = client.get_avg_price(symbol='BTCUSDT')
print(f"5min avg price: {avg_price['price']}")

Trade Data

Recent and historical trade information.

def get_recent_trades(self, **params) -> Dict: ...
def get_historical_trades(self, **params) -> Dict: ...
def get_aggregate_trades(self, **params) -> Dict: ...
def aggregate_trade_iter(self, symbol: str, start_str=None, last_id=None): ...

Usage Example

# Get recent trades (no API key required)
recent_trades = client.get_recent_trades(symbol='BTCUSDT', limit=10)
for trade in recent_trades:
    print(f"Price: {trade['price']}, Qty: {trade['qty']}, Time: {trade['time']}")

# Get historical trades (requires API key)
historical_trades = client.get_historical_trades(symbol='BTCUSDT', limit=100)

# Get aggregate trades with time range
agg_trades = client.get_aggregate_trades(
    symbol='BTCUSDT',
    startTime=1609459200000,  # Timestamp in milliseconds
    endTime=1609462800000,
    limit=500
)

# Iterate through aggregate trades
for agg_trade in client.aggregate_trade_iter(symbol='BTCUSDT', start_str='1 day ago UTC'):
    print(f"Agg trade: {agg_trade}")
    if len(processed_trades) > 1000:  # Limit iteration
        break

Kline/Candlestick Data

Historical and current kline data with various intervals.

def get_klines(self, **params) -> Dict: ...
def get_ui_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]: ...
def get_historical_klines_generator(
    self,
    symbol: str,
    interval: str,
    start_str: str,
    end_str: Optional[str] = None,
    limit: int = 1000,
    klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT,
): ...

Usage Example

from binance import KLINE_INTERVAL_1HOUR, HistoricalKlinesType

# Get recent klines
klines = client.get_klines(
    symbol='BTCUSDT',
    interval=KLINE_INTERVAL_1HOUR,
    limit=24  # Last 24 hours
)

# Each kline contains: [timestamp, open, high, low, close, volume, close_time, ...]
for kline in klines:
    timestamp, open_price, high, low, close, volume = kline[:6]
    print(f"Time: {timestamp}, OHLC: {open_price}/{high}/{low}/{close}, Vol: {volume}")

# Get historical klines with date strings
historical_klines = client.get_historical_klines(
    symbol='BTCUSDT',
    interval=KLINE_INTERVAL_1HOUR,
    start_str='1 Jan 2024',
    end_str='2 Jan 2024'
)

# Get futures klines
futures_klines = client.get_historical_klines(
    symbol='BTCUSDT',
    interval=KLINE_INTERVAL_1HOUR,
    start_str='1 day ago UTC',
    klines_type=HistoricalKlinesType.FUTURES
)

# Use generator for large datasets to avoid memory issues
kline_generator = client.get_historical_klines_generator(
    symbol='BTCUSDT',
    interval=KLINE_INTERVAL_1HOUR,
    start_str='1 week ago UTC'
)

for kline_batch in kline_generator:
    # Process batch of klines
    print(f"Processing {len(kline_batch)} klines")

System Status

Server connectivity and system status information.

def ping(self) -> Dict: ...
def get_server_time(self) -> Dict: ...
def get_system_status(self): ...

Usage Example

# Test connectivity
ping_result = client.ping()
print("Connection successful" if ping_result == {} else "Connection failed")

# Get server time
server_time = client.get_server_time()
print(f"Server timestamp: {server_time['serverTime']}")

# Check system status
system_status = client.get_system_status()
print(f"System status: {system_status['status']}")  # 0 = normal, 1 = maintenance

Advanced Market Data Options

Futures Market Data

# Get futures exchange info
futures_info = client.futures_get_exchange_info()

# Get futures tickers
futures_tickers = client.futures_get_all_tickers()

# Get futures order book
futures_book = client.futures_get_order_book(symbol='BTCUSDT')

# Get funding rate
funding_rate = client.futures_funding_rate(symbol='BTCUSDT')

Options Market Data

# Get options exchange info
options_info = client.options_get_exchange_info()

# Get options index price
index_price = client.options_get_index_price(underlying='BTC')

# Get options mark price
mark_price = client.options_get_mark_price(symbol='BTC-240329-70000-C')

Data Types and Structures

Kline Data Structure

Each kline is a list with the following structure:

[
    1609459200000,      # Open time (timestamp)
    "29000.00000000",   # Open price
    "29500.00000000",   # High price  
    "28800.00000000",   # Low price
    "29200.00000000",   # Close price
    "100.50000000",     # Volume
    1609462799999,      # Close time (timestamp)
    "2950000.00000000", # Quote asset volume
    1000,               # Number of trades
    "50.25000000",      # Taker buy base asset volume
    "1475000.00000000", # Taker buy quote asset volume
    "0"                 # Ignore
]

Ticker Data Structure

24hr ticker statistics:

{
    "symbol": "BTCUSDT",
    "priceChange": "200.00000000",
    "priceChangePercent": "0.69",
    "weightedAvgPrice": "29100.50000000",
    "prevClosePrice": "29000.00000000",
    "lastPrice": "29200.00000000",
    "lastQty": "0.10000000",
    "bidPrice": "29199.00000000",
    "askPrice": "29201.00000000",
    "openPrice": "29000.00000000",
    "highPrice": "29500.00000000",
    "lowPrice": "28800.00000000",
    "volume": "1000.50000000",
    "quoteVolume": "29150000.00000000",
    "openTime": 1609459200000,
    "closeTime": 1609545599999,
    "firstId": 100000,
    "lastId": 200000,
    "count": 100001
}

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