coingecko-pro
v0.1.0
Published
The most comprehensive CoinGecko API SDK — all 84 endpoints, Pro API + On-chain DEX, TypeScript-first, zero dependencies
Maintainers
Readme
Full coverage of the CoinGecko Pro API and On-chain DEX data (GeckoTerminal) in a single, typed SDK. One import, every endpoint.
Features
- 86 endpoints across 8 namespaces -- coins, exchanges, derivatives, NFTs, on-chain DEX, global, treasury, and meta
- TypeScript-first -- every request and response is fully typed, with JSDoc on every method
- Zero runtime dependencies -- uses the built-in
fetchAPI (Node 18+, Bun, Deno, browsers) - In-memory TTL cache -- deduplicates identical requests within a configurable window
- Token-bucket rate limiter -- automatically enforces CoinGecko rate limits (30/min free, 500/min Pro)
- Exponential-backoff retry -- retries on 429 and 503 with configurable attempts and delay
- Request timeout -- AbortController-based timeout with clean error reporting
- Lifecycle hooks --
onRequest,onResponse,onErrorfor logging, metrics, and debugging - Dual format -- ships ESM and CommonJS builds with full source maps and declaration files
- Tree-shakeable -- import only the endpoint classes you need for minimal bundle size
Quick Start
Install
npm install coingecko-propnpm add coingecko-proyarn add coingecko-proBasic Usage
import { CoinGecko } from 'coingecko-pro';
// Pro tier (recommended)
const cg = new CoinGecko({ apiKey: 'CG-xxx' });
// Free tier (lower rate limits, some endpoints unavailable)
const cg = new CoinGecko();
// Check connectivity
const { gecko_says } = await cg.ping();
console.log(gecko_says); // "(V3) To the Moon!"
// Get Bitcoin market data
const btc = await cg.coins.getById('bitcoin');
console.log(btc.market_data.current_price.usd);
// Get top coins by market cap
const markets = await cg.coins.markets({ vs_currency: 'usd', per_page: 10 });
markets.forEach(coin => {
console.log(`${coin.name}: $${coin.current_price}`);
});Configuration
All options are optional. Sensible defaults are applied automatically.
| Option | Type | Default | Description |
|---|---|---|---|
| apiKey | string | -- | CoinGecko Pro API key. Switches base URL to pro-api.coingecko.com and sets the auth header. |
| baseUrl | string | auto | Override the base URL (useful for proxies or testing). |
| cacheTtl | number | 30000 | Default response cache TTL in milliseconds. Set to 0 to disable. |
| maxRetries | number | 3 | Maximum retry attempts for transient errors (429, 503). |
| retryDelay | number | 1000 | Base delay (ms) for the first retry. Uses exponential backoff: retryDelay * 2^attempt. |
| rateLimit | number | 500 (Pro) / 30 (Free) | Maximum requests per minute. |
| timeout | number | 15000 | Request timeout in milliseconds. |
| onRequest | (url) => void | -- | Hook called before every outgoing request. |
| onResponse | (url, status, ms) => void | -- | Hook called after every completed request. |
| onError | (url, error) => void | -- | Hook called when a request fails after all retries. |
const cg = new CoinGecko({
apiKey: process.env.CG_API_KEY,
cacheTtl: 60_000, // 1 minute cache
maxRetries: 5,
retryDelay: 2_000,
rateLimit: 500,
timeout: 30_000,
onRequest: (url) => console.log(`-> ${url}`),
onResponse: (url, status, ms) => console.log(`<- ${status} ${ms}ms`),
onError: (url, err) => console.error(`!! ${url}`, err.message),
});API Reference
Namespace Overview
| Namespace | Methods | Description |
|---|---|---|
| cg.coins | 23 | Prices, markets, charts, OHLC, supply, categories, contract lookups |
| cg.exchanges | 6 | Exchange listings, details, tickers, volume charts |
| cg.derivatives | 4 | Derivatives tickers and exchange data |
| cg.nfts | 7 | NFT collections, market data, charts, tickers |
| cg.onchain | 27 | On-chain DEX pools, tokens, trades, OHLCV, top traders/holders |
| cg.global | 8 | Global stats, search, trending, exchange rates, asset platforms |
| cg.treasury | 5 | Public treasury holdings, charts, transactions |
| cg.ping() | 1 | API connectivity check |
| cg.apiUsage() | 1 | API key usage stats (Pro only) |
Coins
// Simple price lookup
const prices = await cg.coins.price({
ids: 'bitcoin,ethereum',
vs_currencies: 'usd,eur',
});
// Token price by contract address
const tokenPrice = await cg.coins.tokenPrice('ethereum', {
contract_addresses: '0xdac17f958d2ee523a2206206994597c13d831ec7',
vs_currencies: 'usd',
});
// Market data with sorting and pagination
const markets = await cg.coins.markets({
vs_currency: 'usd',
order: 'market_cap_desc',
per_page: 100,
page: 1,
sparkline: true,
});
// Full coin detail
const btc = await cg.coins.getById('bitcoin', {
localization: false,
tickers: false,
community_data: false,
});
// Historical market chart
const chart = await cg.coins.marketChart('bitcoin', {
vs_currency: 'usd',
days: '30',
});
// OHLC candlestick data
const ohlc = await cg.coins.ohlc('bitcoin', {
vs_currency: 'usd',
days: '14',
});
// Top gainers and losers
const movers = await cg.coins.topGainersLosers({ vs_currency: 'usd' });
// Categories
const categories = await cg.coins.categories({ order: 'market_cap_desc' });On-chain DEX (GeckoTerminal)
// Trending pools across all networks
const { data: trending } = await cg.onchain.trendingPools();
// Top pools on a specific DEX
const { data: uniPools } = await cg.onchain.topPoolsByDex('eth', 'uniswap_v3');
// Pool OHLCV candlestick data
const ohlcv = await cg.onchain.poolOhlcv(
'eth',
'0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640',
'hour',
{ aggregate: '4', limit: 200 },
);
// Token info with security flags
const { data: tokenInfo } = await cg.onchain.tokenInfo(
'eth',
'0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
);
// Top traders (whale tracking) -- Pro only
const { data: whales } = await cg.onchain.topTraders(
'eth',
'0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
);
// Top holders -- Pro only
const { data: holders } = await cg.onchain.topHolders(
'eth',
'0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',
);
// Search pools by name or address
const { data: results } = await cg.onchain.searchPools('PEPE', { network: 'eth' });
// Advanced pool filtering (megafilter) -- Pro only
const { data: filtered } = await cg.onchain.megafilter({
network: 'eth',
reserve_in_usd_gte: 100_000,
sort: 'h24_volume_usd',
});Treasury
// Companies holding Bitcoin
const btcTreasury = await cg.treasury.companyHoldings('bitcoin');
console.log(btcTreasury.total_holdings, btcTreasury.total_value_usd);
// Entity details
const entity = await cg.treasury.entityHoldings('microstrategy');
// Holding chart over time
const chart = await cg.treasury.entityHoldingChart('microstrategy', 'bitcoin');
// Transaction history
const txs = await cg.treasury.entityTransactions('microstrategy');Global & Search
// Global crypto market data
const global = await cg.global.global();
console.log(global.data.total_market_cap.usd);
// DeFi market data
const defi = await cg.global.globalDefi();
// Search coins, exchanges, categories
const results = await cg.global.search('solana');
// Trending coins and NFTs
const trending = await cg.global.trending();
// BTC exchange rates
const rates = await cg.global.exchangeRates();Exchanges & Derivatives
// Top exchanges by trust score
const exchanges = await cg.exchanges.list({ per_page: 10 });
// Exchange tickers
const tickers = await cg.exchanges.tickers('binance', {
coin_ids: 'bitcoin',
});
// Derivatives tickers
const derivTickers = await cg.derivatives.tickers();
// Derivatives exchanges
const derivExchanges = await cg.derivatives.exchanges();NFTs
// NFT collections list
const collections = await cg.nfts.list();
// Collection detail
const bayc = await cg.nfts.getById('bored-ape-yacht-club');
// NFT market chart -- Pro only
const nftChart = await cg.nfts.marketChart('bored-ape-yacht-club', { days: '30' });Pro vs Free API
CoinGecko offers both free and paid API tiers. This SDK works with both -- just pass your API key to unlock Pro features.
| Feature | Free | Pro (Analyst+) |
|---|---|---|
| Rate limit | 30 req/min | 500 req/min |
| Base URL | api.coingecko.com | pro-api.coingecko.com |
| Top gainers/losers | -- | Yes |
| OHLC range | -- | Yes |
| Supply charts | -- | Yes |
| NFT market charts | -- | Yes |
| On-chain megafilter | -- | Yes |
| On-chain top traders | -- | Yes |
| On-chain top holders | -- | Yes |
| Treasury data | -- | Yes |
| Global market cap chart | -- | Yes |
| API usage endpoint | -- | Yes |
// Free tier -- no API key needed
const cg = new CoinGecko();
// Pro tier -- pass your API key
const cg = new CoinGecko({ apiKey: 'CG-xxxxxxxxxxxxxxxxxxxx' });Get a Pro API key at coingecko.com/api/pricing.
Error Handling
All API errors throw a CoinGeckoError with structured information:
import { CoinGecko, CoinGeckoError } from 'coingecko-pro';
const cg = new CoinGecko({ apiKey: 'CG-xxx' });
try {
await cg.coins.getById('this-coin-does-not-exist');
} catch (err) {
if (err instanceof CoinGeckoError) {
console.error(err.message); // Human-readable error description
console.error(err.status); // HTTP status code (0 for network errors)
console.error(err.url); // The URL that was requested
console.error(err.data); // Raw response body, if available
}
}| Status | Meaning | SDK Behavior |
|---|---|---|
| 0 | Network error / timeout | Retried up to maxRetries times |
| 429 | Rate limited | Retried with exponential backoff |
| 401 | Invalid API key | Thrown immediately (not retried) |
| 403 | Pro-only endpoint | Thrown immediately (not retried) |
| 404 | Resource not found | Thrown immediately (not retried) |
| 503 | Service unavailable | Retried with exponential backoff |
Cache & Rate Limiting
Built-in Cache
Every response is cached in memory with a configurable TTL. Identical requests within the cache window are served instantly without hitting the API.
const cg = new CoinGecko({
apiKey: 'CG-xxx',
cacheTtl: 60_000, // Cache responses for 60 seconds
});
// First call hits the API
const btc1 = await cg.coins.getById('bitcoin');
// Second call within 60s returns cached data instantly
const btc2 = await cg.coins.getById('bitcoin');Disable caching globally by setting cacheTtl: 0.
Rate Limiter
A token-bucket rate limiter runs in-process and ensures your application never exceeds the CoinGecko rate limit. When the bucket is empty, requests automatically wait until a token becomes available.
// Pro tier: 500 requests/minute (default when apiKey is set)
const cg = new CoinGecko({ apiKey: 'CG-xxx' });
// Custom rate limit
const cg = new CoinGecko({ apiKey: 'CG-xxx', rateLimit: 100 });Advanced Usage
Standalone Endpoint Classes
For maximum tree-shaking or custom compositions, import endpoint classes directly:
import { CoinGeckoClient } from 'coingecko-pro';
import { CoinsEndpoints } from 'coingecko-pro';
import { OnchainEndpoints } from 'coingecko-pro';
const client = new CoinGeckoClient({ apiKey: 'CG-xxx' });
const coins = new CoinsEndpoints(client);
const onchain = new OnchainEndpoints(client);
const btc = await coins.getById('bitcoin');
const pools = await onchain.trendingPools();Lifecycle Hooks
Use hooks for logging, metrics, or request tracing:
const cg = new CoinGecko({
apiKey: 'CG-xxx',
onRequest: (url) => {
performance.mark(`cg-start-${url}`);
},
onResponse: (url, status, ms) => {
metrics.histogram('coingecko.latency', ms, { status: String(status) });
},
onError: (url, error) => {
logger.error('CoinGecko request failed', { url, error: error.message });
},
});Requirements
- Node.js 18+, Bun, Deno, or any environment with a global
fetchimplementation - No polyfills needed -- zero runtime dependencies
Contributing
Contributions are welcome! Please follow these steps:
- Fork the repository
- Create a feature branch:
git checkout -b feature/my-feature - Make your changes with tests
- Run checks:
npm run lint && npm test - Submit a pull request
License
MIT -- 0xJesus
