Connect to Coinbase Pro API using Python

Hisho Rajanathan
3 min readFeb 6, 2022
Photo by Pierre Borthiry on Unsplash

Do you want to run some trading strategies on the cryptocurrency market? Look no further! This post shows you how to connect to the Coinbase API using Python.

First thing that needs to be done is to log in to your Coinbase Pro account https://pro.coinbase.com

Select API

Select +New API Key to create a new API.

You can give your API key a nickname, I left this blank. I ticked all the permission boxes and give a passphrase.

Note down the Passphrase, Secret API Key and once you have created the API Key, note down the API key too as this will be needed.

To connect to Coinbase Pro using your newly generated API keys, the ccxt library will be used: https://github.com/ccxt/ccxt

The ccxt library is a powerful library, which allows you to connect to multiple cryptocurrency exchanges including Binance, Coinbase and Coinbase Pro. The following code allows you to connect to your Coinbase Pro account:

import ccxt
import config
API_KEY = "*********"
SECRET_KEY = "*******"
PASSWORD = "*******"
exchange = ccxt.coinbasepro({"apiKey": config.API_KEY,"secret": config.SECRET_KEY,"password": config.PASSWORD})print(exchange.fetch_balance())

The code above allows you to print the balance from your own account.

Looking at the documentation from the ccxt GitHub page, the call below allows us to get the price for a specific symbol.

exchange.fetch_ohlcv()

To store the prices in for a certain cryptocurrency symbol, the code below converts the output from a dictionary into a pandas dataframe. The example below is for the cryptocurrency pair BTC/USDT.

bars = exchange.fetch_ohlcv('BTC/USDT', timeframe='1m', limit=100)df = pd.DataFrame(bars[:-1], columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')print(df.head())

To make a market buy order using the ccxt library:

order = exchange.create_market_buy_order (symbol, amount[, params])

Similarly, to make a market sell order:

order = exchange.create_market_sell_order (symbol, amount[, params])

For example if you wanted to traded Solana against the Pound, the symbol would be ‘SOL/GBP’.

The amount parameter would be how much Solana to buy. The price of Solana as of 06/02/2022 at 19:10 GMT is £83.08. Therefore, if the amount you have selected is 0.05 as a market buy order, your position in SOL/GBP would equate to £4.15 before fees.

The CCXT library allows limit orders as well. Please look at the documentation to see how to create a limit order.

Thank you for reading this post! If you liked this post, please follow me on Medium.

To see how to connect to Binance, please look at my other post found here.

Link to my GitHub repository: https://github.com/Hishok

Connect with me on LinkedIn.

--

--