CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-cbpro

The unofficial Python client for the Coinbase Pro API providing comprehensive trading and market data access

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

authenticated-client.mddocs/

Authenticated Trading

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.

Capabilities

Client Initialization

Create an authenticated client with API credentials for private endpoint access.

class AuthenticatedClient(PublicClient):
    def __init__(self, key: str, b64secret: str, passphrase: str, 
                 api_url: str = "https://api.pro.coinbase.com"):
        """
        Create an instance of the AuthenticatedClient class.

        Parameters:
        - key (str): Your API key
        - b64secret (str): The base64-encoded secret key matching your API key
        - passphrase (str): Passphrase chosen when setting up the key
        - api_url (str): API URL. Defaults to production, use sandbox URL for testing
        """

Usage Example:

import cbpro

# Production trading
auth_client = cbpro.AuthenticatedClient(key, b64secret, passphrase)

# Sandbox testing
auth_client = cbpro.AuthenticatedClient(
    key, b64secret, passphrase,
    api_url="https://api-public.sandbox.pro.coinbase.com"
)

Account Management

Access account information, balances, transaction history, and holds.

def get_accounts(self) -> list:
    """
    Get a list of all trading accounts.

    Returns:
    list: Account information. Each account contains:
        - id: Account UUID
        - currency: Currency code (e.g., "BTC", "USD")
        - balance: Total balance including holds
        - available: Available balance (balance - holds)
        - hold: Amount on hold for orders/withdrawals
        - profile_id: Associated profile ID
    """

def get_account(self, account_id: str) -> dict:
    """
    Get information for a single account.

    Parameters:
    - account_id (str): Account UUID

    Returns:
    dict: Detailed account information
    """

def get_account_history(self, account_id: str, **kwargs):
    """
    List account activity. Account activity either increases or decreases
    your account balance.

    Entry types:
    - transfer: Funds moved to/from Coinbase to cbpro
    - match: Funds moved as a result of a trade
    - fee: Fee as a result of a trade
    - rebate: Fee rebate as per fee schedule

    Parameters:
    - account_id (str): Account UUID to get history of
    - **kwargs: Additional HTTP request parameters (before, after, limit)

    Returns:
    generator: History information for the account. Each entry contains:
        - id: Entry ID
        - created_at: Timestamp
        - amount: Amount change
        - balance: Balance after change
        - type: Entry type (transfer, match, fee, rebate)
        - details: Additional information about the entry
    """

def get_account_holds(self, account_id: str, **kwargs):
    """
    Get holds on an account.

    Holds are placed on an account for active orders or pending withdrawals.
    As orders fill or withdrawals complete, holds are updated or removed.

    Parameters:
    - account_id (str): Account UUID to get holds of
    - **kwargs: Additional HTTP request parameters

    Returns:
    generator: Hold information. Each hold contains:
        - id: Hold UUID
        - account_id: Account UUID
        - created_at: Hold creation timestamp
        - updated_at: Hold update timestamp
        - amount: Hold amount
        - type: Hold type ("order" or "transfer")
        - ref: ID of the order or transfer that created the hold
    """

Usage Example:

# Get all account balances
accounts = auth_client.get_accounts()
for account in accounts:
    if float(account['balance']) > 0:
        print(f"{account['currency']}: {account['balance']} (available: {account['available']})")

# Get USD account details
usd_accounts = [acc for acc in accounts if acc['currency'] == 'USD']
if usd_accounts:
    usd_account = usd_accounts[0]
    
    # Get transaction history
    history = auth_client.get_account_history(usd_account['id'])
    recent_transactions = list(islice(history, 50))
    
    # Get current holds
    holds = auth_client.get_account_holds(usd_account['id'])
    active_holds = list(holds)

Order Management

Place, cancel, and track orders with comprehensive order type support.

def place_limit_order(self, product_id: str, side: str, price: str, size: str,
                     client_oid: str = None, stp: str = None, time_in_force: str = None,
                     cancel_after: str = None, post_only: bool = None,
                     overdraft_enabled: bool = None, funding_amount: str = None) -> dict:
    """
    Place a limit order.

    Parameters:
    - product_id (str): Product to order (e.g., 'BTC-USD')
    - side (str): Order side ('buy' or 'sell')
    - price (str): Price per unit of cryptocurrency
    - size (str): Amount of cryptocurrency to buy or sell
    - client_oid (str): User-specified Order ID (UUID recommended)
    - stp (str): Self-trade prevention ('dc', 'co', 'cn', 'cb')
    - time_in_force (str): 'GTC', 'GTT', 'IOC', or 'FOK'
    - cancel_after (str): Cancel after period for GTT orders ('min', 'hour', 'day')
    - post_only (bool): Only make liquidity, don't take
    - overdraft_enabled (bool): Use margin funding if needed
    - funding_amount (str): Specific margin funding amount

    Returns:
    dict: Order details including order ID, status, and parameters
    """

def place_market_order(self, product_id: str, side: str, size: str = None, funds: str = None,
                      client_oid: str = None, stp: str = None,
                      overdraft_enabled: bool = None, funding_amount: str = None) -> dict:
    """
    Place market order.

    Parameters:
    - product_id (str): Product to order (e.g., 'BTC-USD')
    - side (str): Order side ('buy' or 'sell')
    - size (str): Desired amount in crypto (specify this OR funds)
    - funds (str): Desired amount of quote currency to use (specify this OR size)
    - client_oid (str): User-specified Order ID
    - stp (str): Self-trade prevention flag
    - overdraft_enabled (bool): Use margin funding if needed
    - funding_amount (str): Specific margin funding amount

    Returns:
    dict: Order details including order ID and execution info
    """

def place_stop_order(self, product_id: str, stop_type: str, price: str, 
                    size: str = None, funds: str = None, client_oid: str = None,
                    stp: str = None, overdraft_enabled: bool = None, 
                    funding_amount: str = None) -> dict:
    """
    Place stop order.

    Parameters:
    - product_id (str): Product to order (e.g., 'BTC-USD')
    - stop_type (str): 'loss' (triggers at or below price) or 'entry' (triggers at or above price)
    - price (str): Trigger price for the stop order
    - size (str): Desired amount in crypto (specify this OR funds)
    - funds (str): Desired amount of quote currency (specify this OR size)
    - client_oid (str): User-specified Order ID
    - stp (str): Self-trade prevention flag
    - overdraft_enabled (bool): Use margin funding if needed
    - funding_amount (str): Specific margin funding amount

    Returns:
    dict: Order details including order ID and trigger parameters
    """

Usage Example:

# Place a limit buy order
buy_order = auth_client.place_limit_order(
    product_id='BTC-USD',
    side='buy',
    price='30000.00',
    size='0.001',
    time_in_force='GTC',
    post_only=True  # Only add liquidity, don't take
)
print(f"Limit order placed: {buy_order['id']}")

# Place a market sell order using size
sell_order = auth_client.place_market_order(
    product_id='BTC-USD',
    side='sell',
    size='0.001'
)

# Place a stop-loss order
stop_loss = auth_client.place_stop_order(
    product_id='BTC-USD',
    stop_type='loss',
    price='25000.00',  # Sell if price drops to $25,000
    size='0.001'
)

Order Tracking and Cancellation

Monitor and manage existing orders with comprehensive filtering and cancellation options.

def get_orders(self, product_id: str = None, status: str = None, **kwargs):
    """
    List your current orders.

    Only open or un-settled orders are returned by default. Use status parameter
    to include settled orders.

    Parameters:
    - product_id (str): Only list orders for this product
    - status (str): Limit to specific status or 'all' for all statuses
        Options: 'open', 'pending', 'active', 'done', 'settled'
    - **kwargs: Additional parameters (before, after, limit)

    Returns:
    generator: Order information. Each order contains:
        - id: Order UUID
        - price: Order price
        - size: Order size
        - product_id: Product identifier
        - side: Order side (buy/sell)
        - type: Order type (limit/market/stop)
        - created_at: Order creation timestamp
        - status: Order status
        - settled: Whether order is settled
    """

def get_order(self, order_id: str) -> dict:
    """
    Get a single order by order ID.

    Parameters:
    - order_id (str): Server-assigned order ID (not client_oid)

    Returns:
    dict: Complete order information including fills and fees
    """

def cancel_order(self, order_id: str) -> list:
    """
    Cancel a previously placed order.

    Parameters:
    - order_id (str): Server-assigned order ID (not client_oid)

    Returns:
    list: Contains the canceled order ID
    """

def cancel_all(self, product_id: str = None) -> list:
    """
    With best effort, cancel all open orders.

    Parameters:
    - product_id (str): Only cancel orders for this product

    Returns:
    list: List of canceled order IDs
    """

Usage Example:

# Get all open orders
open_orders = list(auth_client.get_orders(status='open'))
print(f"Open orders: {len(open_orders)}")

# Get orders for specific product
btc_orders = list(auth_client.get_orders(product_id='BTC-USD'))

# Cancel a specific order
if open_orders:
    canceled = auth_client.cancel_order(open_orders[0]['id'])
    print(f"Canceled order: {canceled[0]}")

# Cancel all orders for BTC-USD
canceled_orders = auth_client.cancel_all(product_id='BTC-USD')
print(f"Canceled {len(canceled_orders)} orders")

Trade Fills and Execution Data

Access detailed information about order fills and trade execution.

def get_fills(self, product_id: str = None, order_id: str = None, **kwargs):
    """
    Get a list of recent fills.

    Either product_id or order_id must be specified.

    Parameters:
    - product_id (str): Limit list to this product
    - order_id (str): Limit list to this order
    - **kwargs: Additional parameters (before, after, limit)

    Returns:
    generator: Fill information. Each fill contains:
        - trade_id: Unique trade identifier
        - product_id: Product identifier
        - price: Fill price
        - size: Fill size
        - order_id: Associated order ID
        - created_at: Fill timestamp
        - liquidity: 'M' (maker) or 'T' (taker)
        - fee: Fee charged for this fill
        - settled: Whether fill is settled
        - side: Order side (buy/sell)

    Raises:
    ValueError: If neither product_id nor order_id is specified
    """

Usage Example:

# Get all recent fills
all_fills = list(islice(auth_client.get_fills(product_id='BTC-USD'), 100))

# Calculate total fees paid
total_fees = sum(float(fill['fee']) for fill in all_fills)
print(f"Total fees paid: ${total_fees:.2f}")

# Get fills for specific order
order_fills = list(auth_client.get_fills(order_id=buy_order['id']))

Account Information and Payment Methods

Access payment methods and Coinbase account information for funding operations.

def get_payment_methods(self) -> list:
    """
    Get a list of your payment methods.

    Returns:
    list: Payment method details including method ID, type, and limits
    """

def get_coinbase_accounts(self) -> list:
    """
    Get a list of your Coinbase accounts.

    Returns:
    list: Coinbase account details including account ID, currency, and balance
    """

Stablecoin Conversion

Convert between stablecoins and USD at 1:1 rates.

def convert_stablecoin(self, amount: str, from_currency: str, to_currency: str) -> dict:
    """
    Convert stablecoin.

    Parameters:
    - amount (str): The amount to convert
    - from_currency (str): Source currency type (e.g., 'USDC')
    - to_currency (str): Target currency type (e.g., 'USD')

    Returns:
    dict: Conversion details including conversion ID and account information
    """

Generic Order Placement

Generic order placement method with comprehensive parameter support.

def place_order(self, product_id: str, side: str, order_type: str = None, **kwargs) -> dict:
    """
    Place an order.

    The three order types (limit, market, and stop) can be placed using this
    method. Specific methods are provided for each order type.

    Parameters:
    - product_id (str): Product to order (e.g., 'BTC-USD')
    - side (str): Order side ('buy' or 'sell')
    - order_type (str): Order type ('limit', 'market', or 'stop')
    - **kwargs: Additional arguments for specific order types

    Returns:
    dict: Order details including order ID, status, and parameters
    """

def buy(self, product_id: str, order_type: str, **kwargs) -> dict:
    """
    Place a buy order.

    Legacy method for backwards compatibility. Use specific order type methods
    for better parameter validation and documentation.

    Parameters:
    - product_id (str): Product to order (e.g., 'BTC-USD')
    - order_type (str): Order type ('limit', 'market', or 'stop')
    - **kwargs: Additional arguments for the order type

    Returns:
    dict: Order details
    """

def sell(self, product_id: str, order_type: str, **kwargs) -> dict:
    """
    Place a sell order.

    Legacy method for backwards compatibility. Use specific order type methods
    for better parameter validation and documentation.

    Parameters:
    - product_id (str): Product to order (e.g., 'BTC-USD')
    - order_type (str): Order type ('limit', 'market', or 'stop')
    - **kwargs: Additional arguments for the order type

    Returns:
    dict: Order details
    """

Margin Trading Operations

Manage margin funding, positions, and transfers for margin trading accounts.

def get_fundings(self, status: str = None, **kwargs):
    """
    Get margin funding records.

    Every order placed with a margin profile that draws funding creates
    a funding record.

    Parameters:
    - status (str): Limit funding records to specific status
        Options: 'outstanding', 'settled', 'rejected'
    - **kwargs: Additional HTTP request parameters

    Returns:
    generator: Margin funding information. Each record contains:
        - id: Funding record ID
        - order_id: Associated order ID
        - profile_id: Margin profile ID
        - amount: Funding amount
        - status: Funding status
        - created_at: Funding creation timestamp
        - currency: Funding currency
        - repaid_amount: Amount repaid
    """

def repay_funding(self, amount: str, currency: str) -> dict:
    """
    Repay funding. Repays the older funding records first.

    Parameters:
    - amount (str): Amount of currency to repay
    - currency (str): The currency (e.g., 'USD')

    Returns:
    dict: Repayment confirmation details
    """

def margin_transfer(self, margin_profile_id: str, transfer_type: str, 
                   currency: str, amount: str) -> dict:
    """
    Transfer funds between your standard profile and a margin profile.

    Parameters:
    - margin_profile_id (str): Margin profile ID to deposit/withdraw from
    - transfer_type (str): 'deposit' or 'withdraw'
    - currency (str): Currency to transfer (e.g., 'USD')
    - amount (str): Amount to transfer

    Returns:
    dict: Transfer details including transfer ID and status
    """

def get_position(self) -> dict:
    """
    Get an overview of your margin profile.

    Returns:
    dict: Details about funding, accounts, and margin call status
    """

def close_position(self, repay_only: bool) -> dict:
    """
    Close position.

    Parameters:
    - repay_only (bool): Whether to only repay funding without closing

    Returns:
    dict: Position closure details
    """

Funding and Transfers

Manage deposits, withdrawals, and transfers between accounts.

def deposit(self, amount: str, currency: str, payment_method_id: str) -> dict:
    """
    Deposit funds from a payment method.

    Parameters:
    - amount (str): Amount to deposit
    - currency (str): Currency type
    - payment_method_id (str): ID of the payment method

    Returns:
    dict: Deposit information including deposit ID and payout time
    """

def coinbase_deposit(self, amount: str, currency: str, coinbase_account_id: str) -> dict:
    """
    Deposit funds from a Coinbase account.

    Moving funds between Coinbase and Coinbase Pro is instant and free.

    Parameters:
    - amount (str): Amount to deposit
    - currency (str): Currency type
    - coinbase_account_id (str): ID of the Coinbase account

    Returns:
    dict: Deposit information
    """

def withdraw(self, amount: str, currency: str, payment_method_id: str) -> dict:
    """
    Withdraw funds to a payment method.

    Parameters:
    - amount (str): Amount to withdraw
    - currency (str): Currency type (e.g., 'BTC', 'USD')
    - payment_method_id (str): ID of the payment method

    Returns:
    dict: Withdrawal information including withdrawal ID and payout time
    """

def coinbase_withdraw(self, amount: str, currency: str, coinbase_account_id: str) -> dict:
    """
    Withdraw funds to a Coinbase account.

    Moving funds between Coinbase and Coinbase Pro is instant and free.

    Parameters:
    - amount (str): Amount to withdraw
    - currency (str): Currency type (e.g., 'BTC', 'USD')
    - coinbase_account_id (str): ID of the Coinbase account

    Returns:
    dict: Withdrawal information
    """

def crypto_withdraw(self, amount: str, currency: str, crypto_address: str) -> dict:
    """
    Withdraw funds to a cryptocurrency address.

    Parameters:
    - amount (str): Amount to withdraw
    - currency (str): Currency type (e.g., 'BTC')
    - crypto_address (str): Destination cryptocurrency address

    Returns:
    dict: Withdrawal information
    """

Usage Example:

# Get available payment methods
payment_methods = auth_client.get_payment_methods()
bank_accounts = [pm for pm in payment_methods if pm['type'] == 'ach_bank_account']

# Deposit from bank account
if bank_accounts:
    deposit_result = auth_client.deposit(
        amount='100.00',
        currency='USD',
        payment_method_id=bank_accounts[0]['id']
    )
    print(f"Deposit initiated: {deposit_result['id']}")

# Withdraw to crypto address
withdrawal = auth_client.crypto_withdraw(
    amount='0.001',
    currency='BTC',
    crypto_address='1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa'
)

Reports and Analytics

Generate and access account reports and trading analytics.

def create_report(self, report_type: str, start_date: str, end_date: str,
                 product_id: str = None, account_id: str = None,
                 report_format: str = 'pdf', email: str = None) -> dict:
    """
    Create report of historic information about your account.

    Parameters:
    - report_type (str): 'fills' or 'account'
    - start_date (str): Starting date in ISO 8601 format
    - end_date (str): Ending date in ISO 8601 format
    - product_id (str): Required for 'fills' reports
    - account_id (str): Required for 'account' reports
    - report_format (str): 'pdf' or 'csv'
    - email (str): Email address to send report to

    Returns:
    dict: Report creation details including report ID and status
    """

def get_report(self, report_id: str) -> dict:
    """
    Get report status and download URL.

    Parameters:
    - report_id (str): Report ID from create_report

    Returns:
    dict: Report details including file URL when ready
    """

def get_trailing_volume(self) -> list:
    """
    Get your 30-day trailing volume for all products.

    Returns:
    list: 30-day trailing volumes with exchange volume and recorded timestamps
    """

def get_fees(self) -> dict:
    """
    Get your maker & taker fee rates and 30-day trailing volume.

    Returns:
    dict: Fee information containing:
        - maker_fee_rate: Maker fee percentage
        - taker_fee_rate: Taker fee percentage
        - usd_volume: 30-day USD volume
    """

Usage Example:

# Check current fee rates
fees = auth_client.get_fees()
print(f"Maker fee: {float(fees['maker_fee_rate']) * 100:.3f}%")
print(f"Taker fee: {float(fees['taker_fee_rate']) * 100:.3f}%")

# Get 30-day trading volume
volume = auth_client.get_trailing_volume()
total_volume = sum(float(v['volume']) for v in volume)
print(f"30-day volume: {total_volume} BTC equivalent")

# Generate fills report
from datetime import datetime, timedelta
end_date = datetime.utcnow()
start_date = end_date - timedelta(days=30)

report = auth_client.create_report(
    report_type='fills',
    start_date=start_date.isoformat(),
    end_date=end_date.isoformat(),
    product_id='BTC-USD',
    report_format='csv'
)
print(f"Report requested: {report['id']}")

Authentication and Security

  • API Key Management: Store credentials securely, never in source code
  • Permissions: Set minimum required permissions on API keys
  • IP Restrictions: Restrict API keys to specific IP addresses when possible
  • Sandbox Testing: Always test with sandbox API before production
  • Rate Limiting: Respect rate limits to avoid being blocked
  • Error Handling: Implement proper error handling for authentication failures

Install with Tessl CLI

npx tessl i tessl/pypi-cbpro

docs

authenticated-client.md

index.md

order-book.md

public-client.md

websocket-client.md

tile.json