Skip to content

Instantly share code, notes, and snippets.

@SrNightmare09
Last active April 1, 2024 16:27
Show Gist options
  • Save SrNightmare09/c0492a8852eb172ebea6c93837837998 to your computer and use it in GitHub Desktop.
Save SrNightmare09/c0492a8852eb172ebea6c93837837998 to your computer and use it in GitHub Desktop.
Using the CoinMarketCap API: A Beginner's Guide

Using the CoinMarketCap API: A Beginner's Guide

CoinMarketCap is the world's most-referenced price-tracking website for crypto assets in the rapidly growing cryptocurrency space. Its mission is to make crypto discoverable and efficient globally by empowering retail users with unbiased, high quality and accurate information

In this guide, we will break down the process of leveraging the CoinMarketCap API to seamlessly integrate real-time crptocurrency data in your applications or projects.

While the examples in this blog primarily utilize Python code, it's important to note that the API can be utilized with various programming languages. To explore further, click here.


Getting Started

This section covers the basics of using the CoinMarketCap API to retrieve cryptocurrency data

1. Signing Up to CoinMarketCap

Our first step will be to make an account on CoinMarketCap.

2. Getting your API Key

After creating your account, you will be redirected to your dashboard. If that does not happen, follow this link. From the dashboard, copy your API key and paste it in a local .txt file.

3. Retrieving Crypto Data

Let us write the code that retrieves cryptocurrency data in JSON format. Simply copy and paste the following code into your preferred development environment.

Note: Replace YOUR_API_KEY with the API key you pasted in the .txt file.

View Code
from requests import Session
import json
import pprint

def getInfo (): # Function to get the info

    url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest' # Coinmarketcap API url

    api = 'YOUR_API_KEY' # Replace this with your API key

    parameters = { 'slug': 'bitcoin', 'convert': 'USD' } # API parameters to pass in for retrieving specific cryptocurrency data

    headers = {
        'Accepts': 'application/json',
        'X-CMC_PRO_API_KEY': api
    } # Headers for the API request

    session = Session() # Create new session object to manage API requests
    session.headers.update(headers) #Update the session headers with the specified headers

    response = session.get(url, params=parameters) # Receiving the response from the API

    info = json.loads(response.text)

    pprint.pprint(info) # Displaying JSON data in a visually pleasing format on the terminal for improved readability

getInfo() # Calling the function to get the data

4. Running the Code

Running this code will produce results such as the following:

View Result
{'data': {'1': {'circulating_supply': 19405368,
                'cmc_rank': 1,
                'date_added': '2010-07-13T00:00:00.000Z',
                'id': 1,
                'infinite_supply': False,
                'is_active': 1,
                'is_fiat': 0,
                'last_updated': '2023-06-18T09:00:00.000Z',
                'max_supply': 21000000,
                'name': 'Bitcoin',
                'num_market_pairs': 10247,
                'platform': None,
                'quote': {'USD': {'fully_diluted_market_cap': 556544808013.3,
                                  'last_updated': '2023-06-18T09:00:00.000Z',
                                  'market_cap': 514283657523.2155,
                                  'market_cap_dominance': 48.0966,
                                  'percent_change_1h': -0.29553396,
                                  'percent_change_24h': -0.30944941,
                                  'percent_change_30d': -1.46162201,
                                  'percent_change_60d': -9.16801758,
                                  'percent_change_7d': 2.92720074,
                                  'percent_change_90d': -6.68909286,
                                  'price': 26502.13371491927,
                                  'tvl': None,
                                  'volume_24h': 9276792871.439861,
                                  'volume_change_24h': -47.1715}},
                'self_reported_circulating_supply': None,
                'self_reported_market_cap': None,
                'slug': 'bitcoin',
                'symbol': 'BTC',
                'tags': ['mineable',
                         'pow',
                         'sha-256',
                         'store-of-value',
                         'state-channel',
                         'coinbase-ventures-portfolio',
                         'three-arrows-capital-portfolio',
                         'polychain-capital-portfolio',
                         'binance-labs-portfolio',
                         'blockchain-capital-portfolio',
                         'boostvc-portfolio',
                         'cms-holdings-portfolio',
                         'dcg-portfolio',
                         'dragonfly-capital-portfolio',
                         'electric-capital-portfolio',
                         'fabric-ventures-portfolio',
                         'framework-ventures-portfolio',
                         'galaxy-digital-portfolio',
                         'huobi-capital-portfolio',
                         'alameda-research-portfolio',
                         'a16z-portfolio',
                         '1confirmation-portfolio',
                         'winklevoss-capital-portfolio',
                         'usv-portfolio',
                         'placeholder-ventures-portfolio',
                         'pantera-capital-portfolio',
                         'multicoin-capital-portfolio',
                         'paradigm-portfolio',
                         'bitcoin-ecosystem'],
                'total_supply': 19405368,
                'tvl_ratio': None}},
 'status': {'credit_count': 1,
            'elapsed': 35,
            'error_code': 0,
            'error_message': None,
            'notice': None,
            'timestamp': '2023-06-18T09:02:13.424Z'}}

Congratulations! If you've found the information you need on using the CoinMarketCap API for cryptocurrency data, you can stop here. But if you want to improve your code for more specific results, keep reading.


Working with the data

You have the flexibility to narrow down the received data and obtain more specific information, such as the price, market cap, and more.

To narrow down the data, it's a straightforward process of adding the corresponding parent elements before each desired data type. For instance, if you want to retrieve the price of Bitcoin, you can achieve that by modifying the following line of code.

# info = json.loads(response.text)
info = json.loads(response.text)['data']['1']['quote']['USD']['price'] # Get only the price of BTC
# OUTPUT : 26510.569334993506

Similarly, to retrieve only the symbol of Bitcoin, the line of code will be modified as follows.

# info = json.loads(response.text)
# info = json.loads(response.text)['data']['1']['quote']['USD']['price']
info = json.loads(response.text)['data']['1']['symbol']
# OUTPUT : 'BTC'

Changing Currency

Say we're interested in obtaining the price of Ethereum in Indian Rupee, you can achieve this by adjusting the parameters within the code.

# parameters = { 'slug': 'bitcoin', 'convert': 'USD' }
parameters = { 'slug': 'ethereum', 'convert': 'INR' }
# OUTPUT : 141925.7369671622
Note: Ensure that you update relevant information, such as the ID within the info variable, as you retrieve data for different cryptocurrencies. To locate the ID of a specific cryptocurrency, print its raw data and locate the corresponding ID within the JSON structure.

Conclusion

Congratulations! You have reached the end of this beginner's guide on using the CoinMarketCap API to retrieve cryptocurrency data. We have covered the basics of leveraging the API, from signing up to obtaining your API key and retrieving crypto data in JSON format. If you wish to research the API further, make sure to read the CoinMarketCap Documentation. By following the provided examples and code snippets, you can effortlessly incorporate live cryptocurrency data into your applications or projects. Happy Coding!

@Cralins
Copy link

Cralins commented Dec 19, 2022

``Thank your code and explanation which i kooking for. Coinmarketcap didnt define so well the argument.

İ made some changes and get AI help to fix my usage. i didnt fulu know github as newbie Can you add this part who ever need.

i am try get historical BTC Closing price data from 2017 to 2023 for data anlysis

Thnks

import configparser
import json
import pytz
from datetime import datetime
from requests import Request, Session
from dateutil import parser

def get_info():
    # Read the API key from the coinmarket.ini file
    config = configparser.ConfigParser()
    config.read('coinmarket.ini')
    api_key = config['DEFAULT']['API_KEY']

    # Set up the request parameters and headers
    url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest'
    parameters = { 'slug': 'bitcoin', 'convert': 'USD' }
    headers = {
        'Accepts': 'application/json',
        'X-CMC_PRO_API_KEY': api_key
    }

    # Send the request and retrieve the response
    session = Session()
    session.headers.update(headers)
    response = session.get(url, params=parameters)
    info = json.loads(response.text)

    # Extract the desired information from the response
    data = info['data']['1']
    name = data['name']
    symbol = data['symbol']
    rank = data['cmc_rank']
    total_supply = data['total_supply']
    circulating_supply = data['circulating_supply']
    market_cap = data['quote']['USD']['market_cap']
    price = data['quote']['USD']['price']
    market_cap_dominance = data['quote']['USD']['market_cap_dominance']
    percent_change_1h = data['quote']['USD']['percent_change_1h']
    percent_change_24h = data['quote']['USD']['percent_change_24h']
    volume_24h = data['quote']['USD']['volume_24h']
    volume_change_24h = data['quote']['USD']['volume_change_24h']
    timestamp = info['status']['timestamp']

    # Convert the timestamp to a timezone-aware datetime object
    timestamp_local = parser.parse(timestamp).astimezone(pytz.timezone('Turkey'))
    

    # Format the timestamp as desired
    formatted_timestamp = timestamp_local.strftime('%Y-%m-%d %H:%M:%S')

    # Print the information
    print(f'Name: {name}, Symbol: {symbol}, Price: {price:,.2f}, Percent change (1h): {percent_change_1h}, Percent change (24h): {percent_change_24h}, Total supply: {total_supply}, Circulating supply: {circulating_supply}, Market capitalization: {market_cap}, Market capitalization dominance: {market_cap_dominance}, Volume (24h): {volume_24h}, Volume change (24h): {volume_change_24h}, Timestamp: {formatted_timestamp}')

get_info()

@SrNightmare09
Copy link
Author

@Cralins I have updated the gist again to make it more concise! Please consider rerunning the code to see view any further problems! If you have any suggestions/feedback please do comment!

@Rahul-Prasad-07
Copy link

hey can you help me with converting crypto price in other currency in express-node.js server

@CoCo-27
Copy link

CoCo-27 commented Mar 12, 2024

How can I get hot-pair information from CMC using its API & free API key?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment