Convert Figma logo to code with AI

man-c logopycoingecko

Python wrapper for the CoinGecko API

1,051
275
1,051
14

Top Related Projects

33,624

A JavaScript / TypeScript / Python / C# / PHP cryptocurrency trading API with support for more than 100 bitcoin/altcoin exchanges

Simple connector to Binance Public API

Binance Exchange API python implementation for automated trading

Quick Overview

PyCoingecko is a Python wrapper for the CoinGecko API v3. It provides a simple and efficient way to interact with CoinGecko's cryptocurrency data API, allowing developers to easily retrieve various information about cryptocurrencies, exchanges, and markets.

Pros

  • Easy to use and well-documented
  • Covers most endpoints of the CoinGecko API
  • Regularly updated to keep up with API changes
  • Supports both synchronous and asynchronous requests

Cons

  • Limited error handling and input validation
  • Lacks advanced features like rate limiting or caching
  • Dependency on the CoinGecko API's availability and rate limits
  • Some less common API endpoints may not be implemented

Code Examples

  1. Getting Bitcoin's current price in USD:
from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()
bitcoin_price = cg.get_price(ids='bitcoin', vs_currencies='usd')
print(f"Bitcoin price: ${bitcoin_price['bitcoin']['usd']}")
  1. Fetching top 10 cryptocurrencies by market cap:
from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()
top_10 = cg.get_coins_markets(vs_currency='usd', order='market_cap_desc', per_page=10, page=1)
for coin in top_10:
    print(f"{coin['name']}: ${coin['current_price']}")
  1. Retrieving historical price data for Ethereum:
from pycoingecko import CoinGeckoAPI
from datetime import datetime, timedelta
cg = CoinGeckoAPI()

end_date = datetime.now()
start_date = end_date - timedelta(days=30)
eth_history = cg.get_coin_market_chart_range_by_id(
    id='ethereum',
    vs_currency='usd',
    from_timestamp=int(start_date.timestamp()),
    to_timestamp=int(end_date.timestamp())
)
print(f"Ethereum prices for the last 30 days: {eth_history['prices']}")

Getting Started

To get started with PyCoingecko, follow these steps:

  1. Install the library using pip:

    pip install pycoingecko
    
  2. Import the CoinGeckoAPI class and create an instance:

    from pycoingecko import CoinGeckoAPI
    cg = CoinGeckoAPI()
    
  3. Start making API calls:

    # Get Bitcoin price in USD
    bitcoin_price = cg.get_price(ids='bitcoin', vs_currencies='usd')
    print(f"Bitcoin price: ${bitcoin_price['bitcoin']['usd']}")
    
    # Get top 10 coins by market cap
    top_10 = cg.get_coins_markets(vs_currency='usd', order='market_cap_desc', per_page=10, page=1)
    for coin in top_10:
        print(f"{coin['name']}: ${coin['current_price']}")
    

That's it! You can now explore the various methods available in the CoinGeckoAPI class to access different endpoints and data from the CoinGecko API.

Competitor Comparisons

33,624

A JavaScript / TypeScript / Python / C# / PHP cryptocurrency trading API with support for more than 100 bitcoin/altcoin exchanges

Pros of ccxt

  • Supports multiple cryptocurrency exchanges (100+)
  • Offers a unified API for trading operations across exchanges
  • Provides extensive documentation and examples

Cons of ccxt

  • Steeper learning curve due to its comprehensive nature
  • Larger codebase, which may impact performance for simple tasks

Code Comparison

pycoingecko

from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()
bitcoin_data = cg.get_coin_by_id(id='bitcoin')

ccxt

import ccxt
exchange = ccxt.binance()
btc_usdt = exchange.fetch_ticker('BTC/USDT')

Key Differences

  • pycoingecko focuses solely on CoinGecko API, while ccxt supports multiple exchanges
  • ccxt provides trading functionality, whereas pycoingecko is primarily for data retrieval
  • pycoingecko has a simpler API for quick access to CoinGecko data
  • ccxt offers more advanced features for trading and order management

Use Cases

  • Choose pycoingecko for quick and easy access to CoinGecko data
  • Opt for ccxt when working with multiple exchanges or requiring trading functionality

Simple connector to Binance Public API

Pros of binance-connector-python

  • Comprehensive API coverage for Binance-specific features
  • Official library maintained by Binance, ensuring up-to-date compatibility
  • Robust error handling and WebSocket support

Cons of binance-connector-python

  • Limited to Binance exchange data only
  • Steeper learning curve due to more complex API structure
  • Requires API key and secret for most operations

Code Comparison

pycoingecko:

from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()
bitcoin_data = cg.get_coin_by_id(id='bitcoin')

binance-connector-python:

from binance.spot import Spot
client = Spot(api_key='your_api_key', api_secret='your_api_secret')
btc_price = client.ticker_price("BTCUSDT")

The pycoingecko library offers a simpler interface for retrieving general cryptocurrency data across multiple exchanges, while binance-connector-python provides more detailed and specific functionality for interacting with the Binance exchange, including trading operations and real-time data streams.

Binance Exchange API python implementation for automated trading

Pros of python-binance

  • Comprehensive API coverage for Binance exchange
  • Real-time websocket support for live data streaming
  • Extensive documentation and examples

Cons of python-binance

  • Limited to Binance exchange only
  • More complex setup and usage compared to pycoingecko
  • Requires API key and secret for most functionalities

Code Comparison

pycoingecko:

from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()
bitcoin_data = cg.get_coin_by_id(id='bitcoin')

python-binance:

from binance.client import Client
client = Client(api_key, api_secret)
bitcoin_price = client.get_symbol_ticker(symbol="BTCUSDT")

Summary

pycoingecko is a simpler, more general-purpose cryptocurrency data retrieval library that doesn't require authentication. It's ideal for quick market data access across multiple exchanges.

python-binance offers deeper integration with Binance, including real-time data and trading capabilities, but is limited to that single exchange and requires API credentials.

Choose pycoingecko for broad market data or python-binance for Binance-specific trading and detailed exchange data.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

CoinGecko API wrapper

PyPi Version GitHub

Python3 wrapper around the CoinGecko API (V3) 🦎
Supports both Public and Pro API:

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 Public API:

  • without any demo api key (x-cg-demo-api-key):
    from pycoingecko import CoinGeckoAPI
    cg = CoinGeckoAPI()
    
  • 🔑 with a demo api key:
    from pycoingecko import CoinGeckoAPI
    cg = CoinGeckoAPI(demo_api_key='YOUR_DEMO_API_KEY')
    

For Pro API:

  • 🔑 with a pro api key:
    from pycoingecko import CoinGeckoAPI
    cg = CoinGeckoAPI(api_key='YOUR_PRO_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

:warning: 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()
    
key

  • [Pro API] 💼 /key

    Monitor your account's API usage, including rate limits, monthly total credits, remaining credits, and more

    cg.key()
    
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()
    
  • [Pro API] 💼 /coins/top_gainers_losers

    Query the top 30 coins with largest price gain and loss by a specific time duration

    cg.get_coin_top_gainers_losers()
    
  • [Pro API] 💼 /coins/list/new

    Query the latest 200 coins that recently listed on CoinGecko

    cg.get_coins_list_new()
    
  • /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 the OHLC chart (Open, High, Low, Close) of a coin based on particular coin id

    cg.get_coin_ohlc_by_id()
    
  • [Pro API] 💼 /coins/{id}/ohlc/range

    Get the OHLC chart (Open, High, Low, Close) of a coin within a range of timestamp based on particular coin id

    cg.get_coin_ohlc_by_id_range()
    
  • [Pro API] 👑 /coins/{id}/circulating_supply_chart

    Query historical circulating supply of a coin by number of days away from now based on provided coin id

    cg.get_coin_circulating_supply_chart()
    
  • [Pro API] 👑 /coins/{id}/circulating_supply_chart/range

    Query historical circulating supply of a coin, within a range of timestamp based on the provided coin id

    cg.get_coin_circulating_supply_chart_range()
    
  • [Pro API] 👑 /coins/{id}/total_supply_chart

    Query historical total supply of a coin by number of days away from now based on provided coin id

    cg.get_coin_total_supply_chart()
    
  • [Pro API] 👑 /coins/{id}/total_supply_chart/range

    Query historical total supply of a coin, within a range of timestamp based on the provided coin id

    cg.get_coin_total_supply_chart_range()
    
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()
    
  • [Pro API] 👑 /token_lists/{asset_platform_id}/all.json

    Get full list of tokens of a blockchain network (asset platform) that is supported by Ethereum token list standard

    cg.get_asset_platform_by_id()
    
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()
    
  • [Pro API] 💼 /exchanges/{id}/volume_chart/range

    Query the historical volume chart data in BTC by specifying date range in UNIX based on exchange’s id

    cg.get_exchanges_volume_chart_by_id_within_time_range()
    
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()
    
  • [Pro API] 💼 /nfts/markets

    Query all the supported NFT collections with floor price, market cap, volume and market related data on CoinGecko

    cg.get_nfts_markets()
    
  • [Pro API] 💼 /nfts/{id}/market_chart

    Query historical market data of a NFT collection, including floor price, market cap, and 24h volume, by number of days away from now

    cg.get_nfts_market_chart_by_id()
    
  • [Pro API] 💼 /nfts/{asset_platform_id}/contract/{contract_address}/market_chart

    Query historical market data of a NFT collection, including floor price, market cap, and 24h volume, by number of days away from now based on the provided contract address

    cg.get_ntfs_market_chart_by_asset_platform_id_and_contract_address()
    
  • [Pro API] 💼 /nfts/{id}/tickers

    Query the latest floor price and 24h volume of a NFT collection, on each NFT marketplace, e.g. OpenSea and LooksRare

    cg.get_nfts_tickers_by_id()
    
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()
    
  • [Pro API] 💼 /global/market_cap_chart

    Query historical global market cap and volume data by number of days away from now)

    cg.get_global_market_cap_chart()
    
companies (beta)

  • /companies/public_treasury/{coin_id}

    Query public companies’ bitcoin or ethereum holdings

    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