0
# CBPro
1
2
The unofficial Python client for the Coinbase Pro API providing comprehensive access to cryptocurrency trading, market data, and account management. This library enables developers to build automated trading systems, portfolio management tools, and market analysis applications with full access to Coinbase Pro's trading infrastructure.
3
4
## Package Information
5
6
- **Package Name**: cbpro
7
- **Language**: Python
8
- **Installation**: `pip install cbpro`
9
10
## Core Imports
11
12
```python
13
import cbpro
14
```
15
16
Direct class imports:
17
18
```python
19
from cbpro import PublicClient, AuthenticatedClient, WebsocketClient, OrderBook, CBProAuth
20
```
21
22
## Basic Usage
23
24
```python
25
import cbpro
26
27
# Public market data access
28
public_client = cbpro.PublicClient()
29
30
# Get all available trading pairs
31
products = public_client.get_products()
32
print(f"Available products: {len(products)}")
33
34
# Get current price for BTC-USD
35
ticker = public_client.get_product_ticker('BTC-USD')
36
print(f"BTC-USD price: ${ticker['price']}")
37
38
# Get order book
39
order_book = public_client.get_product_order_book('BTC-USD', level=1)
40
print(f"Best bid: ${order_book['bids'][0][0]}")
41
print(f"Best ask: ${order_book['asks'][0][0]}")
42
43
# Authenticated trading (requires API credentials)
44
auth_client = cbpro.AuthenticatedClient(key, b64secret, passphrase)
45
46
# Get account balances
47
accounts = auth_client.get_accounts()
48
for account in accounts:
49
if float(account['balance']) > 0:
50
print(f"{account['currency']}: {account['balance']}")
51
52
# Place a limit buy order
53
order = auth_client.place_limit_order(
54
product_id='BTC-USD',
55
side='buy',
56
price='30000.00',
57
size='0.001'
58
)
59
print(f"Order placed: {order['id']}")
60
```
61
62
## Architecture
63
64
CBPro is organized around five main components that provide comprehensive access to Coinbase Pro's API:
65
66
- **PublicClient**: Access to public market data, product information, and historical data without authentication
67
- **AuthenticatedClient**: Full trading functionality including order management, account access, and private data (inherits from PublicClient)
68
- **WebsocketClient**: Real-time streaming of market data, order updates, and account changes via WebSocket connections
69
- **OrderBook**: Automated maintenance of real-time order book state from WebSocket messages
70
- **CBProAuth**: Authentication handler for securing API requests with HMAC-SHA256 signatures
71
72
This design enables everything from simple market data queries to sophisticated trading systems with real-time data processing and automated order book maintenance.
73
74
## Capabilities
75
76
### Public Market Data
77
78
Access to all public Coinbase Pro endpoints including products, order books, trade history, candlestick data, and market statistics. No authentication required.
79
80
```python { .api }
81
class PublicClient:
82
def __init__(self, api_url: str = 'https://api.pro.coinbase.com', timeout: int = 30): ...
83
def get_products(self) -> list: ...
84
def get_product_order_book(self, product_id: str, level: int = 1) -> dict: ...
85
def get_product_ticker(self, product_id: str) -> dict: ...
86
def get_product_trades(self, product_id: str, before: str = '', after: str = '', limit: int = None, result: list = None): ...
87
def get_product_historic_rates(self, product_id: str, start: str = None, end: str = None, granularity: int = None) -> list: ...
88
def get_product_24hr_stats(self, product_id: str) -> dict: ...
89
def get_currencies(self) -> list: ...
90
def get_time(self) -> dict: ...
91
```
92
93
[Public Market Data](./public-client.md)
94
95
### Authenticated Trading
96
97
Complete trading functionality including order placement, cancellation, account management, funding operations, and private data access. Requires API credentials.
98
99
```python { .api }
100
class AuthenticatedClient(PublicClient):
101
def __init__(self, key: str, b64secret: str, passphrase: str, api_url: str = "https://api.pro.coinbase.com"): ...
102
def get_accounts(self) -> list: ...
103
def get_account(self, account_id: str) -> dict: ...
104
def get_account_history(self, account_id: str, **kwargs): ...
105
def place_limit_order(self, product_id: str, side: str, price: str, size: str, **kwargs) -> dict: ...
106
def place_market_order(self, product_id: str, side: str, size: str = None, funds: str = None, **kwargs) -> dict: ...
107
def place_stop_order(self, product_id: str, stop_type: str, price: str, **kwargs) -> dict: ...
108
def cancel_order(self, order_id: str) -> list: ...
109
def cancel_all(self, product_id: str = None) -> list: ...
110
def get_orders(self, product_id: str = None, status: str = None, **kwargs): ...
111
def get_fills(self, product_id: str = None, order_id: str = None, **kwargs): ...
112
def deposit(self, amount: str, currency: str, payment_method_id: str) -> dict: ...
113
def coinbase_deposit(self, amount: str, currency: str, coinbase_account_id: str) -> dict: ...
114
def withdraw(self, amount: str, currency: str, payment_method_id: str) -> dict: ...
115
def coinbase_withdraw(self, amount: str, currency: str, coinbase_account_id: str) -> dict: ...
116
def crypto_withdraw(self, amount: str, currency: str, crypto_address: str) -> dict: ...
117
def get_fees(self) -> dict: ...
118
```
119
120
[Authenticated Trading](./authenticated-client.md)
121
122
### Real-time Data Streaming
123
124
WebSocket client for real-time market data, order updates, and account changes with customizable message handling and optional MongoDB integration.
125
126
```python { .api }
127
class WebsocketClient:
128
def __init__(self, url: str = "wss://ws-feed.pro.coinbase.com", products: list = None,
129
message_type: str = "subscribe", mongo_collection = None, should_print: bool = True,
130
auth: bool = False, api_key: str = "", api_secret: str = "", api_passphrase: str = "",
131
*, channels: list): ...
132
def start(self): ...
133
def close(self): ...
134
def on_open(self): ...
135
def on_message(self, msg: dict): ...
136
def on_close(self): ...
137
def on_error(self, e: Exception, data = None): ...
138
```
139
140
[Real-time Data Streaming](./websocket-client.md)
141
142
### Order Book Management
143
144
Real-time order book maintenance that automatically processes WebSocket messages to maintain accurate bid/ask state for a specific product.
145
146
```python { .api }
147
class OrderBook:
148
def __init__(self, product_id: str = 'BTC-USD', log_to = None): ...
149
def process_message(self, message: dict): ...
150
def get_current_book(self) -> dict: ...
151
def get_ask(self): ...
152
def get_bid(self): ...
153
def get_current_ticker(self) -> dict: ...
154
```
155
156
[Order Book Management](./order-book.md)
157
158
## Types
159
160
```python { .api }
161
class CBProAuth:
162
"""Authentication handler for API requests."""
163
def __init__(self, api_key: str, secret_key: str, passphrase: str): ...
164
def __call__(self, request): ...
165
166
def get_auth_headers(timestamp: str, message: str, api_key: str, secret_key: str, passphrase: str) -> dict:
167
"""Generate authentication headers for API requests."""
168
```
169
170
## Error Handling
171
172
The library handles various error conditions:
173
174
- **API Rate Limits**: Automatic retry logic for rate-limited requests
175
- **Network Errors**: Connection timeout handling and retry mechanisms
176
- **Authentication Errors**: Clear error messages for invalid credentials
177
- **WebSocket Disconnections**: Automatic reconnection and error recovery
178
- **Order Book Gaps**: Automatic resyncing when message sequence gaps are detected
179
180
## Environment Support
181
182
- **Production**: `https://api.pro.coinbase.com` (default)
183
- **Sandbox**: `https://api-public.sandbox.pro.coinbase.com` for testing