### Synchronous Client Example Usage Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/01-client-initialization.md Demonstrates initializing the synchronous client with environment variables, setting timeout and retries, making an API call to get Bitcoin price, and closing the client. Ensure to close the client when done to release resources. ```python import os from coingecko_sdk import Coingecko # Initialize with Pro API client = Coingecko( pro_api_key=os.environ.get("COINGECKO_PRO_API_KEY"), environment="pro", timeout=30.0, max_retries=3, ) # Make API calls price_data = client.simple.price.get( vs_currencies="usd", ids="bitcoin", ) print(price_data['bitcoin'].usd) # Close the client when done client.close() ``` -------------------------------- ### Install from Local Wheel File Source: https://github.com/coingecko/coingecko-python/blob/main/CONTRIBUTING.md Install the package efficiently after building it from source by providing the path to the generated wheel file. ```sh $ pip install ./path-to-wheel-file.whl ``` -------------------------------- ### Install Coingecko Python SDK Source: https://github.com/coingecko/coingecko-python/blob/main/README.md Install the library using pip. ```sh pip install coingecko_sdk ``` -------------------------------- ### Install CoinGecko Python SDK Source: https://github.com/coingecko/coingecko-python/blob/main/README.md Install the SDK using pip. Include `[aiohttp]` for asynchronous HTTP client support. ```bash pip install "coingecko_sdk[aiohttp]" ``` -------------------------------- ### Add and Run a New Example Source: https://github.com/coingecko/coingecko-python/blob/main/CONTRIBUTING.md Add new example files to the 'examples/' directory. Make them executable and then run them against your API. The shebang line ensures they are run with 'rye run python'. ```python # add an example to examples/.py #!/usr/bin/env -S rye run python … ``` ```sh $ chmod +x examples/.py # run the example against your api $ ./examples/.py ``` -------------------------------- ### Installation Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/README.md Install the CoinGecko Python SDK using pip. ```APIDOC ## Installation ```bash pip install coingecko_sdk ``` ``` -------------------------------- ### Install from Git Source: https://github.com/coingecko/coingecko-python/blob/main/CONTRIBUTING.md Install the coingecko-python package directly from its GitHub repository using pip. ```sh $ pip install git+ssh://git@github.com/coingecko/coingecko-python.git ``` -------------------------------- ### Install aiohttp for Async Client Source: https://github.com/coingecko/coingecko-python/blob/main/README.md Install aiohttp to use it as the HTTP backend for the asynchronous Coingecko client, which can improve concurrency performance. ```sh pip install aiohttp ``` -------------------------------- ### Async Get Cryptocurrency Prices Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/02-simple-api.md Perform asynchronous queries for cryptocurrency prices using `AsyncCoingecko`. This example fetches prices for Bitcoin and Ethereum and prints the Bitcoin price. ```python import asyncio from coingecko_sdk import AsyncCoingecko async def main(): client = AsyncCoingecko() price_data = await client.simple.price.get( vs_currencies="usd", ids="bitcoin,ethereum", ) print(price_data['bitcoin'].usd) await client.close() asyncio.run(main()) ``` -------------------------------- ### Get Prices with Additional Data Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/02-simple-api.md Retrieve cryptocurrency prices along with market cap, 24-hour volume, and 24-hour price change. This example demonstrates how to include extra market data for Bitcoin. ```python client.simple.price.get( vs_currencies="usd,eur", ids="bitcoin", include_market_cap=True, include_24hr_vol=True, include_24hr_change=True, ) ``` -------------------------------- ### Get Bitcoin Price and Supported Currencies (Async) Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/02-simple-api.md Demonstrates fetching Bitcoin's price in USD and EUR, including market cap and 24-hour change, and listing supported currencies using the asynchronous client. Ensure the `coingecko-sdk` is installed and an asyncio event loop is running. ```python import asyncio from coingecko_sdk import AsyncCoingecko async def main(): client = AsyncCoingecko() # Get Bitcoin price price = await client.simple.price.get( vs_currencies="usd,eur", ids="bitcoin", include_market_cap=True, include_24hr_change=True, ) print(f"BTC: ${price['bitcoin'].usd}") print(f"BTC Market Cap: ${price['bitcoin'].usd_market_cap}") # Get supported currencies currencies = await client.simple.supported_vs_currencies.get() print(f"Supported currencies: {len(currencies)}") await client.close() asyncio.run(main()) ``` -------------------------------- ### Get Cryptocurrency Prices Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/02-simple-api.md Query the prices of one or more cryptocurrencies using their IDs. This example shows a basic query for Bitcoin and Ethereum prices in USD. ```python client.simple.price.get( vs_currencies="usd", ids="bitcoin,ethereum", ) ``` -------------------------------- ### Get Paginated Market Data Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/03-coins-api.md Retrieve paginated market data for multiple cryptocurrencies. This example shows how to fetch the top 50 cryptocurrencies by market cap and iterate through the results. ```python from coingecko_sdk import Coingecko client = Coingecko() # Get top 50 cryptocurrencies by market cap markets = client.coins.markets.get( vs_currency="usd", order="market_cap_desc", per_page=50, page=1, ) for coin in markets: print(f"{coin.market_cap_rank}. {coin.name} - ${coin.current_price}") ``` -------------------------------- ### Get Prices with Precision Control Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/02-simple-api.md Specify the desired decimal precision for price values. This example requests Bitcoin prices with two decimal places. ```python client.simple.price.get( vs_currencies="usd", ids="bitcoin", precision="2", # 2 decimal places ) ``` -------------------------------- ### Basic Usage with Async Client Source: https://github.com/coingecko/coingecko-python/blob/main/README.md Demonstrates how to install the SDK with aiohttp support and use the AsyncCoingecko client to fetch Bitcoin prices. ```APIDOC ## Install from PyPI pip install "coingecko_sdk[aiohttp]" ## Basic Usage with Async Client ```python import os import asyncio from coingecko_sdk import DefaultAioHttpClient from coingecko_sdk import AsyncCoingecko async def main() -> None: async with AsyncCoingecko( pro_api_key=os.environ.get("COINGECKO_PRO_API_KEY"), http_client=DefaultAioHttpClient(), ) as client: price = await client.simple.price.get( vs_currencies="usd", ids="bitcoin", ) print(price["bitcoin"].usd) asyncio.run(main()) ``` ``` -------------------------------- ### Install Development Dependencies with Pip Source: https://github.com/coingecko/coingecko-python/blob/main/CONTRIBUTING.md If not using Rye, install development dependencies using pip by referencing the lock file. Ensure your Python version matches the one specified in .python-version. ```sh $ pip install -r requirements-dev.lock ``` -------------------------------- ### Sync Dependencies with Rye Source: https://github.com/coingecko/coingecko-python/blob/main/CONTRIBUTING.md After installing Rye manually, use this command to sync all dependencies and features for the project. ```sh $ rye sync --all-features ``` -------------------------------- ### Get Entities List Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieves a list of entities. Ensure the 'coingecko_sdk' library is imported. ```python from coingecko_sdk.types import EntityGetListResponse ``` ```python client.entities.get_list(**params) -> EntityGetListResponse ``` -------------------------------- ### Get Detailed Data for a Specific Exchange Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/04-additional-apis.md Retrieves comprehensive data for a single cryptocurrency exchange by its ID. The ID is a string, for example, 'binance' or 'coinbase'. ```python exchange = client.exchanges.get_id("binance") ``` -------------------------------- ### Initialize Coingecko Client with Demo API Key Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/08-configuration.md Initialize the Coingecko client for the demo environment, using the COINGECKO_DEMO_API_KEY from environment variables. ```python import os from coingecko_sdk import Coingecko client = Coingecko( demo_api_key=os.environ.get("COINGECKO_DEMO_API_KEY"), environment="demo", ) ``` -------------------------------- ### Initialize Client and Fetch Bitcoin Price Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/09-common-patterns.md Demonstrates how to create a CoinGecko client instance and fetch the price of Bitcoin in USD, EUR, and GBP. ```python from coingecko_sdk import Coingecko # Create client client = Coingecko() # Get Bitcoin price in multiple currencies prices = client.simple.price.get( vs_currencies="usd,eur,gbp", ids="bitcoin", ) # Access prices btc = prices['bitcoin'] print(f"BTC/USD: ${btc.usd}") print(f"BTC/EUR: €{btc.eur}") print(f"BTC/GBP: £{btc.gbp}") ``` -------------------------------- ### Initialize and Use Async Client Source: https://github.com/coingecko/coingecko-python/blob/main/README.md Instantiate the asynchronous client with `DefaultAioHttpClient` and retrieve Bitcoin price. Ensure the `COINGECKO_PRO_API_KEY` environment variable is set. ```python import os import asyncio from coingecko_sdk import DefaultAioHttpClient from coingecko_sdk import AsyncCoingecko async def main() -> None: async with AsyncCoingecko( pro_api_key=os.environ.get("COINGECKO_PRO_API_KEY"), http_client=DefaultAioHttpClient(), ) as client: price = await client.simple.price.get( vs_currencies="usd", ids="bitcoin", ) print(price["bitcoin"].usd) asyncio.run(main()) ``` -------------------------------- ### Programmatic Logging Setup Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/07-advanced-usage.md Enable SDK logging programmatically using the `setup_logging` utility. Further configure your application's logging behavior with Python's standard `logging` module. ```python import logging from coingecko_sdk._utils._logs import setup_logging # Enable logging at module level setup_logging() # Configure logging for your app logging.basicConfig(level=logging.DEBUG) ``` -------------------------------- ### DefaultHttpxClient Initialization Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/01-client-initialization.md Demonstrates how to initialize the CoinGecko SDK with the default synchronous HTTP client using httpx, including proxy and transport customization. ```APIDOC ## DefaultHttpxClient ### Description Default synchronous HTTP client using `httpx`. Can be customized with proxies and transports. ### Usage ```python from coingecko_sdk import Coingecko, DefaultHttpxClient import httpx client = Coingecko( http_client=DefaultHttpxClient( proxy="http://my.proxy.example.com:8080", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) ``` ``` -------------------------------- ### Making GET Requests to Undocumented Endpoints Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/07-advanced-usage.md Shows how to perform a GET request to an undocumented endpoint. The `get` method can be used similarly to `post`, with `cast_to=httpx.Response` to handle the raw response. ```python response = client.get( "/undocumented/endpoint", cast_to=httpx.Response, ) ``` -------------------------------- ### Initialize and Use Synchronous Client with Error Handling Source: https://github.com/coingecko/coingecko-python/blob/main/README.md Initialize the synchronous client and fetch Bitcoin price. This example demonstrates handling `APIConnectionError`, `RateLimitError`, and `APIStatusError`. ```python import os import coingecko_sdk from coingecko_sdk import Coingecko client = Coingecko( pro_api_key=os.environ.get("COINGECKO_PRO_API_KEY"), # demo_api_key=os.environ.get("COINGECKO_DEMO_API_KEY"), # Optional, for Demo API access environment="pro", # "demo" to initialize the client with Demo API access ) try: price = client.simple.price.get( vs_currencies="usd", ids="bitcoin", ) print(price["bitcoin"].usd) except coingecko_sdk.APIConnectionError as e: print("The server could not be reached") print(e.__cause__) # an underlying Exception, likely raised within httpx. except coingecko_sdk.RateLimitError as e: print("A 429 status code was received; we should back off a bit.") except coingecko_sdk.APIStatusError as e: print("Another non-200-range status code was received") print(e.status_code) print(e.response) ``` -------------------------------- ### Get All Coins Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/03-coins-api.md Retrieves a list of all cryptocurrencies with their IDs, symbols, and names. This is useful for getting a general overview of available coins. ```python from coingecko_sdk import Coingecko client = Coingecko() # Get all coins coins = client.coins.list.get() for coin in coins[:5]: print(f"{coin.id}: {coin.symbol.upper()} - {coin.name}") ``` -------------------------------- ### Initialize and Fetch Prices Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/09-common-patterns.md Demonstrates how to initialize the CoinGecko client and fetch the price of a specific cryptocurrency in multiple currencies. ```APIDOC ## Initialize and Fetch Prices ### Description Initializes the CoinGecko client and fetches the price of a specified cryptocurrency in multiple target currencies. ### Method GET ### Endpoint /simple/price ### Parameters #### Query Parameters - **vs_currencies** (string) - Required - Comma-separated list of target currencies (e.g., "usd,eur,gbp"). - **ids** (string) - Required - Comma-separated list of cryptocurrency IDs (e.g., "bitcoin"). ### Request Example ```python from coingecko_sdk import Coingecko client = Coingecko() prices = client.simple.price.get( vs_currencies="usd,eur,gbp", ids="bitcoin", ) ``` ### Response #### Success Response (200) - **[coin_id]** (object) - Contains price data for the requested coin. - **[currency]** (float) - The price of the coin in the specified currency. ``` -------------------------------- ### Get All Coins List Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieves a list of all available coins. Use this method to get a comprehensive list of coin IDs and their details. ```python client.coins.list.get(**params) -> ListGetResponse ``` -------------------------------- ### Initialize Alternative Asynchronous HTTP Client Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/01-client-initialization.md Use DefaultAioHttpClient for an alternative asynchronous client with aiohttp. Requires `pip install coingecko_sdk[aiohttp]`. ```python from coingecko_sdk import Coingecko, DefaultAioHttpClient # Assuming DefaultAioHttpClient is used similarly to DefaultHttpxClient # Example: client = Coingecko(http_client=DefaultAioHttpClient(...)) ``` -------------------------------- ### Get Basic Coin Data by ID Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/03-coins-api.md Fetches essential data for a cryptocurrency using its ID. This is the simplest way to get coin information. ```python coin_data = client.coins.get_id("bitcoin") ``` -------------------------------- ### Example Usage of NFTs API Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/04-additional-apis.md Demonstrates how to initialize the CoinGecko client, fetch data for a specific NFT collection by ID, and list NFT collections with sorting and pagination. Includes printing key details of the retrieved NFT data. ```python from coingecko_sdk import Coingecko client = Coingecko() # Get CryptoPunks data nft = client.nfts.get_id("cryptopunks") print(f"Name: {nft.name}") print(f"Floor Price: {nft.floor_price}") print(f"Market Cap: {nft.market_cap}") # Get NFT list nfts = client.nfts.list.get( per_page=10, order="market_cap_usd_desc", ) for nft in nfts: print(f"{nft.name} - Market Cap: {nft.market_cap}") ``` -------------------------------- ### Determine Installed Coingecko SDK Version Source: https://github.com/coingecko/coingecko-python/blob/main/README.md Check the installed version of the coingecko-sdk library at runtime. This is useful for verifying upgrades or debugging version-related issues. ```python import coingecko_sdk print(coingecko_sdk.__version__) ``` -------------------------------- ### Initialize Coingecko Client with Custom Base URL Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/08-configuration.md Initialize the Coingecko client, optionally providing a custom base URL. Note that the 'environment' parameter takes precedence if both are provided. ```python import os from coingecko_sdk import Coingecko client = Coingecko( base_url=os.environ.get("COINGECKO_BASE_URL"), ) ``` -------------------------------- ### Get Cryptocurrency Entities List Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/04-additional-apis.md Retrieves a paginated list of cryptocurrency entities. This is useful for getting information about projects and organizations within the cryptocurrency space. ```python from coingecko_sdk import Coingecko client = Coingecko() entities = client.entities.get_list(page=1) ``` -------------------------------- ### Initialize Default Synchronous HTTP Client Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/01-client-initialization.md Use DefaultHttpxClient for a synchronous client. Customize with proxies and transports. ```python from coingecko_sdk import Coingecko, DefaultHttpxClient import httpx client = Coingecko( http_client=DefaultHttpxClient( proxy="http://my.proxy.example.com:8080", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) ``` -------------------------------- ### Initialize Default Asynchronous HTTP Client Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/01-client-initialization.md Use DefaultAsyncHttpxClient for an asynchronous client with httpx. ```python from coingecko_sdk import Coingecko, DefaultAsyncHttpxClient # Assuming DefaultAsyncHttpxClient is used similarly to DefaultHttpxClient # Example: client = Coingecko(http_client=DefaultAsyncHttpxClient(...)) ``` -------------------------------- ### Get 7-Day Bitcoin OHLC Data Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/03-coins-api.md Fetches 7-day hourly OHLC data for Bitcoin in USD. This snippet demonstrates basic usage of the get method for OHLC data. ```python from coingecko_sdk import Coingecko client = Coingecko() # 7-day hourly OHLC data ohlc = client.coins.ohlc.get( id="bitcoin", vs_currency="usd", days="7", ) for timestamp, open_price, high, low, close in ohlc[-5:]: print(f"{timestamp}: O:{open_price} H:{high} L:{low} C:{close}") ``` -------------------------------- ### IDE Type Hinting Example (VS Code) Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/07-advanced-usage.md Demonstrates how to use type hints with the Coingecko SDK to enable features like 'Reveal Type' in VS Code, allowing developers to inspect inferred types directly within the editor. ```python from coingecko_sdk import Coingecko client = Coingecko() price = client.simple.price.get(vs_currencies="usd", ids="bitcoin") # Hover over `price` to see inferred type # Should show: Dict[str, PriceGetResponseItem] # Hover over `price['bitcoin']` to see type # Should show: PriceGetResponseItem ``` -------------------------------- ### Basic Async/Await Usage Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/07-advanced-usage.md Demonstrates the fundamental pattern for using the asynchronous client. Ensure the client is properly closed using `async with`. ```python import asyncio from coingecko_sdk import AsyncCoingecko async def get_price(coin_id: str) -> float: async with AsyncCoingecko() as client: price = await client.simple.price.get( vs_currencies="usd", ids=coin_id, ) return price[coin_id].usd # Run async function price = asyncio.run(get_price("bitcoin")) print(f"BTC: ${price}") ``` -------------------------------- ### Basic Usage with Synchronous Client and Error Handling Source: https://github.com/coingecko/coingecko-python/blob/main/README.md Shows how to initialize the synchronous Coingecko client, fetch Bitcoin prices, and handle potential API errors. ```APIDOC ## Basic Usage with Synchronous Client and Error Handling ```python import os import coingecko_sdk from coingecko_sdk import Coingecko client = Coingecko( pro_api_key=os.environ.get("COINGECKO_PRO_API_KEY"), # demo_api_key=os.environ.get("COINGECKO_DEMO_API_KEY"), # Optional, for Demo API access environment="pro", # "demo" to initialize the client with Demo API access ) try: price = client.simple.price.get( vs_currencies="usd", ids="bitcoin", ) print(price["bitcoin"].usd) except coingecko_sdk.APIConnectionError as e: print("The server could not be reached") print(e.__cause__) # an underlying Exception, likely raised within httpx. except coingecko_sdk.RateLimitError as e: print("A 429 status code was received; we should back off a bit.") except coingecko_sdk.APIStatusError as e: print("Another non-200-range status code was received") print(e.status_code) print(e.response) ``` ``` -------------------------------- ### Get 7-Day Bitcoin Price History Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/03-coins-api.md Fetches the historical price data for Bitcoin in USD for the last 7 days. This snippet demonstrates basic usage of the `get` method for price history. ```python from coingecko_sdk import Coingecko client = Coingecko() # 7-day price history chart = client.coins.market_chart.get( id="bitcoin", vs_currency="usd", days="7", ) print(f"Data points: {len(chart.prices)}") for timestamp, price in chart.prices[-5:]: print(f"{timestamp}: ${price}") ``` -------------------------------- ### Get Derivative Exchanges Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieves a list of derivative exchanges. ```APIDOC ## GET /derivatives/exchanges ### Description Retrieves a list of derivative exchanges available on CoinGecko. ### Method GET ### Endpoint /derivatives/exchanges ### Parameters #### Query Parameters This endpoint accepts additional parameters as specified in `coingecko_sdk.types.derivatives.exchange_get_params`. ### Request Example ```python # Example usage (actual parameters depend on the params object) client.derivatives.exchanges.get() ``` ### Response #### Success Response (200) Returns an `ExchangeGetResponse` object containing derivative exchange data. ``` -------------------------------- ### Resource Hierarchy Example Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/07-advanced-usage.md Illustrates the hierarchical structure of available methods within the 'coins', 'simple', and 'exchanges' resources. This helps in understanding how to chain method calls to access specific data. ```python client.coins ├── .get_id(id) ├── .list.get() ├── .markets.get() ├── .market_chart.get() ├── .history.get() ├── .ohlc.get() ├── .tickers.get() ├── .categories.get() ├── .contract │ ├── .get_id() │ └── .market_chart.get() ├── .top_gainers_losers.get() ├── .circulating_supply_chart.get() └── .total_supply_chart.get() client.simple ├── .price.get() ├── .supported_vs_currencies.get() └── .token_price.get() client.exchanges ├── .list.get() ├── .get_id(id) ├── .tickers.get() └── .volume_chart.get() ``` -------------------------------- ### Get Derivative Data Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieves general derivative data. ```APIDOC ## GET /derivatives ### Description Retrieves general derivative data from CoinGecko. ### Method GET ### Endpoint /derivatives ### Parameters This endpoint does not have explicit path or query parameters documented in this snippet, but may accept parameters as specified in `coingecko_sdk.types.derivative_get_response`. ### Request Example ```python client.derivatives.get() ``` ### Response #### Success Response (200) Returns a `DerivativeGetResponse` object containing derivative information. ``` -------------------------------- ### Initialize Coingecko Client with Pro API Key Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/08-configuration.md Initialize the Coingecko client, which automatically loads the Pro API key from the COINGECKO_PRO_API_KEY environment variable. You can also pass it explicitly. ```python import os from coingecko_sdk import Coingecko # Automatically loads from environment variable client = Coingecko() # Or explicitly (overrides environment variable) client = Coingecko(pro_api_key="explicit-key") ``` -------------------------------- ### Get Categories List Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieves a list of all available coin categories. ```APIDOC ## GET /coins/categories/list ### Description Retrieves a list of all available coin categories. ### Method GET ### Endpoint /coins/categories/list ### Response #### Success Response (200) - **CategoryGetListResponse** (object) - A response object containing a list of categories. ``` -------------------------------- ### Simple Price Client Method Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Use the client.simple.price.get method to fetch simple price data. Pass parameters as a dictionary. ```python client.simple.price.get(**params) -> PriceGetResponse ``` -------------------------------- ### Get List of Derivative Exchanges Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieves a list of all available derivative exchanges. ```APIDOC ## GET /derivatives/exchanges/list ### Description Retrieves a comprehensive list of all derivative exchanges supported by CoinGecko. ### Method GET ### Endpoint /derivatives/exchanges/list ### Parameters This endpoint does not have any documented parameters. ### Request Example ```python client.derivatives.exchanges.get_list() ``` ### Response #### Success Response (200) Returns an `ExchangeGetListResponse` object containing a list of all derivative exchanges. ``` -------------------------------- ### Bootstrap Development Environment with Rye Source: https://github.com/coingecko/coingecko-python/blob/main/CONTRIBUTING.md Run this script to automatically provision a Python environment with the expected Python version using Rye. ```sh $ ./scripts/bootstrap ``` -------------------------------- ### Initialize Coingecko Client with Default Retries Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/05-exceptions.md Instantiate the Coingecko client with default retry settings. ```python from coingecko_sdk import Coingecko # Initialize with default retries (usually 3) client = Coingecko() ``` -------------------------------- ### Get Coin Category List Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieve a list of all available coin categories. ```python client.coins.categories.get_list() -> CategoryGetListResponse ``` -------------------------------- ### client.simple.supported_vs_currencies.get Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieves a list of all supported fiat currencies that can be used in price conversions. ```APIDOC ## GET /simple/supported_vs_currencies ### Description Returns a list of all supported fiat currencies. ### Method GET ### Endpoint /simple/supported_vs_currencies ### Response #### Success Response (200) - **SupportedVsCurrencyGetResponse** - An array of strings representing supported fiat currencies. Refer to `coingecko_sdk.types.simple.supported_vs_currency_get_response` for the schema. ``` -------------------------------- ### Get NFT by ID Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieve a specific NFT by its ID using the client.nfts.get_id method. ```python client.nfts.get_id(id) -> NFTGetIDResponse ``` -------------------------------- ### Get Exchanges List Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Obtains a list of all available exchanges. Ensure 'ExchangeGetListResponse' is imported. ```python client.exchanges.get_list(**params) -> ExchangeGetListResponse ``` -------------------------------- ### Testing Configuration with Mock Client Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/08-configuration.md Configure the client for testing by using a mock HTTP client. This allows for isolated testing without making actual network requests. ```python from unittest.mock import Mock, patch from coingecko_sdk import Coingecko, DefaultHttpxClient import httpx # Use test/mock HTTP client mock_client = Mock(spec=httpx.Client) client = Coingecko( http_client=DefaultHttpxClient(), ) ``` -------------------------------- ### Development Configuration Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/08-configuration.md Configure the client for development using a demo API key, a longer timeout for debugging, and disabling retries for faster feedback. ```python import os from coingecko_sdk import Coingecko client = Coingecko( # Use demo API for development demo_api_key=os.environ.get("COINGECKO_DEMO_API_KEY"), environment="demo", # Longer timeout for debugging timeout=60.0, # Disable retries for faster feedback max_retries=0, ) ``` -------------------------------- ### Get Exchanges Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieves general exchange information. Import necessary types from 'coingecko_sdk.types'. ```python from coingecko_sdk.types import ExchangeGetResponse, ExchangeGetIDResponse, ExchangeGetListResponse ``` ```python client.exchanges.get(**params) -> ExchangeGetResponse ``` -------------------------------- ### Build Distribution Files Source: https://github.com/coingecko/coingecko-python/blob/main/CONTRIBUTING.md Create distributable package files (.tar.gz and .whl) for the library using Rye or the standard Python build module. ```sh $ rye build # or $ python -m build ``` -------------------------------- ### Get Derivative Exchange by ID Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieves details for a specific derivative exchange by its ID. ```APIDOC ## GET /derivatives/exchanges/{id} ### Description Retrieves detailed information for a specific derivative exchange identified by its ID. ### Method GET ### Endpoint /derivatives/exchanges/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the derivative exchange. #### Query Parameters This endpoint accepts additional parameters as specified in `coingecko_sdk.types.derivatives.exchange_get_id_params`. ### Request Example ```python # Example usage (actual parameters depend on the params object) client.derivatives.exchanges.get_id(id='binance') ``` ### Response #### Success Response (200) Returns an `ExchangeGetIDResponse` object containing the details of the specified derivative exchange. ``` -------------------------------- ### Get On-Chain Search Pools Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Searches for on-chain pools. Requires importing the PoolGetResponse type. ```python from coingecko_sdk.types.onchain.search import PoolGetResponse ``` ```python client.onchain.search.pools.get(**params) -> PoolGetResponse ``` -------------------------------- ### Initialize Synchronous Coingecko Client Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/01-client-initialization.md Instantiate the synchronous Coingecko client with a Pro API key and specify the environment. This client is used for making direct API calls. ```python from coingecko_sdk import Coingecko client = Coingecko( pro_api_key="your-pro-api-key", environment="pro", # or "demo" ) ``` -------------------------------- ### Production Configuration Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/08-configuration.md Configure the client for production use by loading the API key from environment variables, setting a reasonable timeout, enabling retries, and specifying custom headers. ```python import os from coingecko_sdk import Coingecko client = Coingecko( # Load API key from environment pro_api_key=os.environ.get("COINGECKO_PRO_API_KEY"), environment="pro", # Set reasonable timeouts timeout=30.0, # Enable retries for transient failures max_retries=3, # Custom headers (e.g., User-Agent) default_headers={ "User-Agent": "MyApp/1.0.0", }, ) ``` -------------------------------- ### Get Token Info Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieves detailed information for a specific token address on a given network. ```APIDOC ## GET /onchain/networks/{network}/tokens/{address}/info ### Description Retrieves detailed information for a specific token address on a given network. ### Method GET ### Endpoint /onchain/networks/{network}/tokens/{address}/info ### Parameters #### Path Parameters - **address** (string) - Required - The token address. - **network** (string) - Required - The network identifier. ``` -------------------------------- ### Get Pools Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieves a list of pools for a given network. Supports filtering and pagination through parameters. ```APIDOC ## GET /onchain/networks/{network}/pools ### Description Retrieves a list of pools for a given network. Supports filtering and pagination through parameters. ### Method GET ### Endpoint /onchain/networks/{network}/pools ### Parameters #### Path Parameters - **network** (string) - Required - The network identifier. #### Query Parameters - **params** (object) - Optional - Additional parameters for filtering and pagination. ``` -------------------------------- ### get /onchain/categories Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieves a list of onchain categories. This method can be filtered using provided parameters. ```APIDOC ## GET /onchain/categories ### Description Retrieves a list of onchain categories. This method can be filtered using provided parameters. ### Method GET ### Endpoint /onchain/categories ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for filtering the categories. ### Response #### Success Response (200) - **CategoryGetResponse** (object) - The response object containing category information. ``` -------------------------------- ### Get News Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieve news articles using the client.news.get method. Pass parameters as a dictionary. ```python client.news.get(**params) -> NewsGetResponse ``` -------------------------------- ### Fetch Multiple Coins with Market Data Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/09-common-patterns.md Shows how to query prices and market data for multiple cryptocurrencies, including market cap, 24h volume, and 24h change. ```python from coingecko_sdk import Coingecko client = Coingecko() # Query multiple coins with additional data prices = client.simple.price.get( vs_currencies="usd", ids="bitcoin,ethereum,cardano", include_market_cap=True, include_24hr_vol=True, include_24hr_change=True, ) # Process results for coin_id, data in prices.items(): print(f"\n{coin_id.upper()}") print(f" Price: ${data.usd:.2f}") print(f" Market Cap: ${data.usd_market_cap:,.0f}") print(f" 24h Volume: ${data.usd_24h_vol:,.0f}") print(f" 24h Change: {data.usd_24h_change:+.2f}%") ``` -------------------------------- ### Basic Usage Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/README.md Demonstrates basic usage of the CoinGecko Python SDK to fetch the price of Bitcoin. ```APIDOC ## Basic Usage ```python from coingecko_sdk import Coingecko client = Coingecko() price = client.simple.price.get(vs_currencies="usd", ids="bitcoin") print(f"Bitcoin: ${price['bitcoin'].usd}") ``` ``` -------------------------------- ### Get Exchanges Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieves a list of exchanges. This method can accept various parameters to filter the results. ```APIDOC ## GET /exchanges ### Description Retrieves a list of exchanges. This method can accept various parameters to filter the results. ### Method GET ### Endpoint /exchanges ### Parameters #### Query Parameters - **params** (dict) - Optional - Parameters for filtering the exchange list. ### Response #### Success Response (200) - **ExchangeGetResponse** - The response object containing exchange information. ``` -------------------------------- ### Get Exchange Rates Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieves a list of currency exchange rates. This endpoint does not accept any parameters. ```APIDOC ## GET /exchange_rates ### Description Retrieves a list of currency exchange rates. This endpoint does not accept any parameters. ### Method GET ### Endpoint /exchange_rates ### Response #### Success Response (200) - **ExchangeRateGetResponse** - The response object containing exchange rates. ``` -------------------------------- ### Synchronous Client Initialization Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/01-client-initialization.md Instantiate the synchronous Coingecko client with optional parameters for API keys, environment, timeouts, and retries. ```APIDOC ## Coingecko Client ### Description Instantiates the synchronous client for interacting with the CoinGecko API. ### Class `coingecko_sdk.Coingecko` ### Constructor Parameters #### `pro_api_key` - **Type**: `str | None` - **Required**: No - **Default**: `None` - **Description**: API key for CoinGecko Pro API. If not provided, reads from `COINGECKO_PRO_API_KEY` environment variable. #### `demo_api_key` - **Type**: `str | None` - **Required**: No - **Default**: `None` - **Description**: API key for CoinGecko Demo API. If not provided, reads from `COINGECKO_DEMO_API_KEY` environment variable. #### `environment` - **Type**: `Literal["pro", "demo"] | NotGiven` - **Required**: No - **Default**: `not_given` - **Description**: API environment to use. Determines the base URL (pro: https://pro-api.coingecko.com/api/v3, demo: https://api.coingecko.com/api/v3). #### `base_url` - **Type**: `str | httpx.URL | None | NotGiven` - **Required**: No - **Default**: `not_given` - **Description**: Custom base URL for API requests. Overrides environment-based URL. Can be set via `COINGECKO_BASE_URL` environment variable. #### `timeout` - **Type**: `float | Timeout | None | NotGiven` - **Required**: No - **Default**: `not_given` - **Description**: Request timeout in seconds. Default is 60 seconds. Can be a float or `httpx.Timeout` object for granular control. #### `max_retries` - **Type**: `int` - **Required**: No - **Default**: `2` - **Description**: Number of times to retry failed requests. Applies to connection errors, 408, 409, 429, and 5xx status codes. #### `default_headers` - **Type**: `Mapping[str, str] | None` - **Required**: No - **Default**: `None` - **Description**: Custom headers to include in all requests. #### `default_query` - **Type**: `Mapping[str, object] | None` - **Required**: No - **Default**: `None` - **Description**: Default query parameters to include in all requests. #### `http_client` - **Type**: `httpx.Client | None` - **Required**: No - **Default**: `None` - **Description**: Custom `httpx.Client` instance for HTTP requests. When not provided, uses `DefaultHttpxClient`. #### `_strict_response_validation` - **Type**: `bool` - **Required**: No - **Default**: `False` - **Description**: Enable schema validation for API responses. Raises `APIResponseValidationError` if response doesn't match expected schema. ### Example Usage ```python import os from coingecko_sdk import Coingecko # Initialize with Pro API client = Coingecko( pro_api_key=os.environ.get("COINGECKO_PRO_API_KEY"), environment="pro", timeout=30.0, max_retries=3, ) # Make API calls price_data = client.simple.price.get( vs_currencies="usd", ids="bitcoin", ) print(price_data['bitcoin'].usd) # Close the client when done client.close() ``` ### Context Manager Usage ```python from coingecko_sdk import Coingecko # Automatically closes HTTP connections when exiting the block with Coingecko(pro_api_key="your-api-key") as client: price = client.simple.price.get( vs_currencies="usd", ids="bitcoin", ) ``` ``` -------------------------------- ### Implement Pagination to Fetch All Coins Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/09-common-patterns.md Demonstrates how to fetch a large number of coins by iterating through paginated results, collecting them until a desired count is reached. ```python from coingecko_sdk import Coingecko client = Coingecko() # Fetch all coins in batches all_coins = [] page = 1 while len(all_coins) < 500: # Get first 500 coins coins = client.coins.list.get( per_page=250, page=page, ) if not coins: break all_coins.extend(coins) page += 1 print(f"Total coins fetched: {len(all_coins)}") for coin in all_coins[:10]: print(f"{coin.id:20s} {coin.symbol:5s} {coin.name}") ``` -------------------------------- ### Get Total Supply Chart Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieves the total supply chart data for a specific cryptocurrency. ```APIDOC ## GET /coins/{id}/total_supply_chart ### Description Retrieves the total supply chart data for a specific cryptocurrency identified by its ID. ### Method GET ### Endpoint /coins/{id}/total_supply_chart ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the cryptocurrency. #### Query Parameters This endpoint accepts additional parameters as specified in `coingecko_sdk.types.coins.total_supply_chart_get_params`. ### Request Example ```python # Example usage (actual parameters depend on the params object) client.coins.total_supply_chart.get(id='bitcoin') ``` ### Response #### Success Response (200) Returns a `TotalSupplyChartGetResponse` object containing the total supply chart data. ``` -------------------------------- ### Initialize Asynchronous Coingecko Client Source: https://github.com/coingecko/coingecko-python/blob/main/README.md Initialize the asynchronous client using AsyncCoingecko and await API calls. This client also supports API keys and environment variables. ```python import os import asyncio from coingecko_sdk import AsyncCoingecko client = AsyncCoingecko( pro_api_key=os.environ.get("COINGECKO_PRO_API_KEY"), # demo_api_key=os.environ.get("COINGECKO_DEMO_API_KEY"), # Optional, for Demo API access environment="pro", # "demo" to initialize the client with Demo API access ) async def main() -> None: price_data = await client.simple.price.get( vs_currencies="usd", ids="bitcoin", ) print(price_data['bitcoin'].usd) asyncio.run(main()) ``` -------------------------------- ### Get Derivative Data Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieves general derivative data. This method does not require any specific parameters. ```python from coingecko_sdk.types import DerivativeGetResponse client.derivatives.get() -> DerivativeGetResponse ``` -------------------------------- ### Run Tests Source: https://github.com/coingecko/coingecko-python/blob/main/CONTRIBUTING.md Execute the project's test suite using the provided test script. ```sh $ ./scripts/test ``` -------------------------------- ### Initialize Synchronous Coingecko Client Source: https://github.com/coingecko/coingecko-python/blob/main/README.md Initialize the synchronous client with an API key. It's recommended to use environment variables for API keys to avoid storing them in source control. ```python import os from coingecko_sdk import Coingecko client = Coingecko( pro_api_key=os.environ.get("COINGECKO_PRO_API_KEY"), # demo_api_key=os.environ.get("COINGECKO_DEMO_API_KEY"), # Optional, for Demo API access environment="pro", # "demo" to initialize the client with Demo API access ) price_data = client.simple.price.get( vs_currencies="usd", ids="bitcoin", ) print(price_data['bitcoin'].usd) ``` -------------------------------- ### get /onchain/search/pools Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Searches for on-chain pools. This endpoint allows for detailed searching with various filtering options. ```APIDOC ## GET /onchain/search/pools ### Description Searches for on-chain pools. This endpoint allows for detailed searching with various filtering options. ### Method GET ### Endpoint /onchain/search/pools ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for searching pools. ### Request Example ```json { "example": "client.onchain.search.pools.get(params={...})" } ``` ### Response #### Success Response (200) - **PoolGetResponse** (object) - The response object containing pool search results. ``` -------------------------------- ### get /onchain/pools/trending_search Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Fetches trending search data for on-chain pools. This method can be customized with specific parameters. ```APIDOC ## GET /onchain/pools/trending_search ### Description Fetches trending search data for on-chain pools. This method can be customized with specific parameters. ### Method GET ### Endpoint /onchain/pools/trending_search ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for filtering the trending search results. ### Request Example ```json { "example": "client.onchain.pools.trending_search.get(params={...})" } ``` ### Response #### Success Response (200) - **TrendingSearchGetResponse** (object) - The response object containing trending search data. ``` -------------------------------- ### Testing Configuration with Request Mocking Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/08-configuration.md Configure the client for testing by using `respx` to mock HTTP requests. This allows recording and replaying specific API responses for predictable test outcomes. ```python # Or use custom transport for recording/replaying requests import respx @respx.mock def test_price(): respx.get("https://api.coingecko.com/api/v3/simple/price").mock( return_value=httpx.Response( 200, json={"bitcoin": {"usd": 45000}}, ) ) client = Coingecko() price = client.simple.price.get(vs_currencies="usd", ids="bitcoin") assert price['bitcoin'].usd == 45000 ``` -------------------------------- ### Get All Pools Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieves a list of all pools for a given network. Optional parameters can be passed for filtering or pagination. ```python client.onchain.networks.pools.get(network, **params) -> PoolGetResponse ``` -------------------------------- ### Supported Vs Currencies Client Method Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Use the client.simple.supported_vs_currencies.get method to list all supported vs currencies. ```python client.simple.supported_vs_currencies.get() -> SupportedVsCurrencyGetResponse ``` -------------------------------- ### get /onchain/networks Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieves a list of supported onchain networks. Filtering can be applied using the provided parameters. ```APIDOC ## GET /onchain/networks ### Description Retrieves a list of supported onchain networks. Filtering can be applied using the provided parameters. ### Method GET ### Endpoint /onchain/networks ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for filtering the networks. ### Response #### Success Response (200) - **NetworkGetResponse** (object) - The response object containing network information. ``` -------------------------------- ### Switch Between API Environments Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/08-configuration.md Instantiate the Coingecko client for different environments (Pro, Demo) or specify a custom base URL. This allows targeting different API deployments. ```python from coingecko_sdk import Coingecko # Pro API pro_client = Coingecko( pro_api_key="pro-key", environment="pro", ) # Demo API demo_client = Coingecko( demo_api_key="demo-key", environment="demo", ) # Custom URL custom_client = Coingecko( base_url="https://custom-api.example.com/v3", ) ``` -------------------------------- ### Get NFT Tickers Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieve ticker information for a specific NFT by its ID using the client.nfts.tickers.get method. ```python client.nfts.tickers.get(id) -> TickerGetResponse ``` -------------------------------- ### Initialize Coingecko Client Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/02-simple-api.md Instantiate the Coingecko client to access API endpoints. This client can be used for both synchronous and asynchronous operations. ```python from coingecko_sdk import Coingecko client = Coingecko() ``` -------------------------------- ### Get NFT List Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieve a list of NFTs using the client.nfts.get_list method. Parameters can be passed as a dictionary. ```python client.nfts.get_list(**params) -> NFTGetListResponse ``` -------------------------------- ### Get Key Data Source: https://github.com/coingecko/coingecko-python/blob/main/api.md Retrieve key information from the CoinGecko API. This method returns a KeyGetResponse object. ```python client.key.get() -> KeyGetResponse ``` -------------------------------- ### Basic CoinGecko SDK Usage Source: https://github.com/coingecko/coingecko-python/blob/main/_autodocs/README.md Initialize the CoinGecko client and fetch the current price of Bitcoin in USD. This demonstrates a simple API call to retrieve price data. ```python from coingecko_sdk import Coingecko client = Coingecko() price = client.simple.price.get(vs_currencies="usd", ids="bitcoin") print(f"Bitcoin: ${price['bitcoin'].usd}") ```