CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-coinmarketcap

Python wrapper around the coinmarketcap.com API.

Pending
Overview
Eval results
Files

CoinMarketCap

Python wrapper around the coinmarketcap.com API (Version 2), enabling developers to easily retrieve cryptocurrency market data including listings, ticker information, and global market statistics. The library features built-in caching (120-second cache), support for multiple fiat and cryptocurrency conversions, and a clean object-oriented interface through the Market class.

Package Information

  • Package Name: coinmarketcap
  • Package Type: pypi
  • Language: Python
  • Installation: pip install coinmarketcap

Core Imports

from coinmarketcap import Market

Basic Usage

from coinmarketcap import Market

# Initialize the market client with default settings
coinmarketcap = Market()

# Get all active cryptocurrency listings
listings = coinmarketcap.listings()
print(f"Found {len(listings['data'])} cryptocurrencies")

# Get top 10 cryptocurrencies by rank
top_10 = coinmarketcap.ticker(limit=10)
for crypto_id, data in top_10['data'].items():
    print(f"{data['name']} ({data['symbol']}) - Rank: {data['rank']}")

# Get specific cryptocurrency by ID (Bitcoin = 1)
bitcoin = coinmarketcap.ticker(1)
btc_price = bitcoin['data']['quotes']['USD']['price']
print(f"Bitcoin price: ${btc_price}")

# Get global market statistics
stats = coinmarketcap.stats()
total_market_cap = stats['data']['quotes']['USD']['total_market_cap']
print(f"Total market cap: ${total_market_cap:,.0f}")

Architecture

The package uses a caching strategy with SQLite backend through requests_cache to optimize API usage:

  • 120-second cache expiry: All API responses are cached for 2 minutes
  • Automatic cache management: Cache files stored in temp directory by default
  • Session reuse: Single HTTP session with proper headers for all requests
  • Error handling: Graceful exception handling for network and parsing errors

Capabilities

Market Client

The main interface for accessing CoinMarketCap API endpoints with built-in request caching and error handling.

class Market:
    def __init__(
        self,
        base_url: str = "https://api.coinmarketcap.com/v2/",
        request_timeout: int = 30,
        tempdir_cache: bool = True
    ):
        """
        Initialize Market client with API configuration.
        
        Parameters:
        - base_url (str): CoinMarketCap API base URL (default: v2 API)
        - request_timeout (int): HTTP request timeout in seconds (default: 30)
        - tempdir_cache (bool): Use system temp directory for cache (default: True)
        """

Cryptocurrency Listings

Retrieve all active cryptocurrency listings with basic information for further querying.

def listings(self) -> dict:
    """
    Get all active cryptocurrency listings.
    
    Returns:
    dict: Response containing list of cryptocurrencies with id, name, symbol, website_slug
    Exception: Returns Exception object on network or parsing errors
    
    Note: Response includes 'cached' field indicating if data came from cache
    """

Ticker Data

Retrieve cryptocurrency ticker data with pagination, sorting, and currency conversion options.

def ticker(self, currency: str = "", **kwargs) -> dict:
    """
    Get cryptocurrency ticker data with optional filtering and conversion.
    
    Parameters:
    - currency (str): Specific cryptocurrency ID to query (empty for all)
    - start (int): Return results from rank [start] and above (default: 1)
    - limit (int): Maximum results to return (default: 100, max: 100)
    - convert (str): Currency conversion code
        Fiat: AUD, BRL, CAD, CHF, CLP, CNY, CZK, DKK, EUR, GBP, HKD, HUF, 
              IDR, ILS, INR, JPY, KRW, MXN, MYR, NOK, NZD, PHP, PKR, PLN, 
              RUB, SEK, SGD, THB, TRY, TWD, ZAR
        Crypto: BTC, ETH, XRP, LTC, BCH
    - sort (str): Sort order - "id", "rank", "volume_24h", "percent_change_24h" (default: rank)
        Note: "id" is recommended for pagination as it provides consistent ordering
    - structure (str): Response structure format - "dictionary" or "array" (default: dictionary)
    
    Returns:
    dict: Response containing ticker data with pricing, market cap, volume info
    Exception: Returns Exception object on network or parsing errors
    
    Note: Response includes 'cached' field indicating if data came from cache
    """

Global Market Statistics

Retrieve global cryptocurrency market data and statistics.

def stats(self, **kwargs) -> dict:
    """
    Get global cryptocurrency market statistics.
    
    Parameters:
    - convert (str): Currency conversion code (same options as ticker method)
    
    Returns:
    dict: Response containing global market data with total market cap, volume, 
          active cryptocurrencies count, Bitcoin dominance
    Exception: Returns Exception object on network or parsing errors
    
    Note: Response includes 'cached' field indicating if data came from cache
    """

Usage Examples

Currency Conversion

# Get Bitcoin price in EUR
bitcoin_eur = coinmarketcap.ticker(1, convert='EUR')
eur_price = bitcoin_eur['data']['quotes']['EUR']['price']
print(f"Bitcoin price: €{eur_price:.2f}")

# Get global stats in multiple currencies
global_btc = coinmarketcap.stats(convert='BTC')
btc_market_cap = global_btc['data']['quotes']['BTC']['total_market_cap']
print(f"Total market cap: {btc_market_cap:.2f} BTC")

Pagination and Sorting

# Get cryptocurrencies ranked 11-20, sorted by 24h volume
page_2 = coinmarketcap.ticker(start=11, limit=10, sort='volume_24h')

# Get top 5 by 24h percentage change
top_gainers = coinmarketcap.ticker(limit=5, sort='percent_change_24h')

# Get data in array format instead of dictionary
array_data = coinmarketcap.ticker(limit=10, structure='array')

# Use ID sorting for consistent pagination (recommended)
consistent_page = coinmarketcap.ticker(start=1, limit=10, sort='id')

Error Handling

# The API methods can return Exception objects on error
try:
    data = coinmarketcap.ticker(99999)  # Invalid ID
    if isinstance(data, Exception):
        print(f"API error: {data}")
    else:
        print("Success:", data)
except Exception as e:
    print(f"Network error: {e}")

# Alternative: Check for successful response structure
response = coinmarketcap.listings()
if not isinstance(response, Exception) and 'data' in response:
    print(f"Found {len(response['data'])} cryptocurrencies")
else:
    print("API call failed")

Install with Tessl CLI

npx tessl i tessl/pypi-coinmarketcap
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/coinmarketcap@5.0.x
Publish Source
CLI
Badge
tessl/pypi-coinmarketcap badge