Display crypto data real-time in a chart using Sveltekit, Chart.js & coincap.io

Hessel
6 min readFeb 17, 2023

--

In recent years, cryptocurrency has become a popular investment option for many people around the world. As the cryptocurrency market continues to grow, the demand for real-time data visualization tools has also increased. In this tutorial, you will learn how to display crypto data in real-time using a combination of Sveltekit , Chart.js and coincap.io.

Create a Sveltekit project

The first step we need to take is to set up our Sveltekit project and install the necessary dependencies. If you already have a Svelte project, you can skip this.

To set up a new Sveltekit project, first, make sure that you have Node.js and npm installed on your machine. Then, open a terminal window and run the following command to create a new project:

npm create svelte@latest my-app

then you will get to see the following in your terminal:

Sveltekit installation terminal

For this tutorial, we will go for the second option named “Skeleton project”.

Then they will ask you for a bunch of options like do you want to add type checking, ESLint, prettier for code formatting, browser testing and Vitest for unit testing. For this tutorial, I selected no for every option, since we don’t need it right now:

Now that you have created your Sveltekit project, head over to that directory and run the following commands:

#install the dependencies
npm install

#Serve your project
npm run dev

If everything went correct, you should now have a working Sveltekit project.

Setting up Chart.js

The next step is to set up Chart.js, a popular JavaScript library for creating interactive charts and graphs. Chart.js makes it easy to create dynamic and visually appealing charts.

To get started with Chart.js, we need to install it as a dependency in our Sveltekit project. From the root directory of our project, run the following command:

npm install chart.js

This will download and install the latest version of Chart.js in our project.

Next, we need to import Chart.js into our Svelte component. Open the file src/routes/+page.svelte in your code editor and add the following code:

<script>
import Chart from 'chart.js/auto';

import { onMount } from 'svelte';

onMount(() => {

});

</script>

First, we’re using the import statement to import the Chart.js library and make it available to use in our code. We're also importing the onMount function from Svelte, which allows us to run code when the component is first mounted.

Inside the onMount function, we'll be writing the code to initialize the chart:

<script>
import Chart from 'chart.js/auto';

import { onMount } from 'svelte';

onMount(() => {
const ctx = document.getElementById('chart');
const chart = new Chart(ctx, {
//Type of the chart
type: 'line',
data: {
//labels on x-axis
labels: [],
datasets: [{
//The label for the dataset which appears in the legend and tooltips.
label: 'Price',
//data for the line
data: [],
//styling of the chart
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
],
borderColor: [
'rgba(255, 99, 132, 1)',
],
borderWidth: 1
}]
},
options: {
scales: {
//make sure Y-axis starts at 0
y: {
beginAtZero: true
}
},
}
});
});

</script>
<div>
<canvas id="chart"></canvas>
</div>

The const ctx = document.getElementById('chart'); line selects the DOM element with an ID of chart, which is where our chart will be rendered. The next line creates a new instance of the Chart object and assigns it to the variable chart. This allows us to interact with the chart, which we have to do later on.

By setting the initial configuration of our chart inside the onMount function, we ensure that the chart is only created once, when the component is first mounted. Now that we have configured the chart, our webpage should now look similar to this:

Update the chart real-time

In order to update our chart, we first need data. In this tutorial, we will be using coincap.io to get our data. To get started, we need the websocket from coincap.io

<script>
import Chart from 'chart.js/auto';

import { onMount } from 'svelte';

let prices = {}

onMount(() => {

/* chart config here */

const socket = new WebSocket('wss://ws.coincap.io/prices?assets=bitcoin,ethereum,litecoin,maker,dogecoin,stellar,algorand,basic-attention-coin,compound,celo')
socket.onmessage = e => {
let data = JSON.parse(e.data);

};

})

</script>

we’re setting up a WebSocket connection to the coincap.io API to receive real-time cryptocurrency price data. The const socket = new WebSocket('wss://ws.coincap.io/prices?assets=bitcoin,ethereum,litecoin,maker,dogecoin,stellar,algorand,basic-attention-coin,compound,celo') line creates a new WebSocket connection to the wss://ws.coincap.io/prices endpoint with a query parameter specifying the assets we want to receive updates for.

The socket.onmessage event handler is called every time a new message is received from the WebSocket. We parse the JSON data in the message using JSON.parse(e.data).

<script>
import Chart from 'chart.js/auto';

import { onMount } from 'svelte';

let prices = {}

onMount(() => {

/* chart config here */

const socket = new WebSocket('wss://ws.coincap.io/prices?assets=bitcoin,ethereum,litecoin,maker,dogecoin,stellar,algorand,basic-attention-coin,compound,celo')
socket.onmessage = e => {
let data = JSON.parse(e.data);
Object.keys(data).forEach(ticker => {

if (!prices[ticker]) {
prices[ticker] = { price: parseFloat(data[ticker])};

return;
}
prices[ticker] = { price: parseFloat(data[ticker])};
});
};

})

</script>

In the code Object.keys(data).forEach(ticker => { ... }), we're using the Object.keys() method to get an array of all the keys (i.e. the tickers) in the data object, which contains the latest prices for the cryptocurrencies we're interested in.

Next, for each ticker, we have to check whether it’s already in our prices object using if (!prices[ticker]) { ... }. If it's not, we create a new entry in the prices object with the initial price data. If it is, we simply update the existing price data.

Finally, we update the chart with the new price data:

<script>
import Chart from 'chart.js/auto';

import { onMount } from 'svelte';

let prices = {}

onMount(() => {

/* chart config here */

const socket = new WebSocket('wss://ws.coincap.io/prices?assets=bitcoin,ethereum,litecoin,maker,dogecoin,stellar,algorand,basic-attention-coin,compound,celo')
socket.onmessage = e => {
let data = JSON.parse(e.data);
Object.keys(data).forEach(ticker => {

if (!prices[ticker]) {
prices[ticker] = { price: parseFloat(data[ticker])};

return;
}
prices[ticker] = { price: parseFloat(data[ticker])};
});
};

setTimeout(() => {
chart.data.labels = Object.keys(prices);
chart.data.datasets[0].data = Object.values(prices).map(p => p.price);
chart.update();
}, 2000);

})

</script>

We're using the setTimeout() function to delay the chart update by 2 seconds. We do this to prevent the chart from being updated too frequently, because updating it too frequently could cause problems. You can remove this to get constant updates, but I decided for this tutorial to add a small delay.

In the setTimeout() function, we're updating the chart.data.labels and chart.data.datasets[0].data properties with the latest data from the prices object, which is being continuously updated with new price data as it comes in through the WebSocket connection.

We’re using the Object.keys(prices) method to get an array of the ticker symbols, which we use to set the labels property of the chart. We're using the Object.values(prices).map(p => p.price) method to get an array of the latest prices for each ticker, which we use to set the data property of the chart's first dataset.

Finally, we call chart.update() to redraw the chart with the new data.

And that’s it, we now have a chart that continuously updates with real-time data. Now it looks like that chart is not updating, and that is because the prices don’t skyrocket. If you hover over the dots on the line in the chart, you will see that the value is updating:

The reason I chose Sveltekit not just Svelte is that some people want to integrate this into a dashboard and usually dashboards are behind authentication and Sveltekit is used if it comes to authentication.

--

--

Hessel

Web developer sharing knowledge on Web Development through Medium articles. From beginner to advanced topics, follow me to improve your skills and stay current.