Coinbase API - A Introduction Guide - AlgoTrading101 Blog (2024)

Coinbase API - A Introduction Guide - AlgoTrading101 Blog (1)

Last Updated on April 3, 2023

Coinbase API - A Introduction Guide - AlgoTrading101 Blog (2)

Table of contents:

  1. What is Coinbase API?
  2. What is Coinbase?
    • What can I trade on Coinbase?
    • What are the pricing and fees of 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

» If you are looking for the guide for Coinbase Pro API, check this out instead:

Link: Coinbase Pro API – An Introductory Guide

What is Coinbase API?

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

Link: https://www.coinbase.com

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.

Here are some user and revenue statistics about Coinbase: Coinbase Statistics.

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.

Coinbase API - A Introduction Guide - AlgoTrading101 Blog (3)

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.

Coinbase API - A Introduction Guide - AlgoTrading101 Blog (4)

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.

Coinbase API - A Introduction Guide - AlgoTrading101 Blog (5)

The following screen will appear:

Coinbase API - A Introduction Guide - AlgoTrading101 Blog (6)

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.

Coinbase API - A Introduction Guide - AlgoTrading101 Blog (7)

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 = 0message = [ ]

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 ))
Coinbase API - A Introduction Guide - AlgoTrading101 Blog (8)

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 Clientcoinbase_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))
Coinbase API - A Introduction Guide - AlgoTrading101 Blog (9)

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. 😀

Coinbase API - A Introduction Guide - AlgoTrading101 Blog (10)

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 Clientfrom coinbase.wallet.model import APIObjectcoinbase_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)
Coinbase API - A Introduction Guide - AlgoTrading101 Blog (11)

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 cbproimport cbpropublic_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')
Coinbase API - A Introduction Guide - AlgoTrading101 Blog (12)

Now, let’s obtain the historic rates:

data =public_client.get_product_historic_rates('ETH-USD')
Coinbase API - A Introduction Guide - AlgoTrading101 Blog (13)

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 pdimport 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))
Coinbase API - A Introduction Guide - AlgoTrading101 Blog (14)

And the other one:

sma = btalib.sma(dataframe.close)print(sma.df)
Coinbase API - A Introduction Guide - AlgoTrading101 Blog (15)

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).dfprint(dataframe.tail())
Coinbase API - A Introduction Guide - AlgoTrading101 Blog (16)

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)
Coinbase API - A Introduction Guide - AlgoTrading101 Blog (17)

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=’[emailprotected]’, 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.

Coinbase API - A Introduction Guide - AlgoTrading101 Blog (18)
Coinbase API - A Introduction Guide - AlgoTrading101 Blog (19)

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 Clientcoinbase_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’)
Coinbase API - A Introduction Guide - AlgoTrading101 Blog (20)

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 = 300sell_price_threshold = 450Now, 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

Coinbase API - A Introduction Guide - AlgoTrading101 Blog (21)

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:

Coinbase API - A Introduction Guide - AlgoTrading101 Blog (22)

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

Coinbase API - A Introduction Guide - AlgoTrading101 Blog (23)
Coinbase API - A Introduction Guide - AlgoTrading101 Blog (24)
Coinbase API - A Introduction Guide - AlgoTrading101 Blog (25)

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

Coinbase API - A Introduction Guide - AlgoTrading101 Blog (26)

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

Coinbase API - A Introduction Guide - AlgoTrading101 Blog (2024)

FAQs

Where is Coinbase API secret key? ›

Sign in to your account and access your Settings by selecting the profile menu in your account and choosing Settings from the drop-down menu. Select the Security tab to view your current API keys and select New API key to generate a new key. This should appear under your existing API Keys automatically.

Does Coinbase have a free API? ›

Are there examples of free Coinbase APIs? There are several free APIs for Coinbase currently available. Some examples include Coinranking and CoinGecko.

Does Coinbase allow algorithmic trading? ›

Algo trading is permitted under certain regulations. However, it's important to note that while algo trading is permitted, it must be done in a manner that complies with the rules and regulations of the jurisdiction in which the trader operates.

How to make money fast with Coinbase? ›

10 ways to make money on Coinbase
  1. Learn and earn rewards.
  2. Stake with Coinbase Earn.
  3. Earn stablecoin rewards.
  4. Become a Coinbase affiliate.
  5. Get a Coinbase sign-up bonus.
  6. Earn cash back with a Coinbase card.
  7. Save on fees with Coinbase One.
  8. Get into DeFi with Coinbase Wallet.
Feb 1, 2024

How do I generate API secret from Coinbase? ›

Under Profile Information, select the API Settings tab, then select + New API Key. Select your profile and appropriate permissions, create a passphrase, and then enter in your 2-step verification code. Finally, select Create API Key at the bottom to make a unique key.

What is the API secret on Coinbase? ›

An API Secret or API Private Key is simply another string of characters that must be used in combination with the API Key to establish the connection. An additional security layer can be added by generating an API Passphrase.

How to make free money with Coinbase? ›

Coinbase sign up rewards

To receive a sign up reward, you'll need to create a Coinbase account and buy cryptocurrency. Once you've done this, you'll be able to spin a wheel to receive sign-up rewards between $3 and $200 in USDC or Bitcoin!

What is the API limit for Coinbase? ›

Advanced Trade API private endpoints are throttled by user at 30 requests per second. Advanced Trade API public endpoints are throttled by IP address at 10 requests per second.

Can you trade with Coinbase API? ›

Connect, build, and trade with Coinbase Advanced API.

Automate market, limit, and stop-limit orders by building with REST API or leverage your preferred trading bot². Security features include 2FA, mobile biometrics, YubiKey for mobile, Address Whitelisting, and more.

Is algorithmic trading illegal? ›

Yes, algorithmic trading is legal. There are no rules or laws that limit the use of trading algorithms. Some investors may contest that this type of trading creates an unfair trading environment that adversely impacts markets. However, there's nothing illegal about it.

What is the best algorithm for crypto trading? ›

Top Crypto Trading Algorithm Strategies to Get Long-Term Benefits
  • Scalping. ...
  • Momentum Trading Crypto. ...
  • Buy Dips and Hold. ...
  • Day Trading Strategy. ...
  • Range Trading. ...
  • Reverse Trading. ...
  • High-Frequency Trading (HFT)

Can I do algorithmic trading on my own? ›

To create algo-trading strategies, you need to have programming skills that help you control the technical aspects of the strategy. So, being a programmer or having experience in languages such as C++, Python, Java, and R will assist you in managing data and backtest engines on your own.

How do I get $200 free on Coinbase? ›

Additional terms
  1. Valid for new Coinbase users who make a cryptocurrency purchase on Coinbase.
  2. All new users who spin the wheel will randomly receive a reward, in either USD or Bitcoin, determined by Coinbase in its sole discretion, between $3 - $200.

Can you make good money on Coinbase? ›

Coinbase Earn is a program that allows users to earn cryptocurrency rewards by completing educational tasks. The amount of money you can earn depends on the specific tasks and the value of the cryptocurrencies you earn, but it's generally possible to make a decent profit if you're strategic about it.

What app gives free cryptocurrency? ›

Platforms like Coinbase and Binance allow you to earn cryptocurrency for free after completing short educational modules. While there are some investors who trade cryptocurrency full-time, it's important to remember that cryptocurrency is volatile and that investors should be aware of potential risks.

How do I get an API key? ›

To create your application's API key:
  1. Go to the API Console.
  2. From the projects list, select a project or create a new one.
  3. If the APIs & services page isn't already open, open the left side menu and select APIs & services.
  4. On the left, choose Credentials.
  5. Click Create credentials and then select API key.

What is my Coinbase private key? ›

When you first buy cryptocurrency, you are issued two keys: a public key, which works like an email address (meaning you can safely share it with others, allowing you to send or receive funds), and a private key, which is typically a string of letters and numbers (and which is not to be shared with anyone).

What is API key and secret? ›

Public API keys These are most often used for read-only access to public data. These may be embedded in client-side applications. Secret API keys These are used for access to sensitive data (and may include write access). As the name implies, these are secret and shouldn't be shared publicly.

Top Articles
Latest Posts
Article information

Author: Chrissy Homenick

Last Updated:

Views: 5821

Rating: 4.3 / 5 (54 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Chrissy Homenick

Birthday: 2001-10-22

Address: 611 Kuhn Oval, Feltonbury, NY 02783-3818

Phone: +96619177651654

Job: Mining Representative

Hobby: amateur radio, Sculling, Knife making, Gardening, Watching movies, Gunsmithing, Video gaming

Introduction: My name is Chrissy Homenick, I am a tender, funny, determined, tender, glorious, fancy, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.