Categorygithub.com/justinsimmons/go-coinbase
modulepackage
0.0.0-20241018003752-b110a78f6c4a
Repository: https://github.com/justinsimmons/go-coinbase.git
Documentation: pkg.go.dev

# README

go-coinbase

Go SDK for Coinbase's v3 Advanced Trade REST API

This does not include the Advanced Trade WebSocket.

Project Status

Coinbase is pretty rapidly updating and modifing their API's, which makes it hard to keep on top of new features. I am actively using this repo in a few side projects and will maintain it. For now I will not be implementing new endpoints like the converts APIs any time soon, as I do not use them for any of my side projects. I dont really want to invest the time if I am the only one using the SDK. If you would like any new features implemented or encounter a bug please open a Github issue and I will go ahead and jump on them. Thanks!

Installation

go-coinbase is compatible with Go releases in module mode:

go get github.com/justinsimmons/go-coinbase

Usage

    import "github.com/justinsimmons/go-coinbase"

Alternatively you can use an alias to shorten the invocation.

    import cb "github.com/justinsimmons/go-coinbase"

Construct a new Coinbase client, then use the various services on the client to access different parts of the Advanced Trade REST API. For example:

client := coinbase.NewWithCloud("api-key", "api-secret")

// List all accounts for the user.
accounts, err := client.Accounts.List(context.Background(), nil)

Some APIs have optional parameters that can be passed:

client := coinbase.NewWithCloud("api-key", "api-secret")

// Will filter the orders response to only return a specific product.
opt := &coinbase.ListOrdersOptions{ProductID: coinbase.String("BTC-USD")}

// Gets a list of orders that can be filterd with filtered by optional parameters.
orders, err := client.Orders.List(context.Background(), opt)

The services of a client divide the API into logical chunks and correspond to the structure of the Advanced Trade REST API documentation at: https://docs.cloud.coinbase.com/advanced-trade-api/docs/welcome .

NOTE: Using the context package, one can easily pass cancelation signals and deadlines to various services of the client for handling a request. In case there is no context available, then context.Background() can be used as a starting point.

Supported APIs

Accounts

APIDescriptionSupported
List AccountsGet a list of authenticated accounts for the current user.
Get AccountGet a list of information about an account, given an account UUID.

Products

APIDescriptionSupported
Get Best Bid/AskGet the best bid/ask for all products. A subset of all products can be returned instead by using the product_ids input.
Get Product BookGet a list of bids/asks for a single product. The amount of detail shown can be customized with the limit parameter.
List ProductsGet a list of the available currency pairs for trading.
Get ProductGet information on a single product by product ID.
Get Product CandlesGet rates for a single product by product ID, grouped in buckets.
Get Market TradesGet snapshot information, by product ID, about the last trades (ticks), best bid/ask, and 24h volume.

Orders

APIDescriptionSupported
Create OrderCreate an order with a specified product_id (asset-pair), side (buy/sell), etc.
Cancel OrdersInitiate cancel requests for one or more orders.
Edit OrderEdit an order with a specified new size, or new price.
Edit Order PreviewSimulate an edit order request with a specified new size, or new price, to preview the result of an edit. Only limit order types, with time in force type of good-till-cancelled can be edited.
List OrdersGet a list of orders filtered by optional query parameters (product_id, order_status, etc).
List FillsGet a list of fills filtered by optional query parameters (product_id, order_id, etc).
Get OrderGet a single order by order ID.
Preview OrderPreview the results of an order request before sending.

Portfolios

APIDescriptionSupported
List PortfoliosGet a list of all portfolios of a user.
Create PortfolioCreate a portfolio.
Move Portfolio FundsTransfer funds between portfolios.
Get Portfolio BreakdownGet the breakdown of a portfolio by portfolio ID.
Delete PortfolioDelete a portfolio by portfolio ID.
Edit PortfolioModify a portfolio by portfolio ID.
Close PositionPlaces an order to close any open positions for a specified product_id.
Get Intraday Margin SettingGet the status of whether your account is opted-in to receive increased leverage on futures trades on weekdays from 8am-4pm ET. During these hours, intraday margin rates apply, which are lower than the standard margin requirement needed to hold a futures position overnight.
Set Intraday Margin SettingSetting your margin window to INTRADAY opts you in to receive increased leverage on futures trades on weekdays from 8am-4pm ET. During these hours, intraday margin rates apply, which are lower than the standard margin requirement needed to hold a futures position overnight. You can opt out at anytime.
Get Current Margin WindowGet the current margin window to determine whether intraday or overnight margin rates are in effect.
Allocate PortfolioAllocate more funds to an isolated position in your Perpetuals portfolio.
Get Perpetuals Portfolio SummaryGet a summary of your Perpetuals portfolio
List Perpetuals PositionsGet a list of open positions in your Perpetuals portfolio
Get Perpetuals PositionGet a specific open position in your Perpetuals portfolio.
Get Portfolio BalancesGet a list of asset balances on Intx for a given Portfolio.
Opt In or Out of Multi Asset CollateralEnable or Disable Multi Asset Collateral for a given Portfolio.

Futures

APIDescriptionSupported
Get Futures Balance SummaryGet information on your balances related to Coinbase Financial Markets (CFM) futures trading.
List Futures PositionsGet a list of all open positions in CFM futures products.
Get Futures PositionGet the position of a specific CFM futures product
Schedule Futures SweepSchedule a sweep of funds from your CFTC-regulated futures account to your Coinbase Inc. USD Spot wallet.
List Futures SweepsGet information on your pending and/or processing requests to sweep funds from your CFTC-regulated futures account to your Coinbase Inc. USD Spot wallet.
Cancel Pending Futures SweepCancel your pending sweep of funds from your CFTC-regulated futures account to your Coinbase Inc. USD Spot wallet.

Fees

APIDescriptionSupported
Get Transactions SummaryGet a summary of transactions with fee tiers, total volume, and fees.

Converts

APIDescriptionSupported
Create Convert QuoteCreate a convert quote with a specified source currency, target currency, and amount.
Commit Convert TradeCommits a convert trade with a specified trade ID, source currency, and target currency.
Get Convert TradeGets a list of information about a convert trade with a specified trade ID, source currency, and target currency.

Public

APIDescriptionSupported
Get Server TimeGet the current time from the Coinbase Advanced API.
Get Public Product BookGet a list of bids/asks for a single product. The amount of detail shown can be customized with the limit parameter.
List Public ProductsGet a list of the available currency pairs for trading.
Get Public ProductGet information on a single product by product ID.
Get Public Product CandlesGet rates for a single product by product ID, grouped in buckets.
Get Public Market TradesGet snapshot information by product ID about the last trades (ticks) and best bid/ask.

Payment Methods

APIDescriptionSupported
List Payment MethodsGet a list of payment methods for the current user.
Get Payment MethodGet information about a payment method for the current user.

✅ = Implemented and fully tested. ⚠️ = Implemented but not able to test. ❌ = Not implemented but on roadmap.

Authentication

Coinbase has multiple authentication schemes available for different APIs. For information on which scheme you should use please consult the docs.

I would recommend you use cloud API trading keys as they allow for the full functionality of the advance trade APIs.

The following is the compatibility list for the available authentication schemes with go-coinbase.

SchemeSupported
Cloud API Trading keys
OAuth⚠️
Legacy API Keys

Cloud API Trading Keys

Coinbase Cloud supports two API key types, "Trading" keys and "General" keys. The Advanced API is only compatible with Cloud API Trading keys.

Instructions on generating a cloud API trading key.

Generate a client with Cloud API Trading credentials:

// Please don't actually hard code these, pass them in via flag.
const (
    apiKey = "organizations/{org_id}/apiKeys/{key_id}"
    apiSecret = "-----BEGIN EC PRIVATE KEY-----\nYOUR PRIVATE KEY\n-----END EC PRIVATE KEY-----\n"
)

// All API requests will use cloud API trading credentials.
client := coinbase.NewWithCloud(apiKey, apiSecret)

Legacy API Keys

Note that the legacy api keys do not suport any of the newer functionality of the Advanced Trade API (Portfolios, etc.).

Instructions on generating a legacy api key.

Generate a client with legacy credentials:

// All API requests will use legacy API credentials.
client := coinbase.NewWithLegacy("api-key", "api-secret")

OAuth

The OAuth authentication scheme is for applications serving many users, which is outside my use case for this package. To use this authentication scheme you are going to need to implement a custom authentication scheme.

Custom Authentication Scheme

If for whatever reason you would like to use your own authentication method for the API requests you need not rely on the prebuilt functionality provided by this client. You may implem

  1. Implement the coinbase.Authenticator interface. Example:

    type customAuthenticator struct {
        token string
    }
    
    // customAuthenticator implements coinbase.Authenticator interface.
    func (a customAuthenticator) Authenticate(r *http.Request) error {
        r.Header.Set("Authorization", "Bearer " + a.token)
    
        return nil
    }
    
  2. Inject it into the client with the option coinbase.WithCustomAuthenticator().

    token := "foo"
    authenticator := customAuthenticator{token: token}
    
    // Inject custom authenticator into the client.
    client := client.New(coinbase.WithCustomAuthenticator(authenticator))
    
    // Headers will now have a {"Authentication": {"Bearer foo"}} entry.
    orders, err := client.Orders.List(context.Background(), opt)
    

Rate Limits

Advanced Trade API endpoints are throttled by user at 30 requests per second.

Learn more about Coinbase rate limiting at https://docs.cloud.coinbase.com/advanced-trade-api/docs/rest-api-rate-limits .

Order Management

The maximum number of OPEN orders allowed per product_id is 500. If you have 500 open orders for a product_id at submission, new orders placed for that product immediately enter a failed state.

Advanced API Order Management

Coinbase Pro

Coinbase Pro has been disabled for use and all customers have been migrated as of December 1, 2023. This was accelerated from a prior announcement of Pro deprecation in 2024.

You cannot use existing Pro API keys to trade with Advanced Trade. See Migrating from Pro.

License

Copyright 2024 Justin Simmons.

This program is released under the GNU Affero General Public License v3 or later.

# Functions

Bool is a helper function that allocates a new bool value to store v and returns a pointer to it.
Int is a helper function that allocates a new int value to store v and returns a pointer to it.
Int64 is a helper function that allocates a new int64 value to store v and returns a pointer to it.
NewClient creates a new Coinbase Advanced Trade REST API client.
New creates a new Coinbase Advanced Trade REST API client, using Cloud API Trading Keys for authentication.
New creates a new Coinbase Advanced Trade REST API client, using legacy API key authentication.
String is a helper function that allocates a new string value to store v and returns a pointer to it.
Time is a helper function that allocates a new time value to store v and returns a pointer to it.
WithBaseURL overrides the base URL of the Advanced Trade REST API on the client.
WithCustomAuthenticator allows the caller to provide custom authentication schema to the client.
WithHTTPClient overrides the default HTTP client used by the client.

# Constants

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
orders remain open on the book until canceled.
Orders are valid till a specified date or time.
orders instantly cancel the remaining size of the limit order instead of opening it on the book.
Unknown or unspecified.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# Variables

ErrUnexpectedAPIResponse - coinbase API returned a response outside the API documetation.

# Structs

Coinabase account metadata.
No description provided by the author
No description provided by the author
Available balance belonging to coinbase account.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Coinbase Advanced Trade REST API client.
Detault error returned by the coinbase API.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
TODO: Not 100% sure what this is..?.
Limit Order Good Till Canceled.
Limit Order Good Till Date.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Market Order Immediate Or Cancel.
No description provided by the author
Configuration of the order, it can only consist of a single order type at at time.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Stop Order Good Till Canceled.
Stop Order Good Till Date.
No description provided by the author

# Interfaces

Authenticator adds authentication details to each HTTP request made from the client.

# Type aliases

No description provided by the author
Type of coinbase account.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Interface for interacting with Fututres APIs.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
All of these API endpoints are public and do not require authentication to use.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author