May 17, 2023

Create Python Cryptocurrency Charts with CoinAPI

featured image

Create Python Cryptocurrency Charts with CoinAPI

Here’s a step-by-step guide to creating interactive cryptocurrency charts with Python and CoinAPI. This tutorial shows how to fetch historical OHLCV data from the CoinAPI Market Data REST API, convert it into a Pandas DataFrame, and visualize it as an interactive candlestick chart with Plotly.

Start by setting up a new Python project. Create a directory for your project and navigate to it in your terminal or command prompt.

You’ll also need a CoinAPI API key.

Create an account in the API BRICKS Console, generate a CoinAPI Market Data API key, and use it to authenticate your requests. New users can start with $25 in free credits to test API calls.

For local development, it is better to store your API key as an environment variable instead of placing it directly in your Python source code.

For example:

1export COINAPI_KEY="YOUR_API_KEY"

Then access it in Python:

1import os
2
3API_KEY = os.environ["COINAPI_KEY"]

Do not commit API keys to GitHub or expose them in frontend code.

To begin, install the packages required to retrieve, process, and visualize the data.

For this tutorial, you’ll need:

  • requests for CoinAPI REST requests
  • pandas for working with OHLCV data
  • plotly for interactive charts

Install them using pip:

1pip install requests pandas plotly

You do not need to connect separately to individual exchanges. CoinAPI provides standardized access to supported exchange data through its Market Data API.

Before requesting historical OHLCV data, you need a valid CoinAPI symbol_id.

CoinAPI uses standardized identifiers that specify the exchange, instrument type, and asset pair.

For example:

1BITSTAMP_SPOT_BTC_USD

This identifies the BTC/USD spot market on Bitstamp.

You can discover supported symbols through the /v1/symbols endpoint:

1curl -H "X-CoinAPI-Key: YOUR_API_KEY" \
2"https://rest.coinapi.io/v1/symbols"

You can also query a specific identifier:

1curl -H "X-CoinAPI-Key: YOUR_API_KEY" \
2"https://rest.coinapi.io/v1/symbols?filter_symbol_id=BITSTAMP_SPOT_BTC_USD"

Using the complete symbol_id is important. The OHLCV endpoint expects an identifier such as BITSTAMP_SPOT_BTC_USD, rather than simply BTC or BTC/USD.

Now create a file named coinapi.py.

This tutorial uses the CoinAPI Market Data REST API to retrieve historical OHLCV bars.

1import os
2import requests
3import pandas as pd
4
5API_KEY = os.environ["COINAPI_KEY"]
6BASE_URL = "https://rest.coinapi.io/v1"
7
8
9def get_historical_ohlcv(
10    symbol_id,
11    period_id="1DAY",
12    time_start="2025-06-01T00:00:00",
13    limit=100
14):
15    url = f"{BASE_URL}/ohlcv/{symbol_id}/history"
16
17    headers = {
18        "X-CoinAPI-Key": API_KEY
19    }
20
21    params = {
22        "period_id": period_id,
23        "time_start": time_start,
24        "limit": limit
25    }
26
27    response = requests.get(
28        url,
29        headers=headers,
30        params=params,
31        timeout=30
32    )
33
34    if response.status_code == 429:
35        raise RuntimeError(
36            "Rate limit or quota exceeded. "
37            "Check your usage in the API BRICKS Console."
38        )
39
40    response.raise_for_status()
41
42    credits_used = response.headers.get("x-credits-used")
43    if credits_used:
44        print(f"Credits used: {credits_used}")
45
46    data = response.json()
47
48    if not data:
49        raise RuntimeError(
50            f"No OHLCV data returned for {symbol_id}."
51        )
52
53    df = pd.DataFrame(data)
54
55    df["time_period_start"] = pd.to_datetime(
56        df["time_period_start"]
57    )
58
59    return df

The request uses:

1/v1/ohlcv/BITSTAMP_SPOT_BTC_USD/history

to fetch historical OHLCV bars for the selected market.

The response can include fields such as:

  • time_period_start
  • time_period_end
  • price_open
  • price_high
  • price_low
  • price_close
  • volume_traded
  • trades_count

When experimenting with REST requests, start with a relatively small limit. You can also inspect the x-credits-used response header when available to monitor API usage.

OHLCV stands for Open, High, Low, Close, and Volume.

CoinAPI's OHLCV formation can use transaction and order book activity. If no trades occur during a period but the order book remains active, a bar can still be emitted with:

1volume_traded = 0
2trades_count = 0

This is useful to understand when interpreting periods with little or no trading activity.

Next, create a separate file named charting.py.

Because we are working with OHLCV data, a candlestick chart is more informative than plotting only price_close.

1import plotly.graph_objects as go
2
3
4def generate_chart(df, symbol_id):
5    fig = go.Figure(
6        data=[
7            go.Candlestick(
8                x=df["time_period_start"],
9                open=df["price_open"],
10                high=df["price_high"],
11                low=df["price_low"],
12                close=df["price_close"],
13                name=symbol_id
14            )
15        ]
16    )
17
18    fig.update_layout(
19        title=f"{symbol_id} OHLCV",
20        xaxis_title="Time",
21        yaxis_title="Price",
22        xaxis_rangeslider_visible=False
23    )
24
25    fig.show()

Plotly uses the CoinAPI fields price_open, price_high, price_low, and price_close to create each candle.

The result is an interactive chart that allows you to inspect historical BTC/USD price behavior directly in your browser.

Once the basic candlestick chart is working, you can extend it with additional visualizations.

For example, you could add:

  • Moving averages
  • Trading volume
  • Relative Strength Index (RSI)
  • Bollinger Bands
  • Multiple symbols
  • Different OHLCV periods

Advanced charting techniques can help visualize trends, volatility, volume, and historical price behavior for research and strategy analysis.

For example, a simple moving average can be calculated directly with Pandas:

1df["sma_20"] = df["price_close"].rolling(window=20).mean()

You could then add it to your Plotly chart:

1fig.add_trace(
2    go.Scatter(
3        x=df["time_period_start"],
4        y=df["sma_20"],
5        name="20-period SMA"
6    )
7)

These indicators are analytical tools rather than predictions of future market behavior.

Now create a main.py file and import the CoinAPI and charting functions:

1from coinapi import get_historical_ohlcv
2from charting import generate_chart
3
4SYMBOL_ID = "BITSTAMP_SPOT_BTC_USD"
5
6df = get_historical_ohlcv(
7    symbol_id=SYMBOL_ID,
8    period_id="1DAY",
9    time_start="2025-06-01T00:00:00",
10    limit=100
11)
12
13generate_chart(df, SYMBOL_ID)

Run the project:

1python main.py

The script will:

  1. Authenticate using your CoinAPI key.
  2. Request historical OHLCV data for BITSTAMP_SPOT_BTC_USD.
  3. Convert the response into a Pandas DataFrame.
  4. Parse the CoinAPI timestamps.
  5. Generate an interactive Plotly candlestick chart.

You can change SYMBOL_ID, period_id, time_start, and limit to explore different markets and historical periods.

The example above demonstrates a basic way to combine Python, Pandas, Plotly, and CoinAPI.

Instead of retrieving generic “historical prices,” the application is specifically requesting historical OHLCV bars for a CoinAPI symbol_id.

This distinction becomes important as your application grows because CoinAPI provides several different types of market data, including trades, quotes, order books, OHLCV, metrics, and metadata.

For continuous real-time charts, CoinAPI WebSocket streams are more appropriate than repeatedly polling historical REST endpoints.

For large historical research datasets, CoinAPI Flat Files provides bulk access to historical trades, quotes, order books, and OHLCV.

The example above is intentionally simple, but a production application should include a few additional safeguards.

  • Protect your API key. Store it in an environment variable or secrets manager rather than hardcoding it into your application.
  • Handle API errors. Check HTTP responses and implement appropriate handling for connection problems, invalid requests, and 429 responses.
  • Monitor usage. When available, log the x-credits-used response header and monitor your consumption in the API BRICKS Console.
  • Cache historical data. If the same historical period is used repeatedly, storing the result locally can prevent unnecessary API requests.
  • Use the right CoinAPI interface. REST is useful for targeted historical requests. WebSocket or FIX is better suited to continuous real-time market data, while Flat Files is designed for bulk historical datasets.

With a few Python packages and the CoinAPI Market Data REST API, you can retrieve historical OHLCV data and turn it into an interactive cryptocurrency chart.

From there, you can extend the project with volume charts, moving averages, additional symbols, technical indicators, or real-time WebSocket data.

Remember to replace YOUR_API_KEY with your own CoinAPI key when using the command-line examples. You can review current access and pricing on the Market Data API pricing page and find endpoint details in the CoinAPI documentation.

This tutorial is for educational purposes and is not investment advice.

How to deploy a currency alerting pipeline with Quix and CoinAPI

CoinAPI Flat Files for bulk historical cryptocurrency data

Recent Articles

Crypto API made simple: Try now or speak to our sales team