Skip to main content

Plot crypto prices in real time

· 5 min read
DALL·E prompt: Crypyo coins and a line graph floating in a yellow room, highly detailed 3d digital art [yes, crypyo was a typo]
JJ Brosnan

If you've used Python for data visualization, you probably used Matplotlib to do it. It has long been the most popular visualization toolkit for Python. So why not use it for real-time applications like in the videos above? I'll show how easy that can be with Deephaven's Matplotlib plug-in.

What better data to plot than cryptocurrencies? Real-time visualization of prices is a simple way to lower risk of investment. Don't rely on outside sources for your real-time pricing graphs - do it yourself with the tools you've come to know and love.

Read on to learn how I made the animated chart above.

Get started

Our how to use Matplotlib and Seaborn guide has all of the information you need to get up and running with Deephaven, Matplotlib, and Seaborn.

Get real-time crypto data

For this application, I'll be pulling data from CryptoWatch's Public Data API. I get 10 CryptoWatch credits per day. Each time I pull a live price for a given coin, currency, and exchange from the API, it costs me 0.005 credits. I can make 2000 of these requests per day.

To make the requests, I'll be using the requests package. It is tailor-made for this type of application. It doesn't come stock with Deephaven, so install it using your preferred method from our how to install Python packages guide.

Use the CryptoWatch Public Data API

To use the public data API, you'll need a URL. For live prices, copy this url:

https://api.cryptowat.ch/markets/{exchange}/{pair}/price

Where:

  • exchange is a cryptocurrency exchange available on the API. Exchanges include kraken and bitfinex.
  • pair is a coin and currency symbol. Coin symbols include btc and eth, and currency symbols include usd and eur.

If you want the price of Bitcoin in USD on the Kraken exchange, this is the URL:

https://api.cryptowat.ch/markets/kraken/btcusd/price

Write the data to a table

Since getting the data is that simple, let's briefly discuss putting it into a Deephaven table for consumption. I use DynamicTableWriter. Here's my query without any plotting. It pulls current prices for xrp, ada, and matic in USD on kraken every 15 seconds for 3 minutes.

from deephaven import DynamicTableWriter
from deephaven import dtypes as dht
import itertools
import threading
import requests
import time
import sys

exchange = "kraken"
coins = ["xrp", "ada", "matic"]
currencies = ["usd"]

pairs = ["".join(item) for item in list(itertools.product(coins, currencies))]

col_defs = {**{"Time": dht.long}, **{coin.title(): dht.double for coin in coins}}

table_writer = DynamicTableWriter(col_defs)
live_crypto_prices = table_writer.table

num_writes = 12
time_between_writes = 15

def write_live_crypto():
for write_idx in range(num_writes):
start = time.time()
epoch_time = int(start)
prices = [0.] * len(pairs)
for pair_idx, pair in enumerate(pairs):
url = f"https://api.cryptowat.ch/markets/{exchange}/{pair}/price"
resp = requests.get(url)
if not(resp.status_code == 200):
print(f"The request failed with status code {resp.status_code}.")
sys.exit()
json_data = resp.json()
prices[pair_idx] = json_data["result"]["price"]
table_writer.write_row(epoch_time, prices[0], prices[1], prices[2])
end = time.time()
time.sleep(time_between_writes - (end - start))

cw_credits_left = json_data["allowance"]["remaining"]
print(f"You have {cw_credits_left} CryptoWatch credits remaining after this query.")

thread = threading.Thread(target=write_live_crypto)
thread.start()

Bring Matplotlib into the mix

Using Matplotlib in Deephaven is easy. It follows the same syntax you're used to, with a simple addition to make the figure update with your data.

Import the plug-in

To use Matplotlib in Deephaven for real-time applications, start by using the proper imports.

from deephaven.plugin.matplotlib import TableAnimation

import matplotlib.pyplot as plt

Define plots, axes, and data

For this application, we'll be making a single plot with three different lines.

crypto_fig = plt.figure()
crypto_ax = crypto_fig.subplots()
xrp_line, = crypto_ax.plot([], [], label="XRP")
ada_line, = crypto_ax.plot([], [], label="ADA")
matic_line, = crypto_ax.plot([], [], label="MATIC")
crypto_ax.set_xlabel("Seconds from epoch")
crypto_ax.set_ylabel("Price (USD)")
crypto_ax.legend()

Define the function to animate the figure

This is the additional step required to use Matplotlib for real-time applications. Don't worry, it's simple, and follows the same syntax regardless of what you're trying to plot.

def animate_mpl_fig(data, update):
xrp_line.set_data([data["Time"], data["Xrp"]])
ada_line.set_data([data["Time"], data["Ada"]])
matic_line.set_data([data["Time"], data["Matic"]])
crypto_ax.relim()
crypto_ax.autoscale_view(True, True, True)

The code block above animates the crypto figure by:

  • Setting the updated data for each crypto symbol
  • Resizing the x and y-axis limits
  • Rescaling the view to fit all data

Call the function

The final step is to call the animate_mpl_fig function. It takes three inputs:

  • The figure containing data (in this case it's crypto_fig).
  • The table containing data (in this case it's live_crypto_prices).
  • The function defining how to animate the figure (animate_mpl_fig).
ani = TableAnimation(crypto_fig, live_crypto_prices, animate_mpl_fig)

Put it all together

Here's the entire query to pull live crypto prices from CryptoWatch, place them in a table, and animate a Matplotlib figure:

Full code
from deephaven.plugin.matplotlib import TableAnimation
from deephaven import DynamicTableWriter
from deephaven import dtypes as dht

import matplotlib.pyplot as plt
import itertools
import threading
import requests
import time
import sys

exchange = "kraken"
coins = ["xrp", "ada", "matic"]
currencies = ["usd"]

pairs = ["".join(item) for item in list(itertools.product(coins, currencies))]

crypto_fig = plt.figure()
crypto_ax = crypto_fig.subplots()
xrp_line, = crypto_ax.plot([], [], label="XRP")
ada_line, = crypto_ax.plot([], [], label="ADA")
matic_line, = crypto_ax.plot([], [], label="MATIC")
crypto_ax.set_xlabel("Seconds from epoch")
crypto_ax.set_ylabel("Price (USD)")
crypto_ax.legend()

col_defs = {**{"Time": dht.long}, **{coin.title(): dht.double for coin in coins}}

table_writer = DynamicTableWriter(col_defs)
live_crypto_prices = table_writer.table

num_writes = 12
time_between_writes = 15

def write_live_crypto():
for write_idx in range(num_writes):
start = time.time()
epoch_time = int(start)
prices = [0.] * len(pairs)
for pair_idx, pair in enumerate(pairs):
url = f"https://api.cryptowat.ch/markets/{exchange}/{pair}/price"
resp = requests.get(url)
if not(resp.status_code == 200):
print(f"The request failed with status code {resp.status_code}.")
sys.exit()
json_data = resp.json()
prices[pair_idx] = json_data["result"]["price"]
table_writer.write_row(epoch_time, prices[0], prices[1], prices[2])
end = time.time()
time.sleep(time_between_writes - (end - start))

cw_credits_left = json_data["allowance"]["remaining"]
print(f"You have {cw_credits_left} CryptoWatch credits remaining after this query.")

def animate_mpl_fig(data, update):
xrp_line.set_data([data["Time"], data["Xrp"]])
ada_line.set_data([data["Time"], data["Ada"]])
matic_line.set_data([data["Time"], data["Matic"]])
crypto_ax.relim()
crypto_ax.autoscale_view(True, True, True)

thread = threading.Thread(target=write_live_crypto)
thread.start()

ani = TableAnimation(crypto_fig, test_table, animate_mpl_fig)

Further reading