This page may contain legacy content

To get our most up-to-date content please access our documentation

October 5, 2021

How to Code Token Price Charts

Table of Contents

As a blockchain developer, the main focus is not generally spent solely monitoring individual token prices. Nevertheless, developers and users involved in the blockchain industry are still likely to keep an eye on different price charts. As such, developers should know how to code and implement token price charts into their decentralized applications (dApps), which enable users to view price movements for various tokens. This is a “must-have” feature for quality Web3 applications since most users want to observe the cryptocurrency market. Therefore, we’ll show how your decentralized applications can gain an extra edge and offer additional value to users by teaching you how to code token price charts with maximum ease.

In the following sections, we’ll cover all the details required for you to learn how to code token price charts. Moreover, you’ll realize that doing so is much simpler and quicker than you might have imagined when you use Moralis and its powerful platform. This ultimate Web3 development platform provides you with simple code snippets that take care of all the heavy lifting and backend-related work. By harnessing Moralis’ documentation, which is one of the best in the industry, you essentially copy and paste single lines of code to cover your dApps blockchain-related coding. Create your free account today to gain full access to Moralis’ platform, including Moralis Speedy Nodes, Moralis’ NFT API and its capable Web3 SDK. That way, you’ll be able to follow along as we cover the steps on how to code token price charts in the following sections. Let’s do this!  

What are Tokens?

If you’re new to crypto, you may not be sure what tokens are. Moreover, there seems to be confusion regarding terms such as “tokens” and “coins”, even among those who are veterans in the blockchain field. As such, let’s get you all up to speed. So, what’s this talk about crypto coins and crypto tokens?

Generally speaking, coins and tokens are largely the same. Coins, or native tokens, are cryptocurrencies native to a particular blockchain. For example, Bitcoin (BTC) is the coin for Bitcoin’s chain, Ether (ETH) is the coin for Ethereum’s chain, etc. Nevertheless, those coins mentioned are native to their chain. On the other hand, additional cryptocurrencies can be created on top of an existing chain, and in that case, we talk about tokens. For instance, most tokens in existence are built on top of the Ethereum blockchain following the ERC-20 token standard. As such, they are known as ERC-20 tokens. Of course, there are also many tokens built on other popular chains, including Binance Smart Chain, Polygon, Avalanche, and many others.

Furthermore, while crypto is still in its infancy, many token use cases are not yet fully implemented. As such, trading tokens remain the main point of interest among many users. Therefore, since one cannot trade without knowing the price and volatility of a token, learning how to code token price charts can indeed be a useful skill. 

How to Code Token Price Charts – Moralis Setup

Before we go into the exact steps that will clearly show you how to code token price charts, we need to cover the initial Moralis setup and its essential steps. Aside from signing up or logging in to your existing Moralis account, you need to create a new server and then initialize Moralis inside your HTML or JavaScript programming file.

These are the steps you need to complete to obtain a Moralis server’s ID and URL:

  1. Create Your Moralis Account – If you haven’t created your Moralis account yet, make sure to do so now. Remember: it’s completely free! Just follow this link, enter your email address and create your password. Next, you’ll need to confirm your email address (you’ll receive an email with a confirmation link). In case you already have an active Moralis account, just log in
  2. Create a New Server – Once you log into your Moralis account, you need to create a new server. You do this by clicking the “+ Create a new Server” button in the top-right corner. A drop-down menu will appear offering different types of networks (see the image below). We recommend starting with the “Testnet Server” option.

To complete this step, you need to enter the required details, including server name (it can be anything you want), select region, network, chain(s) (you can select one or multiple options), and click “Add instance”. 

  1. Access Server Details – Once you create a server, you can obtain the details (for use inside your “.html” or “.js” file). Just click the “View Details” button next to your server name. Next, a pop-up window will appear containing all of the information (see the image below). If this is not your first time using Moralis, you may already have one or more servers set up. In that case, you may use any of them.
  1. Initialize Moralis – All that’s left is to populate the “.html” or “.js” file with the Moralis server details (application ID and server URL). That way, you obtain the required backend functionality:

Note: Do not copy the server details from the image above. You need to use the details of your particular server.

How to Code Token Price Charts – An Example Project

Let’s start our “how to code token price charts” quest by looking at what we’ll be creating. Below is an image of the simple dApp we’ll create that enables us to display price action for a wide range of tokens.

Aside from the “login” and “logout” buttons, the Web3 application that we’ll build in order to teach you how to code token price charts includes an option to select the time frame (7, 14, or 30 days). Moreover, there’s also a drop-down menu. This enables users to select a token (by its ticker symbol) of which they can look at its price. The chart above has dollar amounts on its Y-axis and dates on its X-axis. 

As we move along, we’ll present you with particular code snippets. However, if you want to access the complete HTML code for this example project, it’s available on GitHub. 

Moreover, looking at the end goal of our example project, we can see that the chart-displaying part is a matter of the frontend coding. However, obtaining each token price at a specific time is the backend’s job, which we’ll entrust Moralis with. 

How to Code Token Price Charts – Getting Token Price

As mentioned, Moralis makes time-consuming tasks markedly quicker and easier, which we’ll experience when it comes to token price acquisition. To get a certain token price, all we need to do is using the following code snippet:

Moralis.Web3API.token.getTokenPrice(options)

The “options” part takes in several parameters, including chain (only needed when not focusing on Ethereum’s blockchain), exchange name (optional), and token address. However, since our example concerns Ethereum’s blockchain, which is a native chain, we can only use a token address as a parameter. Furthermore, a reliable way to obtain token addresses is by using “Etherscan”, where you can access contract addresses for all tokens based on Ethereum’s chain. When visiting a particular token’s Etherscan page, we also get to see its price, which we can use as a reference. 

If you want more details regarding the “getTokenPrice” function, check out the relevant section of Moralis’ documentation. 

Furthermore, the above function also has another parameter (to_block), which enables us to get the data from a specific block. When this is not specified, the function automatically returns the price from the latest block. However, when we specify this parameter, we can obtain the price of the token from any other block. 

Here’s an example of how the “getTokenPrice” function looks like in action for the “AAVE” token:

Moralis.Web3API.token.getTokenPrice({address:”0x7fc66500c84a76ad7e9c93437bfc5ac33e2ddae9”, to_block: 13359177 })

To access data of past blocks, we again use Etherscan. Use the “Blockchain” drop-down menu and then click on “View Blocks”:

Using the “getTokenPrice” function that Moralis offers and its “address” and “to_block” parameters, we get to access the latest price of any token, as well as the price recorded in past blocks. With that, we have all our Y-axis needs covered. Thus, we can shift our focus to the X-axis of our chart.

How to Code Token Price Charts – The X-Axis

Looking at the image displaying how we want our dApp to present the token price, we see that the X-axis of our chart should display dates. As such, we need to find a way to be able to collect the price of a token on specific dates instead of block numbers. Fortunately, we can again rely on Moralis to do the hard work on our behalf. 

Moralis.Web3API.native.getDateToBlock(options)

The above function accepts two parameters; one is “chain”, and it’s optional (by default, Ethereum’s chain is considered), the other one is “date”, which is required. Any date format accepted by “Moment.js” will work. Using the function above and entering a date as a parameter, we get a block number in return. Here’s an example:

Moralis.Web3API.native.getDateToBlock({date:“2021-10-05”})

If you want more details regarding the “getDateToBlock” function, check out the relevant section of Moralis’ documentation. 

The “getTokenPrice” and “getDateToBlock” functions let us easily create an array of data points (price-date pairs). Moreover, we can do this for a specific time frame and for every token that we want to display. Without these two functions provided, we’d spend weeks on backend coding. However, with Moralis, we can do this in minutes. 

How to Code Token Price Charts – Creating an Array

Inside our “index.html” file, we can now create an array. This will provide us with the data point to populate our chart. Here’s the code that will accomplish this:

let dates1 = Array(Number(days).fill().map((e.i) =>
moment().substract(i, “d”).format(“YYYY-MM-DD”)
).reverse()

Because we’re subtracting the dates, we need to use the “reverse()” function to get a proper format. To populate the above array, we use the two Moralis functions covered in the previous sections. Here are the lines of code that will help us get the blocks via dates:

let blocks1 = await Promise.all(dates1.map(async(e,i) =>
await Moralis.Web3API.native.getDateToBlock({date:e})
))

These is the code that will enable us to get the prices for the blocks assigned to our array:

let prices1 = await Promise.all(blocks1.map(async(e,i) =>
await Moralis.Web3API.token.getTokenPrice({address: addrs, to_block:e.block})
))

We add the above lines of code inside the “priceHistory()” function within our HTML file accessible in GitHub.

That’s it; now you know how to code token price charts! In case you prefer to be guided by a video tutorial, see the following one tackling the same example project:

https://www.youtube.com/watch?v=90dMpTlPNZ0

How to Code Token Price Charts – Summary

Since cryptocurrencies are the most popular blockchain use case, for now, it’s practical to know how to code token price charts quickly and easily. At this point, you should know how to use Moralis’ SDK to obtain single lines of code, enabling you to get the price of any token at any specific time. We do this with the “Moralis.Web3API.token.getTokenPrice()” and “Moralis.Web3API.native.getDateToBlock()” functions, and with some simple HTML coding, we can put that data to use. 

In case you’ve been developing in the blockchain field using a tedious way of building around RPC nodes, we encourage you to use Moralis to your advantage. Moralis’ Speedy Nodes make Moralis a cross-chain alternative, and is a great “Infura for BSC” option. With Moralis’ powerful Web3 API on your side, you’ll start creating and launching Web3 apps at much greater speed and with minimal resources spent. For instance, you can create your own ERC-20 tokens in minutes or BEP20 token, focus on NFT game development, or build a crypto wallet. Essentially, whatever crypto project you’re working on, Moralis will help you get to the finish line markedly quicker.

On the other hand, if you’re new to blockchain development, we suggest diving deeper into the wide range of valuable information we offer for free. On Moralis’ blog and Moralis’ YouTube channel, we cover numerous example projects as well as explain different concepts of this disruptive technology in an easy-to-understand manner. Moreover, in case you’re not proficient in JavaScript yet, we strongly recommend enrolling in the “JavaScript Programming for Blockchain Developers” course from Ivan on Tech Academy. We look forward to seeing the Web3 applications you’ll create and launch!

Moralis Money
Stay ahead of the markets with real-time, on-chain data insights. Inform your trades with true market alpha!
Moralis Money
Related Articles
January 14, 2023

ENS Resolver – How to Resolve any ENS Domain

January 31, 2023

Notify API Alternatives – Easiest Way to Set Up Web3 Notifications

October 16, 2023

How to Get the Current Price of an NFT – NFT API Guide

October 25, 2022

What is Sui Blockchain? – The Ultimate Guide

January 25, 2024

Why Did Crypto Go Up Today? Get Digital Currency Price Triggers via API

November 29, 2022

The Best ERC20 Token Balance API for Dapp Development

January 17, 2023

Polygon Mumbai Faucet – Get Free MATIC with this Mumbai Faucet

February 20, 2024

Crypto Portfolio Tracker Endpoint – Get Portfolio Data with a Single API Call 

December 11, 2022

Web3.js vs Ethers.js – The Full 2023 Guide to ETH JavaScript Libraries