Coinbase API – A Introduction Guide

10 min read

Get 10-day Free Algo Trading Course

Last Updated on January 17, 2021

Coinbase Logo

Table of contents:

  1. What is Coinbase API?
  2. What is Coinbase?
  3.  Why should I use Coinbase API?
  4. Why shouldn’t I use Coinbase API?
  5. What alternatives are there to Coinbase API?
  6. What are the account types for Coinbase API?
  7. What are the libraries for the Coinbase API?
  8. How to get started with the Coinbase API?
  9. How do I retrieve my account balance using the Coinbase API?
  10. How to get real time price data for Bitcoin using Coinbase API?
  11. How to retrieve spot price data with the Coinbase API?
  12. How to retrieve historical data using the Coinbase API?
  13. How to access technical indicators such as the 20 SMA with the Coinbase API?
  14. How to send and receive Bitcoin with the Coinbase API?
  15. How to buy and sell Bitcoin with the Coinbase API?
  16. What are access and refresh tokens in the Coinbase API?
  17. Potential errors and warning
  18. Download Code

What is Coinbase API?

Coinbase API is a method for us to trade cryptocurrencies on Coinbase automatically via code.

What is Coinbase?

Coinbase is a trading platform allows us to buy, sell and store cryptocurrencies.

Coinbase also provides a Coinbase Mobile App which is available on IOS and Android. Their mobile app provides users with the possibility to trade on the go. Their services are widely available counting up to more than 100 countries.

What can I trade on Coinbase?

When it comes to the tradable assets, Coinbase offers various cryptocurrencies like:

  • Bitcoin
  • Ethereum
  • Bitcoin Cash
  • XRP
  • Litecoin
  • Dash
  • EOS
  • Tezos
  • Augur
  • Stellar
  • USD Coin
  • Ethereum Classic
  • Chainlink, and many more.

What are the pricing and fees of Coinbase?

If you want to learn about the pricing and fees of Coinbase which depend on things like your location and transactions, check out this link: https://help.coinbase.com/en/coinbase/trading-and-funding/pricing-and-fees/fees

The example for the fees that Coinbase gives us is the following:

  • If the total transaction amount is less than or equal to $10, the fee is $0.99 | €0,99 | £0,99 
  • If the total transaction amount is more than $10 but less than or equal to $25, the fee is $1.49 | €1,49 | £1,49
  • If the total transaction amount is more than $25 but less than or equal to $50, the fee is $1.99 | €1,99 | £1,99
  • If the total transaction amount is more than $50 but less than or equal to $200, the fee is $2.99 | €2,99 | £2,99

 Why should I use Coinbase API?

  • Flexible Trading Platform
  • Has many trading tools such as the Coinbase Pro API
  • Provides educational materials
  • Good customer service
  • Offers a variety of more than 25 cryptocurrencies
  • The interface is easy to use
  • Has high liquidity exchanges

Why shouldn’t I use Coinbase API?

  • Not regulated in all countries
  • Only offers cryptocurrency trading
  • There are not any MetaTrader platforms
  • Doesn’t offer online chat support
  • No official libraries
  • High fees (standard version is overpriced)
  • Coinbase Pro is severely lacking in features (i.e. only two EMA indicators available)
  • No control over the wallet key
  • Doesn’t offer all the altcoins that an altcoin trader would prefer

What alternatives are there to Coinbase API?

Coinbase API can be replaces with some alternatives and they are the following:

  • Gemini
  • Binance
  • Kraken.io
  • CoinGate
  • CoinPaymets
  • GoCoin
  • Coinomi
  • Cryptopay
  • Blocknomics
  • Blockchain
  • BitPay and more…

What are the account types for Coinbase API?

They also have 3 types of accounts with a minimum 1$ deposit (this can change depending on the account).

First type

The first one is your simple Coinbase API for beginners and individual traders. It has many usages and some of them are the following:

  • Generate bitcoin cash, bitcoin, litecoin and ethereum wallets and addresses.
  • Securely store the coins.
  • Obtain real-time and/or historical price data.
  • Get notified when the payments arrive.
  • Send/receive or sell/buy bitcoin cash, bitcoin, litecoin and ethereum.

Here is a link to its full documentation: https://developers.coinbase.com/

Second type

The second one is the Coinbase Pro API that provides individual traders the ability to trade various assets. It has an intuitive and easy to use interface.

This app is primarily built for advanced crytocurrency traders. Coinbase Pro API also has many tools like the following:

  • Order book and candlestick chart
  • Limit and market orders
  • Portfolio overview

Here is the link to the Coinbase Pro API documentation: https://docs.pro.coinbase.com

Third type

The third integration is the Coinbase Prime API that is a professional trading platform built for institutional traders. With it, they gain access to various liquidity pools for all Coinbase products. Its uses are aimed for the following types of traders:

  • Financial institutions
  • Liquidity providers
  • Crypto businesses
  • Asset Issuers
  • Institutional investors

On the following link you can learn more about the Coinbase Prime by reading the resources they offer: https://primebroker.coinbase.com/resource-center

If you want to check out the Coinbase API GitHub repo, you can do it on the following link: https://github.com/coinbase/coinbase-python

What are the libraries for the Coinbase API?

Coinbase doesn’t offer official libraries and the ones we can use are built by the community. The client libraries are the following:

  • Python
  • Java
  • Rust
  • C#
  • Go
  • Ruby
  • Node.js
  • Haskell

How to get started with the Coinbase API?

In order to get started with the Coinbase API, we’ll need to go over to their website (https://www.coinbase.com) and sign up for an account.

In the top right corner you’ll see a “Get started” button that will take you to the account creation screen when you click it. After that, you’ll enter your first and last name, email and password. When everything is written click the “Create account” button.

After that, you’ll need to verify your email and add a mobile phone number for two-step authentication. Be sure to have your phone with you as you’ll get a lot of authentication messages while following through this article.

The next step is to obtain our API key. When you’re all logged in, click on your profile icon in the top right corner and go to settings. From there, click on the API section and press the “+ New API Key” button.

The following screen will appear:

You’ll select the type of account you want and permissions you’ll have access to. For this article I’ll select both accounts and all permissions. On the newly appeared window you can also select the notification URL and input allowed IP addresses.

When you’re done click create. Also, have in mind that you can create multiple API keys with your account. When created, you’ll get your API key and API Secret.

For all of our next examples we’ll be using Python, so let’s go ahead and install the Coinbase API with the following command:

pip install coinbase

How do I retrieve my account balance using the Coinbase API?

Coinbase API allows us to retrieve our account balance but one at a time for each account. In the following example I’ll show how we can add up all of those accounts to get a full account balance sum.

Firstly, let’s import the Coinbase API library with the following command:

from coinbase.wallet.client import Client

The next step is to add our Coinbase API Key and the Coinbase API secret. After adding them we’ll start the client and authenticate them:

coinbase_API_key = “Your API Key”
coinbase_API_secret = “Your API Secret”
client = Client(coinbase_API_key, coinbase_API_secret)

After our client is running and the key is authenticated we’ll specify the starting account balance upon which the summation process will begin.

total = 0
message = [ ]

Now, we’ll get our accounts and for each wallet in our accounts data we’ll append the wallet name and the native balance (USD). After that, each wallet will be added to the total sum and the total account balance message will be shown:

accounts = client.get_accounts()
for wallet in accounts.data:
    message.append( str(wallet['name']) + ' ' +   str(wallet['native_balance']) )
    value = str( wallet['native_balance']).replace('USD','')
    total += float(value)
message.append( 'Total Balance: ' + 'USD ' + str(total) )
print ('\n'.join( message ))

How to get real time price data for Bitcoin using Coinbase API?

Getting real time prices with the Coinbase API is quite easy. The first thing we need to do is import the relevant library and authenticate our API key:

from coinbase.wallet.client import Client
coinbase_API_key = “Your API Key”
coinbase_API_secret = “Your API Secret”
client = Client(coinbase_API_key, coinbase_API_secret)
Now, we’ll specify the currency code we want to obtain:
currency_code = “EUR”

Now, we’ll specify the currency code we want to obtain:

price = client.get_spot_price(currency=currency_code)
print ('Current bitcoin price in %s: %s' % (currency_code, price.amount))

How to retrieve spot price data with the Coinbase API?

Retrieving spot price data with the Coinbase API is easy to do. For this example let’s retrieve the historical Bitcoin to USD spot price for the 06.06.2020 date.

As in our previous examples we’ll import the library and authenticate the API key:

coinbase_API_key = “Your API Key”
coinbase_API_secret = “Your API Secret”
client = Client(coinbase_API_key, coinbase_API_secret)

After this, let’s ask for the spot price date of our asset with a specified date time:

price = client.get_spot_price(currency_pair= 'BTC-USD', date='2020-06-06')

That’s it. 😀

How to retrieve historical data using the Coinbase API?

In this example we’ll obtain the historical price data for Ethereum converted to the EUR value. In order to do this we’ll import the relevant libraries and authorize our API key:

from coinbase.wallet.client import Client
from coinbase.wallet.model import APIObject
coinbase_API_key = “Your API Key”
coinbase_API_secret = “Your API Secret”
client = Client(coinbase_API_Key, coinbase_API_Secret)

After that, we’ll ask for the historical price data:

client._make_api_object(client._get('v2', 'prices', 'ETH-EUR', 'historic'), APIObject)

Allow me to show you how to get historic rates using the Coinbase API Pro as I find it more thorough to use. Firstly, we’ll need to install the Coinbase API Pro as it has its own library and documentation.

pip install cbpro
import cbpro
public_client.get_product_ticker(product_id='ETH-USD')

Now, let’s access the public client that the Coinbase API Pro.

public_client = cbpro.PublicClient()

After this, let’s obtain the list of products:

public_client.get_products()

And check for the ticker we’ll work on:

public_client.get_product_ticker(product_id='ETH-USD')

Now, let’s obtain the historic rates:

data =public_client.get_product_historic_rates('ETH-USD')

This data will lead us straight to the next chapter where we will discuss the simple moving average.

How to access technical indicators such as the 20 SMA with the Coinbase API?

In this example, I’ll show you how to create the 20 SMA and access other technical indicators. Have in mind that this example is leaning on the previous one, so if you jumped to here, be sure to read the chapter above.

For this to work, we’ll import the following libraries:

import pandas as pd
import btalib	

The bta-lib library is a technical indicator library made by the creator of the Backtrader backtesting framework.

Now, we shall only keep what we need from the obtain data and that is the date, high, low, open, close. We don’t need the last column so let’s get rid of it:

for line in data:
    del line[5:]

After it is cleaned, let’s create a pandas data frame and name the columns:

dataframe = pd.DataFrame(data, columns=['date', 'open', 'high', 'low', 'close'])
dataframe.set_index('date', inplace=True)
print(dataframe.head())

And let’s save our data frame to a CSV file:

dataframe.to_csv('HistoricRates')

Pandas can do a lot of stuff and I’m going to calculate the 20SMA with it first and then show you how to do it with the bta-lib that can access more indicators such as the RSI.

dataframe['20sma'] = dataframe.close.rolling(20).mean()
print(dataframe.tail(5))

And the other one:

sma = btalib.sma(dataframe.close)
print(sma.df)

As the bta-lib calculates the 30 simple moving average, we’ll need to change it. And while at it, let’s add it to our data frame some we can compare the two 20 SMA:

dataframe['sma'] = btalib.sma(dataframe.close, period=20).df
print(dataframe.tail())

How to send and receive Bitcoin with the Coinbase API?

In order to receive or send Bitcoin with the Coinbase API we’ll need to go through the following steps:

  • Generate a bitcoin address in order to receive funds
  • Send funds from the Coinbase wallet to a bitcoin address or email
  • Request funds via email address

Let’s start by creating our bitcoin address for the primary wallet. Firstly, we’ll add the required library and authenticate the API key and secret:

coinbase_API_key = “Your API Key”
coinbase_API_secret = “Your API Secret”
client = Client(coinbase_API_key, coinbase_API_secret)

Now, let’s create a primary account address:

primary_account = client.get_primary_account()
address = primary_account.create_address()
print (address)

After creating the address we can send funds to it. With the following code we’ll be able to send the funds to our primary wallet:

primary_account = client.get_primary_account()

send = primary_account.send_money(to=address,
                                amount='0.01',
                                currency='BTC')

If we want to receive funds the code is similar with a few alterations. We can even specify an email or an address for our request:

primary_account = client.get_primary_account()

tx = primary_account.request_money(to=’[email protected]’,
                                   amount='0.1',
                                   currency='BTC')

Another and easier way is to log in to your Coinbase profile and in the upper right corner click send or receive. After that a window will pop-up asking you to specify to whom, add a note, and payment type.

How to buy and sell Bitcoin with the Coinbase API?

As in our previous examples we’ll import the library and authorize our API key:

from coinbase.wallet.client import Client
coinbase_API_key = “Your API Key”
coinbase_API_secret = “Your API Secret”
client = Client(coinbase_API_key, coinbase_API_secret)

Before trying to buy or sell anything we will need to check if our payment method is verified:

payment_methods = client.get_payment_methods()

In order to buy or sell Bitcoin we’d also want to check for their prices. That can be done with the following code:

client.get_sell_price(currency_pair = 'BTC-EUR’)

client.get_buy_price(currency_pair = 'BTC-EUR’)

After confirming that we can buy or sell bitcoin and checking their prices, we can go ahead and construct some simple price checks. These price checks will run buy or sell functions when the price of bitcoin crosses the specified threshold:

account = client.get_primary_account()
payment_method = client.get_payment_methods()[0]

Let’s add the thresholds:

buy_price_threshold  = 300
sell_price_threshold = 450

Now, we will ask for the currencies again:
buy_price  = client.get_buy_price(currency=’EUR’)
sell_price = client.get_sell_price(currency=’EUR’)

The next step is to add the “if” statements that will conduct the buying or selling requests. On top of that, we’ll also specify the currency (BTC):

if float(sell_price.amount) 
  sell = account.sell(amount='1',
                      currency="BTC",
                      payment_method=payment_method.id)

if float(buy_price.amount) 
  buy = account.buy(amount='1',
                    currency="BTC",
                    payment_method=payment_method.id)

When it comes to the Coinbase Pro, it offers a trading platform that we can use. For this example we will use their virtual sandbox and explore its features. The sandbox can be found on the following link:

https://public.sandbox.pro.coinbase.com/trade/ETH-BTC

As we can see, the options that are in front of us are deposit and withdraw, and buy and sell. For the buy and sell options we can specify our amount, limit, and stop price:

We can also alternate between the candlestick and line chart and also add overlays as EMA 12 and EMA 26

For portfolio creation we can click the portfolio button in the top right corner:

What are access and refresh tokens in the Coinbase API?

Coinbase implemented an optional security feature of OAuth2 that uses the refresh tokens. When we first authenticate, our app will give us an access token and a refresh token.

The purpose behind the access token is to authenticate our requests and it expires after about two hours. When it is expired the refresh token comes into play as it allows us to get a new access token and refresh token.

Have in mind that the refresh token doesn’t have an expiration date, but it can only be used once for a new set of access and refresh tokens.

Potential errors and warning

While writing this article I ran into several problems and informing you about them will be helpful.

Firstly, the libraries for the Coinbase API aren’t official and their updates aren’t frequent. In my opinion, the standard Coinbase API can’t compete with the Coinbase API Pro.

Also, you may run into bugs while writing the code that will say that the variable isn’t defined when it is. The workaround for this was to restart the kernel or move the line of code into a new cell.

Sometimes the code written in the Coinbase API documentation simply won’t work and thus you’ll need to rely on the source code that appears when you try to run it.

The tutorials on the Coinbase API website are quite simplistic and they don’t go into the coding part much. Thus, I’d advise beginners to practice coding with other, more tutorial/lecture-friendly, API’s before trying to learn this one.

Download Code

Link: https://github.com/Lucas170/Coinbase-API-Guide-AlgoTrading101

Igor Radovanovic