0
# Authenticated Trading
1
2
The AuthenticatedClient provides complete access to Coinbase Pro's private endpoints for trading, account management, and portfolio operations. It inherits all PublicClient functionality while adding authenticated capabilities for order management, account access, funding operations, and private data.
3
4
## Capabilities
5
6
### Client Initialization
7
8
Create an authenticated client with API credentials for private endpoint access.
9
10
```python { .api }
11
class AuthenticatedClient(PublicClient):
12
def __init__(self, key: str, b64secret: str, passphrase: str,
13
api_url: str = "https://api.pro.coinbase.com"):
14
"""
15
Create an instance of the AuthenticatedClient class.
16
17
Parameters:
18
- key (str): Your API key
19
- b64secret (str): The base64-encoded secret key matching your API key
20
- passphrase (str): Passphrase chosen when setting up the key
21
- api_url (str): API URL. Defaults to production, use sandbox URL for testing
22
"""
23
```
24
25
**Usage Example:**
26
```python
27
import cbpro
28
29
# Production trading
30
auth_client = cbpro.AuthenticatedClient(key, b64secret, passphrase)
31
32
# Sandbox testing
33
auth_client = cbpro.AuthenticatedClient(
34
key, b64secret, passphrase,
35
api_url="https://api-public.sandbox.pro.coinbase.com"
36
)
37
```
38
39
### Account Management
40
41
Access account information, balances, transaction history, and holds.
42
43
```python { .api }
44
def get_accounts(self) -> list:
45
"""
46
Get a list of all trading accounts.
47
48
Returns:
49
list: Account information. Each account contains:
50
- id: Account UUID
51
- currency: Currency code (e.g., "BTC", "USD")
52
- balance: Total balance including holds
53
- available: Available balance (balance - holds)
54
- hold: Amount on hold for orders/withdrawals
55
- profile_id: Associated profile ID
56
"""
57
58
def get_account(self, account_id: str) -> dict:
59
"""
60
Get information for a single account.
61
62
Parameters:
63
- account_id (str): Account UUID
64
65
Returns:
66
dict: Detailed account information
67
"""
68
69
def get_account_history(self, account_id: str, **kwargs):
70
"""
71
List account activity. Account activity either increases or decreases
72
your account balance.
73
74
Entry types:
75
- transfer: Funds moved to/from Coinbase to cbpro
76
- match: Funds moved as a result of a trade
77
- fee: Fee as a result of a trade
78
- rebate: Fee rebate as per fee schedule
79
80
Parameters:
81
- account_id (str): Account UUID to get history of
82
- **kwargs: Additional HTTP request parameters (before, after, limit)
83
84
Returns:
85
generator: History information for the account. Each entry contains:
86
- id: Entry ID
87
- created_at: Timestamp
88
- amount: Amount change
89
- balance: Balance after change
90
- type: Entry type (transfer, match, fee, rebate)
91
- details: Additional information about the entry
92
"""
93
94
def get_account_holds(self, account_id: str, **kwargs):
95
"""
96
Get holds on an account.
97
98
Holds are placed on an account for active orders or pending withdrawals.
99
As orders fill or withdrawals complete, holds are updated or removed.
100
101
Parameters:
102
- account_id (str): Account UUID to get holds of
103
- **kwargs: Additional HTTP request parameters
104
105
Returns:
106
generator: Hold information. Each hold contains:
107
- id: Hold UUID
108
- account_id: Account UUID
109
- created_at: Hold creation timestamp
110
- updated_at: Hold update timestamp
111
- amount: Hold amount
112
- type: Hold type ("order" or "transfer")
113
- ref: ID of the order or transfer that created the hold
114
"""
115
```
116
117
**Usage Example:**
118
```python
119
# Get all account balances
120
accounts = auth_client.get_accounts()
121
for account in accounts:
122
if float(account['balance']) > 0:
123
print(f"{account['currency']}: {account['balance']} (available: {account['available']})")
124
125
# Get USD account details
126
usd_accounts = [acc for acc in accounts if acc['currency'] == 'USD']
127
if usd_accounts:
128
usd_account = usd_accounts[0]
129
130
# Get transaction history
131
history = auth_client.get_account_history(usd_account['id'])
132
recent_transactions = list(islice(history, 50))
133
134
# Get current holds
135
holds = auth_client.get_account_holds(usd_account['id'])
136
active_holds = list(holds)
137
```
138
139
### Order Management
140
141
Place, cancel, and track orders with comprehensive order type support.
142
143
```python { .api }
144
def place_limit_order(self, product_id: str, side: str, price: str, size: str,
145
client_oid: str = None, stp: str = None, time_in_force: str = None,
146
cancel_after: str = None, post_only: bool = None,
147
overdraft_enabled: bool = None, funding_amount: str = None) -> dict:
148
"""
149
Place a limit order.
150
151
Parameters:
152
- product_id (str): Product to order (e.g., 'BTC-USD')
153
- side (str): Order side ('buy' or 'sell')
154
- price (str): Price per unit of cryptocurrency
155
- size (str): Amount of cryptocurrency to buy or sell
156
- client_oid (str): User-specified Order ID (UUID recommended)
157
- stp (str): Self-trade prevention ('dc', 'co', 'cn', 'cb')
158
- time_in_force (str): 'GTC', 'GTT', 'IOC', or 'FOK'
159
- cancel_after (str): Cancel after period for GTT orders ('min', 'hour', 'day')
160
- post_only (bool): Only make liquidity, don't take
161
- overdraft_enabled (bool): Use margin funding if needed
162
- funding_amount (str): Specific margin funding amount
163
164
Returns:
165
dict: Order details including order ID, status, and parameters
166
"""
167
168
def place_market_order(self, product_id: str, side: str, size: str = None, funds: str = None,
169
client_oid: str = None, stp: str = None,
170
overdraft_enabled: bool = None, funding_amount: str = None) -> dict:
171
"""
172
Place market order.
173
174
Parameters:
175
- product_id (str): Product to order (e.g., 'BTC-USD')
176
- side (str): Order side ('buy' or 'sell')
177
- size (str): Desired amount in crypto (specify this OR funds)
178
- funds (str): Desired amount of quote currency to use (specify this OR size)
179
- client_oid (str): User-specified Order ID
180
- stp (str): Self-trade prevention flag
181
- overdraft_enabled (bool): Use margin funding if needed
182
- funding_amount (str): Specific margin funding amount
183
184
Returns:
185
dict: Order details including order ID and execution info
186
"""
187
188
def place_stop_order(self, product_id: str, stop_type: str, price: str,
189
size: str = None, funds: str = None, client_oid: str = None,
190
stp: str = None, overdraft_enabled: bool = None,
191
funding_amount: str = None) -> dict:
192
"""
193
Place stop order.
194
195
Parameters:
196
- product_id (str): Product to order (e.g., 'BTC-USD')
197
- stop_type (str): 'loss' (triggers at or below price) or 'entry' (triggers at or above price)
198
- price (str): Trigger price for the stop order
199
- size (str): Desired amount in crypto (specify this OR funds)
200
- funds (str): Desired amount of quote currency (specify this OR size)
201
- client_oid (str): User-specified Order ID
202
- stp (str): Self-trade prevention flag
203
- overdraft_enabled (bool): Use margin funding if needed
204
- funding_amount (str): Specific margin funding amount
205
206
Returns:
207
dict: Order details including order ID and trigger parameters
208
"""
209
```
210
211
**Usage Example:**
212
```python
213
# Place a limit buy order
214
buy_order = auth_client.place_limit_order(
215
product_id='BTC-USD',
216
side='buy',
217
price='30000.00',
218
size='0.001',
219
time_in_force='GTC',
220
post_only=True # Only add liquidity, don't take
221
)
222
print(f"Limit order placed: {buy_order['id']}")
223
224
# Place a market sell order using size
225
sell_order = auth_client.place_market_order(
226
product_id='BTC-USD',
227
side='sell',
228
size='0.001'
229
)
230
231
# Place a stop-loss order
232
stop_loss = auth_client.place_stop_order(
233
product_id='BTC-USD',
234
stop_type='loss',
235
price='25000.00', # Sell if price drops to $25,000
236
size='0.001'
237
)
238
```
239
240
### Order Tracking and Cancellation
241
242
Monitor and manage existing orders with comprehensive filtering and cancellation options.
243
244
```python { .api }
245
def get_orders(self, product_id: str = None, status: str = None, **kwargs):
246
"""
247
List your current orders.
248
249
Only open or un-settled orders are returned by default. Use status parameter
250
to include settled orders.
251
252
Parameters:
253
- product_id (str): Only list orders for this product
254
- status (str): Limit to specific status or 'all' for all statuses
255
Options: 'open', 'pending', 'active', 'done', 'settled'
256
- **kwargs: Additional parameters (before, after, limit)
257
258
Returns:
259
generator: Order information. Each order contains:
260
- id: Order UUID
261
- price: Order price
262
- size: Order size
263
- product_id: Product identifier
264
- side: Order side (buy/sell)
265
- type: Order type (limit/market/stop)
266
- created_at: Order creation timestamp
267
- status: Order status
268
- settled: Whether order is settled
269
"""
270
271
def get_order(self, order_id: str) -> dict:
272
"""
273
Get a single order by order ID.
274
275
Parameters:
276
- order_id (str): Server-assigned order ID (not client_oid)
277
278
Returns:
279
dict: Complete order information including fills and fees
280
"""
281
282
def cancel_order(self, order_id: str) -> list:
283
"""
284
Cancel a previously placed order.
285
286
Parameters:
287
- order_id (str): Server-assigned order ID (not client_oid)
288
289
Returns:
290
list: Contains the canceled order ID
291
"""
292
293
def cancel_all(self, product_id: str = None) -> list:
294
"""
295
With best effort, cancel all open orders.
296
297
Parameters:
298
- product_id (str): Only cancel orders for this product
299
300
Returns:
301
list: List of canceled order IDs
302
"""
303
```
304
305
**Usage Example:**
306
```python
307
# Get all open orders
308
open_orders = list(auth_client.get_orders(status='open'))
309
print(f"Open orders: {len(open_orders)}")
310
311
# Get orders for specific product
312
btc_orders = list(auth_client.get_orders(product_id='BTC-USD'))
313
314
# Cancel a specific order
315
if open_orders:
316
canceled = auth_client.cancel_order(open_orders[0]['id'])
317
print(f"Canceled order: {canceled[0]}")
318
319
# Cancel all orders for BTC-USD
320
canceled_orders = auth_client.cancel_all(product_id='BTC-USD')
321
print(f"Canceled {len(canceled_orders)} orders")
322
```
323
324
### Trade Fills and Execution Data
325
326
Access detailed information about order fills and trade execution.
327
328
```python { .api }
329
def get_fills(self, product_id: str = None, order_id: str = None, **kwargs):
330
"""
331
Get a list of recent fills.
332
333
Either product_id or order_id must be specified.
334
335
Parameters:
336
- product_id (str): Limit list to this product
337
- order_id (str): Limit list to this order
338
- **kwargs: Additional parameters (before, after, limit)
339
340
Returns:
341
generator: Fill information. Each fill contains:
342
- trade_id: Unique trade identifier
343
- product_id: Product identifier
344
- price: Fill price
345
- size: Fill size
346
- order_id: Associated order ID
347
- created_at: Fill timestamp
348
- liquidity: 'M' (maker) or 'T' (taker)
349
- fee: Fee charged for this fill
350
- settled: Whether fill is settled
351
- side: Order side (buy/sell)
352
353
Raises:
354
ValueError: If neither product_id nor order_id is specified
355
"""
356
```
357
358
**Usage Example:**
359
```python
360
# Get all recent fills
361
all_fills = list(islice(auth_client.get_fills(product_id='BTC-USD'), 100))
362
363
# Calculate total fees paid
364
total_fees = sum(float(fill['fee']) for fill in all_fills)
365
print(f"Total fees paid: ${total_fees:.2f}")
366
367
# Get fills for specific order
368
order_fills = list(auth_client.get_fills(order_id=buy_order['id']))
369
```
370
371
### Account Information and Payment Methods
372
373
Access payment methods and Coinbase account information for funding operations.
374
375
```python { .api }
376
def get_payment_methods(self) -> list:
377
"""
378
Get a list of your payment methods.
379
380
Returns:
381
list: Payment method details including method ID, type, and limits
382
"""
383
384
def get_coinbase_accounts(self) -> list:
385
"""
386
Get a list of your Coinbase accounts.
387
388
Returns:
389
list: Coinbase account details including account ID, currency, and balance
390
"""
391
```
392
393
### Stablecoin Conversion
394
395
Convert between stablecoins and USD at 1:1 rates.
396
397
```python { .api }
398
def convert_stablecoin(self, amount: str, from_currency: str, to_currency: str) -> dict:
399
"""
400
Convert stablecoin.
401
402
Parameters:
403
- amount (str): The amount to convert
404
- from_currency (str): Source currency type (e.g., 'USDC')
405
- to_currency (str): Target currency type (e.g., 'USD')
406
407
Returns:
408
dict: Conversion details including conversion ID and account information
409
"""
410
```
411
412
### Generic Order Placement
413
414
Generic order placement method with comprehensive parameter support.
415
416
```python { .api }
417
def place_order(self, product_id: str, side: str, order_type: str = None, **kwargs) -> dict:
418
"""
419
Place an order.
420
421
The three order types (limit, market, and stop) can be placed using this
422
method. Specific methods are provided for each order type.
423
424
Parameters:
425
- product_id (str): Product to order (e.g., 'BTC-USD')
426
- side (str): Order side ('buy' or 'sell')
427
- order_type (str): Order type ('limit', 'market', or 'stop')
428
- **kwargs: Additional arguments for specific order types
429
430
Returns:
431
dict: Order details including order ID, status, and parameters
432
"""
433
434
def buy(self, product_id: str, order_type: str, **kwargs) -> dict:
435
"""
436
Place a buy order.
437
438
Legacy method for backwards compatibility. Use specific order type methods
439
for better parameter validation and documentation.
440
441
Parameters:
442
- product_id (str): Product to order (e.g., 'BTC-USD')
443
- order_type (str): Order type ('limit', 'market', or 'stop')
444
- **kwargs: Additional arguments for the order type
445
446
Returns:
447
dict: Order details
448
"""
449
450
def sell(self, product_id: str, order_type: str, **kwargs) -> dict:
451
"""
452
Place a sell order.
453
454
Legacy method for backwards compatibility. Use specific order type methods
455
for better parameter validation and documentation.
456
457
Parameters:
458
- product_id (str): Product to order (e.g., 'BTC-USD')
459
- order_type (str): Order type ('limit', 'market', or 'stop')
460
- **kwargs: Additional arguments for the order type
461
462
Returns:
463
dict: Order details
464
"""
465
```
466
467
### Margin Trading Operations
468
469
Manage margin funding, positions, and transfers for margin trading accounts.
470
471
```python { .api }
472
def get_fundings(self, status: str = None, **kwargs):
473
"""
474
Get margin funding records.
475
476
Every order placed with a margin profile that draws funding creates
477
a funding record.
478
479
Parameters:
480
- status (str): Limit funding records to specific status
481
Options: 'outstanding', 'settled', 'rejected'
482
- **kwargs: Additional HTTP request parameters
483
484
Returns:
485
generator: Margin funding information. Each record contains:
486
- id: Funding record ID
487
- order_id: Associated order ID
488
- profile_id: Margin profile ID
489
- amount: Funding amount
490
- status: Funding status
491
- created_at: Funding creation timestamp
492
- currency: Funding currency
493
- repaid_amount: Amount repaid
494
"""
495
496
def repay_funding(self, amount: str, currency: str) -> dict:
497
"""
498
Repay funding. Repays the older funding records first.
499
500
Parameters:
501
- amount (str): Amount of currency to repay
502
- currency (str): The currency (e.g., 'USD')
503
504
Returns:
505
dict: Repayment confirmation details
506
"""
507
508
def margin_transfer(self, margin_profile_id: str, transfer_type: str,
509
currency: str, amount: str) -> dict:
510
"""
511
Transfer funds between your standard profile and a margin profile.
512
513
Parameters:
514
- margin_profile_id (str): Margin profile ID to deposit/withdraw from
515
- transfer_type (str): 'deposit' or 'withdraw'
516
- currency (str): Currency to transfer (e.g., 'USD')
517
- amount (str): Amount to transfer
518
519
Returns:
520
dict: Transfer details including transfer ID and status
521
"""
522
523
def get_position(self) -> dict:
524
"""
525
Get an overview of your margin profile.
526
527
Returns:
528
dict: Details about funding, accounts, and margin call status
529
"""
530
531
def close_position(self, repay_only: bool) -> dict:
532
"""
533
Close position.
534
535
Parameters:
536
- repay_only (bool): Whether to only repay funding without closing
537
538
Returns:
539
dict: Position closure details
540
"""
541
```
542
543
### Funding and Transfers
544
545
Manage deposits, withdrawals, and transfers between accounts.
546
547
```python { .api }
548
def deposit(self, amount: str, currency: str, payment_method_id: str) -> dict:
549
"""
550
Deposit funds from a payment method.
551
552
Parameters:
553
- amount (str): Amount to deposit
554
- currency (str): Currency type
555
- payment_method_id (str): ID of the payment method
556
557
Returns:
558
dict: Deposit information including deposit ID and payout time
559
"""
560
561
def coinbase_deposit(self, amount: str, currency: str, coinbase_account_id: str) -> dict:
562
"""
563
Deposit funds from a Coinbase account.
564
565
Moving funds between Coinbase and Coinbase Pro is instant and free.
566
567
Parameters:
568
- amount (str): Amount to deposit
569
- currency (str): Currency type
570
- coinbase_account_id (str): ID of the Coinbase account
571
572
Returns:
573
dict: Deposit information
574
"""
575
576
def withdraw(self, amount: str, currency: str, payment_method_id: str) -> dict:
577
"""
578
Withdraw funds to a payment method.
579
580
Parameters:
581
- amount (str): Amount to withdraw
582
- currency (str): Currency type (e.g., 'BTC', 'USD')
583
- payment_method_id (str): ID of the payment method
584
585
Returns:
586
dict: Withdrawal information including withdrawal ID and payout time
587
"""
588
589
def coinbase_withdraw(self, amount: str, currency: str, coinbase_account_id: str) -> dict:
590
"""
591
Withdraw funds to a Coinbase account.
592
593
Moving funds between Coinbase and Coinbase Pro is instant and free.
594
595
Parameters:
596
- amount (str): Amount to withdraw
597
- currency (str): Currency type (e.g., 'BTC', 'USD')
598
- coinbase_account_id (str): ID of the Coinbase account
599
600
Returns:
601
dict: Withdrawal information
602
"""
603
604
def crypto_withdraw(self, amount: str, currency: str, crypto_address: str) -> dict:
605
"""
606
Withdraw funds to a cryptocurrency address.
607
608
Parameters:
609
- amount (str): Amount to withdraw
610
- currency (str): Currency type (e.g., 'BTC')
611
- crypto_address (str): Destination cryptocurrency address
612
613
Returns:
614
dict: Withdrawal information
615
"""
616
```
617
618
**Usage Example:**
619
```python
620
# Get available payment methods
621
payment_methods = auth_client.get_payment_methods()
622
bank_accounts = [pm for pm in payment_methods if pm['type'] == 'ach_bank_account']
623
624
# Deposit from bank account
625
if bank_accounts:
626
deposit_result = auth_client.deposit(
627
amount='100.00',
628
currency='USD',
629
payment_method_id=bank_accounts[0]['id']
630
)
631
print(f"Deposit initiated: {deposit_result['id']}")
632
633
# Withdraw to crypto address
634
withdrawal = auth_client.crypto_withdraw(
635
amount='0.001',
636
currency='BTC',
637
crypto_address='1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa'
638
)
639
```
640
641
### Reports and Analytics
642
643
Generate and access account reports and trading analytics.
644
645
```python { .api }
646
def create_report(self, report_type: str, start_date: str, end_date: str,
647
product_id: str = None, account_id: str = None,
648
report_format: str = 'pdf', email: str = None) -> dict:
649
"""
650
Create report of historic information about your account.
651
652
Parameters:
653
- report_type (str): 'fills' or 'account'
654
- start_date (str): Starting date in ISO 8601 format
655
- end_date (str): Ending date in ISO 8601 format
656
- product_id (str): Required for 'fills' reports
657
- account_id (str): Required for 'account' reports
658
- report_format (str): 'pdf' or 'csv'
659
- email (str): Email address to send report to
660
661
Returns:
662
dict: Report creation details including report ID and status
663
"""
664
665
def get_report(self, report_id: str) -> dict:
666
"""
667
Get report status and download URL.
668
669
Parameters:
670
- report_id (str): Report ID from create_report
671
672
Returns:
673
dict: Report details including file URL when ready
674
"""
675
676
def get_trailing_volume(self) -> list:
677
"""
678
Get your 30-day trailing volume for all products.
679
680
Returns:
681
list: 30-day trailing volumes with exchange volume and recorded timestamps
682
"""
683
684
def get_fees(self) -> dict:
685
"""
686
Get your maker & taker fee rates and 30-day trailing volume.
687
688
Returns:
689
dict: Fee information containing:
690
- maker_fee_rate: Maker fee percentage
691
- taker_fee_rate: Taker fee percentage
692
- usd_volume: 30-day USD volume
693
"""
694
```
695
696
**Usage Example:**
697
```python
698
# Check current fee rates
699
fees = auth_client.get_fees()
700
print(f"Maker fee: {float(fees['maker_fee_rate']) * 100:.3f}%")
701
print(f"Taker fee: {float(fees['taker_fee_rate']) * 100:.3f}%")
702
703
# Get 30-day trading volume
704
volume = auth_client.get_trailing_volume()
705
total_volume = sum(float(v['volume']) for v in volume)
706
print(f"30-day volume: {total_volume} BTC equivalent")
707
708
# Generate fills report
709
from datetime import datetime, timedelta
710
end_date = datetime.utcnow()
711
start_date = end_date - timedelta(days=30)
712
713
report = auth_client.create_report(
714
report_type='fills',
715
start_date=start_date.isoformat(),
716
end_date=end_date.isoformat(),
717
product_id='BTC-USD',
718
report_format='csv'
719
)
720
print(f"Report requested: {report['id']}")
721
```
722
723
## Authentication and Security
724
725
- **API Key Management**: Store credentials securely, never in source code
726
- **Permissions**: Set minimum required permissions on API keys
727
- **IP Restrictions**: Restrict API keys to specific IP addresses when possible
728
- **Sandbox Testing**: Always test with sandbox API before production
729
- **Rate Limiting**: Respect rate limits to avoid being blocked
730
- **Error Handling**: Implement proper error handling for authentication failures