Coins: 14,761
Exchanges: 1,205
Market Cap: $2.255T 1.6%
24h Vol: $45.34B
Gas: 3.87438198 GWEI
Go Ad-free
API
TABLE OF CONTENTS

How to Import Live Crypto Prices into Notion

5.0
| by
Roxait
|
Edited by
Julia Ng
-

In the world of cryptocurrency, staying updated with your assets' latest prices is crucial for effective portfolio management. However, manually tracking and updating your portfolio can be time-consuming and prone to errors – this is where automation comes into play.

In this article, we'll be walking through how to import crypto prices into Notion, using Node.js, Express, the Notion API and CoinGecko API. This basic crypto portfolio tracker leverages real-time crypto prices and has the ability to update automatically at regular intervals.

Whether you are an avid crypto investor or a Notion enthusiast looking to streamline your processes, this tutorial will give you the tools and knowledge to import cyptocurrency prices into Notion and maintain track your crypto portfolio effortlessly. Let's dive in!


Import Cryptocurrency Price Data into Notion Template | CoinGecko API

Prerequisites

Before we begin, ensure you have the following:

  1. Basic knowledge of JavaScript and Node.js.
  2. Node.js and npm are installed on your machine.
  3. A Notion account with a database set up to track your crypto portfolio.
  4. CoinGecko API: We will use the CoinGecko API to fetch market data for cryptocurrencies. The free Demo plan is sufficient for our needs, with a rate limit of 30 calls per minute and a monthly cap of 10,000 calls. Check out our API documentation or create a Demo account to try it out. 

Tools and Technologies

  • Node.js: A JavaScript runtime used to build the server.
  • Express: A web application framework for Node.js.
  • CoinGecko API: An API to fetch the latest cryptocurrency prices.
  • Notion API: An API to interact with your Notion database.
  • dotenv: A module to load environment variables.
  • node-cron: A module to schedule tasks in Node.js.

Setting Up the Project

Initialize the Project

First, create a new directory for your Portfolio tracker app. Open your terminal or command prompt and run the following command to create a new directory:

mkdir coingecko-notion-template

cd coingecko-notion-template 

Run the following command for creating package.json file

npm init

Install Dependencies

Install the necessary dependencies:

npm install express axios @notionhq/client dotenv node-cron

Create the Project Structure

coingecko-notion-template/

├── src/

│   ├── services

│      ├── notionService.js

│      └── cryptoService.js

│   ├── index.js

├── .env

└── package.json

Environment Variables

Create a .env file in the root directory and add the following environment variables:

NOTION_API_KEY=your_notion_integration_token

NOTION_DATABASE_ID=your_database_id

COINGECKO_API_KEY = your_api_key

PORT=3000

Setting Up Notion

Notion is an all-in-one workspace that allows you to take notes, manage tasks, and organize your projects. It provides a versatile platform where users can create databases, documents, wikis, and more. One of Notion's powerful features is its API, which enables developers to interact with Notion programmatically. By integrating with Notion's API, you can automate data updates, create custom workflows, and build dynamic applications that leverage Notion's organizational capabilities.

Let's run through how to set up Notion:

Generate a Notion API Key on Notion Integrations

Ensure you've logged into your Notion account, and navigate to Notion Integrations. Click on "New Integration", fill in the details for your integration and save it to get your API key.

Notion Integrations - How to get your Notion API key

Copy your Notion API Key and add it to your .env file.

Create a New Database in Notion

In Notion, and create a new page where you want to import crypto prices.

Add a database by typing /database, and select "Database - Inline" or Database - Full Page".
Notion Database Inline

To configure the database, add the following columns to the table:

  • Coin (Text): Name of coins you'd like to track.
  • Symbol (Text): This column is for coin ids, based on CoinGecko API's coin id list.
  • Quantity (Number): The quantity of the cryptocurrency you own.
  • Current Price (USD) (Number): The current price of cryptocurrencies in USD.
  • Current Value (USD) (Formula: Current Price (USD) * Quantity): The total value of your holdings.

     
  • Market Cap (USD) (Number): The market capitalization of the cryptocurrency in USD.
  • Purchase Price (USD) (Number): The hardcoded purchase price of the cryptocurrency in USD.
  • P&L (USD) (Formula: (Current Value (USD) - (Purchase Price (USD) * Quantity)): The profit and loss for each cryptocurrency.
    Crypto Profit & Loss

We'll now proceed to seed initial data, for example:

  • Coin: BTC, Symbol: bitcoin, Quantity: 2
  • Coin: ETH, Symbol: ethereum, Quantity: 4
  • Coin: SOL, Symbol: solana, Quantity: 25

Your crypto portfolio tracker should appear as such:

Crypto Price Tracker Notion Template

Proceed to share the Notion database with your integration, by clicking on the hamburger menu icon on the top right, then "Connections". From there, you can choose which integrations to connect.

Next, save the Database ID by following these steps:

  • Open the database in Notion and copy its URL.
  • Extract the Database ID from the URL. It is the part of the URL that comes after "notion.so/" and before the first question mark ("?").
  • Add the Database ID to your .env file as follows:

 

Step-by-Step Guide

Creating the Express Server (index.js)

import express from "express";

import dotenv from "dotenv";

import cron from 'node-cron'

import { updateCryptoPrices } from "./services/notionService.js";

dotenv.config();

const app = express();

const port = process.env.PORT || 3000;

app.get("/", async (req, res) => {

 try {

   await updateCryptoPrices();

   res.status(200).json({ message: "Portfolio updated successfully" });

 } catch (error) {

   console.error("Error updating crypto prices:", error);

   res.status(500).send("Error updating crypto prices.");

 }

});

// Schedule the task to run every hour

cron.schedule('0 * * * *', async () => {

 try {

   await updateCryptoPrices();

 } catch (error) {

   console.error('Error during scheduled update:', error);

 }

});

app.listen(port, () => {

 console.log(`Server is running on http://localhost:${port}`);

});

What the above code snippet means:

  • Importing Required Modules: Import Express, dotenv, cron, and the updateCryptoPrices function from notionService.js.
  • Configuring Environment Variables: Use dotenv to load environment variables from the .env file.
  • Setting Up Express App: Initialize an Express application and set the port.
  • Defining Routes: Define a route (/) to manually trigger the update of crypto prices.
  • Scheduling Cron Job: Schedule a cron job to update crypto prices every hour.
  • Starting the Server: Start the Express server and listen on the specified port.

Fetching Cryptocurrency Prices (cryptoService.js)

import axios from "axios";

export const fetchCryptoPrices = async () => {

 const cryptoSymbols = ["bitcoin", "ethereum", "solana"];

 const BASE_URL = "https://api.coingecko.com/api/v3";

 const API_KEY = process.env.COINGECKO_API_KEY;

 const url = `${BASE_URL}/v3/simple/price`;

 const params = {

   ids: cryptoSymbols.join(","),

   vs_currencies: "usd",

   include_market_cap: true,

 };

 const headers = {

   "x-cg-demo-api-key": API_KEY,

 };

 try {

   const response = await axios.get(url, { params, headers });

   return response.data;

 } catch (error) {

   console.error("Error fetching data from CoinGecko:", error);

   throw error;

 }

};

Unpacking the code above:

  1. Importing Axios: Axios is used for making HTTP requests.

  2. Defining Crypto Symbols: This specifies the cryptocurrencies to track, like Bitcoin, Ethereum, and Solana.

  3. Setting Base URL and API Key:

    • BASE_URL is the CoinGecko API endpoint.

    • API_KEY is retrieved from environment variables for authentication.

  4. Constructing Request URL and Parameters: This constructs the API endpoint URL and sets query parameters to fetch prices in USD, and include market cap.

  5. Setting Request Headers: This adds the API key to the request headers for authentication.

  6. Making the API Request:

    • This sends a GET request to the CoinGecko API and returns the response data.

    • Handles any errors by logging and throwing them.

This function fetches the latest prices and market capitalization of specified cryptocurrencies (Bitcoin, Ethereum, Solana) in USD from the CoinGecko API using the provided API key for authentication.


Updating Notion Database (notionService.js)

import { Client } from "@notionhq/client";
import { fetchCryptoPrices } from "./cryptoService.js";

export const updateCryptoPrices = async () => {
  const notion = new Client({
    auth: process.env.NOTION_API_KEY,
  });

  const databaseId = process.env.NOTION_DATABASE_ID;
  const prices = await fetchCryptoPrices();
  const defaultHoldings = {
    bitcoin: 2,
    ethereum: 4,
    solana: 25,
  };

  const purchasePrices = {
    bitcoin: 30000, // Hardcoded purchase price for Bitcoin
    ethereum: 2000, // Hardcoded purchase price for Ethereum
    solana: 120, // Hardcoded purchase price for Solana
  };

  for (const [symbol, priceData] of Object.entries(prices)) {
    const price = priceData.usd;
    const marketCap = priceData?.usd_market_cap;
    const quantity = defaultHoldings[symbol] || 0;
    const currentValue = (price * quantity).toFixed(2);
    const purchasePrice = purchasePrices[symbol] || 0;
    const purchaseValue = (purchasePrice * quantity).toFixed(2);
    const pAndL = (currentValue - purchaseValue).toFixed(2);

    const response = await notion.databases.query({
      database_id: databaseId,
      filter: {
        property: "Symbol",
        rich_text: {
          equals: symbol.toUpperCase(),
        },
      },
    });

    const page = response.results[0];

    if (page) {
      await notion.pages.update({
        page_id: page.id,
        properties: {
          "Current Price (USD)": {
            number: parseFloat(price.toFixed(2)),
          },
          "Current Value (USD)": {
            number: parseFloat(currentValue),
          },
          "Market Cap (USD)": {
            number: parseFloat(marketCap.toFixed(2)),
          },
          "Quantity": {
            number: quantity,
          },
          "Purchase Price (USD)": {
            number: parseFloat(purchasePrice.toFixed(2)),
          },
          "Purchase Value (USD)": {
            number: parseFloat(purchaseValue),
          },
          "P&L (USD)": {
            number: parseFloat(pAndL),
          },
        },
      });
    }
  }
};

Breaking down the code snippet above:

  1. Importing Notion Client and Fetch Prices: This serves to import the Notion client and the fetchCryptoPrices function.

  2. Initializing Notion Client: This creates a Notion client using the API key from environment variables.

  3. Setting Database ID: This retrieves the Notion database ID from environment variables.

  4. Fetching Crypto Prices: This calls fetchCryptoPrices to get the latest cryptocurrency prices.

  5. Iterating Through Prices: This iterates over the fetched prices. For each cryptocurrency, it extracts the price and market cap in USD.

  6. Querying Notion Database: This queries the Notion database for a page with the matching cryptocurrency symbol.

  7. Updating Notion Page: This triggers the following actions if a matching page is found,

    • Updates the page with the new price, calculated value, and market cap in USD.

    • Calculates the value based on the quantity of cryptocurrency.

This function refreshes the Notion database with the latest cryptocurrency prices, calculated values based on quantity, and market capitalization for specified cryptocurrencies.


How It Works: Crypto Price Tracker on Notion

Now that you have all the code set up, let’s see how everything works together:

Start the Server

Open your terminal, navigate to your project directory, and start the server:
    npm start

This will start the Express server, and it will be listening on http://localhost:3000.

Initial Data Update

When you first visit http://localhost:3000 in your browser, the server will call the updateCryptoPrices function.

This function fetches the latest cryptocurrency prices from the CoinGecko API and updates your Notion database with the current prices, market cap, and calculated value based on the quantity you have specified.

Scheduled Updates

The application uses a cron job to automatically update the crypto prices in your Notion database every hour. This ensures that your portfolio is always up-to-date with the latest market information.

The cron job is configured to run the updateCryptoPrices function every hour using the following schedule:

// Schedule the task to run every hour

cron.schedule('0 * * * *', async () => {

 try {

   await updateCryptoPrices();

 } catch (error) {

   console.error('Error during scheduled update:', error);

 }

});

Finally - this is how the crypto portfolio tracker appears on Notion:

How to Import Crypto Prices into Notion - CoinGecko API


Additional Enhancements & API Endpoints to Explore

Display Trending Coins & Categories

Use the Trending Search (/search/trending) endpoint to display the top trending coins, categories and NFTs on CoinGecko, in the last 24 hours. More specifically, this will retrieve:

  • The top 15 trending coins, sorted by the most popular user searches on CoinGecko
  • The top 5 trending categories, sorted by the most popular user searches on CoinGecko
  • The top 7 trending NFTs, sorted by the highest percentage change in NFT floor prices

Show Historical Crypto Price Data & Performance Insights

In the event you'd like to fetch and store historical crypto price data to provide insights into each crypto's performance over time, you can use the Coin Historical Chart Data by ID (/coins/{id}/market_chart) to retrieve detailed historical performance data for each coin. Analyze price trends and market behavior, implement charts and graphs in Notion to visualize trends and historical data.

💡Pro-tip: For error handling and logging, we recommend using a logging library like Winston for better debugging and monitoring.

By incorporating these enhancements, you can create a more comprehensive and user-friendly crypto portfolio tracking application, providing users with a valuable tool for managing their cryptocurrency investments.


Conclusion

In this article, we've walked through the process of importing crypto prices into Notion using the CoinGecko API. By integrating these powerful tools with a Node.js and Express backend, we've demonstrated how to dynamically update cryptocurrency prices, market caps, and portfolio values directly within a Notion database.

This setup provides a seamless way to monitor and manage your cryptocurrency investments, ensuring you always have the latest market information at your fingertips. The automatic updates via cron jobs and the ability to easily expand the system with additional features make this solution not only practical but also highly extensible.

With these steps, you've built a foundational tool that can be enhanced and customized further according to your needs. We hope this guide has been helpful and inspires you to explore more possibilities with Notion and CoinGecko. Happy coding and successful investing!


Looking for more API resources and guides? Learn how to use Python to fetch crypto prices using CoinGecko API, or build your own crypto portfolio dashboard!

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: 4
Roxait
Roxait
With 18 years of pioneering experience in the crypto space, Roxait excels in technical collaborations to develop cutting-edge decentralized solutions. Our commitment to innovation and expertise in blockchain technology has made us a trusted partner in driving the future of decentralized systems. Follow the author on Twitter @roxaittech

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
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
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
繁體中文
Log in
By continuing, you agree to CoinGecko Terms of Service and acknowledge you’ve read our Privacy Policy
or
Forgot your password?
Didn't receive confirmation instructions?
Resend confirmation instructions
Sign up
By continuing, you agree to CoinGecko Terms of Service and acknowledge you’ve read our Privacy Policy
or
Password must contain at least 8 characters including 1 uppercase letter, 1 lowercase letter, 1 number, and 1 special character
Didn't receive confirmation instructions?
Resend confirmation instructions
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
coingecko
Continue in app
Track prices in real-time
Open App
Join us at our first hybrid conference on 11 Nov 2024. Final chance to grab tickets at 25% off—don’t wait!