Giter Site home page Giter Site logo

pycoingecko's Introduction

CoinGecko API wrapper

PyPi Version GitHub

Python3 wrapper around the CoinGecko API (V3)

Installation

PyPI

pip install -U pycoingecko

or from source

git clone https://github.com/man-c/pycoingecko.git
cd pycoingecko
python3 setup.py install

Usage

For free API:

from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()

For users with Pro API Key:

from pycoingecko import CoinGeckoAPI
cg = pycoingecko.CoinGeckoAPI(api_key='YOUR_API_KEY')

Examples

The required parameters for each endpoint are defined as required (mandatory) parameters for the corresponding functions.
Any optional parameters can be passed using same names, as defined in CoinGecko API doc (https://www.coingecko.com/en/api/documentation).

For any parameter:

  • Lists are supported as input for multiple-valued comma-separated parameters
    (e.g. see /simple/price usage examples).
  • Booleans are supported as input for boolean type parameters; they can be str ('true', 'false'') or bool (True, False)
    (e.g. see /simple/price usage examples).

Usage examples:

# /simple/price endpoint with the required parameters
>>> cg.get_price(ids='bitcoin', vs_currencies='usd')
{'bitcoin': {'usd': 3462.04}}

>>> cg.get_price(ids='bitcoin,litecoin,ethereum', vs_currencies='usd')
# OR (lists can be used for multiple-valued arguments)
>>> cg.get_price(ids=['bitcoin', 'litecoin', 'ethereum'], vs_currencies='usd')
{'bitcoin': {'usd': 3461.27}, 'ethereum': {'usd': 106.92}, 'litecoin': {'usd': 32.72}}

>>> cg.get_price(ids='bitcoin,litecoin,ethereum', vs_currencies='usd,eur')
# OR (lists can be used for multiple-valued arguments)
>>> cg.get_price(ids=['bitcoin', 'litecoin', 'ethereum'], vs_currencies=['usd', 'eur'])
{'bitcoin': {'usd': 3459.39, 'eur': 3019.33}, 'ethereum': {'usd': 106.91, 'eur': 93.31}, 'litecoin': {'usd': 32.72, 'eur': 28.56}}

# optional parameters can be passed as defined in the API doc (https://www.coingecko.com/api/docs/v3)
>>> cg.get_price(ids='bitcoin', vs_currencies='usd', include_market_cap='true', include_24hr_vol='true', include_24hr_change='true', include_last_updated_at='true')
{'bitcoin': {'usd': 3458.74, 'usd_market_cap': 60574330199.29028, 'usd_24h_vol': 4182664683.6247883, 'usd_24h_change': 1.2295378479069035, 'last_updated_at': 1549071865}}
# OR (also booleans can be used for boolean type arguments)
>>> cg.get_price(ids='bitcoin', vs_currencies='usd', include_market_cap=True, include_24hr_vol=True, include_24hr_change=True, include_last_updated_at=True)
{'bitcoin': {'usd': 3458.74, 'usd_market_cap': 60574330199.29028, 'usd_24h_vol': 4182664683.6247883, 'usd_24h_change': 1.2295378479069035, 'last_updated_at': 1549071865}}

API documentation

https://www.coingecko.com/en/api/documentation

Endpoints included

⚠️ Endpoints documentation: To make sure that you are using properly each endpoint you should check the API documentation. Return behaviour and parameters of the endpoints, such as pagination, might have changed.
Any optional parameters defined in CoinGecko API doc can be passed as function parameters using same parameters names with the API (see Examples above).

ping

  • /ping (Check API server status)
    cg.ping()
simple

  • /simple/price (Get the current price of any cryptocurrencies in any other supported currencies that you need)
    cg.get_price()
  • /simple/token_price/{id} (Get current price of tokens (using contract addresses) for a given platform in any other currency that you need)
    cg.get_token_price()
  • /simple/supported_vs_currencies (Get list of supported_vs_currencies)
    cg.get_supported_vs_currencies()
coins

  • /coins/list (List all supported coins id, name and symbol (no pagination required))

    cg.get_coins_list()
  • /coins/markets (List all supported coins price, market cap, volume, and market related data)

    cg.get_coins_markets()
  • /coins/{id} (Get current data (name, price, market, ... including exchange tickers) for a coin)

    cg.get_coin_by_id()
  • /coins/{id}/tickers (Get coin tickers (paginated to 100 items))

    cg.get_coin_ticker_by_id()
  • /coins/{id}/history (Get historical data (name, price, market, stats) at a given date for a coin)

    cg.get_coin_history_by_id()
  • /coins/{id}/market_chart (Get historical market data include price, market cap, and 24h volume (granularity auto))

    cg.get_coin_market_chart_by_id()
  • /coins/{id}/market_chart/range (Get historical market data include price, market cap, and 24h volume within a range of timestamp (granularity auto))

    cg.get_coin_market_chart_range_by_id()
  • /coins/{id}/ohlc (Get coin's OHLC (beta))
    cg.get_coin_ohlc_by_id()
contract

  • /coins/{id}/contract/{contract_address} (Get coin info from contract address)
    cg.get_coin_info_from_contract_address_by_id()
  • /coins/{id}/contract/{contract_address}/market_chart/ (Get historical market data include price, market cap, and 24h volume (granularity auto) from a contract address)
    cg.get_coin_market_chart_from_contract_address_by_id()
  • /coins/{id}/contract/{contract_address}/market_chart/range (Get historical market data include price, market cap, and 24h volume within a range of timestamp (granularity auto) from a contract address)
    cg.get_coin_market_chart_range_from_contract_address_by_id()
asset_platforms

  • /asset_platforms (List all asset platforms (Blockchain networks))
    cg.get_asset_platforms()
categories

  • /coins/categories/list (List all categories)
    cg.get_coins_categories_list()
  • coins/categories (List all categories with market data)
    cg.get_coins_categories()
exchanges

  • /exchanges (List all exchanges)
    cg.get_exchanges_list()
  • /exchanges/list (List all supported markets id and name (no pagination required))
    cg.get_exchanges_id_name_list()
  • /exchanges/{id} (Get exchange volume in BTC and top 100 tickers only)
    cg.get_exchanges_by_id()
  • /exchanges/{id}/tickers (Get exchange tickers (paginated, 100 tickers per page))
    cg.get_exchanges_tickers_by_id()
  • /exchanges/{id}/volume_chart (Get volume_chart data for a given exchange)
    cg.get_exchanges_volume_chart_by_id()
indexes

  • /indexes (List all market indexes)
cg.get_indexes()
  • /indexes/{market_id}/{id} (Get market index by market id and index id)
cg.get_indexes_by_market_id_and_index_id()
  • /indexes/list (List market indexes id and name)
cg.get_indexes_list()
derivatives

  • /derivatives (List all derivative tickers)
    cg.get_derivatives()
  • /derivatives/exchanges (List all derivative exchanges)
    cg.get_derivatives_exchanges()
  • /derivatives/exchanges/{id} (Show derivative exchange data)
    cg.get_derivatives_exchanges_by_id()
  • /derivatives/exchanges/list (List all derivative exchanges name and identifier)
    cg.get_derivatives_exchanges_list()
nfts (beta)

  • /nfts/list (List all supported NFT ids, paginated by 100 items per page, paginated to 100 items)
    cg.get_nfts_list()
  • /nfts/{id} (Get current data (name, price_floor, volume_24h ...) for an NFT collection. native_currency (string) is only a representative of the currency.)
    cg.get_nfts_by_id()
  • /nfts/{asset_platform_id}/contract/{contract_address} (Get current data (name, price_floor, volume_24h ...) for an NFT collection. native_currency (string) is only a representative of the currency)
    cg.get_nfts_collection_by_asset_platform_id_and_contract_address()
exchange_rates

  • /exchange_rates (Get BTC-to-Currency exchange rates)
    cg.get_exchange_rates()
search

  • /search (Search for coins, categories and markets on CoinGecko)
    cg.search()
trending

  • /search/trending (Get trending search coins (Top-7) on CoinGecko in the last 24 hours)
    cg.get_search_trending()
global

  • /global (Get cryptocurrency global data)
    cg.get_global()
  • /global/decentralized_finance_defi (Get cryptocurrency global decentralized finance(defi) data)
    cg.get_global_decentralized_finance_defi()
companies (beta)

  • /companies/public_treasury/{coin_id} (Get public companies data)
    cg.get_companies_public_treasury_by_coin_id()

Test

Installation

Install required packages for testing using:

pip install pytest responses

Usage

Run unit tests with:

# after installing pytest and responses using pip3
pytest tests

License

MIT

pycoingecko's People

Contributors

0xtakamaka avatar emperormew avatar gkrasulya avatar glints avatar hmallen avatar man-c avatar mfiro avatar scrambldchannel avatar tanoabeleyra avatar trevisanj avatar tsifrer avatar yitzikc 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  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

pycoingecko's Issues

How to get top 100 coins by market cap on specific day

Is there a canonical way to get the top 100 coins by market cap on a given day in the past?

The /coins/markets endpoint is close to being able to answer that question but unfortunately it doesn't accept a date parameter.

How to use the "get_coin_market_chart_range_from_contract_address_by_id()" function?

I'm trying to use the function with this code:

cg.get_coin_market_chart_range_from_contract_address_by_id(id = 'ethereum', contract_address = '0x514910771af9ca656af840dff83e8264ecf986ca', vs_currency = 'usd', from_timestamp = 1593650267, to_timestamp = 1593650267)

and it's just giving me this output:

{'prices': [], 'market_caps': [], 'total_volumes': []}

I get this no matter what erc-20 token address I use and no matter what I change the timestamps to. What am I doing wrong here?

API json result format 'data' instead of "data"

Hi,

I'm trying to understand why when I use the wrapper, the results of my call are not looking like supported json.

Example with the result from get_coin_market_chart_by_id call :

cg.get_coin_market_chart_by_id(bitcoin ,'usd', 1, interval = 'daily')

{
'prices':[
[
1628640000000,
45639.51401890709
]
}

when trying to use parser/formatter, it's indicate me that syntax are not json and when I try the same API on coingecko directly I receive the correct format :

{
"prices": [
[
1628640000000,
45639.51401890709
]
}

Is there any reason for such difference ?

Thanks,

Change output format to pandas dataframe

Hi,
thanks for creating this package. In my opinion, it would be more convenient to have the outputs in pandas dataframe format (e.g. similarly as in the yfinance package).
Have you thought about that, is there an argument to stick with the current implementation with dictionary outputs?
If not, I would be happy to contribute to this project and change outputs to pandas dataframes

How to get crypto pair prices (e.g. BTC/ETH)?

If I extract the price of BTC, for example, I can only specify fiat currencies as quote currencies: BTC/[fiat].

Is there an easy way to extract BTC/ETH, ETH/AVAX or any other crypto/crypto pair?

Using cg.get_coin_history_by_id to get older price

I'm using cg.get_coin_history_by_id to get the price of the coin 1 month ago, but whenever I use "market_data" and "current_price" like in CoinGecko API V3 Docs, it gives an error and says KeyError: .

pycoingecko module error

Am i missing a step? getting the error below with the code below

ModuleNotFoundError: No module named 'pycoingecko'

from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()_
import json
import requests
import pandas as pd
from datetime import date

Create a ouput shell for data

today = date.today()
stdate = date(2017,1,1) # Your start date here
tdelta = today - stdate
DT = pd.date_range(stdate,periods=tdelta.days,freq='D')
shell = pd.DataFrame(index=DT)

cg = CoinGeckoAPI()

Help

Hi, I'm new on Python programming and i'm going to use pycoingecko. Using the function "cg.get_coin_market_chart_by_id()" when I insert the parameters I don't known what I have to insert in "self".
Can someone help me?

Unhandled exception in exception handler

Request timeouts are handled incorrectly, and will result in an exception of local variable 'response' referenced before assignment.

As a timeout will cause a requests.Timeout exception on the first line of the "try" block, the subsequent exception handler has response undefined.

A better way would probably be to handle the "timeout" exception seperately - or define response before the try block and check if it's defined in the exception handler.

Relevant code:

try:
response = self.session.get(url, timeout=self.request_timeout)
response.raise_for_status()
content = json.loads(response.content.decode('utf-8'))
return content
except Exception as e:
# check if json (with error message) is returned
try:
content = json.loads(response.content.decode('utf-8'))
raise ValueError(content)
# if no json
except json.decoder.JSONDecodeError:
pass
# except UnboundLocalError as e:
# pass
raise

Unfortunately, reproducing this reliably is quite hard, as timeouts are ... in general not easy to reproduce.

Support for Apple's arm64 architecture (osx-arm64)

Hi, I'm trying to install pycoingecko on a new Apple MacBook with Apple Silicon, but it fails to install via Conda due to no packages matching the architecture.

Would it be possible to add support for this?

[Question] Getting Historical 24 Hour Highest and Lowest Price

Hi, I have a question.

I am looking to find some historical data, I had used cg.get_coin_market_chart_by_id to get price data, however, I also need high_24h and low_24h.

These two data are given by cg.get_coin_market_chart_by_id, but only for the current date.

Is there a way to get historical data for these two variables?

Thank You.

Wrong volume and market cap data for some coins

The response of cg.get_coin_market_chart_by_id(id=ripple,vs_currency=' usd',days='30') differs strongly from the response of https://api.coingecko.com/api/v3/coins/ripple/market_chart?vs_currency=usd&days=30 in terms of market cap and volume. For the pycoingecko response, market cap is zero while volume is much lower compared with the URL output. The symbols where I found this to be the case are:
ADA
APE
AST
BCH
BNX
CAKE
CHESS
CITY
CLV
COMP
DAR
DOGE
DOT
DREP
EOS
EZ
FARM
FIL
GRS
GRT
GTC
HIGH
IOTX
LINA
LOOM
LTC
MC
MDX
OG
ONG
ONT
PERL
PNT
POLY
PORTO
RAD
SAND
SNT
SUPER
TRU
UNI
UST
WAVES
XRP

Pagination

Hi,

I am trying to use get_exchanges_tickers_by_id() to pull all tickers by exchange. I believe this needs to use pagination, by way of page_integer, to get all of the results. However I cannot seem to get multiple pages to return.

The two lines of code below, produce the same results. same tickers just the volume etc that is slightly different

cg.get_exchanges_tickers_by_id('binance', page_integer = 1)
cg.get_exchanges_tickers_by_id('binance', page_integer = 2)

Wrong id Return

co = CoinGeckoAPI()
store =co.get_coins_list()
wrong_id =[(s['id'],i) for i,s in enumerate(store) if "academy token" in s['id']]

wrong_id

output

[('academy token', 203)]

checked data

ALSO tried

import requests
import json
data= requests.get('https://api.coingecko.com/api/v3/coins/list')
data=json.loads(data.content)
data[203]
{'id': 'academy token', 'name': 'Academy Token', 'symbol': 'acad'}

'id': 'academy token', id is wrong
the id should be academy-token (https://www.coingecko.com/en/coins/academy-token)

Let me know if anything is Wrong Thank you

Standardization behind id

Is there anyway to just use the 3 letter/4 letter ticker for when searching for an asset instead of having to type out the whole name? And if the name consists of two words, i.e. wrapped-bitcoin or yearn-finance, is it always mandatory to put a hyphen "-" in between the two words?

No per_page & page on /exchanges

Hi, thanks for doing this, most useful.

The /exchanges endpoint, according to coingecko defaults to 100 records.

Without the option being available to fetch more and request the 2nd page, it becomes limited as can never get a full list.

Can you change this to include these options?

get_exchanges_list(self, per_page=100, page=1) perhaps? Seems to match with the API documentation?

I could do a pull request if that helps - pretty new to programming so there maybe a reason why this isn't included.

Difference number in exchanges__list compared to website

Dear author,

I have just installed your libary. When running exchanges_list = cg.get_exchanges_list() in python it returns a list of 235 exchanges. the website in top left says 264 here: https://www.coingecko.com/api#

when running coins_list = cg.get_coins_list() returns 3648 same as the website
so noticed this discrepancy on exchanges
is this an issue that requries investigating?
please let me know
thanks
tom

ValueError: arrays must all be same length

Dear Authors.
Thank you for great library. I have been using pycoingecko for long time.
I get an error while requesting for historical market data of a cryptocurrency by id, vs_currency and days.

pycoingecko gives ValueError when days > 813, But CoinGecko API V3 works fine.

See attached screenshots for your reference.
Screen Shot 2019-06-24 at 11 04 21
Screen Shot 2019-06-24 at 11 04 46

Twitter Followers and other community data retrning as 'None'

Hi guys, love the wrapper.

I'm getting None back for some coins community data even though there is real data on the website.

Simplest example would be for Polkadot say.

dict = cg.get_coin_history_by_id('polkadot', '08-04-2021')['community_data']

I'm getting None for 'twitter_followers' , but if you check the website https://www.coingecko.com/en/coins/polkadot#social you see there is 275K.

Is there a way to get the actual followers instead of just None?

Cheers

get_coins_list(include_platform=True) is not implemented?

Hello, I can't seem to make
CoinGeckoAPI().get_coins_list(include_platform=True)
function to return platform information, like

{
    "id": "bifi",
    "symbol": "bifi",
    "name": "BiFi",
    "platforms": {
      "ethereum": "0x2791bfd60d232150bff86b39b7146c0eaaa2ba81",
      "fantom": "0xad260f380c9a30b1d60e4548a75010ede630b665"
    }
  }

Currently, platform info is missing. Is my code wrong?

Where to input API key?

I got the Analyst API subscription plan and was wondering where I need to put the api key so I can start using it with this Python library.

Updating Get Requests

Dear author,

Excellent library connecting the API

https://www.coingecko.com/api#
I noticed, there are a few GET requests possibly new on libraray (some beta) if wanted to additionally enhance the library functions?

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

/simple/supported_vs_currencies
Get list of supported_vs_currencies.

HEADER coins

/coins/{id}/status_updates
Get status updates for a given coin (beta)

/coins/{id}/contract/{contract_address}
Get coin info from contract address

HEADER: exchanges (beta)

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

HEADER events

/events
Get events, paginated by 100

/events/countries
Get list of event countries

/events/types
Get list of events types

HEADER exchange_rates

/exchange_rates
Get BTC-to-Currency exchange rates

Recently Added Coins?

I can't find any option in the documentation to get the recently added coins. Is this still to come or is there another way to get this information?

Thanks!

Categories

Hi, there isnt a method for the /coins/categories/list or /coins/categories/

get_coins_markets() no sparkline

cg = pycoingecko.CoinGeckoAPI()

m = cg.get_coins_markets(vs_currency="USD", per_page=1, order="market_cap_desc", page=1, sparkline=True, price_change_percentage="1h,24h,7d,14d,30d,200d,1y")
print(m)

You've got to do it as sparkline='true' otherwise the sparkline does not come

Boolean conversion to a string that CoinGecko can understand would be nice

Price change percentage does not return expected reponse

When tried to get percentage change for various period - didn't get proper response. Here is examples where I'm asking for percentage changes in additional, non-default periods: "1h,24h,7d,14d,30d,200d,1y"

cg = CoinGeckoAPI()
  cg.get_coins_markets(
      vs_currency="usd",
      per_page=2,
      price_change_percentage="1h,24h,7d,14d,30d,200d,1y",
  )

this does return keys:

['id', 'symbol', 'name', 'image', 'current_price', 'market_cap',
       'market_cap_rank', 'fully_diluted_valuation', 'total_volume',
       'high_24h', 'low_24h', 'price_change_24h',
       'price_change_percentage_24h', 'market_cap_change_24h',
       'market_cap_change_percentage_24h', 'circulating_supply',
       'total_supply', 'max_supply', 'ath', 'ath_change_percentage',
       'ath_date', 'atl', 'atl_change_percentage', 'atl_date', 'roi',
       'last_updated']

keys corresponding for the percentage change for other than default 24 are missing.

The unwrapped API returns what was asked, e.g:

(...)
    "price_change_percentage_14d_in_currency": 19.38179106361344,
    "price_change_percentage_1h_in_currency": -0.8845932191952984,
    "price_change_percentage_1y_in_currency": 606.9564598121143,
    "price_change_percentage_200d_in_currency": 381.63660610140784,
    "price_change_percentage_24h_in_currency": 1.6059902278211433,
    "price_change_percentage_30d_in_currency": 20.46641596843917,
    "price_change_percentage_7d_in_currency": 15.13158250698197

xrp unknown by the api

from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()
cg.get_price(ids='xrp', vs_currencies='eur')
{}

Any version beyond 2.2.0 is breaking my application

Hi, not quite sure where the issue is, but i get freezing of my application if i try to use 2.3.0+ but with 2.2.0 my app will not freeze but sometimes returns no values... it seems with 2.3.0 the no values become feezing.. Not quite sure how to troubleshoot. still looking into the cause. just FYI

Improve the methods for pagination

Hi
Thank you for providing this package.
I would like to suggest what I think about pagination while using this package.
It's a little inconvenient to check whether there is a next page or not, because it only returns the response content.
It would be better to return not only the content but also the header of the response.
The response header contains the total number of results, which is very convenient for pagination.
This is only my thought. What do you think?
Regards.

Add rate limit restriction

Would be great to add an option to use rate limiter to avoid ip block for a lot of API requests. Just a thought.

names vs symbols

I can't understand from the API how to get conversions.
do I have to supply the full name of the coin to get it? why is the difference between the ids and the vs?
e.g. what do I need to get cg.get_price(ids="xrp", vs_currencies="eur") ? and is it true cg.get_price(ids="eur", vs_currencies="xrp") is against the APIs logic in some hidden way?

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.