CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pycoingecko

Python3 wrapper around the CoinGecko API (V3) enabling access to cryptocurrency market data, prices, exchanges, and NFT information.

Pending
Overview
Eval results
Files

system-utils.mddocs/

System & Utilities

API status monitoring, account information, and utility functions for data processing. This module provides system-level functionality for API health checks, account management, and data preprocessing utilities.

Capabilities

API Status Monitoring

Check the health and availability of the CoinGecko API servers.

def ping(**kwargs):
    """
    Check API server status and connectivity.
    
    Returns:
    dict: Server status response with greeting message
    """

Usage Example:

# Check if API is responding
try:
    status = cg.ping()
    print(status)  # {'gecko_says': '(V3) To the Moon!'}
    print("API is healthy and responding")
except Exception as e:
    print(f"API is down or unreachable: {e}")

Response Format:

{
    "gecko_says": "(V3) To the Moon!"
}

Account Management (Pro API)

Monitor API usage, rate limits, and account information for Pro API users.

def key(**kwargs):
    """
    Monitor your account's API usage including rate limits, monthly credits, and remaining credits.
    
    Note: This endpoint is only available for Pro API users with valid API keys.
    
    Returns:
    dict: Account usage statistics, rate limits, and billing information
    """

Usage Example:

# Initialize with Pro API key
cg_pro = CoinGeckoAPI(api_key='YOUR_PRO_API_KEY')

# Check account usage
try:
    account_info = cg_pro.key()
    print(f"Monthly credits used: {account_info['monthly_call_credit']}")
    print(f"Remaining credits: {account_info['remaining_monthly_call_credit']}")
    print(f"Rate limit: {account_info['current_total_monthly_calls']}")
except ValueError as e:
    print(f"Pro API key required or invalid: {e}")

Account Info Response Format:

{
    "monthly_call_credit": 10000,
    "current_total_monthly_calls": 2847,
    "remaining_monthly_call_credit": 7153,
    "rate_limit_request_per_minute": 500,
    "rate_limit_request_per_second": 50,
    "plan": "Analyst",
    "is_active": True
}

Utility Functions

Data preprocessing utilities that handle parameter conversion for API calls.

Function Argument Preprocessing

Decorator that automatically preprocesses function arguments for API compatibility.

def func_args_preprocessing(func):
    """
    Decorator that converts list input arguments to comma-separated strings and handles boolean conversion.
    
    Parameters:
    - func: Function to wrap with preprocessing
    
    Returns:
    function: Wrapped function with automatic argument preprocessing
    """

Usage Example:

from pycoingecko.utils import func_args_preprocessing

@func_args_preprocessing
def custom_api_call(ids, vs_currencies, include_market_cap=False):
    # Lists and booleans are automatically preprocessed
    # ids=['bitcoin', 'ethereum'] becomes 'bitcoin,ethereum'
    # include_market_cap=True becomes 'true'
    pass

Individual Argument Preprocessing

Process individual arguments for API compatibility.

def arg_preprocessing(arg_v):
    """
    Return the values of an argument after preprocessing for API compatibility.
    
    Parameters:
    - arg_v: Argument value to preprocess (list, bool, or other type)
    
    Returns:
    str or original type: Preprocessed argument value
    """

Usage Examples:

from pycoingecko.utils import arg_preprocessing

# Convert list to comma-separated string
coin_list = ['bitcoin', 'ethereum', 'litecoin']
processed = arg_preprocessing(coin_list)
print(processed)  # 'bitcoin,ethereum,litecoin'

# Convert boolean to lowercase string
include_cap = True
processed = arg_preprocessing(include_cap)
print(processed)  # 'true'

# Other types pass through unchanged  
number = 42
processed = arg_preprocessing(number)
print(processed)  # 42

Comma-Separated Value Creation

Convert values to comma-separated strings for API parameters.

def get_comma_separated_values(values):
    """
    Return the values as a comma-separated string.
    
    Parameters:
    - values: Single value, list, or tuple to convert
    
    Returns:
    str: Comma-separated string representation
    """

Usage Examples:

from pycoingecko.utils import get_comma_separated_values

# Convert list to comma-separated string
coins = ['bitcoin', 'ethereum', 'cardano']
csv_string = get_comma_separated_values(coins)
print(csv_string)  # 'bitcoin,ethereum,cardano'

# Convert tuple
currencies = ('usd', 'eur', 'gbp')
csv_string = get_comma_separated_values(currencies)
print(csv_string)  # 'usd,eur,gbp'

# Single value becomes single-item string
single = 'bitcoin'
csv_string = get_comma_separated_values(single)
print(csv_string)  # 'bitcoin'

Error Handling and Diagnostics

API Error Responses

The API returns structured error information that can help with debugging:

try:
    # Invalid API call
    result = cg.get_price(ids='invalid_coin', vs_currencies='usd')
except ValueError as e:
    print(f"API Error: {e}")
    # May contain JSON error details from CoinGecko
except requests.exceptions.HTTPError as e:
    print(f"HTTP Error: {e}")
    # HTTP status codes like 404, 429 (rate limit), 500
except requests.exceptions.RequestException as e:
    print(f"Network Error: {e}")
    # Connection timeouts, DNS resolution, etc.

Rate Limit Handling

CoinGecko enforces rate limits that vary by API tier:

  • Public API: 10-50 calls/minute (varies by endpoint)
  • Demo API: Enhanced rate limits with demo key
  • Pro API: 500+ calls/minute with professional key
import time

def safe_api_call(func, *args, **kwargs):
    """Example of rate limit aware API calling."""
    max_retries = 3
    for attempt in range(max_retries):
        try:
            return func(*args, **kwargs)
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 429:  # Rate limit exceeded
                wait_time = 2 ** attempt  # Exponential backoff
                print(f"Rate limited, waiting {wait_time} seconds...")
                time.sleep(wait_time)
            else:
                raise
        except Exception as e:
            if attempt == max_retries - 1:
                raise
            time.sleep(1)
    
    raise Exception("Max retries exceeded")

# Usage
result = safe_api_call(cg.get_price, ids='bitcoin', vs_currencies='usd')

Connection Configuration

The CoinGeckoAPI class provides configuration options for robust API interaction:

# Initialize with custom retry configuration
cg = CoinGeckoAPI(retries=10)  # Increase retry attempts

# The client automatically handles:
# - Connection pooling and keep-alive
# - Automatic retries on 502, 503, 504 errors
# - 120-second request timeout
# - Exponential backoff between retries

API Endpoint Selection

The client automatically selects the appropriate endpoint based on provided keys:

# Public API (free tier)
cg_free = CoinGeckoAPI()
# Uses: https://api.coingecko.com/api/v3/

# Demo API (enhanced free tier)
cg_demo = CoinGeckoAPI(demo_api_key='demo_key')
# Uses: https://api.coingecko.com/api/v3/ with demo key header

# Pro API (paid tier)
cg_pro = CoinGeckoAPI(api_key='pro_key')
# Uses: https://pro-api.coingecko.com/api/v3/

Health Check Best Practices

API Availability Monitoring

def check_api_health():
    """Check if CoinGecko API is available and responding."""
    try:
        cg = CoinGeckoAPI()
        response = cg.ping()
        
        if 'gecko_says' in response:
            return {
                'status': 'healthy',
                'message': response['gecko_says'],
                'timestamp': time.time()
            }
        else:
            return {
                'status': 'unhealthy', 
                'message': 'Unexpected response format',
                'timestamp': time.time()
            }
            
    except Exception as e:
        return {
            'status': 'error',
            'message': str(e),
            'timestamp': time.time()
        }

# Periodic health checks
health_status = check_api_health()
print(f"API Status: {health_status['status']}")

Performance Monitoring

import time

def timed_api_call(func, *args, **kwargs):
    """Measure API call performance."""
    start_time = time.time()
    try:
        result = func(*args, **kwargs)
        end_time = time.time()
        return {
            'success': True,
            'result': result,
            'duration': end_time - start_time,
            'timestamp': start_time
        }
    except Exception as e:
        end_time = time.time() 
        return {
            'success': False,
            'error': str(e),
            'duration': end_time - start_time,
            'timestamp': start_time
        }

# Monitor API performance
perf = timed_api_call(cg.get_price, ids='bitcoin', vs_currencies='usd')
print(f"API call took {perf['duration']:.2f} seconds")

This system and utilities module provides the foundation for robust, production-ready applications using pycoingecko.

Install with Tessl CLI

npx tessl i tessl/pypi-pycoingecko

docs

coins.md

exchanges.md

global.md

index.md

nfts.md

price-market.md

search.md

system-utils.md

tile.json