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!
Prerequisites
Before we begin, ensure you have the following:
- Basic knowledge of JavaScript and Node.js.
- Node.js and npm are installed on your machine.
- A Notion account with a database set up to track your crypto portfolio.
- 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.
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".
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.
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:
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:
-
Importing Axios: Axios is used for making HTTP requests.
-
Defining Crypto Symbols: This specifies the cryptocurrencies to track, like Bitcoin, Ethereum, and Solana.
-
Setting Base URL and API Key:
-
BASE_URL
is the CoinGecko API endpoint. -
API_KEY
is retrieved from environment variables for authentication.
-
-
Constructing Request URL and Parameters: This constructs the API endpoint URL and sets query parameters to fetch prices in USD, and include market cap.
-
Setting Request Headers: This adds the API key to the request headers for authentication.
-
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:
-
Importing Notion Client and Fetch Prices: This serves to import the Notion client and the
fetchCryptoPrices
function. -
Initializing Notion Client: This creates a Notion client using the API key from environment variables.
-
Setting Database ID: This retrieves the Notion database ID from environment variables.
-
Fetching Crypto Prices: This calls
fetchCryptoPrices
to get the latest cryptocurrency prices. -
Iterating Through Prices: This iterates over the fetched prices. For each cryptocurrency, it extracts the price and market cap in USD.
-
Querying Notion Database: This queries the Notion database for a page with the matching cryptocurrency symbol.
-
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:
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.
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!
Subscribe to the CoinGecko Daily Newsletter!