Coins: 17,916
Exchanges: 1,471
Market Cap: $2.435T 1.4%
24h Vol: $110.786B
Gas: 0.237 GWEI
Upgrade to Premium
API
TABLE OF CONTENTS

How to Fetch Crypto Market Data Using GOATSDK

4.3
| by
Roxait
|
Edited by
Brian Lee
-

This guide will walk you through fetching cryptocurrency market data using GOATSDK and its CoinGecko plugin. Whether you're interested in historical coin data, OHLC candlestick data, trending coins, top gainers and losers, or coin categories, this guide provides step-by-step instructions, detailed explanations of inputs and outputs, and reusable TypeScript code you can plug directly into your own projects.


Prerequisites

Before getting started, ensure you have the following ready:

  • CoinGecko API Key The CoinGecko API offers both free and Pro tiers. The free plan is sufficient for basic features like fetching historical prices, OHLC data, and trending coins. It is a great starting point for hobby projects or learning. For advanced endpoints such as trending pools and top gainers/losers, you'll need a Pro API key, which you can obtain from the CoinGecko API Pricing page.

  • Node.js Install Node.js (v16 or later) from the official Node.js website. This is required to run the program and manage dependencies.

  • TypeScript TypeScript is used for type safety and maintainability. You can install it globally using npm install -g typescript or as a dev dependency in your project. TypeScript helps catch errors early and makes your code easier to refactor and maintain.

  • Code Editor Use a code editor like Visual Studio Code to write and manage your project efficiently.

  • Goat SDK and CoinGecko Plugin Refer to the Goat SDK Documentation and CoinGecko Plugin Documentation for more details. These packages provide a high-level interface to the CoinGecko API, abstracting away HTTP requests and response parsing.


Setting up the Project Environment

1. Initialise the Project Create a new project directory and initialise it:

mkdir goat-gecko-tool cd goat-gecko-tool npm init -y

2. Install Dependencies Install the required libraries:

npm install @goat-sdk/core @goat-sdk/plugin-coingecko dotenv inquirer
npm install --save-dev typescript @types/node

3. Set Up TypeScript Initialise TypeScript and configure the tsconfig.json file:

npx tsc --init

Set Up TypeScript

Update the tsconfig.json file to include:

{
    "compilerOptions": {
        "target": "ES2020",
        "module": "ESNext",
        "moduleResolution": "Node",
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "outDir": "./dist"
    },
    "include": ["src/**/*"]
}

4. Set Up Environment Variables Create a .env file in the root directory and add your CoinGecko API key:

COINGECKO_API_KEY=your_pro_api_key_here

5. Create the wallet.ts File To avoid repeating wallet logic, create a reusable wallet module in src/wallet.ts:

// src/wallet.ts

export const wallet = {
    getChain: () => ({
        id: 1,
        name: "Ethereum",
        rpcUrls: [],
        type: "radix",
    }),
    getAccounts: () => [
        {
            address: "0x0",
            balance: {
                amount: "0",
                decimals: 18,
                symbol: "ETH",
                name: "Ether",
                value: "0",
                inBaseUnits: "0",
            },
        },
    ],
    signMessage: async () => ({ signature: "stub" }),
    getAddress: () => "0x0",
    balanceOf: async () => ({
        amount: "0",
        decimals: 18,
        symbol: "ETH",
        name: "Ether",
        value: "0",
        inBaseUnits: "0",
    }),
    getCoreTools: () => [],
};

This mock wallet is sufficient for all CoinGecko endpoints in this guide.

6. Create the index.ts File Create a new file named index.ts in the src directory. This file will serve as your application's main entry point and contain the core logic for interacting with the GOATSDK and the CoinGecko plugin. In this file, you will import your reusable wallet module, set up environment variables, initialise the SDK with your CoinGecko API key, and implement the logic for calling various CoinGecko endpoints.

7. Update package.json The package.json file defines your project's metadata, dependencies, and scripts. It manages required packages, build commands, and how to run or develop your app.

   "scripts": {
    "build": "tsc",
    "start": "node dist/index.js",
    "dev": "ts-node src/index.ts",
    "test": "echo "Error: no test specified" && exit 1",
    "clean": "rimraf dist"
  },

8. Compile the Code Use the TypeScript compiler to transpile the TypeScript code into JavaScript:

npx tsc

How to Get Historical Coin Data

To fetch historical data, use the coingecko_get_historical_data tool. This endpoint is useful for analysing a coin's price, market cap, and volume on a specific date.

Inputs:

  • id (string): The CoinGecko coin ID (e.g., "bitcoin")

  • date (string): The date in "DD-MM-YYYY" format (e.g., "30-12-2021")

  • localization (boolean, optional): Whether to localize descriptions

Example:

import { coingecko } from "@goat-sdk/plugin-coingecko";
import { getTools } from "@goat-sdk/core";
import dotenv from "dotenv";
import { wallet } from "./wallet.js";
dotenv.config();
(async () => {
  const tools = await getTools({
    wallet,
    plugins: [
      coingecko({
        apiKey: process.env.COINGECKO_API_KEY || "",
        isPro: true,
      }),
    ],
  });
  const getHistoricalData = tools.find(
    (t: { name: string }) => t.name === "coingecko_get_historical_data"
  );


  if (!getHistoricalData || typeof getHistoricalData.execute !== "function") {
    throw new Error("coingecko_get_historical_data tool not found or invalid");
  }
  try {
    const result = await getHistoricalData.execute({
      id: "bitcoin",
      date: "30-12-2021",
      localization: false,
    });


    console.log(result);
  } catch (error) {
    console.error("Error fetching historical data:", error);
  }
})();

Output Explanation:

  • Returns an object with coin metadata, price, market cap, and volume for the specified date.

  • Includes fields like id, symbol, market_data, community_data, and developer_data.

Sample Output:

{

  "id": "bitcoin",
  "symbol": "btc",
  "name": "Bitcoin",
  "localization": { "en": "Bitcoin", "de": "Bitcoin", ... },
  "market_data": {
    "current_price": 47000,
    "market_cap": 900000000000,
    "total_volume": 35000000000,
    "high_24h": 48000,
    "low_24h": 46000
  },

  "community_data": {
    "facebook_likes": null,
    "twitter_followers": 3500000,
    "reddit_average_posts_48h": 120,
    "reddit_average_comments_48h": 450
  },

  "developer_data": {
    "forks": 25000,
    "stars": 120000,
    "subscribers": 3500,
    "total_issues": 5000,
    "closed_issues": 4800
  }
}

How to Get Historical Coin Data

This output provides a snapshot of the coin's status on the requested date, including price, volume, and community engagement.


How to Get OHLC Candlestick Data

To fetch OHLC (Open, High, Low, Close) data, use the coingecko_get_ohlc_data tool. This is essential for technical analysis and charting.

Inputs:

  • id (string): Coin ID (e.g., "bitcoin")

  • vsCurrency (string): Comparison currency (e.g., "usd", "eur")

  • days (number): Number of days (1, 7, 14, 30, 90, 180, 365, or "max")

Example:

import { coingecko } from "@goat-sdk/plugin-coingecko";
import { getTools } from "@goat-sdk/core";
import dotenv from "dotenv";
import { wallet } from "./wallet.js";
dotenv.config();


(async () => {
  const tools = await getTools({
    wallet,
    plugins: [
      coingecko({
        apiKey: process.env.COINGECKO_API_KEY || "",
        isPro: true,
      }),
    ],
  });


  const getOHLCData = tools.find(
    (t: { name: string }) => t.name === "coingecko_get_ohlc_data"
  );
  if (!getOHLCData || typeof getOHLCData.execute !== "function") {
    throw new Error("coingecko_get_ohlc_data tool not found or invalid");
  }
  try {
    const result = await getOHLCData.execute({
      id: "bitcoin",
      vsCurrency: "usd",
      days: 1,
    });


    console.log(result);
  } catch (error) {
    console.error("Error fetching OHLC data:", error);
  }
})();

Output Explanation:

  • Returns an array of arrays, each representing a candlestick: [timestamp, open, high, low, close]

  • Timestamps are in milliseconds since the Unix epoch.

Sample Output:

[
  [1622505600000, 37000, 38000, 36000, 37500],
  [1622592000000, 37500, 39000, 37000, 38500],
  [1622678400000, 38500, 40000, 38000, 39500]
]

How to Get OHLC Candlestick Data

Each sub-array represents a day's trading data, which can be used to plot candlestick charts or perform technical analysis.


To fetch trending coins, use the coingecko_get_trending_coins tool. This endpoint provides a list of coins that are currently popular based on CoinGecko's trending algorithm.

Inputs:

  • No parameters required.

Example:

import { coingecko } from "@goat-sdk/plugin-coingecko";
import { getTools } from "@goat-sdk/core";
import dotenv from "dotenv";
dotenv.config();


(async () => {
  const tools = await getTools({
    wallet,
    plugins: [
      coingecko({
        apiKey: process.env.COINGECKO_API_KEY || "",
        isPro: true,
      }),
    ],
  });


  const getTrendingCoins = tools.find(
    (t: { name: string }) => t.name === "coingecko_get_trending_coins"
  );


  if (!getTrendingCoins || typeof getTrendingCoins.execute !== "function") {
    throw new Error("coingecko_get_trending_coins tool not found or invalid");
  }


  try {
    const trending = await getTrendingCoins.execute({});
    console.log(trending);
  } catch (error) {
    console.error("Error fetching trending coins:", error);
  }
})();

Output Explanation:

  • Returns a list of trending coins, each with metadata such as id, symbol, name, market cap rank, and score.

  • The coins array contains trending coins (cryptocurrencies).

  • The nfts array contains trending NFTs.

  • The categories array contains trending categories.

Sample Output:

{

  "coins": [
    {
      "item": {
        "id": "solana",
        "coin_id": 5426,
        "name": "Solana",
        "symbol": "sol",
        "market_cap_rank": 7,
        "thumb": "https://assets.coingecko.com/coins/images/4128/thumb/solana.png",
        "score": 1
      }
    },
    {
      "item": {
        "id": "avalanche",
        "coin_id": 5805,
        "name": "Avalanche",
        "symbol": "avax",
        "market_cap_rank": 10,
        "thumb": "https://assets.coingecko.com/coins/images/12559/thumb/avalanche.png",
        "score": 2
      }
    }
  ]
}

How to Get Trending Coins

This output helps you quickly spot which coins are trending and may be worth further research.


How to Get Top Gainers and Losers

To fetch the top gainers and losers, use the coingecko_get_top_gainers_losers tool. This endpoint is valuable for identifying market movers and potential trading opportunities.

Inputs:

  • vsCurrency (string): Comparison currency (e.g., "usd")

  • perPage (number): Results per page (e.g., 10)

  • page (number): Page number (e.g., 1)

Example:

import { coingecko } from "@goat-sdk/plugin-coingecko";
import { getTools } from "@goat-sdk/core";
import dotenv from "dotenv";
import { wallet } from "./wallet.js";


dotenv.config();


(async () => {
  const tools = await getTools({
    wallet,
    plugins: [
      coingecko({
        apiKey: process.env.COINGECKO_API_KEY || "",
        isPro: true,
      }),
    ],
  });


  // Fetch top gainers and losers
  const getTopGainersLosers = tools.find(
    (t: { name: string }) => t.name === "coingecko_get_top_gainers_losers"
  );


  if (!getTopGainersLosers || typeof getTopGainersLosers.execute !== "function") {
    throw new Error("coingecko_get_top_gainers_losers tool not found or invalid");
  }


  try {
    const result = await getTopGainersLosers.execute({
      vsCurrency: "usd",
      perPage: 10,
      page: 1,
    });
    console.log(result);
  } catch (error) {
    console.error("Error fetching top gainers and losers:", error);
  }
})();

Output Explanation:

  • Returns two arrays: gainers and losers.

  • Each entry includes coin id, symbol, name, and price_change_percentage_24h.

Sample Output:

{
  "top_gainers": [
    {
      "id": "kekius-maximus",
      "symbol": "kekius",
      "name": "Kekius Maximus",
      "image": "https://coin-images.coingecko.com/coins/images/52791/original/Untitled_design.png?1734292733",
      "market_cap_rank": 689,
      "usd": 0.055188426169617555,
      "usd_24h_vol": 67217419.61136065,
      "usd_24h_change": 102.7110242135808
    }
  ],
  "top_losers": [
    {
      "id": "revox",
      "symbol": "rex",
      "name": "REVOX",
      "image": "https://coin-images.coingecko.com/coins/images/52909/original/RREVOX_LOG.png?1734647416",
      "market_cap_rank": 830,
      "usd": 0.01920480321547333,
      "usd_24h_vol": 17920681.18126372,
      "usd_24h_change": -31.65025493362888
    }
  ]
}

How to Get Top Gainers and Losers

This output allows you to quickly identify which coins are experiencing the largest gains and losses over the past 24 hours.


Summary and Conclusion

This guide demonstrates how to fetch cryptocurrency market data using the GOATSDK and CoinGecko plugin. By leveraging tools like coingecko_get_historical_data, coingecko_get_ohlc_data, coingecko_get_trending_coins, and coingecko_get_top_gainers_losers, you can easily integrate CoinGecko's extensive API capabilities into your projects.

The modular architecture of the GOATSDK ensures scalability and flexibility, allowing you to add more tools or customise the functionality as needed. By separating wallet logic into its module and using a consistent main program structure, you keep your codebase clean and maintainable.

You can find all the sample code and example usage shown in this program in the GitHub repository. Feel free to explore, clone, and adapt the samples for your projects.

Tips for Further Exploration:

  • Explore additional endpoints in the CoinGecko API for more data types.

  • Combine multiple endpoints for richer analytics (e.g., compare trending coins with top gainers).

  • Use the output data to build dashboards, trading bots, or research tools.

  • Experiment with different parameters to see how the results change.

For more information, refer to the CoinGecko API Documentation and the GOATSDK Documentation.

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: 10
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

New Portfolio
Icon & name
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
Track wallet address
Paste
We only display assets from supported networks.
Ethereum Mainnet
Base Mainnet
BNB Smart Chain
Arbitrum
Avalanche
Fantom
Flare
Gnosis
Linea
Optimism
Polygon
Polygon zkEVM
Scroll
Stellar
Story
Syscoin
Telos
X Layer
Xai
Read-only access
We only fetch public data. No private keys, no signing, and we can't make any changes to your wallet.
Create Portfolio
Select icon
💎
🔥
👀
🚀
💰
🦍
🌱
💩
🌙
🪂
💚
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.