Coins: 18,022
Exchanges: 1,481
Market Cap: $2.522T 3.3%
24h Vol: $115.74B
Gas: 0.236 GWEI
Upgrade to Premium
API
TABLE OF CONTENTS

Build a Candlestick Chart App with TradingView & CoinGecko API

4.4
| by
Cryptomaton
|
Edited by
Julia Ng
-

A candlestick chart is a type of financial chart used to represent the price movement of an asset over a specific period. Each candle on the chart provides a visual summary of price data, showing the open, high, low, and close prices of an asset within that specific candle interval.

In this article, we will build an interactive web app that plots candlestick charts using the TradingView Lightweight Charts library and the CoinGecko API for our historical dataset.

Build a Candlestick Chart App - CoinGecko API & TradingView


Requirements

To replicate a modern production environment, we'll build our application with SvelteKit. This user-friendly framework has everything we need to develop and deploy an interactive web application.

Here is everything you’re going to need:

  • Node.js and npm
  • An IDE
  • Some TypeScript knowledge (optional)
  • Some TailwindCSS knowledge (also optional)
  • A CoinGecko Demo API Key

You can access CoinGecko’s Demo API for free, but please note that it only provides historical data for up to 365 days and offers limited interval options. If your use case requires a larger dataset or more granular intervals, it's recommended to upgrade to a Pro API key.

To get started, create your CoinGecko account, head to the Developers’ Dashboard, and click on '+Add New Key' to generate a new API Key.


Configuring Your Project

After installing node.js, the first thing we want to do is create a new SvelteKit project.

The easiest way to do that is to create a root directory for your project and then run the command npx sv create from your command prompt or terminal window, from within your directory.

Next, you’ll be presented with a series of configuration options for your SvelteKit Project. Feel free to configure these to suit your coding preferences, or use the following settings to replicate our configuration:

Where would you like your project to be created?

  • Hit Enter

Which template would you like?

  • Select SvelteKit minimal

Add type checking with Typescript?

  • Select Yes, using Typescript syntax

What would you like to add to your project?

  • Use the arrow keys + space to select Prettier, eslint and TailwindCSS

Which package manager do you want to install dependencies with?

  • Select npm (if not already selected)

You should now be able to navigate to your website’s homepage if you go to http://localhost:5173/

Finally, let’s install the charting library that we’ll be using:

npm install lightweight-charts


Step 1: Safely load our API key

Let’s create a .env file inside our project’s root directory. Since we’re working within a web environment, we must ensure that only the server can access this information.

Inside your .env file, go ahead and save your API Key like so:

This will enable us to load it on the server side later on safely.


Step 2: Defining our data types

Inside the src/lib directory, create a subdirectory called types. Inside types, we’ll create a PriceData.ts file defining the data type that we’ll be expecting from CoinGecko’s endpoint Coin OHLC Chart by ID.

By default, this endpoint returns candlestick OHLC data for a single coin as a list of lists:

Tradingview’s lightweight-charts expect the historical data to be a list of objects, so we’ll need to define both types:

Next, navigate to the src/lib directory and create a new subdirectory called enums. Inside this directory, we'll define a new file named VsCurrencyEnum.ts.

In this enum, we'll store all the valid options for the vs_currency parameter used in our historical data queries.

CoinGecko's historical data endpoint expects a vs_currency parameter, allowing us to retrieve asset prices in a currency of our choice. For example, passing 'usd' when querying Bitcoin's historical data will return the BTC/USD dataset.

To fetch all valid base assets, you can use a tool like Postman to make an authenticated request to /simple/supported_vs_currencies and save it inside the Currency enum. Another option would be to use the getVsCurrencies() method that we’ll be defining inside our main CoinGecko class down below.

However, if you prefer to keep it simple, you can manually define the base pairs that are relevant to you. 


Step 3: Fetching historical data

Next, let's return to the lib directory and create a new subdirectory called providers. Inside providers create a file named PriceDataProvider.ts.

Here we'll handle all our CoinGecko API calls. To keep the code organized, we’ll define a CoinGecko class that will contain the various methods for interacting with the API:

The constructor in our CoinGecko class utilizes two ternary operators for this root and auth_param, allowing us to switch between the Demo and Pro API Keys easily. By replacing the Demo key with a Pro key in our .env file and setting the API_TYPE variable to "PRO", our class constructor logic will automatically handle the rest when the app is restarted or hot-reloaded.

The getHistoricalData() method is the core function responsible for fetching the candlestick data. It takes three parameters and returns an object of type CandleObjectArray, which we defined in PriceData.ts.

Here's how it works: We make a request to the CoinGecko API (either the demo or pro version) using the coinId, vs_currency, and days parameters:

After receiving the response, we map the object (which is typically a list of lists) to a list of objects so that we can pass the historical data to the TradingView charting library.

One important detail here is the timestamp conversion:

The timestamp we receive from the API is in milliseconds, which causes issues with the chart rendering. By dividing it by 1000, we convert it to seconds, ensuring the chart displays correctly.

Next, we have the getVsCurrencies() and getCoinIdByName() methods. While not actively used in our current code, they are helpful utilities for fetching and storing relevant data.

For example, getVsCurrencies() can be used to populate the Currency enum in VsCurrencies.ts, while getCoinIdByName() helps us obtain the API ID for a coin based on its name.

Since the historical data API requires a coinId rather than a symbol or name, we may need to periodically call getCoinIdByName() to determine a coin's correct ID.


Step 4: Accessing The data inside our app

Now that we’ve successfully integrated the CoinGecko API, we need to connect it to our front end to interact with the data through a simple web interface. Thankfully, this is straightforward to set up in SvelteKit.

To start, navigate to src/routes and create a new file called +page.server.ts. Unlike other frameworks, SvelteKit follows a standardized file naming convention for Svelte-specific files, such as the one we just created.

Inside this server file, we’ll export a function named load, typed as PageServerLoad. This is a SvelteKit default method that allows us to make its return value accessible on the webpage.

To ensure a smooth start-up, we’ll set it to load a 7-day Bitcoin chart by default if no parameters are provided. These parameters will be specified in the URL, for example:

?coin=bitcoin&days=14


Step 5: Building the UI and plotting the data

With everything in place, we’re ready to start plotting our charts and building a simple interactive page. To begin, open the +page.svelte file under routes. If you started with an empty project, you may need to create this file.

The +page.svelte file defines a page in our app, and since it’s located at the root of the routes directory, it will serve as the main page (or homepage) for our application.

These files support <script> tags, HTML syntax, and Svelte’s powerful reactivity features.

We’ll begin by adding the code in the <script> section.

In this <script> section, we’re setting up the charting logic and making the page responsive to user input for selecting coins and intervals:

First, we declare data as a prop of type PageData, representing the data we fetched in our +page.server.ts file. Using the $: reactive assignment syntax, we assign chartData to data.chartData. This makes chartData reactive, so any changes will automatically update the chart on the page.

We also define arrays for coins and intervals, allowing users to choose which cryptocurrency and time interval to display. These are simple lists of strings and will populate dropdowns for user selection on the page. Feel free to edit the coins array to suit your preferences. 

To update the page without refreshing, we use the updateQueryParams() method. This function captures the selected coin and interval, updates the URL query parameters accordingly, and uses Svelte’s goto function with replaceState: true. This keeps the URL in sync with user selections.

Finally, to handle updates each time chartData or the selected options change, we use the afterUpdate lifecycle hook to recreate the chart with fresh data whenever any input selections are modified.

This setup makes the chart dynamically update as users change options, or as new data becomes available, creating a smooth interactive experience.

All that’s left to do now is hook this up to a simple frontend. In the same file, we’re adding the following code:


Step 6: Test the app

Congratulations - you should now be able to see your work by running npm run dev and navigating to http://localhost:5173/

The page will look something like this:

plot an interactive candlestick chart

You use the two select boxes at the top to change the coin and the interval. You now have a fully interactive TradingView chart for your favourite assets.


Considerations

When working with CoinGecko OHLC data, it’s important to consider the data's frequency and granularity. CoinGecko automatically adjusts candlestick granularity based on the selected interval. For instance:

  • An interval of 1-2 days returns 30-minute candles.
  • A 3-30 day range returns 4-hour candles.
  • 31 days and beyond returns 4-day candles

The Pro API allows you to specify an hourly or daily interval for time frames of up to 90 and 180 days, respectively.

coinmarketcap api alternatives - CoinGecko API is accurate, reliable

Another consideration is the data refresh rate. CoinGecko updates its data every 15 minutes, so if you want live tick updates, you must fetch the current price separately and update the last candle’s close price with this live data.

The good news with the lightweight-charts library is its flexibility; you can plot any data you have, from indicators to line charts, and more. So let us know if you’d like to see us extend this app in a future article!

Finally, to deploy your app in a production environment, you will have to bundle your code with npm run build and pick a hosting or cloud provider. To make it accessible from a custom domain, you can configure a reverse proxy with Nginx, allowing you to serve it like any regular website from a domain name.


If you've enjoyed this article, be sure to check out other similar API guides!

CoinGecko's Content Editorial Guidelines
CoinGecko’s content aims to demystify the crypto industry. While certain posts you see may be sponsored, we strive to uphold the highest standards of editorial quality and integrity, and do not publish any content that has not been vetted by our editors.
Learn more
Want to be the first to know about upcoming airdrops?
Subscribe to the CoinGecko Daily Newsletter!
Join 600,000+ crypto enthusiasts, traders, and degens in getting the latest crypto news, articles, videos, and reports by subscribing to our FREE newsletter.
Tell us how much you like this article!
Vote count: 7
Cryptomaton
Cryptomaton
Cryptomaton (Andrei Badoiu) is the Co-founder of Aesir, an algorithmic cryptocurrency trading platform. Andrei's expertise lies in working with the evolving intersection of finance and technology, driving innovation that empowers traders and transforms the way they engage with the market. Follow the author on Twitter @cryptomatonblog

Related Articles

Select Currency
Suggested Currencies
USD
US Dollar
IDR
Indonesian Rupiah
TWD
New Taiwan Dollar
EUR
Euro
KRW
South Korean Won
JPY
Japanese Yen
RUB
Russian Ruble
CNY
Chinese Yuan
Fiat Currencies
AED
United Arab Emirates Dirham
ARS
Argentine Peso
AUD
Australian Dollar
BDT
Bangladeshi Taka
BHD
Bahraini Dinar
BMD
Bermudian Dollar
BRL
Brazil Real
CAD
Canadian Dollar
CHF
Swiss Franc
CLP
Chilean Peso
CZK
Czech Koruna
DKK
Danish Krone
GBP
British Pound Sterling
GEL
Georgian Lari
HKD
Hong Kong Dollar
HUF
Hungarian Forint
ILS
Israeli New Shekel
INR
Indian Rupee
KWD
Kuwaiti Dinar
LKR
Sri Lankan Rupee
MMK
Burmese Kyat
MXN
Mexican Peso
MYR
Malaysian Ringgit
NGN
Nigerian Naira
NOK
Norwegian Krone
NZD
New Zealand Dollar
PHP
Philippine Peso
PKR
Pakistani Rupee
PLN
Polish Zloty
SAR
Saudi Riyal
SEK
Swedish Krona
SGD
Singapore Dollar
THB
Thai Baht
TRY
Turkish Lira
UAH
Ukrainian hryvnia
VEF
Venezuelan bolívar fuerte
VND
Vietnamese đồng
ZAR
South African Rand
XDR
IMF Special Drawing Rights
Cryptocurrencies
BTC
Bitcoin
ETH
Ether
LTC
Litecoin
BCH
Bitcoin Cash
BNB
Binance Coin
EOS
EOS
XRP
XRP
XLM
Lumens
LINK
Chainlink
DOT
Polkadot
YFI
Yearn.finance
SOL
Solana
Bitcoin Units
BITS
Bits
SATS
Satoshi
Commodities
XAG
Silver - Troy Ounce
XAU
Gold - Troy Ounce
Select Language
Popular Languages
EN
English
RU
Русский
DE
Deutsch
PL
język polski
ES
Español
VI
Tiếng việt
FR
Français
PT-BR
Português
All Languages
AR
العربية
BG
български
CS
čeština
DA
dansk
EL
Ελληνικά
FI
suomen kieli
HE
עִבְרִית
HI
हिंदी
HR
hrvatski
HU
Magyar nyelv
ID
Bahasa Indonesia
IT
Italiano
JA
日本語
KO
한국어
LT
lietuvių kalba
NL
Nederlands
NO
norsk
RO
Limba română
SK
slovenský jazyk
SL
slovenski jezik
SV
Svenska
TH
ภาษาไทย
TR
Türkçe
UK
украї́нська мо́ва
ZH
简体中文
ZH-TW
繁體中文
Welcome to CoinGecko
Welcome back!
Login or Sign up in seconds
or
Sign in with . Not you?
Forgot your password?
Didn't receive confirmation instructions?
Resend confirmation instructions
Password must contain at least 8 characters including 1 uppercase letter, 1 lowercase letter, 1 number, and 1 special character
By continuing, you acknowledge that you've read and agree fully to our Terms of Service and Privacy Policy.
Get Price Alerts with CoinGecko App
Forgot your password?
You will receive an email with instructions on how to reset your password in a few minutes.
Resend confirmation instructions
You will receive an email with instructions for how to confirm your email address in a few minutes.
Get the CoinGecko app.
Scan this QR code to download the app now App QR Code Or check it out in the app stores
Add NFT
CoinGecko
Better on the app
Real-time price alerts and a faster, smoother experience.
You’ve reached the limit.
Guest portfolios are limited to 10 coins. Sign up or log in to keep the coins listed below.