### Install Coin Metrics Python API Client Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/index.md Use this command to install the client. Ensure you have pip installed. ```bash pip install coinmetrics-api-client ``` -------------------------------- ### Verify Tool Installation Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/site/tools/FlatFilesExport.html Check if the `coinmetrics export` tool is installed correctly by running the help command. This will display available commands. ```bash coinmetrics export --help ``` -------------------------------- ### Install and Initialize Coin Metrics Python API Client Source: https://context7.com/coinmetrics/api-client-python/llms.txt Install the package using pip. Initialize the client with an API key for the pro endpoint or omit it for the free community endpoint. Proxy and SSL options can also be configured. ```python # pip install coinmetrics-api-client from coinmetrics.api_client import CoinMetricsClient # Pro API (requires key) client = CoinMetricsClient(api_key="YOUR_API_KEY") # Community API (no key required) client = CoinMetricsClient() # With proxy and SSL options client = CoinMetricsClient( api_key="YOUR_API_KEY", proxy_url="http://proxy.example.com:8080", verify_ssl_certs=False, # or path to CA bundle verbose=True, # enable request logging ) ``` -------------------------------- ### Install CoinMetrics API Client Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/site/tools/FlatFilesExport.html Install the `coinmetrics-api-client` package within a Python virtual environment. Ensure your API key is set as an environment variable. ```bash python -m venv .venv source .venv/bin/activate pip install coinmetrics-api-client ``` -------------------------------- ### Iterate Asset Metrics with Paging from Start Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/user-guide/introduction.md Retrieves asset metrics and iterates through the data points starting from the beginning of the dataset. Requires importing `CoinMetricsClient` and `PagingFrom`. ```python from coinmetrics.api_client import CoinMetricsClient from coinmetrics.constants import PagingFrom client = CoinMetricsClient() for metric_data in client.get_asset_metrics(assets='btc', metrics=['ReferenceRateUSD'], paging_from=PagingFrom.START): print(metric_data) ``` -------------------------------- ### Get Help for a Specific Export Command Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/site/tools/FlatFilesExport.html Access detailed usage information for a specific export command, such as `market-trades-spot`. This includes arguments, options, and examples. ```bash coinmetrics export market-trades-spot --help ``` -------------------------------- ### Client Initialization Source: https://context7.com/coinmetrics/api-client-python/llms.txt Install the package and create an authenticated client. Use an empty string or omit the key to use the free community API endpoint. ```APIDOC ## Installation and Client Initialization Install the package and create an authenticated client. Use an empty string or omit the key to use the free community API endpoint. ```python # pip install coinmetrics-api-client from coinmetrics.api_client import CoinMetricsClient # Pro API (requires key) client = CoinMetricsClient(api_key="YOUR_API_KEY") # Community API (no key required) client = CoinMetricsClient() # With proxy and SSL options client = CoinMetricsClient( api_key="YOUR_API_KEY", proxy_url="http://proxy.example.com:8080", verify_ssl_certs=False, # or path to CA bundle verbose=True, # enable request logging ) ``` ``` -------------------------------- ### Get Available Index Candles Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Returns meta information about available index candles. If no indexes are provided, all available index candles are returned. ```python from typing import Optional, Union, List @deprecated("catalog") def catalog_index_candles( indexes: Optional[Union[List[str], str]] = None) -> CatalogMarketCandlesData: pass ``` -------------------------------- ### Get Reference Data Assets Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Retrieves asset metadata. The 'format' argument influences performance and the applicability of 'page_size' and 'paging_from'. 'next_page_token' should not be used directly. ```python def reference_data_assets( assets: Optional[Union[str, List[str]]] = None, page_size: Optional[int] = None, paging_from: Optional[str] = None, next_page_token: Optional[str] = None, format: Optional[str] = "json_stream") -> DataCollection: pass ``` -------------------------------- ### Get Market Liquidations Source: https://context7.com/coinmetrics/api-client-python/llms.txt Fetch liquidation events for futures markets. Requires market identifiers, start time, and end time. ```python from coinmetrics.api_client import CoinMetricsClient client = CoinMetricsClient(api_key="YOUR_API_KEY") df = client.get_market_liquidations( markets=["bitmex-XBTUSD-future"], start_time="2024-01-01", end_time="2024-01-07", ).to_dataframe() print(df[["market", "time", "side", "amount", "price"]]) ``` -------------------------------- ### Get Market Trades for Specific Exchange and Asset Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/site/user-guide/introduction.html Fetch market trades for a specific exchange and asset, then retrieve historical trades for a given time range. This example demonstrates filtering by exchange and asset, then fetching detailed market trades. ```python btc_coinbase_markets = [market['market'] for market in client.catalog_market_trades_v2(exchange="coinbase", asset="btc").to_list()] start_time = "2023-01-01T00:00:00" end_time = "2023-01-01T01:00:00" coinbase_market_trades = client.get_market_trades( markets=btc_coinbase_markets, start_time=start_time, end_time=end_time, ).export_to_csv("coinbase_trades.csv") ``` -------------------------------- ### Initialize CoinMetricsClient with arguments Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Configure the client with various parameters including API key, SSL verification, proxy, session, logging modes, host, port, and schema. ```python def __init__(api_key: str = "", verify_ssl_certs: Union[bool, str] = True, proxy_url: Optional[str] = None, session: Optional[requests.Session] = None, debug_mode: bool = False, verbose: bool = False, host: Optional[str] = None, port: Optional[int] = None, schema: str = "https") ``` -------------------------------- ### Step 1: Obtain Spot Markets using Reference Data Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/user-guide/best-practices.md Retrieve all available spot markets by querying the reference data endpoint. This serves as the initial step to identify relevant markets for further analysis. ```python # Step 1 spot_markets = client.reference_data_markets(type='spot').to_dataframe() ``` -------------------------------- ### Install Python Packages with Disabled SSL Verification Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/site/user-guide/troubleshooting.html Use this pip command to install packages when SSL verification is causing issues, such as behind a corporate firewall. Ensure you understand the security implications and company policies. ```bash pip install --trusted-host pypi.python.org ``` -------------------------------- ### Initialize Coin Metrics Client with API Key Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/site/index.html Initialize the client using your API key, preferably stored in an environment variable. Alternatively, use the community API by omitting the key. ```python from coinmetrics.api_client import CoinMetricsClient import os # we recommend storing your Coin Metrics API key in an environment variable api_key = os.environ.get("CM_API_KEY") client = CoinMetricsClient(api_key) # or to use community API: client = CoinMetricsClient() ``` -------------------------------- ### __init__ Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/site/reference/api_client.html Initializes the CoinMetrics API client. Allows configuration of API key, SSL verification, proxy, and connection details. ```APIDOC def __init__(api_key: str = "", verify_ssl_certs: Union[bool, str] = True, proxy_url: Optional[str] = None, session: Optional[requests.Session] = None, debug_mode: bool = False, verbose: bool = False, host: Optional[str] = None, port: Optional[int] = None, schema: str = "https") Arguments: * api_key (str): The API key for the CoinMetrics API. * verify_ssl_certs (bool or str): Whether to verify SSL certificates. Default is True. SSLErrors may be raised due to network configurations (e.g. proxies). You may set this to False or a path to bypass this error. * proxy_url (str): The URL of the proxy to use. * session (requests.Session): The session to use. * debug_mode (bool): Whether to enable debug mode for logging. * verbose (bool): Whether to enable verbose mode for logging. * host (str): The host for the Coin Metrics API. Default is "api.coinmetrics.io" or "community-api.coinmetrics.io based on user credentials. * port (int): The port for accessing the Coin Metrics API. Default is None. * schema (str): The schema for accessing the Coin Metrics API. Default is "https". ``` -------------------------------- ### Get Exchange Asset Metrics Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Retrieve time series metrics for specified exchange-asset pairs. Use this to get historical data like 'open_interest_reported_future_usd'. Available metrics can be found using `client.catalog_exchanges()`. Consider using `format='json_stream'` for better performance on large datasets. ```python def get_exchange_asset_metrics( exchange_assets: Union[List[str], str], metrics: Union[List[str], str], frequency: Optional[str] = None, page_size: Optional[int] = None, paging_from: Optional[Union[PagingFrom, str]] = "start", start_time: Optional[Union[datetime, date, str]] = None, end_time: Optional[Union[datetime, date, str]] = None, start_height: Optional[int] = None, end_height: Optional[int] = None, start_inclusive: Optional[bool] = None, end_inclusive: Optional[bool] = None, timezone: Optional[str] = None, sort: Optional[str] = None, limit_per_exchange_asset: Optional[int] = None, format: Optional[str] = "json") -> DataCollection ``` -------------------------------- ### Initialize CoinMetricsClient Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Instantiate the client with optional API key and SSL verification settings. Debug and verbose modes can also be enabled. ```python class CoinMetricsClient() ``` -------------------------------- ### Get Blockchain Metadata Locations Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Retrieves a list of all supported locations, ordered lexicographically. Supports pagination. ```APIDOC ## get_blockchain_metadata_locations ### Description Returns a list of all supported locations, ordered lexicographically. Supports pagination. ### Method Signature ```python get_blockchain_metadata_locations( page_size: Optional[int] = None, next_page_token: Optional[str] = None ) -> DataCollection ``` ### Parameters #### Query Parameters - `page_size` (Optional[int]): Number of items per single page of results. - `next_page_token` (Optional[str]): Token for receiving the results from the next page of a query. Should not be used directly. ### Returns `DataCollection`: A list of locations. ``` -------------------------------- ### Initialize CoinMetricsClient with API Key Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/index.md Initialize the client using your API key, preferably stored in an environment variable. This client connects to the authenticated Coin Metrics API. ```python from coinmetrics.api_client import CoinMetricsClient import os # we recommend storing your Coin Metrics API key in an environment variable api_key = os.environ.get("CM_API_KEY") client = CoinMetricsClient(api_key) ``` -------------------------------- ### Get Blockchain Metadata Locations Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Retrieves a list of all supported locations, ordered lexicographically. Supports pagination. ```python def get_blockchain_metadata_locations( page_size: Optional[int] = None, next_page_token: Optional[str] = None) -> DataCollection ``` -------------------------------- ### Parallelization Output Example Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/user-guide/best-practices.md Shows the expected output and timing difference when using the parallel export feature compared to a normal single-threaded export. ```command line Exporting to dataframe type: 100%|██████████| 36/36 [00:00<00:00, 54.62it/s] Time taken parallel: 0:00:36.654147 Time taken normal: 0:05:20.073826 ``` -------------------------------- ### Get Available Institutions Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Returns meta information about available institutions. If none are provided, all available pairs are returned. ```python from typing import Optional, Union, List @deprecated("catalog") def catalog_institutions( institutions: Optional[Union[List[str], str]] = None ) -> CatalogInstitutionsData: pass ``` -------------------------------- ### Configure Proxy With Authentication Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/site/user-guide/troubleshooting.html Initialize the CoinMetricsClient with a proxy URL that includes username and password for authenticated proxy servers. Ensure you replace placeholders with your actual credentials and proxy information. ```python client = CoinMetricsClient(proxy_url=f'http://:@:') ``` -------------------------------- ### Query market candles for all spot exchanges and pairs Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/site/user-guide/best-practices.html This example demonstrates how to dynamically query market candle data for all spot exchanges and pairs. It first retrieves a list of all spot exchanges and then constructs market identifiers using wildcards for each exchange. ```python # Get all spot exchanges and pairs exchanges_reference = client.reference_data_exchanges().to_list() market_candles_spot = client.get_market_candles(markets=[f'{exchange["exchange"]}-*-spot' for exchange['exchange'] in exchanges_reference], limit_per_market=10) ``` -------------------------------- ### Get Blockchain Metadata Owners Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Retrieves a list of all supported owners, ordered lexicographically by owner name. Supports pagination. ```APIDOC ## get_blockchain_metadata_owners ### Description Returns a list of all supported owners, lexicographically ordered by the `owner_name` field. Supports pagination. ### Method Signature ```python get_blockchain_metadata_owners( page_size: Optional[int] = None, next_page_token: Optional[str] = None ) -> DataCollection ``` ### Parameters #### Query Parameters - `page_size` (Optional[int]): Number of items per single page of results. - `next_page_token` (Optional[str]): Token for receiving the results from the next page of a query. Should not be used directly. ### Returns `DataCollection`: A list of owners. ``` -------------------------------- ### Initialize CoinMetricsClient Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/site/user-guide/introduction.html Initialize the client using your API key, which is recommended to be stored in an environment variable. Alternatively, you can use the community API. ```python from coinmetrics.api_client import CoinMetricsClient import os # we recommend storing your Coin Metrics API key in an environment variable api_key = os.environ.get("CM_API_KEY") client = CoinMetricsClient(api_key) # or to use community API: client = CoinMetricsClient() ``` -------------------------------- ### Get Blockchain Metadata Owners Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Retrieves a list of all supported owners, ordered lexicographically by owner name. Supports pagination. ```python def get_blockchain_metadata_owners( page_size: Optional[int] = None, next_page_token: Optional[str] = None) -> DataCollection ``` -------------------------------- ### Get Stream Market Candles Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Returns a timeseries stream of market candles. Specify markets, frequency, and backfill preference. ```python def get_stream_market_candles( markets: Union[List[str], str], frequency: Optional[str] = None, backfill: Union[Backfill, str] = Backfill.LATEST) -> CmStream ``` -------------------------------- ### List Available Export Commands Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/site/tools/FlatFilesExport.html View all available commands for the `coinmetrics export` tool. This helps in understanding the types of data that can be exported. ```bash Commands: get-asset-pairs get-exchanges market-candles-future Used to export data related to future market... market-candles-spot Used to export data related to spot market candles. market-quotes-future Used to export data related to future market... market-quotes-spot Used to export data related to spot market quotes... market-trades-future Used to export data related to future market... market-trades-spot Used to export data related to spot market trades. ``` -------------------------------- ### Get Stream Market Trades Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Returns a timeseries stream of market trades. Configure backfill behavior for initial data. ```python def get_stream_market_trades( markets: Union[List[str], str], backfill: Union[Backfill, str] = Backfill.LATEST) -> CmStream ``` -------------------------------- ### Get Blockchain Metadata Tags Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Retrieves a list of blockchain metadata tags. This method is deprecated and users should use `get_blockchain_metadata_tags` instead. ```APIDOC ## blockchain_metadata_tags ### Description Get blockchain metadata tags. ### Method Signature ```python blockchain_metadata_tags(type: Optional[str] = None, page_size: Optional[int] = None, next_page_token: Optional[str] = None) -> DataCollection ``` ### Parameters #### Optional Parameters - **type** (Optional[str]): The type of a tag. - **page_size** (Optional[int]): Number of items per single page of results. - **next_page_token** (Optional[str]): Token for receiving the results from the next page of a query. Should not be used directly. To iterate through pages just use `next_page_url` response field. ### Returns `DataCollection`: List of tags. ``` -------------------------------- ### Dynamically Constructing Market Queries with Wildcards Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/user-guide/best-practices.md Fetch reference data for exchanges and then dynamically construct a list of markets using wildcards to query for spot candles. This allows for targeted data retrieval across various exchanges. ```python # Get all spot exchanges and pairs exchanges_reference = client.reference_data_exchanges().to_list() market_candles_spot = client.get_market_candles(markets=[f'{exchange["exchange"]}-*-spot' for exchange['exchange'] in exchanges_reference], limit_per_market=10) ``` -------------------------------- ### CoinMetricsClient Initialization Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Initializes the CoinMetricsClient with various configuration options for connecting to the Coin Metrics API. ```APIDOC ## CoinMetricsClient() ### Description Initializes the CoinMetricsClient for interacting with the Coin Metrics API. ### Arguments - **api_key** (str): The API key for authentication. - **verify_ssl_certs** (bool or str): Controls SSL certificate verification. Defaults to True. Can be set to False or a path to bypass verification. - **proxy_url** (str): URL for a proxy server to use for requests. - **session** (requests.Session): An optional `requests.Session` object to use. - **debug_mode** (bool): Enables debug logging. Defaults to False. - **verbose** (bool): Enables verbose logging. Defaults to False. - **host** (str): The API host. Defaults to 'api.coinmetrics.io' or 'community-api.coinmetrics.io'. - **port** (int): The API port. Defaults to None. - **schema** (str): The connection schema (e.g., 'https'). Defaults to 'https'. ``` -------------------------------- ### Get Blockchain Metadata Tags Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Retrieves a list of blockchain metadata tags. Use the `next_page_url` field in the response to paginate through results. ```python def blockchain_metadata_tags( type: Optional[str] = None, page_size: Optional[int] = None, next_page_token: Optional[str] = None) -> DataCollection ``` -------------------------------- ### Initialize CoinMetricsClient for Community API Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/index.md Initialize the client without an API key to use the community API. This is suitable for accessing public data. ```python client = CoinMetricsClient() ``` -------------------------------- ### Get Asset Profiles Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Fetches profile data for specified assets. Can filter by asset symbols or full names, and supports pagination. ```python def get_asset_profiles(assets: Optional[Union[List[str], str]] = None, full_names: Optional[Union[List[str], str]] = None, page_size: Optional[int] = None, paging_from: Optional[str] = None) -> DataCollection ``` -------------------------------- ### CoinMetricsClient Initialization Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/site/reference/api_client.html Initializes the CoinMetricsClient. This is the primary entry point for interacting with the API. ```APIDOC ## __init__ ### Description Initializes the CoinMetricsClient. ### Method `__init__()` ``` -------------------------------- ### Get Stream Asset Quotes Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Returns a timeseries stream of quotes for specified assets. Supports aggregation methods and backfill options. ```python def get_stream_asset_quotes(assets: Union[str, List[str]], aggregation_method: Optional[str] = None, backfill: Optional[str] = None) -> CmStream ``` -------------------------------- ### Catalog Full Metrics Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Retrieve a list of supported metrics along with their descriptions, categories, precision, and the assets for which they are available. Use this to understand available metrics and their properties. ```python @deprecated("catalog") def catalog_full_metrics( metrics: Optional[Union[List[str], str]] = None, reviewable: Optional[bool] = None) -> CatalogMetricsData ``` -------------------------------- ### Get Mempool Feerates Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Retrieve mempool feerates for specified assets. Note: page_size must be less than or equal to 200 for this method. ```python def get_mempool_feerates(assets: Union[List[str], str], page_size: Optional[int] = 200, paging_from: Optional[Union[PagingFrom, str]] = "start", start_time: Optional[Union[datetime, date, str]] = None, end_time: Optional[Union[datetime, date, str]] = None, start_inclusive: Optional[bool] = None, end_inclusive: Optional[bool] = None, timezone: Optional[str] = None) -> DataCollection ``` -------------------------------- ### Get Mining Pool Tips Summary Source: https://context7.com/coinmetrics/api-client-python/llms.txt Obtain a summary of which chain tips mining pools are building on. Requires specifying the asset and a time range. ```python from coinmetrics.api_client import CoinMetricsClient client = CoinMetricsClient(api_key="YOUR_API_KEY") df = client.get_mining_pool_tips_summary( assets="btc", start_time="2024-01-01", end_time="2024-01-07", ).to_dataframe() print(df) ``` -------------------------------- ### Get Index Levels Source: https://context7.com/coinmetrics/api-client-python/llms.txt Fetch historical levels for Coin Metrics CMBI indexes. Specify the indexes, frequency, and start/end times. ```python from coinmetrics.api_client import CoinMetricsClient client = CoinMetricsClient(api_key="YOUR_API_KEY") df = client.get_index_levels( indexes=["CMBIBTC", "CMBI10"], frequency="1d", start_time="2024-01-01", end_time="2024-03-31", ).to_dataframe() print(df[["index", "time", "level"]]) ``` -------------------------------- ### Get Supported Exchanges for a Command Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/site/tools/FlatFilesExport.html Determine which exchanges are supported for a specific flat file export command by using the `get-exchanges` subcommand. ```bash coinmetrics export get-exchanges market-trades-spot ``` -------------------------------- ### Get Catalog Mining Pool Tips Summaries Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/reference/api_client.md Retrieve summaries of mining pool tips for specified assets. By default, this returns data for all available assets. ```python @deprecated("catalog") def catalog_mining_pool_tips_summaries( assets: Optional[Union[str, List[str]]] = None) -> CatalogMiningPoolTipsData ``` -------------------------------- ### Transform Timeseries Data to Pandas DataFrame Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/user-guide/introduction.md Convert timeseries data obtained from the API into a pandas DataFrame for further analysis. Ensure pandas is installed. ```python import pandas as pd from coinmetrics.api_client import CoinMetricsClient from os import environ client = CoinMetricsClient() trades = client.get_market_trades( markets='coinbase-btc-usd-spot', start_time='2021-09-19T00:00:00Z', limit_per_market=10 ) trades_df = trades.to_dataframe() print(trades_df.head()) ``` -------------------------------- ### Querying Specific Market Candles with Wildcards Source: https://github.com/coinmetrics/api-client-python/blob/master/docs/docs/user-guide/best-practices.md Employ wildcards within market identifiers to fetch data for multiple markets matching a pattern. This example retrieves BTC-USD spot candles across all exchanges. ```python # Get btc-usd candles for all exchanges market_candles_btc_usd = client.get_market_candles(markets=['*-btc-usd-spot'], limit_per_market=10) ```