CCXT
CCXT (Cryptocurrency eXchange Trading Library) is a JavaScript / TypeScript / Python / C# / PHP / Go library providing a unified API for connecting to and trading with over 100 cryptocurrency exchanges worldwide. It offers quick access to market data (tickers, order books, OHLCV, trade history) and enables algorithmic trading functionalities like placing market/limit orders, managing balances, and handling deposits/withdrawals. The library is actively maintained with frequent updates and new exchange integrations.
Warnings
- gotcha Always enable and configure rate limiting to avoid being banned by exchanges. Set `enableRateLimit: True` and adjust `rateLimit` (in milliseconds) as needed, especially for high-frequency operations. Default `rateLimit` values may not always prevent issues with aggressive API usage.
- gotcha Handle API keys and secrets securely. Never hardcode them directly in your script, especially when using private API methods. Use environment variables or a secure configuration management system.
- gotcha Differentiate between synchronous (`import ccxt`) and asynchronous (`import ccxt.async_support as ccxt`) imports. Using asynchronous methods (e.g., `await exchange.fetch_ticker`) requires the `async_support` module and an `asyncio` event loop. Mixing them without proper handling will lead to runtime errors.
- gotcha Implement robust error handling for network and exchange-specific issues. API calls can fail due to network problems, exchange-specific errors (e.g., invalid symbol, insufficient funds), or rate limits.
- breaking While CCXT aims for a unified interface, underlying exchange APIs frequently change. These changes, though often abstracted, can sometimes lead to unexpected behavior or require minor adjustments to your code (e.g., changes in error messages, supported parameters, or data formats for specific exchanges).
- gotcha CCXT.Pro, a distinct (though integrated) part of the library, provides WebSocket APIs for real-time, high-frequency trading. It has different `watch*` methods and incremental data structures. The standard CCXT library primarily uses REST APIs.
Install
-
pip install ccxt
Imports
- ccxt
import ccxt
- ccxt.async_support
import ccxt.async_support as ccxt
Quickstart
import ccxt
import os
exchange_id = 'binance'
exchange_class = getattr(ccxt, exchange_id)
# Public API access (no API keys needed for public data)
exchange = exchange_class({
'rateLimit': 1200,
'enableRateLimit': True, # Important for respecting exchange limits
})
try:
# Fetch ticker for a symbol
symbol = 'BTC/USDT'
ticker = exchange.fetch_ticker(symbol)
print(f"Fetched ticker for {symbol} on {exchange_id}: {ticker['last']} (last price)")
# For private API, uncomment and replace with actual keys (use environment variables in production)
# exchange_private = exchange_class({
# 'apiKey': os.environ.get('CCXT_BINANCE_API_KEY', ''),
# 'secret': os.environ.get('CCXT_BINANCE_SECRET', ''),
# 'rateLimit': 1200,
# 'enableRateLimit': True,
# })
# if exchange_private.apiKey and exchange_private.secret:
# balance = exchange_private.fetch_balance()
# print(f"Fetched balance for {exchange_id}: {balance['total']}")
except ccxt.NetworkError as e:
print(f"Network error: {type(e).__name__} {str(e)}")
except ccxt.ExchangeError as e:
print(f"Exchange error: {type(e).__name__} {str(e)}")
except Exception as e:
print(f"An unexpected error occurred: {type(e).__name__} {str(e)}")