The unofficial Python client for the Coinbase Advanced Trade API
Project description
cbadvanced
A modern, async-first Python client for the Coinbase Advanced Trade API.
Features
- Async & Sync Support - Both asynchronous and synchronous clients
- Type Hints - Full type annotations with Pydantic models
- Modern Python - Requires Python 3.10+, uses
httpxfor HTTP - Validated Responses - All API responses are validated with Pydantic
- Context Manager Support - Proper resource management with
with/async with
Disclaimer
This is an unofficial library. I am in no way affiliated with Coinbase. Use at your own risk.
Installation
pip install cbadvanced
Or with your preferred package manager:
# Using uv
uv add cbadvanced
# Using poetry
poetry add cbadvanced
Quick Start
Getting API Credentials
- Go to Coinbase Developer Platform
- Create a new API key with "Advanced Trade" permissions
- Save your API key name and private key (PEM format)
Synchronous Usage
from cbadvanced import Client
# Your API credentials
API_KEY = "organizations/your-org/apiKeys/your-key"
API_SECRET = """-----BEGIN EC PRIVATE KEY-----
YOUR PRIVATE KEY HERE
-----END EC PRIVATE KEY-----"""
with Client(key=API_KEY, secret=API_SECRET) as client:
# Get all products
products = client.get_products()
for product in products:
print(f"{product.product_id}: ${product.price}")
# Get account balances
accounts = client.get_accounts()
for account in accounts:
if float(account.available_balance.value) > 0:
print(f"{account.currency}: {account.available_balance.value}")
Asynchronous Usage
import asyncio
from cbadvanced import AsyncClient
async def main():
async with AsyncClient(key=API_KEY, secret=API_SECRET) as client:
# Get BTC-USD price
product = await client.get_product("BTC-USD")
print(f"BTC-USD: ${product.price}")
# Get recent candles
candles = await client.get_candles("BTC-USD")
for candle in candles[:5]:
print(f"Open: {candle['open']}, Close: {candle['close']}")
asyncio.run(main())
API Reference
Client Initialization
Both Client and AsyncClient accept the same parameters:
Client(
key: str, # API key name
secret: str, # PEM-encoded private key
timeout: float = 30.0 # Request timeout in seconds
)
Account Methods
# Get all accounts (wallets)
accounts = client.get_accounts(limit=250, cursor=None)
# Get a specific account
account = client.get_account(account_id="your-account-uuid")
Product Methods
# Get all tradeable products
products = client.get_products(product_type="SPOT", limit=None)
# Get a specific product
product = client.get_product("BTC-USD")
# Get historical candles (OHLCV data)
from cbadvanced import Granularity
from datetime import datetime, timedelta
candles = client.get_candles(
"BTC-USD",
start=datetime.now() - timedelta(days=7), # or Unix timestamp
end=datetime.now(), # or Unix timestamp
granularity=Granularity.ONE_HOUR
)
# Get recent market trades
trades = client.get_market_trades("BTC-USD", limit=100)
print(f"Best bid: {trades.best_bid}, Best ask: {trades.best_ask}")
Order Methods
from cbadvanced import OrderSide
# Create a limit order
response = client.create_order(
product_id="BTC-USD",
side=OrderSide.BUY, # or "BUY"
order_type="limit",
size="0.001", # Amount in base currency (BTC)
price="50000.00" # Limit price in quote currency (USD)
)
if response.success:
print(f"Order created: {response.order_id}")
# Create a market order
response = client.create_order(
product_id="BTC-USD",
side=OrderSide.BUY,
order_type="market",
size="100.00" # Amount in quote currency (USD) for market orders
)
# Get historical orders
orders = client.get_orders(
product_id="BTC-USD", # Optional: filter by product
order_status=["FILLED"], # Optional: filter by status
limit=100
)
# Get a specific order
order = client.get_order("order-id-here")
# Cancel orders
result = client.cancel_orders(["order-id-1", "order-id-2"])
for r in result.results:
print(f"Order {r.order_id}: {'Cancelled' if r.success else r.failure_reason}")
Fill Methods
# Get trade fills (executed orders)
fills = client.get_fills(
product_id="BTC-USD", # Optional
order_id="order-123", # Optional
limit=100
)
for fill in fills:
print(f"Trade {fill.trade_id}: {fill.size} @ ${fill.price}")
Models & Enums
All API responses are validated and returned as Pydantic models:
from cbadvanced import (
# Enums
OrderSide, # BUY, SELL
OrderStatus, # PENDING, OPEN, FILLED, CANCELLED, EXPIRED, FAILED
OrderType, # MARKET, LIMIT, STOP, STOP_LIMIT
Granularity, # ONE_MINUTE, FIVE_MINUTE, FIFTEEN_MINUTE, etc.
TimeInForce, # GTC, GTD, IOC, FOK
# Account models
Account,
Balance,
# Product models
Product,
Candle,
Trade,
# Order models
Order,
CreateOrderResponse,
CancelOrdersResponse,
# Fill models
Fill,
)
Error Handling
The library provides specific exception types:
from cbadvanced import (
CoinbaseError, # Base exception
CoinbaseAPIError, # API returned an error (4xx, 5xx)
CoinbaseAuthError, # Authentication failed
CoinbaseRequestError, # Request/network error
)
try:
product = client.get_product("INVALID-PRODUCT")
except CoinbaseAPIError as e:
print(f"API Error {e.status_code}: {e.message}")
print(f"Error code: {e.error_code}")
print(f"Details: {e.details}")
except CoinbaseRequestError as e:
print(f"Request failed: {e.message}")
Configuration
Environment Variables
Store your credentials securely using environment variables:
import os
from cbadvanced import Client
with Client(
key=os.environ["COINBASE_API_KEY"],
secret=os.environ["COINBASE_API_SECRET"]
) as client:
...
Timeout Configuration
# Set a custom timeout (in seconds)
with Client(key=API_KEY, secret=API_SECRET, timeout=60.0) as client:
...
Development
Setup
# Clone the repository
git clone https://github.com/mlindland/python-cbadvanced.git
cd python-cbadvanced
# Create virtual environment
python -m venv .venv
source .venv/bin/activate # or `.venv\Scripts\activate` on Windows
# Install development dependencies
pip install -e ".[dev]"
Running Tests
# Run all tests
pytest
# Run with coverage
pytest --cov=cbadvanced
# Run specific test file
pytest tests/test_client.py
Code Quality
# Format code
ruff format .
# Lint code
ruff check .
# Type check
mypy cbadvanced
Changelog
See CHANGELOG.md for a list of changes.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Links
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file cbadvanced-3.0.0.tar.gz.
File metadata
- Download URL: cbadvanced-3.0.0.tar.gz
- Upload date:
- Size: 52.0 MB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b95feb254f36eb152a5836bec6f55ec8867d7601cc40f51687105828c5b9ce95
|
|
| MD5 |
8a4125a3ce61d204ffb6468b5c60c176
|
|
| BLAKE2b-256 |
59fd83a4048b4e143ffa76dbd38eba1e22a2ea07a54a43e971ada80f558669d0
|
File details
Details for the file cbadvanced-3.0.0-py3-none-any.whl.
File metadata
- Download URL: cbadvanced-3.0.0-py3-none-any.whl
- Upload date:
- Size: 15.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7d0cea87f8d89a023bdd11164cdfb6c8d55aaebca98a6499cee361a302de374b
|
|
| MD5 |
5d39fc8a5bd8a74be00a0dd14c7a7c92
|
|
| BLAKE2b-256 |
00fc62ef044bf224f9243bb5ef051420f795405fed7a7b44abaa108f070cd745
|