Інтеграція з CoinGecko API

Проєктуємо та розробляємо блокчейн-рішення повного циклу: від архітектури смарт-контрактів до запуску DeFi-протоколів, NFT-маркетплейсів та криптобірж. Аудит безпеки, токеноміка, інтеграція з наявною інфраструктурою.
Показано 1 з 1Усі 1306 послуг
Інтеграція з CoinGecko API
Простий
~2-3 дні
Часті запитання

Напрямки блокчейн-розробки

Етапи блокчейн-розробки

Останні роботи

  • image_website-b2b-advance_0.webp
    Розробка сайту компанії B2B ADVANCE
    1308
  • image_web-applications_feedme_466_0.webp
    Розробка веб-додатків для компанії FEEDME
    1220
  • image_websites_belfingroup_462_0.webp
    Розробка веб-сайту для компанії БЕЛФІНГРУП
    921
  • image_ecommerce_furnoro_435_0.webp
    Розробка інтернет магазину для компанії FURNORO
    1149
  • image_logo-advance_0.webp
    Розробка логотипу компанії B2B Advance
    611
  • image_crm_enviok_479_0.webp
    Розробка веб-додатків для компанії Enviok
    886

Інтеграція з CoinGecko API

CoinGecko — один з двох крупних агрегаторів ринкових даних (другий — CoinMarketCap). Якщо потрібні ціни токенів, історичні дані, метадані монет або ринкова капіталізація — CoinGecko API покриває більшість завдань. Free tier (Demo) достатньо для більшості додатків; Pro дає вищі ліміти та додаткові ендпоінти.

Ліміти та автентифікація

Тариф Rate limit Ліміт/місяць
Demo (безкоштовно) 30 req/min ~10,000
Analyst 500 req/min 500,000
Lite 500 req/min 500,000
Pro 1,000 req/min Unlimited

Demo-ключ отримується на сайті, передається як x-cg-demo-api-key header або ?x_cg_demo_api_key= параметр. Без ключа — дуже жорсткий rate limit (~10 req/min), в production так працювати не можна.

const COINGECKO_BASE = 'https://api.coingecko.com/api/v3';

class CoinGeckoClient {
  private apiKey: string;

  constructor(apiKey: string) {
    this.apiKey = apiKey;
  }

  private async get<T>(endpoint: string, params: Record<string, string> = {}): Promise<T> {
    const url = new URL(`${COINGECKO_BASE}${endpoint}`);
    Object.entries(params).forEach(([k, v]) => url.searchParams.set(k, v));

    const response = await fetch(url.toString(), {
      headers: {
        'x-cg-demo-api-key': this.apiKey,
        'Accept': 'application/json',
      },
    });

    if (response.status === 429) {
      throw new RateLimitError('CoinGecko rate limit exceeded');
    }

    if (!response.ok) {
      throw new Error(`CoinGecko API error: ${response.status}`);
    }

    return response.json();
  }
}

Ключові ендпоінти

Ціна токена — найчастіший запрос:

// Ціна одного або кількох токенів
async function getTokenPrices(
  coinIds: string[],
  vsCurrencies: string[] = ['usd', 'eur']
): Promise<Record<string, Record<string, number>>> {
  return this.get('/simple/price', {
    ids: coinIds.join(','),         // 'bitcoin,ethereum,tether'
    vs_currencies: vsCurrencies.join(','),
    include_24hr_change: 'true',
    include_last_updated_at: 'true',
  });
}

// За адресою контракту (без знання CoinGecko ID)
async function getTokenPriceByContract(
  contractAddress: string,
  platform: string = 'ethereum'  // 'binance-smart-chain', 'polygon-pos', тощо
): Promise<TokenPrice> {
  return this.get(`/simple/token_price/${platform}`, {
    contract_addresses: contractAddress,
    vs_currencies: 'usd',
    include_24hr_change: 'true',
  });
}

Історичні дані для графіків:

// OHLC дані (свічи)
async function getOhlcData(coinId: string, days: number): Promise<[number, number, number, number, number][]> {
  // Повертає масив [timestamp, open, high, low, close]
  return this.get(`/coins/${coinId}/ohlc`, {
    vs_currency: 'usd',
    days: days.toString(),  // 1, 7, 14, 30, 90, 180, 365, 'max'
  });
}

// Market chart (ціна + volume + marketcap за часом)
async function getMarketChart(coinId: string, days: number) {
  return this.get(`/coins/${coinId}/market_chart`, {
    vs_currency: 'usd',
    days: days.toString(),
    interval: days <= 1 ? 'minutely' : days <= 90 ? 'hourly' : 'daily',
  });
}

Кешування — обов'язково

Дергати CoinGecko на кожний запрос користувача — швидкий шлях до вичерпання ліміту. Ціни оновлюються кожні 60 секунд; кеш на 30–60 секунд не гіршає точність:

import { Redis } from 'ioredis';

class CachedCoinGeckoClient extends CoinGeckoClient {
  constructor(private redis: Redis, apiKey: string) {
    super(apiKey);
  }

  async getCachedPrice(coinId: string): Promise<number> {
    const cacheKey = `coingecko:price:${coinId}`;
    const cached = await this.redis.get(cacheKey);

    if (cached) return parseFloat(cached);

    const data = await this.getTokenPrices([coinId]);
    const price = data[coinId]?.usd;

    if (price) {
      await this.redis.setex(cacheKey, 60, price.toString());  // TTL 60 секунд
    }

    return price;
  }
}

Для high-traffic сервісів: фоновий job оновлює ціни кожні 30 секунд, усі користувацькі запити читають з кешу.

Пошук CoinGecko ID за контрактом

Проблема: у вас є адреса токена, але не його CoinGecko ID. Рішення:

// Отримати список усіх монет з їх контрактами
// Цей ендпоінт викликається рідко, кешується на годи
async function buildContractToIdMap(platform: string): Promise<Map<string, string>> {
  const coins = await this.get<Array<{ id: string; platforms: Record<string, string> }>>(
    '/coins/list',
    { include_platform: 'true' }
  );

  const map = new Map<string, string>();
  for (const coin of coins) {
    const contractAddress = coin.platforms[platform];
    if (contractAddress) {
      map.set(contractAddress.toLowerCase(), coin.id);
    }
  }

  return map;
}

Кешуйте список монет (~15,000 позицій) на кілька годин — він змінюється рідко.

Обробка помилок та retry

async function fetchWithRetry<T>(
  fn: () => Promise<T>,
  maxRetries = 3,
  baseDelay = 1000
): Promise<T> {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await fn();
    } catch (err) {
      if (err instanceof RateLimitError) {
        // Експоненціальний backoff при rate limit
        const delay = baseDelay * Math.pow(2, attempt);
        await new Promise(r => setTimeout(r, delay));
        continue;
      }
      throw err;  // Інші помилки не ретраимо
    }
  }
  throw new Error('Max retries exceeded');
}

Для критичних сервісів: додайте fallback на CoinMarketCap або Binance Public API при недоступності CoinGecko.