The Coinbase Advanced API Python SDK empowers developers to seamlessly integrate with one of the most powerful cryptocurrency trading platforms available today. Whether you're building algorithmic trading bots, real-time market dashboards, or portfolio management tools, this SDK provides the essential infrastructure for connecting to both REST and WebSocket APIs offered by Coinbase Advanced Trade.
Designed with simplicity and scalability in mind, the SDK streamlines authentication, request handling, and data parsing—allowing developers to focus on strategy and application logic rather than low-level API intricacies.
👉 Discover how to supercharge your crypto trading applications with advanced API tools.
Getting Started with Installation
To begin using the SDK, install it via pip:
pip3 install coinbase-advanced-pyThis lightweight package supports Python 3.8 and above and is regularly updated to align with Coinbase’s evolving API standards. Once installed, you can immediately start importing core modules like RESTClient and WSClient to interact with market data and execute trades programmatically.
Setting Up Your CDP API Credentials
To access private endpoints and authenticated WebSocket channels, you must generate a Cloud Developer Platform (CDP) API key and secret from your Coinbase account dashboard.
Navigate to the Coinbase CDP portal to create your credentials. Upon generation, you’ll receive:
- An API key ID (e.g.,
organizations/{org_id}/apiKeys/{key_id}) - An EC private key in PEM format
⚠️ Security Note: Never hardcode your API secret directly into source files. Instead, use environment variables or a secure secrets manager.
You can securely load credentials using environment variables:
export COINBASE_API_KEY="organizations/{org_id}/apiKeys/{key_id}"
export COINBASE_API_SECRET="-----BEGIN EC PRIVATE KEY-----\nYOUR PRIVATE KEY\n-----END EC PRIVATE KEY-----\n"Then initialize the client without passing credentials explicitly:
from coinbase.rest import RESTClient
client = RESTClient()Alternatively, pass keys directly or use a JSON key file:
client = RESTClient(api_key="...", api_secret="...")
# Or load from file
client = RESTClient(key_file="path/to/cdp_api_key.json")Interacting with the REST API
The RESTClient class gives full access to Coinbase's brokerage endpoints for account management, order execution, and market data retrieval.
Key Use Cases
Fetch Account Balances
accounts = client.get_accounts()
print(accounts.accounts[0].available_balance)Place a Market Buy Order
order = client.market_order_buy(
client_order_id="unique_order_123",
product_id="BTC-USD",
quote_size="10" # Spend $10
)
print(order.status)TIP: Leave client_order_id blank to auto-generate a unique ID per request—but be cautious about accidental duplicate orders.
Custom Response Objects & Data Access
Responses are returned as structured Python objects. Use dot notation for defined fields:
product = client.get_product("BTC-USD")
print(product.price) # Direct accessFor nested or undefined fields, fall back to dictionary-style access:
print(accounts.accounts[0].available_balance['value'])Flexible Parameter Handling
Pass additional parameters using **kwargs. This ensures compatibility with future API updates:
kwargs = {"limit": 50, "order": "desc"}
products = client.list_products(**kwargs)Generic HTTP Methods for Advanced Control
For endpoints not yet wrapped by dedicated methods, use generic calls:
trades = client.get("/api/v3/brokerage/products/BTC-USD/ticker", params={"limit": 5})
portfolio = client.post("/api/v3/brokerage/portfolios", data={"name": "MyPortfolio"})However, prefer built-in methods when available—they offer better type safety and error handling.
Rate Limit Awareness
Enable rate limit headers in responses by initializing with rate_limit_headers=True:
client = RESTClient(rate_limit_headers=True)This appends headers like X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset directly into the response body for easy monitoring.
Real-Time Data via WebSocket API
For real-time price feeds, order book updates, and user activity streams, the WSClient connects to Coinbase’s low-latency WebSocket server.
Basic Connection Setup
from coinbase.websocket import WSClient
def on_message(msg):
print("Received:", msg)
client = WSClient(
api_key="...",
api_secret="...",
on_message=on_message
)Subscribe to Market Channels
Connect and subscribe to public channels like ticker or heartbeat:
client.open()
client.subscribe(product_ids=["BTC-USD"], channels=["ticker"])
time.sleep(10)
client.close()Or use channel-specific shortcuts:
client.ticker(product_ids=["ETH-USD"])Auto-Reconnection & Resilience
By default, the client uses exponential backoff with up to 5 retry attempts if the connection drops. Disable automatic retries if implementing custom logic:
client = WSClient(retry=False)Handle disconnections gracefully using exception-aware loops:
try:
client.run_forever_with_exception_check()
except WSClientConnectionClosedException:
print("Reconnecting in 20 seconds...")
time.sleep(20)
connect_and_subscribe()Simplified Message Parsing with WebsocketResponse
Parse incoming messages into structured objects:
from coinbase.websocket import WebsocketResponse
def on_message(msg):
ws_msg = WebsocketResponse(json.loads(msg))
if ws_msg.channel == "ticker":
for event in ws_msg.events:
for ticker in event.tickers:
print(f"{ticker.product_id}: {ticker.price}")Always validate the channel type before accessing nested fields to prevent runtime errors.
Public Endpoints Without Authentication
Both REST and WebSocket clients support unauthenticated access to public data:
Public REST Calls
client = RESTClient() # No keys needed
products = client.get_public_products()Useful for fetching product lists, ticker data, and historical rates without exposing sensitive keys.
Public WebSocket Feeds
client = WSClient(on_message=on_message)
client.ticker(product_ids=["BTC-USD"])Most WebSocket channels are public by default. However, authenticated channels like user or futures_balance_summary require valid CDP credentials.
👉 Access real-time crypto data streams securely and efficiently.
Debugging and Logging
Enable verbose logging during development:
rest_client = RESTClient(verbose=True)
ws_client = WSClient(on_message=on_message, verbose=True)This logs request/response cycles, connection states, and internal errors—critical for troubleshooting integration issues.
Authentication Deep Dive
While the SDK handles JWT creation automatically, advanced users can generate tokens manually:
REST JWT Token
from coinbase import jwt_generator
jwt_uri = jwt_generator.format_jwt_uri("POST", "/api/v3/brokerage/orders")
jwt = jwt_generator.build_rest_jwt(jwt_uri, api_key, api_secret)
# Use in header: "Authorization: Bearer <jwt>"WebSocket JWT Token
ws_jwt = jwt_generator.build_ws_jwt(api_key, api_secret)
# Include in subscription messages under "jwt" fieldManual token generation is useful for cross-platform integrations or debugging authentication failures.
Core Keywords
Coinbase Advanced API, Python SDK, REST API, WebSocket API, crypto trading, market data, order execution, API integration
Frequently Asked Questions
Q: Can I use this SDK without an API key?
A: Yes—for public endpoints only. Accessing account balances or placing orders requires authenticated CDP keys.
Q: How do I avoid rate limiting?
A: Authenticate your requests—they receive higher rate limits. Monitor X-RateLimit-* headers and implement throttling logic when nearing limits.
Q: Is automatic reconnection built into the WebSocket client?
A: Yes. The client retries up to 5 times using exponential backoff. You can disable this and implement custom retry logic if needed.
Q: What’s the difference between get_product and get_public_products?
A: Both return similar data, but get_product requires authentication while get_public_products does not. Use the latter for public-facing apps.
Q: Can I run multiple WebSocket subscriptions simultaneously?
A: Yes. Subscribe to multiple products and channels (e.g., ticker, level2, user) in a single connection.
Q: How do I handle exceptions in async WebSocket operations?
A: Use run_forever_with_exception_check() or sleep_with_exception_check() to catch exceptions raised in background threads.
Ready to take your algorithmic trading to the next level?
👉 Start building smarter trading strategies with powerful API-driven tools today.