Coinbase Advanced API Python SDK

repository·master·Indexed 43 days ago

https://github.com/coinbase/coinbase-advanced-py

A Python SDK for interacting with Coinbase Advanced Trade REST and WebSocket APIs. It provides high-level interfaces for trading, account management, and market data, simplifying authentication using Coinbase Developer Platform (CDP) API keys (Ed25519 and ECDSA). Features include the RESTClient for executing orders and fetching market data, and WSClient/WSUserClient for real-time WebSocket connections with automatic reconnection and exponential backoff.

Tokens
7K
Snippets
21
Records
33
Agent score
56%

What's inside Coinbase Advanced API Python SDK

  1. Access response data using dot-notation and bracket notation

    master

    Endpoints return custom class objects. You can access defined fields using dot-notation. For fields that are not explicitly defined in the SDK's custom classes, use standard bracket notation to access the underlying data.

    Example: Dot-notation (Defined fields)

    product = client.get_product("BTC-USD")
    print(product.price)

    Example: Bracket notation (Undefined/Nested fields)

    accounts = client.get_accounts()
    # Accessing a nested field not explicitly defined in the SDK class
    print(accounts.accounts[0].available_balance['value'])
    product = client.get_product("BTC-USD")
    print(product.price)
    
    accounts = client.get_accounts()
    print(accounts.accounts[0].available_balance['value'])
  2. Handle WebSocket exceptions and reconnection

    master

    The WebSocket client automatically attempts to reconnect using exponential backoff (up to 5 retries) if the connection is lost. If you want to disable this, set retry=False during instantiation.

    Because the WebSocket runs on its own thread, exceptions raised in the message handler or during forced disconnects are not automatically raised to your main thread. To catch them, use the provided helper methods:

    • run_forever_with_exception_check(): Runs indefinitely, checking for exceptions every second.
    • sleep_with_exception_check(sleep: int): Sleeps for the specified number of seconds and then checks for exceptions.

    Exceptions:

    • WSClientConnectionClosedException: Raised on forced disconnects or when retry attempts are exhausted.
    • WSClientException: Raised for other WebSocket errors.
    from coinbase.websocket import (WSClient, WSClientConnectionClosedException,
                                    WSClientException)
    
    client = WSClient(api_key=api_key, api_secret=api_secret, on_message=on_message)
    
    try:
        client.open()
        client.subscribe(product_ids=["BTC-USD", "ETH-USD"], channels=["ticker", "heartbeats"])
        client.run_forever_with_exception_check()
    except WSClientConnectionClosedException as e:
        print("Connection closed! Retry attempts exhausted.")
    except WSClientException as e:
        print("Error encountered!")
  3. Access public endpoints without authentication

    master

    Both the RESTClient and WSClient allow access to public endpoints without providing API keys. To use them unauthenticated, initialize the clients without any arguments.

    Important Considerations:

    • Private Endpoints: Attempting to call private endpoints or channels while unauthenticated will result in an error.
    • Rate Limits: Unauthenticated requests are subject to more aggressive rate limiting. It is recommended to authenticate your requests whenever possible.
    • REST vs WebSocket Behavior: In the REST client, public endpoints are distinct from their authenticated counterparts (e.g., get_public_products() vs get_products()). In the WebSocket client, channels typically handle both authenticated and unauthenticated requests, and most channels are public.
  4. Configure Coinbase Developer Platform (CDP) API Keys

    master

    The SDK requires CDP API keys. It supports both Ed25519 (recommended) and ECDSA key types. The SDK automatically detects the key type and selects the correct JWT signing algorithm (EdDSA or ES256).

    Supported Formats

    • Ed25519: PKCS8 PEM (-----BEGIN PRIVATE KEY-----) or raw base64 (32-byte seed or 64-byte seed||pubkey).
    • ECDSA: SEC1 PEM (-----BEGIN EC PRIVATE KEY-----).

    Environment Variables

    You can set your credentials in your environment to avoid hardcoding them:

    For Ed25519:

    export COINBASE_API_KEY="organizations/{org_id}/apiKeys/{key_id}"
    export COINBASE_API_SECRET="YOUR_BASE64_ENCODED_ED25519_PRIVATE_KEY"

    For ECDSA:

    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"
  5. Enable Rate Limit Response Headers

    master

    To see rate limit information in your API responses, initialize the RESTClient with rate_limit_headers=True. This will append the rate limit headers from the Coinbase API to the response body.

    client = RESTClient(api_key=api_key, api_secret=api_secret, rate_limit_headers=True)
  6. Use the REST client to fetch public products

    master

    You can use the RESTClient to access public data without authentication. For example, get_public_products() returns the same data as the authenticated get_products() method but does not require API keys.

    from coinbase.rest import RESTClient
    import json
    
    client = RESTClient()
    
    public_products = client.get_public_products()
    print(json.dumps(public_products.to_dict(), indent=2))
  7. Use the WebSocket client to subscribe to public channels

    master

    The WSClient can subscribe to public channels like ticker without authentication. You must provide an on_message callback function during initialization to handle incoming data.

    import time
    from coinbase.websocket import WSClient
    
    def on_message(msg):
        print(msg)
    
    client = WSClient(on_message=on_message)
    
    client.open()
    client.ticker(product_ids=["BTC-USD"])
    
    time.sleep(10)
    
    client.ticker_unsubscribe(product_ids=["BTC-USD"])
    client.close()
  8. Use the REST Client to make API calls

    master

    The RESTClient provides high-level hooks for various Coinbase API endpoints. You can call methods like get_accounts() or market_order_buy() to execute trades and manage accounts.

    Tip: When calling order methods, setting client_order_id to an empty string will auto-generate a unique ID, but this removes the safeguard against accidental duplicate orders.

    from json import dumps
    from coinbase.rest import RESTClient
    
    client = RESTClient()
    
    # Get all accounts
    accounts = client.get_accounts()
    print(dumps(accounts.to_dict(), indent=2))
    
    # Place a market buy order
    order = client.market_order_buy(client_order_id="clientOrderId", product_id="BTC-USD", quote_size="1")
    print(dumps(order.to_dict(), indent=2))
  9. Manage Futures and Perpetuals

    master

    The SDK provides specialized methods for trading derivatives.

    Futures:

    • get_futures_balance_summary(): Get summary of futures balances.
    • list_futures_positions(): List all open futures positions.
    • get_futures_position(position_id): Get details for a specific position.
    • schedule_futures_sweep(): Schedule a sweep of funds.
    • list_futures_sweeps(): List scheduled sweeps.
    • cancel_pending_futures_sweep(): Cancel a pending sweep.
    • get_intraday_margin_setting() / set_intraday_margin_setting(): Manage margin settings.
    • get_current_margin_window(): Check the current margin window.

    Perpetuals:

    • allocate_portfolio(portfolio_id, ...): Allocate funds to a perpetuals portfolio.
    • get_perps_portfolio_summary(): Get summary for perpetuals.
    • list_perps_positions(): List open perpetuals positions.
    • get_perps_position(position_id): Get details for a specific perpetuals position.
    • get_perps_portfolio_balances(): Get balances for the perpetuals portfolio.
    • opt_in_or_out_multi_asset_collateral(): Manage multi-asset collateral settings.
  10. Manage WSUserClient connections and subscriptions

    master

    The WSUserClient provides several utility methods to manage the lifecycle of a WebSocket connection and its subscriptions:

    Connection Management

    • open() / open_async(): Establishes the WebSocket connection.
    • close() / close_async(): Gracefully closes the connection.

    Subscription Management

    • subscribe(channel, ...) / subscribe_async(channel, ...): Subscribes to a specific data channel.
    • unsubscribe(channel, ...) / unsubscribe_async(channel, ...): Stops receiving updates for a specific channel.
    • unsubscribe_all() / unsubscribe_all_async(): Cancels all active subscriptions.

    Execution Helpers

    • run_forever_with_exception_check() / run_forever_with_exception_check_async(): Runs the client loop continuously while monitoring for errors.
    • sleep_with_exception_check() / sleep_with_exception_check_async(): A specialized sleep function that checks for background exceptions during the wait period.