By the end of this tutorial, you’ll know exactly what the CoinGecko API is, how its market-data and onchain coverage work, and how to integrate it into a simple portfolio app.
You’ll also see where CoinGecko stops being enough for trading-grade and wallet-heavy products, and how teams typically layer Codex as their real-time, enriched onchain data backbone.
Prerequisites
Before you start, you should have:
- Basic familiarity with REST APIs and HTTP requests
- A working knowledge of JavaScript (Node.js) or Python
- A simple web or backend environment (e.g., Node.js + Express or a Python script)
- Optional but recommended: a Codex API key and access to docs.codex.io for later steps
We’ll use JavaScript examples, but all concepts apply to any language that can call HTTP APIs.
1. Understand What the CoinGecko API Actually Provides
The CoinGecko API is a market-data-first service. It’s designed to provide:
- Token prices (spot and historical)
- Market caps
- 24h volumes
- Price charts and OHLC data
- Coin metadata (symbols, categories, descriptions)
- Global market stats (e.g., total market cap, BTC dominance)
- Select onchain analytics (DEX prices, liquidity, wallet balances, transfers)
Key facts product teams should know
- CoinGecko describes itself as “the world’s largest independent crypto data aggregator” with:
- 1,500+ exchanges
- 18,000+ coins
- 600+ categories
- Onchain coverage (via GeckoTerminal) spans:
- 200+ blockchains
- 1,800+ DEXes
- 39M+ tokens
- The API is exposed as REST endpoints with both public, keyless access and paid tiers.
Where CoinGecko is strong
CoinGecko is ideal when you need:
- Broad market data for thousands of assets
- Simple price feeds for portfolios and dashboards
- Historical market charts for performance views
- Category and sector screening (e.g., DeFi, gaming, L1s)
Where CoinGecko is not designed to go deep
Despite its onchain analytics:
- It’s not a full trading or account-data stack
- It’s not positioned as a high-frequency trading engine
- It doesn’t provide prediction market structures (events, markets, outcomes, trader stats)
- Its wallet coverage is useful but limited compared to dedicated wallet APIs or Codex’s wallet analytics
Common failure at this step: Treating CoinGecko as a replacement for a dedicated onchain indexer or wallet API. It’s a market data layer first, not your full-chain infra.
2. Set Up Basic Access and Respect CoinGecko Rate Limits
CoinGecko offers a keyless public API and paid plans.
Keyless public API
- Intended for testing and prototyping
- Docs explicitly say it is not suitable for production workloads, scheduled polling, or high-frequency updates
- Typical limits (as of docs examples):
- ~10–30 calls/min for CoinGecko endpoints
- ~10 calls/min for GeckoTerminal onchain endpoints
For production, you should use a paid plan with defined rate limits. The /key endpoint returns:
- Your current requests per minute
- Monthly credit quota (docs example shows 1,000 requests/min and 1,000,000 monthly calls for a sample plan)
Example: quick keyless request
curl "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum&vs_currencies=usd"
Best practices for rate limits
- Cache responses on your side for at least 30–60 seconds for top coins
- Back off or queue requests if you approach your minute quota
- Use server-side calls and fan out to clients, rather than hitting CoinGecko from every client
Common failure at this step: Polling /simple/price every second from thousands of clients and hitting rate limits or bans. Always centralize calls and cache.
3. Use Core Market Endpoints for Prices, Market Caps, and Charts
Most portfolio and dashboard apps rely on a small set of CoinGecko REST endpoints.
CoinGecko’s own docs recommend:
/simple/price– live valuations/coins/markets– dashboard lists with price, market cap, volume/coins/{id}/market_chart– historical price charts/coins/{id}/history– historical price on specific dates (e.g., for cost basis)
Example: get live prices for a portfolio
We’ll use Node.js with node-fetch (or native fetch in modern runtimes).
import fetch from 'node-fetch';
const COINS = ['bitcoin', 'ethereum', 'cardano'];
async function fetchLivePrices() {
const params = new URLSearchParams({
ids: COINS.join(','),
vs_currencies: 'usd',
include_market_cap: 'true',
include_24hr_vol: 'true',
include_24hr_change: 'true'
});
const res = await fetch(
`https://api.coingecko.com/api/v3/simple/price?${params.toString()}`
);
if (!res.ok) throw new Error(`CoinGecko error: ${res.status}`);
const data = await res.json();
return data;
}
fetchLivePrices().then(console.log).catch(console.error);
This gives you a simple object like:
{
"bitcoin": {
"usd": 68000,
"usd_market_cap": 1350000000000,
"usd_24h_vol": 35000000000,
"usd_24h_change": 1.23
},
"ethereum": { ... }
}
Example: historical chart for a single coin
async function fetchMarketChart(coinId, days = 30) {
const params = new URLSearchParams({
vs_currency: 'usd',
days: days.toString()
});
const res = await fetch(
`https://api.coingecko.com/api/v3/coins/${coinId}/market_chart?${params.toString()}`
);
if (!res.ok) throw new Error(`CoinGecko error: ${res.status}`);
const data = await res.json();
return data; // prices, market_caps, total_volumes
}
The chart endpoint auto-adjusts granularity depending on the time window, which is handy for portfolio performance views.
Common failure at this step: Hitting /coins/{id}/market_chart repeatedly for the same asset and time range on every page load. Cache chart data server-side and reuse.
4. Explore CoinGecko’s On-Chain Coverage and Its Limits
CoinGecko has expanded “up the stack” with onchain analytics, powered largely by GeckoTerminal. It now exposes:
- Onchain token prices from DEXes
- Pool OHLCV (open-high-low-close-volume) data
- Onchain trades
- Liquidity metrics
- Holder distribution
- Onchain wallet balances and transfers
The onchain wallet balance endpoint, for example, returns:
- Total wallet USD value
- Number of holdings
- Per-network breakdowns
- Token balances
- Token prices and 24h changes
- Liquidity-like reserve fields
This makes CoinGecko suitable for lightweight wallet views and DeFi discovery.
However, the key gap: no deep wallet or prediction market stack
CoinGecko’s wallet and onchain data remain:
- Narrower than dedicated wallet APIs or specialized onchain layers like Codex
- Not structured for advanced trader analytics, attribution, or cross-chain aggregations
- Not tailored for prediction markets (no events/markets/outcomes/traders schema)
By contrast, Codex provides a GraphQL-style API focused on:
- Real-time token prices and OHLC across 80+ networks
- Wallet balances and holders across 700M+ wallets
- Aggregated metrics (liquidity, volume, unique wallets, TVL-like stats)
- Prediction market data (events, markets, trades, trader analytics) for platforms like Polymarket and Kalshi
Common failure at this step: Assuming CoinGecko’s onchain endpoints can replace a full-featured wallet analytics or prediction market API. They’re complementary, not equivalent.
5. Build a Simple Portfolio App Using CoinGecko Market Data
Now let’s build a minimal portfolio valuation flow to show how CoinGecko fits into a product.
Goal
Given a user’s holdings by symbol (e.g., BTC, ETH, ADA), we will:
- Map symbols to CoinGecko IDs
- Fetch live prices and market caps via CoinGecko REST
- Calculate portfolio value and allocation
Step 5.1: Maintain a symbol-to-ID map
CoinGecko IDs differ from symbols (e.g., bitcoin, ethereum, cardano). You can:
- Fetch
/coins/listonce and cache the mapping - Or maintain a curated mapping for the assets you support
Example mapping:
const SYMBOL_TO_ID = {
BTC: 'bitcoin',
ETH: 'ethereum',
ADA: 'cardano'
};
Step 5.2: Define the user portfolio
const portfolio = [
{ symbol: 'BTC', amount: 0.5 },
{ symbol: 'ETH', amount: 10 },
{ symbol: 'ADA', amount: 5000 }
];
Step 5.3: Fetch prices from CoinGecko
async function getPricesForPortfolio(portfolio) {
const ids = [
...new Set(portfolio.map(p => SYMBOL_TO_ID[p.symbol]))
].filter(Boolean);
const params = new URLSearchParams({
ids: ids.join(','),
vs_currencies: 'usd'
});
const res = await fetch(
`https://api.coingecko.com/api/v3/simple/price?${params.toString()}`
);
if (!res.ok) throw new Error(`CoinGecko error: ${res.status}`);
return res.json();
}
Step 5.4: Calculate portfolio value
async function calculatePortfolioValue(portfolio) {
const priceData = await getPricesForPortfolio(portfolio);
let totalUsd = 0;
const positions = portfolio.map(pos => {
const id = SYMBOL_TO_ID[pos.symbol];
const price = priceData[id]?.usd ?? 0;
const valueUsd = pos.amount * price;
totalUsd += valueUsd;
return { ...pos, id, priceUsd: price, valueUsd };
});
const positionsWithAllocation = positions.map(pos => ({
...pos,
allocationPct: totalUsd ? (pos.valueUsd / totalUsd) * 100 : 0
}));
return { totalUsd, positions: positionsWithAllocation };
}
calculatePortfolioValue(portfolio)
.then(console.log)
.catch(console.error);
This gives you:
- Total portfolio value in USD
- Per-asset allocations
- Ready-to-display data for a CoinGecko-backed portfolio app
Common failure at this step: Relying solely on symbol strings and assuming uniqueness. Always map via CoinGecko IDs to avoid symbol collisions.
6. Add Codex for Trading-Grade On-Chain, Wallet, and Prediction Data
Once you go beyond simple market views, CoinGecko alone becomes limiting.
Examples:
- You want sub-second latency for tokens and charts in a high-traffic trading UI
- You need cross-chain wallet views and holder analytics
- You’re building a prediction market front-end with events, outcomes, trader stats
This is where teams add a specialized onchain data layer like Codex.
How Codex complements CoinGecko
CoinGecko:
- Broad market data across 18,000+ coins and 1,500+ exchanges
- REST-based API with strong historical charts and category views
- Onchain analytics suitable for discovery and light wallet views
Codex:
- Real-time token and pair data across 80+ networks and 70M+ tokens
- Sub-second latency, optimized for trading-grade UX
- Wallet analytics across 700M+ wallets (balances, holders)
- Enriched chart data (OHLC, candles, volume) and aggregated metrics (liquidity, volume, unique wallets, TVL-like stats)
- Dedicated prediction market endpoints: events, markets, outcomes, trades, trader analytics
Codex already powers products like Coinbase, TradingView, Uniswap, Magic Eden, Rainbow, MoonPay, Farcaster, pump.fun, making it infrastructure-grade for production.
Example division of responsibilities in a production app
-
Use CoinGecko to:
- Show global crypto market stats
- Provide broad asset lists (including CEX-only coins)
- Offer historical market caps and category views
-
Use Codex to:
- Drive real-time token charts and prices in trading terminals
- Power cross-chain wallet and portfolio views
- Enable prediction market UIs (e.g., Polymarket, Kalshi) with outcome prices and trader stats
Common failure at this step: Forcing CoinGecko to handle high-frequency, trading-grade workloads that require low latency and enriched onchain data. In practice, teams layer a provider like Codex for these paths.
7. Example: Portfolio App Combining CoinGecko and Codex
Let’s put it together with a pragmatic architecture you can actually ship.
Use case
You’re building a portfolio app that:
- Shows total portfolio value and allocations (multi-chain)
- Displays real-time charts for tokens
- Provides a basic wallet view (addresses, balances)
- Plans to add prediction market holdings later
Data flow
- Use Codex to fetch wallet balances and normalized token identifiers
- Use Codex for real-time token prices and OHLCV charts
- Optionally, use CoinGecko for global market stats or coverage gaps (e.g., certain CEX-only coins)
Step 7.1: Fetch wallet balances via Codex (conceptual example)
Pseudo-code illustrating how Codex might be used; see docs.codex.io for exact queries.
query WalletPortfolio($address: String!) {
wallet(address: $address) {
balances {
token {
id
symbol
name
chainId
}
amount
usdValue
}
totalUsdValue
}
}
Codex returns normalized balances and USD valuation in one shot, saving you from stitching raw chain data.
Step 7.2: Drive charts with Codex
Use Codex’s chart endpoints for trading-ready OHLC data with sub-second responses. This is where CoinGecko’s chart API often shows its latency and rate-limit constraints for real-time trading UIs.
Step 7.3: Enhance with CoinGecko’s global market data
Still plug CoinGecko into your stack for:
- Category/tag views (e.g., DeFi, L2, NFTs)
- Comparisons like ADA market cap vs. other L1s
- Global overview: total crypto market cap, BTC/ETH dominance
This hybrid approach keeps CoinGecko where it’s strongest (macro market data), and Codex where you need trading-grade onchain, wallet, and prediction market capabilities.
Common failure at this step: Trying to maintain homegrown indexers and ETL pipelines on top of raw chain data for wallets and prediction markets. Most teams underestimate the infra and instead consolidate on an enriched layer like Codex.
If you’re starting with CoinGecko for market data, you’re on a solid path. As your app grows into high-traffic trading, cross-chain wallets, or prediction markets, layering Codex as your onchain data backbone will help you ship faster and avoid years of infra work.



