GithubHelp home page GithubHelp logo

miscavage / coingecko-api Goto Github PK

View Code? Open in Web Editor NEW
475.0 6.0 114.0 80 KB

A Node.js wrapper for the CoinGecko API with no dependencies.

Home Page: https://www.coingecko.com/api/docs/v3

License: MIT License

JavaScript 100.00%
coingecko cryptocurrency api api-wrapper dependency-less no-dependencies nodejs npm javascript api-client

coingecko-api's Introduction

CoinGecko API Client for Node.js

Travis CI Build Status NPM version NPM downloads Dependency Status Dev Dependency Status

A Node.js wrapper for the CoinGecko API with no dependencies.

• Installation

Latest version: 1.0.10

npm install coingecko-api

• CoinGecko API Documentation

For complete API documentation, up-to-date parameters, responses and errors, please refer to https://www.coingecko.com/api/docs/v3.

• Quick Start Example

//1. Import coingecko-api
const CoinGecko = require('coingecko-api');

//2. Initiate the CoinGecko API Client
const CoinGeckoClient = new CoinGecko();

//3. Make calls
var func = async() => {
  let data = await CoinGeckoClient.ping();
};

• Constants

This module provides helper constants for use in calls.


CoinGecko.ORDER

Order results in specific calls by using one of the following values.

Key Usage Description
GECKO_ASC CoinGecko.ORDER.GECKO_ASC Order results by CoinGecko's scoring system (ascending)
GECKO_DESC CoinGecko.ORDER.GECKO_DESC Order results by CoinGecko's scoring system (descending)
MARKET_CAP_ASC CoinGecko.ORDER.MARKET_CAP_ASC Order results by market cap (ascending)
MARKET_CAP_DESC CoinGecko.ORDER.MARKET_CAP_DESC Order results by market cap (descending)
VOLUME_ASC CoinGecko.ORDER.VOLUME_ASC Order results by volume (ascending)
VOLUME_DESC CoinGecko.ORDER.VOLUME_DESC Order results by volume (descending)
COIN_NAME_ASC CoinGecko.ORDER.COIN_NAME_ASC Order results by coin name (ascending)
COIN_NAME_DESC CoinGecko.ORDER.COIN_NAME_DESC Order results by coin name (descending)
PRICE_ASC CoinGecko.ORDER.PRICE_ASC Order results by price (ascending)
PRICE_DESC CoinGecko.ORDER.PRICE_DESC Order results by price (descending)
HOUR_24_ASC CoinGecko.ORDER.HOUR_24_ASC Order results by 24 hour change (ascending)
HOUR_24_DESC CoinGecko.ORDER.HOUR_24_DESC Order results by 24 hour change (descending)
TRUST_SCORE_DESC CoinGecko.ORDER.TRUST_SCORE_DESC Order results by CoinGecko's trust scoring system (descending)

CoinGecko.STATUS_UPDATE_CATEGORY

Available status update categories to filter by.

Key Usage Description
GENERAL CoinGecko.STATUS_UPDATE_CATEGORY.GENERAL Filter status update results by general news
MILESTONE CoinGecko.STATUS_UPDATE_CATEGORY.MILESTONE Filter status update results by milestones
PARTNERSHIP CoinGecko.STATUS_UPDATE_CATEGORY.PARTNERSHIP Filter status update results by partnerships
EXCHANGE_LISTING CoinGecko.STATUS_UPDATE_CATEGORY.EXCHANGE_LISTING Filter status update results by exchange listings
SOFTWARE_RELEASE CoinGecko.STATUS_UPDATE_CATEGORY.SOFTWARE_RELEASE Filter status update results by software releases
FUND_MOVEMENT CoinGecko.STATUS_UPDATE_CATEGORY.FUND_MOVEMENT Filter status update results by fund movements
NEW_LISTINGS CoinGecko.STATUS_UPDATE_CATEGORY.NEW_LISTINGS Filter status update results by new listings
EVENT CoinGecko.STATUS_UPDATE_CATEGORY.EVENT Filter status update results by events

CoinGecko.STATUS_UPDATE_PROJECT_TYPE

Available status update project types to filter by.

Key Usage Description
COIN CoinGecko.STATUS_UPDATE_PROJECT_TYPE.COIN Filter status update results by coins only
MARKET CoinGecko.STATUS_UPDATE_PROJECT_TYPE.MARKET Filter status update results by markets only

CoinGecko.EVENT_TYPE

List of event types (most recent from CoinGeckoClient.events.fetchTypes())

Key Usage Description
EVENT CoinGecko.EVENT_TYPE.EVENT Filter events by events only
CONFERENCE CoinGecko.EVENT_TYPE.CONFERENCE Filter events by conferences only
MEETUP CoinGecko.EVENT_TYPE.MEETUP Filter events by meetups only

• Making Calls

All calls using the CoinGeckoClient are asynchronous.

All calls are returned in the following format:

{
    success: Boolean,
    message: String,
    code: Number,
    data: Object
}

The CoinGeckoClient splits up the currently available calls outline in the official CoinGecko API documentation into nine (9) parts. (Aside from the ping and global calls.)

Namespace Usage Description
coins CoinGeckoClient.coins[...] Calls related to coins
exchanges CoinGeckoClient.exchanges[...] Calls related to exchanges
statusUpdates CoinGeckoClient.statusUpdates[...] Calls related to status updates
events CoinGeckoClient.events[...] Calls related to events
exchangeRates CoinGeckoClient.exchangeRates[...] Calls related to exchange rates
simple CoinGeckoClient.simple[...] Calls related to "simple" endpoints
finance CoinGeckoClient.finance[...] Calls related to finance endpoints
indexes CoinGeckoClient.indexes[...] Calls related to index endpoints
derivatives CoinGeckoClient.derivatives[...] Calls related to derivative endpoints

• Ping

Check API server status.

ping()

Check API server status.

Usage Example:

let data = await CoinGeckoClient.ping();

• Global

Get cryptocurrency global data.

global()

Get cryptocurrency global data.

Usage Example:

let data = await CoinGeckoClient.global();

• Coins

Calls related to coins.

coins.all()

List all coins with data (name, price, market, developer, community, etc) - paginated by 50.

Official documentation: https://www.coingecko.com/api/docs/v3#/coins/get_coins

Params:

  • params: Object - Parameters to pass through to the request
  • params.order: String - Order results by CoinGecko.ORDER[*]
  • params.per_page: Number - Total results per page
  • params.page: Number - Page through results
  • params.localization: Boolean [default: true] - Set to false to exclude localized languages in response
  • params.sparkline: Boolean [default: false] - Include sparkline 7 days data

Usage Example:

let data = await CoinGeckoClient.coins.all();

coins.list()

Use this to obtain all the coins’ id in order to make API calls

Official documentation: https://www.coingecko.com/api/docs/v3#/coins/get_coins_list

Usage Example:

let data = await CoinGeckoClient.coins.list();

coins.markets()

Use this to obtain all the coins market data (price, market cap, volume).

Official documentation: https://www.coingecko.com/api/docs/v3#/coins/get_coins_markets

Params:

  • params: Object - Parameters to pass through to the request
  • params.order: String - Order results by CoinGecko.ORDER[*]
  • params.per_page: Number - Total results per page
  • params.page: Number - Page through results
  • params.localization: Boolean [default: true] - Set to false to exclude localized languages in response
  • params.sparkline: Boolean [default: false] - Include sparkline 7 days data
  • params.vs_currency: String [default: usd] - The target currency of market data (usd, eur, jpy, etc.)
  • params.ids: Array|String - List of coin id to filter if you want specific results

Usage Example:

let data = await CoinGeckoClient.coins.markets();

coins.fetch()

Get current data (name, price, market, … including exchange tickers) for a coin.

Official documentation: https://www.coingecko.com/api/docs/v3#/coins/get_coins__id_

Params:

  • coinId: String - (Required) The coin id (can be obtained from coins.list()) eg. bitcoin
  • params: Object - Parameters to pass through to the request
  • params.tickers: Boolean - [default: true] - Include ticker data
  • params.market_data: Boolean - [default: true] - Include market data
  • params.community_data: Boolean - [default: true] - Include community data
  • params.developer_data: Boolean - [default: true] - Include developer data
  • params.localization: Boolean [default: true] - Set to false to exclude localized languages in response
  • params.sparkline: Boolean [default: false] - Include sparkline 7 days data

Usage Example:

let data = await CoinGeckoClient.coins.fetch('bitcoin', {});

coins.fetchTickers()

Get coin tickers (paginated to 100 items).

Official documentation: https://www.coingecko.com/api/docs/v3#/coins/get_coins__id__tickers

Params:

  • coinId: String - (Required) The coin id (can be obtained from coins.list()) eg. bitcoin
  • params: Object - Parameters to pass through to the request
  • params.page: Number - Page through results
  • params.exchange_ids: Array|String - Filter tickers by exchange_ids (can be obtained from exchanges.list()) eg. binance
  • params.order: String - [default: trust_score_desc] - Order results by CoinGecko.ORDER.TRUST_SCORE_DESC or CoinGecko.ORDER.VOLUME_DESC

Usage Example:

let data = await CoinGeckoClient.coins.fetchTickers('bitcoin');

coins.fetchHistory()

Get historical data (name, price, market, stats) at a given date for a coin.

Official documentation: https://www.coingecko.com/api/docs/v3#/coins/get_coins__id__history

Params:

  • coinId: String - (Required) The coin id (can be obtained from coins.list()) eg. bitcoin
  • params: Object - Parameters to pass through to the request
  • params.date: String - (Required) The date of data snapshot in dd-mm-yyyy eg. 30-12-2017
  • params.localization: Boolean [default: true] - Set to false to exclude localized languages in response

Usage Example:

let data = await CoinGeckoClient.coins.fetchHistory('bitcoin', {
  date: '30-12-2017'
});

coins.fetchMarketChart()

Get historical market data include price, market cap, and 24h volume (granularity auto).

Official documentation: https://www.coingecko.com/api/docs/v3#/coins/get_coins__id__market_chart

Params:

  • coinId: String - (Required) The coin id (can be obtained from coins.list()) eg. bitcoin
  • params: Object - Parameters to pass through to the request
  • params.days: String [default: 1] - (Required )Data up to number of days ago (eg. 1, 14, 30, max)
  • params.vs_currency: String [default: usd] - (Required) The target currency of market data (usd, eur, jpy, etc.)

Usage Example:

let data = await CoinGeckoClient.coins.fetchMarketChart('bitcoin');

coins.fetchMarketChartRange()

Get historical market data include price, market cap, and 24h volume within a range of timestamp (granularity auto). Minutely data will be used for duration within 1 day. Hourly data will be used for duration between 1 day and 90 days. Daily data will be used for duration above 90 days.

Official documentation: https://www.coingecko.com/api/documentations/v3#/coins/get_coins__id__market_chart_range

Params:

  • coinId: String - (Required) The coin id (can be obtained from coins.list()) eg. bitcoin
  • params: Object - Parameters to pass through to the request
  • params.vs_currency: String [default: usd] - The target currency of market data (usd, eur, jpy, etc.)
  • params.from: Number - (Required) From date in UNIX Timestamp (eg. 1392577232)
  • params.to: Number - (Required) To date in UNIX Timestamp (eg. 1422577232)

Usage Example:

let data = await CoinGeckoClient.coins.fetchMarketChartRange('bitcoin', {
  from: 1392577232,
  to: 1422577232,
});

coins.fetchStatusUpdates()

Get status updates for a given coin.

Official documentation: https://www.coingecko.com/api/docs/v3#/coins/get_coins__id__status_updates

Params:

  • coinId: String - (Required) The coin id (can be obtained from coins.list()) eg. bitcoin
  • params: Object - Parameters to pass through to the request
  • params.per_page: Number - Total results per page
  • params.page: Number - Page through results

Usage Example:

let data = await CoinGeckoClient.coins.fetchStatusUpdates('bitcoin');

coins.fetchCoinContractInfo()

Get coin info from contract address.

Official documentation: https://www.coingecko.com/api/docs/v3#/coins/get_coins__id__contract__contract_address_

Params:

  • contractAddress: String - (Required) Token’s contract address
  • assetPlatform: String [default: ethereum] - Asset platform (only ethereum is supported at this moment).

Usage Example:

// 0x contract address (as a test)
let zrx = '0xe41d2489571d322189246dafa5ebde1f4699f498';
let data = await CoinGeckoClient.coins.fetchCoinContractInfo(zrx);

coins.fetchCoinContractMarketChart()

Get historical market data include price, market cap, and 24h volume (granularity auto) from a contract address.

Official documentation: https://www.coingecko.com/api/documentations/v3#/contract/get_coins__id__contract__contract_address__market_chart_

Params:

  • contractAddress: String - (Required) Token’s contract address
  • assetPlatform: String [default: ethereum] - Asset platform (only ethereum is supported at this moment).
  • params: Object - Parameters to pass through to the request
  • params.vs_currency: String [default: usd] - (Required) The target currency of market data (usd, eur, jpy, etc.)
  • params.days: String [default: 1] - (Required) Data up to number of days ago (eg. 1,14,30,max)

Usage Example:

// 0x contract address (as a test)
let zrx = '0xe41d2489571d322189246dafa5ebde1f4699f498';
let data = await CoinGeckoClient.coins.fetchCoinContractMarketChart(zrx);

coins.fetchCoinContractMarketChartRange()

Get historical market data include price, market cap, and 24h volume within a range of timestamp (granularity auto).

Official documentation: https://www.coingecko.com/api/documentations/v3#/contract/get_coins__id__contract__contract_address__market_chart_range Params:

  • contractAddress: String - (Required) Token’s contract address
  • assetPlatform: String [default: ethereum] - Asset platform (only ethereum is supported at this moment).
  • params: Object - Parameters to pass through to the request
  • params.vs_currency: String [default: usd] - (Required) The target currency of market data (usd, eur, jpy, etc.)
  • params.from: Number - (Required) From date in UNIX Timestamp (eg. 1392577232)
  • params.to: Number - (Required) To date in UNIX Timestamp (eg. 1422577232)

Usage Example:

// 0x contract address (as a test)
let zrx = '0xe41d2489571d322189246dafa5ebde1f4699f498';
let data = await CoinGeckoClient.coins.fetchCoinContractMarketChartRange(zrx, 'ethereum', {
  from: 1392577232,
  to: 1422577232,
});

• Exchanges

Calls related to exchanges.

exchanges.all()

List all exchanges.

Official documentation: https://www.coingecko.com/api/docs/v3#/exchanges_(beta)/get_exchanges

Usage Example:

let data = await CoinGeckoClient.exchanges.all();

exchanges.list()

List all supported markets id and name (no pagination required).

Official documentation: https://www.coingecko.com/api/docs/v3#/exchanges_(beta)/get_exchanges_list

Usage Example:

let data = await CoinGeckoClient.exchanges.list();

exchanges.fetch()

Get exchange volume in BTC and top 100 tickers only for a given exchange.

Official documentation: https://www.coingecko.com/api/docs/v3#/exchanges_(beta)/get_exchanges__id_

Params:

  • exchangeId: String - (Required) The exchange id (can be obtained from exchanges.all()) eg. binance

Usage Example:

let data = await CoinGeckoClient.exchanges.fetch('binance');

exchanges.fetchTickers()

Get tickers for a given exchange.

Official documentation: https://www.coingecko.com/api/docs/v3#/exchanges_(beta)/get_exchanges__id__tickers

Params:

  • exchangeId: String - (Required) The exchange id (can be obtained from exchanges.all()) eg. binance
  • params: Object - Parameters to pass through to the request
  • params.page: Number - Page through results
  • params.coin_ids: Array|String - Filter tickers by coin_ids (can be obtained from coins.list()) eg. bitcoin
  • params.order: String - [default: trust_score_desc] - Order results by CoinGecko.ORDER.TRUST_SCORE_DESC or CoinGecko.ORDER.VOLUME_DESC

Usage Example:

let data = await CoinGeckoClient.exchanges.fetchTickers('binance');

exchanges.fetchStatusUpdates()

Get status updates for a given exchange.

Official documentation: https://www.coingecko.com/api/docs/v3#/exchanges_(beta)/get_exchanges__id__status_updates

Params:

  • exchangeId: String - (Required) The exchange id (can be obtained from exchanges.all()) eg. binance
  • params: Object - Parameters to pass through to the request
  • params.page: Number - Page through results
  • params.per_page: Number - Total results per page

Usage Example:

let data = await CoinGeckoClient.exchanges.fetchStatusUpdates('binance');

exchanges.fetchVolumeChart()

Get volume chart data for a given exchange, returned in BTC

Official documentation: https://www.coingecko.com/en/api#operations-exchanges%20(beta)-get_exchanges__id__volume_chart

Params:

  • exchangeId: String - (Required) The exchange id (can be obtained from exchanges.all()) eg. binance
  • params: Object - Parameters to pass through to the request
  • params.days: Number - Data up to number of days ago (eg. 1, 14, 30)

Usage Example:

let data = await CoinGeckoClient.exchanges.fetchVolumeChart('binance', {
  days: 1,
});

• Status Updates

Calls related to status updates.

statusUpdates.all()

List all status_updates with data (description, category, created_at, user, user_title and pin).

Official documentation: https://www.coingecko.com/api/docs/v3#/status_updates_(beta)/get_status_updates

Params:

  • params: Object - Parameters to pass through to the request
  • params.category: Number - Filter results by CoinGecko.STATUS_UPDATE_CATEGORY[*]
  • params.project_type: Number - Filter results by CoinGecko.STATUS_UPDATE_PROJECT_TYPE[*] (If left empty returns both status from coins and markets)
  • params.page: Number - Page through results
  • params.per_page: Number - Total results per page

Usage Example:

let data = await CoinGeckoClient.statusUpdates.all();

• Events

Calls related to events.

events.all()

Get events, paginated by 100.

Official documentation: https://www.coingecko.com/api/docs/v3#/events/get_events

Params:

  • params: Object - Parameters to pass through to the request
  • params.country_code: Number - country_code of event (eg. US). Use events.fetchHistory() for list of country_codes
  • params.type: String - Type of event (eg. Conference). Use events.fetchTypes() for list of types. Or use CoinGecko.EVENT_TYPE[*]
  • params.page: Number - Page through results
  • params.upcoming_events_only: Boolean - [default: true] - Lists only upcoming events
  • params.from_date: String - Lists events after this date yyyy-mm-dd
  • params.to_date: String - Lists events before this date yyyy-mm-dd (set upcoming_events_only to false if fetching past events)

Usage Example:

let data = await CoinGeckoClient.events.all();

events.fetchCountries()

Get list of event countries.

Official documentation: https://www.coingecko.com/api/docs/v3#/events/get_events_countries

Usage Example:

let data = await CoinGeckoClient.events.fetchCountries();

events.fetchTypes()

Get list of event types.

Official documentation: https://www.coingecko.com/api/docs/v3#/events/get_events_types

Usage Example:

let data = await CoinGeckoClient.events.fetchTypes();

• Exchange Rates

Calls related to exchange rates.

exchangeRates.all()

Get BTC-to-Currency exchange rates.

Official documentation: https://www.coingecko.com/api/docs/v3#/exchange_rates/get_exchange_rates

Usage Example:

let data = await CoinGeckoClient.exchangeRates.all();

• Simple

Calls related to simple endpoints.

simple.price()

Get the current price of any cryptocurrencies in any other supported currencies that you need.

Official documentation: https://www.coingecko.com/api/docs/v3#/simple/get_simple_price

Params:

  • params: Object - Parameters to pass through to the request
  • params.ids: Array|String - (Required) A single id or a list of coin ids to filter if you want specific results. Use coins.list() for a list of coin ids.
  • params.vs_currencies: Array|String - [default: usd] - A single id or a list of ids. Use simple.supportedVsCurrencies() for a list of vsCurrency ids.
  • params.include_24hr_vol: Boolean - [default: false] - To include 24hr volume.
  • params.include_last_updated_at: Boolean - [default: false] - To include last_updated_at of price.

Usage Example:

let data = await CoinGeckoClient.simple.price({
    ids: ['bitcoin', 'ethereum'],
    vs_currencies: ['eur', 'usd'],
});

simple.supportedVsCurrencies()

Get list of supported vs/comparisons currencies.

Official documentation: https://www.coingecko.com/api/docs/v3#/simple/get_simple_supported_vs_currencies

Usage Example:

let data = await CoinGeckoClient.simple.supportedVsCurrencies();

simple.fetchTokenPrice()

Get current price of tokens (using contract addresses) for a given platform in any other currency that you need.

Official documentation: https://www.coingecko.com/en/api#operations-simple-get_simple_token_price__id_

Params:

  • params: Object - Parameters to pass through to the request
  • assetPlatform: String - [default: ethereum] - (Required) Asset platform (only ethereum is supported at this moment)
  • params.contract_addresses: String|Array - (Required) Token’s contract address
  • params.vs_currencies: String|Array - (Required) vs_currency of coins. Use simple.supportedVsCurrencies() for a list of vsCurrency ids.
  • params.include_market_cap: Boolean - [default: false] - Include market cap in results or not
  • params.include_24hr_vol: Boolean - [default: false] - Include 24hr volume in results or not
  • params.include_24hr_change: Boolean - [default: false] - Include 24hr change in results or not
  • params.include_last_updated_at: Boolean - [default: false] - Include last updated date in results or not

Usage Example:

// 0x contract address (as a test)
var zrx = '0xe41d2489571d322189246dafa5ebde1f4699f498';
let data = await CoinGeckoClient.simple.fetchTokenPrice({
  contract_addresses: zrx,
  vs_currencies: 'usd',
});

• Finance

Calls related to finance endpoints.

finance.fetchPlatforms()

List all finance platforms

Official documentation: https://www.coingecko.com/api/documentations/v3#/finance_(beta)/get_finance_platforms

Params:

  • params: Object - Parameters to pass through to the request
  • params.per_page: Number - Total results per page
  • params.page: Number - Page of results (paginated to 100 by default)

Usage Example:

let data = await CoinGeckoClient.finance.fetchPlatforms();

finance.fetchProducts()

List all finance products

Official documentation: https://www.coingecko.com/api/documentations/v3#/finance_(beta)/get_finance_products

Params:

  • params: Object - Parameters to pass through to the request
  • params.per_page: Number - Total results per page
  • params.page: Number - Page of results (paginated to 100 by default)
  • params.start_at: String - Start date of the financial products
  • params.end_at: String - End date of the financial products

Usage Example:

let data = await CoinGeckoClient.finance.fetchProducts();

• Indexes

Calls related to index endpoints.

indexes.all()

List all market indexes

Official documentation: https://www.coingecko.com/en/api#operations-tag-indexes_(beta)

Params:

  • params: Object - Parameters to pass through to the request
  • params.per_page: Number - Total results per page
  • params.page: Number - Page of results (paginated to 100 by default)

Usage Example:

let data = await CoinGeckoClient.indexes.all();

indexes.fetch()

List all market indexes

Official documentation: https://www.coingecko.com/en/api#operations-indexes%20(beta)-get_indexes__id_

Params:

  • indexId: String - (Required) The index id (can be obtained from indexes.list())

Usage Example:

let testIndexId = 'BTC'; // as a test
let data = await CoinGeckoClient.indexes.fetch(testIndexId);

indexes.list()

List market indexes id and name

Official documentation: https://www.coingecko.com/en/api#operations-indexes%20(beta)-get_indexes_list

Usage Example:

let data = await CoinGeckoClient.indexes.list();

• Derivatives

Calls related to derivative endpoints.

derivatives.fetchTickers()

List all derivative tickers

Official documentation: https://www.coingecko.com/api/documentations/v3#/operations-tag-derivatives_(beta)

Usage Example:

let data = await CoinGeckoClient.derivatives.fetchTickers();

derivatives.allExchanges()

List all derivative exchanges

Official documentation: https://www.coingecko.com/en/api#operations-derivatives%20(beta)-get_derivatives_exchanges

Params:

  • params: Object - Parameters to pass through to the request
  • params.order: String - Order results by CoinGecko.ORDER[*]
  • params.per_page: Number - Total results per page
  • params.page: Number - Page of results

Usage Example:

let data = await CoinGeckoClient.derivatives.allExchanges();

derivatives.fetchExchange()

Show derivative exchange data

Official documentation: https://www.coingecko.com/en/api#operations-derivatives%20(beta)-get_derivatives_exchanges__id_

Params:

  • exchangeId: String - (Required) The exchange id (can be obtained from derivatives.listExchanges())
  • params: Object - Parameters to pass through to the request
  • params.include_tickers: boolean - [default: false] - Include the tickers information

Usage Example:

let testExchangeId = 'bitmex'; // as a test
let data = await CoinGeckoClient.derivatives.fetchExchange(testExchangeId);

derivatives.listExchanges()

List all derivative exchanges name and identifier

Official documentation: https://www.coingecko.com/en/api#operations-derivatives%20(beta)-get_derivatives_exchanges_list

Usage Example:

let data = await CoinGeckoClient.derivatives.listExchanges();

• Say Hi

Find me on Gab: @markmiscavage.

Tweet at me: @markmiscavage.

• License

MIT License

Copyright (c) 2020 Mark Miscavage

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

coingecko-api's People

Contributors

miscavage avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

coingecko-api's Issues

Coins list fetching api call fails with parse error

Description

I am using this library to scrape data from coingecko platform but i have recently started receiving the following error a lot

SyntaxError: Unexpected token e in JSON at position 0
at JSON.parse (<anonymous>)
at IncomingMessage.<anonymous> (/home/omer/abc-miner/node_modules/coingecko-api/lib/CoinGecko.js:864:25)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (internal/streams/readable.js:1327:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)

on checking the source code at node_modules/coingecko-api/lib/CoinGecko.js:864 i find this

res.on('end', () => {
          try {
            body = Buffer.concat(body);
            body = body.toString();

            //Check if page is returned instead of JSON
            if (body.startsWith('<!DOCTYPE html>')) {
              Utils._WARN_('Invalid request', 'There was a problem with your request. The parameter(s) you gave are missing or incorrect.');
            } else if (body.startsWith('Throttled')) {
              Utils._WARN_('Throttled request', 'There was a problem with request limit.');
            }

            //Attempt to parse
>>            body = JSON.parse(body);    // this is the line referred to in the error stack i-e CoinGecko.js:864
          }
          catch (error) {
            reject(error);
          };
...

I use this way of fetching a list coins list, here is my code

try  {
  const CoinGecko = require('coingecko-api');
  const CoinGeckoClient = new CoinGecko();
  console.log('before calling CG api');
  let response = await CoinGeckoClient.coins.list();
  console.log('after calling CG api'); // this log rarely works
} catch(err) {
  console.log(err)
}

CORS error when querying from localhost

Sometimes I see the following error:

Access to fetch at 'https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
request.js:145 GET https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd net::ERR_FAILED 429

Is it possible to set the no-cors request mode as suggested by the error?

"error code: 1015" not treated as rate limit error

I was for-looping to get prices of multiple tokens. My server receives error: SyntaxError: Unexpected token e in JSON at position 0. I used debugger and found out that the problem occurs here in CoinGecko.js:

            //Check if page is returned instead of JSON
            if (body.startsWith('<!DOCTYPE html>')) {
              Utils._WARN_('Invalid request', 'There was a problem with your request. The parameter(s) you gave are missing or incorrect.');
            } else if (body.startsWith('Throttled')) {
              Utils._WARN_('Throttled request', 'There was a problem with request limit.');
            }
            //Attempt to parse
            body = JSON.parse(body);

Does it work with Angular?

I think this library should work with latest Angular (7) but I'm having hard time making it work.
I installed the library and added it to Angular component like this:

const CoinGecko = require('coingecko-api');
const CoinGeckoClient = new CoinGecko();

then called it like in the example just to test it:

ngOnInit() {
    const func = async() => {
      const data = await CoinGeckoClient.ping();
      console.log(data);
    };
    func();
}

When I run ng serve I'm getting this error:

ERROR in ./node_modules/coingecko-api/lib/CoinGecko.js
Module not found: Error: Can't resolve 'https' in '/node_modules/coingecko-api/lib'

So Im not really sure what can be the problem here. I tried couple of things but I cannot make it work. Any help would be appreciated. Thanks

TypeError: CoinGecko is not a constructor

Tested with the example given, what's wrong?

/var/www/Crypto/syncPriceData.js:14
const CoinGeckoClient = new CoinGecko();
                        ^

TypeError: CoinGecko is not a constructor
    at Object.<anonymous> (/var/www/Crypto/syncPriceData.js:14:25)
    at Module._compile (internal/modules/cjs/loader.js:707:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:718:10)
    at Module.load (internal/modules/cjs/loader.js:605:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:544:12)
    at Function.Module._load (internal/modules/cjs/loader.js:536:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:760:12)
    at startup (internal/bootstrap/node.js:303:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:872:3)

Missing TypeScript Interface Definitions

Hi,

I'm getting a TypeScript error for the coins.list() function. It says it doesn't exist on coins. I can see that it's not included in the interface definition for it but the call still works.

image

Has it been deprecated? Or just not included in the interface?

Thanks,
Alex

Browser platform support request

By removing the dependencies on querystring and https, this codebase would also run on browser platforms. I see there's only one call for each module in the whole code.

Supporting the browser platform would be very helpful for server-less apps!

Package doesn't support premium subscription on CoinGecko.

We are trying to migrate from free to pro subscription in Coingecko API. this doesn't sound good. As we have to reimplement
the whole logic again. Another solution is to allow me to open a new pull request and implement the solution.

Coingecko is using another base URL for the pro subscription http://pro-api.coingecko.com
also, it requires you to add a param whenever you are using the API x_cg_pro_api_key. you will be given the token when you create a premium account. I already have one so I can implement the solution.
What do you think?

Missing fetch() type

The type definition for client.coin.fetch() function is missing for typescript.

// package.json
{
	"dependencies": {
		"coingecko-api": "^1.0.10",
		...
	"devDependencies": {
		"@types/coingecko-api": "^1.0.2",
		...
}

Error message with CoinGeckoClient.coins.markets endpoint

I recently implemented the markets endpoint which was working fine until recently. There was a recent change in Coingecko API for the markets endpoint (I think), so now when I am calling the markets endpoint, it gives me this error message:

SyntaxError: Unexpected token e in JSON at position 0
    at JSON.parse (<anonymous>)
    at IncomingMessage.<anonymous> (/node_modules/coingecko-api/lib/CoinGecko.js:864:25)
    at IncomingMessage.emit (events.js:326:22)
    at endReadableNT (_stream_readable.js:1241:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)
(node:69766) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:530:11)
    at ServerResponse.header (/node_modules/express/lib/response.js:794:10)
    at ServerResponse.send (/node_modules/express/lib/response.js:174:12)
    at ServerResponse.json (/node_modules/express/lib/response.js:278:15)
    at /api.routes.js:167:29
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:69766) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:69766) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

This is what I am using in my call as parameters:

CoinGeckoClient.coins.markets({
          ids: coinNames,
          vs_currency: currencyUsed,
          localization: false
  }) 
   .then(data => {
     ...
  })

Coin Images full color

Hello world!

Possibly it is not a problem, but a suggestion.

In the market data, you can pull the images of each coin from the data. But the images have been saved into a circle shape with a transparent background. Since you can create the circle shape in most applications with a "borderRadius" or similar, it is better to provide the images with a background color or white with a transparent background.

From my point of view, it would be better to save the coin icon as white on a transparent background or as SVG with another data field with the base color. Like Bitcoin: { image: "the image URL", coin_color: "##F79413" }. But it depends on what you guys aim for.

I pulled the data with the following code:

let coinDataSet = async () => {
  let coinData = await CoinGeckoClient.coins.markets();
  
  fs.writeFileSync("./assets/data/coinData.json", JSON.stringify(coinData));
};

what I got was:

  {
  "success": true,
  "message": "OK",
  "code": 200,
  "data": [
  {
    "id": "bitcoin",
    "symbol": "btc",
    "name": "Bitcoin",
// this is the image i mean the other images in this dataset aew similar.
    "image": "https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579",
// ---
    "current_price": 47003,
    "market_cap": 887157897642,
    "market_cap_rank": 1,
    "fully_diluted_valuation": 985473262230,
    "total_volume": 22264401998,
    "high_24h": 48126,
    "low_24h": 46487,
    "price_change_24h": 68.53,
    "price_change_percentage_24h": 0.14602,
    "market_cap_change_24h": -293282295.3970947,
    "market_cap_change_percentage_24h": -0.03305,
    "circulating_supply": 18904943,
    "total_supply": 21000000,
    "max_supply": 21000000,
    "ath": 69045,
    "ath_change_percentage": -31.94853,
    "ath_date": "2021-11-10T14:24:11.849Z",
    "atl": 67.81,
    "atl_change_percentage": 69191.66172,
    "atl_date": "2013-07-06T00:00:00.000Z",
    "roi": null,
    "last_updated": "2021-12-19T10:35:35.424Z"
  },
  {
    "id": "ethereum",
    "symbol": "eth",
    "name": "Ethereum",

by the way: I love your API, thank you very much that you allow us to us it :)

Ability to use pro endpoint

Currently there doesn't seem to be an option to specify the url in the constructor.

Would it be possible to add support for passing endpoints in. For example, the pro endpoint is like below.

https://pro-api.coingecko.com/api/v3/ping?x_cg_pro_api_key=YOUR_API_KEY

We need the typescript typings

Hi,

Thanks for the great work. Love the api and this package. Would it be possible for you to create typescript typings? This will make it a lot easier to implement the package in our projects.

with kind regards

Update document to notify that `binance-smart-chain` is now supported with token contracts API

As I read here https://github.com/miscavage/CoinGecko-API/blob/master/README.md#coinsfetchcoincontractinfo, it says currently unsupported with BSC but when I call

const response = await client.contractMarketChartRange({
    id: "binance-smart-chain" as any,
    contract_address: cakeTokenCotractAddress,
    vs_currency: "usd",
    from: 1647101750,
    to: 1647131756,
  });

it gave response correctly so I suggest update documentatiot for avoid unnecessary guessing effort from users. Just confirm that you are still standing by to review and merge PR, I will do it for you guys.

Just a question

Please forgive me, but i cannot find the answer to my question anywhere else so i had to post it here.
i try to get historical data on the Total Market cap. This seems to not be possible with the API?
Do you know of a way to get this data?

Nodejs Not working.

I need extract Bitcoin value in nodejs!
That no reply with any code;

var func = async() => {
let data = await CoinGeckoClient.ping();
let data2 = CoinGeckoClient.coins.fetchTickers('bitcoin')
};

function expvu(message){
var func = async() => {
console.log(CoinGeckoClient.coins.fetchTickers('bitcoin'));
let data = await CoinGeckoClient.coins.fetch('bitcoin', {});
console.log(data2); message.reply(data2);
console.log("Test");

};}

API request timeout

The following error is encountered sometimes.
Error: CoinGecko API request timed out. Current timeout is: 30000 milliseconds

Is there a way to set a default timeout or auto-retry on timeout?

Simple price request does not work with the current version of the API

Up until a week ago, this package worked with the CoinGecko API. However, now it's broken.

Script to reproduce:

import CoinGeckoApi from 'coingecko-api';

const CoinGeckoClient = new CoinGeckoApi();

async function main() {
  const result = await CoinGeckoClient.simple.price({
    ids: ['ethereum', 'litecoin', 'matic-network', 'optimism', 'aave'],
    vs_currencies: ['eur', 'usd', 'gbp', 'chf', 'btc', 'eth']
  });
  console.log(result);
}

main();

Error message:

(node:104763) [CoinGecko] Warning: Invalid request
There was a problem with your request. The parameter(s) you gave are missing or incorrect.
(Use `node --trace-warnings ...` to show where the warning was created)
/path/to/project/node_modules/coingecko-api/lib/CoinGecko.js:864
            body = JSON.parse(body);
                        ^
SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at IncomingMessage.<anonymous> (/path/to/project/node_modules/coingecko-api/lib/CoinGecko.js:864:25)
    at IncomingMessage.emit (node:events:525:35)
    at IncomingMessage.emit (node:domain:489:12)
    at endReadableNT (node:internal/streams/readable:1358:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.