# Welcome to Coin Metrics

Crypto intelligence for the future of finance

Welcome to the Coin Metrics Product Documentation!

We’re really glad you’re here.

At Coin Metrics, our mission is to make digital asset data more accessible, trustworthy, and actionable, whether you’re a developer, analyst, researcher, or just exploring the space. Our data is trusted by some of the biggest financial institutions and crypto businesses in the world, and we’re proud to make those same tools and reliable data available to you.

This site is here to help you get started. Find what you need, and make the most of our data and APIs. We’ve worked hard to make it as easy as possible to navigate, understand, and use.

Thank you for choosing Coin Metrics. We’re excited to have you on this journey with us!

If you’d like to learn more or have questions, we’re here to help:

* **Sales and Account Management:** Evaluate options, expand usage and explore crypto-related insights. [Schedule a call with our team](https://coinmetrics.io/contact/).
* **Solutions Engineering**: Get help integrating Coin Metrics data into your workflow. [Check out our Tutorials.](/tutorials-and-examples/tutorials)
* **Product Team:** Share feedback or [learn about new features.](https://coinmetrics.io/news/product-announcements/)
* **Research:** Check out our newest [State of the Network Newsletters](https://coinmetrics.io/insights/state-of-the-network/) and [Special Insights Reports](https://coinmetrics.io/special-insights/).
* **Support:** Clients looking to report incidents or errors that require an immediate response from Coin Metrics can submit a ticket to Zendesk to engage with our on-call teams. For Assistance setting up your Zendesk access reach out to your Account Manager.
* **Status Updates:** Subscribe to product specific [status updates](https://status.coinmetrics.io/) for outage, maintenance or incident alerts.

We’re always just a message away - don’t hesitate to get in touch.


# Product Overview

An Overview of the Coin Metrics Data Universe

Below is video by our Solutions Engineer providing an overview of the Coin Metrics Products and Data types. To learn more about each of the products check out the Product Overview Pages.

{% embed url="<https://www.youtube.com/embed/kvGHbbkl_Wg?si=4sdp3Dy9OWYeMzHl>" %}
High Level Data Overview
{% endembed %}

## Network Data

### [Network Data Pro (NDP)](/network-data/network-data-overview)

* **Network Data Pro** is a data feed of insightful, aggregate network data metrics for all of the top cryptoassets. These metrics are available with an API key through our [API](https://docs.coinmetrics.io/api/v4/) via the `/timeseries/asset-metrics` endpoint or through our [Data Visualization](/data-visualization) tools. All Network Data metrics are described in Network Data Overview.

### [Blockchain Explorer (Atlas)](/network-data/atlas-overview)

* **Atlas** is a complete blockchain search engine that enables users to look up information on transactions, addresses, and blocks through a high-performance [API](https://docs.coinmetrics.io/api/v4/). An API key is required to query the `/blockchain-v2/` endpoint via our API. Specifics on the format of the API output are described below in the [**Atlas**](/network-data/atlas-overview) section of this Encyclopedia.

## [Market Data](/market-data/market-data-overview)

### [Market Data Feed (MDF)](/market-data/market-data-overview)

* **Market Data Feed** provides access to historical and real-time data from over 30 of the world’s leading spot and derivatives crypto exchanges. This data is available primarily via the market data endpoints: `/timeseries/market-trades`, `/timeseries/market-openinterest`, `/timeseries/market-liquidations`, `/timeseries/market-funding-rates`, `/timeseries/market-orderbooks`, `/timeseries/market-quotes`, `/timeseries/market-candles` , and more. All endpoints and concepts are described in the [**Market Data**](/market-data/market-data-overview) section. There are also several aggregated market data metrics in `/timeseries/asset-metrics` and `/timeseries/pair-metrics`.

### [CM Prices](#coin-metrics-prices)

* **Reference Rates** provide prices calculated in U.S. Dollars and Euros for several assets using a transparent and independent methodology, robust to manipulation and derived from high-quality constituent markets. This data is available through our [API](/access-our-data/api) (`timeseries/asset-metrics` endpoint) and also in our [Data Visualization](/data-visualization) tools.
* **Reference Rates Community** (Community [API](/access-our-data/api), [Data Visualization](/data-visualization)) provides access to all of our reference rates with a limited amount of history for our more granular resolutions. For more info on our Community terms and offerings see our [Labs](https://coinmetrics.io/cm-labs/) page

## [Indexes](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/broken-reference/README.md)

### [Coin Metrics Bletchley Indexes (CMBI)](https://coinmetrics.io/cm-indexes/)

* **Coin Metrics Bletchley Indexes (CMBI)** are a comprehensive suite of single-asset, multi-asset, and unique crypto asset benchmarks used by leading crypto and traditional financial institutions. This data is available through our [API](/access-our-data/api) (`timeseries/index-levels` and `/timeseries/index-constituents` endpoints) and also in our [Data Visualization](/data-visualization) tools.
* **CMBI Community** (Community [API](/access-our-data/api), [Data Visualization](/data-visualization)) provides access to all of our index levels with a limited amount of history for our more granular resolutions. For more info on our Community terms and offerings see our [Labs](https://coinmetrics.io/cm-labs/) page. A further description of the limitations of this data is listed in the data concepts in the **Indexes** section of this Encyclopedia.

## [Reference Data](#reference-data)

* [**Datonomy**](/reference-data/datonomy-overview) is a digital asset classification system created by Coin Metrics, Goldman Sachs and MSCI that creates a consistent, standardized way for investors to analyze the digital assets ecosystem. This data is available via our API via the `/taxonomy/assets` endpoint.
* [**Asset Profiles**](/reference-data/asset-profiles-overview/asset-profiles) are descriptions of cryptoassets that supplement our asset metrics data to provide a comprehensive overview of a particular asset. This data is available via our API via the `/profiles/assets` endpoint.
* The [**Security Master**](/reference-data/security-master-overview) is a dataset that unifies metadata and provides fundamental reference data about crypto assets and markets. The data is available via our API via the `/security-master/` endpoint.


# Getting Started with Coin Metrics Data

Welcome! Follow the steps below to get started with using Coin Metrics data.

## 1. Set up Your API Key

Most of our data requires an API Key. If you want an API key, get in touch with us on our contact page: <https://coinmetrics.io/contact/>

We offer some data for free under our Community Data. For more information, go to: [Coin Metrics Community Data](/packages/coin-metrics-community-data)

Data coverage can be seen by plugging in your API key at [coverage.coinmetrics.io](https://coverage.coinmetrics.io)

## 2. Learn How to Use Coin Metrics Tools

Coin Metrics offers several ways to access our data.

### For Business Users

You can use our [Data Viz](https://charts.coinmetrics.io/crypto-data/) to create charts dynamically using a point-and-click interface without any code. To learn how to use the charting tool, see our data visualization guide.

[Data Visualization](/data-visualization)

You can directly download files from your browser by adding a "format=csv" in your HTTP request, i.e. `https://api.coinmetrics.io/v4/timeseries/asset-metrics?assets=btc&metrics=PriceUSD,FlowInGEMUSD&frequency=1d&pretty=true&api_key=<your_key>&format=csv`

On Google Sheets, you can use the `IMPORTDATA` function on the formula tab:

```
=IMPORTDATA("https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=CapMrktEstUSD,SplyCur,PriceUSD,CapMrktCurUSD&assets=usdc&frequency=1d&limit_per_asset=1&format=csv&api_key=<your_key>")
```

For more information on exporting data, see the guide: [How To Export Data](/tutorials-and-examples/user-guides/exporting-data)

### For Developers

Check out this introduction that requires no special tools at all.

{% embed url="<https://youtu.be/b-olRlBUepc>" %}
Testing the Coin Metrics API in the Browser
{% endembed %}

You can use our [API](https://docs.coinmetrics.io/api/v4/) for accessing data. To learn more about our API design, see the [API Conventions](/access-our-data/api) page.

[API Conventions](/access-our-data/api)

We offer convenient wrappers for our API in different languages.

#### **Python Users**

[Python API Client](/access-our-data/python-client)

**R Users**

[R API Client](/access-our-data/r-client)

## 3. Use and Explore Coin Metrics Data

You can view examples of how to use Coin Metrics data in the [Tutorials and Examples](/tutorials-and-examples) section.

We recommend new users to read the following guides first to get a basic understanding of Coin Metrics data:

* [Python API Client Walkthrough](/tutorials-and-examples/tutorials/walkthrough_community)
* [Data Visualization Walkthrough](/data-visualization)
* [How To Export Data](/tutorials-and-examples/user-guides/exporting-data)

Refer to our more use-case-specific guides to make the most out of our data:

* [How To Use the Coin Metrics API Efficiently](/tutorials-and-examples/user-guides/how-to-use-the-coin-metrics-api-efficiently-http)
* [How To Migrate From Catalog V1 to Catalog V2](/tutorials-and-examples/user-guides/how-to-migrate-from-catalog-v1-to-catalog-v2)

## 4. Understand our Data

Coin Metrics data is divided into the following types of data:

* **Network Data**: Data sourced directly onchain, primarily from nodes maintained by Coin Metrics.
* **Market Data**: Historical and real-time data from the world’s leading centralized and decentralized (Labs) spot and derivatives crypto exchanges
* **Index Data**: Independent measurements of cryptoasset market performance and network activity
* **Reference Data**: Information about the properties of a token or other entity.

[Network Data Pro Overview](/network-data/network-data-overview)

[Market Data Overview](/market-data/market-data-overview)

[Index Overview](/index-data/index)

[https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/broken-reference/README.md](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/broken-reference/README.md "mention")

More information on each dataset can be found in their respective sections. You can find different metrics or data types by navigating the sidebar e.g. Market Data Overview > Volume > Trusted Volume, Network Data Overview > Addresses > Active Addresses.

Coin Metrics data is heavily featured in our research at <https://coinmetrics.io/insights/>. You can subscribe to our weekly newsletter State of the Network at <https://coinmetrics.substack.com/>.


# Tutorials and Examples

In general, our examples are divided into these sections.

[Tutorials](/tutorials-and-examples/tutorials) are guides for exploring how to use Coin Metrics data. The goal is for a user to achieve a basic familiarity with using Coin Metrics tools and explore what is possible with our data.

[How To Guides](/tutorials-and-examples/user-guides) are instructions for accomplishing specific tasks. These tasks include "*how to export data into a CSV*" or "*how to make the Python API Client run faster*".

[Dashboards](/tutorials-and-examples/dashboard-examples) provide a curated set of charts for specific topics that you can view without having to use the data.


# Tutorials

Below are some demonstartion notebooks and videos based on the products used and topic of exploration.\
\
[**General Tutorials**](#general-tutorials) **:** Covering our data tools and accessing our data\
[**Market Data Tutorials**](#market-data-tutorials)**:** Covering our Market Data Products, Market Data Feed, Market Data Pro\
[**Network Data Tutorials**](#network-data-tutorials)**:** Covering our Network Data Products: Network Data Pro Metrics and Atlas\
[**Defi Data Tutorials**](#defi-data-tutorials)**:** Covering Defi Products that include both Network Data and Market Data

## General Tutorials

### [Python API Client Walkthrough](/tutorials-and-examples/tutorials/walkthrough_community)

**Products:** All

**Summary:** This walkthrough guides you through the basic functionality of the Python API Client, a convenient wrapper of our API for Python users.

**Use Cases**: Any

**Personas**: Analysts, Researchers, Developers

## Market Data Tutorials

### [Getting Started With Market Data](/tutorials-and-examples/tutorials/md_market_data_overview)

**Products:** [Market Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md)

**Summary:** This notebook steps through various market data types available in Market Data Feed, displaying the basic structure of the data & highlighting use cases with examples from our weekly State of the Market. The notebook explains how data is gathered at the most granular level (i.e. trades, order book snapshots) & aggregated upwards to provide convenient hourly/daily metrics across spot, futures, & options markets.

**Use Cases**: Trading, Research

**Personas**: Quant Trader, Market Analyst

### [Comparing Stablecoin Prices Using Different Pricing Methods](/tutorials-and-examples/tutorials/comparing-stablecoin-prices-using-different-pricing-methods)

**Products**: [Market Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md), [CM Prices](/coin-metrics-prices/coin-metrics-prices)

**Summary:** This demo steps through various methodologies for pricing crypto assets, utilizing USDT price fluctuations as a case study. Pricing methodologies include examples from Market Data Feed, such as market-level trades and candles data, as well as aggregated price methodologies from CM Prices, such as Reference Rates, Reference Rate Candles, and Principal Market Price.

**Use Cases**: Fund Administration, Asset Management, Trading, Research

**Personas**: Fund Admin, Oracles, Quant Trader, Market Analyst

### [Comparing Volumes of Exchanges and Assets](/tutorials-and-examples/tutorials/comparing-volumes-of-exchanges-and-assets)

**Products:** [Market Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md)

**Summary:** This notebook shows how Market Data Feed can be used to analyze exchange volume patterns at several levels: 1) examining aggregate volume across all exchanges using Exchange Metrics, 2) analyzing the relative share of specific assets’ volume within an exchange with Market Candles, and 3) investigating trade sizes (i.e. retail vs. institutional) using Market Trades data.

**Use Cases**: Trading, Research

**Personas**: Quant Trader, Market Analyst

### [Getting Started With Futures Data](/tutorials-and-examples/tutorials/md_futures_overview)

**Products:** [Market Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md)

**Summary:** This notebook steps through various derivatives-specific data types across multiple aggregation windows. First, investigate futures open interest for BTC, broken down by exchange. Then examine individual liquidation trades and their effect on price. Finally, view USD-denominated liquidations aggregated at the exchange level, plotted against the total BTC open interest.

**Use Cases**: Trading, Research, Asset Management

**Personas**: Quant Trader, Market Analyst, Fund Admin

### [Getting Started With Options Data](/tutorials-and-examples/tutorials/md_futures_overview-1)

**Products:** [Market Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md)

**Summary:** This github notebook steps through various options-specific data types across multiple aggregation windows.

**Use Cases**: Trading, Research, Asset Management

**Personas**: Quant Trader, Market Analyst, Fund Admin

### [Aggregating Options Data](/tutorials-and-examples/tutorials/md_options_aggregation)

**Products:** [Market Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md)

**Summary:** This notebook shows the basic usage for Coin Metrics options data. First, we show how to find the options markets in our coverage. Then, we calculate volume and open interest. The open interest data is further broken down by puts and calls to look at the put/call ratio in the options markets examined.

**Use Cases**: Trading, Research, Risk Management

**Personas**: Quant Trader, Market Analyst

### [Reconstructing the Order Book from Snapshots and Updates](/tutorials-and-examples/tutorials/order-book-updates)

**Products:** [Market Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md)

**Summary:** This tutorial shows how Coin Metrics serves the order book three ways — historical snapshots, the full stream of historical updates, and a real-time websocket — and how one set of reconstruction code rebuilds the exact book across all of them. It streams a live sample, then replays that exact time window from the historical `updates` dataset, and derives best bid/ask, spread, and depth-near-mid for TCA, microstructure research, and backtests.

**Use Cases**: Trading, Research, Execution & TCA

**Personas**: Quant Trader, Market Microstructure Researcher, Developer

### [Examining Orderbook Depth](/tutorials-and-examples/tutorials/md_orderbook_depth)

**Products:** [Market Data Feed](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md)

**Summary:** This notebook shows how granular bid/ask data (from our hourly order book snapshots) can be aggregated into a +/-2% liquidity profile to quantify and visualize the amount of available liquidity in individual crypto asset markets. The same methodology is applied to generate order book depth charts in our weekly State of the Market report.

**Use Cases**: Trading, Research, Risk Management (Liquidity)

**Personas**: Quant Trader, Market Analyst

### [Aggregating Orderbook Depth to Create Liquidity Metrics](/tutorials-and-examples/tutorials/aggregating-orderbook-depth-to-create-liquidity-metrics)

**Products:** [Market Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md)

**Summary:** This notebook showcases our new aggregated USD bid/ask depth metrics, allowing users to quickly quantify market liquidity without needing to manually sum up order book snapshots. The notebook steps through the process of selecting relevant BTC fiat & stablecoin trading pairs from the catalog and creating a market-wide view of BTC order book liquidity.

**Use Cases**: Trading, Research, Asset Management, Risk Management

**Personas**: Quant Trader, Market Analyst, Operations/Risk Analyst

### [Exploring Options, Open Interest and Volatility Data](/tutorials-and-examples/tutorials/exploring-options-open-interest-and-volatility-data)

**Products:** [Market Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md)

**Summary:** This demo shows how to use options market metadata contained in our Catalog/Markets endpoint with the Implied Volatility endpoint to construct “Volatility Smiles,” a popular way of visualizing the relationship between IV and strike price across various contract expiries. A similar analysis is performed in State of the Network 169, in which volatility smiles are examined prior to the ETH “Merge” to proof of stake.

**Use Cases**: Trading, Research

**Personas**: Quant Trader, Market Analyst

### [Obtaining Futures Market Liquidations](/tutorials-and-examples/tutorials/obtaining-futures-market-liquidations)

**Products:** [Market Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md)

**Summary:** The notebook shows how to obtain liquidation metrics for futures. We show both REST API calls and web socket connections for the same. The video also covers how to use Reference Data and Catalog. It is applicable for all market data / asset metrics.

**Use Cases**: Trading, Research

**Personas**: Quant Trader, Market Analyst

### [Obtaining Predicted Funding Rates for Futures](/tutorials-and-examples/tutorials/obtaining-predicted-funding-rates-for-futures)

**Products:** [Market Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md)

**Summary:** The notebook linked above shows how to obtain predicted funding rates for futures. While the *actual* funding rates don't change very frequently, the *predicted* funding rate is calculated every minute or so and therefore can be a leading indicator for funding rate changes.

**Use Cases**: Trading, Research

**Personas**: Quant Trader, Market Analyst

### [Exploring Availability of Market Data for CME (Derivatives)](/tutorials-and-examples/tutorials/exploring-availability-of-market-data-for-cme-derivatives)

**Products:** [Market Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md)

**Summary:** The notebook linked above shows how to explore data from CME (Chicago Mercantile Exchange), one of the big derivatives exchanges. Options on derivatives are probably the most complicated market instruments available on Coin Metrics, so this may be particularly interesting!

**Use Cases**: Trading, Research

**Personas**: Quant Trader, Market Analyst

### [Analyzing BTC Liquidity](/tutorials-and-examples/tutorials/analyzing-btc-liquidity)

**Products:** [Market Data](/market-data/market-data-overview)\
\
**Summary:** This tutorial introduces core BTC liquidity metrics and explores how to interpret them across different exchanges. It distinguishes between “market” and “exchange-asset” metrics, walks through total BTC trading volume concentration, and examines slippage metrics to understand price impact for various order sizes.\
**Use Cases**: Trading, Research

**Personas**: Quant Trader, Market Analyst, Researchers

## Network Data Tutorials

### [Creating Custom Network Data Metrics Using ATLAS](/tutorials-and-examples/tutorials/atlas_metric_workbench)

**Products:** [Network Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md), [ATLAS](/network-data/atlas-overview)

**Summary:** This demo walks through the various ways ATLAS can be used to construct custom metrics not currently available in Network Data Pro. Examples include 1) basic block-by-block metrics (i.e. block-by-block stablecoin transaction counts), 2) cross-asset metrics (i.e. transactions where USDT + USDC are moved simultaneously), and 3) entity-based metrics (i.e. stablecoin flows to DEX pools).

**Use Cases**: Trading, Research

**Personas**: Quant Trader, On-Chain Researcher

### [Applying Different Types of MarketCap Metrics](/tutorials-and-examples/tutorials/ndp_marketcap_metrics)

**Products:** [Network Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md)

**Summary:** This notebook steps through Coin Metrics various methodologies for indexing the total market capitalization of major crypto assets. Three market cap metrics are highlighted: verified on-chain market cap (CapMrktCurUSD), estimated market cap (CapMrktEstUSD), and free float market cap (CapMrktFFUSD). The notebook discusses asset coverage and trade-offs for each, and shows how the metrics can be used to quantify the total crypto market cap.

**Use Cases**: Research, Asset Management, Passive Trading

**Personas**: On-Chain Researcher, Fund Admin, Trader

### [Comparing the Dominance of Mining Pools Using ATLAS](/tutorials-and-examples/tutorials/atlas_miner_signatures)

**Products:** [Network Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md), [ATLAS](/network-data/atlas-overview)

**Summary:** This demo shows how ATLAS v2’s extra\_data field can be used to extract a block’s “coinbase signature,” which is often used by mining pools to denote blocks they’ve mined. By transforming the data in this field and combining it with other block metadata (i.e. is it an “empty block,” or does it contain transactions?), we can derive a number of interesting mining pool performance and profitability metrics.

**Use Cases**: Research (Bitcoin Mining), Risk Management (Hashrate Concentration)

**Personas**: On-Chain Researcher, Risk Analyst

### [Using Staking Metrics to Get Yield and Staked Supply](/tutorials-and-examples/tutorials/using-staking-metrics-to-get-yield-and-staked-supply)

**Products:** [Network Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md)

**Summary:** This notebook demonstrates how metrics sourced from the Ethereum Execution Layer (ETH) and the Consensus Layer (ETH\_CL) can be combined to create a holistic picture of the Ethereum staking ecosystem. First, we walk through the process of calculating an “estimated validator yield” based on the number of active validators and the average amount of priority tips. Then, we determine the total amount of staked vs. unstaked supply by examining the ETH Staking Contract.

**Use Cases**: Asset Management, Research, Operations/Risk Management, Passive Trading

**Personas**: Fund Admin, On-Chain Researcher, Operations/Risk Analyst, Trader

### [Granular Insights On-Chain Using Hourly Network Data Metrics](/tutorials-and-examples/tutorials/granular-insights-on-chain-using-hourly-network-data-metrics)

**Products:** [Network Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md)

**Summary:** This notebook highlights capabilities enabled by Coin Metrics’ new suite of hourly on-chain metrics. First, we examine the relationship between ETH tx count & “fee burn,” quantifying the amount of Ether removed from circulation during peak periods of activity. Then, investigate the response of BTC fees to slow block times, with median tx fee exhibiting a clear dependence on the mean inter-block interval.

**Use Cases**: Trading, Research, Risk Management

**Personas**: Quant Trader, On-Chain Researcher, Risk Analyst

### [Analyzing Free Float Supply](/tutorials-and-examples/tutorials/analyzing-free-float-supply)

**Products:** [Network Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md)

**Summary:** The notebook shows how to obtain the asset metric "Free Float Supply" for a variety of crypto assets, and how to draw some conclusions by comparing the metric indexed to a particular date. The video covers how to use Reference Data and Catalog. It is applicable for all network data / asset metrics.

**Use Cases**: Research, Index Creation

**Personas**: On-Chain Researcher, Risk Analyst, Trader

## DeFi Data Tutorials

### [Calculating Total Value Locked in Liquidity Pools using DEX Data](/tutorials-and-examples/tutorials/calculating-total-value-locked-in-liquidity-pools-using-dex-data)

**Products:** [Network Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md), [ATLAS](/network-data/atlas-overview), [CM Prices](/coin-metrics-prices/coin-metrics-prices), [DeFi](/network-data/defi-data-overview)

**Summary:** This demo shows how ATLAS can be used to monitor imbalances in decentralized exchange liquidity pool contracts. First, leverage the Reference Data endpoint to extract a list of contract addresses for liquidity pools of interest. Then, use ATLAS to query for balance updates in the pool address. Finally, multiply the supply held in the pool contract by the Coin Metrics Reference Rate to calculate USD-denominated pool TVL.

**Use Cases**: Research, Trading, Risk management

**Personas**: On-Chain Researcher, Quant Trader, Operations/Risk Analyst

### [Calculating DEX Liquidity Pool Fees and Volumes](/tutorials-and-examples/tutorials/calculating-dex-liquidity-pool-fees-and-volumes)

**Products:** [Network Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md), [ATLAS](/network-data/atlas-overview), [Market Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md), [DeFi](/network-data/defi-data-overview)

**Summary:** This notebook explores Coin Metrics’ coverage of decentralized exchanges like Uniswap & Sushiswap. First, examine a list of available liquidity pools, supplemented with contract addresses in the catalog’s DEX-specific fields. Then, dig into swaps data, estimating the number of unique buyers with an added beneficiary field. Finally, pull aggregated market candles to easily compare Uniswap volume against equivalent Coinbase markets.

**Use Cases**: Research, Trading

**Personas**: OnChain Researcher, Quant Trader

### [Analyzing DeFi Protocol Balance Sheets](/tutorials-and-examples/tutorials/analyzing-defi-protocol-balance-sheets)

**Products:** [Network Data](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/tutorials-and-examples/tutorials/broken-reference/README.md), [DeFi](/network-data/defi-data-overview)

**Summary:** This notebook explores our newest DeFi capabilities, unlocking a detailed view of Total Value Locked (TVL) for major lending protocols like AAVE and Compound. After highlighting a set of key “Protocol Health Metrics,” the notebook shows how assets & liabilities can be extracted and transformed into novel TVL metrics.

**Use Cases**: Research, Risk Management

**Personas**: On-Chain Researcher, Operations/Risk Analyst


# Python API Client Walkthrough

## Python API Client Walkthrough

*Last Updated: Version `2024.08.20`*

This notebook demonstrates basic functionality offered by the Coin Metrics Python API Client using Coin Metrics Community Data.

Coin Metrics offers a vast assortment of data for hundreds of cryptoassets. The Python API Client allows for easy access to this data using Python without needing to create your own wrappers using `requests` and other such libraries.

### Prerequisites

First, Python must be installed. Download and install from [python.org](https://www.python.org/downloads/). The Coin Metrics API Client is best used with Python 3.8 or later.

Then, install the Python API Client:

`pip install coinmetrics-api-client`

Some of the optional libraries such as pandas, numpy, and seaborn are used in the notebook to make the examples more interactive. These libraries are not required to use the Coin Metrics API Client.

You are now ready to run the code in the rest of the notebook.

### Resources

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics.
* The [Coin Metrics Product Documentation](https://docs.coinmetrics.io/) gives detailed, conceptual explanations of the data that Coin Metrics offers.
* The [API Spec](https://docs.coinmetrics.io/python-api-client/reference) contains a full list of functions.
* The [Coverage Tool](https://coverage.coinmetrics.io/) shows what assets, metrics, and other data types are covered.

### Setup

```python
from os import environ
import sys
import pandas as pd
import numpy as np
import seaborn as sns
import logging
from datetime import date, datetime, timedelta
from coinmetrics.api_client import CoinMetricsClient

import matplotlib.pyplot as plt
# %matplotlib inline
```

```python
logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S'
)
```

```python
# We recommend privately storing your API key in your local environment.
# Uncomment below if you have an API Key. Otherwise we will use Community data.
# try:
#     api_key = environ["CM_API_KEY"]
#     logging.info("Using API key found in environment")
# except KeyError:
#     api_key = ""
#     logging.info("API key not found. Using community client")

client = CoinMetricsClient()
# client = CoinMetricsClient(api_key)
```

```python
assets = ['btc', 'eth']
metrics = ['ReferenceRateUSD', 'CapMrktEstUSD']
start_time = datetime(year=2024, month=9, day=1)
end_time = datetime(year=2024, month=9, day=30)
asset_mapping = {i: assets[i] for i in range(len(assets))}
```

```
{0: 'btc', 1: 'eth'}
```

### Catalogs

The Coin Metrics API contains two types of catalog endpoints (Python client functions in paranthesis): the `catalog` (`catalog_*_v2`) and `catalog-all` (`catalog_full_*_v2`).

The `catalog` endpoint displays the set of data available to your API key. The `catalog-all` endpoint displays the full set of data for our dataset.

```python
asset_metrics_catalog = client.catalog_asset_metrics_v2(assets=assets).to_list()
full_asset_metrics_catalog = client.catalog_full_asset_metrics_v2(assets=assets).to_list()
```

Catalog objects return a list of dictionaries. For `catalog_asset_metrics_v2`, each element of the list is an asset, while each dictionary is a set of metadata for that specific asset.

```python
print(f"Asset Metrics Catalog metadata includes: {list(asset_metrics_catalog[0].keys())}")

for i in asset_mapping:
    print(f"Asset {asset_mapping[i]} has {len(asset_metrics_catalog[i]['metrics'])} metrics in catalog.")
    print(f"Asset {asset_mapping[i]} has {len(full_asset_metrics_catalog[i]['metrics'])} metrics in catalog-all.")
```

```
Asset Metrics Catalog metadata includes: ['asset', 'metrics']
Asset btc has 147 metrics in catalog.
Asset btc has 696 metrics in catalog-all.
Asset eth has 146 metrics in catalog.
Asset eth has 699 metrics in catalog-all.
```

```
Asset Metrics Catalog metadata includes: ['asset', 'metrics']
Asset btc has 147 metrics in catalog.
Asset btc has 513 metrics in catalog-all.
Asset eth has 146 metrics in catalog.
Asset eth has 500 metrics in catalog-all.
```

For more details on what metrics are covered, see [Coverage](https://coverage.coinmetrics.io/asset-metrics-v2)

### Getting Timeseries Data

Next, we will pull timeseries data. Typically there are two types of timeseries data that you can pull: raw observations such as trades and aggregated metrics. We will explore these two below.

#### Asset Metrics

First, we will use the [`asset-metrics`](https://docs.coinmetrics.io/api/v4/#tag/Timeseries/operation/getTimeseriesAssetMetrics) endpoint to get metrics for BTC and ETH.

```python
btc_metrics = [m['metric'] for m in asset_metrics_catalog[0]['metrics']]
eth_metrics = [m['metric'] for m in asset_metrics_catalog[1]['metrics']]
```

You can bound your query by time like below:

```python
df_asset_metrics = client.get_asset_metrics(
    assets=assets, 
    metrics=metrics, 
    start_time=start_time,
    end_time=end_time
).to_dataframe()
```

```python
df_asset_metrics.head()
```

|   | asset | time                      | CapMrktEstUSD        | ReferenceRateUSD |
| - | ----- | ------------------------- | -------------------- | ---------------- |
| 0 | btc   | 2024-09-01 00:00:00+00:00 | 1132518348250.186279 | 58959.926273     |
| 1 | btc   | 2024-09-02 00:00:00+00:00 | 1168286956855.852539 | 57349.080718     |
| 2 | btc   | 2024-09-03 00:00:00+00:00 | 1138274882375.744873 | 59159.023888     |
| 3 | btc   | 2024-09-04 00:00:00+00:00 | 1146114653782.878418 | 57637.775444     |
| 4 | btc   | 2024-09-05 00:00:00+00:00 | 1108213762229.152832 | 58033.39897      |

|   | asset | time                      | CapMrktEstUSD        | ReferenceRateUSD |
| - | ----- | ------------------------- | -------------------- | ---------------- |
| 0 | btc   | 2024-08-15 00:00:00+00:00 | 1137894996787.05249  | 58840.64668      |
| 1 | btc   | 2024-08-16 00:00:00+00:00 | 1163252605521.227783 | 57644.187688     |
| 2 | btc   | 2024-08-17 00:00:00+00:00 | 1172900035803.550781 | 58927.276509     |
| 3 | btc   | 2024-08-18 00:00:00+00:00 | 1160659435495.434814 | 59414.674335     |
| 4 | btc   | 2024-08-19 00:00:00+00:00 | 1172894781992.733887 | 58793.206146     |

```python
df_asset_metrics.loc[df_asset_metrics.asset=='btc'].plot(x='time', y='ReferenceRateUSD')
```

<figure><img src="/files/HSco8KIc1hxjRvN3CGej" alt=""><figcaption></figcaption></figure>

Coin Metrics supports several metrics for various data types such as exchanges, markets, and asset-pairs.

You can also bound your queries by using the `limit` parameter.

```python
df_asset_metrics_limit = client.get_asset_metrics(
    assets=assets, 
    metrics=btc_metrics[:5], 
    start_time=start_time,
    end_time=end_time,
    limit_per_asset=2
).to_dataframe()
```

```python
df_asset_metrics_limit
```

|   | asset | time                      | AdrActCnt | AdrBal1in100KCnt | AdrBal1in100MCnt | AdrBal1in10BCnt | AdrBal1in10KCnt |
| - | ----- | ------------------------- | --------- | ---------------- | ---------------- | --------------- | --------------- |
| 0 | btc   | 2024-09-01 00:00:00+00:00 | 660770    | 9283             | 3046587          | 20365534        | 973             |
| 1 | btc   | 2024-09-02 00:00:00+00:00 | 717673    | 9284             | 3046904          | 20359814        | 972             |
| 2 | eth   | 2024-09-01 00:00:00+00:00 | 548611    | 6907             | 1836310          | 27996184        | 1221            |
| 3 | eth   | 2024-09-02 00:00:00+00:00 | 488354    | 6902             | 1836617          | 28008369        | 1218            |

|   | asset | time                      | AdrActCnt | AdrBal1in100KCnt | AdrBal1in100MCnt | AdrBal1in10BCnt | AdrBal1in10KCnt |
| - | ----- | ------------------------- | --------- | ---------------- | ---------------- | --------------- | --------------- |
| 0 | btc   | 2024-08-15 00:00:00+00:00 | 715632    | 9229             | 3054724          | 20292616        | 973             |
| 1 | btc   | 2024-08-16 00:00:00+00:00 | 700335    | 9231             | 3055010          | 20300505        | 977             |
| 2 | eth   | 2024-08-15 00:00:00+00:00 | 603353    | 6862             | 1837926          | 27972812        | 1226            |
| 3 | eth   | 2024-08-16 00:00:00+00:00 | 541263    | 6871             | 1837366          | 27962507        | 1223            |

#### Market Observations

The other common timeseries data type that you will encounter are individual observations.

First, we will need to familiarize ourselves with the market convention which we can find on faqs. You can see a full list of markets by using the `reference-data` endpoint.

```python
df_coinbase_btc_markets = client.reference_data_markets(asset='btc', exchange='coinbase').to_dataframe()
```

```python
df_coinbase_btc_markets.head()
```

|   | market                  | exchange | base  | quote | pair      | symbol    | type | size\_asset | margin\_asset | strike | ... | order\_price\_increment | order\_price\_min | order\_price\_max | order\_size\_min | order\_taker\_fee | order\_maker\_fee | margin\_trading\_enabled | experimental | base\_native | quote\_native |
| - | ----------------------- | -------- | ----- | ----- | --------- | --------- | ---- | ----------- | ------------- | ------ | --- | ----------------------- | ----------------- | ----------------- | ---------------- | ----------------- | ----------------- | ------------------------ | ------------ | ------------ | ------------- |
| 0 | coinbase-1inch-btc-spot | coinbase | 1inch | btc   | 1inch-btc | 1INCH-BTC | spot | \<NA>       | \<NA>         | \<NA>  | ... | 0.0                     | 0.0               | \<NA>             | 0.000016         | \<NA>             | \<NA>             | False                    | \<NA>        | \<NA>        | \<NA>         |
| 1 | coinbase-aave-btc-spot  | coinbase | aave  | btc   | aave-btc  | AAVE-BTC  | spot | \<NA>       | \<NA>         | \<NA>  | ... | 0.000001                | 0.000001          | \<NA>             | 0.000016         | \<NA>             | \<NA>             | False                    | \<NA>        | \<NA>        | \<NA>         |
| 2 | coinbase-ada-btc-spot   | coinbase | ada   | btc   | ada-btc   | ADA-BTC   | spot | \<NA>       | \<NA>         | \<NA>  | ... | 0.0                     | 0.0               | \<NA>             | 0.000016         | \<NA>             | \<NA>             | False                    | \<NA>        | \<NA>        | \<NA>         |
| 3 | coinbase-algo-btc-spot  | coinbase | algo  | btc   | algo-btc  | ALGO-BTC  | spot | \<NA>       | \<NA>         | \<NA>  | ... | 0.0                     | 0.0               | \<NA>             | 0.000016         | \<NA>             | \<NA>             | False                    | \<NA>        | \<NA>        | \<NA>         |
| 4 | coinbase-ankr-btc-spot  | coinbase | ankr  | btc   | ankr-btc  | ANKR-BTC  | spot | \<NA>       | \<NA>         | \<NA>  | ... | 0.0                     | 0.0               | \<NA>             | 0.000016         | \<NA>             | \<NA>             | False                    | \<NA>        | \<NA>        | \<NA>         |

5 rows × 39 columns

|   | market                  | exchange | base  | quote | pair      | symbol    | type | size\_asset | margin\_asset | strike | ... | order\_amount\_min | order\_amount\_max | order\_price\_increment | order\_price\_min | order\_price\_max | order\_size\_min | order\_taker\_fee | order\_maker\_fee | margin\_trading\_enabled | experimental |
| - | ----------------------- | -------- | ----- | ----- | --------- | --------- | ---- | ----------- | ------------- | ------ | --- | ------------------ | ------------------ | ----------------------- | ----------------- | ----------------- | ---------------- | ----------------- | ----------------- | ------------------------ | ------------ |
| 0 | coinbase-1inch-btc-spot | coinbase | 1inch | btc   | 1inch-btc | 1INCH-BTC | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | 0.0                     | 0.0               | \<NA>             | 0.000016         | \<NA>             | \<NA>             | False                    | \<NA>        |
| 1 | coinbase-aave-btc-spot  | coinbase | aave  | btc   | aave-btc  | AAVE-BTC  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | 0.000001                | 0.000001          | \<NA>             | 0.000016         | \<NA>             | \<NA>             | False                    | \<NA>        |
| 2 | coinbase-ada-btc-spot   | coinbase | ada   | btc   | ada-btc   | ADA-BTC   | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | 0.0                     | 0.0               | \<NA>             | 0.000016         | \<NA>             | \<NA>             | False                    | \<NA>        |
| 3 | coinbase-algo-btc-spot  | coinbase | algo  | btc   | algo-btc  | ALGO-BTC  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | 0.0                     | 0.0               | \<NA>             | 0.000016         | \<NA>             | \<NA>             | False                    | \<NA>        |
| 4 | coinbase-ankr-btc-spot  | coinbase | ankr  | btc   | ankr-btc  | ANKR-BTC  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | 0.0                     | 0.0               | \<NA>             | 0.000016         | \<NA>             | \<NA>             | False                    | \<NA>        |

5 rows × 37 columns

We can then pass these markets onto the `timeseries/market-*` endpoints. Below is an example of how to pull individual market trades.

```python
df_coinbase_btc_trades = client.get_market_trades(
    markets=["coinbase-btc-usd-spot"],
    start_time=datetime.now()-timedelta(seconds=60),
    end_time=datetime.now(),
).to_dataframe()
```

```python
df_coinbase_btc_trades.head()
```

|   | market                | time                             | coin\_metrics\_id | amount   | price    | database\_time                   | side |
| - | --------------------- | -------------------------------- | ----------------- | -------- | -------- | -------------------------------- | ---- |
| 0 | coinbase-btc-usd-spot | 2024-10-25 15:22:44.919441+00:00 | 705966854         | 0.000004 | 68353.27 | 2024-10-25 15:22:45.721609+00:00 | buy  |
| 1 | coinbase-btc-usd-spot | 2024-10-25 15:22:44.919441+00:00 | 705966855         | 0.000012 | 68353.27 | 2024-10-25 15:22:45.721609+00:00 | buy  |
| 2 | coinbase-btc-usd-spot | 2024-10-25 15:22:44.919441+00:00 | 705966856         | 0.002187 | 68354.37 | 2024-10-25 15:22:45.721609+00:00 | buy  |
| 3 | coinbase-btc-usd-spot | 2024-10-25 15:22:44.919441+00:00 | 705966857         | 0.002523 | 68354.38 | 2024-10-25 15:22:45.721609+00:00 | buy  |
| 4 | coinbase-btc-usd-spot | 2024-10-25 15:22:45.078614+00:00 | 705966858         | 0.001043 | 68353.27 | 2024-10-25 15:22:45.721609+00:00 | buy  |

|   | market                | time                             | coin\_metrics\_id | amount   | price    | database\_time                   | side |
| - | --------------------- | -------------------------------- | ----------------- | -------- | -------- | -------------------------------- | ---- |
| 0 | coinbase-btc-usd-spot | 2024-09-13 16:55:02.663733+00:00 | 691698441         | 0.008    | 59491.6  | 2024-09-13 16:55:03.253369+00:00 | sell |
| 1 | coinbase-btc-usd-spot | 2024-09-13 16:55:02.670644+00:00 | 691698442         | 0.008    | 59491.61 | 2024-09-13 16:55:03.253369+00:00 | buy  |
| 2 | coinbase-btc-usd-spot | 2024-09-13 16:55:03.057923+00:00 | 691698443         | 0.001186 | 59491.61 | 2024-09-13 16:55:03.771512+00:00 | buy  |
| 3 | coinbase-btc-usd-spot | 2024-09-13 16:55:03.143752+00:00 | 691698444         | 0.15742  | 59491.6  | 2024-09-13 16:55:03.771512+00:00 | sell |
| 4 | coinbase-btc-usd-spot | 2024-09-13 16:55:03.143816+00:00 | 691698445         | 0.076281 | 59491.6  | 2024-09-13 16:55:03.771512+00:00 | sell |

#### Examples from State of the Network

The Python API Client is often used for transforming data for [State of the Network](https://coinmetrics.substack.com/). Below are some examples of data transformations done to produce the data visualizations.

**Example 1: Get returns by coin in the CM reference rates universe over the last 10-years**

In [State of the Network #128](https://coinmetrics.substack.com/p/coin-metrics-state-of-the-network-53b), we looked at the returns for each asset dating back the last 10 years.

![returns-10-yr](https://cdn.substack.com/image/fetch/f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2F38b38adb-c4b7-43f6-a387-0cbae028861a_985x525.png)

We can generate this data by weaving in the `catalog_asset_metrics_v2` and `get_asset_metrics` endpoint. The code snippets below demonstrate how to do this with a small list of assets.

```python

# Get all assets that have a reference rate 
assets_refrate = client.catalog_asset_metrics_v2(metrics="ReferenceRateUSD")
# Get list of assets with daily ref rate 
# uncomment the top line to look at *every* asset with reference rates
# asset_with_ref_rates = assets_refrate[0]["frequencies"][0]["assets"]
asset_with_ref_rates = ['btc', 'eth', 'bnb', 'ada', 'doge', 'xrp']
#Query API for prices, daily CM reference rates as dataframe
metrics = "ReferenceRateUSD"
frequency = "1d"

logging.info("Getting prices...")
df_prices = client.get_asset_metrics(
    assets=asset_with_ref_rates,
    metrics=metrics,
    frequency=frequency,
    start_time=start_time,
    end_time=end_time
).to_dataframe()
# Assign datatypes
df_prices["time"] = pd.to_datetime(df_prices.time)
df_prices["ReferenceRateUSD"] = df_prices.ReferenceRateUSD.astype(float)

# Reshape dataset so assets are in columns, dates are the rows, and the values are prices
df_prices_pivot = df_prices.pivot(
    index="time",
    columns="asset",
    values="ReferenceRateUSD"
)

# Index each asset's time series to 1 
for col in df_prices_pivot.columns:
    logging.info(f"Calculating Reference rate for {col}....")
    # First price in time series
    first_price = df_prices_pivot[df_prices_pivot[col].notnull()][col].iloc[0]
    # Index time series
    df_prices_pivot[col] = df_prices_pivot[col]/first_price
    # Fill forward for Null values
    df_prices_pivot[col] = df_prices_pivot[col].ffill()
```

```
2024-10-25 15:23:44 INFO     Getting prices...
2024-10-25 15:23:45 INFO     Calculating Reference rate for ada....
2024-10-25 15:23:45 INFO     Calculating Reference rate for bnb....
2024-10-25 15:23:45 INFO     Calculating Reference rate for btc....
2024-10-25 15:23:45 INFO     Calculating Reference rate for doge....
2024-10-25 15:23:45 INFO     Calculating Reference rate for eth....
2024-10-25 15:23:45 INFO     Calculating Reference rate for xrp....
```

```
2024-09-13 16:56:10 INFO     Getting prices...
2024-09-13 16:56:11 INFO     Calculating Reference rate for ada....
2024-09-13 16:56:11 INFO     Calculating Reference rate for bnb....
2024-09-13 16:56:11 INFO     Calculating Reference rate for btc....
2024-09-13 16:56:11 INFO     Calculating Reference rate for doge....
2024-09-13 16:56:11 INFO     Calculating Reference rate for eth....
2024-09-13 16:56:11 INFO     Calculating Reference rate for xrp....
```

```python
df_prices_pivot.tail()
```

| asset                     | ada      | bnb      | btc      | doge     | eth      | xrp      |
| ------------------------- | -------- | -------- | -------- | -------- | -------- | -------- |
| time                      |          |          |          |          |          |          |
| 2024-09-26 00:00:00+00:00 | 1.102137 | 1.100617 | 1.069534 | 1.070347 | 1.024427 | 1.030510 |
| 2024-09-27 00:00:00+00:00 | 1.162204 | 1.118540 | 1.103424 | 1.164025 | 1.046276 | 1.042040 |
| 2024-09-28 00:00:00+00:00 | 1.165724 | 1.141772 | 1.115465 | 1.222446 | 1.073526 | 1.040046 |
| 2024-09-29 00:00:00+00:00 | 1.158667 | 1.127693 | 1.115512 | 1.267128 | 1.064176 | 1.084632 |
| 2024-09-30 00:00:00+00:00 | 1.151477 | 1.119118 | 1.112921 | 1.232789 | 1.056856 | 1.133519 |

| asset                     | ada      | bnb      | btc      | doge     | eth      | xrp      |
| ------------------------- | -------- | -------- | -------- | -------- | -------- | -------- |
| time                      |          |          |          |          |          |          |
| 2024-09-09 00:00:00+00:00 | 1.008826 | 0.960197 | 0.932336 | 0.936040 | 0.862489 | 0.930312 |
| 2024-09-10 00:00:00+00:00 | 1.024744 | 0.990748 | 0.971026 | 1.011867 | 0.885729 | 0.948722 |
| 2024-09-11 00:00:00+00:00 | 1.024288 | 0.988299 | 0.980011 | 1.001351 | 0.896031 | 0.950876 |
| 2024-09-12 00:00:00+00:00 | 1.051865 | 1.011061 | 0.975672 | 0.987734 | 0.878328 | 0.940610 |
| 2024-09-13 00:00:00+00:00 | 1.061901 | 1.036981 | 0.987831 | 1.001874 | 0.885837 | 0.987858 |

#### Example 2: Get daily spot trading volume on Coinbase for USDC markets

In [State of the Network #126](https://coinmetrics.substack.com/p/coin-metrics-state-of-the-network-issue-126), we looked at spot volume on trusted exchanges over time.

![vol-over-time](https://substackcdn.com/image/fetch/$s_!XF68!,f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2F011acfa6-6b3e-4c51-bbc8-d0354235e005_1200x709.png)

We can replicate similar data behind chart using just coinbase spot markets at 2021. Here, we derive volume from our `get_market_candles` endpoint.

```python
candles_coinbase = client.get_market_candles(
    markets="coinbase-*-usdc-spot", # wildcards can be passed to get all asset pairs
    start_time="2024-01-01",
    end_time="2024-09-30",
    frequency="1d"
).to_dataframe()
candles_coinbase["candle_usd_volume"] = candles_coinbase.candle_usd_volume.astype(float)
candles_coinbase["time"] = pd.to_datetime(candles_coinbase.time)
```

```
2024-10-25 15:23:45 INFO     Sleeping for a rate limit window because 429 (too many requests) error was returned. Pleasesee Coin Metrics APIV4 documentation for more information: https://docs.coinmetrics.io/api/v4/#tag/Rate-limits
```

```python
candles_coinbase.head()
```

|   | market                  | time                      | price\_open | price\_close | price\_high | price\_low | vwap     | volume    | candle\_usd\_volume | candle\_trades\_count |
| - | ----------------------- | ------------------------- | ----------- | ------------ | ----------- | ---------- | -------- | --------- | ------------------- | --------------------- |
| 0 | coinbase-eurc-usdc-spot | 2024-08-23 00:00:00+00:00 | 1.121       | 1.119        | 1.121       | 1.118      | 1.120121 | 997787.0  | 1.117636e+06        | 140                   |
| 1 | coinbase-eurc-usdc-spot | 2024-08-24 00:00:00+00:00 | 1.12        | 1.12         | 1.13        | 1.119      | 1.120547 | 1122215.0 | 1.257359e+06        | 412                   |
| 2 | coinbase-eurc-usdc-spot | 2024-08-25 00:00:00+00:00 | 1.121       | 1.12         | 1.132       | 1.119      | 1.121433 | 2796276.0 | 3.135467e+06        | 1727                  |
| 3 | coinbase-eurc-usdc-spot | 2024-08-26 00:00:00+00:00 | 1.12        | 1.118        | 1.126       | 1.116      | 1.118883 | 1999004.0 | 2.236406e+06        | 882                   |
| 4 | coinbase-eurc-usdc-spot | 2024-08-27 00:00:00+00:00 | 1.117       | 1.119        | 1.122       | 1.116      | 1.118849 | 1505368.0 | 1.684066e+06        | 1227                  |

|   | market                  | time                      | price\_open | price\_close | price\_high | price\_low | vwap     | volume    | candle\_usd\_volume | candle\_trades\_count |
| - | ----------------------- | ------------------------- | ----------- | ------------ | ----------- | ---------- | -------- | --------- | ------------------- | --------------------- |
| 0 | coinbase-eurc-usdc-spot | 2024-08-23 00:00:00+00:00 | 1.121       | 1.119        | 1.121       | 1.118      | 1.120121 | 997787.0  | 1.117636e+06        | 140                   |
| 1 | coinbase-eurc-usdc-spot | 2024-08-24 00:00:00+00:00 | 1.12        | 1.12         | 1.13        | 1.119      | 1.120547 | 1122215.0 | 1.257357e+06        | 412                   |
| 2 | coinbase-eurc-usdc-spot | 2024-08-25 00:00:00+00:00 | 1.121       | 1.12         | 1.132       | 1.119      | 1.121433 | 2796276.0 | 3.135472e+06        | 1727                  |
| 3 | coinbase-eurc-usdc-spot | 2024-08-26 00:00:00+00:00 | 1.12        | 1.118        | 1.126       | 1.116      | 1.118883 | 1999004.0 | 2.236419e+06        | 882                   |
| 4 | coinbase-eurc-usdc-spot | 2024-08-27 00:00:00+00:00 | 1.117       | 1.119        | 1.122       | 1.116      | 1.118849 | 1505368.0 | 1.684074e+06        | 1227                  |

We can also break this down by month. Note that for this example, the volume numbers will look smaller because we are using fewer exchanges.

![vol-by-month](https://cdn.substack.com/image/fetch/f_auto,q_auto:good,fl_progressive:steep/https%3A%2F%2Fbucketeer-e05bbc84-baa3-437e-9518-adb32be77984.s3.amazonaws.com%2Fpublic%2Fimages%2Fdd12c9e3-9728-478b-b8aa-7136f2aaae10_985x525.png)

```python
month_order = [
    'January', 'February', 'March', 'April', 'May', 'June', 
    'July', 'August', 'September', 'October', 'November', 'December'
]


candles_coinbase.groupby(
    candles_coinbase.time.dt.month_name()
)[['candle_usd_volume']].sum().reindex(month_order).dropna()
```

|           | candle\_usd\_volume |
| --------- | ------------------- |
| time      |                     |
| January   | 4.401994e+08        |
| February  | 1.227417e+08        |
| March     | 2.522828e+08        |
| April     | 1.476761e+08        |
| May       | 2.575348e+08        |
| June      | 9.312749e+08        |
| July      | 1.331209e+09        |
| August    | 2.433962e+09        |
| September | 1.849214e+09        |


# Getting Started With Market Data

![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/Demo%20Asset%20Resources/CM-Demo-market_data_overview-Cover.png)

Coin Metrics **Market Data Feed** provides access to historical and real-time data from the world’s leading spot and derivatives crypto exchanges. We offer all of the fundamental market-related data types including tick-by-tick trades, quotes, order book snapshots, candles, and more.

The example charts showcased in this notebook are presented on a weekly basis in our [State of the Market](https://coinmetrics.io/insights/state-of-the-market/) newsletter.

#### Resources

This notebook demonstrates basic functionality offered by the Coin Metrics Python API Client and [Market Data Feed](https://coinmetrics.io/market-data-feed/).

Coin Metrics offers a vast assortment of data for hundreds of cryptoassets. The Python API Client allows for easy access to this data using Python without needing to create your own wrappers using `requests` and other such libraries.

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics.
* The [Coin Metrics Product Docs](https://docs.coinmetrics.io/) gives detailed, conceptual explanations of the data that Coin Metrics offers.
* The [Python API Client Spec](https://docs.coinmetrics.io/python-api-client/reference) contains a full list of functions..

### Setup

```python
from os import environ
import sys
from datetime import date, datetime, timedelta
import logging

import pandas as pd
import numpy as np
import seaborn as sns
from coinmetrics.api_client import CoinMetricsClient
import logging
import matplotlib.pyplot as plt

# %matplotlib inline
```

```python
sns.set_theme()
sns.set(rc={"figure.figsize":(12,8)})
# pd.set_option("display.notebook_repr_html", False)
```

```python
logging.basicConfig(
    format="%(asctime)s %(levelname)-8s %(message)s",
    level=logging.INFO,
    datefmt="%Y-%m-%d %H:%M:%S"
)
```

```python
# We recommend privately storing your API key in your local environment.
try:
    api_key = environ["CM_API_KEY"]
    logging.info("Using API key found in environment")
except KeyError:
    api_key = ""
    logging.info("API key not found. Using community client")
client = CoinMetricsClient(api_key)
```

```
2024-10-25 14:48:22 INFO     Using API key found in environment
```

## Reference Data/Catalog Endpoints

The `catalog` endpoints display the set of data available to your API key. The `catalog-all` endpoints display the full set of data for our data set.

```python
btc_market_catalog = client.reference_data_markets(
    base="btc",
    type="spot",
    exchange="binance"
).to_dataframe()
btc_market_catalog.tail(5)
```

```
                      market exchange base    quote         pair   symbol  \
26     binance-btc-usdt-spot  binance  btc     usdt     btc-usdt  BTCUSDT   
27      binance-btc-ust-spot  binance  btc      ust      btc-ust   BTCUST   
28      binance-btc-vai-spot  binance  btc      vai      btc-vai     <NA>   
29  binance-btc-vai_vai-spot  binance  btc  vai_vai  btc-vai_vai   BTCVAI   
30      binance-btc-zar-spot  binance  btc      zar      btc-zar   BTCZAR   

    type  size_asset  margin_asset  strike  ...  order_price_increment  \
26  spot        <NA>          <NA>    <NA>  ...                   0.01   
27  spot        <NA>          <NA>    <NA>  ...                   0.01   
28  spot        <NA>          <NA>    <NA>  ...                   <NA>   
29  spot        <NA>          <NA>    <NA>  ...                   0.01   
30  spot        <NA>          <NA>    <NA>  ...                    1.0   

    order_price_min  order_price_max  order_size_min  order_taker_fee  \
26             0.01          1000000               5             <NA>   
27             0.01          1000000              10             <NA>   
28             <NA>             <NA>            <NA>             <NA>   
29             0.01          1000000              10             <NA>   
30              1.0         99928191             100             <NA>   

    order_maker_fee  margin_trading_enabled  experimental  base_native  \
26             <NA>                    <NA>          <NA>         <NA>   
27             <NA>                    <NA>          <NA>         <NA>   
28             <NA>                    <NA>          <NA>         <NA>   
29             <NA>                    <NA>          <NA>         <NA>   
30             <NA>                    <NA>          <NA>         <NA>   

    quote_native  
26          <NA>  
27          <NA>  
28          <NA>  
29          <NA>  
30          <NA>  

[5 rows x 39 columns]
```

```python
print(f"Market reference_data metadata includes: {list(btc_market_catalog.keys())}")
```

```
Market catalog metadata includes: ['market', 'exchange', 'base', 'quote', 'pair', 'symbol', 'type', 'size_asset', 'margin_asset', 'strike', 'option_contract_type', 'is_european', 'contract_size', 'tick_size', 'multiplier_size', 'listing', 'expiration', 'settlement_price', 'pool_config_id', 'contract_address', 'fee', 'price_includes_fee', 'variable_fee', 'base_address', 'quote_address', 'status', 'order_amount_increment', 'order_amount_min', 'order_amount_max', 'order_price_increment', 'order_price_min', 'order_price_max', 'order_size_min', 'order_taker_fee', 'order_maker_fee', 'margin_trading_enabled', 'experimental', 'base_native', 'quote_native']
```

***

## Example 1: Returns by coin in the CM Reference Rates universe

***

We offer reference rates quoted in USD, Euro, Bitcoin, and Ethereum. We now support these quote currencies for our entire reference rates coverage universe which can be found on [coverage.coinmetrics.io](http://coverage.coinmetrics.io/)

**Fig. 1 - 7 Day Price Change chart from State of the Market**\
![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/State%20of%20the%20Market%20-%20Chart%20Examples/Mini-RefRate-Returns.png)

```python
# Get all assets that have a reference rate 
assets_refrate = client.catalog_asset_metrics_v2(metrics="ReferenceRateUSD").to_dataframe()
assets_refrate[["metric","frequency","asset"]]
```

```
                metric    frequency    asset
0     ReferenceRateUSD           1s     1cat
1     ReferenceRateUSD           1m     1cat
2     ReferenceRateUSD           1h     1cat
3     ReferenceRateUSD           1d     1cat
4     ReferenceRateUSD  1d-ny-close     1cat
...                ...          ...      ...
6060  ReferenceRateUSD           1s  ztx_ztx
6061  ReferenceRateUSD           1m  ztx_ztx
6062  ReferenceRateUSD           1h  ztx_ztx
6063  ReferenceRateUSD           1d  ztx_ztx
6064  ReferenceRateUSD  1d-ny-close  ztx_ztx

[6065 rows x 3 columns]
```

```python
print("\nNumber of unique Reference Rate assets: " + str(len(pd.unique(assets_refrate["asset"])))+"\n")
```

```
Number of unique Reference Rate assets: 1213
```

We can retrieve Reference Rates from the `get_asset_metrics` endpoint. The code snippets below demonstrate how to do this with a small list of assets.

```python
# Retrieve Reference Rate
df_prices = client.get_asset_metrics(
    assets=["btc", "eth", "bnb", "ada", "doge", "xrp"],
    metrics="ReferenceRateUSD",
    frequency="1d",
    start_time="2022-08-10",
    end_time="2022-08-17"
).to_dataframe()

# Reshape dataset so assets are in columns, dates are the rows, and the values are prices
df_prices_pivot = df_prices.pivot(index="time",columns="asset",values="ReferenceRateUSD")
```

```python
df_prices_pivot.head(3)
```

```
asset                          ada         bnb           btc       doge  \
time                                                                      
2022-08-10 00:00:00+00:00  0.514033  325.442291  23186.291746  0.069148   
2022-08-11 00:00:00+00:00  0.536694  328.034925  23923.058483  0.071153   
2022-08-12 00:00:00+00:00  0.530497  323.337253  23934.439056    0.0708   

asset                             eth       xrp   
time                                              
2022-08-10 00:00:00+00:00  1703.992249  0.368363  
2022-08-11 00:00:00+00:00  1850.829961  0.380704  
2022-08-12 00:00:00+00:00  1878.113096  0.379859  
```

```python
# Index each asset"s time series to 1 
for col in df_prices_pivot.columns:
    logging.info(f"Calculating returns for {col}....")
    first_price = df_prices_pivot[df_prices_pivot[col].notnull()][col].iloc[0]
    df_prices_pivot[col] = df_prices_pivot[col]/first_price
    df_prices_pivot[col] = df_prices_pivot[col].ffill()
```

```
2024-10-25 14:48:25 INFO     Calculating returns for ada....
2024-10-25 14:48:25 INFO     Calculating returns for bnb....
2024-10-25 14:48:25 INFO     Calculating returns for btc....
2024-10-25 14:48:25 INFO     Calculating returns for doge....
2024-10-25 14:48:25 INFO     Calculating returns for eth....
2024-10-25 14:48:25 INFO     Calculating returns for xrp....
```

```python
df_prices_pivot
```

```
asset                          ada       bnb       btc       doge      eth   \
time                                                                          
2022-08-10 00:00:00+00:00       1.0       1.0       1.0       1.0       1.0   
2022-08-11 00:00:00+00:00  1.044084  1.007966  1.031776  1.028991  1.086173   
2022-08-12 00:00:00+00:00  1.032028  0.993532  1.032267  1.023896  1.102184   
2022-08-13 00:00:00+00:00  1.051484  1.005325  1.052187  1.046478  1.147176   
2022-08-14 00:00:00+00:00  1.089703  0.995682  1.053477  1.054227  1.162703   
2022-08-15 00:00:00+00:00  1.110819  0.976807  1.048646  1.183001  1.136355   
2022-08-16 00:00:00+00:00  1.070279  0.980408  1.038715  1.106155  1.116053   
2022-08-17 00:00:00+00:00    1.0852  0.971739  1.029437  1.257445  1.101305   

asset                          xrp   
time                                 
2022-08-10 00:00:00+00:00       1.0  
2022-08-11 00:00:00+00:00  1.033501  
2022-08-12 00:00:00+00:00  1.031207  
2022-08-13 00:00:00+00:00  1.030523  
2022-08-14 00:00:00+00:00  1.025361  
2022-08-15 00:00:00+00:00  1.021364  
2022-08-16 00:00:00+00:00  1.017113  
2022-08-17 00:00:00+00:00  1.023202  
```

***

## Example 2: Spot trading volume on Coinbase

***

**Fig. 2 - Coinbase daily spot volume breakdown from State of the Market**\
![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/State%20of%20the%20Market%20-%20Chart%20Examples/Coinbase-Volume-Breakdown.png)

#### Foundational Data Types - Trades

Trades are one of the foundational data types we collect from exchanges. From raw trades data, we can construct additional aggregated metrics.

```python
coinbase_btc_trades = client.get_market_trades(
    markets="coinbase-btc-usd-spot",
    limit_per_market=5,
    paging_from="end"
).to_dataframe()
```

```python
coinbase_btc_trades
```

```
                  market                             time  coin_metrics_id  \
0  coinbase-btc-usd-spot 2024-10-25 19:48:24.188784+00:00        706142046   
1  coinbase-btc-usd-spot 2024-10-25 19:48:24.188784+00:00        706142047   
2  coinbase-btc-usd-spot 2024-10-25 19:48:24.767882+00:00        706142048   
3  coinbase-btc-usd-spot 2024-10-25 19:48:25.158094+00:00        706142049   
4  coinbase-btc-usd-spot 2024-10-25 19:48:25.570517+00:00        706142050   

     amount     price                    database_time  side  
0   0.00721  66854.87 2024-10-25 19:48:24.787998+00:00  sell  
1   0.00758  66854.01 2024-10-25 19:48:24.787998+00:00  sell  
2  0.000341  66854.02 2024-10-25 19:48:25.557208+00:00   buy  
3  0.001426  66849.19 2024-10-25 19:48:26.096516+00:00   buy  
4     0.004  66846.31 2024-10-25 19:48:26.096516+00:00  sell  
```

#### Spot Volume Share - Candles Data

From raw trades data, we construct OHLC candles for each market. For our *Spot Volume % by Asset* chart, we derive volume from our `get_market_candles` endpoint.

All of our endpoints that accept the markets parameter will accept wildcards like exchange-\* or exchange-\*-spot or \*USDT-future. The wildcards will match any market which fits this pattern so users do not need to specify every individual market when querying data for multiple markets.

```python
candles_coinbase = client.get_market_candles(
    markets="coinbase-*-spot", # wildcards can be passed to get all asset pairs
    start_time="2022-08-16",
    end_time="2022-08-17",
    frequency="1d"
).to_dataframe()

```

```python
candles_coinbase.info()
```

```
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1046 entries, 0 to 1045
Data columns (total 10 columns):
 #   Column               Non-Null Count  Dtype              
---  ------               --------------  -----              
 0   market               1046 non-null   string             
 1   time                 1046 non-null   datetime64[ns, UTC]
 2   price_open           1046 non-null   Float64            
 3   price_close          1046 non-null   Float64            
 4   price_high           1046 non-null   Float64            
 5   price_low            1046 non-null   Float64            
 6   vwap                 1046 non-null   Float64            
 7   volume               1046 non-null   Float64            
 8   candle_usd_volume    1046 non-null   Float64            
 9   candle_trades_count  1046 non-null   Int64              
dtypes: Float64(7), Int64(1), datetime64[ns, UTC](1), string(1)
memory usage: 90.0 KB
```

```python
candles_coinbase.head()
```

```
                    market                      time  price_open  price_close  \
0  coinbase-1inch-btc-spot 2022-08-16 00:00:00+00:00    0.000034     0.000034   
1  coinbase-1inch-btc-spot 2022-08-17 00:00:00+00:00    0.000034     0.000033   
2  coinbase-1inch-eur-spot 2022-08-16 00:00:00+00:00       0.807        0.805   
3  coinbase-1inch-eur-spot 2022-08-17 00:00:00+00:00       0.805        0.755   
4  coinbase-1inch-gbp-spot 2022-08-16 00:00:00+00:00       0.679        0.677   

   price_high  price_low      vwap    volume  candle_usd_volume  \
0    0.000035   0.000034  0.000034  12601.82       10324.267565   
1    0.000035   0.000033  0.000034   6400.08        5251.890725   
2        0.82      0.795  0.807773  62791.36       51499.294594   
3       0.828      0.752   0.78722  56349.99       45122.160088   
4       0.691      0.669  0.680058  16631.32       13651.391996   

   candle_trades_count  
0                  204  
1                  226  
2                  475  
3                  478  
4                   67  
```

* **price\_open:** The opening price of the candle.
* **price\_high:** The high price of the candle.
* **price\_low:** The low price of the candle.
* **price\_close:** The close price of the candle.
* **vwap:** The volume-weighted average price of the candle.
* **volume:** The volume of the candle in units of the base asset.
* **candle\_usd\_volume:** The volume of the candle in units of U.S. dollars.
* **candle\_trades\_count:** The number of trades in the candle interval.

#### Total Exchange Spot Volume - Exchange Metrics

We can retrieve the overall volume on the exchange using our `exchange_metrics` endpoint.

```python
coinbase_volume = client.get_exchange_metrics(
    exchanges="coinbase",
    metrics ="volume_reported_spot_usd_1d",
    start_time="2022-08-10",
    end_time="2022-08-17"
).to_dataframe()
```

```python
coinbase_volume
```

```
   exchange                      time  volume_reported_spot_usd_1d
0  coinbase 2022-08-10 00:00:00+00:00             2364732395.45783
1  coinbase 2022-08-11 00:00:00+00:00             2388044971.16654
2  coinbase 2022-08-12 00:00:00+00:00             1568920157.28374
3  coinbase 2022-08-13 00:00:00+00:00             1564683366.92133
4  coinbase 2022-08-14 00:00:00+00:00             2093992312.94672
5  coinbase 2022-08-15 00:00:00+00:00             2514301745.80601
6  coinbase 2022-08-16 00:00:00+00:00             1978781752.31132
7  coinbase 2022-08-17 00:00:00+00:00             2353956243.32178
```

***

## Example 3: Spot order book depth

***

**Fig. 3 - Binance order book depth from State of the Market**\
![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/State%20of%20the%20Market%20-%20Chart%20Examples/Binance-Order-Book-Depth.png)

#### Foundational Data Types - Order Book Snapshots

Exchange order book data is one of the most foundational data types in the crypto industry— arguably, even more foundational than trades data, as two orders must be matched for a trade to occur. Order book data is useful for various entities, including market makers, systematic or quantitative traders, and funds studying trade execution patterns.

Coin Metrics stores three types of order book snapshots. One type consists of a snapshot of the top 100 bids and top 100 asks taken once every 10 seconds for major markets. The second type consists of a full order book snapshot (every bid and every ask) taken once every hour for all markets. The third is a snapshot where the price is +/-10% of mid-price taken once every 10 seconds. All of these snapshots are served through our */timeseries/market-orderbooks* endpoint.

```python
top100_snapshot = client.get_market_orderbooks(
    markets="coinbase-btc-usd-spot",
    depth_limit=100, # For full order book depth, pass the parameter "full_book". 
                     # For 10% of depth (where the price is within +/-10 % of mid-price), pass the parameter "10pct_mid_price".
    limit_per_market=5,
    paging_from="end"
).to_dataframe()
```

```python
top100_snapshot
```

```
                  market                      time     coin_metrics_id  \
0  coinbase-btc-usd-spot 2024-10-25 19:47:40+00:00  1729885660000000-0   
1  coinbase-btc-usd-spot 2024-10-25 19:47:50+00:00  1729885670000000-0   
2  coinbase-btc-usd-spot 2024-10-25 19:48:00+00:00  1729885680000000-0   
3  coinbase-btc-usd-spot 2024-10-25 19:48:10+00:00  1729885690000000-0   
4  coinbase-btc-usd-spot 2024-10-25 19:48:20+00:00  1729885700000000-0   

                                                asks  \
0  [{'price': '66924.57', 'size': '0.00420518'}, ...   
1  [{'price': '66912.05', 'size': '0.08986286'}, ...   
2  [{'price': '66894.65', 'size': '0.06726527'}, ...   
3  [{'price': '66875.86', 'size': '0.40178901'}, ...   
4  [{'price': '66857.83', 'size': '0.00053574'}, ...   

                                                bids  \
0  [{'price': '66920.85', 'size': '0.00081'}, {'p...   
1  [{'price': '66912.04', 'size': '0.00284986'}, ...   
2  [{'price': '66894.64', 'size': '0.00015879'}, ...   
3  [{'price': '66875.85', 'size': '0.00015736'}, ...   
4  [{'price': '66857.82', 'size': '0.07172'}, {'p...   

                     database_time  
0 2024-10-25 19:47:40.403698+00:00  
1 2024-10-25 19:47:50.354886+00:00  
2 2024-10-25 19:48:00.501666+00:00  
3 2024-10-25 19:48:10.338177+00:00  
4 2024-10-25 19:48:20.357161+00:00  
```

```python
bids = eval(top100_snapshot.bids[0])
bids[0:10]
```

```
[{'price': '66920.85', 'size': '0.00081'},
 {'price': '66918.17', 'size': '0.0001607'},
 {'price': '66918.16', 'size': '0.15000424'},
 {'price': '66918.15', 'size': '0.49999905'},
 {'price': '66917.92', 'size': '0.00001495'},
 {'price': '66916.15', 'size': '0.00002241'},
 {'price': '66914.96', 'size': '0.04797143'},
 {'price': '66914.58', 'size': '0.00001495'},
 {'price': '66912.31', 'size': '0.1221577'},
 {'price': '66912.3', 'size': '0.04763478'}]
```

#### Market Quotes - Best Bid & Asks

As an added convenience, we also serve the top bid/ask via a separate timeseries/market-quotes endpoint. Quotes are derived from our order book snapshots, so they are available at the same 10s intervals.

```python
btc_quotes = client.get_market_quotes(
    markets="coinbase-btc-usd-spot",
    limit_per_market=5,
    paging_from="end"
).to_dataframe()
```

```python
btc_quotes
```

```
                  market                      time     coin_metrics_id  \
0  coinbase-btc-usd-spot 2024-10-25 19:47:40+00:00  1729885660000000-0   
1  coinbase-btc-usd-spot 2024-10-25 19:47:50+00:00  1729885670000000-0   
2  coinbase-btc-usd-spot 2024-10-25 19:48:00+00:00  1729885680000000-0   
3  coinbase-btc-usd-spot 2024-10-25 19:48:10+00:00  1729885690000000-0   
4  coinbase-btc-usd-spot 2024-10-25 19:48:20+00:00  1729885700000000-0   

   ask_price  ask_size  bid_price  bid_size  
0   66924.57  0.004205   66920.85   0.00081  
1   66912.05  0.089863   66912.04   0.00285  
2   66894.65  0.067265   66894.64  0.000159  
3   66875.86  0.401789   66875.85  0.000157  
4   66857.83  0.000536   66857.82   0.07172  
```

**Note:** We now also offer *every quote update* via the new Coin Metrics flat file application.

***

## Example 4: Futures data types

***

We offer futures data for 3,000+ markets across top derivatives trading venues such as Binance, CME, FTX, BitMEX, Huobi, Bybit, etc. Supported data types include liquidations, contract prices, open interest, candles, volume, funding rates, and more.

**Fig. 4 - Bitcoin and Ethereum futures open interest from State of the Market**\
![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/State%20of%20the%20Market%20-%20Chart%20Examples/BTC-ETH-open-interest.png)

#### Market Open Interest - Total Contracts Outstanding

Open interest represents the number of contracts that are currently outstanding and not settled for a specific derivatives market.

```python
oi_btc_perp = client.get_market_open_interest(
    markets="binance-BTCUSD_PERP-future",
    end_time="2022-08-17",
    limit_per_market=5,
    paging_from="end"
).to_dataframe()
```

```python
oi_btc_perp
```

```
                       market                      time  contract_count  \
0  binance-BTCUSD_PERP-future 2022-08-17 23:55:00+00:00         3982211   
1  binance-BTCUSD_PERP-future 2022-08-17 23:56:00+00:00         3981078   
2  binance-BTCUSD_PERP-future 2022-08-17 23:57:00+00:00         3979201   
3  binance-BTCUSD_PERP-future 2022-08-17 23:58:00+00:00         3979191   
4  binance-BTCUSD_PERP-future 2022-08-17 23:59:00+00:00         3979133   

   value_usd                    database_time             exchange_time  
0  398221100 2022-08-17 23:55:11.890405+00:00 2022-08-17 23:55:00+00:00  
1  398107800 2022-08-17 23:56:30.226528+00:00 2022-08-17 23:56:00+00:00  
2  397920100 2022-08-17 23:57:08.240922+00:00 2022-08-17 23:57:00+00:00  
3  397919100 2022-08-17 23:58:18.250239+00:00 2022-08-17 23:58:00+00:00  
4  397913300 2022-08-17 23:59:07.291820+00:00 2022-08-17 23:59:00+00:00  
```

#### Aggregated Open Interest - Daily by Asset & Contract Type

In addition to querying open interest for specific markets/contracts, the `get_asset_metrics` endpoint can also be used to retrieve aggregated open interest. Our reported future open interest metric is an aggregation of the reported future open interest from all futures exchanges in CM"s coverage universe.

We offer aggregated futures open interest for the following futures contract types:

* Reported Future Open Interest
* Reported Perpetual Future Open Interest
* Reported Non-Perpetual Future Open Interest
* Reported Coin-Margined Future Open Interest
* Reported Tether-Margined Future Open Interest

```python
oi_btc_eth = client.get_asset_metrics(
    assets="btc,eth",
    metrics="open_interest_reported_future_usd,open_interest_reported_future_nonperpetual_usd,open_interest_reported_future_perpetual_usd",
    frequency="1d",
    limit_per_asset=3,
    paging_from="end"
).to_dataframe()
```

```python
oi_btc_eth
```

```
  asset                      time  \
0   btc 2024-10-23 00:00:00+00:00   
1   btc 2024-10-24 00:00:00+00:00   
2   btc 2024-10-25 00:00:00+00:00   
3   eth 2024-10-23 00:00:00+00:00   
4   eth 2024-10-24 00:00:00+00:00   
5   eth 2024-10-25 00:00:00+00:00   

   open_interest_reported_future_nonperpetual_usd  \
0                                13923479711.9669   
1                              13453533211.895201   
2                                13392581425.7694   
3                                1535153876.09309   
4                                1473483638.19916   
5                                1451292649.13502   

   open_interest_reported_future_perpetual_usd  \
0                           19982575374.762501   
1                           19754715551.441399   
2                           20179456440.591499   
3                             9517890065.12204   
4                            9292600168.441351   
5                            9313906648.995859   

   open_interest_reported_future_usd  
0                 33906055086.729401  
1                 33208248763.336601  
2                 33572037866.360901  
3                 11053043941.215099  
4                 10766083806.640499  
5                 10765199298.130899  
```

#### Perpetual Futures Funding Rates

Funding rates are a mechanism that exchanges use to ensure that perpetual futures trade at a price that is close to the price of the underlying spot markets. The funding rate is used to calculate the funding fee which long position holders pay short position holders, or vice versa, as a way to incentivize market participants to take positions that keep perpetual futures prices close to the underlying.

```python
funding_btc_perp = client.get_market_funding_rates(
    markets="binance-BTCUSD_PERP-future",
    end_time="2022-08-17",
    limit_per_market=5
).to_dataframe()
```

```python
funding_btc_perp
```

```
                       market                             time  \
0  binance-BTCUSD_PERP-future        2020-08-10 16:00:00+00:00   
1  binance-BTCUSD_PERP-future        2020-08-11 00:00:00+00:00   
2  binance-BTCUSD_PERP-future 2020-08-11 08:00:00.008000+00:00   
3  binance-BTCUSD_PERP-future        2020-08-11 16:00:00+00:00   
4  binance-BTCUSD_PERP-future        2020-08-12 00:00:00+00:00   

                     database_time    rate    period  interval  
0 2020-12-02 10:49:37.530167+00:00  0.0001  08:00:00  08:00:00  
1 2020-12-02 10:49:37.530167+00:00  0.0001  08:00:00  08:00:00  
2 2020-12-02 10:49:37.530167+00:00  0.0001  08:00:00  08:00:00  
3 2020-12-02 10:49:37.530167+00:00  0.0001  08:00:00  08:00:00  
4 2020-12-02 10:49:37.530167+00:00  0.0001  08:00:00  08:00:00  
```

**Fig. 5 - Bitcoin perpetual futures funding rates from State of the Market**\
![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/State%20of%20the%20Market%20-%20Chart%20Examples/BTC-perp-funding-rates.png)

#### Futures Basis Metrics - Aggregated by Exchange-Asset

The basis is the annualized percent difference between the price of a theoretical futures contract and the price of its underlying spot market. Coin Metrics calculates this for several exchange-assets such as `binance-btc` and `ftx-eth`. We calculate four basis metrics at defined days to expiration: 30 day, 60 day, 90 day, and 120 day.

```python
basis_binance = client.get_exchange_asset_metrics(
    exchange_assets="binance-btc", 
    metrics="basis_annualized_30d_exp,basis_annualized_60d_exp,basis_annualized_90d_exp"
).to_dataframe()
```

```python
basis_binance.tail()
```

```
     exchange_asset                      time  basis_annualized_30d_exp  \
1592    binance-btc 2024-10-21 00:00:00+00:00                  0.104488   
1593    binance-btc 2024-10-22 00:00:00+00:00                  0.095617   
1594    binance-btc 2024-10-23 00:00:00+00:00                  0.103859   
1595    binance-btc 2024-10-24 00:00:00+00:00                  0.103878   
1596    binance-btc 2024-10-25 00:00:00+00:00                  0.108495   

      basis_annualized_60d_exp  basis_annualized_90d_exp  
1592                  0.104552                  0.098069  
1593                  0.095675                  0.092418  
1594                  0.103922                  0.096754  
1595                  0.103941                  0.100998  
1596                  0.108561                  0.102192  
```

**Fig. 6 - Bitcoin futures basis from State of the Market**\
![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/State%20of%20the%20Market%20-%20Chart%20Examples/Futures-Basis.png)

#### Futures Liquidations - Individual Orders/Trades

Exchanges which offer futures markets utilize a risk management system that will attempt to close a user’s position before the point at which the user begins to owe more than what is in the user"s account. The trade or order that closes the user"s position is referred to as a liquidation.

* Some exchanges report **liquidations orders** in which they will report the creation of a liquidation order when a trader’s position initially enters liquidation. When a trader’s position enters liquidation, an exchange will typically enter a limit order at the trader"s bankruptcy price. The order will show the amount of the position that is being liquidated and the liquidation price, but will not represent the matched trades that are executed as a result of the liquidation.
* Other exchanges will report **liquidation trades** which represent the actual matched trades as a result of a liquidation order but will not report liquidation orders.
* Some exchanges will report both liquidation orders and liquidation trades.

```python
mkt_liqs_binance = client.get_market_liquidations(
    markets="binance-BTCUSDT-future", 
    limit_per_market=3
).to_dataframe()
```

```python
mkt_liqs_binance.head()
```

```
                   market                             time  \
0  binance-BTCUSDT-future 2019-09-10 19:36:50.009000+00:00   
1  binance-BTCUSDT-future 2019-09-10 19:38:06.010000+00:00   
2  binance-BTCUSDT-future 2019-09-11 06:51:13.010000+00:00   

       coin_metrics_id  amount     price   type  \
0  1568144210009000000   0.199  10013.89  trade   
1  1568144286010000000    0.04   9952.16  trade   
2  1568184673010000000    0.04   9944.65  trade   

                     database_time  side  
0 2020-10-08 06:03:35.854962+00:00  sell  
1 2020-10-08 06:03:35.854962+00:00  sell  
2 2020-10-08 06:03:35.854962+00:00  sell  
```

#### Futures Liquidations - Aggregated Daily or Hourly

```python
liqs_binance = client.get_market_metrics(
    markets="binance-BTCUSDT-future", 
    metrics="liquidations_reported_future_buy_usd_1d"
).to_dataframe()
```

```python
liqs_binance.head()
```

```
                   market                      time  \
0  binance-BTCUSDT-future 2019-09-12 00:00:00+00:00   
1  binance-BTCUSDT-future 2019-09-19 00:00:00+00:00   
2  binance-BTCUSDT-future 2019-09-20 00:00:00+00:00   
3  binance-BTCUSDT-future 2019-09-21 00:00:00+00:00   
4  binance-BTCUSDT-future 2019-09-23 00:00:00+00:00   

   liquidations_reported_future_buy_usd_1d  
0                                 114.5749  
1                             268916.41422  
2                              18519.28155  
3                                  8795.16  
4                              62820.22767  
```

**Fig. 7 - Bitcoin perpetual futures liquidations from State of the Market**\
![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/State%20of%20the%20Market%20-%20Chart%20Examples/BTC-Perp-Liquidations.png)

***

## Example 5: Options data types

***

We offer options data from two of the most liquid options trading venues, Deribit and OKX. Supported data types include implied volatility, trades, open interest, contract prices, contract specifications, quotes, and greeks. We recently expanded our options coverage to include several new data types from Deribit and added several new API endpoints to serve this data.

#### Options Contracts - Implied Volatility

```python
iv_deribit = client.get_market_implied_volatility(
    markets="deribit-BTC-18AUG22-*-option", 
    end_time="2022-08-17",
    limit_per_market=1
).to_dataframe()
```

```python
iv_deribit.head()
```

```
                               market                      time  \
0  deribit-BTC-18AUG22-19000-C-option 2022-08-16 08:04:00+00:00   
1  deribit-BTC-18AUG22-19000-P-option 2022-08-16 08:04:00+00:00   
2  deribit-BTC-18AUG22-20000-C-option 2022-08-16 08:04:00+00:00   
3  deribit-BTC-18AUG22-20000-P-option 2022-08-16 08:04:00+00:00   
4  deribit-BTC-18AUG22-21000-C-option 2022-08-16 08:04:00+00:00   

                     database_time  iv_bid  iv_ask  iv_mark  \
0 2022-08-16 08:04:59.435418+00:00     0.0     0.0      1.0   
1 2022-08-16 08:04:58.430009+00:00     0.0  2.5561      1.0   
2 2022-08-16 08:04:57.429870+00:00     0.0     0.0      1.0   
3 2022-08-16 08:04:58.430009+00:00     0.0  2.0536      1.0   
4 2022-08-16 08:04:58.430009+00:00     0.0     0.0      1.0   

                     exchange_time  
0 2022-08-16 08:04:58.622000+00:00  
1 2022-08-16 08:04:57.613000+00:00  
2 2022-08-16 08:04:56.605000+00:00  
3 2022-08-16 08:04:57.612000+00:00  
4 2022-08-16 08:04:57.620000+00:00  
```

**Fig. 8 - Bitcoin "Volatility Smile" from State of the Market**\
![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/State%20of%20the%20Market%20-%20Chart%20Examples/BTC-IV-vs-StrikePrice.png)

#### Options Contracts - Market Greeks

```python
greeks_deribit = client.get_market_greeks(
    markets="deribit-BTC-18AUG22-*-option", 
    end_time="2022-08-17",
    limit_per_market=1
).to_dataframe()
```

```python
greeks_deribit.head()
```

```
                               market                      time  \
0  deribit-BTC-18AUG22-19000-C-option 2022-08-16 08:04:00+00:00   
1  deribit-BTC-18AUG22-19000-P-option 2022-08-16 08:04:00+00:00   
2  deribit-BTC-18AUG22-20000-C-option 2022-08-16 08:04:00+00:00   
3  deribit-BTC-18AUG22-20000-P-option 2022-08-16 08:04:00+00:00   
4  deribit-BTC-18AUG22-21000-C-option 2022-08-16 08:04:00+00:00   

                     database_time     vega     theta      rho    delta  \
0 2022-08-16 08:04:59.435418+00:00  0.03878  -0.97127  1.03845  0.99938   
1 2022-08-16 08:04:58.430009+00:00  0.03875  -0.30251 -0.00084 -0.00062   
2 2022-08-16 08:04:57.429870+00:00    0.287  -7.18741  1.08637  0.99435   
3 2022-08-16 08:04:58.430009+00:00  0.28587  -3.27365 -0.00759 -0.00563   
4 2022-08-16 08:04:58.430009+00:00  1.22414 -30.65678   1.1075   0.9696   

     gamma                    exchange_time  
0      0.0 2022-08-16 08:04:58.622000+00:00  
1      0.0 2022-08-16 08:04:57.613000+00:00  
2  0.00001 2022-08-16 08:04:56.605000+00:00  
3  0.00001 2022-08-16 08:04:57.612000+00:00  
4  0.00004 2022-08-16 08:04:57.620000+00:00  
```

**Fig. 9 - Option Chain from State of the Market**\
![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/State%20of%20the%20Market%20-%20Chart%20Examples/Option-Chain.png)

#### Options Contracts - Market Quotes

```python
quotes_deribit = client.get_market_quotes(
    markets="deribit-BTC-18AUG22-*-option", 
    end_time="2022-08-17",
    limit_per_market=3
).to_dataframe()
```

```python
quotes_deribit.head()
```

```
                               market                      time  \
0  deribit-BTC-18AUG22-19000-C-option 2022-08-16 08:04:00+00:00   
1  deribit-BTC-18AUG22-19000-C-option 2022-08-16 08:05:00+00:00   
2  deribit-BTC-18AUG22-19000-C-option 2022-08-16 08:06:00+00:00   
3  deribit-BTC-18AUG22-19000-P-option 2022-08-16 08:04:00+00:00   
4  deribit-BTC-18AUG22-19000-P-option 2022-08-16 08:05:00+00:00   

      coin_metrics_id  ask_price  ask_size  bid_price  bid_size  
0  1660637040000000-0        0.0       0.0        0.0       0.0  
1  1660637100000000-0        0.0       0.0        0.0       0.0  
2  1660637160000000-0        0.0       0.0        0.0       0.0  
3  1660637040000000-0        0.1    0.0085        0.0       0.0  
4  1660637100000000-0       10.0    0.0005        0.0       0.0  
```

#### Options Contracts - Market Open Interest

```python
oi_deribit = client.get_market_open_interest(
    markets="deribit-BTC-30DEC22-*-option", 
    paging_from="end",
    limit_per_market=1
).to_dataframe()
```

```python
oi_deribit.sort_values("value_usd").tail()
```

```
                                market                      time  \
62  deribit-BTC-30DEC22-35000-C-option 2022-12-30 07:59:00+00:00   
7   deribit-BTC-30DEC22-12000-P-option 2022-12-30 07:59:00+00:00   
15  deribit-BTC-30DEC22-15000-P-option 2022-12-30 07:59:00+00:00   
1   deribit-BTC-30DEC22-10000-P-option 2022-12-30 07:59:00+00:00   
54  deribit-BTC-30DEC22-30000-C-option 2022-12-30 07:59:00+00:00   

    contract_count      value_usd                    database_time  \
62          6564.4    108156695.5 2022-12-30 07:59:11.450250+00:00   
7           6609.7  108902937.431 2022-12-30 07:59:21.456460+00:00   
15          6873.1  113242845.144 2022-12-30 07:59:12.451403+00:00   
1           7731.2  127381029.376 2022-12-30 07:59:21.456460+00:00   
54          7836.8  129120997.632 2022-12-30 07:59:17.454662+00:00   

               exchange_time  
62 2022-12-30 07:59:00+00:00  
7  2022-12-30 07:59:00+00:00  
15 2022-12-30 07:59:00+00:00  
1  2022-12-30 07:59:00+00:00  
54 2022-12-30 07:59:00+00:00  
```

**Fig. 10 - Option Open Interest from State of the Market**\
![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/State%20of%20the%20Market%20-%20Chart%20Examples/Options-OI.png)


# Getting Started With Futures Data

![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/Demo%20Asset%20Resources/Demo%20Covers/CM-Demo-futures_overview.png)

This notebook demonstrates basic functionality offered by the Coin Metrics Python API Client and **Market Data Feed.**

Coin Metrics offers a vast assortment of data for hundreds of cryptoassets. The Python API Client allows for easy access to this data using Python without needing to create your own wrappers using `requests` and other such libraries.

### Resources

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics.
* The [Coin Metrics Product Documentation](https://docs.coinmetrics.io/info) gives detailed, conceptual explanations of the data that Coin Metrics offers.
* The [API Spec](https://docs.coinmetrics.io/python-api-client/reference) contains a full list of functions.

### File Download

Download the entire notebook as either a jupyter notebook to run yourself or as a pdf from the two links below

{% file src="/files/HFRGCesnksVnIinzmldG" %}

{% file src="/files/x78mtym3Ic7zoCRezlpN" %}

### Notebook Setup

```python
import os
from os import environ
import sys
import pandas as pd
import numpy as np
import seaborn as sns
import logging
from datetime import date, datetime, timedelta
from coinmetrics.api_client import CoinMetricsClient
import json
import logging
from pytz import timezone as timezone_conv
from datetime import timezone as timezone_info
import matplotlib.ticker as mticker
from matplotlib.ticker import ScalarFormatter
from matplotlib.ticker import FuncFormatter
from matplotlib.dates import DateFormatter
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# %matplotlib inline
```

```python
sns.set_theme()
sns.set(rc={'figure.figsize':(8,6)})
```

```python
logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S'
)
now = datetime.utcnow()
last_day_date_time = now - timedelta(hours = 24)
```

```python
# We recommend privately storing your API key in your local environment.
try:
    api_key = environ["CM_API_KEY"]
    logging.info("Using API key found in environment")
except KeyError:
    api_key = ""
    logging.info("API key not found. Using community client")

client = CoinMetricsClient(api_key)
```

```
2024-09-16 16:41:57 INFO     Using API key found in environment
```

## Futures Catalog

Futures contracts are standardized contracts that allow counterparties to enter into an agreement to buy or sell a standardized asset under contract specifications that are defined by the exchange. Each specific futures contract offered by a specific exchange will have identical contract specifications regardless of who is the counterparty.

The contract specifications include information such as the underlying base and quote asset, the margin asset, the contract size, the listing time, expiration time, and other terms.

Coin Metrics offers contract specifications for both futures and options. Here we define futures to include both non-perpetual futures that expire and perpetual futures (sometimes called perpetual swaps).

```python
market_reference = client.reference_data_markets(
    type='future',
    page_size=10000
).to_dataframe()
```

```python
print('Total number of supported futures markets: ' + str(len(market_reference)))
```

```
Total number of supported futures markets: 18682
```

```python
# Perpetual futures markets are any futures market with null expiration
print('Total number of perpetual futures markets: ' + str(len(market_reference.loc[market_reference['expiration'].isna()])))
```

```
Total number of perpetual futures markets: 4222
```

```python
# Filter by base or quote asset
print('Total number of supported BTC futures markets: ' + str(len(market_reference.loc[market_reference['base'] == 'btc'])))
```

```
Total number of supported BTC futures markets: 3109
```

```python
# Select first BTC futures market as an example
market_reference.loc[market_reference['base'] == 'btc'].iloc[0]
```

```
market                            binance-BTCBUSD-future
exchange                                         binance
base                                                 btc
quote                                               busd
pair                                            btc-busd
symbol                                           BTCBUSD
type                                              future
size_asset                                           btc
margin_asset                                        busd
strike                                              <NA>
option_contract_type                                <NA>
is_european                                         <NA>
contract_size                                        1.0
tick_size                                            0.1
multiplier_size                                     <NA>
listing                   2021-01-11T08:00:00.000000000Z
expiration                                          <NA>
settlement_price                                    <NA>
pool_config_id                                      <NA>
contract_address                                    <NA>
fee                                                 <NA>
price_includes_fee                                  <NA>
variable_fee                                        <NA>
base_address                                        <NA>
quote_address                                       <NA>
status                                              <NA>
order_amount_increment                             0.001
order_amount_min                                   0.001
order_amount_max                                     500
order_price_increment                                0.1
order_price_min                                    557.6
order_price_max                                4529890.0
order_size_min                                       5.0
order_taker_fee                                     <NA>
order_maker_fee                                     <NA>
margin_trading_enabled                              <NA>
experimental                                        <NA>
Name: 151, dtype: object
```

## Open Interest

Open interest represents the number of contracts that are currently outstanding and not settled for a specific derivatives market.

#### Open Interest is available at various levels

* Assets level (i.e btc)
* Asset Pair level (i.e. btc-usd)
* Exchange level (i.e. binance)
* Exchange-Asset level (i.e. binance-btc)
* Market level (i.e. binance-BTCUSDT-future)

### BTC Open Interest at the Market Level

```python
binance_btcusdt_oi = client.get_market_open_interest(
    markets = 'binance-BTCUSDT-future',
    start_time = datetime.utcnow() - timedelta(days=1),
).to_dataframe()
```

```python
binance_btcusdt_oi
```

|      | market                 | time                      | contract\_count | value\_usd      | database\_time                   | exchange\_time            |
| ---- | ---------------------- | ------------------------- | --------------- | --------------- | -------------------------------- | ------------------------- |
| 0    | binance-BTCUSDT-future | 2024-09-15 21:42:00+00:00 | 87506.236       | 5214374094.5096 | 2024-09-15 21:42:31.800754+00:00 | 2024-09-15 21:42:00+00:00 |
| 1    | binance-BTCUSDT-future | 2024-09-15 21:43:00+00:00 | 87493.551       | 5213766952.1553 | 2024-09-15 21:43:55.721238+00:00 | 2024-09-15 21:43:00+00:00 |
| 2    | binance-BTCUSDT-future | 2024-09-15 21:44:00+00:00 | 87505.378       | 5215066763.2038 | 2024-09-15 21:44:48.749434+00:00 | 2024-09-15 21:44:00+00:00 |
| 3    | binance-BTCUSDT-future | 2024-09-15 21:45:00+00:00 | 87499.076       | 5215364925.1648 | 2024-09-15 21:45:41.693858+00:00 | 2024-09-15 21:45:00+00:00 |
| 4    | binance-BTCUSDT-future | 2024-09-15 21:46:00+00:00 | 87503.139       | 5214338303.9517 | 2024-09-15 21:46:35.001759+00:00 | 2024-09-15 21:46:00+00:00 |
| ...  | ...                    | ...                       | ...             | ...             | ...                              | ...                       |
| 1435 | binance-BTCUSDT-future | 2024-09-16 21:37:00+00:00 | 84817.5         | 4903884915.75   | 2024-09-16 21:37:39.951283+00:00 | 2024-09-16 21:37:00+00:00 |
| 1436 | binance-BTCUSDT-future | 2024-09-16 21:38:00+00:00 | 84825.836       | 4902466778.702  | 2024-09-16 21:38:33.480165+00:00 | 2024-09-16 21:38:00+00:00 |
| 1437 | binance-BTCUSDT-future | 2024-09-16 21:39:00+00:00 | 84832.474       | 4902417772.9756 | 2024-09-16 21:39:26.976255+00:00 | 2024-09-16 21:39:00+00:00 |
| 1438 | binance-BTCUSDT-future | 2024-09-16 21:40:00+00:00 | 84842.805       | 4902471801.315  | 2024-09-16 21:40:46.680850+00:00 | 2024-09-16 21:40:00+00:00 |
| 1439 | binance-BTCUSDT-future | 2024-09-16 21:41:00+00:00 | 84851.162       | 4904380193.3676 | 2024-09-16 21:41:40.406353+00:00 | 2024-09-16 21:41:00+00:00 |

1440 rows × 6 columns

### BTC Open Interest by Exchange (Exchange-Asset Endpoint)

```python
oi_catalog = client.catalog_exchange_asset_metrics_v2(metrics='open_interest_reported_future_usd').to_dataframe()
oi_catalog = oi_catalog[oi_catalog['exchange_asset'].str.split('-').str[1] == 'btc']
exchange_assets = oi_catalog['exchange_asset'].to_list()
```

Use the **get\_exchange\_asset\_metrics** client function to pull the all BTC exchange-asset pairs at daily frequency:

```python
btc_oi = client.get_exchange_asset_metrics(
    exchange_assets = exchange_assets,
    metrics = 'open_interest_reported_future_usd',
    start_time = datetime.utcnow() - timedelta(days=365),
    frequency = '1d'
).to_dataframe()
```

```python
# Convert 'open_interest_reported_future_usd' to numeric
btc_oi['open_interest_reported_future_usd'] = btc_oi['open_interest_reported_future_usd'].astype(np.float64)

# Convert 'time' to datetime
btc_oi['time'] = btc_oi['time'].dt.tz_localize(None).astype('datetime64[ns]')
btc_oi
```

|      | exchange\_asset | time       | open\_interest\_reported\_future\_usd |
| ---- | --------------- | ---------- | ------------------------------------- |
| 0    | binance-btc     | 2023-09-18 | 3.074676e+09                          |
| 1    | binance-btc     | 2023-09-19 | 3.220249e+09                          |
| 2    | binance-btc     | 2023-09-20 | 3.359060e+09                          |
| 3    | binance-btc     | 2023-09-21 | 3.272911e+09                          |
| 4    | binance-btc     | 2023-09-22 | 3.280109e+09                          |
| ...  | ...             | ...        | ...                                   |
| 3280 | okex-btc        | 2024-09-12 | 2.346645e+09                          |
| 3281 | okex-btc        | 2024-09-13 | 2.431933e+09                          |
| 3282 | okex-btc        | 2024-09-14 | 2.693548e+09                          |
| 3283 | okex-btc        | 2024-09-15 | 2.608818e+09                          |
| 3284 | okex-btc        | 2024-09-16 | 2.569876e+09                          |

3285 rows × 3 columns

```python
# Drop rows with missing data
btc_oi.dropna(inplace=True)
```

```python
exchanges = btc_oi['exchange_asset'].unique()
dates = btc_oi['time'].unique() 
stacked_data = [btc_oi[btc_oi['exchange_asset'] == exchange]['open_interest_reported_future_usd'].values for exchange in exchanges]

fig, ax = plt.subplots(figsize=(12, 7))
ax.stackplot(dates, stacked_data, labels=exchanges, edgecolor='none')

ax.set_title('\nBTC Open Interest\nby Exchange\n', fontsize=16)
ax.set_xlabel('', fontsize=14)
ax.set_ylabel('Reported Open Interest (USD)\n', fontsize=14)
ax.legend(loc='upper left', title='Exchange Asset', bbox_to_anchor=(1,1), frameon=False)
ax.grid(True, linestyle='--', alpha=0.5, color='gray')
ax.set_facecolor('white')

# Format y-axis in billions of dollars
def billions(x, pos):
    return f'${x * 1e-9:.1f}B'

ax.yaxis.set_major_formatter(FuncFormatter(billions))

ax.set_xlim([btc_oi['time'].min(), btc_oi['time'].max()])
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b\n%Y'))
fig.autofmt_xdate()
ax.tick_params(axis='x', which='major', pad=10) 
_ = plt.xticks(rotation=0)
plt.tight_layout()
plt.show()
```

<figure><img src="/files/QqBJJBOdmkifTj41S156" alt=""><figcaption></figcaption></figure>

## Liquidations

Next, we'll take a look at liquidations data. As a reminder, exchanges which offer futures markets utilize a risk management system that will attempt to close a user’s position before the point at which the user begins to owe more than what is in the user's account. The trade or order that closes the user's position is referred to as a liquidation.

This time, we'll use the **get\_market\_liquidations** client function to pull all BTCUSDT liquidations over the last 24 hours on Binance:

```python
market = 'binance-BTCUSDT-future'
```

```python
liquidations_df = client.get_market_liquidations(
    markets = market,
    start_time = datetime.utcnow() - timedelta(days=1),
).to_dataframe()
liquidations_df['amount'] = liquidations_df['amount'].astype(np.float64)
liquidations_df['price'] = liquidations_df['price'].astype(np.float64)
```

```python
liquidations_df.head()
```

|   | market                 | time                             | coin\_metrics\_id   | amount | price   | type  | database\_time                   | side |
| - | ---------------------- | -------------------------------- | ------------------- | ------ | ------- | ----- | -------------------------------- | ---- |
| 0 | binance-BTCUSDT-future | 2024-09-15 21:54:34.145000+00:00 | 1726437274145000000 | 0.011  | 59648.0 | trade | 2024-09-15 21:54:34.297968+00:00 | buy  |
| 1 | binance-BTCUSDT-future | 2024-09-15 21:57:52.361000+00:00 | 1726437472361000000 | 0.006  | 59663.1 | trade | 2024-09-15 21:57:53.574117+00:00 | buy  |
| 2 | binance-BTCUSDT-future | 2024-09-15 22:02:17.426000+00:00 | 1726437737426000000 | 0.242  | 59511.0 | trade | 2024-09-15 22:02:18.244282+00:00 | sell |
| 3 | binance-BTCUSDT-future | 2024-09-15 22:02:19.433000+00:00 | 1726437739433000000 | 0.041  | 59503.1 | trade | 2024-09-15 22:02:20.362299+00:00 | sell |
| 4 | binance-BTCUSDT-future | 2024-09-15 22:02:33.095000+00:00 | 1726437753095000000 | 0.009  | 59479.2 | trade | 2024-09-15 22:02:34.376645+00:00 | sell |

```python
# Get volume-weighted average price of the futures contract from the market-candles endpoint
price = client.get_market_candles(
        markets = market,
        start_time = datetime.utcnow() - timedelta(days=1),
        end_time = datetime.utcnow(),
        frequency='1m'
).to_dataframe()
price['vwap'] = price['vwap'].astype(np.float64)
```

```python
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

plt.figure(figsize=(13,7))
scaling_factor = 300  # Adjust this value to get the desired point size
color_map = {'buy': 'green', 'sell': 'red'}
liqs = plt.scatter(
    x=liquidations_df['time'],
    y=liquidations_df['price'],
    s=liquidations_df['amount'] * scaling_factor,  # Scale point sizes by the scaling factor
    c=liquidations_df['side'].map(color_map),
    alpha=0.6
)

plt.plot(price['time'], price['vwap'], color='black', linestyle='-', label='VWAP')

mean_price = liquidations_df['price'].mean()
std_price = liquidations_df['price'].std()
plt.ylim(mean_price - 3*std_price, mean_price + 3*std_price)
plt.xlabel("", fontsize=15)
plt.ylabel("Price\n", font='arial',fontsize=15)
plt.title('\n' + str(market) + '\nLiquidations\n', size=20)

# Format the xtick labels
date_format = DateFormatter('%D\n%H:%M')
plt.gca().xaxis.set_major_formatter(date_format)

legend_labels = ['BUY', 'SELL', 'VWAP']
legend_handles = [
    plt.Line2D([0], [0], marker='o', color='w', markerfacecolor=color_map['buy'], markersize=12),
    plt.Line2D([0], [0], marker='o', color='w', markerfacecolor=color_map['sell'], markersize=12),
    plt.Line2D([0], [0], color='black', lw=2)  # Legend entry for VWAP
]
legend = plt.legend(legend_handles, legend_labels, loc='lower right', fontsize=14, ncol=2, framealpha=0, bbox_to_anchor=(0.99, 1.02))

plt.gca().set_facecolor('white')
plt.grid(color='black', linestyle='dotted')

plt.tight_layout() 
plt.show()
```

<figure><img src="/files/ix5QYIe4KDzEevHUXUKZ" alt=""><figcaption></figcaption></figure>

Notice that this timeseries also includes the liquidation **type**. Some exchanges report “liquidations orders” in which they will report the creation of a liquidation **order** when a trader’s position initially enters liquidation. When a trader’s position enters liquidation, an exchange will typically enter a limit order at the price at which the trader will be bankruptcy price. The liquidation orders will show the amount of the position that is being liquidated and the liquidation price, but will not represent the matched trades that are executed as a result of the liquidation. Other exchanges will report “liquidation trades” which represent the actual matched **trade** as a result of a liquidation order but will not report liquidation orders. Some exchanges will report both liquidation orders and liquidation trades.

#### Aggregated Liquidation Metrics

In addition to examining individual liquidations, we can also leverage aggregated liquidations metrics. This allows us to quickly view the total amount of USD-denominated liquidations that have occurred over large timeframes, without needing to aggregate the amounts at the trade level.

```python
metrics = ['liquidations_reported_future_buy_usd_1h', 'liquidations_reported_future_sell_usd_1h']
```

```python
liq_catalog = client.catalog_exchange_asset_metrics_v2(metrics=metrics).to_dataframe()
liq_catalog = liq_catalog[liq_catalog['exchange_asset'].str.split('-').str[1] == 'btc']
liq_catalog
```

|      | exchange\_asset | metrics                                                |
| ---- | --------------- | ------------------------------------------------------ |
| 61   | binance-btc     | \[{'metric': 'liquidations\_reported\_future\_buy\_... |
| 335  | bitfinex-btc    | \[{'metric': 'liquidations\_reported\_future\_buy\_... |
| 401  | bitmex-btc      | \[{'metric': 'liquidations\_reported\_future\_buy\_... |
| 577  | bybit-btc       | \[{'metric': 'liquidations\_reported\_future\_buy\_... |
| 925  | deribit-btc     | \[{'metric': 'liquidations\_reported\_future\_buy\_... |
| 978  | ftx-btc         | \[{'metric': 'liquidations\_reported\_future\_buy\_... |
| 1213 | huobi-btc       | \[{'metric': 'liquidations\_reported\_future\_buy\_... |
| 1475 | kraken-btc      | \[{'metric': 'liquidations\_reported\_future\_buy\_... |
| 1688 | okex-btc        | \[{'metric': 'liquidations\_reported\_future\_buy\_... |

```python
agg_liqs = client.get_exchange_asset_metrics(
    exchange_assets=liq_catalog['exchange_asset'].to_list(),
    metrics = metrics,
    start_time = datetime.utcnow() - timedelta(days=1.5),
    frequency='1h'
).to_dataframe()
agg_liqs.replace('None', np.nan, inplace=True)
agg_liqs[metrics[0]] = agg_liqs['liquidations_reported_future_buy_usd_1h'].astype(np.float64)
agg_liqs['liquidations_reported_future_sell_usd_1h'] = -1 * agg_liqs['liquidations_reported_future_sell_usd_1h'].astype(np.float64)
```

```python
agg_liqs = agg_liqs.fillna(0)
agg_liqs
```

|     | exchange\_asset | time                      | liquidations\_reported\_future\_buy\_usd\_1h | liquidations\_reported\_future\_sell\_usd\_1h |
| --- | --------------- | ------------------------- | -------------------------------------------- | --------------------------------------------- |
| 0   | binance-btc     | 2024-09-15 10:00:00+00:00 | 41189.76644                                  | -123119.61981                                 |
| 1   | binance-btc     | 2024-09-15 11:00:00+00:00 | 2219.32844                                   | -26757.74386                                  |
| 2   | binance-btc     | 2024-09-15 12:00:00+00:00 | 20766.66452                                  | -540.03552                                    |
| 3   | binance-btc     | 2024-09-15 13:00:00+00:00 | 166694.89730                                 | -28269.05000                                  |
| 4   | binance-btc     | 2024-09-15 14:00:00+00:00 | 208587.82170                                 | -319846.10928                                 |
| ... | ...             | ...                       | ...                                          | ...                                           |
| 167 | okex-btc        | 2024-09-16 16:00:00+00:00 | 2309.60000                                   | -231.20680                                    |
| 168 | okex-btc        | 2024-09-16 17:00:00+00:00 | 753306.85950                                 | -676171.41858                                 |
| 169 | okex-btc        | 2024-09-16 18:00:00+00:00 | 0.00000                                      | -245113.87800                                 |
| 170 | okex-btc        | 2024-09-16 19:00:00+00:00 | 0.00000                                      | -18840.23928                                  |
| 171 | okex-btc        | 2024-09-16 20:00:00+00:00 | 52104.18704                                  | -131510.72160                                 |

172 rows × 4 columns

```python
btc_total_oi = client.get_asset_metrics(
    assets='btc',
    metrics='open_interest_reported_future_usd',
    frequency='1h', 
    start_time = datetime.utcnow() - timedelta(days=2)
).to_dataframe()
btc_total_oi.head()
```

|   | asset | time                      | open\_interest\_reported\_future\_usd |
| - | ----- | ------------------------- | ------------------------------------- |
| 0 | btc   | 2024-09-14 22:00:00+00:00 | 27085472082.8134                      |
| 1 | btc   | 2024-09-14 23:00:00+00:00 | 27086895034.416401                    |
| 2 | btc   | 2024-09-15 00:00:00+00:00 | 27089846618.242401                    |
| 3 | btc   | 2024-09-15 01:00:00+00:00 | 27103605277.447899                    |
| 4 | btc   | 2024-09-15 02:00:00+00:00 | 27206441557.918598                    |

```python
df = agg_liqs
```

```python
melted_df = df.melt(id_vars=['time', 'exchange_asset'], 
                    value_vars=['liquidations_reported_future_buy_usd_1h', 'liquidations_reported_future_sell_usd_1h'],
                    var_name='transaction_type', value_name='amount')
melted_df['amount'] /= 1e6
melted_df['time'] = melted_df['time'].dt.tz_localize(None)

fig, ax = plt.subplots(figsize=(12,7))
plt.gca().set_facecolor('white')
plt.grid(color='gray', linestyle='dotted',alpha=0.3)
ax2 = ax.twinx()

unique_assets = melted_df['exchange_asset'].unique()
colormap = plt.cm.tab20
colors = {asset: colormap(i) for i, asset in enumerate(unique_assets)}

for asset in unique_assets:
    subset = melted_df[melted_df['exchange_asset'] == asset]
    ax.bar(subset['time'], subset['amount'], width=0.01, label=asset, color=colors[asset]) 

# Plot open interest on secondary y-axis
btc_total_oi['time'] = btc_total_oi['time'].dt.tz_localize(None)
ax2.plot(btc_total_oi['time'], btc_total_oi['open_interest_reported_future_usd'], color='black', label='Open Interest (USD)', linewidth=1, linestyle='--')

ax.set_xlabel('')
ax.set_ylabel('Amount Liquidated (USD)', fontsize=14)
ax2.set_ylabel('\nOpen Interest (USD)', fontsize=14)
ax.set_title('\nBTC Hourly Liquidations \nand Open Interest (USD)\n', fontsize=16)

locator = mdates.HourLocator(interval=6)  
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%D\n%H:%M'))  

# Format y-axis ticks for liquidations
def y_formatter(x, pos):
    if x < 0:
        return f"-${abs(x):.1f}M"
    else:
        return f"${x:.1f}M"

ax.yaxis.set_major_formatter(mticker.FuncFormatter(y_formatter))
ax.yaxis.grid(True, linestyle='--', which='major')  
ax2.yaxis.grid(False)  
ax.yaxis.tick_left()  
ax.tick_params(axis='both', length=0, labelsize=12)
ax2.tick_params(axis='both', length=0, labelsize=12) 

# Format y-axis ticks for open interest in billions
def y_formatter_billion(x, pos):
    return f"${x*1e-9:.2f}B"
ax2.yaxis.set_major_formatter(mticker.FuncFormatter(y_formatter_billion))

num_ticks = 10
yticks = np.linspace(melted_df['amount'].min(), melted_df['amount'].max(), num_ticks)
ax.set_yticks(yticks)

# Set y-ticks based on a similar range
yticks2 = np.linspace(btc_total_oi['open_interest_reported_future_usd'].min(), 
                      btc_total_oi['open_interest_reported_future_usd'].max(), num_ticks)
ax2.set_yticks(yticks2)

# Legend for both axes
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc='upper right', fontsize=10, ncol=2, framealpha=0, bbox_to_anchor=(1.08, 1.19))

plt.tight_layout()

for spine in ax2.spines.values():
    spine.set_visible(False)
for spine in ax.spines.values():
    spine.set_visible(False)

plt.show()
```

<figure><img src="/files/1mRi8mGaM6FFa4KzsDiX" alt=""><figcaption></figcaption></figure>

## Funding Rates

Funding rates are a mechanism that exchanges use to ensure that perpetual futures trade at a price that is close to the price of the underlying spot markets. The funding rate is used to calculate the funding fee which long position holders pay short position holders, or vice versa, as a way to incentivize market participants to take positions that keep perpetual futures prices close to the underlying.

Coin Metrics funding rate data from the *timeseries/market-funding-rates* endpoint includes the following fields:

* **market:** The id of the market. Market ids use the following naming convention: exchangeName-baseAsset-quoteAsset-spot for spot markets, exchangeName-futuresSymbol-future for futures markets, and exchangeName-optionsSymbol-option for options markets.
* **time:** The exchange-reported time in ISO 8601 date-time format. Always with nanoseconds precision.
* **rate:** The funding rate expressed as a percentage over the period. For example, if the funding rate is 0.10%, expressed as an 8 hour rate and calculated over the past 8 hours, the rate is 0.0010.
* **period:** The periodicity of the funding rate. If the rate is 0.0010then this rate would be applied every period defined by this field.
* **interval:** The interval of time over which the funding rate is calculated.
* **database\_time:** The timestamp when the data was saved in the database in ISO 8601 date-time format with nanoseconds precision.

```python
fr_catalog = client.catalog_market_funding_rates_v2(exchange='binance').to_dataframe()
```

```python
fr_catalog
```

|     | market                       | min\_time                        | max\_time                        |
| --- | ---------------------------- | -------------------------------- | -------------------------------- |
| 0   | binance-1000BONKUSDC-future  | 2024-05-01 00:00:00+00:00        | 2024-09-16 20:00:00+00:00        |
| 1   | binance-1000BONKUSDT-future  | 2023-11-22 16:00:00+00:00        | 2024-09-16 20:00:00+00:00        |
| 2   | binance-1000BTTCUSDT-future  | 2022-01-26 08:00:00.001000+00:00 | 2022-04-11 08:00:00+00:00        |
| 3   | binance-1000FLOKIUSDT-future | 2023-05-06 16:00:00+00:00        | 2024-09-16 16:00:00+00:00        |
| 4   | binance-1000LUNCBUSD-future  | 2022-05-30 16:00:00.005000+00:00 | 2023-06-08 08:00:00+00:00        |
| ... | ...                          | ...                              | ...                              |
| 442 | binance-ZILUSDT-future       | 2020-06-17 08:00:00.007000+00:00 | 2024-09-16 16:00:00+00:00        |
| 443 | binance-ZILUSD\_PERP-future  | 2022-04-06 08:00:00.013000+00:00 | 2022-12-26 08:00:00.014000+00:00 |
| 444 | binance-ZKUSDT-future        | 2024-06-17 12:00:00+00:00        | 2024-09-16 20:00:00+00:00        |
| 445 | binance-ZROUSDT-future       | 2024-06-20 16:00:00+00:00        | 2024-09-16 20:00:00+00:00        |
| 446 | binance-ZRXUSDT-future       | 2020-06-24 08:00:00+00:00        | 2024-09-16 16:00:00+00:00        |

447 rows × 3 columns

```python
fr_markets = [
    'bitmex-XBTUSD-future',
    'bybit-BTCUSD-future',
    'okex-BTC-USD-SWAP-future'
]
```

```python
fr_raw = client.get_market_funding_rates(
    markets = fr_markets,
    start_time=datetime.utcnow() - timedelta(days=7),
).to_dataframe()
fr_raw
```

|     | market                   | time                      | database\_time                   | rate      | period   | interval |
| --- | ------------------------ | ------------------------- | -------------------------------- | --------- | -------- | -------- |
| 0   | bitmex-XBTUSD-future     | 2024-09-10 04:00:00+00:00 | 2024-09-10 04:00:55.910555+00:00 | -0.000116 | 08:00:00 | 08:00:00 |
| 1   | bitmex-XBTUSD-future     | 2024-09-10 12:00:00+00:00 | 2024-09-10 12:00:40.929397+00:00 | 0.000037  | 08:00:00 | 08:00:00 |
| 2   | bitmex-XBTUSD-future     | 2024-09-10 20:00:00+00:00 | 2024-09-10 20:00:01.451626+00:00 | 0.000048  | 08:00:00 | 08:00:00 |
| 3   | bitmex-XBTUSD-future     | 2024-09-11 04:00:00+00:00 | 2024-09-11 04:00:15.978545+00:00 | 0.0001    | 08:00:00 | 08:00:00 |
| 4   | bitmex-XBTUSD-future     | 2024-09-11 12:00:00+00:00 | 2024-09-11 12:00:04.727025+00:00 | 0.0001    | 08:00:00 | 08:00:00 |
| ... | ...                      | ...                       | ...                              | ...       | ...      | ...      |
| 58  | okex-BTC-USD-SWAP-future | 2024-09-15 08:00:00+00:00 | 2024-09-15 08:00:05.108766+00:00 | 0.000062  | 08:00:00 | 08:00:00 |
| 59  | okex-BTC-USD-SWAP-future | 2024-09-15 16:00:00+00:00 | 2024-09-15 16:00:12.545520+00:00 | 0.000061  | 08:00:00 | 08:00:00 |
| 60  | okex-BTC-USD-SWAP-future | 2024-09-16 00:00:00+00:00 | 2024-09-16 00:00:04.734967+00:00 | 0.000046  | 08:00:00 | 08:00:00 |
| 61  | okex-BTC-USD-SWAP-future | 2024-09-16 08:00:00+00:00 | 2024-09-16 08:00:07.052638+00:00 | 0.000013  | 08:00:00 | 08:00:00 |
| 62  | okex-BTC-USD-SWAP-future | 2024-09-16 16:00:00+00:00 | 2024-09-16 16:00:06.345528+00:00 | 0.000011  | 08:00:00 | 08:00:00 |

63 rows × 6 columns

```python
# Convert 'time' to datetime for plotting, if not already in this format
fr_raw['time'] = pd.to_datetime(fr_raw['time'])
fr_raw = fr_raw.sort_values(by='time')
for column in fr_raw.columns:
    if column not in ['time', 'market']:
        fr_raw[column] = pd.to_numeric(fr_raw[column], errors='coerce') * 100
```

```python
# Create a color map
markets = fr_raw['market'].unique()
colors = plt.cm.jet(np.linspace(0, 1, len(markets)))  # Generating a color for each market
color_map = dict(zip(markets, colors))

# Plotting
plt.figure(figsize=(15, 6))
plt.gca().set_facecolor('white')
# Plot bars for each market
for market in markets:
    market_data = fr_raw[fr_raw['market'] == market]
    plt.bar(market_data['time'], market_data['rate'], color=color_map[market], label=market, width=0.07, alpha=0.9)

formatter = mticker.FuncFormatter(lambda y, _: '{:.4f}%'.format(y))
plt.gca().yaxis.set_major_formatter(formatter)
plt.grid(True, linestyle='--', which='major', color='gray', alpha=0.3)  
plt.xticks(rotation=45)
plt.xlabel('')
plt.ylabel('Funding Rate (%)')
plt.title('\nPerpetual Futures\n Funding Rates\n',fontsize=16)
plt.legend(loc='upper left', fontsize=10, bbox_to_anchor=(0.76,1.2), frameon=False)

plt.show()
```

<figure><img src="/files/oNvEUlzjj9jdswX1WJCP" alt=""><figcaption></figcaption></figure>

### Aggregated Funding Rates

Coin Metrics also calculates several aggregated funding rate metrics.

**Aggregate Funding Rate** is the average funding rate weighted by open interest, published once per hour and representing the average funding rate converted to 8 hour, 1 day, 30 day, and 1 year time periods.

* **futures\_aggregate\_funding\_rate\_usd\_margin\_\*:** metrics represent the average funding rate weighted by open interest from perpetual futures markets where the margin asset is U.S. dollars or stablecoins converted to a specified time period.
* **futures\_aggregate\_funding\_rate\_coin\_margin\_\*:** represent the average funding rate weighted by open interest from perpetual futures markets where the margin asset is equivalent to the underlying base asset converted to a specified period.
* **futures\_aggregate\_funding\_rate\_all\_margin\_\*:** represent the average funding rate weighted by open interest from all perpetual futures markets, regardless of the margin asset, converted to a specified time period.

```python
btc_fr = client.get_asset_metrics(
    assets='btc',
    start_time='2023-10-01',
    metrics = [
        'futures_aggregate_funding_rate_all_margin_1d_period',
        'futures_aggregate_funding_rate_all_margin_30d_period',
        'futures_aggregate_funding_rate_all_margin_1y_period'
        ]
).to_dataframe()
```

```python
btc_fr.head()
```

|   | asset | time                      | futures\_aggregate\_funding\_rate\_all\_margin\_1d\_period | futures\_aggregate\_funding\_rate\_all\_margin\_1y\_period | futures\_aggregate\_funding\_rate\_all\_margin\_30d\_period |
| - | ----- | ------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------- | ----------------------------------------------------------- |
| 0 | btc   | 2023-10-01 00:00:00+00:00 | 0.000101                                                   | 0.036712                                                   | 0.003017                                                    |
| 1 | btc   | 2023-10-02 00:00:00+00:00 | 0.000087                                                   | 0.031662                                                   | 0.002602                                                    |
| 2 | btc   | 2023-10-03 00:00:00+00:00 | 0.000086                                                   | 0.031306                                                   | 0.002573                                                    |
| 3 | btc   | 2023-10-04 00:00:00+00:00 | 0.000109                                                   | 0.039942                                                   | 0.003283                                                    |
| 4 | btc   | 2023-10-05 00:00:00+00:00 | 0.000071                                                   | 0.025923                                                   | 0.002131                                                    |

```python
plt.figure(figsize=(14, 8))

plt.plot(btc_fr['time'], btc_fr['futures_aggregate_funding_rate_all_margin_1d_period'] * 100, label='1D Period', color='blue')
plt.plot(btc_fr['time'], btc_fr['futures_aggregate_funding_rate_all_margin_30d_period'] * 100, label='30D Period', color='green')
plt.plot(btc_fr['time'], btc_fr['futures_aggregate_funding_rate_all_margin_1y_period'] * 100, label='1Y Period', color='red')

plt.gca().set_facecolor('white')
plt.grid(color='gray', linestyle='dotted', alpha=0.3)

plt.title('Bitcoin Perpetual Futures\nAggregated Funding Rate\n', fontsize=16)
plt.xlabel('')
plt.ylabel('Aggregate\nFunding Rate\n', fontsize=14)
plt.grid(True, alpha=0.3, linestyle='--')

# Set the formatter for the Y-axis to display percentages
formatter = mticker.FuncFormatter(lambda y, _: '{:.0f}%'.format(y))
plt.gca().yaxis.set_major_formatter(formatter)

plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator())
plt.gca().xaxis.set_major_formatter(mdates.ConciseDateFormatter(mdates.AutoDateLocator()))
plt.legend(loc='upper right', fontsize=10, ncol=1, framealpha=0, bbox_to_anchor=(0.99, 1.13))
plt.show()
```

<figure><img src="/files/tl6VINB1ko6JVxlpbzsG" alt=""><figcaption></figcaption></figure>

#### Plotting a heatmap of BTC funding rates across exchanges

```python
btc_exch_fr_catalog = client.catalog_exchange_asset_metrics_v2(metrics='futures_aggregate_funding_rate_all_margin_1y_period').to_dataframe()
btc_exch_fr_catalog = btc_exch_fr_catalog.loc[btc_exch_fr_catalog['metric']=='futures_aggregate_funding_rate_all_margin_1y_period']
btc_exch_fr_catalog = btc_exch_fr_catalog[btc_exch_fr_catalog['exchange_asset'].str.contains(r'-btc$', case=False)]
btc_exch_fr_catalog
```

```
2024-09-16 16:42:29 WARNING  /catalog/ endpoints will be deprecated in the future. Consider using /catalog-v2/ and /reference-data/ endpoints instead.
```

|        | exchange\_asset | metric                                                   | frequency | min\_time                 | max\_time                 |
| ------ | --------------- | -------------------------------------------------------- | --------- | ------------------------- | ------------------------- |
| 4711   | binance-btc     | futures\_aggregate\_funding\_rate\_all\_margin\_1y\_p... | 1d        | 2020-07-27 18:00:00+00:00 | 2024-09-16 21:00:00+00:00 |
| 24034  | bitfinex-btc    | futures\_aggregate\_funding\_rate\_all\_margin\_1y\_p... | 1d        | 2020-12-02 09:00:00+00:00 | 2024-09-16 21:00:00+00:00 |
| 29530  | bitmex-btc      | futures\_aggregate\_funding\_rate\_all\_margin\_1y\_p... | 1d        | 2020-07-27 18:00:00+00:00 | 2024-09-16 21:00:00+00:00 |
| 41723  | bybit-btc       | futures\_aggregate\_funding\_rate\_all\_margin\_1y\_p... | 1d        | 2021-05-01 20:00:00+00:00 | 2024-09-16 21:00:00+00:00 |
| 66927  | deribit-btc     | futures\_aggregate\_funding\_rate\_all\_margin\_1y\_p... | 1d        | 2020-07-27 18:00:00+00:00 | 2024-09-16 21:00:00+00:00 |
| 69721  | ftx-btc         | futures\_aggregate\_funding\_rate\_all\_margin\_1y\_p... | 1d        | 2020-07-27 18:00:00+00:00 | 2022-11-12 04:00:00+00:00 |
| 88682  | huobi-btc       | futures\_aggregate\_funding\_rate\_all\_margin\_1y\_p... | 1d        | 2020-07-27 18:00:00+00:00 | 2024-09-16 21:00:00+00:00 |
| 105482 | kraken-btc      | futures\_aggregate\_funding\_rate\_all\_margin\_1y\_p... | 1d        | 2020-10-09 09:00:00+00:00 | 2024-09-16 21:00:00+00:00 |
| 126904 | okex-btc        | futures\_aggregate\_funding\_rate\_all\_margin\_1y\_p... | 1d        | 2020-10-30 09:00:00+00:00 | 2024-09-16 21:00:00+00:00 |

```python
btc_fr_exchanges = client.get_exchange_asset_metrics(
    exchange_assets=btc_exch_fr_catalog['exchange_asset'].to_list(),
    start_time='2023-01-01',
    end_time='2023-12-31',
    metrics = 'futures_aggregate_funding_rate_all_margin_1y_period',
    frequency='1d'
).to_dataframe()
btc_fr_exchanges
```

|      | exchange\_asset | time                      | futures\_aggregate\_funding\_rate\_all\_margin\_1y\_period |
| ---- | --------------- | ------------------------- | ---------------------------------------------------------- |
| 0    | binance-btc     | 2023-01-01 00:00:00+00:00 | 0.1095                                                     |
| 1    | binance-btc     | 2023-01-02 00:00:00+00:00 | 0.012148                                                   |
| 2    | binance-btc     | 2023-01-03 00:00:00+00:00 | 0.046845                                                   |
| 3    | binance-btc     | 2023-01-04 00:00:00+00:00 | 0.041311                                                   |
| 4    | binance-btc     | 2023-01-05 00:00:00+00:00 | 0.061746                                                   |
| ...  | ...             | ...                       | ...                                                        |
| 2915 | okex-btc        | 2023-12-27 00:00:00+00:00 | 0.376005                                                   |
| 2916 | okex-btc        | 2023-12-28 00:00:00+00:00 | 0.254648                                                   |
| 2917 | okex-btc        | 2023-12-29 00:00:00+00:00 | 0.536332                                                   |
| 2918 | okex-btc        | 2023-12-30 00:00:00+00:00 | 0.455873                                                   |
| 2919 | okex-btc        | 2023-12-31 00:00:00+00:00 | 0.548358                                                   |

2920 rows × 3 columns

```python
df = btc_fr_exchanges
pivot_df = df.pivot(index='exchange_asset', columns='time', values='futures_aggregate_funding_rate_all_margin_1y_period')
pivot_df = pivot_df.astype(float)
pivot_df
```

| time            | 2023-01-01 00:00:00+00:00 | 2023-01-02 00:00:00+00:00 | 2023-01-03 00:00:00+00:00 | 2023-01-04 00:00:00+00:00 | 2023-01-05 00:00:00+00:00 | 2023-01-06 00:00:00+00:00 | 2023-01-07 00:00:00+00:00 | 2023-01-08 00:00:00+00:00 | 2023-01-09 00:00:00+00:00 | 2023-01-10 00:00:00+00:00 | ... | 2023-12-22 00:00:00+00:00 | 2023-12-23 00:00:00+00:00 | 2023-12-24 00:00:00+00:00 | 2023-12-25 00:00:00+00:00 | 2023-12-26 00:00:00+00:00 | 2023-12-27 00:00:00+00:00 | 2023-12-28 00:00:00+00:00 | 2023-12-29 00:00:00+00:00 | 2023-12-30 00:00:00+00:00 | 2023-12-31 00:00:00+00:00 |
| --------------- | ------------------------- | ------------------------- | ------------------------- | ------------------------- | ------------------------- | ------------------------- | ------------------------- | ------------------------- | ------------------------- | ------------------------- | --- | ------------------------- | ------------------------- | ------------------------- | ------------------------- | ------------------------- | ------------------------- | ------------------------- | ------------------------- | ------------------------- | ------------------------- |
| exchange\_asset |                           |                           |                           |                           |                           |                           |                           |                           |                           |                           |     |                           |                           |                           |                           |                           |                           |                           |                           |                           |                           |
| binance-btc     | 0.109500                  | 0.012148                  | 0.046845                  | 0.041311                  | 0.061746                  | 0.077517                  | 0.096432                  | 0.089722                  | 0.057266                  | 0.017031                  | ... | 0.281263                  | 0.206533                  | 0.154560                  | 0.195473                  | 0.425674                  | 0.383043                  | 0.379663                  | 0.549031                  | 0.457254                  | 0.387193                  |
| bitfinex-btc    | 0.240054                  | 0.382189                  | 0.211039                  | 0.229558                  | 0.074891                  | 0.131655                  | 0.131765                  | 0.160125                  | 0.113086                  | 0.129979                  | ... | 0.270820                  | 0.156269                  | 0.125486                  | 0.308607                  | 0.465474                  | 0.147093                  | 0.655639                  | 0.688972                  | 0.453521                  | 0.265981                  |
| bitmex-btc      | 0.109500                  | -0.147477                 | -0.027653                 | -0.075540                 | 0.109140                  | 0.058906                  | -0.078846                 | 0.109500                  | 0.109500                  | 0.109500                  | ... | 0.124057                  | 0.120385                  | 0.105715                  | 0.111534                  | 0.109102                  | 0.118988                  | 0.178754                  | 0.469497                  | 0.127023                  | 0.127770                  |
| bybit-btc       | 0.332716                  | 0.328811                  | 0.106620                  | 0.109500                  | 0.108059                  | 0.056104                  | 0.076392                  | -0.001772                 | 0.090156                  | -0.066673                 | ... | 0.109500                  | 0.109500                  | 0.109500                  | 0.109500                  | 0.109500                  | 0.109500                  | 0.109500                  | 0.109500                  | 0.109500                  | 0.109500                  |
| deribit-btc     | 0.004014                  | -0.004356                 | 0.000194                  | -0.000777                 | -0.000004                 | -0.003702                 | -0.000003                 | 0.000411                  | 0.000128                  | 0.009021                  | ... | 0.162735                  | 0.222283                  | 0.009642                  | 0.074016                  | 0.344480                  | 0.472755                  | 0.558913                  | 0.589233                  | 0.398686                  | 0.509796                  |
| huobi-btc       | 0.109500                  | 0.099561                  | 0.109500                  | 0.109500                  | -0.031955                 | 0.109500                  | 0.109500                  | 0.815508                  | -0.012098                 | 0.062326                  | ... | 0.261585                  | 1.119745                  | 0.330376                  | 0.585262                  | 0.487209                  | 1.132452                  | 0.657258                  | 0.739781                  | 0.549361                  | 0.700592                  |
| kraken-btc      | 0.030208                  | 0.040457                  | -0.095853                 | -0.027047                 | 0.061041                  | -0.130703                 | -0.061580                 | 0.036233                  | -0.006607                 | 0.217927                  | ... | 0.316554                  | 0.166807                  | 0.167266                  | 0.130185                  | 0.474480                  | 0.381600                  | 0.226822                  | 0.361264                  | 0.169106                  | 0.289377                  |
| okex-btc        | 0.209290                  | 0.191624                  | -0.019627                 | 0.007415                  | 0.206787                  | 0.104460                  | -0.038630                 | 0.124934                  | 0.025828                  | 0.020786                  | ... | 0.396916                  | 0.417243                  | -0.002470                 | 0.271116                  | 0.250061                  | 0.376005                  | 0.254648                  | 0.536332                  | 0.455873                  | 0.548358                  |

8 rows × 365 columns

```python
# Plotting the heatmap
plt.figure(figsize=(16, 8))
ax = sns.heatmap(pivot_df, cmap='viridis', annot=False)
plt.title('BTC Perp Futures\nAggregate Funding Rate (APR)\n', fontsize=14)

# Set x-ticks for monthly intervals
date_labels = [pd.to_datetime(label).strftime('%b %Y') for label in pivot_df.columns]
monthly_intervals = [i for i, label in enumerate(pivot_df.columns) if pd.to_datetime(label).day == 1]

ax.set_xticks(monthly_intervals)
ax.set_xticklabels([date_labels[i] for i in monthly_intervals], rotation=0)
ax.set_yticklabels(ax.get_yticklabels(), rotation=0)

# Formatting colorbar labels as percentages
colorbar = ax.collections[0].colorbar
colorbar.ax.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x, _: f'{x:.0%}'))

plt.xlabel('')
plt.ylabel('')
plt.show()
```

<figure><img src="/files/fJvoU1ms0E20W5urYsTv" alt=""><figcaption></figcaption></figure>

### Cumulative Funding Rate

**Cumulative Funding Rate** is the cumulative average funding rate that would be accumulated by contract holders over a specified time period. Published once per hour, representing the cumulative realized funding rate over the previous 1 day, 7 day, and 30 day time periods.

* **futures\_cumulative\_funding\_rate\_usd\_margin\_\*:** metrics represent the cumulative average funding rate weighted by open interest from futures markets where the margin asset is U.S. dollars or stablecoins over the previous specified time period.
* **futures\_cumulative\_funding\_rate\_coin\_margin\_\*:** metrics represent the cumulative average funding rate weighted by open interest from futures markets where the margin asset is equivalent to the underlying base asset over the previous specified time period.
* **futures\_cumulative\_funding\_rate\_all\_margin\_\*:** metrics represent the cumulative average funding rate weighted by open interest from all futures markets, regardless of the margin asset, over the previous specified time period.

```python
btc_cumulative_fr = client.get_asset_metrics(
    assets='btc',
    start_time='2023-01-01',
    end_time='2023-12-31',
    metrics = [
        'futures_cumulative_funding_rate_all_margin_rolling_1d',
        'futures_cumulative_funding_rate_all_margin_rolling_7d',
        'futures_cumulative_funding_rate_all_margin_rolling_30d'
        ]
).to_dataframe()
btc_cumulative_fr.head()
```

|   | asset | time                      | futures\_cumulative\_funding\_rate\_all\_margin\_rolling\_1d | futures\_cumulative\_funding\_rate\_all\_margin\_rolling\_30d | futures\_cumulative\_funding\_rate\_all\_margin\_rolling\_7d |
| - | ----- | ------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------- | ------------------------------------------------------------ |
| 0 | btc   | 2023-01-01 00:00:00+00:00 | 0.00041                                                      | 0.002146                                                      | 0.0015                                                       |
| 1 | btc   | 2023-01-02 00:00:00+00:00 | 0.000358                                                     | 0.002479                                                      | 0.001736                                                     |
| 2 | btc   | 2023-01-03 00:00:00+00:00 | 0.000128                                                     | 0.002587                                                      | 0.001735                                                     |
| 3 | btc   | 2023-01-04 00:00:00+00:00 | 0.000176                                                     | 0.002641                                                      | 0.001754                                                     |
| 4 | btc   | 2023-01-05 00:00:00+00:00 | 0.000194                                                     | 0.002957                                                      | 0.001745                                                     |

```python
for column in btc_cumulative_fr.columns:
    if column != 'time':
        btc_cumulative_fr[column] = pd.to_numeric(btc_cumulative_fr[column], errors='coerce')
```

```python
# Convert the 'time' column to datetime format if it's not already
btc_cumulative_fr['time'] = pd.to_datetime(btc_cumulative_fr['time'], errors='coerce')

# Ensure 'futures_cumulative_funding_rate_all_margin_rolling_7d' is numeric, replacing non-numeric values with numpy.nan
btc_cumulative_fr['futures_cumulative_funding_rate_all_margin_rolling_7d'] = pd.to_numeric(btc_cumulative_fr['futures_cumulative_funding_rate_all_margin_rolling_7d'], errors='coerce')

# Plotting with safe checking
valid_7d_indices = ~btc_cumulative_fr['futures_cumulative_funding_rate_all_margin_rolling_7d'].isna()
valid_30d_indices = ~btc_cumulative_fr['futures_cumulative_funding_rate_all_margin_rolling_30d'].isna()

plt.plot(btc_cumulative_fr['time'], btc_cumulative_fr['futures_cumulative_funding_rate_all_margin_rolling_1d'] * 100, label='1D Period', color='blue')
plt.plot(btc_cumulative_fr['time'][valid_7d_indices], btc_cumulative_fr['futures_cumulative_funding_rate_all_margin_rolling_7d'][valid_7d_indices] * 100, label='7D Period', color='green')
plt.plot(btc_cumulative_fr['time'][valid_30d_indices], btc_cumulative_fr['futures_cumulative_funding_rate_all_margin_rolling_30d'][valid_30d_indices] * 100, label='30D Period', color='red')

plt.gca().set_facecolor('white')
plt.grid(color='gray', linestyle='dotted', alpha=0.3)

plt.title('Bitcoin Perpetual Futures\nCumulative Funding Rate\n', fontsize=16)
plt.xlabel('')
plt.ylabel('Cumulative\nFunding Rate\n', fontsize=14)
plt.grid(True, alpha=0.3, linestyle='--')

formatter = mticker.FuncFormatter(lambda y, _: '{:.2f}%'.format(y))
plt.gca().yaxis.set_major_formatter(formatter)
plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator())
plt.gca().xaxis.set_major_formatter(mdates.ConciseDateFormatter(mdates.AutoDateLocator()))
plt.legend(loc='upper right', fontsize=10, ncol=1, framealpha=0, bbox_to_anchor=(0.99, 1.13))
plt.show()
```

<figure><img src="/files/ex4UxL2QaBIgs6Sm0vBZ" alt=""><figcaption></figcaption></figure>


# Getting Started With Options Data

{% embed url="<https://youtu.be/8Jv4lqMNF0w?feature=shared>" %}
Access and Analyze BTC Options Data
{% endembed %}

This repo demonstrates basic functionality offered by the Coin Metrics Python API Client and **Market Data Feed,** specifically for Options data.

### Resources

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics
* [Python Client docs](https://docs.coinmetrics.io/python-api-client/)

### Github Link

You can clone this repo directly to your desktop using Github Desktop, use PyCharm Github integration, etc.

{% embed url="<https://github.com/coinmetrics/terifi>" %}
Coinmetrics Repo
{% endembed %}


# Aggregating Options Data

## Coin Metrics Options Data Aggregation

This notebook demonstrates basic functionality offered by the Coin Metrics Python API Client and Market Data Feed.

Coin Metrics offers a vast assortment of data for hundreds of cryptoassets. The Python API Client allows for easy access to this data using Python without needing to create your own wrappers using `requests` and other such libraries.

### Resources

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics.
* The [Coin Metrics Product Documentation](https://docs.coinmetrics.io/info) gives detailed, conceptual explanations of the data that Coin Metrics offers.
* The [API Spec](https://docs.coinmetrics.io/python-api-client/reference) contains a full list of functions.

### File Download

Download the entire notebook as either a jupyter notebook to run yourself or as a pdf from the two links below

{% file src="/files/3VyNboGbnuMtKdBRirEH" %}

{% file src="/files/oZluZuEtcT0ZKIjo7dJu" %}

### Notebook Setup

```python
import os
from os import environ
import sys
import pandas as pd
import numpy as np
import seaborn as sns
import logging
from datetime import date, datetime, timedelta
from coinmetrics.api_client import CoinMetricsClient
import json
import logging
from datetime import timezone as timezone_info
import matplotlib.ticker as mticker
from matplotlib.ticker import ScalarFormatter
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# %matplotlib inline
from plotly import graph_objects as go
```

```python
sns.set_theme()
sns.set(rc={'figure.figsize':(14,8)})
sns.set_style("whitegrid",{'axes.grid' : True,'grid.linestyle': '--', 'grid.color': 'gray','axes.edgecolor': 'white'})
```

```python
logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S'
)
```

```python
# We recommend privately storing your API key in your local environment.
try:
    api_key = environ["CM_API_KEY"]
    logging.info("Using API key found in environment")
except KeyError:
    api_key = ""
    logging.info("API key not found. Using community client")

client = CoinMetricsClient(api_key)
```

```
2024-09-12 08:53:59 INFO     Using API key found in environment
```

#### Set start and end time

```python
end = datetime.utcnow()
start = '2024-09-01'
end = '2024-09-08'
asset = 'eth'
```

### OPTIONS CATALOG

To simplify some of the complexity around options contract size, we will investigate only options markets on Deribit, the largest options exchange by volume.

```python
asset_options = client.reference_data_markets(
    type='option',
    exchange='deribit',
    base='eth',
    quote='usd',
    page_size=10000
).to_list()
```

```python
print('Total number of supported options markets: ' + str(len(asset_options)))
```

```
Total number of supported options markets: 74827
```

#### Filter out expired/inactive contracts

```python
df_asset_options = pd.DataFrame(asset_options)
```

```python
df_asset_options.head()
```

|   | market                           | exchange | type   | base | quote | pair    | symbol            | size\_asset | strike | option\_contract\_type | ... | listing                        | expiration                     | settlement\_price | status  | order\_amount\_min | order\_price\_increment | order\_taker\_fee | order\_maker\_fee | base\_native | quote\_native |
| - | -------------------------------- | -------- | ------ | ---- | ----- | ------- | ----------------- | ----------- | ------ | ---------------------- | --- | ------------------------------ | ------------------------------ | ----------------- | ------- | ------------------ | ----------------------- | ----------------- | ----------------- | ------------ | ------------- |
| 0 | deribit-ETH-10APR20-100-P-option | deribit  | option | eth  | usd   | eth-usd | ETH-10APR20-100-P | eth         | 100    | put                    | ... | 2020-03-26T08:00:02.000000000Z | 2020-04-10T08:00:00.000000000Z | 158.1             | offline | 1                  | 0.0005                  | 0.0004            | 0.0004            | NaN          | NaN           |
| 1 | deribit-ETH-10APR20-110-P-option | deribit  | option | eth  | usd   | eth-usd | ETH-10APR20-110-P | eth         | 110    | put                    | ... | 2020-03-26T08:00:02.000000000Z | 2020-04-10T08:00:00.000000000Z | 158.1             | offline | 1                  | 0.0005                  | 0.0004            | 0.0004            | NaN          | NaN           |
| 2 | deribit-ETH-10APR20-120-C-option | deribit  | option | eth  | usd   | eth-usd | ETH-10APR20-120-C | eth         | 120    | call                   | ... | 2020-03-26T08:00:02.000000000Z | 2020-04-10T08:00:00.000000000Z | 158.1             | offline | 1                  | 0.0005                  | 0.0004            | 0.0004            | NaN          | NaN           |
| 3 | deribit-ETH-10APR20-120-P-option | deribit  | option | eth  | usd   | eth-usd | ETH-10APR20-120-P | eth         | 120    | put                    | ... | 2020-03-26T08:00:02.000000000Z | 2020-04-10T08:00:00.000000000Z | 158.1             | offline | 1                  | 0.0005                  | 0.0004            | 0.0004            | NaN          | NaN           |
| 4 | deribit-ETH-10APR20-130-C-option | deribit  | option | eth  | usd   | eth-usd | ETH-10APR20-130-C | eth         | 130    | call                   | ... | 2020-03-26T08:00:02.000000000Z | 2020-04-10T08:00:00.000000000Z | 158.1             | offline | 1                  | 0.0005                  | 0.0004            | 0.0004            | NaN          | NaN           |

5 rows × 22 columns

```python
df_asset_options.info()
```

```
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 74827 entries, 0 to 74826
Data columns (total 22 columns):
 #   Column                 Non-Null Count  Dtype 
---  ------                 --------------  ----- 
 0   market                 74827 non-null  object
 1   exchange               74827 non-null  object
 2   type                   74827 non-null  object
 3   base                   74827 non-null  object
 4   quote                  74827 non-null  object
 5   pair                   74827 non-null  object
 6   symbol                 74827 non-null  object
 7   size_asset             74827 non-null  object
 8   strike                 74827 non-null  object
 9   option_contract_type   74827 non-null  object
 10  is_european            74827 non-null  bool  
 11  contract_size          74827 non-null  object
 12  listing                74827 non-null  object
 13  expiration             74827 non-null  object
 14  settlement_price       74117 non-null  object
 15  status                 74827 non-null  object
 16  order_amount_min       74827 non-null  object
 17  order_price_increment  74827 non-null  object
 18  order_taker_fee        74827 non-null  object
 19  order_maker_fee        74827 non-null  object
 20  base_native            3558 non-null   object
 21  quote_native           3558 non-null   object
dtypes: bool(1), object(21)
memory usage: 12.1+ MB
```

```python
df_asset_options['listing'] = pd.to_datetime(df_asset_options['listing'])
df_asset_options['expiration'] = pd.to_datetime(df_asset_options['expiration'])

df_asset_options = df_asset_options.loc[((df_asset_options.listing > start) & (df_asset_options.listing < end))]
df_asset_options
```

|       | market                            | exchange | type   | base | quote | pair    | symbol             | size\_asset | strike | option\_contract\_type | ... | listing                   | expiration                | settlement\_price | status  | order\_amount\_min | order\_price\_increment | order\_taker\_fee | order\_maker\_fee | base\_native | quote\_native |
| ----- | --------------------------------- | -------- | ------ | ---- | ----- | ------- | ------------------ | ----------- | ------ | ---------------------- | --- | ------------------------- | ------------------------- | ----------------- | ------- | ------------------ | ----------------------- | ----------------- | ----------------- | ------------ | ------------- |
| 2384  | deribit-ETH-10SEP24-1950-C-option | deribit  | option | eth  | usd   | eth-usd | ETH-10SEP24-1950-C | eth         | 1950   | call                   | ... | 2024-09-07 08:00:09+00:00 | 2024-09-10 08:00:00+00:00 | 2360.48           | offline | 1                  | 0.0001                  | 0.0003            | 0.0003            | ETH          | USD           |
| 2385  | deribit-ETH-10SEP24-1950-P-option | deribit  | option | eth  | usd   | eth-usd | ETH-10SEP24-1950-P | eth         | 1950   | put                    | ... | 2024-09-07 08:00:09+00:00 | 2024-09-10 08:00:00+00:00 | 2360.48           | offline | 1                  | 0.0001                  | 0.0003            | 0.0003            | ETH          | USD           |
| 2386  | deribit-ETH-10SEP24-2000-C-option | deribit  | option | eth  | usd   | eth-usd | ETH-10SEP24-2000-C | eth         | 2000   | call                   | ... | 2024-09-07 08:00:09+00:00 | 2024-09-10 08:00:00+00:00 | 2360.48           | offline | 1                  | 0.0001                  | 0.0003            | 0.0003            | ETH          | USD           |
| 2387  | deribit-ETH-10SEP24-2000-P-option | deribit  | option | eth  | usd   | eth-usd | ETH-10SEP24-2000-P | eth         | 2000   | put                    | ... | 2024-09-07 08:00:09+00:00 | 2024-09-10 08:00:00+00:00 | 2360.48           | offline | 1                  | 0.0001                  | 0.0003            | 0.0003            | ETH          | USD           |
| 2388  | deribit-ETH-10SEP24-2050-C-option | deribit  | option | eth  | usd   | eth-usd | ETH-10SEP24-2050-C | eth         | 2050   | call                   | ... | 2024-09-07 08:00:09+00:00 | 2024-09-10 08:00:00+00:00 | 2360.48           | offline | 1                  | 0.0001                  | 0.0003            | 0.0003            | ETH          | USD           |
| ...   | ...                               | ...      | ...    | ...  | ...   | ...     | ...                | ...         | ...    | ...                    | ... | ...                       | ...                       | ...               | ...     | ...                | ...                     | ...               | ...               | ...          | ...           |
| 74822 | deribit-ETH-9SEP24-2800-P-option  | deribit  | option | eth  | usd   | eth-usd | ETH-9SEP24-2800-P  | eth         | 2800   | put                    | ... | 2024-09-06 08:00:10+00:00 | 2024-09-09 08:00:00+00:00 | 2311.75           | offline | 1                  | 0.0001                  | 0.0003            | 0.0003            | ETH          | USD           |
| 74823 | deribit-ETH-9SEP24-2850-C-option  | deribit  | option | eth  | usd   | eth-usd | ETH-9SEP24-2850-C  | eth         | 2850   | call                   | ... | 2024-09-06 08:00:10+00:00 | 2024-09-09 08:00:00+00:00 | 2311.75           | offline | 1                  | 0.0001                  | 0.0003            | 0.0003            | ETH          | USD           |
| 74824 | deribit-ETH-9SEP24-2850-P-option  | deribit  | option | eth  | usd   | eth-usd | ETH-9SEP24-2850-P  | eth         | 2850   | put                    | ... | 2024-09-06 08:00:10+00:00 | 2024-09-09 08:00:00+00:00 | 2311.75           | offline | 1                  | 0.0001                  | 0.0003            | 0.0003            | ETH          | USD           |
| 74825 | deribit-ETH-9SEP24-2900-C-option  | deribit  | option | eth  | usd   | eth-usd | ETH-9SEP24-2900-C  | eth         | 2900   | call                   | ... | 2024-09-06 10:37:00+00:00 | 2024-09-09 08:00:00+00:00 | 2311.75           | offline | 1                  | 0.0001                  | 0.0003            | 0.0003            | ETH          | USD           |
| 74826 | deribit-ETH-9SEP24-2900-P-option  | deribit  | option | eth  | usd   | eth-usd | ETH-9SEP24-2900-P  | eth         | 2900   | put                    | ... | 2024-09-06 10:37:00+00:00 | 2024-09-09 08:00:00+00:00 | 2311.75           | offline | 1                  | 0.0001                  | 0.0003            | 0.0003            | ETH          | USD           |

376 rows × 22 columns

## TRADE VOLUME

On Deribit, each option contract provides notional exposure to 1 unit of the underlying asset (i.e. 1 BTC or 1 ETH). To calculate options volume, we must multiply the 'amount' field (representing the number of contracts traded) by the USD price of the underlying asset.

```python
list_options_markets = list(df_asset_options.market.unique())
```

```python
full_vol = pd.DataFrame()
batch_size = 420

for i in range(0, len(list_options_markets),batch_size):
    mkt_batch = list_options_markets[i:i+batch_size]
    print(str('Retrieving batch of trades for markets ' + str(i) + ' - ' + str(i+batch_size) + '...'))

    vol_batch = client.get_market_trades(
        markets=mkt_batch,
        start_time = start,
        end_time= end,
        page_size=10000
    ).to_dataframe()
    print('Retrieved batch of ' + str(len(vol_batch)) + ' trades')
    
    full_vol = pd.concat((full_vol, vol_batch), axis = 0, ignore_index=False)
    print('Total of ' + str(len(full_vol)) + ' trades\n')

full_vol = full_vol.reset_index(drop=True)
```

```
Retrieving batch of trades for markets 0 - 420...


Retrieved batch of 12012 trades
Total of 12012 trades
```

```python
full_vol = full_vol[['market','time','amount']]
full_vol = full_vol[~(full_vol['time'] > end)]
full_vol.sort_values('time')
```

|       | market                           | time                             | amount |
| ----- | -------------------------------- | -------------------------------- | ------ |
| 1071  | deribit-ETH-3SEP24-2375-P-option | 2024-09-01 06:55:13.947000+00:00 | 1      |
| 1072  | deribit-ETH-3SEP24-2375-P-option | 2024-09-01 08:04:42.145000+00:00 | 1      |
| 1073  | deribit-ETH-3SEP24-2375-P-option | 2024-09-01 08:07:41.254000+00:00 | 3      |
| 2429  | deribit-ETH-4SEP24-2550-C-option | 2024-09-01 08:33:21.911000+00:00 | 1      |
| 2805  | deribit-ETH-4SEP24-2700-C-option | 2024-09-01 08:47:26.803000+00:00 | 14     |
| ...   | ...                              | ...                              | ...    |
| 11208 | deribit-ETH-9SEP24-2300-C-option | 2024-09-07 23:54:16.170000+00:00 | 9      |
| 9225  | deribit-ETH-8SEP24-2325-C-option | 2024-09-07 23:54:52.991000+00:00 | 2      |
| 8166  | deribit-ETH-8SEP24-2050-P-option | 2024-09-07 23:57:33.509000+00:00 | 2      |
| 9650  | deribit-ETH-8SEP24-2400-C-option | 2024-09-07 23:58:04.697000+00:00 | 1      |
| 9651  | deribit-ETH-8SEP24-2400-C-option | 2024-09-07 23:58:53.038000+00:00 | 1      |

10824 rows × 3 columns

#### Retrieve 1-minute Reference Rate

```python
df_refrate = client.get_asset_metrics(
    assets=asset,
    frequency='1m',
    metrics='ReferenceRateUSD',
    start_time=start,
    end_time=end
).to_dataframe()
```

```python
df_refrate = df_refrate.set_index('time').sort_index().drop(columns=['asset'])
df_refrate
```

|                           | ReferenceRateUSD |
| ------------------------- | ---------------- |
| time                      |                  |
| 2024-09-01 00:00:00+00:00 | 2512.79          |
| 2024-09-01 00:01:00+00:00 | 2512.41          |
| 2024-09-01 00:02:00+00:00 | 2510.65          |
| 2024-09-01 00:03:00+00:00 | 2513.37          |
| 2024-09-01 00:04:00+00:00 | 2511.32          |
| ...                       | ...              |
| 2024-09-08 23:55:00+00:00 | 2298.15          |
| 2024-09-08 23:56:00+00:00 | 2297.49          |
| 2024-09-08 23:57:00+00:00 | 2294.79          |
| 2024-09-08 23:58:00+00:00 | 2296.77          |
| 2024-09-08 23:59:00+00:00 | 2298.61          |

11520 rows × 1 columns

```python
full_vol['time'] = full_vol['time'].round('T')

# Merge trades data with 1s reference rate
full_vol = full_vol.merge(df_refrate.reset_index(),how='left', on='time')
```

#### Calculate USD value of trades

```python
full_vol['USD Volume'] = full_vol['amount'] * full_vol['ReferenceRateUSD']
```

```python
full_vol
```

|       | market                            | time                      | amount | ReferenceRateUSD | USD Volume |
| ----- | --------------------------------- | ------------------------- | ------ | ---------------- | ---------- |
| 0     | deribit-ETH-10SEP24-1950-P-option | 2024-09-07 09:06:00+00:00 | 5      | 2293.8           | 11469.0    |
| 1     | deribit-ETH-10SEP24-1950-P-option | 2024-09-07 09:43:00+00:00 | 10     | 2279.45          | 22794.5    |
| 2     | deribit-ETH-10SEP24-1950-P-option | 2024-09-07 09:43:00+00:00 | 9      | 2279.45          | 20515.05   |
| 3     | deribit-ETH-10SEP24-1950-P-option | 2024-09-07 09:43:00+00:00 | 1      | 2279.45          | 2279.45    |
| 4     | deribit-ETH-10SEP24-1950-P-option | 2024-09-07 11:42:00+00:00 | 5      | 2285.0           | 11425.0    |
| ...   | ...                               | ...                       | ...    | ...              | ...        |
| 10819 | deribit-ETH-9SEP24-2750-C-option  | 2024-09-06 17:38:00+00:00 | 1      | 2235.41          | 2235.41    |
| 10820 | deribit-ETH-9SEP24-2750-C-option  | 2024-09-07 17:02:00+00:00 | 5      | 2288.46          | 11442.3    |
| 10821 | deribit-ETH-9SEP24-2750-C-option  | 2024-09-07 18:21:00+00:00 | 45     | 2278.46          | 102530.7   |
| 10822 | deribit-ETH-9SEP24-2750-C-option  | 2024-09-07 18:21:00+00:00 | 23     | 2278.46          | 52404.58   |
| 10823 | deribit-ETH-9SEP24-2800-P-option  | 2024-09-06 17:37:00+00:00 | 1      | 2233.79          | 2233.79    |

10824 rows × 5 columns

```python
vol_sum = full_vol.groupby(pd.Grouper(key='time', axis=0, freq='1D', sort=True)).sum()
```

```python
vol_sum.to_csv('./deribit_' + str(asset).upper() + '_options_vol_' + str(start) + '_to_' + str(end) + '.csv')
```

```python
vol_sum[['USD Volume']]
```

|                           | USD Volume   |
| ------------------------- | ------------ |
| time                      |              |
| 2024-09-01 00:00:00+00:00 | 5424658.14   |
| 2024-09-02 00:00:00+00:00 | 19562749.43  |
| 2024-09-03 00:00:00+00:00 | 40646881.35  |
| 2024-09-04 00:00:00+00:00 | 63609486.54  |
| 2024-09-05 00:00:00+00:00 | 44657679.33  |
| 2024-09-06 00:00:00+00:00 | 158263998.37 |
| 2024-09-07 00:00:00+00:00 | 44401580.5   |

```python
v = vol_sum.plot.line(y='USD Volume')
v.set_xlabel("Date", fontsize = 15)
plt.setp(v.get_yticklabels(), fontsize=13)
plt.setp(v.get_xticklabels(), fontsize=13)
v.set_xlabel("")
plt.xlim([vol_sum.index[0], vol_sum.index[-1]])
v.set_ylabel("Daily Volume (USD)\n", fontsize = 15)
v.set_title(('\nDeribit ' + str(asset).upper() + ' Options Volume\n'),fontsize=23)
v.get_legend().remove()
v.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x, pos: '${:,.1f}'.format(x/1000000) + 'M'))
```

<figure><img src="/files/XzL7yD4Iwc0Gtvqr4xd5" alt=""><figcaption></figcaption></figure>

## OPEN INTEREST

Open interest represents the number of contracts that are currently outstanding and not settled for a specific derivatives market.

```python
# Drop markets without open interest data
oi_cat = df_asset_options.loc[df_asset_options.listing < end, 'market'].tolist()
len(oi_cat)
```

```
376
```

```python
full_oi = pd.DataFrame()
batch_size = 420

for i in range(0, len(oi_cat),batch_size):
    mkt_batch = oi_cat[i:i+batch_size]
    print(str('\nRetrieving EOD open interest for markets ' + str(i) + ' through ' + str(i+batch_size) + '...'))
    
    start_date = pd.to_datetime(start)
    end_date = pd.to_datetime(end)
    delta = timedelta(days=1)
    print(str(start_date) + '\n...')
    
    while start_date <= end_date:
        
        oi_batch = client.get_market_open_interest(
            markets=mkt_batch,
            start_time = start_date.strftime("%Y-%m-%d"),
            limit_per_market = 1,
            paging_from='start',
            timezone='America/New_York'
        ).to_dataframe()
        #print(oi_batch)
        full_oi = pd.concat((full_oi, oi_batch), axis = 0, ignore_index=False)
        start_date += delta
        
    print(start_date)
```

```
Retrieving EOD open interest for markets 0 through 420...
2024-09-01 00:00:00
...


2024-09-09 00:00:00
```

```python
full_oi.info()
```

```
<class 'pandas.core.frame.DataFrame'>
Index: 2534 entries, 0 to 193
Data columns (total 6 columns):
 #   Column          Non-Null Count  Dtype              
---  ------          --------------  -----              
 0   market          2534 non-null   string             
 1   time            2534 non-null   datetime64[ns, UTC]
 2   contract_count  2534 non-null   Int64              
 3   value_usd       2534 non-null   Float64            
 4   database_time   2534 non-null   datetime64[ns, UTC]
 5   exchange_time   2534 non-null   datetime64[ns, UTC]
dtypes: Float64(1), Int64(1), datetime64[ns, UTC](3), string(1)
memory usage: 143.5 KB
```

```python
oi_sum = full_oi.groupby(pd.Grouper(key='time', axis=0, freq='1D', sort=True))['value_usd'].sum()
```

```python
oi_sum.to_csv('./deribit_' + str(asset).upper() + '_options_oi_' + str(start) + '_to_' + str(end) + '.csv')
oi_sum
```

```
time
2024-09-01 00:00:00+00:00             0.0
2024-09-02 00:00:00+00:00      6467612.33
2024-09-03 00:00:00+00:00     24927750.02
2024-09-04 00:00:00+00:00     55323320.59
2024-09-05 00:00:00+00:00     59305999.71
2024-09-06 00:00:00+00:00      51922555.8
2024-09-07 00:00:00+00:00    144108764.26
2024-09-08 00:00:00+00:00    122269418.49
Freq: D, Name: value_usd, dtype: Float64
```

```python
#p = sns.lineplot(data=vol_sum, x="time", y="USD Volume")
oi = oi_sum.plot.area(y='value_usd')
oi.set_xlabel("Date", fontsize = 15)
plt.setp(oi.get_yticklabels(), fontsize=13)
plt.setp(oi.get_xticklabels(), fontsize=13)
oi.set_xlabel("")
plt.xlim([oi_sum.index[0], oi_sum.index[-1]])
oi.set_ylabel("Daily Open Interest (USD)\n", fontsize = 15)
oi.set_title(('\nDeribit ' + str(asset).upper() + ' Options Open Interest\n'),fontsize=23)
# oi.get_legend().remove()
oi.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x, pos: '${:,.2f}'.format(x/1_000_000) + 'M'))
```

<figure><img src="/files/UKUYJMjgBBjRt5hLvy3U" alt=""><figcaption></figcaption></figure>

### Split into Calls/Puts

```python
full_oi_split = full_oi.merge(df_asset_options[['market','option_contract_type']],how='left', on='market')
```

```python
full_oi_split
```

|      | market                            | time                      | contract\_count | value\_usd | database\_time                   | exchange\_time            | option\_contract\_type |
| ---- | --------------------------------- | ------------------------- | --------------- | ---------- | -------------------------------- | ------------------------- | ---------------------- |
| 0    | deribit-ETH-10SEP24-1950-C-option | 2024-09-07 08:00:00+00:00 | 0               | 0.0        | 2024-09-07 08:00:19.312717+00:00 | 2024-09-07 08:00:00+00:00 | call                   |
| 1    | deribit-ETH-10SEP24-1950-P-option | 2024-09-07 08:00:00+00:00 | 0               | 0.0        | 2024-09-07 08:00:18.188738+00:00 | 2024-09-07 08:00:00+00:00 | put                    |
| 2    | deribit-ETH-10SEP24-2000-C-option | 2024-09-07 08:00:00+00:00 | 0               | 0.0        | 2024-09-07 08:00:18.188738+00:00 | 2024-09-07 08:00:00+00:00 | call                   |
| 3    | deribit-ETH-10SEP24-2000-P-option | 2024-09-07 08:00:00+00:00 | 0               | 0.0        | 2024-09-07 08:00:18.708225+00:00 | 2024-09-07 08:00:00+00:00 | put                    |
| 4    | deribit-ETH-10SEP24-2050-C-option | 2024-09-07 08:00:00+00:00 | 0               | 0.0        | 2024-09-07 08:00:18.708225+00:00 | 2024-09-07 08:00:00+00:00 | call                   |
| ...  | ...                               | ...                       | ...             | ...        | ...                              | ...                       | ...                    |
| 2529 | deribit-ETH-9SEP24-2800-P-option  | 2024-09-08 04:00:00+00:00 | 1               | 2285.35    | 2024-09-08 04:00:06.461248+00:00 | 2024-09-08 04:00:00+00:00 | put                    |
| 2530 | deribit-ETH-9SEP24-2850-C-option  | 2024-09-08 04:00:00+00:00 | 0               | 0.0        | 2024-09-08 04:00:01.855497+00:00 | 2024-09-08 04:00:00+00:00 | call                   |
| 2531 | deribit-ETH-9SEP24-2850-P-option  | 2024-09-08 04:00:00+00:00 | 0               | 0.0        | 2024-09-08 04:00:03.353208+00:00 | 2024-09-08 04:00:00+00:00 | put                    |
| 2532 | deribit-ETH-9SEP24-2900-C-option  | 2024-09-08 04:00:00+00:00 | 0               | 0.0        | 2024-09-08 04:00:04.393566+00:00 | 2024-09-08 04:00:00+00:00 | call                   |
| 2533 | deribit-ETH-9SEP24-2900-P-option  | 2024-09-08 04:00:00+00:00 | 0               | 0.0        | 2024-09-08 04:00:02.869006+00:00 | 2024-09-08 04:00:00+00:00 | put                    |

2534 rows × 7 columns

```python
calls = full_oi_split.loc[(full_oi_split.option_contract_type == 'call')]
call_sum_split = calls.groupby(pd.Grouper(key='time', axis=0, freq='1D', sort=True))[['value_usd']].sum()
puts = full_oi_split.loc[(full_oi_split.option_contract_type == 'put')]
put_sum_split = puts.groupby(pd.Grouper(key='time', axis=0, freq='1D', sort=True))[['value_usd']].sum()
```

```python
put_sum_split = put_sum_split.rename(columns={"value_usd": "Puts - USD Value", "contract_count": "Puts - Contract Count" })
call_sum_split = call_sum_split.rename(columns={"value_usd": "Calls - USD Value", "contract_count": "Calls - Contract Count" })
```

```python
full_oi_split = call_sum_split.merge(put_sum_split,how='left', on='time')
full_oi_split
```

|                           | Calls - USD Value | Puts - USD Value |
| ------------------------- | ----------------- | ---------------- |
| time                      |                   |                  |
| 2024-09-01 00:00:00+00:00 | 0.0               | 0.0              |
| 2024-09-02 00:00:00+00:00 | 4987937.59        | 1479674.74       |
| 2024-09-03 00:00:00+00:00 | 14177673.6        | 10750076.42      |
| 2024-09-04 00:00:00+00:00 | 30418324.31       | 24904996.28      |
| 2024-09-05 00:00:00+00:00 | 37814891.94       | 21491107.77      |
| 2024-09-06 00:00:00+00:00 | 24772293.7        | 27150262.1       |
| 2024-09-07 00:00:00+00:00 | 73624086.44       | 70484677.82      |
| 2024-09-08 00:00:00+00:00 | 61750871.09       | 60518547.4       |

```python
full_oi_split['Put/Call Ratio'] = full_oi_split['Puts - USD Value'] / full_oi_split['Calls - USD Value']
full_oi_split[['Put/Call Ratio']]
```

|                           | Put/Call Ratio |
| ------------------------- | -------------- |
| time                      |                |
| 2024-09-01 00:00:00+00:00 | NaN            |
| 2024-09-02 00:00:00+00:00 | 0.296651       |
| 2024-09-03 00:00:00+00:00 | 0.75824        |
| 2024-09-04 00:00:00+00:00 | 0.81875        |
| 2024-09-05 00:00:00+00:00 | 0.568324       |
| 2024-09-06 00:00:00+00:00 | 1.095993       |
| 2024-09-07 00:00:00+00:00 | 0.957359       |
| 2024-09-08 00:00:00+00:00 | 0.980044       |

```python
full_oi_split.to_csv('./deribit_' + str(asset).upper() + '_options_oi_calls_puts_' + str(start) + '_to_' + str(end) + '.csv')
```

```python
pc = sns.lineplot(data=full_oi_split[['Put/Call Ratio']], x="time", y="Put/Call Ratio")
pc.set_xlabel("Date", fontsize = 15)
plt.setp(pc.get_yticklabels(), fontsize=13)
plt.setp(pc.get_xticklabels(), fontsize=13)
pc.set_xlabel("")
plt.xlim([full_oi_split.index[0], full_oi_split.index[-1]])
pc.set_ylabel("Put/Call Ratio\n", fontsize = 15)
pc.set_title(('\nDeribit ' + str(asset).upper() + ' Options\nPut/Call Ratio\n'),fontsize=23)
pc.yaxis.set_major_formatter(mticker.FuncFormatter(lambda x, pos: '{:,.2f}'.format(x)))
```

<figure><img src="/files/jSgZF8Vf7YoasU3zPOvE" alt=""><figcaption></figcaption></figure>


# Reconstructing the Order Book from Snapshots and Updates

An order book is the outstanding bids and asks for a market, by price level. Coin Metrics serves it **three ways** — the three delivery schemas:

1. **Historical snapshots** — periodic point-in-time state of the whole book.
2. **Historical updates + snapshots** — the full event-driven stream of level changes; reconstruct the exact book at any timestamp (`dataset=updates`).
3. **Real-time streaming** — a live websocket that opens with a snapshot, then streams updates.

All three share **one** `[price, size]` message shape (a `size` of `0` removes a level), so the **same reconstruction code works across all of them**. This notebook is fully self-contained — every cell uses the Coin Metrics Python client directly — and it makes the point concrete by **streaming a live sample, then replaying the exact same time window from the historical `updates` dataset**.

### Resources

This notebook demonstrates basic functionality offered by the Coin Metrics Python API Client and Market Data Feed.

Coin Metrics offers a vast assortment of data for hundreds of cryptoassets. The Python API Client allows for easy access to this data using Python without needing to create your own wrappers using `requests` and other such libraries.

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics.
* The [Coin Metrics Product Documentation](https://docs.coinmetrics.io/info) gives detailed, conceptual explanations of the data that Coin Metrics offers.
* The [API Spec](https://docs.coinmetrics.io/python-api-client/reference) contains a full list of functions.

### File Download

Download the notebook to run it yourself:

{% file src="/files/r0t0kDnfV65Dt95dBYKY" %}

## Setup

The only dependency is the Coin Metrics Python API client (`pip install coinmetrics-api-client`). The API key is read from the environment — never hardcode it.

```python
import os, json, time
from datetime import timedelta
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, PillowWriter
from IPython.display import Image, display
from coinmetrics.api_client import CoinMetricsClient

client = CoinMetricsClient(os.environ["CM_API_KEY"])
MARKET = 'coinbase-btc-usd-spot'
DEPTH_PCT = 0.001   # depth band around the mid (0.001 = 0.1%)
```

## Schema 1 — Historical snapshots

The simplest shape: a periodic **snapshot** of the whole book. Coin Metrics stores three snapshot products — the top **100** levels and all levels **within 10% of mid** every **10s**, and the **full book hourly**. We pull the latest few (top-100) and show the top of the most recent one:

```python
# Latest few snapshots (default "snapshots" dataset), returned as a DataFrame.
# limit_per_market + paging_from use format="json" (json_stream always streams from start).
snaps = client.get_market_orderbooks(
    markets=[MARKET],
    limit_per_market=3,
    depth_limit="100",
    paging_from="end",
    format="json",
).to_dataframe()

latest = snaps.sort_values("time").iloc[-1]   # most recent snapshot
print(f"latest snapshot: {latest['time']}")
pd.DataFrame({
    "bid_price": [l["price"] for l in latest["bids"][:5]],
    "bid_size":  [l["size"]  for l in latest["bids"][:5]],
    "ask_price": [l["price"] for l in latest["asks"][:5]],
    "ask_size":  [l["size"]  for l in latest["asks"][:5]],
})
```

```
latest snapshot: 2026-07-07 05:31:59.984346+00:00
```

|   | bid\_price | bid\_size  | ask\_price | ask\_size  |
| - | ---------- | ---------- | ---------- | ---------- |
| 0 | 63033.89   | 0.36320277 | 63033.9    | 0.09268223 |
| 1 | 63033.88   | 0.03       | 63035.48   | 0.05552568 |
| 2 | 63033.86   | 0.03       | 63036.42   | 0.00022309 |
| 3 | 63033.8    | 0.00079322 | 63037.05   | 0.01784664 |
| 4 | 63032.01   | 0.11820631 | 63037.61   | 0.0694071  |

## Reconstructing the book

Both the update stream and the websocket deliver the same messages: a `snapshot` is the full state; an `update` carries absolute `[price, size]` levels where a `size` of `0` removes the level. To maintain the book, treat **every** `snapshot` as a full reset (a redundant-stream failover can emit an out-of-band snapshot), then apply updates in time order. That's the whole algorithm:

```python
def new_book():
    return {"bids": {}, "asks": {}}   # price -> size, per side

def apply_message(book, msg):
    if msg.get("type") == "snapshot":       # full state replacement
        book["bids"].clear()
        book["asks"].clear()
    for side in ("bids", "asks"):           # snapshot or update: apply levels
        levels = msg.get(side)
        if levels is None:
            continue
        for level in levels:
            price, size = float(level["price"]), float(level["size"])
            if size == 0:
                book[side].pop(price, None)  # level removed
            else:
                book[side][price] = size

def best_bid_ask(book):
    bid = max(book["bids"]) if book["bids"] else None
    ask = min(book["asks"]) if book["asks"] else None
    return bid, ask
```

And a small helper to **animate** the top of the book as messages are applied. The *same* function works on live websocket messages and on historical `updates` rows — because they are the same message shape. Levels are drawn by rank (best bid/ask at the center, deeper levels outward) so the bars stay readable and never overlap:

```python
GREEN, CORAL, DARK, TEXT, MUTED = "#22CAAD", "#F96167", "#10121A", "#C9D2DC", "#8E97A8"

def animate_book(messages, out_path, title, top_n=12, max_frames=100, fps=12):
    book, frames = new_book(), []
    for msg in messages:
        apply_message(book, msg)
        if not book["bids"] or not book["asks"]:
            continue
        bids = sorted(book["bids"], reverse=True)[:top_n]
        asks = sorted(book["asks"])[:top_n]
        frames.append(([(p, book["bids"][p]) for p in bids],
                       [(p, book["asks"][p]) for p in asks]))
    if len(frames) > max_frames:
        frames = frames[:: max(1, len(frames) // max_frames)]

    ymax = max((s for b, a in frames for _, s in b + a), default=1.0) * 1.1
    fig, ax = plt.subplots(figsize=(7, 4))
    fig.patch.set_facecolor(DARK)

    def draw(i):
        ax.clear(); ax.set_facecolor(DARK)
        bids, asks = frames[i]
        ax.bar([-(j + 0.5) for j in range(len(bids))], [s for _, s in bids], width=0.9, color=GREEN)
        ax.bar([(j + 0.5) for j in range(len(asks))], [s for _, s in asks], width=0.9, color=CORAL)
        ax.axvline(0, color=MUTED, ls="--", lw=0.8, alpha=0.6)
        ax.text(-0.5, ymax * 0.99, f"bid {bids[0][0]:,.2f}", color=GREEN, fontsize=7.5, ha="right", va="top")
        ax.text(0.5, ymax * 0.99, f"ask {asks[0][0]:,.2f}", color=CORAL, fontsize=7.5, ha="left", va="top")
        ax.text(-(len(bids) - 0.5), ymax * 0.88, f"{bids[-1][0]:,.2f}", color=MUTED, fontsize=6, ha="center", va="top")
        ax.text((len(asks) - 0.5), ymax * 0.88, f"{asks[-1][0]:,.2f}", color=MUTED, fontsize=6, ha="center", va="top")
        ax.set_xlim(-(top_n + 0.5), top_n + 0.5); ax.set_ylim(0, ymax); ax.set_xticks([])
        ax.set_title(f"{title} · frame {i + 1}/{len(frames)}", color=TEXT, fontsize=10)
        ax.set_xlabel("best bid/ask at center · deeper levels outward   (bids ←  |  → asks)", color=TEXT, fontsize=8)
        ax.set_ylabel("size", color=TEXT, fontsize=8)
        ax.tick_params(colors=TEXT, labelsize=7)
        for sp in ("top", "right"): ax.spines[sp].set_visible(False)
        for sp in ("left", "bottom"): ax.spines[sp].set_color(MUTED)

    anim = FuncAnimation(fig, draw, frames=len(frames), interval=1000 / fps)
    anim.save(out_path, writer=PillowWriter(fps=fps), savefig_kwargs={"facecolor": DARK})
    plt.close(fig)
    return out_path
```

## Schema 3 — Real-time streaming

The websocket feed opens with a `snapshot`, then sends `update` messages as the book changes (with occasional re-sync snapshots) — **the production path** for a live book. We subscribe at **`depth_limit="full_book"`** (the stream defaults to top-100) so the live feed matches the historical `updates` dataset, which is full-book — making the two directly comparable. We take a small live sample and **record the time window it spans**, so we can replay exactly that window from history next.

> This cell is *live*: its exact messages (and window) differ every run — unlike the historical replay below, which is reproducible.

```python
def stream_sample(market, n, max_seconds=120):
    """Consume `n` websocket messages, then close. Full-book to match the updates dataset."""
    stream = client.get_stream_market_orderbooks(markets=[market], depth_limit="full_book")
    messages = []
    start = time.time()
    def on_message(ws, message):
        messages.append(json.loads(message))
        if len(messages) >= n or time.time() - start > max_seconds:
            ws.close()
    stream.run(on_message=on_message, reconnect=False)
    return messages

live_msgs = stream_sample(MARKET, n=800)
times = sorted(m["time"] for m in live_msgs)
# The window we just watched, truncated to whole seconds (the messages carry
# nanosecond timestamps; .parallel() chunking needs a second-precision start/end).
win_start, win_end = times[0][:19] + "Z", times[-1][:19] + "Z"
live_changes = sum(len(m.get("asks") or []) + len(m.get("bids") or []) for m in live_msgs)
print(f"{len(live_msgs):,} live messages, {live_changes:,} level-changes")
print(f"streamed window: {win_start} -> {win_end}")
live_msgs[0]
```

```
800 live messages, 85,120 level-changes
streamed window: 2026-07-07T05:31:59Z -> 2026-07-07T05:32:12Z





{'market': 'coinbase-btc-usd-spot',
 'time': '2026-07-07T05:31:59.984346000Z',
 'coin_metrics_id': 'FxT65kMNSy6PL0celq9B7AAAAACEbj6G',
 'asks': [{'price': '63033.9', 'size': '0.09268223'},
  {'price': '63035.48', 'size': '0.05552568'},
  {'price': '63036.42', 'size': '0.00022309'},
  {'price': '63037.05', 'size': '0.01784664'},
  {'price': '63037.61', 'size': '0.0694071'},
  {'price': '63038', 'size': '0.0815'},
  {'price': '63039.97', 'size': '0.00794908'},
  {'price': '63039.98', 'size': '0.02'},
  {'price': '63040', 'size': '0.0815'},
  {'price': '63041.11', 'size': '0.02'},
  {'price': '63041.12', 'size': '0.32528252'},
  {'price': '63041.13', 'size': '0.12690129'},
  {'price': '63041.98', 'size': '0.09541977'},
  {'price': '63041.99', 'size': '0.04781428'},
  {'price': '63042', 'size': '0.085718'},
  {'price': '63042.83', 'size': '0.000097'},
  {'price': '63043.97', 'size': '0.06345327'},
  {'price': '63043.99', 'size': '0.03975824'},
  {'price': '63044', 'size': '0.0857'},
  {'price': '63044.28', 'size': '0.22040213'},
  {'price': '63044.29', 'size': '0.09541977'},
  {'price': '63044.86', 'size': '0.00485'},
  {'price': '63045', 'size': '0.01'},
  {'price': '63045.06', 'size': '0.15861672'},
  {'price': '63045.48', 'size': '0.00583'},
  {'price': '63045.95', 'size': '0.000018'},
  {'price': '63046', 'size': '0.0857'},
  {'price': '63046.18', 'size': '0.000194'},
  {'price': '63046.32', 'size': '0.03965338'},
  {'price': '63047.8', 'size': '0.0097'},
  {'price': '63047.85', 'size': '0.04781428'},
  {'price': '63048.07', 'size': '0.21563175'},
  {'price': '63048.08', 'size': '0.09541977'},
  {'price': '63048.16', 'size': '0.09126327'},
  {'price': '63048.41', 'size': '0.03573'},
  {'price': '63048.66', 'size': '0.03900293'},
  {'price': '63049.9', 'size': '0.000018'},
  {'price': '63050', 'size': '0.01'},
  {'price': '63050.38', 'size': '0.03975824'},
  {'price': '63050.4', 'size': '0.05'},
  {'price': '63050.56', 'size': '0.1007413'},
  {'price': '63051.2', 'size': '0.00158504'},
  {'price': '63051.93', 'size': '0.09541977'},
  {'price': '63052.81', 'size': '0.0000238'},
  {'price': '63052.89', 'size': '0.000388'},
  {'price': '63053.39', 'size': '0.14'},
  {'price': '63053.65', 'size': '0.01779429'},
  {'price': '63053.66', 'size': '0.0194'},
  {'price': '63053.85', 'size': '0.000018'},
  {'price': '63054.27', 'size': '0.267576'},
  {'price': '63055', 'size': '0.01'},
  {'price': '63056', 'size': '0.00038818'},
  {'price': '63057.41', 'size': '0.00079302'},
  {'price': '63057.42', 'size': '0.09541977'},
  {'price': '63057.5', 'size': '0.00792523'},
  {'price': '63057.8', 'size': '0.000018'},
  {'price': '63058.44', 'size': '0.01268649'},
  {'price': '63059.07', 'size': '0.06'},
  {'price': '63059.13', 'size': '0.40495167'},
  {'price': '63059.14', 'size': '0.04781428'},
  {'price': '63059.8', 'size': '0.60290091'},
  {'price': '63059.81', 'size': '0.09541977'},
  {'price': '63059.83', 'size': '0.027596'},
  {'price': '63060', 'size': '0.01'},
  {'price': '63060.38', 'size': '0.03808335'},
  {'price': '63061.75', 'size': '0.000018'},
  {'price': '63062.85', 'size': '0.92792036'},
  {'price': '63062.86', 'size': '0.09541977'},
  {'price': '63062.9', 'size': '0.05'},
  {'price': '63062.98', 'size': '0.29141206'},
  {'price': '63064.08', 'size': '0.03975824'},
  {'price': '63065', 'size': '0.01'},
  {'price': '63065.44', 'size': '0.04781428'},
  {'price': '63065.7', 'size': '0.038818'},
  {'price': '63066.32', 'size': '0.000776'},
  {'price': '63067.42', 'size': '0.03706545'},
  {'price': '63067.97', 'size': '0.06997503'},
  {'price': '63069.65', 'size': '0.000018'},
  {'price': '63070', 'size': '0.01'},
  {'price': '63071.72', 'size': '0.0000238'},
  {'price': '63073.6', 'size': '0.000018'},
  {'price': '63073.94', 'size': '0.08757252'},
  {'price': '63074', 'size': '0.00003186'},
  {'price': '63074.8', 'size': '0.0005'},
  {'price': '63075', 'size': '0.01'},
  {'price': '63075.14', 'size': '0.01965429'},
  {'price': '63077.55', 'size': '0.000018'},
  {'price': '63077.59', 'size': '0.0023284'},
  {'price': '63078.47', 'size': '1.48164991'},
  {'price': '63078.52', 'size': '0.06998563'},
  {'price': '63079.58', 'size': '0.460025'},
  {'price': '63080', 'size': '0.01'},
  {'price': '63080.61', 'size': '0.0485'},
  {'price': '63080.81', 'size': '0.02537682'},
  {'price': '63081.31', 'size': '0.0375546'},
  {'price': '63081.5', 'size': '0.000018'},
  {'price': '63082.54', 'size': '0.06053282'},
  {'price': '63083.08', 'size': '0.00079308'},
  {'price': '63083.09', 'size': '0.00097'},
  {'price': '63083.89', 'size': '0.54639893'},
  {'price': '63084.03', 'size': '0.03975824'},
  {'price': '63085', 'size': '0.01'},
  {'price': '63085.45', 'size': '0.000018'},
  {'price': '63088.87', 'size': '0.00172427'},
  {'price': '63089.4', 'size': '0.000018'},
  {'price': '63090', 'size': '0.01'},
  {'price': '63090.63', 'size': '0.0000238'},
  {'price': '63090.9', 'size': '0.02045163'},
  {'price': '63092.59', 'size': '0.25380631'},
  {'price': '63092.63', 'size': '0.04781428'},
  {'price': '63093.35', 'size': '0.000018'},
  {'price': '63093.64', 'size': '1.42645132'},
  {'price': '63094', 'size': '0.00038711'},
  {'price': '63094.12', 'size': '0.03975824'},
  {'price': '63094.71', 'size': '0.06038706'},
  {'price': '63095', 'size': '0.00001'},
  {'price': '63095.06', 'size': '0.01597231'},
  {'price': '63095.35', 'size': '1.04374867'},
  {'price': '63095.75', 'size': '0.01597231'},
  {'price': '63096.87', 'size': '0.57561176'},
  {'price': '63097.3', 'size': '0.000018'},
  {'price': '63099.42', 'size': '0.01597231'},
  {'price': '63099.6', 'size': '0.04781428'},
  {'price': '63099.62', 'size': '1.189319'},
  {'price': '63100.4', 'size': '0.05'},
  {'price': '63101.25', 'size': '0.000018'},
  {'price': '63101.38', 'size': '0.00078119'},
  {'price': '63104.21', 'size': '0.03975824'},
  {'price': '63105.2', 'size': '0.000018'},
  {'price': '63105.32', 'size': '0.12347723'},
  {'price': '63106.67', 'size': '1.42615677'},
  {'price': '63107.74', 'size': '0.00005579'},
  {'price': '63109.54', 'size': '0.0000238'},
  {'price': '63111.31', 'size': '0.09117195'},
  {'price': '63112.9', 'size': '0.05'},
  {'price': '63113.4', 'size': '0.01100056'},
  {'price': '63114.3', 'size': '0.03975824'},
  {'price': '63114.59', 'size': '0.2999'},
  {'price': '63114.83', 'size': '0.01597231'},
  {'price': '63116.32', 'size': '3.0128208'},
  {'price': '63116.33', 'size': '5.046601'},
  {'price': '63117.08', 'size': '0.237945'},
  {'price': '63117.93', 'size': '0.00194'},
  {'price': '63119.34', 'size': '1.42587064'},
  {'price': '63119.69', 'size': '0.23387099'},
  {'price': '63121', 'size': '0.000018'},
  {'price': '63122.99', 'size': '0.097'},
  {'price': '63123.57', 'size': '0.00001584'},
  {'price': '63125.4', 'size': '0.05'},
  {'price': '63126', 'size': '0.01106597'},
  {'price': '63127.48', 'size': '0.01331'},
  {'price': '63127.93', 'size': '0.01061683'},
  {'price': '63128.45', 'size': '0.0000238'},
  {'price': '63132.12', 'size': '1.42558198'},
  {'price': '63132.65', 'size': '10.674255'},
  {'price': '63135', 'size': '3'},
  {'price': '63136.8', 'size': '0.000018'},
  {'price': '63137.9', 'size': '0.05'},
  {'price': '63138.59', 'size': '2.26595294'},
  {'price': '63141.11', 'size': '0.00031738'},
  {'price': '63142.05', 'size': '0.00827458'},
  {'price': '63144.05', 'size': '0.15972312'},
  {'price': '63145.18', 'size': '1.42528714'},
  {'price': '63147.36', 'size': '0.0000238'},
  {'price': '63148.05', 'size': '0.01130472'},
  {'price': '63149.82', 'size': '0.237915'},
  {'price': '63150.4', 'size': '0.05'},
  {'price': '63152.6', 'size': '0.000018'},
  {'price': '63154.05', 'size': '9.816853'},
  {'price': '63155.84', 'size': '0.12125'},
  {'price': '63157.64', 'size': '1.42500594'},
  {'price': '63160', 'size': '0.00032674'},
  {'price': '63161', 'size': '0.00020311'},
  {'price': '63161.55', 'size': '0.15972312'},
  {'price': '63161.59', 'size': '0.002425'},
  {'price': '63163.12', 'size': '0.05440999'},
  {'price': '63164', 'size': '0.00158414'},
  {'price': '63168.4', 'size': '0.000018'},
  {'price': '63169.31', 'size': '0.00156117'},
  {'price': '63169.43', 'size': '0.1'},
  {'price': '63170.1', 'size': '0.01082721'},
  {'price': '63170.53', 'size': '1.42471503'},
  {'price': '63172.64', 'size': '0.00031738'},
  {'price': '63174.52', 'size': '0.09108074'},
  {'price': '63175.74', 'size': '0.03499999'},
  {'price': '63176', 'size': '0.00033543'},
  {'price': '63178.01', 'size': '3.21750749'},
  {'price': '63182.05', 'size': '0.03499999'},
  {'price': '63183.37', 'size': '1.42442565'},
  {'price': '63184.2', 'size': '0.000018'},
  {'price': '63188.36', 'size': '0.03499999'},
  {'price': '63194.67', 'size': '0.11294'},
  {'price': '63195', 'size': '0.00015998'},
  {'price': '63195.42', 'size': '0.1455'},
  {'price': '63195.68', 'size': '0.00468519'},
  {'price': '63196', 'size': '0.00014778'},
  {'price': '63196.54', 'size': '1.42412865'},
  {'price': '63198', 'size': '0.00069786'},
  {'price': '63200', 'size': '0.00475595'},
  {'price': '63208.89', 'size': '0.06087999'},
  {'price': '63209.11', 'size': '1.42384543'},
  {'price': '63213.98', 'size': '0.00291'},
  {'price': '63214.74', 'size': '0.023796'},
  {'price': '63216.08', 'size': '0.01265329'},
  {'price': '63218.45', 'size': '0.01'},
  {'price': '63221.75', 'size': '1.42356073'},
  {'price': '63221.9', 'size': '0.04851777'},
  {'price': '63222.36', 'size': '0.00040133'},
  {'price': '63223.3', 'size': '0.15972312'},
  {'price': '63229.92', 'size': '12.562598'},
  {'price': '63230.99', 'size': '0.15972312'},
  {'price': '63235.53', 'size': '1.42325069'},
  {'price': '63235.71', 'size': '0.00031738'},
  {'price': '63237.78', 'size': '0.09098962'},
  {'price': '63241.2', 'size': '0.34606778'},
  {'price': '63242.49', 'size': '0.00036364'},
  {'price': '63244.4', 'size': '0.01264637'},
  {'price': '63250', 'size': '1'},
  {'price': '63252.99', 'size': '1.4228578'},
  {'price': '63256.06', 'size': '14.990801'},
  {'price': '63258.8', 'size': '0.03695331'},
  {'price': '63260.21', 'size': '0.00583'},
  {'price': '63266.36', 'size': '1.08382235'},
  {'price': '63266.37', 'size': '1.42255673'},
  {'price': '63266.72', 'size': '1.42254891'},
  {'price': '63279.59', 'size': '1.42225954'},
  {'price': '63279.7', 'size': '0.00003931'},
  {'price': '63292.02', 'size': '1.42198032'},
  {'price': '63292.44', 'size': '0.00161152'},
  {'price': '63297.87', 'size': '0.01074189'},
  {'price': '63298.78', 'size': '0.10119738'},
  {'price': '63301.11', 'size': '0.09089859'},
  {'price': '63303.56', 'size': '0.00005561'},
  {'price': '63303.8', 'size': '0.3'},
  {'price': '63318.51', 'size': '0.22417615'},
  {'price': '63326', 'size': '0.00014107'},
  {'price': '63327.96', 'size': '1.226205'},
  {'price': '63335', 'size': '0.00011978'},
  {'price': '63337.01', 'size': '42.039441'},
  {'price': '63338', 'size': '0.03430957'},
  {'price': '63348.75', 'size': '0.00263859'},
  {'price': '63361.85', 'size': '0.12619738'},
  {'price': '63364.5', 'size': '0.09145896'},
  {'price': '63365.26', 'size': '0.3'},
  {'price': '63371.22', 'size': '0.52191617'},
  {'price': '63371.77', 'size': '0.47916936'},
  {'price': '63373', 'size': '0.00038518'},
  {'price': '63374', 'size': '0.00046064'},
  {'price': '63375', 'size': '0.00029513'},
  {'price': '63379', 'size': '0.00008205'},
  {'price': '63392', 'size': '0.00031177'},
  {'price': '63398', 'size': '0.00037597'},
  {'price': '63400', 'size': '0.02764121'},
  {'price': '63405.98', 'size': '0.47916936'},
  {'price': '63421.53', 'size': '0.47586717'},
  {'price': '63424.92', 'size': '0.1'},
  {'price': '63426.72', 'size': '0.3'},
  {'price': '63427.96', 'size': '0.0907168'},
  {'price': '63444', 'size': '0.05461653'},
  {'price': '63448.46', 'size': '0.00466652'},
  {'price': '63450.47', 'size': '0.00486063'},
  {'price': '63450.77', 'size': '0.03684151'},
  {'price': '63465.5', 'size': '0.00042322'},
  {'price': '63475.11', 'size': '0.00583'},
  {'price': '63477.99', 'size': '0.00018547'},
  {'price': '63486.18', 'size': '0.61251011'},
  {'price': '63488.18', 'size': '0.3'},
  {'price': '63491.49', 'size': '0.09062603'},
  {'price': '63492.25', 'size': '0.00022555'},
  {'price': '63500', 'size': '0.21559277'},
  {'price': '63517.4', 'size': '0.00002011'},
  {'price': '63537.46', 'size': '0.00027639'},
  {'price': '63549.64', 'size': '0.3'},
  {'price': '63550.64', 'size': '0.47916936'},
  {'price': '63555.07', 'size': '0.09053536'},
  {'price': '63555.2', 'size': '0.04851777'},
  {'price': '63558.45', 'size': '0.00036183'},
  {'price': '63576.99', 'size': '0.00000294'},
  {'price': '63586.16', 'size': '0.69119144'},
  {'price': '63586.51', 'size': '0.07438927'},
  {'price': '63596.48', 'size': '0.01069135'},
  {'price': '63599.43', 'size': '0.00040133'},
  {'price': '63600', 'size': '1.88779749'},
  {'price': '63600.78', 'size': '0.00024875'},
  {'price': '63611.1', 'size': '0.3'},
  {'price': '63618.72', 'size': '0.09044479'},
  {'price': '63628.34', 'size': '0.00154127'},
  {'price': '63640.01', 'size': '0.00036638'},
  {'price': '63643.32', 'size': '0.03673005'},
  {'price': '63645.67', 'size': '0.0012'},
  {'price': '63650.19', 'size': '0.1'},
  {'price': '63654.01', 'size': '0.00006255'},
  {'price': '63656.83', 'size': '0.47916936'},
  {'price': '63657.99', 'size': '0.02588'},
  {'price': '63670.89', 'size': '0.00003176'},
  {'price': '63672.56', 'size': '1.9'},
  {'price': '63680.65', 'size': '0.00022488'},
  {'price': '63682.43', 'size': '0.09035431'},
  {'price': '63683.14', 'size': '0.00027575'},
  {'price': '63687.88', 'size': '0.03'},
  {'price': '63689', 'size': '0.0012'},
  {'price': '63690.39', 'size': '0.00583'},
  {'price': '63695.67', 'size': '0.01000821'},
  {'price': '63697.04', 'size': '0.00005527'},
  {'price': '63702.25', 'size': '0.00464793'},
  {'price': '63709.12', 'size': '0.2065704'},
  {'price': '63714.41', 'size': '0.00007902'},
  {'price': '63731', 'size': '0.00074025'},
  {'price': '63732.67', 'size': '0.0012'},
  {'price': '63734.02', 'size': '1.6'},
  {'price': '63736.78', 'size': '0.00003903'},
  {'price': '63746.2', 'size': '0.09026391'},
  {'price': '63746.6', 'size': '0.00024817'},
  {'price': '63769.75', 'size': '0.00001487'},
  {'price': '63776', 'size': '0.0012'},
  {'price': '63784.6', 'size': '0.03785325'},
  {'price': '63785', 'size': '0.025'},
  {'price': '63785.46', 'size': '0.25376911'},
  {'price': '63785.64', 'size': '0.00945005'},
  {'price': '63790.14', 'size': '0.00299946'},
  {'price': '63794.58', 'size': '0.05637562'},
  {'price': '63795.48', 'size': '1.6'},
  {'price': '63800', 'size': '0.00471108'},
  {'price': '63808.75', 'size': '0.01065957'},
  {'price': '63810.05', 'size': '0.09017359'},
  {'price': '63811.55', 'size': '0.00111069'},
  {'price': '63814.2', 'size': '0.00046698'},
  {'price': '63818.73', 'size': '0.0000812'},
  {'price': '63819.67', 'size': '0.0012'},
  {'price': '63828.72', 'size': '0.03164837'},
  {'price': '63835.58', 'size': '0.00241604'},
  {'price': '63836.45', 'size': '0.03661892'},
  {'price': '63850.96', 'size': '0.15118441'},
  {'price': '63851.52', 'size': '0.00263859'},
  {'price': '63856.65', 'size': '0.00000293'},
  {'price': '63856.94', 'size': '1.6'},
  {'price': '63866', 'size': '4'},
  {'price': '63869.6', 'size': '0.00022421'},
  {'price': '63873.95', 'size': '0.09008339'},
  {'price': '63876', 'size': '0.00036003'},
  {'price': '63877.33', 'size': '0.0012'},
  {'price': '63882.44', 'size': '0.00019795'},
  {'price': '63888.5', 'size': '0.04851777'},
  {'price': '63889.22', 'size': '0.00000444'},
  {'price': '63890', 'size': '0.09497292'},
  {'price': '63894.69', 'size': '0.0000551'},
  {'price': '63900', 'size': '0.00000062'},
  {'price': '63903.32', 'size': '0.04883149'},
  {'price': '63903.33', 'size': '0.00499997'},
  {'price': '63904.17', 'size': '0.00482612'},
  {'price': '63904.96', 'size': '0.00554932'},
  {'price': '63905.62', 'size': '0.00583'},
  {'price': '63906.67', 'size': '0.0012'},
  {'price': '63908.44', 'size': '0.04301167'},
  {'price': '63909.53', 'size': '0.00001999'},
  {'price': '63909.95', 'size': '0.01320746'},
  {'price': '63911.2', 'size': '0.00316198'},
  {'price': '63914.04', 'size': '0.00562'},
  {'price': '63914.16', 'size': '0.17102007'},
  {'price': '63915.98', 'size': '0.2035214'},
  {'price': '63918.4', 'size': '1.6'},
  {'price': '63926.9', 'size': '0.01131481'},
  {'price': '63930.5', 'size': '0.00499992'},
  {'price': '63937.91', 'size': '0.08999326'},
  {'price': '63944', 'size': '0.05461653'},
  {'price': '63950', 'size': '0.0012'},
  {'price': '63957.06', 'size': '0.00462941'},
  {'price': '63970', 'size': '0.00850135'},
  {'price': '63976.5', 'size': '0.00040133'},
  {'price': '63979.86', 'size': '1.6'},
  {'price': '63980.84', 'size': '0.00053952'},
  {'price': '63985', 'size': '0.00001'},
  {'price': '63988', 'size': '0.4688379'},
  {'price': '63993.67', 'size': '0.0012'},
  {'price': '64000', 'size': '0.61541177'},
  {'price': '64001.95', 'size': '0.08990322'},
  {'price': '64009.65', 'size': '0.00647644'},
  {'price': '64014.95', 'size': '0.00333195'},
  {'price': '64020', 'size': '0.02358637'},
  {'price': '64030.17', 'size': '0.03650813'},
  {'price': '64034.79', 'size': '0.05492434'},
  {'price': '64037', 'size': '0.0012'},
  {'price': '64037.71', 'size': '0.00031544'},
  {'price': '64041.32', 'size': '1.6'},
  {'price': '64047.16', 'size': '0.18090276'},
  {'price': '64059.11', 'size': '0.00022355'},
  {'price': '64064.4', 'size': '0.00014464'},
  {'price': '64066', 'size': '0.07877157'},
  {'price': '64066.05', 'size': '0.08981328'},
  {'price': '64073.5', 'size': '0.15870787'},
  {'price': '64077.73', 'size': '0.00271674'},
  {'price': '64080', 'size': '0.1'},
  {'price': '64080.67', 'size': '0.0012'},
  {'price': '64085.99', 'size': '0.0001539'},
  {'price': '64092.95', 'size': '0.00005493'},
  {'price': '64093.2', 'size': '0.01060744'},
  {'price': '64093.38', 'size': '0.00081232'},
  {'price': '64096.9', 'size': '0.00015618'},
  {'price': '64099.31', 'size': '0.00039782'},
  {'price': '64102.99', 'size': '0.00008791'},
  {'price': '64120.2', 'size': '0.00583'},
  {'price': '64120.91', 'size': '0.00006209'},
  {'price': '64124', 'size': '0.0012'},
  {'price': '64124.3', 'size': '0.04678413'},
  {'price': '64130.08', 'size': '0.0001579'},
  {'price': '64130.2', 'size': '0.08972342'},
  {'price': '64134.12', 'size': '0.00027382'},
  {'price': '64135', 'size': '0.00009235'},
  {'price': '64137.55', 'size': '0.00000291'},
  {'price': '64137.87', 'size': '0.0006921'},
  {'price': '64139.12', 'size': '0.00137372'},
  {'price': '64144.69', 'size': '0.00054455'},
  {'price': '64150', 'size': '0.03350017'},
  {'price': '64167.72', 'size': '0.0012'},
  {'price': '64172.88', 'size': '0.00298157'},
  {'price': '64177.73', 'size': '0.00039615'},
  {'price': '64189.5', 'size': '0.00972313'},
  {'price': '64191.84', 'size': '0.00049955'},
  {'price': '64194.84', 'size': '0.00012117'},
  {'price': '64195', 'size': '0.00001'},
  {'price': '64195.13', 'size': '0.00035824'},
  {'price': '64197.17', 'size': '0.00003875'},
  {'price': '64198.03', 'size': '0.00024643'},
  {'price': '64200', 'size': '1.10771573'},
  {'price': '64207.01', 'size': '0.00316198'},
  {'price': '64211', 'size': '0.0012'},
  {'price': '64212.89', 'size': '0.00461097'},
  {'price': '64218', 'size': '0.0075'},
  {'price': '64221.53', 'size': '0.00006633'},
  {'price': '64221.8', 'size': '0.04851777'},
  {'price': '64224.48', 'size': '0.03639768'},
  {'price': '64228', 'size': '0.0019328'},
  {'price': '64230.41', 'size': '0.00001784'},
  {'price': '64236', 'size': '0.00018507'},
  {'price': '64243.16', 'size': '0.0018432'},
  {'price': '64244.79', 'size': '0.00009235'},
  {'price': '64249.18', 'size': '0.00022289'},
  {'price': '64250', 'size': '1.39403101'},
  {'price': '64254.72', 'size': '0.0012'},
  {'price': '64259.39', 'size': '0.00008057'},
  {'price': '64286.5', 'size': '0.00004244'},
  {'price': '64291.83', 'size': '0.00005476'},
  {'price': '64298', 'size': '0.0012'},
  {'price': '64300', 'size': '0.06093147'},
  {'price': '64300.92', 'size': '0.00481843'},
  {'price': '64302.24', 'size': '0.00007807'},
  {'price': '64304.08', 'size': '0.00001987'},
  {'price': '64305.46', 'size': '0.00000746'},
  {'price': '64307.32', 'size': '0.0001555'},
  {'price': '64316.6', 'size': '0.004'},
  {'price': '64320.66', 'size': '0.00014406'},
  {'price': '64334.67', 'size': '0.00583'},
  {'price': '64337', 'size': '0.00018642'},
  {'price': '64341.2', 'size': '0.00039632'},
  {'price': '64341.64', 'size': '0.00004349'},
  {'price': '64341.72', 'size': '0.0012'},
  {'price': '64344.98', 'size': '0.01057121'},
  {'price': '64350.29', 'size': '0.00015539'},
  {'price': '64353.57', 'size': '0.00040133'},
  {'price': '64354.56', 'size': '0.00009235'},
  {'price': '64354.66', 'size': '0.00000823'},
  {'price': '64358', 'size': '0.04'},
  {'price': '64361.11', 'size': '0.00479186'},
  {'price': '64380.18', 'size': '0.16943487'},
  {'price': '64381.16', 'size': '0.00258577'},
  {'price': '64381.34', 'size': '0.00000271'},
  {'price': '64383.19', 'size': '0.00956454'},
  {'price': '64385', 'size': '0.03226313'},
  {'price': '64385.83', 'size': '0.00000552'},
  {'price': '64386.02', 'size': '0.00008057'},
  {'price': '64387.5', 'size': '0.00009347'},
  {'price': '64390.75', 'size': '0.00019638'},
  {'price': '64393.12', 'size': '0.00945005'},
  {'price': '64393.54', 'size': '0.07438927'},
  {'price': '64396.56', 'size': '0.00001661'},
  {'price': '64400', 'size': '0.10498536'},
  {'price': '64402.02', 'size': '0.00015527'},
  {'price': '64411', 'size': '0.07792333'},
  {'price': '64415.93', 'size': '0.00080826'},
  {'price': '64418', 'size': '0.01'},
  {'price': '64419.32', 'size': '0.00004695'},
  {'price': '64419.38', 'size': '0.03628756'},
  {'price': '64419.69', 'size': '0.0000029'},
  {'price': '64422.97', 'size': '0.00049594'},
  {'price': '64426', 'size': '0.5'},
  {'price': '64426.84', 'size': '0.00002'},
  {'price': '64428.72', 'size': '0.0012'},
  {'price': '64429.25', 'size': '0.1'},
  {'price': '64434.47', 'size': '0.00079166'},
  {'price': '64438', 'size': '0.00018507'},
  {'price': '64439.82', 'size': '0.00022223'},
  {'price': '64440.29', 'size': '0.00003522'},
  {'price': '64442.08', 'size': '0.01371069'},
  {'price': '64442.6', 'size': '0.01626906'},
  {'price': '64444', 'size': '0.12357562'},
  {'price': '64445', 'size': '0.00001'},
  {'price': '64450', 'size': '2'},
  {'price': '64455.27', 'size': '0.00001303'},
  {'price': '64464.35', 'size': '0.00009235'},
  {'price': '64464.58', 'size': '0.00013017'},
  {'price': '64465', 'size': '0.005001'},
  {'price': '64466.99', 'size': '0.01'},
  {'price': '64467.05', 'size': '0.00243091'},
  {'price': '64469.42', 'size': '0.03133385'},
  {'price': '64469.74', 'size': '0.0045926'},
  {'price': '64469.92', 'size': '0.00007807'},
  {'price': '64472', 'size': '0.0012'},
  {'price': '64472.24', 'size': '0.00002311'},
  {'price': '64475', 'size': '0.97557192'},
  {'price': '64481.67', 'size': '0.00001333'},
  {'price': '64491.33', 'size': '0.00005459'},
  {'price': '64497', 'size': '0.01165279'},
  {'price': '64499.41', 'size': '0.0000044'},
  {'price': '64500', 'size': '30.56680207'},
  {'price': '64502.74', 'size': '0.00001333'},
  {'price': '64504.17', 'size': '0.01264792'},
  {'price': '64510.61', 'size': '0.0083'},
  {'price': '64512.89', 'size': '0.00008057'},
  {'price': '64514.65', 'size': '0.00036638'},
  {'price': '64515.38', 'size': '0.0004619'},
  {'price': '64515.66', 'size': '0.0007'},
  {'price': '64515.72', 'size': '0.0012'},
  {'price': '64515.86', 'size': '0.00035646'},
  {'price': '64518.09', 'size': '0.00002417'},
  {'price': '64518.8', 'size': '0.00006099'},
  {'price': '64523.47', 'size': '0.00007988'},
  {'price': '64523.48', 'size': '0.15118441'},
  {'price': '64528.95', 'size': '0.0000141'},
  {'price': '64532.96', 'size': '0.00396128'},
  {'price': '64535.04', 'size': '0.00562'},
  {'price': '64539', 'size': '0.00012543'},
  {'price': '64542.47', 'size': '0.00003819'},
  {'price': '64544.32', 'size': '0.00015493'},
  {'price': '64549.12', 'size': '0.00583'},
  {'price': '64550', 'size': '0.00030983'},
  {'price': '64550.74', 'size': '0.00001564'},
  {'price': '64551.46', 'size': '0.1'},
  {'price': '64554.06', 'size': '0.03206552'},
  {'price': '64555.1', 'size': '0.04851777'},
  {'price': '64557.93', 'size': '0.00296379'},
  {'price': '64559', 'size': '0.0012'},
  {'price': '64560.77', 'size': '0.0000491'},
  {'price': '64563.67', 'size': '0.0002458'},
  {'price': '64566', 'size': '0.00001662'},
  {'price': '64570', 'size': '0.01628525'},
  {'price': '64574.13', 'size': '0.00009235'},
  {'price': '64577.95', 'size': '0.00014349'},
  {'price': '64585.91', 'size': '0.29892784'},
  {'price': '64586.07', 'size': '0.00001563'},
  {'price': '64587.81', 'size': '0.00006164'},
  {'price': '64588.33', 'size': '0.0001801'},
  {'price': '64588.76', 'size': '0.00008791'},
  {'price': '64592.19', 'size': '0.1'},
  {'price': '64594.1', 'size': '0.0000534'},
  {'price': '64594.81', 'size': '0.00001563'},
  {'price': '64595.68', 'size': '0.09614028'},
  {'price': '64600', 'size': '1.46547481'},
  {'price': '64602.72', 'size': '0.0012'},
  {'price': '64605.97', 'size': '0.00010045'},
  {'price': '64610.02', 'size': '0.00001872'},
  {'price': '64610.2', 'size': '0.00154774'},
  {'price': '64614.87', 'size': '0.03617777'},
  {'price': '64615.05', 'size': '0.01052379'},
  {'price': '64618.06', 'size': '0.11443394'},
  {'price': '64627.6', 'size': '0.00183224'},
  {'price': '64631.03', 'size': '0.00022157'},
  {'price': '64633.48', 'size': '0.00001939'},
  {'price': '64638.03', 'size': '0.00007807'},
  {'price': '64638.32', 'size': '0.00002624'},
  {'price': '64640', 'size': '0.02494453'},
  {'price': '64646', 'size': '0.0012'},
  {'price': '64650', 'size': '0.04030935'},
  {'price': '64654.02', 'size': '0.00044789'},
  {'price': '64657.92', 'size': '0.00001871'},
  {'price': '64658', 'size': '0.00927959'},
  {'price': '64658.85', 'size': '0.01546578'},
  {'price': '64659.69', 'size': '0.00161443'},
  {'price': '64660.88', 'size': '0.00003847'},
  {'price': '64661.06', 'size': '1'},
  {'price': '64666', 'size': '0.02231961'},
  {'price': '64668.68', 'size': '0.00153154'},
  {'price': '64669.65', 'size': '0.00124834'},
  {'price': '64669.77', 'size': '0.00022602'},
  {'price': '64669.81', 'size': '1.91739427'},
  {'price': '64671.05', 'size': '0.0000005'},
  {'price': '64674.97', 'size': '0.00005427'},
  {'price': '64676.81', 'size': '0.00030204'},
  {'price': '64678.9', 'size': '0.00316713'},
  {'price': '64680.13', 'size': '0.00006416'},
  {'price': '64681.56', 'size': '0.00050923'},
  {'price': '64682.72', 'size': '0.02778607'},
  {'price': '64683.54', 'size': '0.02339018'},
  {'price': '64683.91', 'size': '0.00009235'},
  {'price': '64684.17', 'size': '0.00160239'},
  {'price': '64688.19', 'size': '0.0000289'},
  {'price': '64688.78', 'size': '0.00029388'},
  {'price': '64689', 'size': '0.01565'},
  {'price': '64689.72', 'size': '0.0012'},
  {'price': '64690.09', 'size': '0.00002581'},
  {'price': '64691', 'size': '0.00001549'},
  {'price': '64693.05', 'size': '0.00000618'},
  {'price': '64695', 'size': '0.00001'},
  {'price': '64695.18', 'size': '0.00166856'},
  {'price': '64695.55', 'size': '0.00003122'},
  {'price': '64697.46', 'size': '0.00417941'},
  {'price': '64698.99', 'size': '0.00005732'},
  {'price': '64700', 'size': '10.90841805'},
  {'price': '64700.15', 'size': '0.01545591'},
  {'price': '64700.6', 'size': '0.00006099'},
  {'price': '64701', 'size': '0.0026'},
  {'price': '64701.07', 'size': '0.00001974'},
  {'price': '64703.06', 'size': '0.00000288'},
  {'price': '64707.31', 'size': '0.00007727'},
  {'price': '64713.02', 'size': '0.0002'},
  {'price': '64713.79', 'size': '0.00020222'},
  {'price': '64713.94', 'size': '0.00000001'},
  {'price': '64718', 'size': '1'},
  {'price': '64718.35', 'size': '0.00010877'},
  {'price': '64719.77', 'size': '0.00000001'},
  {'price': '64721.74', 'size': '0.00463522'},
  {'price': '64723.36', 'size': '0.00001159'},
  {'price': '64724.39', 'size': '0.00004874'},
  {'price': '64725', 'size': '0.00157589'},
  {'price': '64726.24', 'size': '0.00000002'},
  {'price': '64727', 'size': '0.0367'},
  {'price': '64727.27', 'size': '0.00013662'},
  {'price': '64727.62', 'size': '0.0045743'},
  {'price': '64727.77', 'size': '0.00010983'},
  {'price': '64728.94', 'size': '0.03760874'},
  {'price': '64729.54', 'size': '0.00006689'},
  {'price': '64729.85', 'size': '0.0000005'},
  {'price': '64730.64', 'size': '0.00040133'},
  {'price': '64733.65', 'size': '0.00510779'},
  {'price': '64734.51', 'size': '0.00017606'},
  {'price': '64736.22', 'size': '0.00048225'},
  {'price': '64738.16', 'size': '0.00001421'},
  {'price': '64738.19', 'size': '0.01573465'},
  {'price': '64739.99', 'size': '0.00007163'},
  {'price': '64740', 'size': '0.15'},
  {'price': '64740.11', 'size': '0.00080421'},
  {'price': '64741', 'size': '0.02673566'},
  {'price': '64741.13', 'size': '0.00008072'},
  {'price': '64742.62', 'size': '0.00007859'},
  {'price': '64744.94', 'size': '0.0012'},
  {'price': '64745', 'size': '0.05'},
  {'price': '64746.36', 'size': '0.02927531'},
  {'price': '64747', 'size': '1.7414587'},
  {'price': '64747.19', 'size': '0.00000664'},
  {'price': '64749.68', 'size': '0.00308881'},
  {'price': '64750', 'size': '1.18372957'},
  {'price': '64751.67', 'size': '0.00154436'},
  {'price': '64755.98', 'size': '0.464'},
  {'price': '64759.7', 'size': '0.00123534'},
  {'price': '64760.43', 'size': '0.00004797'},
  {'price': '64761.09', 'size': '0.00021636'},
  {'price': '64761.62', 'size': '0.02362764'},
  {'price': '64762.59', 'size': '0.00023099'},
  {'price': '64762.91', 'size': '0.00051842'},
  {'price': '64763.44', 'size': '0.01525986'},
  {'price': '64764.78', 'size': '0.0002'},
  {'price': '64766.43', 'size': '0.00329329'},
  {'price': '64768.32', 'size': '0.00013633'},
  {'price': '64770.48', 'size': '0.00001142'},
  {'price': '64776.72', 'size': '0.0012'},
  {'price': '64777', 'size': '0.03406896'},
  {'price': '64778.38', 'size': '0.00001481'},
  {'price': '64778.53', 'size': '0.00316713'},
  {'price': '64781.81', 'size': '0.9395'},
  {'price': '64785', 'size': '0.02749621'},
  {'price': '64787.96', 'size': '0.00005432'},
  {'price': '64788', 'size': '0.01125'},
  {'price': '64788.88', 'size': '0.05'},
  {'price': '64791.74', 'size': '0.00000789'},
  {'price': '64793.19', 'size': '0.00011001'},
  {'price': '64793.59', 'size': '0.01543362'},
  {'price': '64793.69', 'size': '0.00009235'},
  {'price': '64794.65', 'size': '0.00001512'},
  {'price': '64797', 'size': '1'},
  {'price': '64797.28', 'size': '0.01201366'},
  {'price': '64797.58', 'size': '0.01543267'},
  {'price': '64799.99', 'size': '0.0000003'},
  {'price': '64800', 'size': '10.45882983'},
  {'price': '64800.68', 'size': '0.0000534'},
  {'price': '64803.38', 'size': '0.00003225'},
  {'price': '64803.95', 'size': '0.07519675'},
  {'price': '64804.9', 'size': '0.0001223'},
  {'price': '64806.58', 'size': '0.00007807'},
  {'price': '64810', 'size': '0.00771485'},
  {'price': '64810.95', 'size': '0.0359592'},
  {'price': '64811', 'size': '0.005'},
  {'price': '64811.2', 'size': '0.00308588'},
  {'price': '64811.7', 'size': '0.00028846'},
  {'price': '64812.5', 'size': '0.0002896'},
  {'price': '64814.91', 'size': '1.5'},
  {'price': '64815.18', 'size': '0.00003147'},
  {'price': '64815.67', 'size': '0.00001234'},
  {'price': '64816.55', 'size': '0.00176111'},
  {'price': '64820', 'size': '0.0012'},
  {'price': '64820.43', 'size': '0.00214501'},
  {'price': '64821.32', 'size': '0.00475784'},
  {'price': '64822.01', 'size': '0.0006913'},
  {'price': '64822.7', 'size': '0.00679873'},
  {'price': '64822.8', 'size': '0.00022092'},
  {'price': '64824.97', 'size': '0.00039337'},
  {'price': '64825.71', 'size': '0.00038565'},
  {'price': '64827.11', 'size': '0.00002159'},
  {'price': '64829.09', 'size': '0.01542517'},
  {'price': '64829.3', 'size': '0.00007394'},
  {'price': '64830.33', 'size': '0.00003223'},
  {'price': '64830.41', 'size': '0.00001766'},
  {'price': '64831.06', 'size': '0.00000001'},
  {'price': '64831.26', 'size': '0.00000001'},
  {'price': '64832', 'size': '0.00308489'},
  {'price': '64833.05', 'size': '0.0000812'},
  {'price': '64833.55', 'size': '0.00154241'},
  {'price': '64834.46', 'size': '0.00000004'},
  {'price': '64834.74', 'size': '0.00000003'},
  {'price': '64836.27', 'size': '0.00014291'},
  {'price': '64838.18', 'size': '0.00035469'},
  {'price': '64838.71', 'size': '0.00010208'},
  {'price': '64839.7', 'size': '0.02386751'},
  {'price': '64839.72', 'size': '0.00003377'},
  {'price': '64841', 'size': '0.00010298'},
  {'price': '64841.09', 'size': '0.00001596'},
  {'price': '64842', 'size': '0.00089154'},
  {'price': '64842.78', 'size': '0.00000001'},
  {'price': '64843.03', 'size': '0.00032607'},
  {'price': '64845.58', 'size': '0.0000293'},
  {'price': '64847.21', 'size': '0.00001372'},
  {'price': '64850', 'size': '0.05'},
  {'price': '64851.42', 'size': '0.00003555'},
  {'price': '64853.18', 'size': '0.0000683'},
  {'price': '64855', 'size': '0.51839264'},
  {'price': '64855.64', 'size': '0.00002482'},
  {'price': '64857.64', 'size': '0.00126773'},
  {'price': '64859.23', 'size': '0.00115635'},
  {'price': '64863.72', 'size': '0.0012'},
  {'price': '64863.81', 'size': '0.01048487'},
  {'price': '64865', 'size': '0.0012538'},
  {'price': '64866', 'size': '0.0019315'},
  {'price': '64867.92', 'size': '0.00770797'},
  {'price': '64867.97', 'size': '0.00003437'},
  {'price': '64870', 'size': '0.5'},
  {'price': '64870.26', 'size': '0.00266932'},
  {'price': '64870.72', 'size': '0.00206487'},
  {'price': '64876.41', 'size': '0.2'},
  {'price': '64878.31', 'size': '0.00316713'},
  {'price': '64878.74', 'size': '0.00000001'},
  {'price': '64882.35', 'size': '0.00003514'},
  {'price': '64882.4', 'size': '0.00006099'},
  {'price': '64883.15', 'size': '0.0017593'},
  {'price': '64887.29', 'size': '0.00308226'},
  {'price': '64888', 'size': '0.29780558'},
  {'price': '64888.4', 'size': '0.04851777'},
  {'price': '64890', 'size': '0.19353997'},
  {'price': '64892.41', 'size': '0.00014037'},
  {'price': '64892.5', 'size': '0.00004007'},
  {'price': '64896.3', 'size': '0.00004853'},
  {'price': '64898.05', 'size': '0.00005007'},
  {'price': '64899', 'size': '0.07704278'},
  {'price': '64899.9', 'size': '0.00100959'},
  {'price': '64900', 'size': '10.18730557'},
  {'price': '64902', 'size': '0.00392'},
  {'price': '64903.12', 'size': '0.00019483'},
  {'price': '64903.48', 'size': '0.00009235'},
  {'price': '64903.71', 'size': '0.00007704'},
  {'price': '64907', 'size': '0.0012'},
  {'price': '64910.61', 'size': '0.00077029'},
  {'price': '64917.78', 'size': '0.02410982'},
  {'price': '64920', 'size': '0.025'},
  {'price': '64924', 'size': '0.0042'},
  {'price': '64925', 'size': '0.02887102'},
  {'price': '64926.79', 'size': '0.0000005'},
  {'price': '64928.32', 'size': '0.00005412'},
  {'price': '64932.12', 'size': '0.00013003'},
  {'price': '64933.67', 'size': '0.00228461'},
  {'price': '64934.99', 'size': '0.2610105'},
  {'price': '64935.49', 'size': '0.00000001'},
  {'price': '64941.06', 'size': '0.00030215'},
  {'price': '64942.92', 'size': '0.00095512'},
  {'price': '64945.27', 'size': '0.00294611'},
  {'price': '64946', 'size': '0.05'},
  {'price': '64950', 'size': '3.84631431'},
  {'price': '64950.4', 'size': '0.00000001'},
  {'price': '64950.72', 'size': '0.0012'},
  {'price': '64951.66', 'size': '0.11525953'},
  {'price': '64955', 'size': '0.50153952'},
  {'price': '64960', 'size': '0.0063439'},
  {'price': '64961.01', 'size': '0.00035559'},
  {'price': '64964.39', 'size': '0.01231376'},
  {'price': '64964.5', 'size': '0.00150081'},
  {'price': '64967.09', 'size': '0.00003894'},
  {'price': '64972.64', 'size': '0.00087771'},
  {'price': '64973.15', 'size': '0.0000005'},
  {'price': '64974', 'size': '0.01608699'},
  {'price': '64975.57', 'size': '0.00007807'},
  {'price': '64976.15', 'size': '0.00001899'},
  {'price': '64977.95', 'size': '0.00175674'},
  {'price': '64978.25', 'size': '0.00316713'},
  {'price': '64980', 'size': '0.00007694'},
  {'price': '64984.97', 'size': '0.00153881'},
  {'price': '64985', 'size': '0.07601338'},
  {'price': '64986.53', 'size': '0.00455607'},
  {'price': '64986.7', 'size': '0.00002584'},
  {'price': '64987.54', 'size': '0.02363068'},
  {'price': '64987.69', 'size': '0.00000287'},
  {'price': '64988', 'size': '0.000022'},
  {'price': '64988.17', 'size': '0.00652749'},
  {'price': '64989', 'size': '0.0000006'},
  {'price': '64989.23', 'size': '0.00046742'},
  {'price': '64994', 'size': '0.0012'},
  {'price': '64994.4', 'size': '0.0039136'},
  {'price': '64994.55', 'size': '0.00212351'},
  {'price': '64995.65', 'size': '0.00022488'},
  {'price': '64995.86', 'size': '0.02435459'},
  {'price': '64999', 'size': '0.61586637'},
  {'price': '65000', 'size': '39.06643542'},
  {'price': '65000.01', 'size': '0.00781538'},
  {'price': '65000.6', 'size': '0.00945005'},
  {'price': '65001', 'size': '0.07795375'},
  {'price': '65002', 'size': '0.06860243'},
  {'price': '65003', 'size': '0.06884149'},
  {'price': '65003.6', 'size': '0.00003819'},
  {'price': '65004', 'size': '0.07525814'},
  {'price': '65005', 'size': '0.07757671'},
  {'price': '65006', 'size': '0.05996067'},
  {'price': '65007', 'size': '0.05936106'},
  {'price': '65007.28', 'size': '0.0000534'},
  {'price': '65007.63', 'size': '0.0358504'},
  {'price': '65008', 'size': '0.05855607'},
  {'price': '65008.25', 'size': '0.00076913'},
  {'price': '65008.65', 'size': '0.0000463'},
  {'price': '65013.27', 'size': '0.00009235'},
  {'price': '65014.32', 'size': '0.00182134'},
  {'price': '65015.13', 'size': '0.00022026'},
  {'price': '65018', 'size': '0.01125'},
  {'price': '65020.2', 'size': '0.00076899'},
  {'price': '65021.33', 'size': '0.00005704'},
  {'price': '65023.55', 'size': '0.05642571'},
  {'price': '65026.65', 'size': '0.01332708'},
  {'price': '65027.02', 'size': '0.00846033'},
  {'price': '65027.6', 'size': '0.00062419'},
  {'price': '65028.35', 'size': '0.00009413'},
  {'price': '65029.62', 'size': '0.00000001'},
  {'price': '65031.41', 'size': '0.00113648'},
  {'price': '65032.13', 'size': '0.03075402'},
  {'price': '65032.34', 'size': '0.07'},
  {'price': '65034.12', 'size': '0.0000478'},
  {'price': '65035.48', 'size': '0.00000001'},
  {'price': '65035.56', 'size': '0.05511752'},
  {'price': '65037.78', 'size': '0.0012'},
  {'price': '65038.6', 'size': '0.00013556'},
  {'price': '65040', 'size': '0.19225903'},
  {'price': '65040.27', 'size': '0.0010897'},
  {'price': '65040.45', 'size': '0.00000002'},
  {'price': '65040.58', 'size': '0.03915492'},
  {'price': '65044', 'size': '0.00010247'},
  {'price': '65045.08', 'size': '0.00002152'},
  {'price': '65047.72', 'size': '0.00015831'},
  {'price': '65050', 'size': '0.06830105'},
  {'price': '65051.01', 'size': '0.00028279'},
  {'price': '65051.51', 'size': '0.02060866'},
  {'price': '65052.05', 'size': '0.059542'},
  {'price': '65053.99', 'size': '0.01474245'},
  {'price': '65054.7', 'size': '0.00006119'},
  {'price': '65064.2', 'size': '0.00006099'},
  {'price': '65065.92', 'size': '0.00080018'},
  {'price': '65066.26', 'size': '0.00099461'},
  {'price': '65066.85', 'size': '0.0003919'},
  {'price': '65068.21', 'size': '0.00016144'},
  {'price': '65073.94', 'size': '0.02460184'},
  {'price': '65078.2', 'size': '0.00008791'},
  {'price': '65078.35', 'size': '0.00316713'},
  {'price': '65081', 'size': '0.0012'},
  {'price': '65081.35', 'size': '0.05'},
  {'price': '65087.76', 'size': '0.00020727'},
  {'price': '65088', 'size': '0.008855'},
  {'price': '65088.66', 'size': '0.00034471'},
  {'price': '65089.33', 'size': '0.00125129'},
  {'price': '65095.06', 'size': '0.00012252'},
  {'price': '65095.61', 'size': '0.00014234'},
  {'price': '65100', 'size': '10.07403843'},
  {'price': '65100.51', 'size': '0.00001962'},
  {'price': '65103.19', 'size': '0.00153602'},
  {'price': '65104.83', 'size': '0.03071968'},
  {'price': '65105', 'size': '0.00002319'},
  {'price': '65107.72', 'size': '0.00040133'},
  {'price': '65115.44', 'size': '0.00000446'},
  {'price': '65116.54', 'size': '0.03102245'},
  {'price': '65117.95', 'size': '0.02451976'},
  {'price': '65119.55', 'size': '0.00007656'},
  {'price': '65119.91', 'size': '0.00040981'},
  {'price': '65120', 'size': '0.02887103'},
  {'price': '65123.04', 'size': '0.00009235'},
  {'price': '65124', 'size': '0.00001819'},
  {'price': '65124.78', 'size': '0.0012'},
  {'price': '65127.94', 'size': '0.00003819'},
  {'price': '65131.28', 'size': '0.0076768'},
  {'price': '65132.94', 'size': '0.01078537'},
  {'price': '65133.82', 'size': '0.0002'},
  {'price': '65141.64', 'size': '0.00004289'},
  {'price': '65141.72', 'size': '0.00001538'},
  {'price': '65143.38', 'size': '0.00007675'},
  {'price': '65144.26', 'size': '0.00000001'},
  {'price': '65145', 'size': '0.01507698'},
  {'price': '65146.36', 'size': '0.01608394'},
  {'price': '65147.23', 'size': '0.0012328'},
  {'price': '65147.51', 'size': '0.00000001'},
  {'price': '65147.67', 'size': '0.00000004'},
  {'price': '65147.95', 'size': '0.00000003'},
  {'price': '65150', 'size': '0.00066893'},
  {'price': '65150.35', 'size': '0.0000005'},
  {'price': '65151', 'size': '0.001'},
  {'price': '65152.02', 'size': '0.0248516'},
  {'price': '65155.07', 'size': '0.00015348'},
  {'price': '65156.03', 'size': '0.00000001'},
  {'price': '65162.12', 'size': '0.00035292'},
  {'price': '65162.71', 'size': '0.01280885'},
  {'price': '65164', 'size': '0.00321781'},
  {'price': '65166.43', 'size': '0.00032263'},
  {'price': '65168', 'size': '0.0012'},
  {'price': '65172.99', 'size': '0.00767188'},
  {'price': '65178.52', 'size': '0.00176362'},
  {'price': '65178.59', 'size': '0.00316713'},
  {'price': '65180.31', 'size': '0.00001534'},
  {'price': '65184.22', 'size': '0.00084704'},
  {'price': '65186.36', 'size': '0.06596472'},
  {'price': '65190', 'size': '2.89'},
  {'price': '65193.69', 'size': '0.00000001'},
  {'price': '65198', 'size': '5'},
  {'price': '65199', 'size': '0.00001688'},
  {'price': '65200', 'size': '4.73664999'},
  {'price': '65200.55', 'size': '0.00003098'},
  {'price': '65200.57', 'size': '0.07438927'},
  {'price': '65204.9', 'size': '0.03574194'},
  {'price': '65205', 'size': '0.00001706'},
  {'price': '65205.67', 'size': '0.00015336'},
  {'price': '65208.04', 'size': '0.00021961'},
  {'price': '65211.78', 'size': '0.0012'},
  {'price': '65213', 'size': '0.0075'},
  {'price': '65213.86', 'size': '0.0000534'},
  {'price': '65216.57', 'size': '0.00045693'},
  {'price': '65218.57', 'size': '0.07666528'},
  {'price': '65220.15', 'size': '0.0001385'},
  {'price': '65221.7', 'size': '0.04851777'},
  {'price': '65225', 'size': '0.111'},
  {'price': '65225.91', 'size': '0.00123114'},
  {'price': '65229', 'size': '0.12033105'},
  {'price': '65230', 'size': '0.01533036'},
  {'price': '65230.1', 'size': '0.0251039'},
  {'price': '65232.41', 'size': '0.00158925'},
  {'price': '65232.83', 'size': '0.00009235'},
  {'price': '65234.84', 'size': '0.00011529'},
  {'price': '65235.25', 'size': '0.01619774'},
  {'price': '65235.33', 'size': '0.00020962'},
  {'price': '65238', 'size': '0.00012691'},
  {'price': '65238.13', 'size': '0.01042649'},
  {'price': '65243.19', 'size': '0.0000469'},
  {'price': '65246', 'size': '0.00020143'},
  {'price': '65246.48', 'size': '0.00453792'},
  {'price': '65248.99', 'size': '0.00314181'},
  {'price': '65249.18', 'size': '0.00000001'},
  {'price': '65250', 'size': '4.08882273'},
  {'price': '65252.25', 'size': '0.00400633'},
  {'price': '65252.98', 'size': '0.00392688'},
  {'price': '65255', 'size': '0.03951124'},
  {'price': '65257.5', 'size': '0.02235246'},
  {'price': '65259.81', 'size': '0.03870204'},
  {'price': '65263.09', 'size': '0.00008007'},
  {'price': '65263.38', 'size': '0.00001535'},
  {'price': '65263.55', 'size': '0.00306449'},
  {'price': '65263.79', 'size': '0.00022375'},
  {'price': '65264.17', 'size': '0.00000001'},
  {'price': '65266.58', 'size': '0.00038954'},
  {'price': '65267', 'size': '1.563'},
  {'price': '65273.56', 'size': '0.00000286'},
  {'price': '65274.25', 'size': '0.00001149'},
  {'price': '65275', 'size': '0.05'},
  {'price': '65279', 'size': '0.00316713'},
  {'price': '65280', 'size': '0.01251629'},
  {'price': '65281.21', 'size': '0.00030432'},
  {'price': '65282.5', 'size': '0.00499384'},
  {'price': '65284.06', 'size': '0.00017686'},
  {'price': '65284.81', 'size': '0.00160647'},
  {'price': '65284.82', 'size': '0.00472406'},
  {'price': '65285', 'size': '0.01366911'},
  {'price': '65295.89', 'size': '0.00032199'},
  {'price': '65295.92', 'size': '0.00000766'},
  {'price': '65296.91', 'size': '0.00003245'},
  {'price': '65298.78', 'size': '0.0012'},
  {'price': '65300', 'size': '2.02273641'},
  {'price': '65305', 'size': '0.00003062'},
  {'price': '65308.18', 'size': '0.02535876'},
  {'price': '65308.73', 'size': '0.00039045'},
  {'price': '65310.04', 'size': '0.0000005'},
  {'price': '65310.16', 'size': '0.00145493'},
  {'price': '65310.95', 'size': '0.09220314'},
  {'price': '65315', 'size': '0.02944845'},
  {'price': '65319', 'size': '0.00344463'},
  {'price': '65319.69', 'size': '0.01475446'},
  ...],
 'bids': [{'price': '63033.89', 'size': '0.36320277'},
  {'price': '63033.88', 'size': '0.03'},
  {'price': '63033.86', 'size': '0.03'},
  {'price': '63033.8', 'size': '0.00079322'},
  {'price': '63032.01', 'size': '0.11820631'},
  {'price': '63032', 'size': '0.0815'},
  {'price': '63031.75', 'size': '0.12692014'},
  {'price': '63030.72', 'size': '0.10563185'},
  {'price': '63030.71', 'size': '0.09541977'},
  {'price': '63030.15', 'size': '0.000018'},
  {'price': '63030', 'size': '0.0815'},
  {'price': '63028.12', 'size': '0.20574154'},
  {'price': '63028.11', 'size': '0.027597'},
  {'price': '63028', 'size': '0.0815'},
  {'price': '63027.84', 'size': '0.09541977'},
  {'price': '63026.58', 'size': '0.06'},
  {'price': '63026.2', 'size': '0.000018'},
  {'price': '63025', 'size': '0.01'},
  {'price': '63024.76', 'size': '0.19412352'},
  {'price': '63024.75', 'size': '0.09541977'},
  {'price': '63024.28', 'size': '0.0007932'},
  {'price': '63024', 'size': '0.0857'},
  {'price': '63022.31', 'size': '0.09541977'},
  {'price': '63022.25', 'size': '0.000018'},
  {'price': '63022.12', 'size': '0.04781428'},
  {'price': '63022.01', 'size': '0.24818865'},
  {'price': '63022', 'size': '0.0857'},
  {'price': '63020.54', 'size': '0.03975824'},
  {'price': '63020.2', 'size': '0.0952022'},
  {'price': '63020', 'size': '0.0957'},
  {'price': '63019.07', 'size': '0.00794908'},
  {'price': '63019.06', 'size': '0.09541977'},
  {'price': '63018.98', 'size': '0.00394391'},
  {'price': '63018.7', 'size': '0.04304949'},
  {'price': '63018.3', 'size': '0.000018'},
  {'price': '63018.01', 'size': '0.64263091'},
  {'price': '63018', 'size': '1'},
  {'price': '63016.89', 'size': '0.0557021'},
  {'price': '63016.86', 'size': '0.459951'},
  {'price': '63016.66', 'size': '0.14357031'},
  {'price': '63016.6', 'size': '0.05818108'},
  {'price': '63016.51', 'size': '0.09541977'},
  {'price': '63015.89', 'size': '0.28203227'},
  {'price': '63015.3', 'size': '0.05453258'},
  {'price': '63015.29', 'size': '0.01984869'},
  {'price': '63015.19', 'size': '0.00592'},
  {'price': '63015.02', 'size': '0.03975824'},
  {'price': '63015', 'size': '0.01'},
  {'price': '63014.4', 'size': '0.0000238'},
  {'price': '63014.35', 'size': '0.000018'},
  {'price': '63013.83', 'size': '0.09541977'},
  {'price': '63012.7', 'size': '0.01577563'},
  {'price': '63012.3', 'size': '0.0000841'},
  {'price': '63012.03', 'size': '0.00583'},
  {'price': '63011.79', 'size': '0.15904213'},
  {'price': '63011.78', 'size': '0.09541977'},
  {'price': '63011.51', 'size': '0.00107082'},
  {'price': '63010.4', 'size': '0.000018'},
  {'price': '63010', 'size': '0.01003186'},
  {'price': '63009.8', 'size': '0.09541977'},
  {'price': '63009.62', 'size': '0.02468377'},
  {'price': '63009.46', 'size': '0.03975824'},
  {'price': '63008.98', 'size': '0.04781428'},
  {'price': '63007.78', 'size': '0.15364397'},
  {'price': '63007.77', 'size': '0.09541977'},
  {'price': '63007.74', 'size': '0.00198388'},
  {'price': '63007.58', 'size': '0.00793555'},
  {'price': '63007.34', 'size': '0.00793558'},
  {'price': '63006.89', 'size': '0.06'},
  {'price': '63006.49', 'size': '0.08'},
  {'price': '63006.45', 'size': '0.000018'},
  {'price': '63006.31', 'size': '0.00006234'},
  {'price': '63005.8', 'size': '0.12236431'},
  {'price': '63005.65', 'size': '0.00012468'},
  {'price': '63005', 'size': '0.01'},
  {'price': '63004.33', 'size': '0.03155127'},
  {'price': '63003.2', 'size': '0.03975824'},
  {'price': '63003.06', 'size': '0.04781428'},
  {'price': '63002.5', 'size': '0.000018'},
  {'price': '63002.34', 'size': '0.00024937'},
  {'price': '63000.55', 'size': '0.00316663'},
  {'price': '63000.35', 'size': '0.00162603'},
  {'price': '63000', 'size': '0.01'},
  {'price': '62999.53', 'size': '0.01997891'},
  {'price': '62999.52', 'size': '0.29991277'},
  {'price': '62999.48', 'size': '0.07004154'},
  {'price': '62998.55', 'size': '0.000018'},
  {'price': '62998.01', 'size': '0.03975824'},
  {'price': '62997.75', 'size': '0.04781428'},
  {'price': '62995.72', 'size': '0.00049873'},
  {'price': '62995.49', 'size': '0.0000238'},
  {'price': '62995.02', 'size': '0.00158507'},
  {'price': '62995', 'size': '0.01'},
  {'price': '62994.6', 'size': '0.000018'},
  {'price': '62993.88', 'size': '0.00079308'},
  {'price': '62993.87', 'size': '0.03943909'},
  {'price': '62992.81', 'size': '0.66397059'},
  {'price': '62992.8', 'size': '0.03975824'},
  {'price': '62991.37', 'size': '0.24267485'},
  {'price': '62990.97', 'size': '0.04781428'},
  {'price': '62990.65', 'size': '0.000018'},
  {'price': '62990', 'size': '0.01'},
  {'price': '62988.72', 'size': '0.00792535'},
  {'price': '62988.09', 'size': '0.06939221'},
  {'price': '62987.45', 'size': '0.00062341'},
  {'price': '62986.7', 'size': '0.000018'},
  {'price': '62985.44', 'size': '0.23304997'},
  {'price': '62985.43', 'size': '0.25380631'},
  {'price': '62985', 'size': '0.01'},
  {'price': '62984.99', 'size': '0.03975824'},
  {'price': '62984.35', 'size': '0.07887817'},
  {'price': '62983.3', 'size': '0.02855587'},
  {'price': '62983.29', 'size': '0.04781428'},
  {'price': '62982.75', 'size': '0.000018'},
  {'price': '62980.48', 'size': '0.00277864'},
  {'price': '62978.8', 'size': '0.000018'},
  {'price': '62978.63', 'size': '0.56780418'},
  {'price': '62978.17', 'size': '0.06818887'},
  {'price': '62977.59', 'size': '0.08757252'},
  {'price': '62976.83', 'size': '1.42909684'},
  {'price': '62976.59', 'size': '0.00482083'},
  {'price': '62976.58', 'size': '0.0000238'},
  {'price': '62974.85', 'size': '0.000018'},
  {'price': '62974.7', 'size': '0.00245906'},
  {'price': '62970.99', 'size': '0.99687506'},
  {'price': '62970.98', 'size': '0.237875'},
  {'price': '62970.92', 'size': '0.00124683'},
  {'price': '62970.9', 'size': '0.000018'},
  {'price': '62969.11', 'size': '0.00150554'},
  {'price': '62968.37', 'size': '0.06580204'},
  {'price': '62968.36', 'size': '0.06965192'},
  {'price': '62967.51', 'size': '0.00079302'},
  {'price': '62967.5', 'size': '0.03975824'},
  {'price': '62966.95', 'size': '0.000018'},
  {'price': '62963.76', 'size': '0.85415299'},
  {'price': '62963.75', 'size': '1.42939387'},
  {'price': '62963', 'size': '0.000018'},
  {'price': '62960.43', 'size': '0.001904'},
  {'price': '62959.05', 'size': '0.000018'},
  {'price': '62957.67', 'size': '0.0000238'},
  {'price': '62957.4', 'size': '0.01061683'},
  {'price': '62957', 'size': '0.01116334'},
  {'price': '62956.62', 'size': '1.38084443'},
  {'price': '62955.1', 'size': '0.000018'},
  {'price': '62952.47', 'size': '0.09859772'},
  {'price': '62952.09', 'size': '0.01331'},
  {'price': '62951.64', 'size': '2.23854834'},
  {'price': '62951.63', 'size': '1.235891'},
  {'price': '62950.65', 'size': '1.42969114'},
  {'price': '62950.24', 'size': '0.00155853'},
  {'price': '62949.02', 'size': '0.00356972'},
  {'price': '62947.2', 'size': '0.000018'},
  {'price': '62945', 'size': '3'},
  {'price': '62944.44', 'size': '0.0108863'},
  {'price': '62938.76', 'size': '0.0000238'},
  {'price': '62937.88', 'size': '1.42998135'},
  {'price': '62937.76', 'size': '0.2999'},
  {'price': '62934.93', 'size': '5.258804'},
  {'price': '62932.09', 'size': '0.00019528'},
  {'price': '62931.88', 'size': '0.01112167'},
  {'price': '62931.4', 'size': '0.000018'},
  {'price': '62925.44', 'size': '0.00187024'},
  {'price': '62925', 'size': '0.05'},
  {'price': '62924.91', 'size': '1.43027616'},
  {'price': '62921.09', 'size': '0.11831726'},
  {'price': '62919.85', 'size': '0.0000238'},
  {'price': '62919.32', 'size': '0.01103176'},
  {'price': '62918.6', 'size': '10.308493'},
  {'price': '62917.72', 'size': '0.00031724'},
  {'price': '62915.6', 'size': '0.000018'},
  {'price': '62912.32', 'size': '0.00031728'},
  {'price': '62911.86', 'size': '1.43057279'},
  {'price': '62909.51', 'size': '0.09135466'},
  {'price': '62903.74', 'size': '0.0000157'},
  {'price': '62901.92', 'size': '0.237976'},
  {'price': '62899.8', 'size': '0.000018'},
  {'price': '62898.86', 'size': '1.43086846'},
  {'price': '62897.2', 'size': '10.056939'},
  {'price': '62894.19', 'size': '0.04364'},
  {'price': '62893.28', 'size': '0.00022445'},
  {'price': '62892.3', 'size': '0.04364'},
  {'price': '62887.98', 'size': '0.00159012'},
  {'price': '62887.84', 'size': '0.23958468'},
  {'price': '62886.13', 'size': '1.43115802'},
  {'price': '62885.36', 'size': '0.23958468'},
  {'price': '62884.38', 'size': '0.23958468'},
  {'price': '62884', 'size': '0.000018'},
  {'price': '62880.04', 'size': '0.00000011'},
  {'price': '62873.59', 'size': '0.00285573'},
  {'price': '62873.24', 'size': '1.43145139'},
  {'price': '62868.2', 'size': '0.000018'},
  {'price': '62862.65', 'size': '0.03'},
  {'price': '62861.21', 'size': '3.27683776'},
  {'price': '62860.82', 'size': '0.00742734'},
  {'price': '62860.76', 'size': '0.03'},
  {'price': '62860.56', 'size': '1.43174015'},
  {'price': '62854.63', 'size': '0.00031724'},
  {'price': '62852.4', 'size': '0.000018'},
  {'price': '62852.28', 'size': '0.00827862'},
  {'price': '62849.23', 'size': '0.00031728'},
  {'price': '62847.61', 'size': '1.43203525'},
  {'price': '62846.57', 'size': '0.09144615'},
  {'price': '62839.76', 'size': '0.03'},
  {'price': '62834.77', 'size': '1.43232779'},
  {'price': '62834.54', 'size': '0.023794'},
  {'price': '62834.49', 'size': '10.910353'},
  {'price': '62831.12', 'size': '0.04364'},
  {'price': '62829.23', 'size': '0.01364'},
  {'price': '62828.71', 'size': '0.0003909'},
  {'price': '62824.56', 'size': '0.00275524'},
  {'price': '62823.57', 'size': '0.00000336'},
  {'price': '62822.21', 'size': '1.43261432'},
  {'price': '62821.04', 'size': '0.00336969'},
  {'price': '62820.1', 'size': '0.00150322'},
  {'price': '62808.72', 'size': '1.43292195'},
  {'price': '62807.63', 'size': '0.28860807'},
  {'price': '62805.8', 'size': '0.05'},
  {'price': '62804.99', 'size': '0.00500051'},
  {'price': '62800.89', 'size': '0.00314645'},
  {'price': '62800', 'size': '0.00012662'},
  {'price': '62798.96', 'size': '0.23958468'},
  {'price': '62797.38', 'size': '0.00499997'},
  {'price': '62796.82', 'size': '0.00583'},
  {'price': '62796.06', 'size': '1.43321082'},
  {'price': '62794.93', 'size': '0.00220659'},
  {'price': '62792', 'size': '0.1'},
  {'price': '62791.54', 'size': '0.00031724'},
  {'price': '62786.14', 'size': '0.00031728'},
  {'price': '62786', 'size': '0.0001343'},
  {'price': '62785.54', 'size': '0.04364'},
  {'price': '62783.7', 'size': '0.09153772'},
  {'price': '62783.44', 'size': '1.43349889'},
  {'price': '62778.12', 'size': '14.024456'},
  {'price': '62776.02', 'size': '1.4336683'},
  {'price': '62768.05', 'size': '0.01364'},
  {'price': '62767.97', 'size': '0.00052534'},
  {'price': '62761.3', 'size': '0.28860807'},
  {'price': '62760.85', 'size': '0.00158378'},
  {'price': '62758.43', 'size': '0.01'},
  {'price': '62750.66', 'size': '1.6'},
  {'price': '62740.34', 'size': '0.00002024'},
  {'price': '62739.73', 'size': '0.1'},
  {'price': '62739.43', 'size': '0.00008057'},
  {'price': '62734.79', 'size': '0.00001594'},
  {'price': '62732', 'size': '0.0012'},
  {'price': '62728.54', 'size': '0.00001594'},
  {'price': '62728.44', 'size': '0.00031724'},
  {'price': '62728', 'size': '0.00020879'},
  {'price': '62724.82', 'size': '0.00020651'},
  {'price': '62723.88', 'size': '0.00077418'},
  {'price': '62723.05', 'size': '0.00031728'},
  {'price': '62722.45', 'size': '0.04364'},
  {'price': '62720.89', 'size': '0.09162939'},
  {'price': '62720.21', 'size': '0.00006301'},
  {'price': '62717.9', 'size': '0.00005596'},
  {'price': '62717.14', 'size': '0.00001594'},
  {'price': '62713.13', 'size': '0.00027067'},
  {'price': '62712', 'size': '0.00008137'},
  {'price': '62710', 'size': '0.02038717'},
  {'price': '62707.5', 'size': '0.0000534'},
  {'price': '62706.6', 'size': '0.00006099'},
  {'price': '62704.98', 'size': '0.01364'},
  {'price': '62704.87', 'size': '0.00670897'},
  {'price': '62704.51', 'size': '0.00001594'},
  {'price': '62702.46', 'size': '0.00026171'},
  {'price': '62700.17', 'size': '0.00319435'},
  {'price': '62700', 'size': '0.06583728'},
  {'price': '62699.94', 'size': '0.00079745'},
  {'price': '62697.18', 'size': '43.653285'},
  {'price': '62689.2', 'size': '1.6'},
  {'price': '62688.81', 'size': '0.01193753'},
  {'price': '62688.61', 'size': '0.0012'},
  {'price': '62686.38', 'size': '0.03717793'},
  {'price': '62678.85', 'size': '0.00041666'},
  {'price': '62675', 'size': '0.00011223'},
  {'price': '62674.63', 'size': '0.00015789'},
  {'price': '62666.49', 'size': '0.00562'},
  {'price': '62666.4', 'size': '0.00396128'},
  {'price': '62665.02', 'size': '0.47586717'},
  {'price': '62660.37', 'size': '0.07931933'},
  {'price': '62659.87', 'size': '0.01050113'},
  {'price': '62658.14', 'size': '0.09172116'},
  {'price': '62657.77', 'size': '0.00136305'},
  {'price': '62656', 'size': '0.0000798'},
  {'price': '62655.91', 'size': '0.02387506'},
  {'price': '62650.11', 'size': '0.00039425'},
  {'price': '62650', 'size': '3.24571756'},
  {'price': '62649.78', 'size': '0.00009235'},
  {'price': '62647.99', 'size': '0.0001626'},
  {'price': '62646.19', 'size': '0.02'},
  {'price': '62645', 'size': '0.0012'},
  {'price': '62642.29', 'size': '0.00031927'},
  {'price': '62632.57', 'size': '0.0001587'},
  {'price': '62627.74', 'size': '1.6'},
  {'price': '62627.44', 'size': '0.0004597'},
  {'price': '62620.91', 'size': '0.00004797'},
  {'price': '62620.01', 'size': '0.03581259'},
  {'price': '62619.41', 'size': '0.00014522'},
  {'price': '62618.83', 'size': '0.001'},
  {'price': '62617.68', 'size': '0.00022622'},
  {'price': '62617.5', 'size': '0.00004007'},
  {'price': '62616.04', 'size': '0.00008057'},
  {'price': '62614.86', 'size': '1'},
  {'price': '62613.12', 'size': '0.00015971'},
  {'price': '62611.16', 'size': '0.00015971'},
  {'price': '62611', 'size': '0.00079379'},
  {'price': '62605.32', 'size': '0.00039933'},
  {'price': '62603.74', 'size': '0.00319435'},
  {'price': '62602.99', 'size': '0.00047921'},
  {'price': '62601.61', 'size': '0.0012'},
  {'price': '62600', 'size': '0.5121244'},
  {'price': '62597.44', 'size': '0.000006'},
  {'price': '62595.45', 'size': '0.09181301'},
  {'price': '62593', 'size': '0.00775837'},
  {'price': '62590', 'size': '0.00119968'},
  {'price': '62588', 'size': '0.00157857'},
  {'price': '62583.8', 'size': '0.1'},
  {'price': '62582.29', 'size': '0.00583'},
  {'price': '62580', 'size': '0.45473394'},
  {'price': '62575.11', 'size': '0.03035662'},
  {'price': '62574.19', 'size': '0.00198564'},
  {'price': '62573.62', 'size': '0.00009521'},
  {'price': '62573.26', 'size': '0.00587843'},
  {'price': '62570.67', 'size': '0.00945005'},
  {'price': '62568', 'size': '0.00014196'},
  {'price': '62567.45', 'size': '0.00019952'},
  {'price': '62566.38', 'size': '0.03196604'},
  {'price': '62566.28', 'size': '1.6'},
  {'price': '62565.02', 'size': '0.00005761'},
  {'price': '62558', 'size': '0.0012'},
  {'price': '62555.55', 'size': '0.0005595'},
  {'price': '62555.3', 'size': '0.04851777'},
  {'price': '62555', 'size': '0.01552633'},
  {'price': '62548.54', 'size': '0.00185423'},
  {'price': '62547.35', 'size': '0.00155274'},
  {'price': '62546.78', 'size': '0.00004244'},
  {'price': '62545.58', 'size': '0.00399708'},
  {'price': '62545.02', 'size': '0.00159884'},
  {'price': '62542.17', 'size': '0.00009235'},
  {'price': '62540.86', 'size': '0.00033721'},
  {'price': '62538.67', 'size': '0.00155295'},
  {'price': '62535.7', 'size': '0.00000001'},
  {'price': '62533.45', 'size': '0.00238432'},
  {'price': '62532.82', 'size': '0.09190497'},
  {'price': '62532.11', 'size': '0.00022715'},
  {'price': '62531.95', 'size': '0.00007995'},
  {'price': '62528.78', 'size': '0.00103952'},
  {'price': '62528.4', 'size': '0.00006099'},
  {'price': '62527.92', 'size': '0.01420165'},
  {'price': '62527.59', 'size': '0.01599294'},
  {'price': '62525', 'size': '0.00007996'},
  {'price': '62523.88', 'size': '0.00005613'},
  {'price': '62523.34', 'size': '0.00000295'},
  {'price': '62521', 'size': '0.03'},
  {'price': '62514.76', 'size': '0.0000018'},
  {'price': '62514.74', 'size': '0.00127971'},
  {'price': '62514.62', 'size': '0.00038838'},
  {'price': '62514.61', 'size': '0.0012'},
  {'price': '62512.72', 'size': '0.07193'},
  {'price': '62506.36', 'size': '0.00470393'},
  {'price': '62506.06', 'size': '0.00047707'},
  {'price': '62505.91', 'size': '0.15118441'},
  {'price': '62505.84', 'size': '0.00085644'},
  {'price': '62505.53', 'size': '0.00111281'},
  {'price': '62505', 'size': '0.0000534'},
  {'price': '62504.82', 'size': '1.6'},
  {'price': '62501', 'size': '0.01591974'},
  {'price': '62500.99', 'size': '0.00007999'},
  {'price': '62500', 'size': '0.36641462'},
  {'price': '62497.49', 'size': '0.00160006'},
  {'price': '62497.04', 'size': '0.0081'},
  {'price': '62496.72', 'size': '0.03729075'},
  {'price': '62495.97', 'size': '0.00077332'},
  {'price': '62495.74', 'size': '0.02'},
  {'price': '62495.47', 'size': '0.000016'},
  {'price': '62494.92', 'size': '0.01330937'},
  {'price': '62492.9', 'size': '0.00008057'},
  {'price': '62489.69', 'size': '0.00938689'},
  {'price': '62489.48', 'size': '0.001'},
  {'price': '62487.03', 'size': '0.0003496'},
  {'price': '62485.77', 'size': '0.00079057'},
  {'price': '62483', 'size': '0.0047821'},
  {'price': '62481.96', 'size': '0.00223023'},
  {'price': '62478.8', 'size': '0.00008692'},
  {'price': '62475.39', 'size': '0.00040015'},
  {'price': '62471', 'size': '0.0012'},
  {'price': '62468.36', 'size': '0.00009604'},
  {'price': '62468.21', 'size': '0.00040133'},
  {'price': '62461.03', 'size': '0.00228718'},
  {'price': '62459.65', 'size': '0.00036545'},
  {'price': '62458.78', 'size': '0.00081641'},
  {'price': '62450', 'size': '0.0719277'},
  {'price': '62447.47', 'size': '0.00030162'},
  {'price': '62447', 'size': '0.28860807'},
  {'price': '62444', 'size': '0.05461653'},
  {'price': '62443.36', 'size': '1.6'},
  {'price': '62437.84', 'size': '0.00000014'},
  {'price': '62434.57', 'size': '0.00009235'},
  {'price': '62433.85', 'size': '0.00160169'},
  {'price': '62432.43', 'size': '0.00022689'},
  {'price': '62427.61', 'size': '0.0012'},
  {'price': '62427.47', 'size': '0.00000014'},
  {'price': '62425.2', 'size': '0.28860807'},
  {'price': '62423.74', 'size': '0.00233372'},
  {'price': '62421.75', 'size': '0.00208035'},
  {'price': '62420', 'size': '0.00237534'},
  {'price': '62418.75', 'size': '0.0004646'},
  {'price': '62416.47', 'size': '0.00000015'},
  {'price': '62411.82', 'size': '0.00047747'},
  {'price': '62411.3', 'size': '0.00045058'},
  {'price': '62411.11', 'size': '0.00301746'},
  {'price': '62406.04', 'size': '0.00799201'},
  {'price': '62404.81', 'size': '0.00000015'},
  {'price': '62404.02', 'size': '0.00008855'},
  {'price': '62401.24', 'size': '0.001'},
  {'price': '62400', 'size': '1.84838392'},
  {'price': '62399', 'size': '0.00795542'},
  {'price': '62392.46', 'size': '0.00000015'},
  {'price': '62391.91', 'size': '0.0559425'},
  {'price': '62388', 'size': '0.0025'},
  {'price': '62384', 'size': '0.0012'},
  {'price': '62381.9', 'size': '9.6'},
  {'price': '62380', 'size': '0.00161306'},
  {'price': '62379.36', 'size': '0.00000015'},
  {'price': '62375.34', 'size': '0.00003959'},
  {'price': '62375', 'size': '0.00159919'},
  {'price': '62374.44', 'size': '0.00799606'},
  {'price': '62373.41', 'size': '0.001'},
  {'price': '62370', 'size': '0.00061585'},
  {'price': '62369.93', 'size': '0.0001458'},
  {'price': '62368.18', 'size': '0.00040085'},
  {'price': '62368.11', 'size': '0.00160338'},
  {'price': '62367.82', 'size': '0.00583'},
  {'price': '62365.48', 'size': '0.00000016'},
  {'price': '62364.28', 'size': '0.16034819'},
  {'price': '62362.66', 'size': '0.00079232'},
  {'price': '62360.17', 'size': '0.02405381'},
  {'price': '62355.38', 'size': '0.00002036'},
  {'price': '62355', 'size': '0.00013198'},
  {'price': '62350.76', 'size': '0.00000016'},
  {'price': '62350.53', 'size': '0.00436354'},
  {'price': '62350.2', 'size': '0.00006099'},
  {'price': '62348.27', 'size': '0.001'},
  {'price': '62345', 'size': '0.00044552'},
  {'price': '62343.92', 'size': '0.00251828'},
  {'price': '62343.21', 'size': '0.00207632'},
  {'price': '62340.56', 'size': '0.0012'},
  {'price': '62340.08', 'size': '0.00125689'},
  {'price': '62337.59', 'size': '0.00001604'},
  {'price': '62335.17', 'size': '0.00000016'},
  {'price': '62331.27', 'size': '0.00002965'},
  {'price': '62330.46', 'size': '0.00005631'},
  {'price': '62327.36', 'size': '0.001'},
  {'price': '62326.95', 'size': '0.00009235'},
  {'price': '62325', 'size': '2'},
  {'price': '62321.15', 'size': '0.00200573'},
  {'price': '62320.44', 'size': '8'},
  {'price': '62318.63', 'size': '0.00000016'},
  {'price': '62313.43', 'size': '0.00004244'},
  {'price': '62309.22', 'size': '0.00008024'},
  {'price': '62307.64', 'size': '0.03740392'},
  {'price': '62303.35', 'size': '0.00031722'},
  {'price': '62302.5', 'size': '0.0000534'},
  {'price': '62301.1', 'size': '0.00000017'},
  {'price': '62300', 'size': '4.54515573'},
  {'price': '62297', 'size': '0.0012'},
  {'price': '62292.77', 'size': '0.00589925'},
  {'price': '62291.95', 'size': '0.00007385'},
  {'price': '62291.5', 'size': '0.02393584'},
  {'price': '62289.83', 'size': '0.00003718'},
  {'price': '62289', 'size': '0.00040085'},
  {'price': '62282.53', 'size': '0.00000018'},
  {'price': '62276', 'size': '0.00079366'},
  {'price': '62275.34', 'size': '0.00001605'},
  {'price': '62271', 'size': '0.00003949'},
  {'price': '62269', 'size': '0.02'},
  {'price': '62262.83', 'size': '0.00000018'},
  {'price': '62261.09', 'size': '0.00001606'},
  {'price': '62260.97', 'size': '0.00020077'},
  {'price': '62258.98', 'size': '8'},
  {'price': '62257.33', 'size': '0.00472274'},
  {'price': '62254.86', 'size': '0.00005789'},
  {'price': '62253.56', 'size': '0.0012'},
  {'price': '62253.31', 'size': '0.00006349'},
  {'price': '62250', 'size': '0.07668714'},
  {'price': '62249.51', 'size': '0.00000297'},
  {'price': '62247.73', 'size': '0.00022756'},
  {'price': '62246', 'size': '0.00150906'},
  {'price': '62241.96', 'size': '0.00000018'},
  {'price': '62241.27', 'size': '0.0006'},
  {'price': '62239.35', 'size': '0.00002'},
  {'price': '62236.96', 'size': '0.00278139'},
  {'price': '62230.41', 'size': '0.00001808'},
  {'price': '62230.33', 'size': '0.00003932'},
  {'price': '62230.21', 'size': '0.03985458'},
  {'price': '62227', 'size': '0.00296196'},
  {'price': '62222', 'size': '0.04851777'},
  {'price': '62221.26', 'size': '0.00235997'},
  {'price': '62219.83', 'size': '0.00000018'},
  {'price': '62219.35', 'size': '0.00009235'},
  {'price': '62218.59', 'size': '0.0002283'},
  {'price': '62216.88', 'size': '0.0007'},
  {'price': '62212.5', 'size': '0.01397327'},
  {'price': '62210.44', 'size': '0.00008202'},
  {'price': '62210', 'size': '0.16066119'},
  {'price': '62209.63', 'size': '0.00002625'},
  {'price': '62207.43', 'size': '0.00079411'},
  {'price': '62206.94', 'size': '0.0001'},
  {'price': '62205', 'size': '0.00003989'},
  {'price': '62200', 'size': '1.77691658'},
  {'price': '62199.86', 'size': '0.00016377'},
  {'price': '62197.52', 'size': '8'},
  {'price': '62196.38', 'size': '0.00000019'},
  {'price': '62193.25', 'size': '0.00000448'},
  {'price': '62191.51', 'size': '0.00803968'},
  {'price': '62188.22', 'size': '0.01196368'},
  {'price': '62183.74', 'size': '0.00156182'},
  {'price': '62181.97', 'size': '0.00001608'},
  {'price': '62176.47', 'size': '0.00186533'},
  {'price': '62172', 'size': '0.00108033'},
  {'price': '62171.52', 'size': '0.0000002'},
  {'price': '62170.68', 'size': '0.00048744'},
  {'price': '62169.06', 'size': '0.25'},
  {'price': '62168.36', 'size': '0.0080105'},
  {'price': '62167.87', 'size': '0.00002011'},
  {'price': '62166.56', 'size': '0.0012'},
  {'price': '62164.85', 'size': '0.00025022'},
  {'price': '62162.1', 'size': '0.00003946'},
  {'price': '62158.94', 'size': '0.92192245'},
  {'price': '62157.07', 'size': '0.00078124'},
  {'price': '62155.22', 'size': '0.03167'},
  {'price': '62154.98', 'size': '0.00055875'},
  {'price': '62154.68', 'size': '0.00008432'},
  {'price': '62152.46', 'size': '0.00171766'},
  {'price': '62149.15', 'size': '0.00036728'},
  {'price': '62148.44', 'size': '0.00119213'},
  {'price': '62148.38', 'size': '0.00008367'},
  {'price': '62146.02', 'size': '0.00082052'},
  {'price': '62145.16', 'size': '0.0000002'},
  {'price': '62144.79', 'size': '0.001'},
  {'price': '62142.43', 'size': '0.00052345'},
  {'price': '62142.11', 'size': '0.0012'},
  {'price': '62137.65', 'size': '0.00005648'},
  {'price': '62136.42', 'size': '0.00001609'},
  {'price': '62136.06', 'size': '8'},
  {'price': '62133.2', 'size': '0.00008902'},
  {'price': '62132.85', 'size': '0.002'},
  {'price': '62131.04', 'size': '0.00040238'},
  {'price': '62127.98', 'size': '0.01180251'},
  {'price': '62123.78', 'size': '0.0063887'},
  {'price': '62122.5', 'size': '0.00004007'},
  {'price': '62122', 'size': '0.00139496'},
  {'price': '62121.44', 'size': '0.00014638'},
  {'price': '62119.13', 'size': '0.03751742'},
  {'price': '62118', 'size': '0.00159052'},
  {'price': '62117.23', 'size': '0.0000002'},
  {'price': '62116.64', 'size': '0.00071564'},
  {'price': '62113.97', 'size': '0.0056348'},
  {'price': '62112.22', 'size': '0.00033647'},
  {'price': '62111.74', 'size': '0.00009235'},
  {'price': '62108.36', 'size': '0.00337106'},
  {'price': '62108.03', 'size': '0.0000161'},
  {'price': '62105', 'size': '0.00240922'},
  {'price': '62102.2', 'size': '0.0000152'},
  {'price': '62100', 'size': '0.07412206'},
  {'price': '62097.5', 'size': '0.00181777'},
  {'price': '62096.26', 'size': '0.00042671'},
  {'price': '62095.77', 'size': '0.00172821'},
  {'price': '62094', 'size': '0.00000016'},
  {'price': '62091.64', 'size': '0.00004579'},
  {'price': '62089', 'size': '0.02000064'},
  {'price': '62088.33', 'size': '0.00018607'},
  {'price': '62087.62', 'size': '0.00000021'},
  {'price': '62080.07', 'size': '0.00004244'},
  {'price': '62079.56', 'size': '0.0012'},
  {'price': '62076', 'size': '0.00080534'},
  {'price': '62074.6', 'size': '8'},
  {'price': '62073.52', 'size': '0.00020111'},
  {'price': '62065.95', 'size': '0.00048335'},
  {'price': '62065.18', 'size': '0.1043502'},
  {'price': '62064.28', 'size': '0.00562'},
  {'price': '62063.58', 'size': '0.00022824'},
  {'price': '62062', 'size': '0.01603235'},
  {'price': '62056.23', 'size': '0.00000021'},
  {'price': '62054.23', 'size': '0.00040287'},
  {'price': '62053.82', 'size': '0.03054558'},
  {'price': '62051', 'size': '0.06430194'},
  {'price': '62050', 'size': '1.00801244'},
  {'price': '62048', 'size': '0.00782652'},
  {'price': '62047.61', 'size': '0.00033989'},
  {'price': '62041.19', 'size': '0.00001209'},
  {'price': '62038.88', 'size': '0.00303556'},
  {'price': '62036', 'size': '0.0012'},
  {'price': '62035', 'size': '0.02'},
  {'price': '62032.84', 'size': '0.00318363'},
  {'price': '62029.51', 'size': '0.005'},
  {'price': '62028.23', 'size': '0.0063887'},
  {'price': '62027.46', 'size': '0.00015988'},
  {'price': '62025', 'size': '0.40810002'},
  {'price': '62022.96', 'size': '0.00000021'},
  {'price': '62018', 'size': '0.0025'},
  {'price': '62013.14', 'size': '8'},
  {'price': '62010', 'size': '0.40938925'},
  {'price': '62009.29', 'size': '0.00474163'},
  {'price': '62005', 'size': '0.00240496'},
  {'price': '62004.13', 'size': '0.00009235'},
  {'price': '62003.69', 'size': '0.0241921'},
  {'price': '62003', 'size': '0.00639969'},
  {'price': '62001', 'size': '0.07769402'},
  {'price': '62000.01', 'size': '0.0015937'},
  {'price': '62000', 'size': '5.99957419'},
  {'price': '61999.99', 'size': '0.00320657'},
  {'price': '61999.27', 'size': '0.00043017'},
  {'price': '61999', 'size': '0.01008073'},
  {'price': '61993.8', 'size': '0.00006099'},
  {'price': '61992.56', 'size': '0.0012'},
  {'price': '61987.7', 'size': '0.00000022'},
  {'price': '61980', 'size': '0.17674127'},
  {'price': '61978.07', 'size': '0.00016134'},
  {'price': '61977.72', 'size': '0.05906'},
  {'price': '61976.88', 'size': '0.00000298'},
  {'price': '61974', 'size': '0.000379'},
  {'price': '61972.78', 'size': '0.00002049'},
  {'price': '61972.46', 'size': '0.07438927'},
  {'price': '61972.18', 'size': '0.00032273'},
  {'price': '61965', 'size': '0.00032276'},
  {'price': '61963.19', 'size': '0.00945005'},
  {'price': '61960', 'size': '0.62615012'},
  {'price': '61957.32', 'size': '0.00112981'},
  {'price': '61957.28', 'size': '0.00209595'},
  {'price': '61954.8', 'size': '0.00169476'},
  {'price': '61950.31', 'size': '0.00000023'},
  {'price': '61949.36', 'size': '0.00000162'},
  {'price': '61949', 'size': '0.0012'},
  {'price': '61946.23', 'size': '0.00005818'},
  {'price': '61945.43', 'size': '0.00005666'},
  {'price': '61944.6', 'size': '0.03228691'},
  {'price': '61944', 'size': '0.05461653'},
  {'price': '61943.71', 'size': '0.04837052'},
  {'price': '61939.52', 'size': '0.01398493'},
  {'price': '61936.01', 'size': '0.00160165'},
  {'price': '61935', 'size': '1'},
  {'price': '61934.69', 'size': '0.00008855'},
  {'price': '61933.81', 'size': '0.00000162'},
  {'price': '61933.46', 'size': '0.001'},
  {'price': '61933.25', 'size': '0.00001615'},
  {'price': '61932.83', 'size': '0.0063887'},
  {'price': '61931.2', 'size': '0.03763127'},
  {'price': '61928.02', 'size': '0.00003988'},
  {'price': '61920.25', 'size': '0.001'},
  {'price': '61918.27', 'size': '0.00000162'},
  {'price': '61917.08', 'size': '0.00080268'},
  {'price': '61915.3', 'size': '0.01188282'},
  {'price': '61913.25', 'size': '0.00161516'},
  {'price': '61912.6', 'size': '0.0025561'},
  {'price': '61910.69', 'size': '0.00000023'},
  {'price': '61910', 'size': '0.1602339'},
  {'price': '61906.64', 'size': '0.00022945'},
  {'price': '61906.17', 'size': '0.00104367'},
  {'price': '61905.56', 'size': '0.0012'},
  {'price': '61903.57', 'size': '0.00001089'},
  {'price': '61902.74', 'size': '0.00000162'},
  {'price': '61901.58', 'size': '0.00008077'},
  {'price': '61900.22', 'size': '0.00001615'},
  {'price': '61900', 'size': '0.10659084'},
  {'price': '61899.25', 'size': '0.00000534'},
  {'price': '61897.5', 'size': '0.0000534'},
  {'price': '61896.52', 'size': '0.00009235'},
  {'price': '61893.4', 'size': '0.0002955'},
  {'price': '61890.73', 'size': '0.00036638'},
  {'price': '61888.22', 'size': '0.01202167'},
  {'price': '61888', 'size': '0.04366881'},
  {'price': '61887.43', 'size': '0.0331'},
  {'price': '61887.22', 'size': '0.00000162'},
  {'price': '61883.22', 'size': '0.00039235'},
  {'price': '61882.61', 'size': '0.00080798'},
  {'price': '61882.01', 'size': '0.00091021'},
  {'price': '61879.97', 'size': '0.00022891'},
  {'price': '61879.65', 'size': '0.00602'},
  {'price': '61878.4', 'size': '0.0064898'},
  {'price': '61878.14', 'size': '0.00002682'},
  {'price': '61875.27', 'size': '0.00008081'},
  {'price': '61875', 'size': '0.00143503'},
  {'price': '61873.95', 'size': '0.00014697'},
  {'price': '61872.69', 'size': '0.00008081'},
  {'price': '61871.7', 'size': '0.00000162'},
  {'price': '61862', 'size': '0.0012'},
  {'price': '61856.19', 'size': '0.00000162'},
  {'price': '61850', 'size': '0.08703515'},
  {'price': '61846.72', 'size': '0.00004244'},
  {'price': '61845.39', 'size': '0.05'},
  {'price': '61840.69', 'size': '0.00000162'},
  {'price': '61840.44', 'size': '0.0020932'},
  {'price': '61840.19', 'size': '0.00036911'},
  {'price': '61837.57', 'size': '0.00319435'},
  {'price': '61837.46', 'size': '0.0000812'},
  {'price': '61834.83', 'size': '0.00082465'},
  {'price': '61828.86', 'size': '0.00246772'},
  {'price': '61827.2', 'size': '0.00050624'},
  {'price': '61825.2', 'size': '0.00000162'},
  {'price': '61818.56', 'size': '0.0012'},
  {'price': '61815.6', 'size': '0.00006099'},
  {'price': '61809.71', 'size': '0.00000162'},
  {'price': '61807.6', 'size': '0.01145304'},
  {'price': '61806.62', 'size': '0.00187649'},
  {'price': '61806.25', 'size': '0.00052369'},
  {'price': '61800', 'size': '0.22627615'},
  {'price': '61799', 'size': '0.05'},
  {'price': '61797', 'size': '0.00119908'},
  {'price': '61794.23', 'size': '0.00000162'},
  {'price': '61790.89', 'size': '0.00647344'},
  {'price': '61790.79', 'size': '0.65489705'},
  {'price': '61788.91', 'size': '0.00009235'},
  {'price': '61786.41', 'size': '0.00006397'},
  {'price': '61784.21', 'size': '0.00000488'},
  {'price': '61778.76', 'size': '0.00000162'},
  {'price': '61777', 'size': '0.00247614'},
  {'price': '61776', 'size': '0.00010247'},
  {'price': '61775', 'size': '0.0012'},
  {'price': '61772.04', 'size': '0.001'},
  {'price': '61770.29', 'size': '0.00005294'},
  {'price': '61766', 'size': '0.00799792'},
  {'price': '61763.3', 'size': '0.00000162'},
  {'price': '61762.9', 'size': '0.00150906'},
  {'price': '61762.25', 'size': '0.0047606'},
  {'price': '61760.15', 'size': '0.00326402'},
  {'price': '61758.76', 'size': '0.00037547'},
  {'price': '61755', 'size': '0.7'},
  {'price': '61754.94', 'size': '0.00016495'},
  {'price': '61754.88', 'size': '0.00043256'},
  {'price': '61753.8', 'size': '0.00005683'},
  {'price': '61753.7', 'size': '0.0004858'},
  {'price': '61750', 'size': '0.21027813'},
  {'price': '61747.85', 'size': '0.00000162'},
  {'price': '61745.76', 'size': '0.01'},
  {'price': '61743.83', 'size': '0.03774547'},
  {'price': '61742.47', 'size': '0.00319435'},
  {'price': '61738.39', 'size': '0.02415028'},
  {'price': '61733.12', 'size': '0.00396128'},
  {'price': '61733', 'size': '0.00824226'},
  {'price': '61732.4', 'size': '0.00000162'},
  {'price': '61731.56', 'size': '0.0012'},
  {'price': '61725', 'size': '0.00157343'},
  {'price': '61720.23', 'size': '0.03147266'},
  {'price': '61720', 'size': '0.02600072'},
  {'price': '61719.51', 'size': '0.00041873'},
  {'price': '61719.39', 'size': '0.0000162'},
  {'price': '61716.96', 'size': '0.00000162'},
  {'price': '61714.07', 'size': '0.00040133'},
  {'price': '61712.9', 'size': '0.00008268'},
  {'price': '61712.24', 'size': '0.01610701'},
  {'price': '61711', 'size': '0.00800505'},
  {'price': '61710.64', 'size': '0.00048289'},
  {'price': '61707.16', 'size': '0.00088614'},
  {'price': '61705.45', 'size': '0.00000299'},
  {'price': '61701.43', 'size': '0.00000163'},
  {'price': '61700', 'size': '1.2226511'},
  {'price': '61699', 'size': '0.00276827'},
  {'price': '61698.88', 'size': '0.00035533'},
  {'price': '61696.97', 'size': '0.00169796'},
  {'price': '61696.91', 'size': '0.00022959'},
  {'price': '61695.24', 'size': '0.00003146'},
  {'price': '61695', 'size': '0.0000534'},
  {'price': '61693', 'size': '0.013'},
  {'price': '61690', 'size': '0.11471855'},
  {'price': '61688', 'size': '0.0012'},
  {'price': '61685.91', 'size': '0.00000163'},
  {'price': '61684.92', 'size': '0.00015988'},
  {'price': '61683.82', 'size': '0.00486351'},
  {'price': '61681.31', 'size': '0.00009235'},
  {'price': '61676.24', 'size': '0.17713157'},
  {'price': '61675', 'size': '0.04852047'},
  {'price': '61670.4', 'size': '0.00000163'},
  {'price': '61668.87', 'size': '0.00305377'},
  {'price': '61665.16', 'size': '0.00326905'},
  {'price': '61663.52', 'size': '0.0003643'},
  {'price': '61655.44', 'size': '0.00057903'},
  {'price': '61654.9', 'size': '0.00000163'},
  {'price': '61653.98', 'size': '0.001'},
  {'price': '61647.51', 'size': '0.0001344'},
  {'price': '61647.16', 'size': '0.00207809'},
  {'price': '61644.56', 'size': '0.0012'},
  {'price': '61642.36', 'size': '0.00001622'},
  {'price': '61639.4', 'size': '0.00000163'},
  {'price': '61639.13', 'size': '0.00005847'},
  {'price': '61638.41', 'size': '0.001'},
  {'price': '61637.4', 'size': '0.00006099'},
  {'price': '61630.41', 'size': '0.00001862'},
  {'price': '61627.5', 'size': '0.00845761'},
  {'price': '61627.44', 'size': '0.00034844'},
  {'price': '61624.29', 'size': '0.00160326'},
  {'price': '61623.91', 'size': '0.00000163'},
  {'price': '61613.35', 'size': '0.00004244'},
  {'price': '61612.72', 'size': '0.00209483'},
  {'price': '61608.63', 'size': '0.000006'},
  {'price': '61608.43', 'size': '0.00000163'},
  {'price': '61604.87', 'size': '0.00000453'},
  {'price': '61603.68', 'size': '0.0003372'},
  {'price': '61601', 'size': '0.0012'},
  {'price': '61600', 'size': '0.41176008'},
  {'price': '61597', 'size': '0.00788382'},
  {'price': '61596.25', 'size': '0.00023061'},
  {'price': '61595.33', 'size': '0.00004171'},
  {'price': '61592.96', 'size': '0.00000163'},
  {'price': '61592.53', 'size': '0.00002061'},
  {'price': '61590', 'size': '2.575'},
  {'price': '61587.85', 'size': '0.00078301'},
  {'price': '61583.49', 'size': '0.00020271'},
  {'price': '61579.83', 'size': '0.0003496'},
  {'price': '61578', 'size': '0.0005422'},
  {'price': '61577.92', 'size': '0.00020088'},
  {'price': '61577.8', 'size': '0.00004797'},
  {'price': '61577.5', 'size': '0.00000163'},
  {'price': '61577', 'size': '0.00016044'},
  {'price': '61573.69', 'size': '0.00009235'},
  {'price': '61570.32', 'size': '0.00327408'},
  {'price': '61570.27', 'size': '0.00066112'},
  {'price': '61570', 'size': '0.0161767'},
  {'price': '61566.83', 'size': '0.00367747'},
  {'price': '61562.77', 'size': '0.00005701'},
  {'price': '61562.04', 'size': '0.00000163'},
  {'price': '61561.21', 'size': '0.0142137'},
  {'price': '61559.64', 'size': '0.00127651'},
  {'price': '61557.56', 'size': '0.0012'},
  {'price': '61557.02', 'size': '0.03786001'},
  {'price': '61555.61', 'size': '0.0001605'},
  {'price': '61555', 'size': '0.00393719'},
  {'price': '61554.37', 'size': '0.00034262'},
  {'price': '61552.69', 'size': '0.0063887'},
  {'price': '61552.17', 'size': '0.00017686'},
  {'price': '61550', 'size': '0.00159471'},
  {'price': '61549.26', 'size': '0.0011373'},
  {'price': '61548.6', 'size': '0.00003342'},
  {'price': '61546.59', 'size': '0.00000163'},
  {'price': '61540', 'size': '0.96373179'},
  {'price': '61537.04', 'size': '0.0003211'},
  {'price': '61533.8', 'size': '0.01925215'},
  {'price': '61532.77', 'size': '0.00037096'},
  {'price': '61531.15', 'size': '0.00000163'},
  {'price': '61528.79', 'size': '0.00443283'},
  {'price': '61528.44', 'size': '0.00020088'},
  {'price': '61528.4', 'size': '0.01625265'},
  {'price': '61525.2', 'size': '0.0008288'},
  {'price': '61525', 'size': '0.00080902'},
  {'price': '61516.18', 'size': '0.00477964'},
  {'price': '61515.72', 'size': '0.00000163'},
  {'price': '61514.38', 'size': '0.00023027'},
  {'price': '61514.21', 'size': '0.0005928'},
  {'price': '61514', 'size': '0.0012'},
  {'price': '61510.46', 'size': '0.01627366'},
  {'price': '61510.25', 'size': '0.16127718'},
  {'price': '61501', 'size': '0.01617859'},
  {'price': '61500.29', 'size': '0.00000163'},
  {'price': '61500', 'size': '4.27115094'},
  {'price': '61496.26', 'size': '0.00211166'},
  {'price': '61492.5', 'size': '0.0000534'},
  {'price': '61484.87', 'size': '0.00000163'},
  {'price': '61483.91', 'size': '0.00004017'},
  {'price': '61480.95', 'size': '0.0003'},
  {'price': '61479', 'size': '0.00020088'},
  {'price': '61475.62', 'size': '0.00327913'},
  {'price': '61471.82', 'size': '0.05677983'},
  {'price': '61470.5', 'size': '0.0012'},
  {'price': '61469.46', 'size': '0.00000163'},
  {'price': '61468.89', 'size': '0.00008855'},
  {'price': '61468.71', 'size': '0.0006998'},
  {'price': '61466.09', 'size': '0.00009235'},
  {'price': '61459.22', 'size': '0.00455586'},
  {'price': '61459.2', 'size': '0.00006099'},
  {'price': '61455.8', 'size': '0.00562'},
  {'price': '61454.06', 'size': '0.00000163'},
  {'price': '61449.79', 'size': '0.02278282'},
  {'price': '61447.74', 'size': '0.01130065'},
  {'price': '61447.1', 'size': '0.00001627'},
  {'price': '61447', 'size': '0.00032287'},
  {'price': '61444', 'size': '0.05461653'},
  {'price': '61441.72', 'size': '0.19276'},
  {'price': '61439.63', 'size': '0.02278659'},
  {'price': '61438.97', 'size': '0.00188772'},
  {'price': '61438.67', 'size': '0.00000163'},
  {'price': '61435.2', 'size': '0.000003'},
  {'price': '61427', 'size': '0.0012'},
  {'price': '61423.89', 'size': '0.04825484'},
  {'price': '61423.28', 'size': '0.00000163'},
  {'price': '61421.3', 'size': '0.00346304'},
  {'price': '61421.2', 'size': '0.00029615'},
  {'price': '61420.35', 'size': '0.0012211'},
  {'price': '61415.65', 'size': '0.00016184'},
  {'price': '61414.42', 'size': '0.00160874'},
  {'price': '61409.98', 'size': '0.00000001'},
  {'price': '61407.9', 'size': '0.00000163'},
  {'price': '61403.52', 'size': '0.00537428'},
  {'price': '61400', 'size': '2.05796384'},
  {'price': '61399', 'size': '0.05'},
  {'price': '61397.93', 'size': '0.00045239'},
  {'price': '61392.53', 'size': '0.00000163'},
  {'price': '61391.01', 'size': '0.01609356'},
  {'price': '61390', 'size': '0.01422863'},
  {'price': '61388', 'size': '0.00160943'},
  {'price': '61387.72', 'size': '0.00341063'},
  {'price': '61383.5', 'size': '0.0012'},
  {'price': '61381.91', 'size': '0.00014815'},
  {'price': '61381.07', 'size': '0.00328418'},
  {'price': '61380', 'size': '0.03080986'},
  {'price': '61377.17', 'size': '0.00000163'},
  {'price': '61377', 'size': '0.00017191'},
  {'price': '61375', 'size': '0.00080488'},
  {'price': '61374.8', 'size': '0.00778373'},
  {'price': '61372.32', 'size': '0.00005719'},
  {'price': '61370.79', 'size': '0.0379749'},
  {'price': '61370.3', 'size': '0.00048101'},
  {'price': '61367.86', 'size': '0.08589'},
  {'price': '61361.81', 'size': '0.00000163'},
  {'price': '61358.48', 'size': '0.00009235'},
  {'price': '61355.76', 'size': '0.00016298'},
  {'price': '61355.71', 'size': '0.00945005'},
  {'price': '61351.83', 'size': '0.00037423'},
  {'price': '61350', 'size': '0.02852548'},
  {'price': '61346.46', 'size': '0.00000163'},
  {'price': '61340.29', 'size': '0.001'},
  {'price': '61340.14', 'size': '0.00003289'},
  {'price': '61340', 'size': '0.0012'},
  {'price': '61337', 'size': '0.00040133'},
  {'price': '61334.64', 'size': '0.001'},
  {'price': '61333.56', 'size': '0.00005876'},
  {'price': '61333', 'size': '0.0489133'},
  {'price': '61332.4', 'size': '0.00023096'},
  {'price': '61331.76', 'size': '0.00533224'},
  {'price': '61331.03', 'size': '0.00000164'},
  {'price': '61330', 'size': '1.02763025'},
  {'price': '61329', 'size': '0.03261099'},
  {'price': '61328.37', 'size': '0.00568415'},
  {'price': '61325', 'size': '0.0024313'},
  {'price': '61319.11', 'size': '0.00179071'},
  {'price': '61315.85', 'size': '0.00020141'},
  {'price': '61315.6', 'size': '0.00000164'},
  {'price': '61313.2', 'size': '0.00016614'},
  {'price': '61309.8', 'size': '0.00325396'},
  {'price': '61302.37', 'size': '0.00001631'},
  {'price': '61301.06', 'size': '0.0030721'},
  {'price': '61301', 'size': '0.11354878'},
  {'price': '61300.18', 'size': '0.00000164'},
  {'price': '61300', 'size': '11.71863777'},
  {'price': '61298', 'size': '0.0018'},
  {'price': '61296.81', 'size': '0.00201478'},
  {'price': '61296.5', 'size': '0.0012'},
  {'price': '61295.8', 'size': '0.01584529'},
  {'price': '61291.64', 'size': '0.00004665'},
  {'price': '61291', 'size': '0.01618508'},
  {'price': '61290', 'size': '0.0000534'},
  {'price': '61289.62', 'size': '0.0017'},
  {'price': '61289.49', 'size': '0.16120218'},
  {'price': '61289', 'size': '0.00040739'},
  {'price': '61287.42', 'size': '0.00023177'},
  {'price': '61286.66', 'size': '0.00328924'},
  {'price': '61284.77', 'size': '0.00000164'},
  {'price': '61282.31', 'size': '0.00045141'},
  {'price': '61282.27', 'size': '0.0016'},
  {'price': '61281', 'size': '0.00016099'},
  {'price': '61275.82', 'size': '0.00001297'},
  {'price': '61274.5', 'size': '0.0012'},
  {'price': '61271.1', 'size': '0.00479876'},
  {'price': '61269.37', 'size': '0.00000164'},
  {'price': '61265.81', 'size': '0.02306914'},
  {'price': '61263.22', 'size': '0.11927'},
  {'price': '61263.19', 'size': '0.00014817'},
  {'price': '61263.18', 'size': '0.02448452'},
  {'price': '61263.13', 'size': '0.12365'},
  {'price': '61263', 'size': '0.00153327'},
  {'price': '61262.29', 'size': '0.00064497'},
  {'price': '61262.2', 'size': '0.00001625'},
  {'price': '61261.84', 'size': '0.00029855'},
  {'price': '61259', 'size': '0.00080641'},
  {'price': '61258.78', 'size': '0.00486787'},
  {'price': '61258', 'size': '0.00044463'},
  {'price': '61255', 'size': '0.10033546'},
  {'price': '61253.97', 'size': '0.00000164'},
  {'price': '61252', 'size': '0.28308694'},
  {'price': '61251.01', 'size': '0.0001613'},
  {'price': '61250.87', 'size': '0.00009235'},
  {'price': '61250', 'size': '0.26370758'},
  {'price': '61249.36', 'size': '0.00233471'},
  {'price': '61249.19', 'size': '0.00079282'},
  {'price': '61246', 'size': '0.01585817'},
  {'price': '61245.77', 'size': '0.00310458'},
  {'price': '61245.57', 'size': '0.01343777'},
  {'price': '61245.36', 'size': '0.00997717'},
  {'price': '61243.35', 'size': '0.00633062'},
  {'price': '61241.74', 'size': '0.00001632'},
  {'price': '61241.23', 'size': '0.00024346'},
  {'price': '61240.71', 'size': '0.00001632'},
  {'price': '61240.04', 'size': '0.00814418'},
  {'price': '61240', 'size': '0.0012381'},
  {'price': '61238.9', 'size': '0.00025022'},
  {'price': '61238.58', 'size': '0.00000164'},
  {'price': '61236.8', 'size': '0.00032464'},
  {'price': '61233.16', 'size': '0.00001633'},
  {'price': '61232', 'size': '0.00162031'},
  {'price': '61231.85', 'size': '0.00816568'},
  {'price': '61231.38', 'size': '0.00002'},
  ...],
 'type': 'snapshot',
 'collect_time': '2026-07-07T05:31:59.996317000Z',
 'cm_sequence_id': '0'}
```

Animate the live book as those messages are applied (green bids, coral asks):

```python
display(Image(animate_book(live_msgs, "live_book.gif", f"Live — {MARKET}")))
```

<figure><img src="/files/pGFBumzE3LJ9zvTYRPEG" alt=""><figcaption></figcaption></figure>

```
<IPython.core.display.Image object>
```

## Schema 2 — Historical updates + snapshots (replay the window we just streamed)

`dataset=updates` returns the **identical** message shape (snapshot + updates) for a **historical** window, and the sequence is **reproducible** — the same market and time range return the same rows on every query. Instead of a hard-coded window, we pass the **`win_start` / `win_end` we just captured from the live stream** — so we replay the very window we watched live. Following the product docs, we fetch it **in parallel** and return a **DataFrame** (`.parallel(time_increment=…).to_dataframe()`), then reconstruct with the **same `apply_message` / `animate_book`** code. `start_with_snapshot=True` prepends a snapshot so we can initialise before the first update.

> **Row count vs live-message count.** Both feeds carry the **full book** (we subscribed the websocket at `depth_limit="full_book"` to match). The websocket **bundles many level changes into each message**, while historical `granularity="raw"` emits them as **finer, individual rows** — so there are more rows than live messages, but the **total book activity (level-changes) is comparable**. Same book, same schema, same code — just different message framing.

> Historical updates settle after a short persistence lag, so the final seconds of a just-streamed window may still be landing; the leading snapshot keeps the replay well-formed regardless.

```python
df = client.get_market_orderbooks(
    markets=[MARKET],
    dataset="updates",
    start_with_snapshot=True,   # leading snapshot to initialise the book
    depth_limit="full_book",
    granularity="raw",
    format="json_stream",
    paging_from="start",
    start_time=win_start,       # the window we streamed live above
    end_time=win_end,
).parallel(time_increment=timedelta(minutes=1)).to_dataframe()

rows = df.to_dict("records")   # message dicts for reconstruction / animation
hist_changes = int(df["asks"].map(len).sum() + df["bids"].map(len).sum())
print(f"historical (raw): {len(df):,} rows, {hist_changes:,} level-changes")
print(f"live (websocket): {len(live_msgs):,} messages, {live_changes:,} level-changes")
df.head()
```

Exporting to dataframe type: 0%| | 0/1 \[00:00\<?, ?it/s]

Exporting to dataframe type: 100%|██████████| 1/1 \[00:08<00:00, 8.02s/it]

Exporting to dataframe type: 100%|██████████| 1/1 \[00:08<00:00, 8.02s/it]

```
historical (raw): 52,974 rows, 97,459 level-changes
live (websocket): 800 messages, 85,120 level-changes
```

|   | market                | time                             | coin\_metrics\_id         | asks                                               | bids                                               | type     | database\_time                      | collect\_time                    |
| - | --------------------- | -------------------------------- | ------------------------- | -------------------------------------------------- | -------------------------------------------------- | -------- | ----------------------------------- | -------------------------------- |
| 0 | coinbase-btc-usd-spot | 2026-07-07 05:30:09.985257+00:00 | AAEDAAZV\_q83wulCVEMtVVNE | \[{'price': '62893.29', 'size': '0.00141817'}, ... | \[{'price': '62893.28', 'size': '1.40248756'}, ... | snapshot | 2026-07-07 05:30:10.204346194+00:00 | 2026-07-07 05:30:09.999438+00:00 |
| 1 | coinbase-btc-usd-spot | 2026-07-07 05:30:10.013888+00:00 | AAEDAAZV\_q84MsBCVEMtVVNE | \[]                                                | \[{'price': '62871.98', 'size': '0.540278'}]       | update   | 2026-07-07 05:30:10.204398185+00:00 | 2026-07-07 05:30:10.018256+00:00 |
| 2 | coinbase-btc-usd-spot | 2026-07-07 05:30:10.016763+00:00 | AAEDAAZV\_q84PftCVEMtVVNE | \[]                                                | \[{'price': '62872.11', 'size': '0.48858106'}]     | update   | 2026-07-07 05:30:10.204419996+00:00 | 2026-07-07 05:30:10.024894+00:00 |
| 3 | coinbase-btc-usd-spot | 2026-07-07 05:30:10.016875+00:00 | AAEDAAZV\_q84PmtCVEMtVVNE | \[{'price': '62925.66', 'size': '0.94122215'}, ... | \[]                                                | update   | 2026-07-07 05:30:10.204430666+00:00 | 2026-07-07 05:30:10.024923+00:00 |
| 4 | coinbase-btc-usd-spot | 2026-07-07 05:30:10.018792+00:00 | AAEDAAZV\_q84RehCVEMtVVNE | \[{'price': '62925.67', 'size': '0'}]              | \[]                                                | update   | 2026-07-07 05:30:10.204440166+00:00 | 2026-07-07 05:30:10.024948+00:00 |

```python
display(Image(animate_book(rows[:600], "historical_book.gif", "Historical replay — same window")))
```

<figure><img src="/files/NDJJYPIKK36zuSTaoRJ1" alt=""><figcaption></figcaption></figure>

```
<IPython.core.display.Image object>
```

## Reconstruct & measure

Replaying the updates in time order gives the level-1 series (best bid/ask, spread) and depth near the mid — the raw material for TCA, event studies, and backtests. The **same** `apply_message` that drove the animations builds the metrics here:

```python
book, series = new_book(), []
for row in sorted(rows, key=lambda r: r["time"]):
    apply_message(book, row)
    bid, ask = best_bid_ask(book)
    if bid is None or ask is None:
        continue
    mid = (bid + ask) / 2
    lo, hi = mid * (1 - DEPTH_PCT), mid * (1 + DEPTH_PCT)
    series.append({
        "time": row["time"],
        "spread_bps": (ask - bid) / mid * 1e4,
        "bid_depth": sum(s for p, s in book["bids"].items() if p >= lo),
        "ask_depth": sum(s for p, s in book["asks"].items() if p <= hi),
    })

metrics = pd.DataFrame(series)
metrics["time"] = pd.to_datetime(metrics["time"])
metrics[["spread_bps", "bid_depth", "ask_depth"]].describe()
```

|       | spread\_bps  | bid\_depth   | ask\_depth   |
| ----- | ------------ | ------------ | ------------ |
| count | 52974.000000 | 52974.000000 | 52974.000000 |
| mean  | 0.037895     | 13.749850    | 14.006826    |
| std   | 0.110120     | 2.348151     | 2.138078     |
| min   | 0.001587     | 6.192858     | 7.618362     |
| 25%   | 0.001588     | 12.175648    | 12.528570    |
| 50%   | 0.001589     | 13.971209    | 14.032747    |
| 75%   | 0.001590     | 15.600170    | 15.622603    |
| max   | 1.188795     | 20.020468    | 22.517797    |

```python
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
ax1.plot(metrics["time"], metrics["spread_bps"], color=GREEN, lw=1)
ax1.set_title("Bid-ask spread (bps)"); ax1.set_ylabel("bps")
ax2.plot(metrics["time"], metrics["bid_depth"], color=GREEN, lw=1, label="bid")
ax2.plot(metrics["time"], metrics["ask_depth"], color=CORAL, lw=1, label="ask")
ax2.set_title(f"Depth within {DEPTH_PCT * 100:g}% of mid"); ax2.set_ylabel("size"); ax2.legend()
fig.autofmt_xdate()
plt.tight_layout(); plt.show()
```

<figure><img src="/files/SyZ5zIDTwYsDpbSDqXk5" alt=""><figcaption></figcaption></figure>

## Takeaways

* **Three schemas, one data model.** Historical snapshots, historical updates, and the real-time stream all share the same `[price, size]` message shape.
* **One code path, live or historical.** The same `apply_message` reconstructs the book from websocket messages and from `dataset=updates` rows — we even replayed the exact window we had just streamed live.
* Treat **every** `snapshot` as a full reset (not just the first) — a redundant-stream failover can emit an out-of-band snapshot.
* Historical `dataset=updates` is **reproducible**, so research and production share the exact same book-building logic.


# Examining Orderbook Depth

Exchange order book data is one of the most foundational data types in the crypto asset industry— arguably, even more foundational than trades data, as two orders must be matched for a trade to occur. Order book data is useful for various entities, including market makers, systematic or quantitative traders, and funds studying trade execution patterns. The Coin Metrics **Market Data Feed** offering includes various API endpoints that allow users to retrieve order book snapshots and updates across a collection of top crypto exchanges.

### Resources

This notebook demonstrates basic functionality offered by the Coin Metrics Python API Client and Market Data Feed.

Coin Metrics offers a vast assortment of data for hundreds of cryptoassets. The Python API Client allows for easy access to this data using Python without needing to create your own wrappers using `requests` and other such libraries.

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics.
* The [Coin Metrics Product Documentation](https://docs.coinmetrics.io/info) gives detailed, conceptual explanations of the data that Coin Metrics offers.
* The [API Spec](https://docs.coinmetrics.io/python-api-client/reference) contains a full list of functions.

### File Download

Download the entire notebook as either a jupyter notebook to run yourself or as a pdf from the two links below

{% file src="/files/I7jR6iqeFBmBR5JqxLJD" %}

{% file src="/files/GsscAqdCXgEnEpOX1udN" %}

### Notebook Setup

```python
import os
from os import environ
import sys
import pandas as pd
import numpy as np
import seaborn as sns
import logging
from datetime import date, datetime, timedelta
from coinmetrics.api_client import CoinMetricsClient
import json
import logging
from pytz import timezone as timezone_conv
from datetime import timezone as timezone_info
import matplotlib.ticker as mticker
from matplotlib.ticker import ScalarFormatter
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# %matplotlib inline
import ast
import plotly.express as px
from tqdm import tqdm
from plotly import graph_objects as go
```

```python
sns.set_theme()
sns.set(rc={'figure.figsize':(12,8)})
```

```python
logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S'
)
now = datetime.utcnow()
last_day_date_time = now - timedelta(hours = 24)
```

```python
# We recommend privately storing your API key in your local environment.
try:
    api_key = environ["CM_API_KEY"]
    logging.info("Using API key found in environment")
except KeyError:
    api_key = ""
    logging.info("API key not found. Using community client")

client = CoinMetricsClient(api_key)
```

```
2024-09-16 16:02:07 INFO     Using API key found in environment
```

## Order Book Depth

Coin Metrics collects and serves 3 types of order book snapshots.

* One type (*depth\_limit=100*) consists of a snapshot of the top 100 bids and top 100 asks taken once every 10 seconds for major markets.
* The second type (*depth\_limit=10pct\_mid\_price*) includes all levels where the price is within 10 percent of the midprice taken once every 10 seconds.
* The third type (*depth\_limit=full\_book*) consists of a full order book snapshot (every bid and every ask) taken once every hour for all markets that we are collecting order book data for . All of these snapshots are served through our HTTP API endpoint /timeseries/market-orderbooks.

```python
def get_order_books(market,start_time,end_time,depth_limit='full_book'):
    df = client.get_market_orderbooks(markets=market,
                                      start_time=start_time,
                                      end_time=end_time,
                                      depth_limit=depth_limit).to_dataframe()
    df.sort_values(by='time',inplace=True)
    return df
```

```python
market = 'coinbase-btc-usd-spot'
start_time = '2022-10-20'
end_time = '2022-10-26'
depth_limit = 'full_book'

df = get_order_books(market,start_time,end_time,depth_limit)
df.tail()
```

|     | market                | time                      | coin\_metrics\_id | asks                                               | bids                                               | database\_time                   |
| --- | --------------------- | ------------------------- | ----------------- | -------------------------------------------------- | -------------------------------------------------- | -------------------------------- |
| 163 | coinbase-btc-usd-spot | 2022-10-26 19:00:00+00:00 | 48876152429       | \[{'price': '20682.21', 'size': '0.001'}, {'pri... | \[{'price': '20680.45', 'size': '0.01098864'}, ... | 2022-10-26 19:02:04.331554+00:00 |
| 164 | coinbase-btc-usd-spot | 2022-10-26 20:00:00+00:00 | 48880595574       | \[{'price': '20777.57', 'size': '0.00182293'}, ... | \[{'price': '20776.49', 'size': '0.01019999'}, ... | 2022-10-26 20:01:16.705315+00:00 |
| 165 | coinbase-btc-usd-spot | 2022-10-26 21:00:00+00:00 | 48885094324       | \[{'price': '20748.12', 'size': '0.004'}, {'pri... | \[{'price': '20747.05', 'size': '0.00207858'}, ... | 2022-10-26 21:00:31.916195+00:00 |
| 166 | coinbase-btc-usd-spot | 2022-10-26 22:00:00+00:00 | 48888140842       | \[{'price': '20741.88', 'size': '0.47814895'}, ... | \[{'price': '20741.87', 'size': '0.00007231'}, ... | 2022-10-26 22:02:24.185607+00:00 |
| 167 | coinbase-btc-usd-spot | 2022-10-26 23:00:00+00:00 | 48892147093       | \[{'price': '20819.81', 'size': '0.03138949'}, ... | \[{'price': '20817.37', 'size': '0.09902'}, {'p... | 2022-10-26 23:01:42.564517+00:00 |

```python
def get_depth(df_orderbook,within=2):
    """
    Takes orderbook as returned by API and returns
    cumulative qty bid/offered at each snapshot and where the liquidity is: how far from best
    """
    dfs=[]
    for row in df_orderbook.itertuples():
        timestamp_ = row.time
        #asks
        asks = pd.DataFrame(ast.literal_eval(row.asks))
        asks["price"]=asks.price.apply(float)
        best_ask = float(asks.price.min())
        asks["size"]=asks['size'].apply(float)*-1
        asks["percent_from_best"]=((asks.price/best_ask)-1)*100
        #asks["best_ask"] = best_ask
        asks["time"] = timestamp_
        asks["side"] = "ask"
        asks["position"] = range(len(asks))
        asks["cumulative_vol"] = asks['size'].cumsum()
        asks["size_usd"] = asks["size"] * asks["price"]
        asks["cumulative_vol_usd"] = asks.size_usd.cumsum()
        #bids
        bids = pd.DataFrame(ast.literal_eval(row.bids))
        bids["price"]=bids.price.apply(float)
        best_bid = float(bids.price.max())
        bids["size"]=bids['size'].apply(float)
        bids["percent_from_best"]=abs(((bids.price/best_bid)-1)*100)
        #bids["best_bid"] = best_bid
        bids["time"] = timestamp_
        bids['side'] = 'bid'
        bids["position"] = range(len(bids))
        bids["cumulative_vol"] = bids['size'].cumsum()
        bids["size_usd"] = bids["size"] * bids["price"]
        bids["cumulative_vol_usd"] = bids.size_usd.cumsum()
        # within depth limit - default 2%
        asks = asks[asks.percent_from_best <= within].copy()
        bids = bids[bids.percent_from_best <= within].copy()
        # group into bins of 0.01% (1 bps)
        bins = np.arange(0, 2.001, 0.10)
        bids['grouping'] = pd.cut(bids.percent_from_best, bins=bins, precision=1, include_lowest=True)
        asks['grouping'] = pd.cut(asks.percent_from_best, bins=bins, precision=1, include_lowest=True)
        # collapse
        bids = bids.groupby('grouping').agg({"size":[sum],"size_usd":[sum]})#.cumsum()
        bids.index = [x/100 for x in range(1,201,10)]
        bids['side']='bid'

        asks = asks.groupby('grouping').agg({"size":[sum],"size_usd":[sum]})#.cumsum()
        asks.index = [x/100 for x in range(1,201,10)]
        asks['side']='asks'
        
        #concat together
        bids_asks = pd.concat([bids,asks])
        dfs.append(bids_asks)
    df_liquidity = pd.concat(dfs)
    df_liquidity['time'] = df_orderbook.time.iloc[0]
    df_liquidity.columns = ["size_ntv","size_usd","side","time"]
    #df_resampled_hourly = df_liquidity.groupby(['side','position']).resample('1h',on='time').mean()
    return df_liquidity
```

```python
# collapse into depth by distance from best bid/ask 
print("Getting order book data for {}...".format(market))
dfs=[]
for i in tqdm(range(len(df))):
    dfs.append(get_depth(df.iloc[i:i+1]))
    
# get rolling 3 hour window
df_aggregated = pd.concat(dfs)    
df_aggregated['pct_from_best'] = df_aggregated.index
df_aggregated.sort_values(["side","pct_from_best","time"],inplace=True)
df_aggregated['rolling_3hr_usd'] = df_aggregated.reset_index().groupby(['side','pct_from_best']).size_usd.rolling(3).mean().values
df_aggregated = df_aggregated[df_aggregated['rolling_3hr_usd'].notnull()].copy()
```

```
Getting order book data for coinbase-btc-usd-spot...


100%|█████████████████████████████████████████████████████████████████████████████| 168/168 [02:21<00:00,  1.19it/s]
```

```python
df_aggregated
```

|      | size\_ntv   | size\_usd     | side | time                      | pct\_from\_best | rolling\_3hr\_usd |
| ---- | ----------- | ------------- | ---- | ------------------------- | --------------- | ----------------- |
| 0.01 | -77.155769  | -1.470296e+06 | asks | 2022-10-20 02:00:00+00:00 | 0.01            | -1.105986e+06     |
| 0.01 | -66.058756  | -1.259527e+06 | asks | 2022-10-20 03:00:00+00:00 | 0.01            | -1.295243e+06     |
| 0.01 | -126.462072 | -2.409340e+06 | asks | 2022-10-20 04:00:00+00:00 | 0.01            | -1.713054e+06     |
| 0.01 | -230.090826 | -4.417017e+06 | asks | 2022-10-20 05:00:00+00:00 | 0.01            | -2.695295e+06     |
| 0.01 | -67.504299  | -1.292230e+06 | asks | 2022-10-20 06:00:00+00:00 | 0.01            | -2.706196e+06     |
| ...  | ...         | ...           | ...  | ...                       | ...             | ...               |
| 1.91 | 3.150618    | 6.389480e+04  | bid  | 2022-10-26 19:00:00+00:00 | 1.91            | 4.899971e+04      |
| 1.91 | 0.284205    | 5.790217e+03  | bid  | 2022-10-26 20:00:00+00:00 | 1.91            | 4.139945e+04      |
| 1.91 | 2.058624    | 4.189135e+04  | bid  | 2022-10-26 21:00:00+00:00 | 1.91            | 3.719212e+04      |
| 1.91 | 1.328615    | 2.703422e+04  | bid  | 2022-10-26 22:00:00+00:00 | 1.91            | 2.490526e+04      |
| 1.91 | 0.243678    | 4.974376e+03  | bid  | 2022-10-26 23:00:00+00:00 | 1.91            | 2.463332e+04      |

6640 rows × 6 columns

```python
def generate_depth_bar(df,title):
    fig = px.bar(df,
                 x=df.time,
                 y="rolling_3hr_usd",
                 height=550,
                 width=850,
                 color=df.index,
                 color_continuous_scale=px.colors.diverging.RdYlGn[::-1],
                 range_color=[0,2])
    fig.update_yaxes(matches=None, showticklabels=True, visible=True)
    fig.update_layout(
        title={
            'text': title,
            'font': {'family': 'arial', 'size': 18 }
        },
        font = { 'family': 'arial' },
        margin=dict(b=0),
        plot_bgcolor = 'white',
        yaxis_showgrid=True)
    fig.update_traces(marker_line_width=0)
    fig.update_yaxes(title="Total Ask Qty (-)    Total Bid Qty (+)", gridwidth=1, gridcolor='#ECECED')
    fig.update_xaxes(title="",matches=None, showticklabels=True, visible=True)
    fig.update_layout(coloraxis_colorbar=dict(
        title="% from best",
        thicknessmode="pixels", thickness=30,
        lenmode="pixels", len=180,
        yanchor="top", y=1, ticksuffix="%"
    ))
    fig.for_each_yaxis(lambda yaxis: yaxis.update(tickprefix="$"))
    return go.Figure(fig,layout=go.Layout(margin={'t': 30,'r': 10,'b': 0,'l': 30,'pad': 2,
    }))
```

```python
depth_chart = generate_depth_bar(df_aggregated,f"{market} SPOT:<br>USD Depth Within 2% of Best Bid/Ask")
```

<figure><img src="/files/cqht0JoueqAApRfBsZfg" alt=""><figcaption></figcaption></figure>


# Aggregating Orderbook Depth to Create Liquidity Metrics

![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/Demo%20Asset%20Resources/Demo%20Covers/CM-Demo-mdf-liquidity-metrics-Cover.png)

A liquid order book (the collection of outstanding bids and asks for a market) is a necessary component of a mature financial asset. The ability to quickly enter and exit large positions with a small degree of price impact, or slippage, is a desirable feature for institutional market participants. Coin Metrics has been collecting order book snapshots for major crypto assets since 2019, and recently launched new liquidity metrics as part of our **Market Data Feed** offering to further enhance institutions’ view of the crypto markets. In this demo, we explore how these metrics can be used to quantify and aggregate order book depth across some of the most actively-traded BTC markets.

### Resources

This notebook demonstrates basic functionality offered by the Coin Metrics Python API Client and Market Data Feed.

Coin Metrics offers a vast assortment of data for hundreds of cryptoassets. The Python API Client allows for easy access to this data using Python without needing to create your own wrappers using `requests` and other such libraries.

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics.
* The [Coin Metrics Product Documentation](https://docs.coinmetrics.io/info) gives detailed, conceptual explanations of the data that Coin Metrics offers.
* The [API Spec](https://docs.coinmetrics.io/python-api-client/reference) contains a full list of functions.

### File Download

Download the entire notebook as either a jupyter notebook to run yourself or as a pdf from the two links below

{% file src="/files/I7jR6iqeFBmBR5JqxLJD" %}

{% file src="/files/GsscAqdCXgEnEpOX1udN" %}

### Notebook Setup

```python
from os import environ
import sys
import pandas as pd
import seaborn as sns
import logging
from datetime import date, datetime, timedelta
from coinmetrics.api_client import CoinMetricsClient
import json
import logging
from pytz import timezone as timezone_conv
from datetime import timezone as timezone_info
import matplotlib
import matplotlib.dates as mdates
import matplotlib.ticker as ticker
from matplotlib.dates import MonthLocator, DateFormatter, YearLocator, AutoDateLocator
from matplotlib.ticker import NullFormatter
import matplotlib.pyplot as plt
import numpy as np
import plotly.express as px 
import matplotlib.ticker as mticker
import matplotlib as mpl
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import matplotlib.image as mpimg
# %matplotlib inline
```

```python
sns.set_theme()
sns.set(rc={'figure.figsize':(14,8)})
```

```python
logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S'
)
```

```python
# We recommend privately storing your API key in your local environment.
try:
    api_key = environ["CM_API_KEY"]
    logging.info("Using API key found in environment")
except KeyError:
    api_key = ""
    logging.info("API key not found. Using community client")

client = CoinMetricsClient(api_key)
```

```
2024-10-03 17:14:45 INFO     Using API key found in environment
```

```python
asset = 'btc'
```

```python
asset_markets = client.reference_data_markets(base=asset,type='spot').to_dataframe()
```

```python
asset_markets
```

|     | market                | exchange | base | quote | pair     | symbol    | type | size\_asset | margin\_asset | strike | ... | order\_amount\_min | order\_amount\_max | order\_price\_increment | order\_price\_min | order\_price\_max | order\_size\_min | order\_taker\_fee | order\_maker\_fee | margin\_trading\_enabled | experimental |
| --- | --------------------- | -------- | ---- | ----- | -------- | --------- | ---- | ----------- | ------------- | ------ | --- | ------------------ | ------------------ | ----------------------- | ----------------- | ----------------- | ---------------- | ----------------- | ----------------- | ------------------------ | ------------ |
| 0   | bibox-btc-gusd-spot   | bibox    | btc  | gusd  | btc-gusd | BTC\_GUSD | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 1   | bibox-btc-sai-spot    | bibox    | btc  | sai   | btc-sai  | BTC\_SAI  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 2   | bibox-btc-usdc-spot   | bibox    | btc  | usdc  | btc-usdc | BTC\_USDC | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 3   | bibox-btc-usdt-spot   | bibox    | btc  | usdt  | btc-usdt | BTC\_USDT | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 4   | binance-btc-aeur-spot | binance  | btc  | aeur  | btc-aeur | BTCAEUR   | spot | \<NA>       | \<NA>         | \<NA>  | ... | 0.00001            | 9000.0             | 0.01                    | 0.01              | 1000000           | 5.0              | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| ... | ...                   | ...      | ...  | ...   | ...      | ...       | ...  | ...         | ...           | ...    | ... | ...                | ...                | ...                     | ...               | ...               | ...              | ...               | ...               | ...                      | ...          |
| 393 | upbit-btc-usdt-spot   | upbit    | btc  | usdt  | btc-usdt | USDT-BTC  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 394 | zb.com-btc-pax-spot   | zb.com   | btc  | pax   | btc-pax  | btc\_pax  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 395 | zb.com-btc-qc-spot    | zb.com   | btc  | qc    | btc-qc   | btc\_qc   | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 396 | zb.com-btc-usdc-spot  | zb.com   | btc  | usdc  | btc-usdc | btc\_usdc | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 397 | zb.com-btc-usdt-spot  | zb.com   | btc  | usdt  | btc-usdt | btc\_usdt | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |

398 rows × 37 columns

```python
selected_markets = asset_markets.loc[(asset_markets['base']==asset)]
```

```python
selected_markets
```

|     | market                | exchange | base | quote | pair     | symbol    | type | size\_asset | margin\_asset | strike | ... | order\_amount\_min | order\_amount\_max | order\_price\_increment | order\_price\_min | order\_price\_max | order\_size\_min | order\_taker\_fee | order\_maker\_fee | margin\_trading\_enabled | experimental |
| --- | --------------------- | -------- | ---- | ----- | -------- | --------- | ---- | ----------- | ------------- | ------ | --- | ------------------ | ------------------ | ----------------------- | ----------------- | ----------------- | ---------------- | ----------------- | ----------------- | ------------------------ | ------------ |
| 0   | bibox-btc-gusd-spot   | bibox    | btc  | gusd  | btc-gusd | BTC\_GUSD | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 1   | bibox-btc-sai-spot    | bibox    | btc  | sai   | btc-sai  | BTC\_SAI  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 2   | bibox-btc-usdc-spot   | bibox    | btc  | usdc  | btc-usdc | BTC\_USDC | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 3   | bibox-btc-usdt-spot   | bibox    | btc  | usdt  | btc-usdt | BTC\_USDT | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 4   | binance-btc-aeur-spot | binance  | btc  | aeur  | btc-aeur | BTCAEUR   | spot | \<NA>       | \<NA>         | \<NA>  | ... | 0.00001            | 9000.0             | 0.01                    | 0.01              | 1000000           | 5.0              | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| ... | ...                   | ...      | ...  | ...   | ...      | ...       | ...  | ...         | ...           | ...    | ... | ...                | ...                | ...                     | ...               | ...               | ...              | ...               | ...               | ...                      | ...          |
| 393 | upbit-btc-usdt-spot   | upbit    | btc  | usdt  | btc-usdt | USDT-BTC  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 394 | zb.com-btc-pax-spot   | zb.com   | btc  | pax   | btc-pax  | btc\_pax  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 395 | zb.com-btc-qc-spot    | zb.com   | btc  | qc    | btc-qc   | btc\_qc   | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 396 | zb.com-btc-usdc-spot  | zb.com   | btc  | usdc  | btc-usdc | btc\_usdc | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 397 | zb.com-btc-usdt-spot  | zb.com   | btc  | usdt  | btc-usdt | btc\_usdt | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |

398 rows × 37 columns

```python
selected_quote_assets = ['usd', 'usdc', 'usdt', 'busd']
selected_quote_markets = selected_markets.loc[selected_markets['quote'].isin(selected_quote_assets)]
```

```python
selected_quote_markets
```

|     | market                       | exchange       | base | quote | pair     | symbol    | type | size\_asset | margin\_asset | strike | ... | order\_amount\_min | order\_amount\_max | order\_price\_increment | order\_price\_min | order\_price\_max | order\_size\_min | order\_taker\_fee | order\_maker\_fee | margin\_trading\_enabled | experimental |
| --- | ---------------------------- | -------------- | ---- | ----- | -------- | --------- | ---- | ----------- | ------------- | ------ | --- | ------------------ | ------------------ | ----------------------- | ----------------- | ----------------- | ---------------- | ----------------- | ----------------- | ------------------------ | ------------ |
| 2   | bibox-btc-usdc-spot          | bibox          | btc  | usdc  | btc-usdc | BTC\_USDC | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 3   | bibox-btc-usdt-spot          | bibox          | btc  | usdt  | btc-usdt | BTC\_USDT | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 10  | binance-btc-busd-spot        | binance        | btc  | busd  | btc-busd | BTCBUSD   | spot | \<NA>       | \<NA>         | \<NA>  | ... | 0.00001            | 9000.0             | 0.01                    | 0.01              | 1000000           | 10.0             | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 27  | binance-btc-usdc-spot        | binance        | btc  | usdc  | btc-usdc | BTCUSDC   | spot | \<NA>       | \<NA>         | \<NA>  | ... | 0.00001            | 9000.0             | 0.01                    | 0.01              | 1000000           | 5.0              | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 30  | binance-btc-usdt-spot        | binance        | btc  | usdt  | btc-usdt | BTCUSDT   | spot | \<NA>       | \<NA>         | \<NA>  | ... | 0.00001            | 9000.0             | 0.01                    | 0.01              | 1000000           | 5.0              | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| ... | ...                          | ...            | ...  | ...   | ...      | ...       | ...  | ...         | ...           | ...    | ... | ...                | ...                | ...                     | ...               | ...               | ...              | ...               | ...               | ...                      | ...          |
| 389 | therocktrading-btc-usdc-spot | therocktrading | btc  | usdc  | btc-usdc | BTCUSDC   | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 390 | therocktrading-btc-usdt-spot | therocktrading | btc  | usdt  | btc-usdt | BTCUSDT   | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 393 | upbit-btc-usdt-spot          | upbit          | btc  | usdt  | btc-usdt | USDT-BTC  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 396 | zb.com-btc-usdc-spot         | zb.com         | btc  | usdc  | btc-usdc | btc\_usdc | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |
| 397 | zb.com-btc-usdt-spot         | zb.com         | btc  | usdt  | btc-usdt | btc\_usdt | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | \<NA>        |

81 rows × 37 columns

```python
selected_btc_usd_market_list = selected_quote_markets['market'].to_list()
```

```python
market_metrics = client.catalog_market_metrics_v2(markets=selected_btc_usd_market_list).to_dataframe()
```

```python
market_metrics
```

|    | market                   | metrics                                                  |
| -- | ------------------------ | -------------------------------------------------------- |
| 0  | binance-btc-busd-spot    | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 1  | binance-btc-usdc-spot    | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 2  | binance-btc-usdt-spot    | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 3  | binance.us-btc-busd-spot | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 4  | binance.us-btc-usd-spot  | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 5  | binance.us-btc-usdc-spot | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 6  | binance.us-btc-usdt-spot | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 7  | bitfinex-btc-usd-spot    | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 8  | bitfinex-btc-usdt-spot   | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 9  | bitflyer-btc-usd-spot    | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 10 | bitstamp-btc-usd-spot    | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 11 | bitstamp-btc-usdc-spot   | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 12 | bitstamp-btc-usdt-spot   | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 13 | bittrex-btc-usd-spot     | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 14 | bittrex-btc-usdc-spot    | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 15 | bittrex-btc-usdt-spot    | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 16 | bullish-btc-usd-spot     | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 17 | bullish-btc-usdc-spot    | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 18 | bullish-btc-usdt-spot    | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 19 | bybit-btc-usdc-spot      | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 20 | bybit-btc-usdt-spot      | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 21 | cex.io-btc-usd-spot      | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 22 | cex.io-btc-usdt-spot     | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 23 | coinbase-btc-usd-spot    | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 24 | coinbase-btc-usdc-spot   | \[{'metric': 'liquidity\_depth\_0\_1\_percent\_ask\_v... |
| 25 | coinbase-btc-usdt-spot   | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 26 | crypto.com-btc-usd-spot  | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 27 | crypto.com-btc-usdt-spot | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 28 | erisx-btc-usd-spot       | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 29 | ftx-btc-usd-spot         | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 30 | ftx-btc-usdt-spot        | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 31 | ftx.us-btc-usd-spot      | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 32 | ftx.us-btc-usdt-spot     | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 33 | gate.io-btc-usd-spot     | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 34 | gate.io-btc-usdc-spot    | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 35 | gate.io-btc-usdt-spot    | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 36 | gemini-btc-usd-spot      | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 37 | gemini-btc-usdt-spot     | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 38 | hitbtc-btc-usdc-spot     | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 39 | hitbtc-btc-usdt-spot     | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 40 | huobi-btc-usdc-spot      | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 41 | huobi-btc-usdt-spot      | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 42 | itbit-btc-usd-spot       | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 43 | kraken-btc-usd-spot      | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 44 | kraken-btc-usdc-spot     | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 45 | kraken-btc-usdt-spot     | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 46 | kucoin-btc-usdc-spot     | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 47 | kucoin-btc-usdt-spot     | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 48 | liquid-btc-usd-spot      | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 49 | liquid-btc-usdc-spot     | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 50 | liquid-btc-usdt-spot     | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 51 | lmax-btc-usd-spot        | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 52 | mexc-btc-busd-spot       | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 53 | mexc-btc-usdc-spot       | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 54 | mexc-btc-usdt-spot       | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 55 | okex-btc-usdc-spot       | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 56 | okex-btc-usdt-spot       | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 57 | poloniex-btc-usdc-spot   | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |
| 58 | poloniex-btc-usdt-spot   | \[{'metric': 'liquidity\_bid\_ask\_spread\_percent\_...  |

```python
available_btc_markets = list(set(market_metrics['market'].to_list()))
```

```python
available_btc_markets
```

```
['bittrex-btc-usdc-spot',
 'bullish-btc-usdc-spot',
 'bitfinex-btc-usd-spot',
 'binance.us-btc-usdc-spot',
 'ftx-btc-usd-spot',
 'kucoin-btc-usdt-spot',
 'bullish-btc-usd-spot',
 'binance.us-btc-usdt-spot',
 'cex.io-btc-usdt-spot',
 'mexc-btc-busd-spot',
 'coinbase-btc-usdc-spot',
 'hitbtc-btc-usdc-spot',
 'huobi-btc-usdt-spot',
 'okex-btc-usdc-spot',
 'binance-btc-busd-spot',
 'poloniex-btc-usdt-spot',
 'huobi-btc-usdc-spot',
 'kraken-btc-usdc-spot',
 'bitstamp-btc-usdt-spot',
 'binance-btc-usdc-spot',
 'coinbase-btc-usd-spot',
 'hitbtc-btc-usdt-spot',
 'kucoin-btc-usdc-spot',
 'coinbase-btc-usdt-spot',
 'mexc-btc-usdc-spot',
 'mexc-btc-usdt-spot',
 'kraken-btc-usdt-spot',
 'kraken-btc-usd-spot',
 'itbit-btc-usd-spot',
 'bittrex-btc-usd-spot',
 'crypto.com-btc-usd-spot',
 'lmax-btc-usd-spot',
 'bullish-btc-usdt-spot',
 'bitflyer-btc-usd-spot',
 'ftx-btc-usdt-spot',
 'binance.us-btc-busd-spot',
 'gemini-btc-usd-spot',
 'liquid-btc-usd-spot',
 'erisx-btc-usd-spot',
 'ftx.us-btc-usd-spot',
 'crypto.com-btc-usdt-spot',
 'bybit-btc-usdc-spot',
 'gate.io-btc-usdt-spot',
 'liquid-btc-usdt-spot',
 'okex-btc-usdt-spot',
 'poloniex-btc-usdc-spot',
 'binance.us-btc-usd-spot',
 'ftx.us-btc-usdt-spot',
 'binance-btc-usdt-spot',
 'bittrex-btc-usdt-spot',
 'bitfinex-btc-usdt-spot',
 'gate.io-btc-usdc-spot',
 'liquid-btc-usdc-spot',
 'bybit-btc-usdt-spot',
 'gemini-btc-usdt-spot',
 'bitstamp-btc-usd-spot',
 'gate.io-btc-usd-spot',
 'cex.io-btc-usd-spot',
 'bitstamp-btc-usdc-spot']
```

```python
start = '2023-01-01'
```

```python
metrics = ['liquidity_depth_1_percent_bid_volume_usd','liquidity_depth_1_percent_ask_volume_usd']
```

```python
df = client.get_market_metrics(
    markets=available_btc_markets,
    metrics=metrics,
    start_time=start,
    end_time='2023-01-08',
    frequency='1h'
).to_dataframe()
```

```python
for metric in metrics:
    df[metric] = pd.to_numeric(df[metric], errors='coerce')
```

```python
df
```

|      | market                 | time                      | liquidity\_depth\_1\_percent\_ask\_volume\_usd | liquidity\_depth\_1\_percent\_bid\_volume\_usd |
| ---- | ---------------------- | ------------------------- | ---------------------------------------------- | ---------------------------------------------- |
| 0    | binance-btc-busd-spot  | 2023-01-01 00:00:00+00:00 | 6573748.305412                                 | 5605136.435418                                 |
| 1    | binance-btc-busd-spot  | 2023-01-01 01:00:00+00:00 | 6913394.853095                                 | 6332381.748353                                 |
| 2    | binance-btc-busd-spot  | 2023-01-01 02:00:00+00:00 | 7214380.809388                                 | 6274423.20817                                  |
| 3    | binance-btc-busd-spot  | 2023-01-01 03:00:00+00:00 | 7523209.589182                                 | 5912474.16043                                  |
| 4    | binance-btc-busd-spot  | 2023-01-01 04:00:00+00:00 | 7449126.92636                                  | 6227347.505593                                 |
| ...  | ...                    | ...                       | ...                                            | ...                                            |
| 6345 | poloniex-btc-usdt-spot | 2023-01-08 19:00:00+00:00 | \<NA>                                          | \<NA>                                          |
| 6346 | poloniex-btc-usdt-spot | 2023-01-08 20:00:00+00:00 | 170301.788236                                  | \<NA>                                          |
| 6347 | poloniex-btc-usdt-spot | 2023-01-08 21:00:00+00:00 | \<NA>                                          | \<NA>                                          |
| 6348 | poloniex-btc-usdt-spot | 2023-01-08 22:00:00+00:00 | \<NA>                                          | \<NA>                                          |
| 6349 | poloniex-btc-usdt-spot | 2023-01-08 23:00:00+00:00 | \<NA>                                          | \<NA>                                          |

6350 rows × 4 columns

```python
df['liquidity_depth_1_percent_ask_volume_usd'] = df['liquidity_depth_1_percent_ask_volume_usd'] * -1
df = df.rename(columns={"liquidity_depth_1_percent_ask_volume_usd": "ASKS", "liquidity_depth_1_percent_bid_volume_usd": "BIDS"})
```

```python
df
```

|      | market                 | time                      | ASKS            | BIDS           |
| ---- | ---------------------- | ------------------------- | --------------- | -------------- |
| 0    | binance-btc-busd-spot  | 2023-01-01 00:00:00+00:00 | -6573748.305412 | 5605136.435418 |
| 1    | binance-btc-busd-spot  | 2023-01-01 01:00:00+00:00 | -6913394.853095 | 6332381.748353 |
| 2    | binance-btc-busd-spot  | 2023-01-01 02:00:00+00:00 | -7214380.809388 | 6274423.20817  |
| 3    | binance-btc-busd-spot  | 2023-01-01 03:00:00+00:00 | -7523209.589182 | 5912474.16043  |
| 4    | binance-btc-busd-spot  | 2023-01-01 04:00:00+00:00 | -7449126.92636  | 6227347.505593 |
| ...  | ...                    | ...                       | ...             | ...            |
| 6345 | poloniex-btc-usdt-spot | 2023-01-08 19:00:00+00:00 | \<NA>           | \<NA>          |
| 6346 | poloniex-btc-usdt-spot | 2023-01-08 20:00:00+00:00 | -170301.788236  | \<NA>          |
| 6347 | poloniex-btc-usdt-spot | 2023-01-08 21:00:00+00:00 | \<NA>           | \<NA>          |
| 6348 | poloniex-btc-usdt-spot | 2023-01-08 22:00:00+00:00 | \<NA>           | \<NA>          |
| 6349 | poloniex-btc-usdt-spot | 2023-01-08 23:00:00+00:00 | \<NA>           | \<NA>          |

6350 rows × 4 columns

```python
sum_bids = df.groupby('time')['BIDS'].sum()
sum_asks = df.groupby('time')['ASKS'].sum()
```

```python
sum_asks
```

```
time
2023-01-01 00:00:00+00:00     -51711674.3155
2023-01-01 01:00:00+00:00   -45829606.793167
2023-01-01 02:00:00+00:00   -45264924.078603
2023-01-01 03:00:00+00:00   -49672194.152268
2023-01-01 04:00:00+00:00   -45360291.558192
                                  ...       
2023-01-08 19:00:00+00:00   -48736064.951989
2023-01-08 20:00:00+00:00   -42514146.912984
2023-01-08 21:00:00+00:00   -48193752.138421
2023-01-08 22:00:00+00:00   -46457643.168556
2023-01-08 23:00:00+00:00   -43813017.641122
Name: ASKS, Length: 192, dtype: Float64
```

```python
average_df = pd.DataFrame(sum_bids).resample('24H').mean()
average_df
```

|                           | BIDS            |
| ------------------------- | --------------- |
| time                      |                 |
| 2023-01-01 00:00:00+00:00 | 40685734.237508 |
| 2023-01-02 00:00:00+00:00 | 44553368.623749 |
| 2023-01-03 00:00:00+00:00 | 45840972.696663 |
| 2023-01-04 00:00:00+00:00 | 46945175.243779 |
| 2023-01-05 00:00:00+00:00 | 47693943.93807  |
| 2023-01-06 00:00:00+00:00 | 50556717.234057 |
| 2023-01-07 00:00:00+00:00 | 47568723.68365  |
| 2023-01-08 00:00:00+00:00 | 51038802.179323 |

```python
# Create the figure and axes
plt.rcParams['font.family'] = 'arial'

fig, ax = plt.subplots(figsize=(15, 9))
ax.set_facecolor('white')

# # Add logo image
# logo_path = './cm-logo.png'
# logo_img = mpimg.imread(logo_path)
# logo_offset = OffsetImage(logo_img, zoom=0.1)
# logo_annotation = AnnotationBbox(logo_offset, xy=(0.1, 1.05), xycoords='axes fraction', 
#                                  bboxprops={'facecolor': 'white', 'edgecolor': 'none'})
# ax.add_artist(logo_annotation)

# Plot the area chart for BIDS (above x-axis) in green
ax.fill_between(sum_bids.index, sum_bids.astype(float), color='green', alpha=0.5)

# Plot the area chart for ASKS (below x-axis) in red
ax.fill_between(sum_asks.index, sum_asks.astype(float), color='red', alpha=0.5)

ax.set_xlabel('')
ax.set_ylabel('ASKS                                                   BIDS\n',fontweight='bold',fontsize=16)

ax.set_title(str(asset).upper() + ' Market Depth (\u00B11%)\n', fontsize=24)
plt.suptitle('       USD & Stablecoin Pairs (USDC, USDT, BUSD)', fontsize=13.5)

formatter = mticker.FuncFormatter(lambda x, pos: f'${x/1e6:.1f}M' if x >= 0 else f'-$ {abs(x)/1e6:.1f}M')

ax.yaxis.set_major_formatter(formatter)
ax.yaxis.grid(color='gray', linestyle='dashed', alpha=0.2)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=1))

plt.xticks(rotation=0)
ax.set_xlim(df['time'].min(), df['time'].max())
plt.subplots_adjust(top=0.95, bottom=0.1)

plt.savefig('./' + str(asset).upper() + '-Market-Depth-1-Percent.png', dpi=300, bbox_inches='tight',pad_inches=0.5,facecolor='white')

plt.show()
```

<figure><img src="/files/IXAOvVf9GYzEx4lmt0Fh" alt=""><figcaption></figcaption></figure>


# Comparing Stablecoin Prices Using Different Pricing Methods

![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/Demo%20Asset%20Resources/CM-Demo-mdf-stablecoins-Cover.png)

Since Tether's launch in 2014, stablecoins have grown to become one of the most dominant sectors in the world of digital assets. Many considered them to be crypto's "killer app," providing global access to stable savings and payment rails beyond the rigid confines of the traditional banking system. In this walkthrough, we use Coin Metrics **Market Data Feed** and **CM Prices** to explore the various venues where these assets are traded, and examine various pricing methodologies that allow us to better understand how they perform in comparison to the underlying fiat currencies.

### Resources

This notebook demonstrates basic functionality offered by the Coin Metrics Python API Client and Market Data Feed.

Coin Metrics offers a vast assortment of data for hundreds of cryptoassets. The Python API Client allows for easy access to this data using Python without needing to create your own wrappers using `requests` and other such libraries.

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics.
* The [Coin Metrics Product Documentation](https://docs.coinmetrics.io/info) gives detailed, conceptual explanations of the data that Coin Metrics offers.
* The [API Spec](https://docs.coinmetrics.io/python-api-client/reference) contains a full list of functions.

### File Download

Download the entire notebook as either a jupyter notebook to run yourself or as a pdf from the two links below

{% file src="/files/2ntIOCflLBghM1INgC8f" %}

{% file src="/files/Yi2cxABzcpUn5PJ0vbLM" %}

### Notebook Setup

```python
from os import environ
import sys
import pandas as pd
import seaborn as sns
import logging
from datetime import date, datetime, timedelta
from coinmetrics.api_client import CoinMetricsClient
import json
import logging
from pytz import timezone as timezone_conv
from datetime import timezone as timezone_info
import matplotlib
import matplotlib.dates as mdates
from matplotlib.dates import MonthLocator, DateFormatter, YearLocator, AutoDateLocator
from matplotlib.ticker import NullFormatter
import matplotlib.pyplot as plt
import plotly.express as px 
import numpy as np
# %matplotlib inline
```

```python
sns.set_theme()
plt.rcParams.update({'font.size': 16, 'font.family': 'arial'})
sns.set(rc={'figure.figsize':(14,8)})
```

```python
logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S'
)
```

```python
# We recommend privately storing your API key in your local environment.
try:
    api_key = environ["CM_API_KEY"]
    logging.info("Using API key found in environment")
except KeyError:
    api_key = ""
    logging.info("API key not found. Using community client")
    
client = CoinMetricsClient(api_key)
```

```
2024-10-03 11:41:34 INFO     Using API key found in environment
```

## Get Stablecoin Markets

The catalog/markets endpoint returns a list of available markets along with time ranges of available data. Users can pass in a list of markets, exchanges, or market types (spot, futures, options). We can retrieve our stablecoin markets by fetching a list of all 'spot' markets, then filtering for the markets where the 'base' or 'quote' parameter is equivalent to our stablecoin of interest.

```python
ticker = 'usdt'

stablecoin_markets = client.reference_data_markets(
    type='spot',
    asset=ticker,
    page_size=10000
).to_dataframe()[['market','exchange','base','quote','symbol']]
```

```python
client.reference_data_markets(
    type='spot',
    asset=ticker,
    page_size=10000
).to_dataframe().info()
```

```
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 19949 entries, 0 to 19948
Data columns (total 37 columns):
 #   Column                  Non-Null Count  Dtype  
---  ------                  --------------  -----  
 0   market                  19949 non-null  string 
 1   exchange                19949 non-null  string 
 2   base                    19949 non-null  string 
 3   quote                   19949 non-null  string 
 4   pair                    19949 non-null  string 
 5   symbol                  19808 non-null  string 
 6   type                    19949 non-null  string 
 7   size_asset              0 non-null      Int64  
 8   margin_asset            0 non-null      Int64  
 9   strike                  0 non-null      Int64  
 10  option_contract_type    0 non-null      Int64  
 11  is_european             0 non-null      Int64  
 12  contract_size           0 non-null      Int64  
 13  tick_size               0 non-null      Int64  
 14  multiplier_size         0 non-null      Int64  
 15  listing                 0 non-null      Int64  
 16  expiration              0 non-null      Int64  
 17  settlement_price        0 non-null      Int64  
 18  pool_config_id          0 non-null      Int64  
 19  contract_address        0 non-null      Int64  
 20  fee                     0 non-null      Int64  
 21  price_includes_fee      0 non-null      Int64  
 22  variable_fee            0 non-null      Int64  
 23  base_address            0 non-null      Int64  
 24  quote_address           0 non-null      Int64  
 25  status                  11787 non-null  string 
 26  order_amount_increment  11436 non-null  Float64
 27  order_amount_min        6300 non-null   Float64
 28  order_amount_max        2567 non-null   Float64
 29  order_price_increment   12022 non-null  Float64
 30  order_price_min         2012 non-null   Float64
 31  order_price_max         759 non-null    Float64
 32  order_size_min          5835 non-null   Float64
 33  order_taker_fee         8332 non-null   Float64
 34  order_maker_fee         8332 non-null   Float64
 35  margin_trading_enabled  6926 non-null   boolean
 36  experimental            0 non-null      Int64  
dtypes: Float64(9), Int64(19), boolean(1), string(8)
memory usage: 6.1 MB
```

|       | market                | exchange | base  | quote | symbol      |
| ----- | --------------------- | -------- | ----- | ----- | ----------- |
| 0     | bibox-1inch-usdt-spot | bibox    | 1inch | usdt  | 1INCH\_USDT |
| 1     | bibox-aaa-usdt-spot   | bibox    | aaa   | usdt  | AAA\_USDT   |
| 2     | bibox-aave-usdt-spot  | bibox    | aave  | usdt  | AAVE\_USDT  |
| 3     | bibox-ac-usdt-spot    | bibox    | ac    | usdt  | AC\_USDT    |
| 4     | bibox-acmd-usdt-spot  | bibox    | acmd  | usdt  | ACMD\_USDT  |
| ...   | ...                   | ...      | ...   | ...   | ...         |
| 19944 | zb.com-yfii-usdt-spot | zb.com   | yfii  | usdt  | yfii\_usdt  |
| 19945 | zb.com-ygg-usdt-spot  | zb.com   | ygg   | usdt  | ygg\_usdt   |
| 19946 | zb.com-zb-usdt-spot   | zb.com   | zb    | usdt  | zb\_usdt    |
| 19947 | zb.com-zkn-usdt-spot  | zb.com   | zkn   | usdt  | zkn\_usdt   |
| 19948 | zb.com-zrx-usdt-spot  | zb.com   | zrx   | usdt  | zrx\_usdt   |

19949 rows × 5 columns

```python
markets_by_exchange = pd.DataFrame(stablecoin_markets['exchange'].value_counts()).reset_index()
markets_by_exchange['count'] = markets_by_exchange['count'].astype(int)
```

```python
markets_by_exchange.info()
```

```
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 30 entries, 0 to 29
Data columns (total 2 columns):
 #   Column    Non-Null Count  Dtype 
---  ------    --------------  ----- 
 0   exchange  30 non-null     string
 1   count     30 non-null     int64 
dtypes: int64(1), string(1)
memory usage: 608.0 bytes
```

```python
fig, ax1 = plt.subplots()
ax1.bar(x=markets_by_exchange['exchange'], height=markets_by_exchange['count'], width=0.8)
plt.setp(ax1.get_xticklabels(), rotation=45);
ax1.set_facecolor("white")
plt.grid(color = 'black', linestyle = '--', linewidth = 0.2)
plt.title('\nCount of '+ str(ticker).upper() + ' Markets \nby Exchange\n',fontdict={'fontsize':20,'font':'arial'});
```

<figure><img src="/files/v2hKfUCaZUsaUMtNtmg7" alt=""><figcaption></figcaption></figure>

## Get stablecoin prices

#### Single market trades

Trades are one of the foundational data types we collect from exchanges. From raw trades data, we can construct additional aggregated metrics.

```python
market = 'coinbase-usdt-usd-spot'
coinbase_trades = client.get_market_trades(
    markets = market,
    limit_per_market = 100,
    paging_from = 'end'
).to_dataframe()
coinbase_trades
```

|     | market                 | time                             | coin\_metrics\_id | amount  | price   | database\_time                   | side |
| --- | ---------------------- | -------------------------------- | ----------------- | ------- | ------- | -------------------------------- | ---- |
| 0   | coinbase-usdt-usd-spot | 2024-10-03 16:37:50.356121+00:00 | 109485916         | 3000.0  | 0.99985 | 2024-10-03 16:37:51.099860+00:00 | buy  |
| 1   | coinbase-usdt-usd-spot | 2024-10-03 16:37:52.857847+00:00 | 109485917         | 3000.0  | 0.99985 | 2024-10-03 16:37:53.278230+00:00 | buy  |
| 2   | coinbase-usdt-usd-spot | 2024-10-03 16:37:54.748770+00:00 | 109485918         | 1555.08 | 0.99985 | 2024-10-03 16:37:55.566500+00:00 | buy  |
| 3   | coinbase-usdt-usd-spot | 2024-10-03 16:37:55.358549+00:00 | 109485919         | 3000.0  | 0.99985 | 2024-10-03 16:37:55.652974+00:00 | buy  |
| 4   | coinbase-usdt-usd-spot | 2024-10-03 16:37:59.787414+00:00 | 109485920         | 2069.41 | 0.99985 | 2024-10-03 16:38:00.856793+00:00 | buy  |
| ... | ...                    | ...                              | ...               | ...     | ...     | ...                              | ...  |
| 95  | coinbase-usdt-usd-spot | 2024-10-03 16:41:24.050200+00:00 | 109486011         | 19.56   | 0.99985 | 2024-10-03 16:41:24.700790+00:00 | buy  |
| 96  | coinbase-usdt-usd-spot | 2024-10-03 16:41:24.746299+00:00 | 109486012         | 1170.67 | 0.99985 | 2024-10-03 16:41:25.211754+00:00 | buy  |
| 97  | coinbase-usdt-usd-spot | 2024-10-03 16:41:26.109516+00:00 | 109486013         | 7.18    | 0.99985 | 2024-10-03 16:41:26.660344+00:00 | buy  |
| 98  | coinbase-usdt-usd-spot | 2024-10-03 16:41:26.855646+00:00 | 109486014         | 3000.0  | 0.99984 | 2024-10-03 16:41:27.752326+00:00 | sell |
| 99  | coinbase-usdt-usd-spot | 2024-10-03 16:41:34.937992+00:00 | 109486015         | 23.49   | 0.99984 | 2024-10-03 16:41:35.141694+00:00 | sell |

100 rows × 7 columns

#### Single market candles

From raw trades data, we construct OHLC candles for each market. Candles include the following data types:

* **price\_open:** The opening price of the candle.
* **price\_high:** The high price of the candle.
* **price\_low:** The low price of the candle.
* **price\_close:** The close price of the candle.
* **vwap:** The volume-weighted average price of the candle.
* **volume:** The volume of the candle in units of the base asset.
* **candle\_usd\_volume:** The volume of the candle in units of U.S. dollars.
* **candle\_trades\_count:** The number of trades in the candle interval.

```python
market = 'coinbase-usdt-usd-spot'
coinbase_candles = client.get_market_candles(
    markets = market,
    frequency = '1d'
).to_dataframe()
```

```python
coinbase_candles
```

|      | market                 | time                      | price\_open | price\_close | price\_high | price\_low | vwap     | volume       | candle\_usd\_volume | candle\_trades\_count |
| ---- | ---------------------- | ------------------------- | ----------- | ------------ | ----------- | ---------- | -------- | ------------ | ------------------- | --------------------- |
| 0    | coinbase-usdt-usd-spot | 2021-05-04 00:00:00+00:00 | 1.002       | 1.0006       | 1.003       | 0.999      | 1.000696 | 24564061.73  | 24581147.409593     | 30527                 |
| 1    | coinbase-usdt-usd-spot | 2021-05-05 00:00:00+00:00 | 1.0006      | 1.0013       | 1.002       | 0.9997     | 1.000816 | 40170830.16  | 40203590.541009     | 43688                 |
| 2    | coinbase-usdt-usd-spot | 2021-05-06 00:00:00+00:00 | 1.0013      | 1.0009       | 1.002       | 1.0004     | 1.001023 | 51129166.79  | 51181449.603235     | 51177                 |
| 3    | coinbase-usdt-usd-spot | 2021-05-07 00:00:00+00:00 | 1.0008      | 1.0011       | 1.0018      | 1.0        | 1.001045 | 44247619.59  | 44293836.840656     | 48729                 |
| 4    | coinbase-usdt-usd-spot | 2021-05-08 00:00:00+00:00 | 1.001       | 1.0016       | 1.0022      | 1.0009     | 1.00147  | 26972741.16  | 27012382.918589     | 50140                 |
| ...  | ...                    | ...                       | ...         | ...          | ...         | ...        | ...      | ...          | ...                 | ...                   |
| 1243 | coinbase-usdt-usd-spot | 2024-09-28 00:00:00+00:00 | 1.00012     | 1.00011      | 1.00021     | 1.0        | 1.000127 | 69876132.62  | 69884972.64875      | 33216                 |
| 1244 | coinbase-usdt-usd-spot | 2024-09-29 00:00:00+00:00 | 1.00011     | 1.00013      | 1.00021     | 1.00001    | 1.000107 | 85000340.62  | 85009396.570012     | 34237                 |
| 1245 | coinbase-usdt-usd-spot | 2024-09-30 00:00:00+00:00 | 1.00014     | 0.99971      | 1.00014     | 0.99958    | 0.999863 | 250585092.98 | 250550678.3691      | 81461                 |
| 1246 | coinbase-usdt-usd-spot | 2024-10-01 00:00:00+00:00 | 0.9997      | 0.99975      | 0.99991     | 0.99923    | 0.999677 | 460273457.69 | 460124819.483157    | 169777                |
| 1247 | coinbase-usdt-usd-spot | 2024-10-02 00:00:00+00:00 | 0.99975     | 0.99977      | 1.0         | 0.99958    | 0.999796 | 345349657.46 | 345279261.97222     | 144072                |

1248 rows × 10 columns

```python
ax1 = plt.subplot()
coinbase_price = sns.lineplot(data=coinbase_candles,y=coinbase_candles.vwap,x=coinbase_candles.time)
plt.setp(ax1.get_xticklabels(), rotation=45);
ax1.set_facecolor("white")
plt.grid(color = 'black', linestyle = '--', linewidth = 0.2)
coinbase_price.set_xlabel("", fontsize = 15)
coinbase_price.set_ylabel("Price", fontsize = 15)
coinbase_price.set_title('\nCoinbase USDT-USD\n', fontsize = 18, font = 'arial');
```

<figure><img src="/files/nZXWX9IRQncM3J78Sigc" alt=""><figcaption></figcaption></figure>

#### Reference Rate Candles

We offer reference rates quoted in USD, Euro, Bitcoin, and Ethereum. We now support these quote currencies for our entire reference rates coverage universe of over 500 assets and for all of our frequencies, including 1s, 1m, 1h, 1d-ny-close and 1d.

Current composition of markets for USDT-USD Reference Rate pair (as of May 17, 2023):

* "coinbase-usdt-usd-spot",
* "coinbase-eth-usdt-spot",
* "coinbase-btc-usdt-spot",
* "kraken-usdt-usd-spot",
* "binance-btc-usdt-spot",
* "binance-eth-usdt-spot",
* "crypto.com-usdt-usd-spot"

```python
pairs = client.catalog_asset_pair_candles().to_dataframe()
```

```
2024-10-03 11:41:41 WARNING  /catalog/ endpoints will be deprecated in the future. Consider using /catalog-v2/ and /reference-data/ endpoints instead.
```

```python
pairs.loc[pairs['pair']=='usdt-usd']
```

|      | pair     | frequency | min\_time                 | max\_time                 |
| ---- | -------- | --------- | ------------------------- | ------------------------- |
| 8640 | usdt-usd | 1m        | 2013-12-28 00:00:00+00:00 | 2024-10-03 16:39:00+00:00 |
| 8641 | usdt-usd | 5m        | 2013-12-28 00:00:00+00:00 | 2024-10-03 16:35:00+00:00 |
| 8642 | usdt-usd | 10m       | 2013-12-28 00:00:00+00:00 | 2024-10-03 16:30:00+00:00 |
| 8643 | usdt-usd | 15m       | 2013-12-28 00:00:00+00:00 | 2024-10-03 16:15:00+00:00 |
| 8644 | usdt-usd | 30m       | 2013-12-28 00:00:00+00:00 | 2024-10-03 16:00:00+00:00 |
| 8645 | usdt-usd | 1h        | 2013-12-28 00:00:00+00:00 | 2024-10-03 15:00:00+00:00 |
| 8646 | usdt-usd | 4h        | 2013-12-28 00:00:00+00:00 | 2024-10-03 12:00:00+00:00 |
| 8647 | usdt-usd | 1d        | 2013-12-28 00:00:00+00:00 | 2024-10-02 00:00:00+00:00 |

```python
pair_candles = client.get_pair_candles(
    pairs='usdt-usd',
    start_time =  datetime.now() - timedelta(weeks=4),
    frequency='1d'
).to_dataframe()
```

```python
pair_candles.tail()
```

|    | pair     | time                      | price\_open | price\_close | price\_high | price\_low |
| -- | -------- | ------------------------- | ----------- | ------------ | ----------- | ---------- |
| 22 | usdt-usd | 2024-09-28 00:00:00+00:00 | 1.00016     | 1.000153     | 1.00053     | 0.999861   |
| 23 | usdt-usd | 2024-09-29 00:00:00+00:00 | 1.000116    | 1.00013      | 1.000492    | 0.999772   |
| 24 | usdt-usd | 2024-09-30 00:00:00+00:00 | 1.00013     | 0.999649     | 1.00053     | 0.99937    |
| 25 | usdt-usd | 2024-10-01 00:00:00+00:00 | 0.999639    | 0.9998       | 1.000897    | 0.998931   |
| 26 | usdt-usd | 2024-10-02 00:00:00+00:00 | 0.9998      | 0.99982      | 1.000601    | 0.999219   |

```python
prices = pair_candles[['price_open','price_close','price_high','price_low','time']].set_index('time')
```

```python
fig, ax = plt.subplots()
ax.ticklabel_format(useOffset=False)
width = 0.8
width2 = .1
ax.set_facecolor("white")
plt.grid(color = 'black', linestyle = '--', linewidth = 0.2)
plt.title('\n'+ str(ticker).upper() + ' Reference Rate Candles (1D)',fontdict={'fontsize':20,'font':'arial'});

up = prices[prices.price_close>=prices.price_open]
down = prices[prices.price_close<prices.price_open]
col1 = 'green'
col2 = 'red'

#plot prices
ax.bar(up.index,up.price_close-up.price_open,width,bottom=up.price_open,color=col1)
ax.bar(up.index,up.price_high-up.price_close,width2,bottom=up.price_close,color=col1)
ax.bar(up.index,up.price_low-up.price_open,width2,bottom=up.price_open,color=col1)
ax.bar(down.index,down.price_close-down.price_open,width,bottom=down.price_open,color=col2)
ax.bar(down.index,down.price_high-down.price_open,width2,bottom=down.price_open,color=col2)
ax.bar(down.index,down.price_low-down.price_close,width2,bottom=down.price_close,color=col2)

#rotate x-axis tick labels
plt.xticks(rotation=45, ha='right')
ax.xaxis.set_minor_locator(MonthLocator(bymonthday=30))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))

plt.show()
```

<figure><img src="/files/Y7A9ZtS5WdE2nXY9DtC8" alt=""><figcaption></figcaption></figure>

#### Reference Rate

```python
rr_catalog = client.catalog_asset_metrics_v2(assets='usdt', metrics='ReferenceRateUSD').to_dataframe()
```

```python
rr_catalog
```

|   | asset | metrics                                            |
| - | ----- | -------------------------------------------------- |
| 0 | usdt  | \[{'metric': 'ReferenceRateUSD', 'frequencies':... |

```python
asset_rr = client.get_asset_metrics(
    assets = 'usdt',
    metrics = 'ReferenceRateUSD',
    frequency = '1m',
    start_time =  datetime.now() - timedelta(hours=24)
).to_dataframe()
```

```python
asset_rr
```

|      | asset | time                      | ReferenceRateUSD |
| ---- | ----- | ------------------------- | ---------------- |
| 0    | usdt  | 2024-10-02 11:42:00+00:00 | 0.99984          |
| 1    | usdt  | 2024-10-02 11:43:00+00:00 | 0.99979          |
| 2    | usdt  | 2024-10-02 11:44:00+00:00 | 0.99983          |
| 3    | usdt  | 2024-10-02 11:45:00+00:00 | 0.999845         |
| 4    | usdt  | 2024-10-02 11:46:00+00:00 | 0.99982          |
| ...  | ...   | ...                       | ...              |
| 1735 | usdt  | 2024-10-03 16:37:00+00:00 | 0.999861         |
| 1736 | usdt  | 2024-10-03 16:38:00+00:00 | 0.99985          |
| 1737 | usdt  | 2024-10-03 16:39:00+00:00 | 0.99985          |
| 1738 | usdt  | 2024-10-03 16:40:00+00:00 | 0.99984          |
| 1739 | usdt  | 2024-10-03 16:41:00+00:00 | 0.999835         |

1740 rows × 3 columns

```python
ax1 = plt.subplot()
ax1.ticklabel_format(useOffset=False)
asset_rr_chart = sns.lineplot(data=asset_rr,y=asset_rr.ReferenceRateUSD,x=asset_rr.time)
plt.setp(ax1.get_xticklabels());
ax1.set_facecolor("white")
plt.grid(color = 'black', linestyle = '--', linewidth = 0.2)
asset_rr_chart.set_xlabel("", fontsize = 15)
asset_rr_chart.set_ylabel("Price", fontsize = 15)
asset_rr_chart.set_title('\nUSDT Reference Rate (1 min)\n', fontsize = 18, font = 'arial');
```

<figure><img src="/files/F7zdZui3p2xIqzTplazK" alt=""><figcaption></figcaption></figure>

### Principal Market Price

The Principal Market Prices identify a principal market for each asset and utilize the most recent price from this market. Common use cases are for fair value measurement, preparing financial statements, and calculating closing prices for indexes or financial benchmarks.

```python
asset_pmp = client.get_asset_metrics(
    assets = 'usdt',
    metrics = ['principal_market_price_usd','principal_market_usd'],
    frequency = '1m',
    start_time =  datetime.now() - timedelta(hours=24)
).to_dataframe()
```

```python
asset_pmp
```

|      | asset | time                      | principal\_market\_price\_usd | principal\_market\_usd   |
| ---- | ----- | ------------------------- | ----------------------------- | ------------------------ |
| 0    | usdt  | 2024-10-02 11:42:00+00:00 | 0.999835                      | binance-btc-usdt-spot    |
| 1    | usdt  | 2024-10-02 11:43:00+00:00 | 0.999921                      | binance-btc-usdt-spot    |
| 2    | usdt  | 2024-10-02 11:44:00+00:00 | 0.999892                      | binance-btc-usdt-spot    |
| 3    | usdt  | 2024-10-02 11:45:00+00:00 | 0.999845                      | binance-btc-usdt-spot    |
| 4    | usdt  | 2024-10-02 11:46:00+00:00 | 0.999763                      | binance-btc-usdt-spot    |
| ...  | ...   | ...                       | ...                           | ...                      |
| 1735 | usdt  | 2024-10-03 16:37:00+00:00 | 0.999861                      | crypto.com-btc-usdt-spot |
| 1736 | usdt  | 2024-10-03 16:38:00+00:00 | 0.999839                      | crypto.com-btc-usdt-spot |
| 1737 | usdt  | 2024-10-03 16:39:00+00:00 | 0.999777                      | crypto.com-btc-usdt-spot |
| 1738 | usdt  | 2024-10-03 16:40:00+00:00 | 0.999679                      | crypto.com-btc-usdt-spot |
| 1739 | usdt  | 2024-10-03 16:41:00+00:00 | 0.999798                      | crypto.com-btc-usdt-spot |

1740 rows × 4 columns

```python
market_list = list(set(asset_pmp['principal_market_usd'].to_list()))
market_list
```

```
['crypto.com-eth-usdt-spot',
 'binance-eth-usdt-spot',
 'binance-btc-usdt-spot',
 'crypto.com-btc-usdt-spot']
```

```python
unique_markets = asset_pmp['principal_market_usd'].unique()
colors = plt.cm.jet(np.linspace(0,1,len(unique_markets)))
color_map = dict(zip(unique_markets, colors))

asset_pmp = asset_pmp.sort_values('time')
fig, ax = plt.subplots()
ax.set_facecolor("white")
ax.grid(color='lightgray', linestyle='--')

for i in range(1, len(asset_pmp)):
    ax.plot(asset_pmp['time'].iloc[i-1:i+1], 
            asset_pmp['principal_market_price_usd'].iloc[i-1:i+1], 
            color=color_map[asset_pmp['principal_market_usd'].iloc[i]], 
            label=asset_pmp['principal_market_usd'].iloc[i])

handles, labels = plt.gca().get_legend_handles_labels()
by_label = dict(zip(labels, handles))
import matplotlib.ticker as ticker

ax.legend(by_label.values(), by_label.keys(), loc='upper right', frameon=False, bbox_to_anchor=(1, 1.135))
ax.get_yaxis().set_major_formatter(ticker.FuncFormatter(lambda x, p: format(float(x), '.4f')))

plt.title('USDT Principal Market Price\n', fontsize=22)
plt.xlabel('')
plt.ylabel('Principal Market Price (USD)\n',fontsize=16)
plt.show()
```

<figure><img src="/files/ntxiMKu2GkkaR5NMY9NQ" alt=""><figcaption></figcaption></figure>


# Comparing Volumes of Exchanges and Assets

![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/Demo%20Asset%20Resources/CM-Demo-mdf-exchange-volume-Cover.png)

Though decentralized finance has garnered significant attention in recent years, centralized exchanges remain a crucial cornerstone of the crypto asset industry. These trading venues serve as some of the deepest pools of liquidity for the top crypto assets, and facilitate the onboarding and offboarding of millions of users by sitting at the intersection of digital assets and fiat currencies. Coin Metrics collects a wide variety of data from a universe of 39+ top crypto exchanges, allowing our users to easily assess exchange dominance, asset trading volumes, and even the composition of trading patterns in specific markets.

### Resources

This notebook demonstrates basic functionality offered by the Coin Metrics Python API Client and Market Data Feed.

Coin Metrics offers a vast assortment of data for hundreds of cryptoassets. The Python API Client allows for easy access to this data using Python without needing to create your own wrappers using `requests` and other such libraries.

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics.
* The [Coin Metrics Product Documentation](https://docs.coinmetrics.io/info) gives detailed, conceptual explanations of the data that Coin Metrics offers.
* The [API Spec](https://docs.coinmetrics.io/python-api-client/reference) contains a full list of functions.

### File Download

Download the entire notebook as either a jupyter notebook to run yourself or as a pdf from the two links below

{% file src="/files/1h4Z8tMhTZqzwgTNP6ya" %}

{% file src="/files/pLri4CdEoxdPQZkuUpX7" %}

### Notebook Setup

```python
from os import environ
import sys
import pandas as pd
import numpy as np
import logging
from datetime import date, datetime, timedelta
from coinmetrics.api_client import CoinMetricsClient
import json
import logging
import matplotlib.pyplot as plt
# import plotly.express as px
# import seaborn as sns
# %matplotlib inline
```

```python
logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S'
)
```

```python
# We recommend privately storing your API key in your local environment.
try:
    api_key = environ["CM_API_KEY"]
    logging.info("Using API key found in environment")
except KeyError:
    api_key = ""
    logging.info("API key not found. Using community client")
client = CoinMetricsClient(api_key)
```

```
2024-10-07 12:48:33 INFO     Using API key found in environment
```

### Daily Exchange Volumes

Coin Metrics creates aggregated metrics to allow users to easily compare the total trading volume of dominant centralized exchanges. By leveraging the *timeseries/exchange-metrics* endpoint, we can retrieve the daily reported spot trading volume for a single trading venue or a list of exchanges.

```python
end = pd.to_datetime(datetime.now())
start = end - timedelta(days=28)
```

```python
exchange_list = [
    e['exchange'] for e in client.get_snapshots_of_asset_metric_constituents(
        'volume_trusted_spot_usd_1d', at_time=end
    ).to_list()
]
```

```python
volumes = client.get_exchange_metrics(
    exchanges=exchange_list,
    metrics='volume_reported_spot_usd_1d',
    frequency='1d',
    start_time=start,
    end_time=end
).to_dataframe()
```

```python
top_volumes = volumes.groupby('exchange')['volume_reported_spot_usd_1d'].sum().sort_values(ascending=False)
volumes['exchange'] = np.where(volumes['exchange'].isin(top_volumes[:8].index), volumes['exchange'], 'other')
```

```python
volumes = volumes.groupby(['exchange', 'time'])[['volume_reported_spot_usd_1d']].sum().reset_index()
exchange_list_truncated = list(volumes.exchange.unique())

```

```python
pivot_volumes = volumes.pivot(
    index="time",
    columns="exchange",
    values="volume_reported_spot_usd_1d"
)
```

```python
pivot_volumes.head()
```

| exchange                  | binance            | bullish          | bybit            | coinbase         | crypto.com       | gate.io          | huobi            | okex             | other             |
| ------------------------- | ------------------ | ---------------- | ---------------- | ---------------- | ---------------- | ---------------- | ---------------- | ---------------- | ----------------- |
| time                      |                    |                  |                  |                  |                  |                  |                  |                  |                   |
| 2024-09-10 00:00:00+00:00 | 9714347717.47266   | 1264837837.1639  | 3667152874.20169 | 1323434212.37803 | 4694543620.14163 | 845127903.462162 | 1605960239.92127 | 1293157356.51002 | 1340992725.680607 |
| 2024-09-11 00:00:00+00:00 | 12274439317.785299 | 1102465276.62474 | 4522846470.92285 | 1706654989.73028 | 7265287964.56301 | 1116958520.42675 | 1758439622.21422 | 1589552806.98192 | 1766919607.712266 |
| 2024-09-12 00:00:00+00:00 | 11296654011.844999 | 1071014247.32579 | 4144560926.66379 | 1781063003.281   | 4845335792.93472 | 1035902360.91803 | 1640974256.92128 | 1418484926.0031  | 1631462282.025268 |
| 2024-09-13 00:00:00+00:00 | 11925481195.452999 | 1073344439.24967 | 4164462938.08954 | 1832416834.75893 | 4559652705.02926 | 1060397918.39275 | 1602703737.9729  | 1544920512.39772 | 1847874572.934688 |
| 2024-09-14 00:00:00+00:00 | 6374474955.75626   | 391985441.722983 | 2230639306.76154 | 1137971743.1438  | 1992728998.68231 | 587007576.028109 | 1267693924.07889 | 961073483.60885  | 870317615.504417  |

```python
pivot_volumes[exchange_list_truncated]
```

| exchange                  | binance            | bullish          | bybit            | coinbase         | crypto.com        | gate.io          | huobi            | okex             | other             |
| ------------------------- | ------------------ | ---------------- | ---------------- | ---------------- | ----------------- | ---------------- | ---------------- | ---------------- | ----------------- |
| time                      |                    |                  |                  |                  |                   |                  |                  |                  |                   |
| 2024-09-10 00:00:00+00:00 | 9714347717.47266   | 1264837837.1639  | 3667152874.20169 | 1323434212.37803 | 4694543620.14163  | 845127903.462162 | 1605960239.92127 | 1293157356.51002 | 1340992725.680607 |
| 2024-09-11 00:00:00+00:00 | 12274439317.785299 | 1102465276.62474 | 4522846470.92285 | 1706654989.73028 | 7265287964.56301  | 1116958520.42675 | 1758439622.21422 | 1589552806.98192 | 1766919607.712266 |
| 2024-09-12 00:00:00+00:00 | 11296654011.844999 | 1071014247.32579 | 4144560926.66379 | 1781063003.281   | 4845335792.93472  | 1035902360.91803 | 1640974256.92128 | 1418484926.0031  | 1631462282.025268 |
| 2024-09-13 00:00:00+00:00 | 11925481195.452999 | 1073344439.24967 | 4164462938.08954 | 1832416834.75893 | 4559652705.02926  | 1060397918.39275 | 1602703737.9729  | 1544920512.39772 | 1847874572.934688 |
| 2024-09-14 00:00:00+00:00 | 6374474955.75626   | 391985441.722983 | 2230639306.76154 | 1137971743.1438  | 1992728998.68231  | 587007576.028109 | 1267693924.07889 | 961073483.60885  | 870317615.504417  |
| 2024-09-15 00:00:00+00:00 | 7361704730.28157   | 562957320.711511 | 2590884166.76392 | 832798774.766878 | 2931984212.55974  | 760804668.552838 | 1124162599.40243 | 997351542.148314 | 1032771425.499747 |
| 2024-09-16 00:00:00+00:00 | 12134299152.8419   | 1060106347.58518 | 4165725283.318   | 1361649870.77583 | 4722670462.41982  | 1191365703.76154 | 1583872653.47973 | 1593737943.29678 | 1535830455.197682 |
| 2024-09-17 00:00:00+00:00 | 12784370854.8181   | 1370902890.66798 | 4599028084.1107  | 1783827256.9648  | 4323879290.27791  | 1164978755.28512 | 1572931912.75403 | 1735321786.52275 | 1939514486.618056 |
| 2024-09-18 00:00:00+00:00 | 13949094048.295601 | 1509743657.16933 | 5191983189.97371 | 1812085945.13132 | 6524939071.87054  | 1588197115.85748 | 1677643847.70291 | 2025256403.67754 | 2131259660.134958 |
| 2024-09-19 00:00:00+00:00 | 15765392190.692499 | 1319652147.96947 | 5525980769.22584 | 2541879532.52425 | 5235187763.93785  | 1887336656.8817  | 1975000649.30877 | 2390932500.79671 | 2569561724.497508 |
| 2024-09-20 00:00:00+00:00 | 15637079381.6693   | 1265080412.99704 | 4627547221.99959 | 1976169614.44787 | 5064003012.65921  | 1629840500.88359 | 1700075845.88566 | 2139950015.81174 | 2114986008.292456 |
| 2024-09-21 00:00:00+00:00 | 7239200803.06984   | 459895539.058303 | 2482619303.48854 | 742642406.840901 | 2411519153.63723  | 833998109.245123 | 1087714374.93748 | 952109526.988626 | 991526560.843603  |
| 2024-09-22 00:00:00+00:00 | 9068630508.16427   | 802099932.54548  | 3151837904.3863  | 963747563.989523 | 3502445418.96481  | 1052501821.18361 | 1171972957.83752 | 1286837506.19408 | 1177308035.41588  |
| 2024-09-23 00:00:00+00:00 | 14119038812.017599 | 1329762723.44272 | 4669434414.70167 | 1776058068.84826 | 5796920448.02394  | 1604826350.38627 | 1572446737.44742 | 1883576140.48251 | 2059560504.183348 |
| 2024-09-24 00:00:00+00:00 | 13803897941.4459   | 1233617827.37224 | 4623955823.48951 | 1889015003.75608 | 4560270564.10611  | 1531245791.35488 | 1499667822.70557 | 2074103404.06031 | 2043368536.120572 |
| 2024-09-25 00:00:00+00:00 | 11243478001.8234   | 1056276031.71222 | 4504151719.14296 | 1543860513.03847 | 3791679743.58698  | 1510723332.35641 | 1492906823.75684 | 1894745371.91    | 1621159844.139992 |
| 2024-09-26 00:00:00+00:00 | 15599762219.3771   | 1610121770.7868  | 5623746968.56271 | 2281290095.10416 | 6042193867.25463  | 1884280762.68463 | 1716777384.93289 | 2384946966.64538 | 2319230690.451392 |
| 2024-09-27 00:00:00+00:00 | 14116726844.818899 | 1069480100.13979 | 5160096066.06245 | 2558606461.87492 | 5638677750.91947  | 1018072023.28832 | 1716844603.36935 | 2342997486.18092 | 2064558204.748724 |
| 2024-09-28 00:00:00+00:00 | 8159304277.82764   | 502782942.654992 | 2694065736.76692 | 964628082.625474 | 2081725893.72908  | 677192203.169288 | 1195274976.603   | 1451311955.47487 | 941584508.956109  |
| 2024-09-29 00:00:00+00:00 | 8921640553.12451   | 539803911.632983 | 2538588361.13329 | 1024493096.08131 | 2706231391.93362  | 900547717.914862 | 1067935423.38093 | 1460065096.9441  | 1018404267.377896 |
| 2024-09-30 00:00:00+00:00 | 15202552937.998301 | 1342394442.65625 | 4937717476.11833 | 2111602915.23605 | 6422163849.5578   | 1370536947.44636 | 1595747524.90984 | 2388331950.3912  | 2037584661.361227 |
| 2024-10-01 00:00:00+00:00 | 23240548408.584702 | 3184757131.55157 | 7759540621.79189 | 3415548316.38006 | 8959183206.512569 | 2137805079.14537 | 1908358048.62952 | 3470705407.36197 | 2871101695.353822 |
| 2024-10-02 00:00:00+00:00 | 17437229519.513699 | 1603025104.85705 | 5526619243.09343 | 2352353661.75056 | 8743651625.525089 | 1815221539.44225 | 1956203879.59561 | 2356068415.41375 | 2205618738.858672 |
| 2024-10-03 00:00:00+00:00 | 14999111682.6152   | 1605418668.37504 | 5120501662.45691 | 1930904616.17741 | 8193532164.49563  | 1538014044.673   | 1771828990.69422 | 2116511967.71281 | 1889111631.496463 |
| 2024-10-04 00:00:00+00:00 | 12876175910.416201 | 1332886726.35117 | 4279900711.68787 | 1918812943.46179 | 5759795028.96788  | 1280488009.44946 | 1437592080.67671 | 1697775201.17512 | 1770689490.345348 |
| 2024-10-05 00:00:00+00:00 | 6532364228.97254   | 392462635.006691 | 2126069409.03706 | 608167606.66407  | 1872894569.02638  | 594321770.03637  | 965511857.476451 | 815970303.962524 | 705386770.661552  |
| 2024-10-06 00:00:00+00:00 | 6930843434.83285   | 444045828.210464 | 2046183278.08736 | 679562882.140494 | 2229413627.75299  | 661460021.074824 | 882202743.119424 | 951842866.408241 | 823568622.1757    |

```python
def format_ticks_usd(y, pos):
    if y >= 1_000_000_000_000:
        return '${:.1f}T'.format(y/1000000000000)
    elif y >= 1_000_000_000:
        return '${:.1f}B'.format(y/1000000000)
    elif y >= 1000000:
        return '${:.1f}M'.format(y/1000000)
    elif y >= 1000:
        return '${:.1f}K'.format(y/1000)
    else:
        return '${:.1f}'.format(y)

fig, ax = plt.subplots(figsize=(8,6))

ax.stackplot(
    pivot_volumes.index,
    [pivot_volumes[exchange].astype(float) for exchange in exchange_list_truncated],
    labels=exchange_list_truncated,
)
ax.set_title("Total Exchange Volume")
ax.yaxis.set_major_formatter(format_ticks_usd)
ax.yaxis.grid(visible=True, which='major', linestyle='--', alpha=0.5)
ax.legend(loc='lower right', bbox_to_anchor=(1.25, 0), title="Exchange")
ax.tick_params(axis='x', labelrotation=45)
ax.xaxis.set_major_locator(plt.MaxNLocator(4))
ax.set_xlim(volumes.time.min(), volumes.time.max())
```

<figure><img src="/files/skjp6UIANZupLDmrRnA2" alt=""><figcaption></figcaption></figure>

```python
pivot_volume_share = 100*pivot_volumes[exchange_list_truncated].div(pivot_volumes[exchange_list_truncated].sum(axis=1), axis=0)
```

```python
import matplotlib.ticker as mtick


fig, ax = plt.subplots(figsize=(8,6))

ax.stackplot(
    pivot_volume_share.index,
    [pivot_volume_share[exchange].astype(float) for exchange in exchange_list_truncated],
    labels=exchange_list_truncated,
)
ax.set_title("Exchange Volume Share")
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
ax.yaxis.grid(visible=True, which='major', linestyle='--', alpha=0.5)
ax.legend(loc='lower right', bbox_to_anchor=(1.25, 0), title="Exchange")
ax.tick_params(axis='x', labelrotation=45)
ax.xaxis.set_major_locator(plt.MaxNLocator(4))
ax.set_xlim(volumes.time.min(), volumes.time.max())
ax.set_ylim(0, 100)
```

<figure><img src="/files/DYLGuJnc5McDN4LRMlx0" alt=""><figcaption></figcaption></figure>

### Asset Share

In addition to retrieving aggregated trading volumes for all markets on an exchange, we can also utilize the *timeseries/market-candles* to obtain the USD trading volume of individual markets on a particular exchange.

```python
# The wildcard parameter (*) enables users to retrieve all markets matching the designated format
exchange = 'coinbase'
markets=f"{exchange}-*-spot"
```

```python
df = client.get_market_candles(
    markets=markets,
    start_time=start,
    end_time=end,
    frequency='1d',
    page_size=10000
).parallel(time_increment=timedelta(days=1)).to_dataframe()
```

```
Exporting to dataframe type:  79%|███████████████████████████████████████▎          | 22/28 [00:02<00:00, 10.38it/s]2024-10-07 12:48:38 INFO     no data to export
Exporting to dataframe type: 100%|██████████████████████████████████████████████████| 28/28 [00:02<00:00,  9.86it/s]
```

```python
df
```

|       | market                  | time                      | price\_open | price\_close | price\_high | price\_low | vwap     | volume       | candle\_usd\_volume | candle\_trades\_count |
| ----- | ----------------------- | ------------------------- | ----------- | ------------ | ----------- | ---------- | -------- | ------------ | ------------------- | --------------------- |
| 0     | coinbase-00-usd-spot    | 2024-09-10 00:00:00+00:00 | 0.0369      | 0.0361       | 0.0393      | 0.036      | 0.037349 | 4538849.98   | 169520.073709       | 1586                  |
| 1     | coinbase-1inch-btc-spot | 2024-09-10 00:00:00+00:00 | 0.000005    | 0.000005     | 0.000005    | 0.000005   | 0.000005 | 14287.41     | 3720.280159         | 21                    |
| 2     | coinbase-1inch-eur-spot | 2024-09-10 00:00:00+00:00 | 0.238       | 0.237        | 0.239       | 0.232      | 0.236182 | 616552.97    | 160541.151569       | 271                   |
| 3     | coinbase-1inch-gbp-spot | 2024-09-10 00:00:00+00:00 | 0.201       | 0.199        | 0.201       | 0.196      | 0.199207 | 358978.94    | 93500.859211        | 194                   |
| 4     | coinbase-1inch-usd-spot | 2024-09-10 00:00:00+00:00 | 0.263       | 0.26         | 0.264       | 0.256      | 0.259755 | 3483735.74   | 904916.71491        | 2772                  |
| ...   | ...                     | ...                       | ...         | ...          | ...         | ...        | ...      | ...          | ...                 | ...                   |
| 11027 | coinbase-zen-usd-spot   | 2024-10-06 00:00:00+00:00 | 7.49        | 8.01         | 8.04        | 7.49       | 7.726637 | 3059.792     | 23641.90321         | 243                   |
| 11028 | coinbase-zeta-usd-spot  | 2024-10-06 00:00:00+00:00 | 0.5964      | 0.6084       | 0.6121      | 0.5815     | 0.59916  | 666852.1     | 399550.77625        | 3258                  |
| 11029 | coinbase-zk-usd-spot    | 2024-10-06 00:00:00+00:00 | 0.12432     | 0.12904      | 0.13047     | 0.12409    | 0.126848 | 562305.1     | 71327.114648        | 462                   |
| 11030 | coinbase-zro-usd-spot   | 2024-10-06 00:00:00+00:00 | 4.109       | 4.236        | 4.253       | 4.067      | 4.162722 | 119387.31    | 496976.15616        | 1341                  |
| 11031 | coinbase-zrx-usd-spot   | 2024-10-06 00:00:00+00:00 | 0.309497    | 0.323902     | 0.323902    | 0.307255   | 0.317242 | 599437.77086 | 190166.885533       | 1235                  |

11032 rows × 10 columns

```python
df["candle_usd_volume"] = df.candle_usd_volume.astype(float)
df["time"] = pd.to_datetime(df.time)
```

```python
df.sort_values(["market","time"],inplace=True)
    
# Create Addt. Cols
df['exchange'] = df.market.apply(lambda x: x.split("-")[0])
df['exchange-base'] = df.market.apply(lambda x: x.split("-")[0]+"-"+x.split("-")[1])
df['market_type'] = df.market.apply(lambda x: x.split("-")[-1])
df['base'] = df.market.apply(lambda x: x.split("-")[1])
df['quote'] = df.market.apply(lambda x: x.split("-")[2])

# Get volume by base asset by day

# Get top 10 assets by volume
total_vol_by_base = df.groupby('base',as_index=False).candle_usd_volume.sum()
total_vol_by_base.sort_values(by="candle_usd_volume",inplace=True)
base_top_list = total_vol_by_base.tail(10).base.tolist()
df["base2"] = np.where(df.base.isin(base_top_list),df.base,f"{len(total_vol_by_base)-10} others")

# Get sum by base asset by day
df_vol_by_base = df.groupby(["time","base2"],as_index=False).candle_usd_volume.sum()
df_vol_by_base['total_vol'] = df_vol_by_base.groupby("time").candle_usd_volume.transform(sum)
df_vol_by_base.columns=["time","base_asset","vol","total_vol"]
df_vol_by_base["vol_pct"]=(df_vol_by_base.vol/df_vol_by_base.total_vol)*100
df_vol_by_base.sort_values(["base_asset","time"],inplace=True)
```

```python
df_vol_by_base
```

|     | time                      | base\_asset | vol          | total\_vol   | vol\_pct  |
| --- | ------------------------- | ----------- | ------------ | ------------ | --------- |
| 0   | 2024-09-10 00:00:00+00:00 | 248 others  | 2.285934e+08 | 1.325089e+09 | 17.251175 |
| 11  | 2024-09-11 00:00:00+00:00 | 248 others  | 2.546721e+08 | 1.708684e+09 | 14.904575 |
| 22  | 2024-09-12 00:00:00+00:00 | 248 others  | 2.478359e+08 | 1.783317e+09 | 13.897469 |
| 33  | 2024-09-13 00:00:00+00:00 | 248 others  | 2.823741e+08 | 1.834706e+09 | 15.390699 |
| 44  | 2024-09-14 00:00:00+00:00 | 248 others  | 1.710470e+08 | 1.139076e+09 | 15.016301 |
| ... | ...                       | ...         | ...          | ...          | ...       |
| 252 | 2024-10-02 00:00:00+00:00 | xrp         | 1.025636e+08 | 2.355545e+09 | 4.354134  |
| 263 | 2024-10-03 00:00:00+00:00 | xrp         | 8.681132e+07 | 1.934456e+09 | 4.487634  |
| 274 | 2024-10-04 00:00:00+00:00 | xrp         | 4.813218e+07 | 1.924832e+09 | 2.500591  |
| 285 | 2024-10-05 00:00:00+00:00 | xrp         | 1.525881e+07 | 6.100742e+08 | 2.501140  |
| 296 | 2024-10-06 00:00:00+00:00 | xrp         | 1.258580e+07 | 6.807883e+08 | 1.848710  |

297 rows × 5 columns

```python
num_assets = len(total_vol_by_base)
top_assets  = df_vol_by_base[~df_vol_by_base.base_asset.isin(["btc","eth",f"{num_assets-10} others"])].groupby("base_asset").vol.sum().sort_values(ascending=False).index.tolist()
top_assets  = ["btc","eth",f"{num_assets-10} others"] + top_assets

# Pivot back to assets in columns
df_vol_pivot = df_vol_by_base.pivot(index='time',
                             columns="base_asset",
                             values="vol_pct")

```

```python
df_vol_pivot = df_vol_pivot[top_assets]
df_vol_pivot
```

| base\_asset               | btc       | eth       | 248 others | usdt      | sol      | sui      | xrp      | bonk     | doge     | shib     | fet      |
| ------------------------- | --------- | --------- | ---------- | --------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- |
| time                      |           |           |            |           |          |          |          |          |          |          |          |
| 2024-09-10 00:00:00+00:00 | 30.972149 | 13.067446 | 17.251175  | 24.945950 | 6.146731 | 1.292479 | 1.117807 | 1.095419 | 1.176307 | 0.505209 | 2.429329 |
| 2024-09-11 00:00:00+00:00 | 42.533098 | 14.601279 | 14.904575  | 16.508054 | 5.409347 | 0.986693 | 0.859503 | 0.918263 | 1.086848 | 0.510467 | 1.681872 |
| 2024-09-12 00:00:00+00:00 | 36.055903 | 11.246405 | 13.897469  | 24.472115 | 5.432146 | 2.323582 | 2.768770 | 0.686577 | 0.897056 | 0.317287 | 1.902690 |
| 2024-09-13 00:00:00+00:00 | 41.600482 | 12.469632 | 15.390699  | 17.687048 | 5.396664 | 1.283156 | 1.744660 | 0.639577 | 2.029411 | 0.438210 | 1.320460 |
| 2024-09-14 00:00:00+00:00 | 18.104549 | 7.169948  | 15.016301  | 46.855937 | 4.118700 | 1.842687 | 3.210786 | 0.853040 | 1.347843 | 0.469507 | 1.010702 |
| 2024-09-15 00:00:00+00:00 | 31.125051 | 16.348491 | 22.996837  | 10.391716 | 7.648190 | 3.747606 | 2.454636 | 1.244448 | 1.527748 | 0.543500 | 1.971777 |
| 2024-09-16 00:00:00+00:00 | 37.193874 | 17.206186 | 14.866560  | 17.164195 | 5.416218 | 2.069775 | 2.074828 | 0.735451 | 1.292425 | 0.482445 | 1.498044 |
| 2024-09-17 00:00:00+00:00 | 43.462805 | 13.122193 | 14.039608  | 16.877017 | 4.806221 | 2.639338 | 1.338655 | 0.617046 | 1.527054 | 0.304794 | 1.265270 |
| 2024-09-18 00:00:00+00:00 | 42.578945 | 14.389160 | 16.363534  | 10.759089 | 6.367782 | 4.161422 | 1.541983 | 0.689565 | 1.025603 | 0.504158 | 1.618760 |
| 2024-09-19 00:00:00+00:00 | 40.554355 | 11.913760 | 16.697873  | 13.990523 | 7.922874 | 3.051438 | 1.419195 | 1.071619 | 1.016350 | 0.619502 | 1.742510 |
| 2024-09-20 00:00:00+00:00 | 37.449647 | 13.966163 | 17.361613  | 13.270193 | 8.267577 | 3.294778 | 1.693500 | 1.156477 | 1.183191 | 0.508040 | 1.848821 |
| 2024-09-21 00:00:00+00:00 | 18.083126 | 17.647521 | 28.822949  | 11.717905 | 7.503045 | 4.002590 | 3.399164 | 1.988337 | 2.762844 | 1.646701 | 2.425818 |
| 2024-09-22 00:00:00+00:00 | 21.307804 | 12.658318 | 26.451636  | 17.494754 | 7.398947 | 7.118906 | 2.268850 | 1.122223 | 1.443169 | 1.173459 | 1.561934 |
| 2024-09-23 00:00:00+00:00 | 28.062013 | 17.667165 | 23.868440  | 13.861710 | 6.594981 | 4.093083 | 1.568748 | 0.654969 | 1.279564 | 0.547387 | 1.801941 |
| 2024-09-24 00:00:00+00:00 | 33.094029 | 16.229860 | 21.218012  | 10.361613 | 8.680876 | 4.290091 | 1.515116 | 0.933201 | 1.290790 | 0.589167 | 1.797243 |
| 2024-09-25 00:00:00+00:00 | 27.404906 | 14.144505 | 24.530905  | 14.985292 | 6.672537 | 4.867293 | 1.458899 | 1.815678 | 1.218182 | 1.596375 | 1.305427 |
| 2024-09-26 00:00:00+00:00 | 39.177160 | 9.940609  | 19.496714  | 11.109452 | 6.368470 | 3.448674 | 1.442450 | 1.690203 | 2.378929 | 4.152833 | 0.794507 |
| 2024-09-27 00:00:00+00:00 | 26.766935 | 11.660842 | 17.983374  | 23.777946 | 5.385791 | 2.343162 | 1.394474 | 2.964885 | 2.609585 | 4.088519 | 1.024488 |
| 2024-09-28 00:00:00+00:00 | 20.230763 | 8.003782  | 28.134525  | 9.949252  | 5.924345 | 2.526298 | 5.794979 | 5.232725 | 5.858864 | 6.783351 | 1.561114 |
| 2024-09-29 00:00:00+00:00 | 18.938614 | 8.169610  | 25.586889  | 12.172558 | 8.480627 | 6.501959 | 7.499683 | 4.049526 | 3.323746 | 4.029056 | 1.247732 |
| 2024-09-30 00:00:00+00:00 | 35.243463 | 10.555167 | 17.243217  | 15.949195 | 5.059958 | 3.853798 | 2.801514 | 3.926700 | 2.007723 | 2.283844 | 1.075420 |
| 2024-10-01 00:00:00+00:00 | 31.632666 | 12.956976 | 15.578165  | 19.152425 | 6.907327 | 4.017289 | 2.204173 | 3.274045 | 1.561403 | 1.602777 | 1.112754 |
| 2024-10-02 00:00:00+00:00 | 25.281508 | 11.474000 | 16.978840  | 20.736372 | 7.466111 | 5.570698 | 4.354134 | 3.818578 | 1.535713 | 1.664415 | 1.119630 |
| 2024-10-03 00:00:00+00:00 | 27.779234 | 10.982394 | 19.681539  | 13.232334 | 7.575048 | 8.686570 | 4.487634 | 3.914550 | 1.509132 | 1.266215 | 0.885351 |
| 2024-10-04 00:00:00+00:00 | 27.744248 | 9.435388  | 18.426154  | 22.715653 | 6.293791 | 5.623055 | 2.500591 | 2.882626 | 1.619108 | 1.761227 | 0.998159 |
| 2024-10-05 00:00:00+00:00 | 19.659108 | 8.427409  | 29.770955  | 14.614917 | 6.718545 | 6.955554 | 2.501140 | 3.304475 | 2.228612 | 3.536127 | 2.283157 |
| 2024-10-06 00:00:00+00:00 | 20.993449 | 7.617764  | 28.486867  | 14.267944 | 6.844585 | 8.255616 | 1.848710 | 3.945631 | 2.145486 | 4.223452 | 1.370494 |

```python
fig, ax = plt.subplots(figsize=(8,6))

ax.stackplot(
    df_vol_pivot.index,
    [df_vol_pivot[asset].astype(float) for asset in df_vol_by_base.base_asset.unique()],
    labels=df_vol_by_base.base_asset.unique(),
)
ax.set_title("Asset Volume Share")
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
ax.yaxis.grid(visible=True, which='major', linestyle='--', alpha=0.5)
ax.legend(loc='lower right', bbox_to_anchor=(1.25, 0), title="Asset")
ax.tick_params(axis='x', labelrotation=45)
ax.xaxis.set_major_locator(plt.MaxNLocator(4))
ax.set_xlim(volumes.time.min(), volumes.time.max())
ax.set_ylim(0, 100)
```

<figure><img src="/files/po139TldBbtDXwpJIgDk" alt=""><figcaption></figcaption></figure>

### Retrieve Trade Sizes

Trade size is a useful metric for understanding the composition of an exchange's trading patterns. Is the platform more popular for retail traders, or large institutions? Which assets are driven by whale trades vs. small buys? These patterns are especially relevant for venues like Coinbase, where fee revenue is determined by trade size.

```python
def get_trade_size_stats(start,end,market):
    """ 
    For a given date and market, get stats on number of trades and dist of trade sizes 
        Returns a df with:
             Number of trades
             Volume (USD/Native)
             Number of trades by size groupings
             Volume derived from trades of various size groupings
    """
    
    #Call api
    df_trades = client.get_market_trades(
        markets=market,
        start_time=start,
        end_time=end,
        page_size=10000
    ).parallel(time_increment=timedelta(hours=1)).to_dataframe()
    #Prep data
    df_trades["amount_usd"] = df_trades.amount*df_trades.price
    df_trades["amount_usd_groups"] = pd.cut(df_trades["amount_usd"],bins=[0,1e3,1e4,1e5,1e6,1e7,1e100])
    print(df_trades.time.min())
    print(df_trades.time.max())

    #Get stats by group
    sum_count_by_size = df_trades.groupby("amount_usd_groups").agg({"amount_usd":['count',sum]})
    
    #Collect into a df
    df_day = pd.DataFrame()

    df_day.loc[start,"NumTrades"] = len(df_trades)
    df_day.loc[start,"VolUSD"] = df_trades.amount_usd.sum()
    df_day.loc[start,"VolNTV"] = df_trades.amount.sum()

    df_day.loc[start,"AvgSizeUSD"] = df_trades.amount_usd.mean()
    df_day.loc[start,"MedSizeUSD"] = df_trades.amount_usd.median()
    df_day.loc[start,"MaxSizeUSD"] = df_trades.amount_usd.max()

    df_day.loc[start,"NumTrades_0-1K"]      = sum_count_by_size.iloc[0,0]
    df_day.loc[start,"NumTrades_1K-10K"]    = sum_count_by_size.iloc[1,0]
    df_day.loc[start,"NumTrades_10K-100K"]  = sum_count_by_size.iloc[2,0]
    df_day.loc[start,"NumTrades_100K-1M"]   = sum_count_by_size.iloc[3,0]
    df_day.loc[start,"NumTrades_1M-10M"]    = sum_count_by_size.iloc[4,0]
    df_day.loc[start,"NumTrades_10M-Over"]  = sum_count_by_size.iloc[5,0]

    df_day.loc[start,"VolUSD_Trades_0-1K"]     = sum_count_by_size.iloc[0,1]
    df_day.loc[start,"VolUSD_Trades_1K-10K"]   = sum_count_by_size.iloc[1,1]
    df_day.loc[start,"VolUSD_Trades_10K-100K"] = sum_count_by_size.iloc[2,1]
    df_day.loc[start,"VolUSD_Trades_100K-1M"]  = sum_count_by_size.iloc[3,1]
    df_day.loc[start,"VolUSD_Trades_1M-10M"]   = sum_count_by_size.iloc[4,1]
    df_day.loc[start,"VolUSD_Trades_10M-Over"] = sum_count_by_size.iloc[5,1]
    
    return df_day
```

```python
start = datetime.today() - timedelta(hours=24)
end = datetime.today()
```

```python
df = get_trade_size_stats(start, end,'coinbase-btc-usd-spot')
```

```
Exporting to dataframe type:  44%|██████████████████████                            | 11/25 [00:02<00:02,  6.99it/s]2024-10-07 12:48:43 INFO     no data to export
Exporting to dataframe type: 100%|██████████████████████████████████████████████████| 25/25 [00:04<00:00,  5.16it/s]

2024-10-06 12:48:39.766637+00:00
2024-10-07 12:48:31.860605+00:00


```

```python
df.head()
```

|                            | NumTrades | VolUSD       | VolNTV     | AvgSizeUSD  | MedSizeUSD | MaxSizeUSD    | NumTrades\_0-1K | NumTrades\_1K-10K | NumTrades\_10K-100K | NumTrades\_100K-1M | NumTrades\_1M-10M | NumTrades\_10M-Over | VolUSD\_Trades\_0-1K | VolUSD\_Trades\_1K-10K | VolUSD\_Trades\_10K-100K | VolUSD\_Trades\_100K-1M | VolUSD\_Trades\_1M-10M | VolUSD\_Trades\_10M-Over |
| -------------------------- | --------- | ------------ | ---------- | ----------- | ---------- | ------------- | --------------- | ----------------- | ------------------- | ------------------ | ----------------- | ------------------- | -------------------- | ---------------------- | ------------------------ | ----------------------- | ---------------------- | ------------------------ |
| 2024-10-06 12:48:39.638626 | 233725.0  | 2.681840e+08 | 4249.99384 | 1147.434052 | 48.436912  | 475567.911314 | 187168.0        | 41234.0           | 5278.0              | 45.0               | 0.0               | 0.0                 | 1.983836e+07         | 1.350884e+08           | 1.056560e+08             | 7.601298e+06            | 0.0                    | 0.0                      |

```python
df.transpose()#.rename_axis('value')
```

|                          | 2024-10-06 12:48:39.638626 |
| ------------------------ | -------------------------- |
| NumTrades                | 2.337250e+05               |
| VolUSD                   | 2.681840e+08               |
| VolNTV                   | 4.249994e+03               |
| AvgSizeUSD               | 1.147434e+03               |
| MedSizeUSD               | 4.843691e+01               |
| MaxSizeUSD               | 4.755679e+05               |
| NumTrades\_0-1K          | 1.871680e+05               |
| NumTrades\_1K-10K        | 4.123400e+04               |
| NumTrades\_10K-100K      | 5.278000e+03               |
| NumTrades\_100K-1M       | 4.500000e+01               |
| NumTrades\_1M-10M        | 0.000000e+00               |
| NumTrades\_10M-Over      | 0.000000e+00               |
| VolUSD\_Trades\_0-1K     | 1.983836e+07               |
| VolUSD\_Trades\_1K-10K   | 1.350884e+08               |
| VolUSD\_Trades\_10K-100K | 1.056560e+08               |
| VolUSD\_Trades\_100K-1M  | 7.601298e+06               |
| VolUSD\_Trades\_1M-10M   | 0.000000e+00               |
| VolUSD\_Trades\_10M-Over | 0.000000e+00               |

```python
trade_sizes = df[['VolUSD_Trades_0-1K',
                  'VolUSD_Trades_1K-10K',
                  'VolUSD_Trades_10K-100K',
                  'VolUSD_Trades_100K-1M',
                  'VolUSD_Trades_1M-10M',
                  'VolUSD_Trades_10M-Over']]

trade_sizes = trade_sizes.rename(columns=lambda x: x.split('_')[2])
trade_sizes
```

|                            | 0-1K         | 1K-10K       | 10K-100K     | 100K-1M      | 1M-10M | 10M-Over |
| -------------------------- | ------------ | ------------ | ------------ | ------------ | ------ | -------- |
| 2024-10-06 12:48:39.638626 | 1.983836e+07 | 1.350884e+08 | 1.056560e+08 | 7.601298e+06 | 0.0    | 0.0      |

```python
fig, ax = plt.subplots()
ax.bar(
    x=trade_sizes.columns,
    height=np.hstack([trade_sizes[c].astype(float) for c in trade_sizes.columns])
)

ax.set_title(f"Coinbase Volume by Trade Size \n{start.isoformat()[:16]} to {end.isoformat()[:16]}")
ax.yaxis.set_major_formatter(format_ticks_usd)
ax.yaxis.grid(visible=True, which='major', linestyle='--', alpha=0.5)

```

<figure><img src="/files/CfpsjHxZrds4T2WNx6Je" alt=""><figcaption></figcaption></figure>


# Analyzing Free Float Supply

{% embed url="<https://www.youtube.com/watch?v=eaj7E6UyZ0M>" %}

{% embed url="<https://github.com/coinmetrics/demo/blob/master/Current_Supply_a_year_on.ipynb>" %}
Jupyter Notebook hosted on Github
{% endembed %}

### Instructions

The notebook linked above shows how to obtain the asset metric "Free Float Supply" for a variety of crypto assets, and how to draw some conclusions by comparing the metric indexed to a particular date.

The video also covers how to use Reference Data and Catalog. It is applicable for all network data / asset metrics.

The notebook was published for [Google Colab](https://colab.research.google.com/). If you want to use it in Colab, the easiest way is to open Colab and load the notebook from the Github URL (pasted into the open dialog). This method does not require cloning the repo first.

If you prefer to use the notebook with Jupyter, all you need to change is the way in which the API key is retrieved. The video actually does not use an API key, since we demo the community API. If you have an API key, you should use it since it will speed up the downloads significantly.

### Optional Deeper Dive on Free Float

{% embed url="<https://www.youtube.com/watch?v=ieZl8PKIB0s>" %}


# Creating Custom Network Data Metrics Using ATLAS

![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/Demo%20Asset%20Resources/CM-Demo-metric_workbench-Cover.png)

While Coin Metrics **Network Data Pro** offers users the ability to analyze aggregated on-chain metrics for a variety of cryptoassets, some power users may require additional customization and granularity. Coin Metrics **ATLAS search engine** equips users with the on-chain analytical toolset they need to workshop their own custom metrics.

### Resources

This notebook demonstrates basic functionality offered by the Coin Metrics Python API Client, ATLAS, and Network Data Pro.

Coin Metrics offers a vast assortment of data for hundreds of cryptoassets. The Python API Client allows for easy access to this data using Python without needing to create your own wrappers using `requests` and other such libraries.

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics.
* The [Coin Metrics Product Documentation](https://docs.coinmetrics.io/info) gives detailed, conceptual explanations of the data that Coin Metrics offers.
* The [API Spec](https://docs.coinmetrics.io/python-api-client/reference) contains a full list of functions.

### File Download

Download the entire notebook as either a jupyter notebook to run yourself or as a pdf from the two links below

{% file src="/files/u1HcajhaAgqlAVgO4w4a" %}

{% file src="/files/MtJo3GRqp5fV1S1Pqwrg" %}

### Notebook Setup

```python
from os import environ
import pandas as pd
import logging
from datetime import date, datetime, timedelta
from coinmetrics.api_client import CoinMetricsClient
import json
import logging
import seaborn as sns
import matplotlib.pyplot as plt
# %matplotlib inline
from IPython.display import Markdown as md
```

```python
sns.set_theme()
sns.set(rc={'figure.figsize':(8,6)})
sns.set_style("whitegrid",{'axes.grid' : False,'grid.linestyle': '--', 'grid.color': 'black','axes.edgecolor': 'white','font.family': ['sans-serif']})
```

```python
logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S'
)
```

```python
# We recommend privately storing your API key in your local environment.
try:
    api_key = environ["CM_API_KEY"]
    logging.info("Using API key found in environment")
except KeyError:
    api_key = ""
    logging.info("API key not found. Using community client")

client = CoinMetricsClient(api_key)
```

```
2024-09-16 14:50:24 INFO     Using API key found in environment
```

## Block-by-Block Metrics

With **Network Data Pro**, block-by-block metrics are offered for both BTC and ETH. With **ATLAS**, however, we have the ability to retrieve block-by-block metrics for any asset in ATLAS coverage.

In this example, we quantify the total amount of USDC and USDT transferred on a block-by-block basis.

```python
hours = 2
end = datetime.now()
start = end - timedelta(hours=hours)
```

```python
# Retrieving data for both USDC and USDT (ETH chain)
asset_list = ['usdc','usdt_eth']
```

```python
for asset in asset_list:
    print('Fetching ' + asset.upper() + ' transactions...')
    
    # ATLAS 'Get List of Transactions' function
    vars()[asset + '_tx'] = client.get_list_of_transactions_v2(
            asset=asset,
            start_time=start,
            end_time=end
    ).to_dataframe().drop_duplicates(subset=['txid'],keep='last')
```

```
Fetching USDC transactions...
Fetching USDT_ETH transactions...
```

#### USDC Transactions

```python
usdc_tx.tail()
```

|      | txid                                              | consensus\_time           | tx\_position      | n\_balance\_updates | amount       | block\_hash                                       | height   | miner\_time               | min\_chain\_sequence\_number | max\_chain\_sequence\_number | fee |
| ---- | ------------------------------------------------- | ------------------------- | ----------------- | ------------------- | ------------ | ------------------------------------------------- | -------- | ------------------------- | ---------------------------- | ---------------------------- | --- |
| 4839 | e4349a2d37cb71ea25068fdae029f99903585d3c221281... | 2024-09-16 14:50:23+00:00 | 89180189833035782 | 2                   | 1047.039959  | 0a590f6b2dd842efa8a7f1a0ebce2746cdb20a2c069bb8... | 20763881 | 2024-09-16 14:50:23+00:00 | 89180189833035790            | 89180189833035791            | 0   |
| 4840 | 9c224f0fd2e8a82561351ace87d0b4db0e382d948ec8fe... | 2024-09-16 14:50:23+00:00 | 89180189833035783 | 2                   | 560.0        | 0a590f6b2dd842efa8a7f1a0ebce2746cdb20a2c069bb8... | 20763881 | 2024-09-16 14:50:23+00:00 | 89180189833035792            | 89180189833035793            | 0   |
| 4841 | 559ba39db4ccd441c3a22ac6de2536567b7e9c78280925... | 2024-09-16 14:50:23+00:00 | 89180189833035784 | 2                   | 82426.032272 | 0a590f6b2dd842efa8a7f1a0ebce2746cdb20a2c069bb8... | 20763881 | 2024-09-16 14:50:23+00:00 | 89180189833035794            | 89180189833035795            | 0   |
| 4842 | fe0d66654af63c8c31f2f012daae75efaff9d91f85be58... | 2024-09-16 14:50:23+00:00 | 89180189833035785 | 2                   | 1455.127734  | 0a590f6b2dd842efa8a7f1a0ebce2746cdb20a2c069bb8... | 20763881 | 2024-09-16 14:50:23+00:00 | 89180189833035796            | 89180189833035797            | 0   |
| 4843 | 8651c23909accf78b1ad45cadc85eb74aeb4afe2031f50... | 2024-09-16 14:50:23+00:00 | 89180189833035786 | 2                   | 30.0         | 0a590f6b2dd842efa8a7f1a0ebce2746cdb20a2c069bb8... | 20763881 | 2024-09-16 14:50:23+00:00 | 89180189833035798            | 89180189833035799            | 0   |

```python
# Transform balance updates into block-by-block transfer metrics with one line of code
usdc_tx_bbb = pd.DataFrame(usdc_tx.groupby('height')['amount'].sum())
usdc_tx_bbb.head()
```

|          | amount        |
| -------- | ------------- |
| height   |               |
| 20763288 | 113663.822406 |
| 20763289 | 99292.054782  |
| 20763290 | 7651.824353   |
| 20763291 | 1018865.93048 |
| 20763292 | 384271.09176  |

```python
ax = sns.lineplot(
    data=usdc_tx_bbb,
    y=usdc_tx_bbb['amount'],
    x=usdc_tx_bbb.index
)
ax.set_xlabel("Block Height", fontsize = 12)
ax.set_ylabel("Total Transfer \nAmount", fontsize = 12)
plt.setp(ax.get_xticklabels(), rotation=45)
ax.xaxis.set_ticks(plt.gca().get_xticks())
plt.gca().set_xticklabels(['{:.0f}'.format(x) for x in plt.gca().get_xticks()])
ax.yaxis.set_ticks(plt.gca().get_yticks())
plt.gca().set_yticklabels(['${:,.1f}M'.format(y/1000000) for y in plt.gca().get_yticks()])
plt.ylim([usdc_tx_bbb['amount'].min(), usdc_tx_bbb['amount'].max()*1.1])
plt.xlim([usdc_tx_bbb.index[0], usdc_tx_bbb.index[-1]])
plt.annotate(
    'Source: Coin Metrics ATLAS',
    xy=(1, -0.195),
    xycoords='axes fraction',
    color='black',xytext=(-8, 0),
    textcoords='offset pixels',
    horizontalalignment='right',
    verticalalignment='bottom'
)
ax.set_title('\nUSDC Transactions (Block-by-Block) \n', fontsize = 16)
plt.show()
```

<figure><img src="/files/FhXLmI5ENvU5nTBRi48f" alt=""><figcaption></figcaption></figure>

```
largest_tx = usdc_tx.loc[usdc_tx['amount'].idxmax()]
```

```python
largest_tx
```

```
txid                         ca9d6c9c2e86a71c5482845abf9a8821d743bd2923fb73...
consensus_time                                       2024-09-16 14:43:11+00:00
tx_position                                                  89180035214213128
n_balance_updates                                                           10
amount                                                          50893857.89172
block_hash                   19e68e57ad114250502478a0e337ea9ee681f5d0730496...
height                                                                20763845
miner_time                                           2024-09-16 14:43:11+00:00
min_chain_sequence_number                                    89180035214213140
max_chain_sequence_number                                    89180035214213149
fee                                                                          0
Name: 4549, dtype: object
```

```python
md('<br><font size="3.5">Transaction info can also be viewed in the **ATLAS** graphical user interface:<br><br>**Largest Transaction:** <br>https://atlas.coinmetrics.io/transaction-details?asset=usdc&tx_hash=' + str(largest_tx.txid) )
```

\
Transaction info can also be viewed in the **ATLAS** graphical user interface:\
\
**Largest Transaction:**\
<https://atlas.coinmetrics.io/transaction-details?asset=usdc\\&tx\\_hash=ca9d6c9c2e86a71c5482845abf9a8821d743bd2923fb73cb87177e6e83d86d9e>

#### USDT Transactions

```python
usdt_eth_tx.tail()
```

|       | txid                                              | consensus\_time           | tx\_position      | n\_balance\_updates | amount     | block\_hash                                       | height   | miner\_time               | min\_chain\_sequence\_number | max\_chain\_sequence\_number | fee |
| ----- | ------------------------------------------------- | ------------------------- | ----------------- | ------------------- | ---------- | ------------------------------------------------- | -------- | ------------------------- | ---------------------------- | ---------------------------- | --- |
| 15151 | 0493f4f094032f2fc01a6a67d1bb7b18cad05d6b3727eb... | 2024-09-16 14:50:23+00:00 | 89180189833035822 | 2                   | 0.111413   | 0a590f6b2dd842efa8a7f1a0ebce2746cdb20a2c069bb8... | 20763881 | 2024-09-16 14:50:23+00:00 | 89180189833035890            | 89180189833035891            | 0   |
| 15152 | 616e8f6cbb50ed258575820c0cdac2b4d768bbb7c4cd7a... | 2024-09-16 14:50:23+00:00 | 89180189833035823 | 2                   | 75.0       | 0a590f6b2dd842efa8a7f1a0ebce2746cdb20a2c069bb8... | 20763881 | 2024-09-16 14:50:23+00:00 | 89180189833035892            | 89180189833035893            | 0   |
| 15153 | bdb7bee6537d63c72055b0b015f9a07e6129aff9fb2c43... | 2024-09-16 14:50:23+00:00 | 89180189833035824 | 2                   | 5.0        | 0a590f6b2dd842efa8a7f1a0ebce2746cdb20a2c069bb8... | 20763881 | 2024-09-16 14:50:23+00:00 | 89180189833035894            | 89180189833035895            | 0   |
| 15154 | 38988bf92c9a968df5d7db4c0307a08a3c857d6879e7c0... | 2024-09-16 14:50:23+00:00 | 89180189833035825 | 2                   | 211.714933 | 0a590f6b2dd842efa8a7f1a0ebce2746cdb20a2c069bb8... | 20763881 | 2024-09-16 14:50:23+00:00 | 89180189833035896            | 89180189833035897            | 0   |
| 15155 | 562fc4b718a681f189cf9aa452937d49527fce7a265193... | 2024-09-16 14:50:23+00:00 | 89180189833035826 | 2                   | 300.0      | 0a590f6b2dd842efa8a7f1a0ebce2746cdb20a2c069bb8... | 20763881 | 2024-09-16 14:50:23+00:00 | 89180189833035898            | 89180189833035899            | 0   |

```python
# Transform balance updates into block-by-block transfer metrics with one line of code
usdt_tx_bbb = pd.DataFrame(usdt_eth_tx.groupby('height')['amount'].sum())
usdt_tx_bbb.head()
```

|          | amount         |
| -------- | -------------- |
| height   |                |
| 20763288 | 523600.540279  |
| 20763289 | 149740.436168  |
| 20763290 | 143192.868507  |
| 20763291 | 79358.83167    |
| 20763292 | 1944483.921281 |

```python
ax = sns.lineplot(
    data=usdt_tx_bbb,
    y=usdt_tx_bbb['amount'],
    x=usdt_tx_bbb.index,
    color='green'
)
ax.set_xlabel("Block Height", fontsize = 15)
ax.set_ylabel("Total Transfer \nAmount", fontsize = 15)
plt.setp(ax.get_xticklabels(), rotation=45)
ax.xaxis.set_ticks(plt.gca().get_xticks())
plt.gca().set_xticklabels(['{:.0f}'.format(x) for x in plt.gca().get_xticks()])
ax.yaxis.set_ticks(plt.gca().get_yticks())
plt.gca().set_yticklabels(['${:,.1f}M'.format(y/1000000) for y in plt.gca().get_yticks()])
plt.ylim([usdt_tx_bbb['amount'].min(), usdt_tx_bbb['amount'].max()*1.1])
plt.xlim([usdt_tx_bbb.index[0], usdt_tx_bbb.index[-1]])
plt.annotate(
    'Source: Coin Metrics ATLAS',
    xy=(1, -0.195), 
    xycoords='axes fraction',color='black',
    xytext=(-8, 6), 
    textcoords='offset pixels',
    horizontalalignment='right',
    verticalalignment='bottom'
)
ax.set_title('\nUSDT Transactions (Block-by-Block) \n', fontsize = 17);

```

<figure><img src="/files/PJjfbmfjaBZdi2GQlqYf" alt=""><figcaption></figcaption></figure>

```

largest_usdt_tx = usdt_eth_tx.loc[usdt_eth_tx['amount'].idxmax()]
largest_usdt_tx
```

```
txid                         ec6ca03c17cea5c528378bbfa65ef1fb7471395c74a6e8...
consensus_time                                       2024-09-16 13:01:47+00:00
tx_position                                                  89177883435597842
n_balance_updates                                                            2
amount                                                              65000000.0
block_hash                   20c5ffdb60ac0aecbe1827788f2d448c8f0d8ab72827f3...
height                                                                20763344
miner_time                                           2024-09-16 13:01:47+00:00
min_chain_sequence_number                                    89177883435597866
max_chain_sequence_number                                    89177883435597867
fee                                                                          0
Name: 1462, dtype: object
```

```python
md('<br><font size="3.5">Transaction info can also be viewed in the **ATLAS** graphical user interface:<br><br>**Largest Transaction:** <br>https://atlas.coinmetrics.io/transaction-details?asset=usdt_eth&tx_hash=' + str(largest_usdt_tx.txid) )
```

\
Transaction info can also be viewed in the **ATLAS** graphical user interface:\
\
**Largest Transaction:**\
<https://atlas.coinmetrics.io/transaction-details?asset=usdt\\_eth\\&tx\\_hash=ec6ca03c17cea5c528378bbfa65ef1fb7471395c74a6e89d7344be0932c94a1c>

## Cross-Asset Metrics

With **Network Data Pro**, users have the ability to retrieve aggregated daily transfers for specific assets such as USDC and USDT. With **ATLAS**, however, we have the ability to create more customized, granular metrics.

In this example, we quantify the total size of **transactions where USDT and USDC are transferred simultaneously**, on a block-by-block basis.

```python
usdc_tx['USDC Amount'] = usdc_tx['amount']
usdt_eth_tx['USDT Amount'] = usdt_eth_tx['amount']

merged = pd.merge(usdc_tx[['height','USDC Amount','txid']], usdt_eth_tx[['USDT Amount','txid']], on ='txid')
merged['Total Amount'] = merged['USDT Amount'] + merged['USDC Amount']
```

```python
merged.tail()
```

|     | height   | USDC Amount  | txid                                              | USDT Amount  | Total Amount |
| --- | -------- | ------------ | ------------------------------------------------- | ------------ | ------------ |
| 310 | 20763867 | 149.890998   | 6288646aa12f6e17854e0e567d33e59baadb000fcccaa7... | 225.073709   | 374.964707   |
| 311 | 20763868 | 20.215977    | 33b82dd5137e8610868966f7738467b3cca7aadee525f0... | 40.291364    | 60.507341    |
| 312 | 20763872 | 59998.50869  | 973b87937c485db542909d2c69730a3d5ce41f78cfe01e... | 60000.0      | 119998.50869 |
| 313 | 20763877 | 160.087258   | 97d6b653d389cb1b1a31e26d555e1e9f182633295b0e88... | 2087.301319  | 2247.388577  |
| 314 | 20763878 | 56908.231643 | 8bd1605839db7cf700ac524012a09c71cf9add77d0edec... | 23055.975936 | 79964.207579 |

```python
last_tx = merged.iloc[-1]
txhash = last_tx.txid
```

```python
md('<br><font size="3.5">Transaction info can also be viewed in the **ATLAS** graphical user interface:<br><br>**USDC:** <br>https://atlas.coinmetrics.io/transaction-details?asset=usdc&tx_hash=' + str(txhash) + '<br>**USDT:** <br>https://atlas.coinmetrics.io/transaction-details?asset=usdt_eth&tx_hash=' + str(txhash))
```

\
Transaction info can also be viewed in the **ATLAS** graphical user interface:\
\
**USDC:**\
<https://atlas.coinmetrics.io/transaction-details?asset=usdc\\&tx\\_hash=8bd1605839db7cf700ac524012a09c71cf9add77d0edec1b81a8342285d092db\\>
**USDT:**\
<https://atlas.coinmetrics.io/transaction-details?asset=usdt\\_eth\\&tx\\_hash=8bd1605839db7cf700ac524012a09c71cf9add77d0edec1b81a8342285d092db>

```python
# Determine total amount of USDT + USDC transferred on a block-by-block basis
both_tx_bbb = pd.DataFrame(merged.groupby('height')['Total Amount'].sum())
both_tx_bbb
```

|          | Total Amount  |
| -------- | ------------- |
| height   |               |
| 20763294 | 161872.380601 |
| 20763296 | 195635.133756 |
| 20763306 | 28362.220094  |
| 20763309 | 7325.095764   |
| 20763316 | 796760.645528 |
| ...      | ...           |
| 20763867 | 374.964707    |
| 20763868 | 60.507341     |
| 20763872 | 119998.50869  |
| 20763877 | 2247.388577   |
| 20763878 | 79964.207579  |

240 rows × 1 columns

```python
ax = sns.lineplot(
    data=both_tx_bbb,
    y=both_tx_bbb['Total Amount'],
    x=both_tx_bbb.index,
    color='purple'
)
ax.set_xlabel("Block Height", fontsize = 15)
ax.set_ylabel("Total Transfer \nAmount", fontsize = 15)
plt.setp(ax.get_xticklabels(), rotation=45)
ax.xaxis.set_ticks(plt.gca().get_xticks())
plt.gca().set_xticklabels(['{:.0f}'.format(x) for x in plt.gca().get_xticks()])
ax.yaxis.set_ticks(plt.gca().get_yticks())
plt.gca().set_yticklabels(['${:,.1f}M'.format(y/1000000) for y in plt.gca().get_yticks()])
plt.ylim([both_tx_bbb['Total Amount'].min(), both_tx_bbb['Total Amount'].max()*1.1])
plt.xlim([both_tx_bbb.index[0], both_tx_bbb.index[-1]])
plt.annotate(
    'Source: Coin Metrics ATLAS',
    xy=(1, -0.195),
    xycoords='axes fraction',
    color='black',
    xytext=(-8, 6), 
    textcoords='offset pixels',
    horizontalalignment='right',
    verticalalignment='bottom'
)
ax.set_title('\nUSDC and USDT\nTransferred in Same Transaction\n', fontsize = 17);
```

<figure><img src="/files/zwXNTtEOZlDCKG7c4mhm" alt=""><figcaption></figcaption></figure>

## Entity-Based Metrics

With **ATLAS,** we can derived our own metrics based on externally-sourced tagged addresses.

In this example, we leverage our catalog of Uniswap liquidity pool contract addresses to **estimate USDC inflows and DEX Supply** for major trading pairs.

#### Retrieving DEX Markets

```python
defi_mkts = client.reference_data_markets(
    exchange="uniswap_v3_eth",
    asset="usdc",
    page_size=1000
).to_dataframe()
```

```python
defi_mkts.tail()
```

|     | market                                      | exchange         | base         | quote | pair              | symbol | type | size\_asset | margin\_asset | strike | ... | order\_amount\_min | order\_amount\_max | order\_price\_increment | order\_price\_min | order\_price\_max | order\_size\_min | order\_taker\_fee | order\_maker\_fee | margin\_trading\_enabled | experimental |
| --- | ------------------------------------------- | ---------------- | ------------ | ----- | ----------------- | ------ | ---- | ----------- | ------------- | ------ | --- | ------------------ | ------------------ | ----------------------- | ----------------- | ----------------- | ---------------- | ----------------- | ----------------- | ------------------------ | ------------ |
| 372 | uniswap\_v3\_eth-agg-wbtc-usdc-spot         | uniswap\_v3\_eth | wbtc         | usdc  | wbtc-usdc         | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         |
| 373 | uniswap\_v3\_eth-agg-wsteth-usdc-spot       | uniswap\_v3\_eth | wsteth       | usdc  | wsteth-usdc       | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         |
| 374 | uniswap\_v3\_eth-agg-xaut\_2\_eth-usdc-spot | uniswap\_v3\_eth | xaut\_2\_eth | usdc  | xaut\_2\_eth-usdc | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         |
| 375 | uniswap\_v3\_eth-agg-xsgd\_eth-usdc-spot    | uniswap\_v3\_eth | xsgd\_eth    | usdc  | xsgd\_eth-usdc    | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         |
| 376 | uniswap\_v3\_eth-agg-yfi-usdc-spot          | uniswap\_v3\_eth | yfi          | usdc  | yfi-usdc          | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>              | \<NA>              | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         |

5 rows × 37 columns

```python
defi_list = defi_mkts.contract_address.dropna().tolist()
defi_list[0:5]
```

```
['2ee7e6e459fffbbc655f09f2e1b3131abf98c397',
 '735a26a57a0a0069dfabd41595a970faf5e1ee8b',
 'bafead7c60ea473758ed6c6021505e8bbd7e8e5d',
 '5e35c4eba72470ee1177dcb14dddf4d9e6d915f4',
 '0eff06710d737c7548c8177ba42e3abdcf3477a7']
```

```python
len(defi_list)
```

```
262
```

```python
day_end = datetime.now()
day_start = day_end - timedelta(days=1)
```

```python
defi_balance = client.get_list_of_balance_updates_v2(
    asset=asset,
    accounts=defi_list,
    start_time=day_start,
    end_time=day_end,
    page_size=10000
).to_dataframe()
```

```python
defi_balance
```

|      | chain\_sequence\_number | account                                  | account\_creation\_height | change        | previous\_balance | new\_balance    | transaction\_sequence\_number | n\_debits | n\_credits | block\_hash                                       | height   | consensus\_time           | credit | total\_received    | total\_sent        | previous\_debit\_height | previous\_credit\_height | previous\_chain\_sequence\_number | txid                                              |
| ---- | ----------------------- | ---------------------------------------- | ------------------------- | ------------- | ----------------- | --------------- | ----------------------------- | --------- | ---------- | ------------------------------------------------- | -------- | ------------------------- | ------ | ------------------ | ------------------ | ----------------------- | ------------------------ | --------------------------------- | ------------------------------------------------- |
| 0    | 89149553831313431       | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 13609065                  | 0.496         | 8838821.586622    | 8838822.082622  | 1                             | 449800    | 479578     | 7ed29942135604bafad3c2820bd06b9757c2ef380e1a87... | 20756748 | 2024-09-15 14:55:23+00:00 | True   | 52777858266.775307 | 52769019444.692688 | 20756718                | 20756719                 | 89149429277261831                 | fa419c42e98bb83b53529891a8ba32768709eb8b254fc2... |
| 1    | 89149738514907201       | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 13609065                  | 588.944621    | 8838822.082622    | 8839411.027243  | 0                             | 449800    | 479579     | 304588d181e196c16aedf2a9721aa6e27ae16484662d13... | 20756791 | 2024-09-15 15:03:59+00:00 | True   | 52777858855.719925 | 52769019444.692688 | 20756718                | 20756748                 | 89149553831313431                 | 9c6bfbf5f155940e832deb6150585f4022f5b07d65c8c8... |
| 2    | 89149777169612812       | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 13609065                  | -287.318755   | 8839411.027243    | 8839123.708488  | 0                             | 449801    | 479579     | 19b757a736ac358fe9f269806a985eb32a8549b01ebfa3... | 20756800 | 2024-09-15 15:05:47+00:00 | False  | 52777858855.719925 | 52769019732.011436 | 20756718                | 20756791                 | 89149738514907201                 | 2095dd79f657e109c82e0589c610a313b873cfa5c5e874... |
| 3    | 89149794349482033       | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 13609065                  | 1801.0        | 8839123.708488    | 8840924.708488  | 0                             | 449801    | 479580     | 148424378d89962dee8f9bd2c63de38cb13ff02297ed31... | 20756804 | 2024-09-15 15:06:35+00:00 | True   | 52777860656.719925 | 52769019732.011436 | 20756800                | 20756791                 | 89149777169612812                 | 09498f7b3ec4307371fc300365d99a0d9eba79a5c69b68... |
| 4    | 89149957558239248       | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 13609065                  | -399.070421   | 8840924.708488    | 8840525.638067  | 0                             | 449802    | 479580     | c51c6f67d2af4dcb65c712c13ed8bfc6f87051b60e2e50... | 20756842 | 2024-09-15 15:14:11+00:00 | False  | 52777860656.719925 | 52769020131.081856 | 20756800                | 20756804                 | 89149794349482033                 | 3c89ecbd238ff474415db6b9d5b4f1821667ea4cb08061... |
| ...  | ...                     | ...                                      | ...                       | ...           | ...               | ...             | ...                           | ...       | ...        | ...                                               | ...      | ...                       | ...    | ...                | ...                | ...                     | ...                      | ...                               | ...                                               |
| 1031 | 89179966494736406       | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 13609065                  | -2.047597     | 11071334.757652   | 11071332.710055 | 0                             | 450269    | 480108     | 9468ed9db151616d84f3206a3c865f15cd1a844d1dabce... | 20763829 | 2024-09-16 14:39:59+00:00 | False  | 52795130311.495941 | 52784058978.785889 | 20763827                | 20763803                 | 89179957904801814                 | b7292f6c1fa6f8e32b9f0934ed1f2ae3564335bee8f755... |
| 1032 | 89179970789703720       | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 13609065                  | -57.627626    | 11071332.710055   | 11071275.082429 | 0                             | 450270    | 480108     | 6db5093f808e69f6e0871973efb6ef56e845c595c7b357... | 20763830 | 2024-09-16 14:40:11+00:00 | False  | 52795130311.495941 | 52784059036.413513 | 20763829                | 20763803                 | 89179966494736406                 | 3aaf4aa1784b63c9498315d8d3e6efb39b81bb95cd03c7... |
| 1033 | 89180005149442094       | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 13609065                  | -28863.215208 | 11071275.082429   | 11042411.867221 | 1                             | 450271    | 480108     | 1edac3c91bbe0bb36fb8c807ed9e41b8f7ee200f16df59... | 20763838 | 2024-09-16 14:41:47+00:00 | False  | 52795130311.495941 | 52784087899.628723 | 20763830                | 20763803                 | 89179970789703720                 | 4756f0560c8b10673f64b914c1bdc938fd14166a0fbfd6... |
| 1034 | 89180005149442110       | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 13609065                  | -29995.561842 | 11042411.867221   | 11012416.305379 | 0                             | 450272    | 480108     | 1edac3c91bbe0bb36fb8c807ed9e41b8f7ee200f16df59... | 20763838 | 2024-09-16 14:41:47+00:00 | False  | 52795130311.495941 | 52784117895.190559 | 20763838                | 20763803                 | 89180005149442094                 | b9ea155e1f0d6e98a1cb085f4fd4b4efcd5e7df9bbdd35... |
| 1035 | 89180056689049603       | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 13609065                  | 4160.547575   | 11012416.305379   | 11016576.852954 | 1                             | 450272    | 480109     | 2b8cab87607901cf45b8739a8ac88ff4c80b3edf3e2bed... | 20763850 | 2024-09-16 14:44:11+00:00 | True   | 52795134472.043518 | 52784117895.190559 | 20763838                | 20763803                 | 89180005149442110                 | 2184156b4af099618f7ce8773c06881027e3ebf711768b... |

1036 rows × 19 columns

#### Retrieve DEX Inflows

```python
defi_inflow = defi_balance[defi_balance.change > 0]
```

```python
largest_inflow = defi_balance.loc[defi_balance['change'].idxmax()]
largest_inflow
```

```
chain_sequence_number                                             89166329973571601
account                                    3416cf6c708da44db2624d63ea0aaef7113527c6
account_creation_height                                                    13609065
change                                                               2561701.979951
previous_balance                                                     8861581.886413
new_balance                                                         11423283.866364
transaction_sequence_number                                                       2
n_debits                                                                     450061
n_credits                                                                    479906
block_hash                        bbce1f72a7384588aaafd053e449b38c93cd07c5d8e997...
height                                                                     20760654
consensus_time                                            2024-09-16 03:59:35+00:00
credit                                                                         True
total_received                                                   52791531415.555038
total_sent                                                       52780108131.688683
previous_debit_height                                                      20760654
previous_credit_height                                                     20760654
previous_chain_sequence_number                                    89166329973571599
txid                              efdc8d8347d53459d3a581d9700b291cb75311f63289ea...
Name: 608, dtype: object
```

```python
largest_inflow.txid
md('<br><font size="3.5">Transaction info can also be viewed in the **ATLAS** graphical user interface:<br><br>**Largest Transaction:** <br>https://atlas.coinmetrics.io/transaction-details?asset=usdc&tx_hash=' + str(largest_inflow.txid) )
```

\
Transaction info can also be viewed in the **ATLAS** graphical user interface:\
\
**Largest Transaction:**\
<https://atlas.coinmetrics.io/transaction-details?asset=usdc\\&tx\\_hash=efdc8d8347d53459d3a581d9700b291cb75311f63289ea0d1859b358d91d8b7f>

```python
defi_inflow = pd.DataFrame(defi_inflow[['consensus_time','account','change','height']])
defi_inflow_sum = pd.DataFrame(defi_inflow.groupby('height')['change'].sum())
```

```python
defi_inflow_sum
```

|          | change       |
| -------- | ------------ |
| height   |              |
| 20756748 | 0.496        |
| 20756791 | 588.944621   |
| 20756804 | 1801.0       |
| 20756883 | 20.0         |
| 20756906 | 28.88709     |
| ...      | ...          |
| 20763786 | 90000.0      |
| 20763794 | 1000.0       |
| 20763798 | 33356.45     |
| 20763803 | 25530.595361 |
| 20763850 | 4160.547575  |

510 rows × 1 columns

```python
ax = defi_inflow_sum['change'].plot.area(color='navy')
plt.title('\n ' + asset.upper() + ' Inflows to Uniswap V3\n',fontdict={'fontsize':23})
ax.set_xlabel("\nBlock Height")
ax.yaxis.set_ticks(plt.gca().get_yticks())
plt.setp(ax.get_xticklabels(), rotation=45)
ax.xaxis.set_ticks(plt.gca().get_xticks())
plt.gca().set_xticklabels(['{:.0f}'.format(x) for x in plt.gca().get_xticks()])
plt.xlim([defi_inflow_sum.index[0], defi_inflow_sum.index[-1]])
plt.annotate(
    'Source: Coin Metrics ATLAS',
    xy=(1, -0.195),
    xycoords='axes fraction',
    color='black',
    xytext=(-8, 6),
    textcoords='offset pixels',
    horizontalalignment='right',
    verticalalignment='bottom'
)
plt.gca().set_yticklabels(['${:,.2f}M'.format(x/1000000) for x in plt.gca().get_yticks()]);
```

<figure><img src="/files/sdJwvruFHxEPKXgbWAYJ" alt=""><figcaption></figcaption></figure>

#### Retrieve DEX Supply

```python
defi_new_bal = pd.DataFrame(defi_balance[['consensus_time','account','new_balance','height']])
defi_new_bal = defi_new_bal.sort_values(by='height')
defi_new_bal = pd.DataFrame(defi_new_bal.drop_duplicates(subset=['account','height'],keep='last'))
```

```python
defi_new_bal
```

|      | consensus\_time           | account                                  | new\_balance    | height   |
| ---- | ------------------------- | ---------------------------------------- | --------------- | -------- |
| 0    | 2024-09-15 14:55:23+00:00 | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 8838822.082622  | 20756748 |
| 1    | 2024-09-15 15:03:59+00:00 | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 8839411.027243  | 20756791 |
| 2    | 2024-09-15 15:05:47+00:00 | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 8839123.708488  | 20756800 |
| 3    | 2024-09-15 15:06:35+00:00 | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 8840924.708488  | 20756804 |
| 4    | 2024-09-15 15:14:11+00:00 | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 8840525.638067  | 20756842 |
| ...  | ...                       | ...                                      | ...             | ...      |
| 1030 | 2024-09-16 14:39:35+00:00 | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 11071334.757652 | 20763827 |
| 1031 | 2024-09-16 14:39:59+00:00 | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 11071332.710055 | 20763829 |
| 1032 | 2024-09-16 14:40:11+00:00 | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 11071275.082429 | 20763830 |
| 1033 | 2024-09-16 14:41:47+00:00 | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 11042411.867221 | 20763838 |
| 1035 | 2024-09-16 14:44:11+00:00 | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 11016576.852954 | 20763850 |

933 rows × 4 columns

```python
bal_updates_pivot = defi_new_bal.pivot(index="height",columns="account",values="new_balance")
bal_updates_pivot = bal_updates_pivot.ffill()
bal_updates_pivot = bal_updates_pivot.bfill()
```

```python
bal_updates_w_zeros = bal_updates_pivot.fillna(0)
```

```python
column_list = list(bal_updates_w_zeros)
bal_updates_w_zeros["sum"] =bal_updates_w_zeros[column_list].sum(axis=1)
```

```python
bal_updates_w_zeros
```

| account  | 3416cf6c708da44db2624d63ea0aaef7113527c6 | 7858e59e0c01ea06df3af3d20ac7b0003275d4bf | ee4cf3b78a74affa38c6a926282bcd8b5952818d | sum          |
| -------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | ------------ |
| height   |                                          |                                          |                                          |              |
| 20756748 | 8838822.082622                           | 1201350.942506                           | 9178.353003                              | 1.004935e+07 |
| 20756791 | 8839411.027243                           | 1201350.942506                           | 9178.353003                              | 1.004994e+07 |
| 20756800 | 8839123.708488                           | 1201350.942506                           | 9178.353003                              | 1.004965e+07 |
| 20756804 | 8840924.708488                           | 1201350.942506                           | 9178.353003                              | 1.005145e+07 |
| 20756842 | 8840525.638067                           | 1201350.942506                           | 9178.353003                              | 1.005105e+07 |
| ...      | ...                                      | ...                                      | ...                                      | ...          |
| 20763827 | 11071334.757652                          | 1250073.026459                           | 9178.353003                              | 1.233059e+07 |
| 20763829 | 11071332.710055                          | 1250073.026459                           | 9178.353003                              | 1.233058e+07 |
| 20763830 | 11071275.082429                          | 1250073.026459                           | 9178.353003                              | 1.233053e+07 |
| 20763838 | 11042411.867221                          | 1250073.026459                           | 9178.353003                              | 1.230166e+07 |
| 20763850 | 11016576.852954                          | 1250073.026459                           | 9178.353003                              | 1.227583e+07 |

926 rows × 4 columns

```python
ax = bal_updates_w_zeros['sum'].plot.area(color='navy')
plt.title('\n ' + asset.upper() + ' Supply on Uniswap V3\n',fontdict={'fontsize':23})
plt.suptitle('\n\n\nTracked Liquidity Pools\n',size=13.5)
ax.set_xlabel("\nBlock Height")
ax.yaxis.set_ticks(plt.gca().get_yticks())
plt.setp(ax.get_xticklabels(), rotation=45)
ax.xaxis.set_ticks(plt.gca().get_xticks())
plt.gca().set_xticklabels(['{:.0f}'.format(x) for x in plt.gca().get_xticks()])
plt.xlim([bal_updates_w_zeros.index[0], bal_updates_w_zeros.index[-1]])
plt.annotate('Source: Coin Metrics ATLAS',xy=(1, -0.195), xycoords='axes fraction',color='black',xytext=(-8, 6), textcoords='offset pixels',horizontalalignment='right',verticalalignment='bottom')
plt.gca().set_yticklabels(['${:,.2f}M'.format(x/1000000) for x in plt.gca().get_yticks()]);
```

<figure><img src="/files/5hsc6hKscIbUAQAazMeh" alt=""><figcaption></figcaption></figure>


# Applying Different Types of Marketcap Metrics

![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/Demo%20Asset%20Resources/Demo%20Covers/CM-Demo-market_cap_metrics-Cover.png)

This notebook demonstrates basic functionality offered by the Coin Metrics Python API Client and Network Data Pro.

Coin Metrics offers a vast assortment of data for hundreds of cryptoassets. The Python API Client allows for easy access to this data using Python without needing to create your own wrappers using `requests` and other such libraries.

### Resources

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics.
* The [Coin Metrics Product Documentation](https://docs.coinmetrics.io/info) gives detailed, conceptual explanations of the data that Coin Metrics offers.
* The [API Spec](https://docs.coinmetrics.io/python-api-client/reference) contains a full list of functions.

### File Download

Download the entire notebook as either a jupyter notebook to run yourself or as a pdf from the two links below

{% file src="/files/US0F5AJnECyDv5SGmwbJ" %}

{% file src="/files/DjPY5Astj7ZGbtoTupQU" %}

### Setup

```python
from os import environ
import sys
import pandas as pd
import numpy as np
import seaborn as sns
import logging
from datetime import date, datetime, timedelta
from coinmetrics.api_client import CoinMetricsClient
import json
import logging
import matplotlib.ticker as mticker
from matplotlib.dates import DateFormatter
from matplotlib.ticker import FuncFormatter
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# %matplotlib inline
```

```python
logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S'
)
```

```python
end_time = datetime.today().date()
start_time = end_time - timedelta(days=90)
```

```python
# We recommend privately storing your API key in your local environment.
try:
    api_key = environ["CM_API_KEY"]
    logging.info("Using API key found in environment")
except KeyError:
    api_key = ""
    logging.info("API key not found. Using community client")


client = CoinMetricsClient(api_key)
```

```
2024-09-16 15:00:54 INFO     Using API key found in environment
```

## Market Cap Based on Verified On-Chain Supply

In order to trustlessly verify market capitalization, Coin Metrics directly indexes the blockchain to independently validate the amount of circulating supply.

The **CapMrktCurUSD** metric offers the most reliable measure of asset supply, with the trade-off of slightly limited asset coverage.

```python
df_reference_capmkrtcur = client.reference_data_asset_metrics(metrics='CapMrktCurUSD').to_dataframe()
```

```python
df_reference_capmkrtcur
```

|   | metric        | full\_name                                  | description                                       | product      | category | subcategory           | unit | data\_type | type    |
| - | ------------- | ------------------------------------------- | ------------------------------------------------- | ------------ | -------- | --------------------- | ---- | ---------- | ------- |
| 0 | CapMrktCurUSD | Capitalization, market, current supply, USD | The sum USD value of the current supply. Also ... | Network Data | Market   | Market Capitalization | USD  | decimal    | Product |

```python
list_capmrktcur_assets = [a['asset'] for a in client.catalog_asset_metrics_v2(metrics='CapMrktCurUSD')]
```

```python
print(f"Number of assets with Market Cap: {len(list_capmrktcur_assets)}")
```

```
Number of assets with Market Cap: 153
```

```python
capmrktcur = client.get_asset_metrics(
    assets=list_capmrktcur_assets,
    metrics='CapMrktCurUSD',
    start_time=start_time,
    end_time=end_time,
    page_size=1000
).to_dataframe()
```

```python
capmrktcur.head()
```

|   | asset | time                      | CapMrktCurUSD    |
| - | ----- | ------------------------- | ---------------- |
| 0 | 1inch | 2024-06-18 00:00:00+00:00 | 601806926.332868 |
| 1 | 1inch | 2024-06-19 00:00:00+00:00 | 669292018.418909 |
| 2 | 1inch | 2024-06-20 00:00:00+00:00 | 638964090.844949 |
| 3 | 1inch | 2024-06-21 00:00:00+00:00 | 602574091.306198 |
| 4 | 1inch | 2024-06-22 00:00:00+00:00 | 614578628.290457 |

```python
capmrktcur_pivot = capmrktcur.pivot(index='time',columns='asset',values='CapMrktCurUSD')
```

```python
capmrktcur_pivot['Total Cap'] = capmrktcur_pivot.sum(axis=1)
```

```python
capmrktcur_pivot
```

| asset                     | 1inch            | aave              | ada                | ae\_eth        | algo             | alpha           | ant              | avaxc             | avaxp              | avaxx            | ... | xem              | xlm                | xmr               | xrp                | xvg               | yfi              | zec              | zil\_eth       | zrx              | Total Cap    |
| ------------------------- | ---------------- | ----------------- | ------------------ | -------------- | ---------------- | --------------- | ---------------- | ----------------- | ------------------ | ---------------- | --- | ---------------- | ------------------ | ----------------- | ------------------ | ----------------- | ---------------- | ---------------- | -------------- | ---------------- | ------------ |
| time                      |                  |                   |                    |                |                  |                 |                  |                   |                    |                  |     |                  |                    |                   |                    |                   |                  |                  |                |                  |              |
| 2024-06-18 00:00:00+00:00 | 601806926.332868 | 1306437999.295638 | 13424730961.241064 | 8832610.158148 | 1339360258.68476 | 80619082.899196 | 352010549.615121 | 2388322499.746325 | 12838611730.911514 | 713309094.675862 | ... | 126980953.174033 | 9610695086.9286    | 3054203115.691232 | 49052418232.612778 | 6724446390.59112  | 212203308.017145 | 311270858.886043 | 2305684.889749 | 336195840.86146  | 2.229542e+12 |
| 2024-06-19 00:00:00+00:00 | 669292018.418909 | 1400637382.569757 | 13423644078.574947 | 9099450.288229 | 1382363720.84246 | 81094309.783218 | 356082846.868479 | 2414215130.39066  | 12984873845.978542 | 721319158.751801 | ... | 126674840.822162 | 9820585062.035196  | 3020726381.652565 | 49268483622.64537  | 6829094885.807176 | 217383791.66592  | 303049562.236562 | 2343771.624651 | 353937035.765548 | 2.237127e+12 |
| 2024-06-20 00:00:00+00:00 | 638964090.844949 | 1358825403.114587 | 13453912813.410269 | 9227041.800181 | 1383256522.94337 | 84522774.743021 | 350618174.842791 | 2471190230.800348 | 13321331442.85092  | 739621942.386422 | ... | 132373773.581515 | 9896582194.97669   | 3046146822.064857 | 48866370533.68499  | 6940480158.50313  | 216572442.484699 | 303519008.658101 | 2350164.716928 | 360417663.325525 | 2.231134e+12 |
| 2024-06-21 00:00:00+00:00 | 602574091.306198 | 1310711198.734895 | 13174182377.372046 | 9316984.240167 | 1391489499.4855  | 82641066.611264 | 353348338.081292 | 2456046637.217133 | 13261561451.744013 | 738741018.612855 | ... | 129064560.654881 | 9697203679.229527  | 2863904454.917198 | 48889782361.155952 | 6827462838.701295 | 213908822.241556 | 304438515.678476 | 2329727.25247  | 359650229.244396 | 2.214003e+12 |
| 2024-06-22 00:00:00+00:00 | 614578628.290457 | 1303628383.546602 | 13475267480.649416 | 9080680.725316 | 1339705315.54913 | 81442254.171929 | 351060582.670069 | 2342337218.532271 | 12381600154.273886 | 639220357.617559 | ... | 129465576.97741  | 9581669381.902111  | 2995259845.285223 | 48655540991.974068 | 7013277883.554922 | 214667247.899236 | 304854610.414748 | 2373452.370937 | 359377609.401009 | 2.213118e+12 |
| ...                       | ...              | ...               | ...                | ...            | ...              | ...             | ...              | ...               | ...                | ...              | ... | ...              | ...                | ...               | ...                | ...               | ...              | ...              | ...            | ...              | ...          |
| 2024-09-11 00:00:00+00:00 | 370795675.998745 | 2394157493.994128 | \<NA>              | 7086282.571463 | 1272138738.08548 | 55696931.758843 | 236080888.610476 | 2381194755.211256 | 11102231898.578779 | 561574500.581236 | ... | 150087591.429489 | 9790016731.104605  | 3120199983.171181 | 53527147783.98262  | 6095473842.098846 | 178156431.46414  | 459255827.96882  | 1810381.365383 | 277605159.385683 | 1.915254e+12 |
| 2024-09-12 00:00:00+00:00 | 384232522.92621  | 2327005794.360288 | \<NA>              | 7371122.985217 | 1299855257.21774 | 57785093.830921 | 236071341.779449 | 2452806790.290408 | 11431048630.015509 | 578191291.778559 | ... | 154361726.733294 | 9997934147.338022  | 3105706133.057552 | 56215867452.010078 | 6267860632.323607 | 178663216.244342 | 454920192.594087 | 1848757.475975 | 287032283.247654 | 1.939759e+12 |
| 2024-09-13 00:00:00+00:00 | 400557336.250521 | 2311665536.23392  | \<NA>              | 7832592.091806 | 1330044901.28941 | 58858736.968168 | 240512223.869399 | 2545118411.801699 | 11866069991.509184 | 600182210.371027 | ... | 157141907.013232 | 10153491708.845804 | 3064948299.210351 | 57221528978.257057 | 6405467690.943713 | 179478034.544076 | 473244206.395726 | 1885345.54056  | 297832199.512269 | 2.004984e+12 |
| 2024-09-14 00:00:00+00:00 | 393157001.05276  | 2244118799.251264 | \<NA>              | 7425554.562711 | 1312275710.52702 | 59357434.029832 | 241324187.737431 | 2585622436.498027 | 12055268780.843508 | 609742449.013718 | ... | 163021038.424844 | 10239633535.133228 | 3044883873.886052 | 59683009523.175056 | 6404671209.191757 | 180551959.332886 | 474742175.553408 | 1876469.594495 | 293961123.7075   | 1.991043e+12 |
| 2024-09-15 00:00:00+00:00 | 368561790.184033 | 2297900163.986864 | \<NA>              | 7423784.032991 | 1265330435.59742 | 56307463.023177 | 237024036.656687 | 2436809618.506954 | 11348207028.418108 | 574093158.696821 | ... | 160791667.882743 | 10027244938.128235 | 3063351773.476915 | 57120501674.456192 | 6073655509.257232 | 179087880.508707 | 453729407.723865 | 1816117.52146  | 286316863.361929 | 1.950918e+12 |

90 rows × 137 columns

```python
current_market_cap_last = capmrktcur_pivot['Total Cap'][-1]

formatted_market_cap = '${:,.2f}'.format(current_market_cap_last)

print('Current Market Cap based on verified on-chain supply: ' + formatted_market_cap)
```

```
Current Market Cap based on verified on-chain supply: $1,950,918,193,666.17
```

```python
plt.figure(figsize=(8, 6))
capmrktcur_pivot['Total Cap'].plot(kind='area', stacked=True)

# Set the title and labels
plt.title('Total Crypto Market Cap \n(CapMrktCurUSD)\n',fontsize=16)
plt.xlabel('') 
plt.ylabel('Market Cap (USD)',fontsize=14)
plt.grid(True, alpha=0.3, linestyle='--')
formatter = mticker.FuncFormatter(lambda x, pos: '${:,.2f}T'.format(x/1000000000000))
plt.gca().yaxis.set_major_formatter(formatter)

plt.savefig("ndp_capmrktcurusd.png");
```

<figure><img src="/files/ixcKPx0z1vwfYGUy32ft" alt=""><figcaption></figcaption></figure>

## Estimated Market Cap

Due to the complexity of running blockchain nodes, some assets pose additional challenges in directly verifying supply data. Coin Metrics partners with CoinGecko to offer a "estimated supply" metric, sourced from a variety of third-party sources like token projects or blockchain explorers.

The **CapMrktEstUSD** metric offers slightly wider asset coverage, with the trade-off of leveraging more "trusted" sources for supply.

```python
df_reference_capmrktest = client.reference_data_asset_metrics(metrics='CapMrktEstUSD').to_dataframe()
```

```python
df_reference_capmrktest
```

|   | metric        | full\_name                                    | description                                       | product      | category | subcategory           | unit | data\_type | type    |
| - | ------------- | --------------------------------------------- | ------------------------------------------------- | ------------ | -------- | --------------------- | ---- | ---------- | ------- |
| 0 | CapMrktEstUSD | Capitalization, market, estimated supply, USD | The sum USD value of the estimated supply in c... | Network Data | Market   | Market Capitalization | USD  | decimal    | Product |

```python
list_capmrktest_assets = [a['asset'] for a in client.catalog_asset_metrics_v2(metrics='CapMrktEstUSD')]
```

```python
capmrktest = client.get_asset_metrics(
    assets=list_capmrktest_assets,
    metrics='CapMrktEstUSD',
    start_time=start_time,
    end_time=end_time,
    page_size=10000
).to_dataframe()
```

```python
capmrktest_pivot = capmrktest.pivot(index='time',columns='asset',values='CapMrktEstUSD')
```

```python
capmrktest_pivot['Total Cap'] = capmrktest_pivot.sum(axis=1)
```

```python
est_market_cap_last = capmrktest_pivot['Total Cap'][-1]

formatted_est_market_cap = '${:,.2f}'.format(est_market_cap_last)

print('Estimated Market Cap based on estimated supply (3rd-party sources): ' + formatted_est_market_cap)
```

```
Estimated Market Cap based on estimated supply (3rd-party sources): $2,084,782,376,216.38
```

```python
plt.figure(figsize=(8, 6))

capmrktest_pivot['Total Cap'].plot(kind='area', stacked=True, color='green')
plt.title('Total Crypto Market Cap \n(CapMrktEstUSD)\n',fontsize=16)
plt.xlabel('') 
plt.ylabel('Market Cap (USD)',fontsize=14)
plt.grid(True, alpha=0.3, linestyle='--')

formatter = mticker.FuncFormatter(lambda x, pos: '${:,.2f}T'.format(x/1000000000000))
plt.gca().yaxis.set_major_formatter(formatter)

plt.show()
```

<figure><img src="/files/nPd92jkVOlWvIMq22JG8" alt=""><figcaption></figcaption></figure>

## Free Float Market Cap

While traditional market capitalization metrics rely on circulating supply to quantify the aggregate value of an asset, circulating supply may not necessarily be the appropriate metric for measuring the liquid, readily-available count of units available on the markert.

Free Float Market Capitalization, or **CapMrktFFUSD**, is a measure of the market value of an asset’s supply that is issued and available to market participants. This excludes supply that is held by insiders (i.e. protocol treasuries), controlling investors, and long term strategic holders (units with 5+ years of inactivity).

```python
df_reference_capmrktffusd = client.reference_data_asset_metrics(metrics='CapMrktFFUSD').to_dataframe()
```

```python
df_reference_capmrktffusd
```

|   | metric       | full\_name                              | description                                       | product      | category | subcategory           | unit | data\_type | type    |
| - | ------------ | --------------------------------------- | ------------------------------------------------- | ------------ | -------- | --------------------- | ---- | ---------- | ------- |
| 0 | CapMrktFFUSD | Capitalization, market, free float, USD | The sum USD value of the current free float su... | Network Data | Market   | Market Capitalization | USD  | decimal    | Product |

```python
catalog_ff = client.catalog_asset_metrics_v2(metrics='CapMrktFFUSD').to_list()
```

```python
catalog_ff[:5]
```

```
[{'asset': '1inch',
  'metrics': [{'metric': 'CapMrktFFUSD',
    'frequencies': [{'frequency': '1d',
      'min_time': '2020-12-26T00:00:00.000000000Z',
      'max_time': '2024-09-15T00:00:00.000000000Z',
      'community': True}]}]},
 {'asset': 'aave',
  'metrics': [{'metric': 'CapMrktFFUSD',
    'frequencies': [{'frequency': '1d',
      'min_time': '2020-10-10T00:00:00.000000000Z',
      'max_time': '2024-09-15T00:00:00.000000000Z',
      'community': True}]}]},
 {'asset': 'ada',
  'metrics': [{'metric': 'CapMrktFFUSD',
    'frequencies': [{'frequency': '1d',
      'min_time': '2017-12-01T00:00:00.000000000Z',
      'max_time': '2024-09-08T00:00:00.000000000Z',
      'community': True}]}]},
 {'asset': 'aion_eth',
  'metrics': [{'metric': 'CapMrktFFUSD',
    'frequencies': [{'frequency': '1d',
      'min_time': '2017-12-22T00:00:00.000000000Z',
      'max_time': '2023-03-03T00:00:00.000000000Z',
      'community': True}]}]},
 {'asset': 'algo',
  'metrics': [{'metric': 'CapMrktFFUSD',
    'frequencies': [{'frequency': '1d',
      'min_time': '2019-06-22T00:00:00.000000000Z',
      'max_time': '2024-09-15T00:00:00.000000000Z',
      'community': True}]}]}]
```

#### Comparing BTC market capitalization with BTC free float market capitalization

```python
btc_ff_and_cur = client.get_asset_metrics(
    assets='btc',
    metrics=['CapMrktFFUSD','CapMrktCurUSD'],
    start_time=start_time,
    end_time=end_time
).to_dataframe()
```

```python
btc_ff_and_cur
```

|     | asset | time                      | CapMrktCurUSD        | CapMrktFFUSD        |
| --- | ----- | ------------------------- | -------------------- | ------------------- |
| 0   | btc   | 2024-06-18 00:00:00+00:00 | 1283620750458.029053 | 892930547450.634399 |
| 1   | btc   | 2024-06-19 00:00:00+00:00 | 1279047103315.121094 | 889718923157.247559 |
| 2   | btc   | 2024-06-20 00:00:00+00:00 | 1279448394407.814453 | 889934057173.784424 |
| 3   | btc   | 2024-06-21 00:00:00+00:00 | 1263474830674.393311 | 878772804275.674194 |
| 4   | btc   | 2024-06-22 00:00:00+00:00 | 1266898089628.073975 | 881035407234.292114 |
| ... | ...   | ...                       | ...                  | ...                 |
| 85  | btc   | 2024-09-11 00:00:00+00:00 | 1133986205007.474609 | 785339554938.315308 |
| 86  | btc   | 2024-09-12 00:00:00+00:00 | 1148145814023.138916 | 795139187847.963867 |
| 87  | btc   | 2024-09-13 00:00:00+00:00 | 1195818457804.406494 | 828180803304.224121 |
| 88  | btc   | 2024-09-14 00:00:00+00:00 | 1185380845498.997314 | 820893975766.963257 |
| 89  | btc   | 2024-09-15 00:00:00+00:00 | 1168079552742.053711 | 808927520410.375    |

90 rows × 4 columns

```python
plt.figure(figsize=(8, 6))

plt.plot(btc_ff_and_cur['time'], btc_ff_and_cur['CapMrktCurUSD'] / 1e9, label='Market Cap', color='blue')
plt.plot(btc_ff_and_cur['time'], btc_ff_and_cur['CapMrktFFUSD'] / 1e9, label='Free Float Market Cap', color='green')

plt.title('Bitcoin Market Cap Over Time\n(Circulating vs. Free Float Supply)\n', fontsize=16)
plt.xlabel('')
plt.ylabel('Market Cap (USD)', fontsize=14)
plt.grid(True, alpha=0.3, linestyle='--')

formatter = mticker.FuncFormatter(lambda x, pos: '${:,.0f}B'.format(x))
plt.gca().yaxis.set_major_formatter(formatter)
plt.gca().xaxis.set_major_locator(mdates.AutoDateLocator())
plt.gca().xaxis.set_major_formatter(mdates.ConciseDateFormatter(mdates.AutoDateLocator()))

plt.legend()

plt.show()

```

<figure><img src="/files/0JfnlooQVUSu544YMReO" alt=""><figcaption></figcaption></figure>


# Comparing the Dominance of Mining Pools Using ATLAS

<figure><img src="https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/Demo%20Asset%20Resources/CM-Demo-miner_signatures.png" alt=""><figcaption></figcaption></figure>

For much of its history, the Bitcoin mining industry has been notoriously opaque. Luckily, it has become a common practice for many BTC mining pools to leave a subtle "miner signature" in each block's coinbase transaction (not to be confused with the popular crypto exchange by the same name). This transaction contains the miner reward— currently 6.25 BTC per block—but also leaves some extra space for arbitrary data, allowing the pool to publicly assert their claim. Using ATLAS v2, we're able to extract this miner signature, enabling us to derive a variety of mining pool metrics.

### Resources

This notebook demonstrates basic functionality offered by the Coin Metrics Python API Client and ATLAS blockchain search engine.

Coin Metrics offers a vast assortment of data for hundreds of cryptoassets. The Python API Client allows for easy access to this data using Python without needing to create your own wrappers using `requests` and other such libraries.

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics.
* The [Coin Metrics Product Documentation](https://docs.coinmetrics.io/info) gives detailed, conceptual explanations of the data that Coin Metrics offers.
* The [API Spec](https://docs.coinmetrics.io/python-api-client/reference) contains a full list of functions.

### File Download

Download the entire notebook as either a jupyter notebook to run yourself or as a pdf from the two links below

{% file src="/files/KkM8BrLgFnuJjkUTKX15" %}
PDF Version of notebook for easy offline viewing
{% endfile %}

{% file src="/files/neVE08ImJRFjk2GzivHg" %}
Jupyter notebook to run code locally
{% endfile %}

### Notebook Setup

```python
from os import environ
import sys
import pandas as pd
import numpy as np
import logging
from datetime import date, datetime, timedelta
from coinmetrics.api_client import CoinMetricsClient
import json
import logging
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
from matplotlib.ticker import FormatStrFormatter, FuncFormatter
from matplotlib import font_manager
import cmasher as cmr
import re
# %matplotlib inline
import plotly
from plotly.subplots import make_subplots
```

```python
logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S'
)
```

```python
# We recommend privately storing your API key in your local environment.
try:
    api_key = environ["CM_API_KEY"]
    logging.info("Using API key found in environment")
except KeyError:
    api_key = ""
    logging.info("API key not found. Using community client")

client = CoinMetricsClient(api_key)
```

```
2024-10-04 13:46:00 INFO     Using API key found in environment
```

```python
colors = np.unique(cmr.take_cmap_colors('Set3', 15, return_fmt='hex'))
colors
```

```
array(['#80B1D3', '#8DD3C7', '#B3DE69', '#BC80BD', '#BEBADA', '#CCEBC5',
       '#D9D9D9', '#FB8072', '#FCCDE5', '#FDB462', '#FFED6F', '#FFFFB3'],
      dtype='<U7')
```

## ATLAS V2

### Retrieve Block Info

```python
block_info = client.get_list_of_blocks_v2(
    asset='btc',
    start_time=datetime.now()-timedelta(days=365),
    page_size=10000
).parallel(time_increment=timedelta(days=1)).to_dataframe()
block_info['extra_data'] = block_info['extra_data'].astype(str)
```

```
Exporting to dataframe type: 100%|██████████| 366/366 [00:06<00:00, 58.56it/s] 
```

```python
block_info.head()
```

|   | block\_hash                                       | height | consensus\_time           | miner\_time               | n\_transactions | n\_balance\_updates | parent\_block\_hash                               | nonce    | extra\_data                                       | version   | difficulty            | physical\_size | consensus\_size | consensus\_size\_limit |
| - | ------------------------------------------------- | ------ | ------------------------- | ------------------------- | --------------- | ------------------- | ------------------------------------------------- | -------- | ------------------------------------------------- | --------- | --------------------- | -------------- | --------------- | ---------------------- |
| 0 | 00000000000000000003cd8c9919b1073bab32cee67bfb... | 810761 | 2023-10-05 13:54:00+00:00 | 2023-10-05 15:21:03+00:00 | 3658            | 22668               | 00000000000000000002667c723b1a1f559ed920504ab6... | 3789b287 | 03095f0c1b4d696e656420627920416e74506f6f6c3830... | 545259520 | 57321508229258.039062 | 1543713        | 3993396         | 4000000                |
| 1 | 000000000000000000000d070d5b4fb5c69ee6bae4bab6... | 810762 | 2023-10-05 14:04:54+00:00 | 2023-10-05 15:26:11+00:00 | 2689            | 18732               | 00000000000000000003cd8c9919b1073bab32cee67bfb... | 388afcd5 | 030a5f0c45022f62696e616e63652f323139fabe6d6d6d... | 536993792 | 57321508229258.039062 | 1494856        | 3993547         | 4000000                |
| 2 | 00000000000000000004090783eb83951d6d9c91dd88f3... | 810763 | 2023-10-05 14:28:43+00:00 | 2023-10-05 15:33:08+00:00 | 2528            | 17306               | 000000000000000000000d070d5b4fb5c69ee6bae4bab6... | 9b7ba148 | 030b5f0c192f5669614254432f4d696e6564206279207a... | 536928256 | 57321508229258.039062 | 1422613        | 3993322         | 4000000                |
| 3 | 00000000000000000004cd165ee9f93e68460c37173027... | 810764 | 2023-10-05 14:36:46+00:00 | 2023-10-05 15:40:56+00:00 | 3227            | 20335               | 00000000000000000004090783eb83951d6d9c91dd88f3... | 003804fb | 030c5f0c194d696e656420627920416e74506f6f6c20f8... | 805298176 | 57321508229258.039062 | 1572755        | 3993278         | 4000000                |
| 4 | 00000000000000000000fb654d8199a1fc240af3bbc173... | 810765 | 2023-10-05 14:57:48+00:00 | 2023-10-05 15:50:03+00:00 | 3078            | 19352               | 00000000000000000004cd165ee9f93e68460c37173027... | 903b489a | 030d5f0c2cfabe6d6d0d426074ccdd9e3b0fe208ab9af1... | 538968064 | 57321508229258.039062 | 1515726        | 3997698         | 4000000                |

```python
# Assign 'empty' to rows where n_transactions == 1
block_info.loc[block_info['n_transactions'] == 1, 'category'] = 'Empty'

# Assign 'not empty' to remaining rows
block_info.loc[block_info['n_transactions'] != 1, 'category'] = 'Not Empty'
```

```python
block_info['extra_data'][0]
```

```
'03095f0c1b4d696e656420627920416e74506f6f6c383036f800c8022ace0b75fabe6d6d7a90b864b377b7d7de125f87ab7890c46a47d58edcd9d602a6758485a2d7a7c2020000000000000026bb0000d455000000000000'
```

```python
def convert_to_human_readable_ascii(s):
    # Check if the input string is a valid hexadecimal string
    if all(c in '0123456789abcdefABCDEF' for c in s):
        # Convert the input string to bytes
        b = bytes.fromhex(s)
        # Decode the bytes using the ISO-8859-1 encoding
        result = b.decode('ISO-8859-1')
        return result
    else:
        # Return an error message if the input string is not a valid hexadecimal string
        return 'Error: input is not a valid hexadecimal string'
```

```python
block_info['miner_tag'] = block_info['extra_data'].apply(convert_to_human_readable_ascii)
```

```python
block_signed = pd.DataFrame(block_info[['miner_tag','height','consensus_time','category']])
block_signed
```

|       | miner\_tag                                          | height | consensus\_time           | category  |
| ----- | --------------------------------------------------- | ------ | ------------------------- | --------- |
| 0     | \t\_ Mined by AntPool806ø�È\*Î uú¾mmz¸d³w·×Þ... | 810761 | 2023-10-05 13:54:00+00:00 | Not Empty |
| 1     | \n\_ E/binance/219ú¾mmm¡¾¼a04Vy>IC°Jgò ¡Ð0...  | 810762 | 2023-10-05 14:04:54+00:00 | Not Empty |
| 2     |  \_ /ViaBTC/Mined by z180203/,ú¾mmñÊ1ä¾Ú!³K...  | 810763 | 2023-10-05 14:28:43+00:00 | Not Empty |
| 3     |  \_ Mined by AntPool ø�¢1ê%-ú¾mm»âHjéZ¾®¨!M...  | 810764 | 2023-10-05 14:36:46+00:00 | Not Empty |
| 4     | \r\_ ,ú¾mm\rB\`tÌÝ;â«ñ\tÆ¢èür¹³a\rmá\rÚ... | 810765 | 2023-10-05 14:57:48+00:00 | Not Empty |
| ...   | ...                                                 | ...    | ...                       | ...       |
| 53385 | /\r< OCEAN.XYZ >3OD�ã.³Lð\n������        | 864146 | 2024-10-04 15:50:04+00:00 | Not Empty |
| 53386 | /\r,ú¾mm÷$@oÈ$\~¸ÑÆn¹Ô3 ñîõä ¼���...  | 864147 | 2024-10-04 15:51:50+00:00 | Not Empty |
| 53387 | /\rc�g/Foundry USA Pool #dropgold/+J�½­�...   | 864148 | 2024-10-04 15:56:39+00:00 | Not Empty |
| 53388 | /\rMined by AntPool èAx®øú¾mm6úq2iF...   | 864149 | 2024-10-04 15:56:44+00:00 | Not Empty |
| 53389 | /\rMined by AntPool �µóú¾mm¹ý½kØ]"...   | 864150 | 2024-10-04 16:22:20+00:00 | Not Empty |

53390 rows × 4 columns

```python
# List of strings included in coinbase signature
miners = ['AntPool', 'ViaBTC', 'binance', 'Binance', 'Foundry', 'Luxor', 
          'SlushPool', 'slush', 'BTC.com','BTC.COM','btc.com','btccom',
          'bitdeer','btcpool', 'F2Pool', 'poolin','xxxxxx.com','CKPool', 
          'BTC.TOP', 'BTCC', 'MARA Pool', 'Mara Pool', 'SpiderPool']
```

```python
def detect_keywords(df, column, keywords):
    # Create a new column called 'miner'
    df['miner'] = None
    # Iterate over the miner names
    for miner in miners:
        # Use the update method to detect the miner name in the specified column
        # df['miner'].update(df[column].str.extract(rf'({miner})', expand=False))
        df.update({'miner':df[column].str.extract(rf'({miner})', expand=False)})
    # Replace any rows where the 'miner' column is None with 'Unknown'
    df['miner'] = df['miner'].replace({None: 'Other'})
    return df
```

```python
miners_tagged = detect_keywords(block_signed, 'miner_tag', miners)
miners_tagged = miners_tagged.set_index('consensus_time')
miners_tagged
```

|                           | miner\_tag                                          | height | category  | miner   |
| ------------------------- | --------------------------------------------------- | ------ | --------- | ------- |
| consensus\_time           |                                                     |        |           |         |
| 2023-10-05 13:54:00+00:00 | \t\_ Mined by AntPool806ø�È\*Î uú¾mmz¸d³w·×Þ... | 810761 | Not Empty | AntPool |
| 2023-10-05 14:04:54+00:00 | \n\_ E/binance/219ú¾mmm¡¾¼a04Vy>IC°Jgò ¡Ð0...  | 810762 | Not Empty | binance |
| 2023-10-05 14:28:43+00:00 |  \_ /ViaBTC/Mined by z180203/,ú¾mmñÊ1ä¾Ú!³K...  | 810763 | Not Empty | ViaBTC  |
| 2023-10-05 14:36:46+00:00 |  \_ Mined by AntPool ø�¢1ê%-ú¾mm»âHjéZ¾®¨!M...  | 810764 | Not Empty | AntPool |
| 2023-10-05 14:57:48+00:00 | \r\_ ,ú¾mm\rB\`tÌÝ;â«ñ\tÆ¢èür¹³a\rmá\rÚ... | 810765 | Not Empty | F2Pool  |
| ...                       | ...                                                 | ...    | ...       | ...     |
| 2024-10-04 15:50:04+00:00 | /\r< OCEAN.XYZ >3OD�ã.³Lð\n������        | 864146 | Not Empty | Other   |
| 2024-10-04 15:51:50+00:00 | /\r,ú¾mm÷$@oÈ$\~¸ÑÆn¹Ô3 ñîõä ¼���...  | 864147 | Not Empty | F2Pool  |
| 2024-10-04 15:56:39+00:00 | /\rc�g/Foundry USA Pool #dropgold/+J�½­�...   | 864148 | Not Empty | Foundry |
| 2024-10-04 15:56:44+00:00 | /\rMined by AntPool èAx®øú¾mm6úq2iF...   | 864149 | Not Empty | AntPool |
| 2024-10-04 16:22:20+00:00 | /\rMined by AntPool �µóú¾mm¹ý½kØ]"...   | 864150 | Not Empty | AntPool |

53390 rows × 4 columns

```python
def transform_index_to_date(index):
    datetime_index = pd.to_datetime(index)
    date_index = [datetime.date(datetime_obj) for datetime_obj in datetime_index]
    return date_index
```

```python
date_index = transform_index_to_date(miners_tagged.index)
miners_tagged.index = pd.to_datetime(date_index)
```

```python
miners_tagged
```

|            | miner\_tag                                          | height | category  | miner   |
| ---------- | --------------------------------------------------- | ------ | --------- | ------- |
| 2023-10-05 | \t\_ Mined by AntPool806ø�È\*Î uú¾mmz¸d³w·×Þ... | 810761 | Not Empty | AntPool |
| 2023-10-05 | \n\_ E/binance/219ú¾mmm¡¾¼a04Vy>IC°Jgò ¡Ð0...  | 810762 | Not Empty | binance |
| 2023-10-05 |  \_ /ViaBTC/Mined by z180203/,ú¾mmñÊ1ä¾Ú!³K...  | 810763 | Not Empty | ViaBTC  |
| 2023-10-05 |  \_ Mined by AntPool ø�¢1ê%-ú¾mm»âHjéZ¾®¨!M...  | 810764 | Not Empty | AntPool |
| 2023-10-05 | \r\_ ,ú¾mm\rB\`tÌÝ;â«ñ\tÆ¢èür¹³a\rmá\rÚ... | 810765 | Not Empty | F2Pool  |
| ...        | ...                                                 | ...    | ...       | ...     |
| 2024-10-04 | /\r< OCEAN.XYZ >3OD�ã.³Lð\n������        | 864146 | Not Empty | Other   |
| 2024-10-04 | /\r,ú¾mm÷$@oÈ$\~¸ÑÆn¹Ô3 ñîõä ¼���...  | 864147 | Not Empty | F2Pool  |
| 2024-10-04 | /\rc�g/Foundry USA Pool #dropgold/+J�½­�...   | 864148 | Not Empty | Foundry |
| 2024-10-04 | /\rMined by AntPool èAx®øú¾mm6úq2iF...   | 864149 | Not Empty | AntPool |
| 2024-10-04 | /\rMined by AntPool �µóú¾mm¹ý½kØ]"...   | 864150 | Not Empty | AntPool |

53390 rows × 4 columns

```python
other_miners = miners_tagged.loc[miners_tagged['miner'] == 'Other']
other_miners
```

|            | miner\_tag                                         | height | category  | miner |
| ---------- | -------------------------------------------------- | ------ | --------- | ----- |
| 2023-10-05 |  \_ F°,ñ¿����/NiceHash/                        | 810784 | Not Empty | Other |
| 2023-10-06 | ¬\_ /ultimus/783p�?�DòuÄú¾mm(0³4yï@×ì7HWlù»... | 810924 | Not Empty | Other |
| 2023-10-06 | Ë\_  \t\t\t \t\t \t\_\[����                | 810955 | Not Empty | Other |
| 2023-10-06 | Ö\_ /ultimus/787p�\ÏD­ú¾mmàÀ.,±r}?^º¿rE¨æ... | 810966 | Not Empty | Other |
| 2023-10-07 | \` w !e/SBICrypto.com Pool/ø³bS�����         | 811027 | Not Empty | Other |
| ...        | ...                                                | ...    | ...       | ...   |
| 2024-10-03 | /\rMined by SecPool�)Õ ­ú¾mmÑÀ)Ñgò2e...  | 864005 | Not Empty | Other |
| 2024-10-03 | /\rMined by SecPool�9ÕuRíú¾mm(5L,±kÏä½...  | 864006 | Not Empty | Other |
| 2024-10-04 | C/\r \t\t\t \t\t \tÉ��\n���                 | 864067 | Not Empty | Other |
| 2024-10-04 | l/\rdÏÿf/SBICrypto.com Pool/\r$²v������        | 864108 | Not Empty | Other |
| 2024-10-04 | /\r< OCEAN.XYZ >3OD�ã.³Lð\n������       | 864146 | Not Empty | Other |

3060 rows × 4 columns

```python
miners_tagged['miner'] = miners_tagged['miner'].replace('xxxxxx.com', 'Poolin')
miners_tagged['miner'] = miners_tagged['miner'].replace('poolin', 'Poolin')
miners_tagged['miner'] = miners_tagged['miner'].replace('btccom', 'BTC.com')
miners_tagged['miner'] = miners_tagged['miner'].replace('btc.com', 'BTC.com')
miners_tagged['miner'] = miners_tagged['miner'].replace('btcpool', 'BTC.com')
miners_tagged['miner'] = miners_tagged['miner'].replace('bitdeer', 'BTC.com')
miners_tagged['miner'] = miners_tagged['miner'].replace('slush', 'Braiins Pool')
miners_tagged['miner'] = miners_tagged['miner'].replace('binance', 'Binance Pool')
miners_tagged['miner'] = miners_tagged['miner'].replace('Binance', 'Binance Pool')
miners_tagged['miner'] = miners_tagged['miner'].replace('Mara Pool', 'MARA Pool')
```

```python
# Group the data by the date and calculate the relative proportions of each category
data = miners_tagged.groupby(miners_tagged.index.date)['miner'].value_counts(normalize=True)
data = data.unstack()

averages = data.sum()
averages = pd.DataFrame(averages.sort_values(ascending=False))
averages = averages.index.tolist()
data = data[averages]
```

```python
data
```

| miner      | Foundry  | AntPool  | ViaBTC   | F2Pool   | Other    | Binance Pool | MARA Pool | Luxor    | SpiderPool | Braiins Pool | BTC.com  | Poolin   |
| ---------- | -------- | -------- | -------- | -------- | -------- | ------------ | --------- | -------- | ---------- | ------------ | -------- | -------- |
| 2023-10-05 | 0.178571 | 0.303571 | 0.160714 | 0.160714 | 0.017857 | 0.125000     | 0.017857  | 0.035714 | NaN        | NaN          | NaN      | NaN      |
| 2023-10-06 | 0.237500 | 0.256250 | 0.112500 | 0.143750 | 0.018750 | 0.081250     | 0.062500  | 0.043750 | NaN        | 0.006250     | 0.012500 | 0.025000 |
| 2023-10-07 | 0.263158 | 0.280702 | 0.087719 | 0.122807 | 0.046784 | 0.046784     | 0.040936  | 0.035088 | NaN        | 0.011696     | 0.046784 | 0.017544 |
| 2023-10-08 | 0.310811 | 0.250000 | 0.121622 | 0.108108 | 0.033784 | 0.067568     | 0.027027  | 0.027027 | NaN        | 0.033784     | 0.013514 | 0.006757 |
| 2023-10-09 | 0.269231 | 0.250000 | 0.115385 | 0.115385 | 0.038462 | 0.108974     | 0.038462  | 0.019231 | NaN        | 0.012821     | 0.019231 | 0.012821 |
| ...        | ...      | ...      | ...      | ...      | ...      | ...          | ...       | ...      | ...        | ...          | ...      | ...      |
| 2024-09-30 | 0.357664 | 0.255474 | 0.065693 | 0.131387 | 0.058394 | 0.021898     | 0.021898  | 0.007299 | 0.058394   | 0.007299     | NaN      | 0.014599 |
| 2024-10-01 | 0.324841 | 0.305732 | 0.133758 | 0.095541 | 0.057325 | 0.012739     | 0.019108  | 0.019108 | 0.006369   | 0.025478     | NaN      | NaN      |
| 2024-10-02 | 0.270968 | 0.219355 | 0.174194 | 0.083871 | 0.064516 | 0.032258     | 0.064516  | 0.025806 | 0.032258   | 0.012903     | 0.012903 | 0.006452 |
| 2024-10-03 | 0.234177 | 0.316456 | 0.101266 | 0.107595 | 0.082278 | 0.037975     | 0.037975  | 0.012658 | 0.031646   | 0.025316     | 0.012658 | NaN      |
| 2024-10-04 | 0.300000 | 0.281818 | 0.181818 | 0.054545 | 0.027273 | 0.027273     | 0.009091  | 0.036364 | 0.018182   | 0.045455     | 0.018182 | NaN      |

366 rows × 12 columns

```python
# Plot the data as an area chart
ax = data.plot.area(figsize=(8, 6),fontsize=13.5,color=colors)
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
ax.set_title('\nBitcoin Mining Pool \nDominance (2023 - 2024)\n',fontsize=22,fontdict={'font':'arial'})
ax.axhline(0.5, linestyle='--', color='black')
plt.xlim([miners_tagged.index[0],miners_tagged.index[-1]])
plt.ylim(0,1)
plt.yticks([0.2, 0.4, 0.6, 0.8, 1.0], ['20%','40%','60%','80%','100%'],fontdict={'font':'arial','size':15})
plt.legend(bbox_to_anchor=(1,1),frameon=False)
plt.annotate('Source: Coin Metrics ATLAS',weight='book',font='arial',xy=(1.001, 0.001), xycoords='axes fraction',color='black',xytext=(-8, 6), textcoords='offset pixels',horizontalalignment='right',verticalalignment='bottom')
plt.savefig('./Pool-Dominance.png',facecolor='white',dpi=100)
plt.show()
```

<figure><img src="/files/n6UY9KXvALwf8srOXUEQ" alt=""><figcaption></figcaption></figure>

```python
total_blocks = pd.DataFrame(miners_tagged.index.value_counts())
total_blocks.rename(columns={total_blocks.columns[0]: 'Total Blocks'}, inplace=True)
total_blocks
```

|            | Total Blocks |
| ---------- | ------------ |
| 2024-02-02 | 188          |
| 2024-01-25 | 181          |
| 2024-03-07 | 180          |
| 2024-07-22 | 179          |
| 2024-02-12 | 179          |
| ...        | ...          |
| 2024-01-15 | 114          |
| 2024-06-23 | 112          |
| 2024-10-04 | 110          |
| 2024-09-11 | 108          |
| 2023-10-05 | 56           |

366 rows × 1 columns

```python
empty_blocks = miners_tagged.groupby([miners_tagged.index.date,miners_tagged.miner])['category'].value_counts()
empty_blocks = empty_blocks.unstack()
```

```python
empty_blocks = pd.DataFrame(empty_blocks.reset_index()).fillna(0).set_index('level_0')
empty_blocks
```

| category   | miner        | Empty | Not Empty |
| ---------- | ------------ | ----- | --------- |
| level\_0   |              |       |           |
| 2023-10-05 | AntPool      | 0.0   | 17.0      |
| 2023-10-05 | Binance Pool | 0.0   | 7.0       |
| 2023-10-05 | F2Pool       | 1.0   | 8.0       |
| 2023-10-05 | Foundry      | 0.0   | 10.0      |
| 2023-10-05 | Luxor        | 0.0   | 2.0       |
| ...        | ...          | ...   | ...       |
| 2024-10-04 | Luxor        | 0.0   | 4.0       |
| 2024-10-04 | MARA Pool    | 0.0   | 1.0       |
| 2024-10-04 | Other        | 0.0   | 3.0       |
| 2024-10-04 | SpiderPool   | 0.0   | 2.0       |
| 2024-10-04 | ViaBTC       | 0.0   | 20.0      |

4004 rows × 3 columns

```python
df_pivot = empty_blocks.pivot_table(index=empty_blocks.index, columns="miner", values="Empty")
df_pivot = df_pivot.join(total_blocks[['Total Blocks']])
df_pivot = df_pivot.fillna(0)
df_pivot
```

|            | AntPool | BTC.com | Binance Pool | Braiins Pool | F2Pool | Foundry | Luxor | MARA Pool | Other | Poolin | SpiderPool | ViaBTC | Total Blocks |
| ---------- | ------- | ------- | ------------ | ------------ | ------ | ------- | ----- | --------- | ----- | ------ | ---------- | ------ | ------------ |
| level\_0   |         |         |              |              |        |         |       |           |       |        |            |        |              |
| 2023-10-05 | 0.0     | 0.0     | 0.0          | 0.0          | 1.0    | 0.0     | 0.0   | 0.0       | 0.0   | 0.0    | 0.0        | 0.0    | 56           |
| 2023-10-06 | 0.0     | 0.0     | 0.0          | 0.0          | 0.0    | 0.0     | 0.0   | 0.0       | 0.0   | 0.0    | 0.0        | 0.0    | 160          |
| 2023-10-07 | 0.0     | 0.0     | 0.0          | 0.0          | 0.0    | 0.0     | 0.0   | 0.0       | 0.0   | 0.0    | 0.0        | 0.0    | 171          |
| 2023-10-08 | 0.0     | 0.0     | 0.0          | 0.0          | 0.0    | 0.0     | 0.0   | 0.0       | 0.0   | 0.0    | 0.0        | 0.0    | 148          |
| 2023-10-09 | 1.0     | 0.0     | 0.0          | 0.0          | 0.0    | 0.0     | 0.0   | 0.0       | 0.0   | 0.0    | 0.0        | 0.0    | 156          |
| ...        | ...     | ...     | ...          | ...          | ...    | ...     | ...   | ...       | ...   | ...    | ...        | ...    | ...          |
| 2024-09-30 | 0.0     | 0.0     | 0.0          | 0.0          | 0.0    | 0.0     | 0.0   | 0.0       | 0.0   | 0.0    | 0.0        | 0.0    | 137          |
| 2024-10-01 | 1.0     | 0.0     | 0.0          | 0.0          | 0.0    | 0.0     | 0.0   | 0.0       | 0.0   | 0.0    | 0.0        | 0.0    | 157          |
| 2024-10-02 | 1.0     | 0.0     | 0.0          | 0.0          | 0.0    | 0.0     | 1.0   | 0.0       | 0.0   | 0.0    | 1.0        | 0.0    | 155          |
| 2024-10-03 | 0.0     | 0.0     | 0.0          | 0.0          | 0.0    | 0.0     | 0.0   | 0.0       | 0.0   | 0.0    | 0.0        | 0.0    | 158          |
| 2024-10-04 | 0.0     | 0.0     | 0.0          | 0.0          | 0.0    | 0.0     | 0.0   | 0.0       | 0.0   | 0.0    | 0.0        | 0.0    | 110          |

366 rows × 13 columns

```python
df_empty = df_pivot.iloc[:,0:].div(df_pivot['Total Blocks'], axis=0)
df_empty = df_empty.drop(df_empty.columns[-1:], axis=1)
```

```python
df_empty = df_empty[averages]
df_empty
```

|            | Foundry | AntPool  | ViaBTC | F2Pool   | Other | Binance Pool | MARA Pool | Luxor    | SpiderPool | Braiins Pool | BTC.com | Poolin |
| ---------- | ------- | -------- | ------ | -------- | ----- | ------------ | --------- | -------- | ---------- | ------------ | ------- | ------ |
| level\_0   |         |          |        |          |       |              |           |          |            |              |         |        |
| 2023-10-05 | 0.0     | 0.000000 | 0.0    | 0.017857 | 0.0   | 0.0          | 0.0       | 0.000000 | 0.000000   | 0.0          | 0.0     | 0.0    |
| 2023-10-06 | 0.0     | 0.000000 | 0.0    | 0.000000 | 0.0   | 0.0          | 0.0       | 0.000000 | 0.000000   | 0.0          | 0.0     | 0.0    |
| 2023-10-07 | 0.0     | 0.000000 | 0.0    | 0.000000 | 0.0   | 0.0          | 0.0       | 0.000000 | 0.000000   | 0.0          | 0.0     | 0.0    |
| 2023-10-08 | 0.0     | 0.000000 | 0.0    | 0.000000 | 0.0   | 0.0          | 0.0       | 0.000000 | 0.000000   | 0.0          | 0.0     | 0.0    |
| 2023-10-09 | 0.0     | 0.006410 | 0.0    | 0.000000 | 0.0   | 0.0          | 0.0       | 0.000000 | 0.000000   | 0.0          | 0.0     | 0.0    |
| ...        | ...     | ...      | ...    | ...      | ...   | ...          | ...       | ...      | ...        | ...          | ...     | ...    |
| 2024-09-30 | 0.0     | 0.000000 | 0.0    | 0.000000 | 0.0   | 0.0          | 0.0       | 0.000000 | 0.000000   | 0.0          | 0.0     | 0.0    |
| 2024-10-01 | 0.0     | 0.006369 | 0.0    | 0.000000 | 0.0   | 0.0          | 0.0       | 0.000000 | 0.000000   | 0.0          | 0.0     | 0.0    |
| 2024-10-02 | 0.0     | 0.006452 | 0.0    | 0.000000 | 0.0   | 0.0          | 0.0       | 0.006452 | 0.006452   | 0.0          | 0.0     | 0.0    |
| 2024-10-03 | 0.0     | 0.000000 | 0.0    | 0.000000 | 0.0   | 0.0          | 0.0       | 0.000000 | 0.000000   | 0.0          | 0.0     | 0.0    |
| 2024-10-04 | 0.0     | 0.000000 | 0.0    | 0.000000 | 0.0   | 0.0          | 0.0       | 0.000000 | 0.000000   | 0.0          | 0.0     | 0.0    |

366 rows × 12 columns

```python
fig, ax = plt.subplots(figsize=(8, 6))
cumval = 0
i = 0
for col in df_empty.columns:
    plt.bar(df_empty.index, df_empty[col], bottom=cumval, label=col, color=colors[i])
    cumval = cumval+df_empty[col]
    i += 1
ax.xaxis.set_major_locator(mdates.MonthLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b'))
plt.title('\nEmpty Blocks\nTotal Percentage (2023 - 2024)\n', fontdict = {'size':18, 'font': 'arial'})
plt.xticks(rotation=0)
plt.xlabel('')
plt.legend(bbox_to_anchor=(1,1),frameon=False)
plt.yticks([0.005, 0.010, 0.015, 0.02, 0.025], ['0.5%','1.0%','1.5%','2.0%','2.5%'],fontdict={'size':14})
plt.grid(True, axis='y',linestyle='--',alpha=0.5)
plt.annotate('Source: Coin Metrics ATLAS',weight='book',font='arial',xy=(1.00, 0.953), xycoords='axes fraction',color='black',xytext=(-8, 6), textcoords='offset pixels',horizontalalignment='right',verticalalignment='bottom')
plt.savefig('./Empty-Blocks-Total-2023-2024.png',facecolor='white',dpi=100)
plt.xlabel('');
```

<figure><img src="/files/IZ8FZNDoGzTQjJE6hrvQ" alt=""><figcaption></figcaption></figure>

```python
empty_blocks_total = pd.DataFrame(miners_tagged.groupby([miners_tagged.miner])['category'].value_counts(normalize=True))
empty_blocks_total = empty_blocks_total.unstack().fillna(0)
empty_blocks_total.columns = empty_blocks_total.columns.droplevel(0)
empty_blocks_total = empty_blocks_total.reindex(averages)
empty_blocks_total
```

| category     | Empty    | Not Empty |
| ------------ | -------- | --------- |
| miner        |          |           |
| Foundry      | 0.000000 | 1.000000  |
| AntPool      | 0.005885 | 0.994115  |
| ViaBTC       | 0.002395 | 0.997605  |
| F2Pool       | 0.003208 | 0.996792  |
| Other        | 0.003595 | 0.996405  |
| Binance Pool | 0.002993 | 0.997007  |
| MARA Pool    | 0.000000 | 1.000000  |
| Luxor        | 0.005000 | 0.995000  |
| SpiderPool   | 0.035996 | 0.964004  |
| Braiins Pool | 0.002331 | 0.997669  |
| BTC.com      | 0.004071 | 0.995929  |
| Poolin       | 0.004640 | 0.995360  |

```python
pool_total_blocks = pd.DataFrame(miners_tagged['miner'].value_counts())
pool_total_blocks = pool_total_blocks.drop('Other')
pool_total_blocks.rename(columns={pool_total_blocks.columns[0]: 'Total Blocks Mined'}, inplace=True)
pool_total_blocks
```

|              | Total Blocks Mined |
| ------------ | ------------------ |
| miner        |                    |
| Foundry      | 15492              |
| AntPool      | 13595              |
| ViaBTC       | 6680               |
| F2Pool       | 5923               |
| Binance Pool | 2339               |
| MARA Pool    | 1986               |
| Luxor        | 1400               |
| SpiderPool   | 889                |
| Braiins Pool | 858                |
| BTC.com      | 737                |
| Poolin       | 431                |

```python
row_num = empty_blocks_total.index.get_loc('Other')
colors_no_other = np.delete(colors, row_num)
empty_blocks_total = empty_blocks_total.drop('Other')
```

```python
pool_total_blocks.reset_index()
```

|    | miner        | Total Blocks Mined |
| -- | ------------ | ------------------ |
| 0  | Foundry      | 15492              |
| 1  | AntPool      | 13595              |
| 2  | ViaBTC       | 6680               |
| 3  | F2Pool       | 5923               |
| 4  | Binance Pool | 2339               |
| 5  | MARA Pool    | 1986               |
| 6  | Luxor        | 1400               |
| 7  | SpiderPool   | 889                |
| 8  | Braiins Pool | 858                |
| 9  | BTC.com      | 737                |
| 10 | Poolin       | 431                |

```python
ax = empty_blocks_total['Empty'].plot.bar(figsize=(8, 6),stacked=True,fontsize=12,color=colors_no_other,width=0.8,zorder=2)
def format_percent(x, pos):
    return '{:.2%}'.format(x)
formatter = FuncFormatter(format_percent)
ax.yaxis.set_major_formatter(formatter)
plt.xticks(rotation=45,size=12)
plt.yticks(rotation=0,size=12)
plt.title('\nEmpty Blocks vs. Total Blocks\nby Mining Pool (Oct 2023 - Oct 2024)\n', fontdict = {'size':18, 'font': 'arial'})
plt.xlabel('');
plt.ylabel('Empty Blocks (%)',fontsize=14,labelpad=10);
plt.tick_params(axis='both', which='both', length=0, pad=8)
plt.ylim(0,0.04)
ax.grid(True, axis='y',linestyle='--',zorder=1,alpha=0.5)
ax2 = ax.twinx()
pool_total_blocks.plot.line(ax=ax2,color='black',linestyle='--',legend=True)
pool_total_blocks.reset_index().plot.scatter(x='miner',y='Total Blocks Mined',ax=ax2,color='black', s=50)
ax2.set_yticks([0,2000,4000,6000,8000,10000,12000,14000,16000])
plt.ylim(0,16000)
ax2.yaxis.set_major_formatter(mtick.StrMethodFormatter('{x:,.0f}'))
plt.legend(bbox_to_anchor=(1,1.0),frameon=False,fontsize=11.3)
plt.tick_params(axis='both', which='both', length=0, pad=8)
plt.yticks(rotation=0,size=12)
plt.ylabel('Total Blocks Mined\n',fontsize=14,labelpad=10);
plt.annotate(
    'Source: Coin Metrics ATLAS',
    weight='book',
    font='arial',
    fontsize=12,
    xy=(1.0, 1.0),
    xycoords='axes fraction',
    color='black',
    xytext=(-8, 6),
    textcoords='offset pixels',
    horizontalalignment='right',
    verticalalignment='bottom'
)
plt.savefig('./Empty-Blocks-by-Pool.png',facecolor='white',dpi=100)
```

<figure><img src="/files/7nYZHeaK9ksv2k5rWcPg" alt=""><figcaption></figcaption></figure>


# Using Staking Metrics to Get Yield and Staked Supply

![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/Demo%20Asset%20Resources/Demo%20Covers/CM-Demo-eth_staking_metrics-Cover.png)

### Resources

This notebook demonstrates basic functionality offered by the Coin Metrics Python API Client and Network Data Pro.

Coin Metrics offers a vast assortment of data for hundreds of cryptoassets. The Python API Client allows for easy access to this data using Python without needing to create your own wrappers using `requests` and other such libraries.

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics.
* The [Coin Metrics Product Documentation](https://docs.coinmetrics.io/info) gives detailed, conceptual explanations of the data that Coin Metrics offers.
* The [API Spec](https://docs.coinmetrics.io/python-api-client/reference) contains a full list of functions.

### File Download

Download the entire notebook as either a jupyter notebook to run yourself or as a pdf from the two links below

{% file src="/files/J0AKsVSNWX1OnZsv1pMM" %}

{% file src="/files/J0AKsVSNWX1OnZsv1pMM" %}

#### Notebook Setup

```python
from os import environ
import pandas as pd
import numpy as np
import seaborn as sns
import logging
from datetime import date, datetime, timedelta
from coinmetrics.api_client import CoinMetricsClient
import logging
import matplotlib.pyplot as plt
import warnings
# %matplotlib inline
```

```python
# Chart themes
sns.set_theme()
warnings.filterwarnings('ignore')
fig = plt.style.use('seaborn')
sns.set(rc={'figure.figsize':(8,6)})
sns.set_style("whitegrid",{'axes.grid' : True,'grid.linestyle': '--', 'grid.color': 'gray','axes.edgecolor': 'white','font.family': ['arial']})
```

```python
logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S'
)
```

```python
# We recommend privately storing your API key in your local environment.
try:
    api_key = environ["CM_API_KEY"]
    logging.info("Using API key found in environment")
except KeyError:
    api_key = ""
    logging.info("API key not found. Using community client")
client = CoinMetricsClient(api_key)
```

```
2024-09-27 14:45:08 INFO     Using API key found in environment
```

## Calculate Estimated Validator Yield

Using ETH\_CL validator metrics it is possible to estimate the yield from the protocol. In combination with historical data on priority tips, we can estimate what a validator should expect to earn. Note that maximal extractable value (MEV) is another source of revenue for validators but is currently not considered as part of this analysis.

A validator’s expected annual percentage return (APR) from staking rewards accumulated on the Consensus Layer, assuming perfect performance and uptime, can be estimated with the formula below (where ValidatorActOngCnt = number of active validators):

> 2940.21 ÷ sqrt(ValidatorActOngCnt) = Staking Yield

```python
start_time = '2022-01-01'
end_time = '2022-12-31'
```

#### Retrieve Consensus Layer Metrics

```python
consensus_metrics = client.get_asset_metrics(
    assets='eth_cl',
    metrics=['ValidatorActOngCnt'],
    start_time = start_time,
    end_time = end_time
).to_dataframe()
```

```python
consensus_metrics['time'] = pd.to_datetime(consensus_metrics['time'])
```

```python
consensus_metrics
```

|     | asset   | time                      | ValidatorActOngCnt |
| --- | ------- | ------------------------- | ------------------ |
| 0   | eth\_cl | 2022-01-01 00:00:00+00:00 | 275880             |
| 1   | eth\_cl | 2022-01-02 00:00:00+00:00 | 276301             |
| 2   | eth\_cl | 2022-01-03 00:00:00+00:00 | 276784             |
| 3   | eth\_cl | 2022-01-04 00:00:00+00:00 | 277530             |
| 4   | eth\_cl | 2022-01-05 00:00:00+00:00 | 278349             |
| ... | ...     | ...                       | ...                |
| 360 | eth\_cl | 2022-12-27 00:00:00+00:00 | 491923             |
| 361 | eth\_cl | 2022-12-28 00:00:00+00:00 | 492863             |
| 362 | eth\_cl | 2022-12-29 00:00:00+00:00 | 493116             |
| 363 | eth\_cl | 2022-12-30 00:00:00+00:00 | 493662             |
| 364 | eth\_cl | 2022-12-31 00:00:00+00:00 | 493896             |

365 rows × 3 columns

Rewards from staking are only one part of a validator’s yield. Post-Merge, validators now also receive user transaction priority fees, or tips, that used to go to miners on the Execution Layer. Considering the historical record of fees, we can estimate the magnitude of this additional source of yield. For our analysis, we show how to estimate both staking revenues and priority tips as yields on staked ETH.

To do this, we use the results we found above and divide gross annual emission by the total number of validators to produce average validator revenue, which for this purpose only consider revenues that originate from the protocol and not from fees.

> 940.87 × sqrt(ValidatorActOngCnt) ÷ ValidatorActOngCnt = Avg. Validator Revenue

The expected annual number of blocks proposed in turn allows us to estimate the priority tip that is earned by each block proposal. Using a 14-day moving average to smooth priority tips, we then estimate what a proposer should expect to earn in tips.

> 1 ÷ ValidatorActOngCnt × 2,629,800 = Annual Num. of\
> Proposals per Validator

> sma(FeePrioTotNtv ÷ BlkCnt, 14) × Ann. Num. of Proposals per Validator = Average Priority Tip per Block

#### Retrieve Execution Layer Metrics

```python
execution_metrics = client.get_asset_metrics(
    assets='eth',
    metrics=['FeePrioTotNtv', 'BlkCnt'],
    start_time = start_time,
    end_time = end_time
).to_dataframe()
```

```python
execution_metrics['time'] = pd.to_datetime(execution_metrics['time'])
```

```python
execution_metrics
```

|     | asset | time                      | BlkCnt | FeePrioTotNtv |
| --- | ----- | ------------------------- | ------ | ------------- |
| 0   | eth   | 2022-01-01 00:00:00+00:00 | 6506   | 747.204977    |
| 1   | eth   | 2022-01-02 00:00:00+00:00 | 6495   | 905.938725    |
| 2   | eth   | 2022-01-03 00:00:00+00:00 | 6461   | 898.990928    |
| 3   | eth   | 2022-01-04 00:00:00+00:00 | 6494   | 1245.74813    |
| 4   | eth   | 2022-01-05 00:00:00+00:00 | 6460   | 1485.351677   |
| ... | ...   | ...                       | ...    | ...           |
| 360 | eth   | 2022-12-27 00:00:00+00:00 | 7156   | 343.663114    |
| 361 | eth   | 2022-12-28 00:00:00+00:00 | 7173   | 353.437599    |
| 362 | eth   | 2022-12-29 00:00:00+00:00 | 7161   | 324.786107    |
| 363 | eth   | 2022-12-30 00:00:00+00:00 | 7166   | 319.41694     |
| 364 | eth   | 2022-12-31 00:00:00+00:00 | 7166   | 290.772518    |

365 rows × 4 columns

```python
eth_metrics = consensus_metrics.merge(execution_metrics, on='time', how='inner')
```

```python
eth_metrics = eth_metrics[['time','ValidatorActOngCnt','BlkCnt','FeePrioTotNtv']]
```

#### Calculate theoretical validator yield based on Active Validator count

```python
eth_metrics['Validator Yield'] = 100 * (
    (32 + ((940.87 * (eth_metrics['ValidatorActOngCnt'] ** (1/2))) / eth_metrics['ValidatorActOngCnt']))/32 - 1
)
eth_metrics
```

|     | time                      | ValidatorActOngCnt | BlkCnt | FeePrioTotNtv | Validator Yield |
| --- | ------------------------- | ------------------ | ------ | ------------- | --------------- |
| 0   | 2022-01-01 00:00:00+00:00 | 275880             | 6506   | 747.204977    | 5.597828        |
| 1   | 2022-01-02 00:00:00+00:00 | 276301             | 6495   | 905.938725    | 5.593561        |
| 2   | 2022-01-03 00:00:00+00:00 | 276784             | 6461   | 898.990928    | 5.588679        |
| 3   | 2022-01-04 00:00:00+00:00 | 277530             | 6494   | 1245.74813    | 5.581163        |
| 4   | 2022-01-05 00:00:00+00:00 | 278349             | 6460   | 1485.351677   | 5.572946        |
| ... | ...                       | ...                | ...    | ...           | ...             |
| 360 | 2022-12-27 00:00:00+00:00 | 491923             | 7156   | 343.663114    | 4.192095        |
| 361 | 2022-12-28 00:00:00+00:00 | 492863             | 7173   | 353.437599    | 4.188095        |
| 362 | 2022-12-29 00:00:00+00:00 | 493116             | 7161   | 324.786107    | 4.187021        |
| 363 | 2022-12-30 00:00:00+00:00 | 493662             | 7166   | 319.41694     | 4.184704        |
| 364 | 2022-12-31 00:00:00+00:00 | 493896             | 7166   | 290.772518    | 4.183713        |

365 rows × 5 columns

#### Calculate estimated blocks proposals per year based on Active Validator count

```python
eth_metrics['est_block_proposals_per_yr'] = ((1/eth_metrics['ValidatorActOngCnt']) * (2629800))
```

#### Estimate tips per block

```python
eth_metrics['avg_per_block_tip_2w'] = (eth_metrics['FeePrioTotNtv'] / eth_metrics['BlkCnt']).rolling(window=14).mean()
```

```python
eth_metrics
```

|     | time                      | ValidatorActOngCnt | BlkCnt | FeePrioTotNtv | Validator Yield | est\_block\_proposals\_per\_yr | avg\_per\_block\_tip\_2w |
| --- | ------------------------- | ------------------ | ------ | ------------- | --------------- | ------------------------------ | ------------------------ |
| 0   | 2022-01-01 00:00:00+00:00 | 275880             | 6506   | 747.204977    | 5.597828        | 9.532405                       | NaN                      |
| 1   | 2022-01-02 00:00:00+00:00 | 276301             | 6495   | 905.938725    | 5.593561        | 9.517881                       | NaN                      |
| 2   | 2022-01-03 00:00:00+00:00 | 276784             | 6461   | 898.990928    | 5.588679        | 9.501272                       | NaN                      |
| 3   | 2022-01-04 00:00:00+00:00 | 277530             | 6494   | 1245.74813    | 5.581163        | 9.475732                       | NaN                      |
| 4   | 2022-01-05 00:00:00+00:00 | 278349             | 6460   | 1485.351677   | 5.572946        | 9.447851                       | NaN                      |
| ... | ...                       | ...                | ...    | ...           | ...             | ...                            | ...                      |
| 360 | 2022-12-27 00:00:00+00:00 | 491923             | 7156   | 343.663114    | 4.192095        | 5.345959                       | 0.048594                 |
| 361 | 2022-12-28 00:00:00+00:00 | 492863             | 7173   | 353.437599    | 4.188095        | 5.335763                       | 0.048059                 |
| 362 | 2022-12-29 00:00:00+00:00 | 493116             | 7161   | 324.786107    | 4.187021        | 5.333025                       | 0.047630                 |
| 363 | 2022-12-30 00:00:00+00:00 | 493662             | 7166   | 319.41694     | 4.184704        | 5.327127                       | 0.045280                 |
| 364 | 2022-12-31 00:00:00+00:00 | 493896             | 7166   | 290.772518    | 4.183713        | 5.324603                       | 0.044691                 |

365 rows × 7 columns

#### Calculate priority tip yield

```python
eth_metrics['Priority Tip Yield'] = (100 *
    ((32 + eth_metrics['avg_per_block_tip_2w'] * eth_metrics['est_block_proposals_per_yr'])/32+(-1)))
```

```python
eth_metrics = eth_metrics.dropna().set_index('time')
```

```python
ax = eth_metrics[['Validator Yield', 'Priority Tip Yield']].plot.area(stacked=True, figsize=(8, 6),color=['orange', 'red'])
ax.set_ylabel('Yield (%)')
ax.set_xlabel('')
ax.set_title('\nETH Staking \nEstimated Yield',fontsize=14)
plt.legend(loc='upper right', bbox_to_anchor=(1.00, 1.0))
plt.savefig("NDP_ETH_staking_metrics_validator_priority_tip_yield.png")
plt.show()
```

## Calculate ETH Supply: Staked vs. Unstaked

One of the many advantages of a blockchain-based ledger is auditability, but increasingly complex consensus architectures and supply mechanics can make it difficult to understand the full picture of asset supply. Ethereum's shift to proof-of-stake introduced a number of novel considerations in obtaining network-wide supply figures. In the following example, we combine various Supply metrics from ETH's Consensus and Execution Layers to ascertain the total amount of staked vs. unstaked supply.

#### Consensus Layer Metrics

```python
cl_supply = client.get_asset_metrics(
    assets='eth_cl',
    metrics=['SplyCur','SplyStkedNtv'],
    start_time = start_time,
    end_time = end_time,
    frequency = '1d'
).to_dataframe()

cl_supply = cl_supply.rename(columns={"SplyCur": "SplyCur_CL"})
```

#### Execution Layer Metrics

```python
el_supply = client.get_asset_metrics(
    assets='eth',
    metrics=['SplyCur','SplyCLCont'],
    start_time = start_time,
    end_time = end_time,
    frequency = '1d'
).to_dataframe()

el_supply = el_supply.rename(columns={"SplyCur": "SplyCur_EL"})
```

```python
adjusted_supply = cl_supply.merge(el_supply, on='time', how='inner')
adjusted_supply = adjusted_supply.set_index('time')
```

```python
adjusted_supply = adjusted_supply[['SplyCur_EL','SplyCur_CL','SplyCLCont','SplyStkedNtv']]
```

#### Calculate the total 'adjusted' ETH supply

```python
adjusted_supply['Total ETH Supply'] = adjusted_supply['SplyCur_EL'] + (adjusted_supply['SplyCur_CL'] - adjusted_supply['SplyCLCont'])
```

```python
adjusted_supply['Staked Supply'] = adjusted_supply['SplyStkedNtv']
```

```python
adjusted_supply['Unstaked Supply'] = adjusted_supply['Total ETH Supply'] - adjusted_supply['Staked Supply'] 
```

```python
adjusted_supply
```

|                           | SplyCur\_EL      | SplyCur\_CL     | SplyCLCont     | SplyStkedNtv | Total ETH Supply | Staked Supply | Unstaked Supply  |
| ------------------------- | ---------------- | --------------- | -------------- | ------------ | ---------------- | ------------- | ---------------- |
| time                      |                  |                 |                |              |                  |               |                  |
| 2022-01-01 00:00:00+00:00 | 118049177.834937 | 9227820.793013  | 8852770.0      | 8828515      | 118424228.62795  | 8828515       | 109595713.62795  |
| 2022-01-02 00:00:00+00:00 | 118054804.893592 | 9242509.802432  | 8866898.0      | 8841891      | 118430416.696023 | 8841891       | 109588525.696023 |
| 2022-01-03 00:00:00+00:00 | 118060102.632049 | 9264680.84189   | 8887122.0      | 8862723      | 118437661.47394  | 8862723       | 109574938.47394  |
| 2022-01-04 00:00:00+00:00 | 118063057.343795 | 9286929.282994  | 8915506.0      | 8883635      | 118434480.626789 | 8883635       | 109550845.626789 |
| 2022-01-05 00:00:00+00:00 | 118064691.965118 | 9311811.478199  | 8931074.0      | 8907187      | 118445429.443318 | 8907187       | 109538242.443318 |
| ...                       | ...              | ...             | ...            | ...          | ...              | ...           | ...              |
| 2022-12-27 00:00:00+00:00 | 120528662.458689 | 16755428.289539 | 15813639.05565 | 15767369     | 121470451.692578 | 15767369      | 105703082.692578 |
| 2022-12-28 00:00:00+00:00 | 120528732.408086 | 16761680.161693 | 15819655.05565 | 15771865     | 121470757.51413  | 15771865      | 105698892.51413  |
| 2022-12-29 00:00:00+00:00 | 120528750.981834 | 16772281.136252 | 15834119.05565 | 15780713     | 121466913.062437 | 15780713      | 105686200.062437 |
| 2022-12-30 00:00:00+00:00 | 120528698.245699 | 16790630.62361  | 15846119.05565 | 15797305     | 121473209.81366  | 15797305      | 105675904.81366  |
| 2022-12-31 00:00:00+00:00 | 120528769.150157 | 16800132.616449 | 15854791.05565 | 15805049     | 121474110.710956 | 15805049      | 105669061.710956 |

365 rows × 7 columns

#### Plot staked vs. unstaked supply

```python
ax = adjusted_supply[['Staked Supply', 'Unstaked Supply']].plot.area(stacked=True, figsize=(8, 4),color=['pink', 'purple'])
ax.set_ylabel('')
ax.set_xlabel('')
ax.set_title('\nETH Staked vs. Unstaked Supply\n',fontsize=14)
ax.yaxis.set_major_formatter(lambda x, _: f'{x*1e-6}M')
plt.legend(loc='upper right', bbox_to_anchor=(1.05, 1.15), fontsize=10)
plt.savefig("NDP_ETH_Staking_Metrics_staked_vs_unstaked_supply.png")
plt.show()
```

```python
```


# Granular Insights On Chain Using Hourly Network Data Metrics

![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/Demo%20Asset%20Resources/Demo%20Covers/CM-Demo-hourly_metrics-Cover.png)

### Resources

This notebook demonstrates basic functionality offered by the Coin Metrics Python API Client and Network Data Pro.

Coin Metrics offers a vast assortment of data for hundreds of cryptoassets. The Python API Client allows for easy access to this data using Python without needing to create your own wrappers using `requests` and other such libraries.

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics.
* The [Coin Metrics Product Documentation](https://docs.coinmetrics.io/info) gives detailed, conceptual explanations of the data that Coin Metrics offers.
* The [API Spec](https://docs.coinmetrics.io/python-api-client/reference) contains a full list of functions.

### File Download

Download the entire notebook as either a jupyter notebook to run yourself or as a pdf from the two links below

{% file src="/files/mXEemEYtu1RKthjpZmuS" %}

{% file src="/files/DTmLkfGWRDz4eaymqNce" %}

#### Notebook Setup

```python
from os import environ
import pandas as pd
import numpy as np
import seaborn as sns
import logging
from datetime import date, datetime, timedelta
from coinmetrics.api_client import CoinMetricsClient
import logging
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.ticker import FuncFormatter
import warnings
# %matplotlib inline
```

```python
logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S'
)
matplotlib.rcParams['font.family'] = 'arial'
```

```python
# We recommend privately storing your API key in your local environment.
try:
    api_key = environ["CM_API_KEY"]
    logging.info("Using API key found in environment")
except KeyError:
    api_key = ""
    logging.info("API key not found. Using community client")
client = CoinMetricsClient(api_key)
```

```
2024-10-04 11:52:04 INFO     Using API key found in environment
```

## Hourly Metrics

Coin Metrics is pleased to announce the release of a new set of hourly metrics for **Network Data Pro**. This feature unlocks a new level granularity for our existing suite of on-chain metrics.

Previously, our Network Data Pro offering provided both Daily (EOD) and Block-by-Block (BBB) aggregations of on-chain metrics. Now, users have the ability to capture on-chain activity at an intermediate frequency, providing timely insights into metrics like Active Address Count, Transaction Fees, and more.

#### Retrieve Hourly Metrics Catalog

```python
asset_metrics_reference = client.reference_data_asset_metrics(page_size=10000).to_dataframe()
list_metrics_nd = list(asset_metrics_reference.loc[asset_metrics_reference['product']=='Network Data', 'metric'])

asset_metrics_catalog = client.catalog_asset_metrics_v2(
    assets='eth', 
    metrics=list_metrics_nd, 
    page_size=10000
).to_list()


list_hourly_metrics_nd = []
for asset in asset_metrics_catalog:
    for metric in asset['metrics']:
        if 'frequencies' in metric.keys():
            for frequency in metric.get('frequencies'):
                if '1h' in frequency.values():
                    list_hourly_metrics_nd.append(metric['metric'])

# # alternatively, use this dataframe. note this is only doable starting coinmetrics-api-client version 2024.10.4.15
# asset_metrics_catalog = client.catalog_asset_metrics_v2(page_size=10000).to_dataframe()
# list_hourly_metrics_nd = list(asset_metrics_catalog.loc[asset_metrics_catalog.frequency=='1h', 'metric'].unique())
```

```
['AdrActBlobCnt',
 'AdrActBlobContRecCnt',
 'AdrActBlobRecCnt',
 'AdrActBlobSendCnt',
 'AdrActCnt',
 'AdrActRecCnt',
 'AdrActSentCnt',
 'AssetCompletionTime',
 'BlkCnt',
 'BlkHgt',
 'BlkIntMean',
 'BlkSizeByte',
 'BlobARBSizeByte',
 'BlobBASESizeByte',
 'BlobCnt',
 'BlobContCnt',
 'BlobInscrCnt',
 'BlobL2SizeByte',
 'BlobMeanCnt',
 'BlobOPSizeByte',
 'BlobSizeAllTimeByte',
 'BlobSizeByte',
 'BlobUniqCnt',
 'DiffLast',
 'FeeBlobARBMeanNtv',
 'FeeBlobARBMeanUSD',
 'FeeBlobARBTotNtv',
 'FeeBlobARBTotUSD',
 'FeeBlobBASEMeanNtv',
 'FeeBlobBASEMeanUSD',
 'FeeBlobBASETotNtv',
 'FeeBlobBASETotUSD',
 'FeeBlobByteMeanNtv',
 'FeeBlobByteMeanUSD',
 'FeeBlobL2MeanNtv',
 'FeeBlobL2MeanUSD',
 'FeeBlobL2TotNtv',
 'FeeBlobL2TotUSD',
 'FeeBlobMeanNtv',
 'FeeBlobMeanUSD',
 'FeeBlobMedNtv',
 'FeeBlobMedUSD',
 'FeeBlobOPMeanNtv',
 'FeeBlobOPMeanUSD',
 'FeeBlobOPTotNtv',
 'FeeBlobOPTotUSD',
 'FeeBlobTotNtv',
 'FeeBlobTotUSD',
 'FeeBlobTxMeanNtv',
 'FeeBlobTxMeanUSD',
 'FeeMeanNtv',
 'FeeMeanUSD',
 'FeeMedNtv',
 'FeeMedUSD',
 'FeePrioMeanNtv',
 'FeePrioMeanUSD',
 'FeePrioMedNtv',
 'FeePrioMedUSD',
 'FeePrioTotNtv',
 'FeePrioTotUSD',
 'FeeTotNtv',
 'FeeTotUSD',
 'PriceBTC',
 'PriceUSD',
 'ROI1yr',
 'ROI30d',
 'RevNtv',
 'RevUSD',
 'SplyBurntNtv',
 'SplyBurntUSD',
 'StakingAPRNominal',
 'StakingAPYNominal',
 'TxBlobARBCnt',
 'TxBlobBASECnt',
 'TxBlobCnt',
 'TxBlobContCnt',
 'TxBlobInscrCnt',
 'TxBlobL2Cnt',
 'TxBlobMeanCnt',
 'TxBlobOPCnt',
 'TxCnt',
 'TxTfrCnt',
 'TxTfrValMeanNtv',
 'TxTfrValMeanUSD',
 'TxTfrValMedNtv',
 'TxTfrValMedUSD',
 'TxTfrValNtv',
 'TxTfrValUSD',
 'ValidatorAPRNominal',
 'ValidatorAPYNominal']
```

## Example Analyses

```python
start = datetime.utcnow() - timedelta(days=7)
```

### ETH Fee Burn vs. Tx Count

First, we'll examine the relationship between Ethereum's transaction count (**TxCnt**) and the amount of ETH being "burned," or removed from circulation (**SplyBurntNtv**).

Since the introduction of EIP-1559, Ethereum has segmented gas fees into two separate fees: the "base fee" and the "priority tip." While the priority tip is rewarded to validators, the base fee is burnt. Over the long-term, this has enabled ETH to offer a deflationary monetary policy, with periods of high transaction activity permanently destroying units of ETH and lowering the total circulating supply.

For more details on the impact of EIP-1559, check out [**State of the Network #166: Ethereum After EIP-1559**](https://coinmetrics.substack.com/p/state-of-the-network-issue-166)

```python
fee_burn_and_tx_metrics = client.get_asset_metrics(
    assets='eth',
    metrics=['TxCnt','SplyBurntNtv'],
    start_time = start,
    frequency='1h'
).to_dataframe()
```

```python
fee_burn_and_tx_metrics['time'] = pd.to_datetime(fee_burn_and_tx_metrics['time'])
```

```python
fee_burn_and_tx_metrics = fee_burn_and_tx_metrics[['SplyBurntNtv','TxCnt','time']].set_index('time')
fee_burn_and_tx_metrics['SplyBurntNtv'] = fee_burn_and_tx_metrics['SplyBurntNtv'] * -1
fee_burn_and_tx_metrics
```

|                           | SplyBurntNtv | TxCnt |
| ------------------------- | ------------ | ----- |
| time                      |              |       |
| 2024-09-27 17:00:00+00:00 | -70.397819   | 53103 |
| 2024-09-27 18:00:00+00:00 | -50.973631   | 52695 |
| 2024-09-27 19:00:00+00:00 | -129.348614  | 49882 |
| 2024-09-27 20:00:00+00:00 | -64.472321   | 52184 |
| 2024-09-27 21:00:00+00:00 | -39.452127   | 50770 |
| ...                       | ...          | ...   |
| 2024-10-04 11:00:00+00:00 | -19.116498   | 48958 |
| 2024-10-04 12:00:00+00:00 | -27.192417   | 49215 |
| 2024-10-04 13:00:00+00:00 | -39.860415   | 49662 |
| 2024-10-04 14:00:00+00:00 | -48.651027   | 51090 |
| 2024-10-04 15:00:00+00:00 | -58.644727   | 51400 |

167 rows × 2 columns

```python
# Function to format y-axis tick labels
def thousands(x, pos):
    'The two args are the value and tick position'
    return '%1.0fK' % (x * 1e-3)

fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(14,8))
ax1.set_title('\nETH Transaction Count \nand Supply Burnt (1H)\n', color='black', fontsize=16)  # Change title color to white for visibility

# Plot TxCnt as a line plot
ax1.plot(fee_burn_and_tx_metrics.index, fee_burn_and_tx_metrics['TxCnt'], color='lime')
ax1.set_facecolor('#212530')
ax1.set_ylabel('Transaction Count', color='black')  
ax1.tick_params(length=0, axis='y', labelcolor='black') 
ax1.tick_params(length=0, axis='x', labelcolor='black')  
ax1.yaxis.set_major_formatter(FuncFormatter(thousands))
ax1.grid(axis='y',linestyle='--', color='gray')  # Change gridline color to white for visibility

cmap = matplotlib.cm.Reds(np.linspace(0.5,0.75,20))
cmap = matplotlib.colors.ListedColormap(cmap[::-1, :-1])

# Plot SplyBurntUSD as a scatter plot with the colormap
sc = ax2.scatter(fee_burn_and_tx_metrics.index, fee_burn_and_tx_metrics['SplyBurntNtv'], c=fee_burn_and_tx_metrics['SplyBurntNtv'], cmap=cmap)
ax2.set_facecolor('#212530')
ax2.set_xlabel('')
ax2.set_ylabel('Supply Burnt (ETH)', color='black')  # Change label color to white for visibility
ax2.tick_params(length=0,axis='y', labelcolor='black')  # Change tick color to white for visibility
ax2.grid(axis='y',linestyle='--', color='gray')  # Change gridline color to white for visibility
ax2.set_ylim(fee_burn_and_tx_metrics['SplyBurntNtv'].min()*1.05,0)
fig.tight_layout()
plt.show()
```

<figure><img src="/files/PT3p4FFNylLVlr46BLvy" alt=""><figcaption></figcaption></figure>

### BTC Block Interval vs. Mean Fee

In contrast to Etheruem's predictable 12-second block time, Bitcoin's block interval is based on probabilistic factors— there's no way of knowing for sure when the next block will come in.

The blockchain's difficulty adjustment software targets an average block interval of 10 minutes, but blocks can occasionally take an hour or more to be mined, resulting in brief periods of transaction congestion. This congestion can result in spikes in transaction fees, as a busy backlog of BTC users bid up fees in order to ensure their inclusion in the next block.

In the following analysis, we examine how Bitcoin's median transaction fee (**FeeMedUSD**) responds to prolonged block intervals (**BlkIntMean**).

```python
blk_size_and_fee_metrics = client.get_asset_metrics(
    assets='btc',
    metrics=['BlkIntMean','FeeMedUSD'],
    start_time = start,
    frequency='1h'
).to_dataframe()
```

```python
blk_size_and_fee_metrics['time'] = pd.to_datetime(blk_size_and_fee_metrics['time'])
blk_size_and_fee_metrics['FeeMedUSD'] = blk_size_and_fee_metrics['FeeMedUSD'].replace('None', np.nan).astype(float)
blk_size_and_fee_metrics['BlkIntMean'] = blk_size_and_fee_metrics['BlkIntMean'] / 60
```

```python
blk_size_and_fee_metrics.set_index('time')
```

|                           | asset | BlkIntMean | FeeMedUSD |
| ------------------------- | ----- | ---------- | --------- |
| time                      |       |            |           |
| 2024-09-27 17:00:00+00:00 | btc   | 16.208333  | 1.289085  |
| 2024-09-27 18:00:00+00:00 | btc   | 5.725      | 1.061119  |
| 2024-09-27 19:00:00+00:00 | btc   | 12.443333  | 0.405089  |
| 2024-09-27 20:00:00+00:00 | btc   | 5.090909   | 0.317237  |
| 2024-09-27 21:00:00+00:00 | btc   | 10.326667  | 0.339649  |
| ...                       | ...   | ...        | ...       |
| 2024-10-04 10:00:00+00:00 | btc   | 8.87619    | 0.126917  |
| 2024-10-04 11:00:00+00:00 | btc   | 5.666667   | 0.183543  |
| 2024-10-04 12:00:00+00:00 | btc   | 15.95      | 0.208127  |
| 2024-10-04 13:00:00+00:00 | btc   | 5.711667   | 0.175143  |
| 2024-10-04 14:00:00+00:00 | btc   | 10.697222  | 0.320860  |

166 rows × 3 columns

```python
fig, ax1 = plt.subplots(figsize=(16,8))

# Calculate width of bars in terms of the time difference
width = 0.02

ax1.set_title('\nBTC Block Interval vs.\nMedian Tx Fee (1H)\n', color='black', fontsize=16)
ax1.set_facecolor('#212530')

# Bar chart for BlkIntMean
ax1.bar(blk_size_and_fee_metrics['time'], blk_size_and_fee_metrics['BlkIntMean'], width=width, color='#ffb836', label='Mean Block Interval')
ax1.set_xlabel('')
ax1.set_ylabel('Block Interval (mins)\n', fontsize=12.5)
ax1.tick_params(axis='y')

# Set x-axis limits
ax1.set_xlim([blk_size_and_fee_metrics['time'].min(), blk_size_and_fee_metrics['time'].max()])

ax1.grid(axis='x',linestyle='--', color='gray')  # Change gridline color to white for visibility
# Line chart for FeeMeanUSD on a second y-axis
ax2 = ax1.twinx()
ax2.plot(blk_size_and_fee_metrics['time'], blk_size_and_fee_metrics['FeeMedUSD'], color='#62fc98', label='Median Fee (USD)')
ax2.set_ylabel('\nMedian Fee (USD)', fontsize=12.5)
ax2.tick_params(axis='y')

# Display the legend
fig.legend(loc="upper left", bbox_to_anchor=(0.82,1.1), bbox_transform=ax1.transAxes, frameon=False)

plt.show()
```

<figure><img src="/files/f6flqPMj8TKPDFjJGAcB" alt=""><figcaption></figcaption></figure>


# Exploring Options, Open Interest, and Volatility Data

![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/Demo%20Asset%20Resources/CM-Demo-options_exploration-Cover.png)

Options contracts have become an increasingly liquid segment of crypytoasset derivatives. Coin Metrics currently offers options data through various endpoints in our Market Data Feed offering. Available endpoints include market greeks, implied volatility, contract prices, market quotes, open interest, and more.

### Resources

This notebook demonstrates basic functionality offered by the Coin Metrics Python API Client and Market Data Feed.

Coin Metrics offers a vast assortment of data for hundreds of cryptoassets. The Python API Client allows for easy access to this data using Python without needing to create your own wrappers using `requests` and other such libraries.

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics.
* The [Coin Metrics Product Documentation](https://docs.coinmetrics.io/info) gives detailed, conceptual explanations of the data that Coin Metrics offers.
* The [API Spec](https://docs.coinmetrics.io/python-api-client/reference) contains a full list of functions.

### File Download

Download the entire notebook as either a jupyter notebook to run yourself or as a pdf from the two links below

{% file src="/files/SEjKaUBwclV4w8awQCBS" %}

{% file src="/files/KmH1FNZUWBzhWkXQteho" %}

## Notebook Setup

```python
from os import environ
import pandas as pd
import numpy as np
import seaborn as sns
import logging
from datetime import date, timedelta
from coinmetrics.api_client import CoinMetricsClient
import logging
import calendar
from datetime import date
import matplotlib.ticker as mtick
import matplotlib.pyplot as plt
# %matplotlib inline
```

```python
sns.set_theme()
sns.set(rc={'figure.figsize':(18,8)})
sns.set_palette("YlGn",3)
sns.set_style("ticks", {"xtick.major.size":20,"ytick.major.size":20})
sns.set_style("whitegrid",{'axes.grid' : True,'grid.linestyle': '--', 'grid.color': '#b0b0b0','axes.edgecolor': 'white',
              'font.family': ['arial'],'axes.facecolor':'#4b5359'})
```

```python
logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S'
)
```

```python
# We recommend privately storing your API key in your local environment.
try:
    api_key = environ["CM_API_KEY"]
    logging.info("Using API key found in environment")
except KeyError:
    api_key = ""
    logging.info("API key not found. Using community client")
client = CoinMetricsClient(api_key)
```

```
2024-02-13 13:17:42 INFO     Using API key found in environment
```

## Query Examples

#### Retrieving Market Greeks

***

```python
greeks_deribit = client.get_market_greeks(
    markets='deribit-BTC-30DEC22-*-option',
    limit_per_market=1
).to_dataframe()
greeks_deribit.head()
```

|   | market                              | time                      | database\_time                   | vega      | theta     | rho        | delta    | gamma   | exchange\_time                   |
| - | ----------------------------------- | ------------------------- | -------------------------------- | --------- | --------- | ---------- | -------- | ------- | -------------------------------- |
| 0 | deribit-BTC-30DEC22-10000-C-option  | 2022-05-11 14:09:00+00:00 | 2022-05-11 14:09:14.701194+00:00 | 12.95354  | -2.40646  | 58.03478   | 0.97893  | 0.0     | 2022-05-11 14:09:13.336000+00:00 |
| 1 | deribit-BTC-30DEC22-10000-P-option  | 2022-05-11 14:09:00+00:00 | 2022-05-11 14:09:14.701194+00:00 | 12.95354  | -2.40646  | -5.73063   | -0.02107 | 0.0     | 2022-05-11 14:09:13.329000+00:00 |
| 2 | deribit-BTC-30DEC22-100000-C-option | 2021-12-30 08:02:00+00:00 | 2021-12-30 08:02:03.247339+00:00 | 158.05411 | -14.17178 | 86.78939   | 0.24002  | 0.00001 | 2021-12-30 08:02:02.591000+00:00 |
| 3 | deribit-BTC-30DEC22-100000-P-option | 2021-12-30 08:02:00+00:00 | 2021-12-30 08:02:04.257489+00:00 | 156.75983 | -13.9386  | -914.15583 | -0.76354 | 0.00001 | 2021-12-30 08:02:03.416000+00:00 |
| 4 | deribit-BTC-30DEC22-11000-C-option  | 2022-11-16 09:06:00+00:00 | 2022-11-16 09:06:40.873351+00:00 | 9.65147   | -11.41404 | 10.99731   | 0.90588  | 0.00003 | 2022-11-16 09:06:40.094000+00:00 |

#### Retrieving Market Quotes

***

```python
quotes_deribit = client.get_market_quotes(
    markets='deribit-BTC-30DEC22-*-option',
    limit_per_market=1,
).to_dataframe()
quotes_deribit.head()
```

|   | market                              | time                      | coin\_metrics\_id  | ask\_price | ask\_size | bid\_price | bid\_size |
| - | ----------------------------------- | ------------------------- | ------------------ | ---------- | --------- | ---------- | --------- |
| 0 | deribit-BTC-30DEC22-10000-C-option  | 2022-05-11 14:09:00+00:00 | 1652278140000000-0 | 0.0        | 0.0       | 0.0        | 0.0       |
| 1 | deribit-BTC-30DEC22-10000-P-option  | 2022-05-11 14:09:00+00:00 | 1652278140000000-0 | 0.012      | 1.9       | 0.01       | 2.3       |
| 2 | deribit-BTC-30DEC22-100000-C-option | 2021-12-30 08:02:00+00:00 | 1640851320000000-0 | 0.0        | 0.0       | 0.0185     | 2.5       |
| 3 | deribit-BTC-30DEC22-100000-P-option | 2021-12-30 08:02:00+00:00 | 1640851320000000-0 | 0.0        | 0.0       | 0.0        | 0.0       |
| 4 | deribit-BTC-30DEC22-11000-C-option  | 2022-11-16 09:06:00+00:00 | 1668589560000000-0 | 0.0        | 0.0       | 0.0        | 0.0       |

#### Retrieving Contract Prices

***

```python
prices_deribit = client.get_market_contract_prices(
    markets='deribit-BTC-30DEC22-*-option',
    limit_per_market=1,
).to_dataframe()
prices_deribit.head()
```

|   | market                              | time                      | database\_time                   | mark\_price | index\_price | exchange\_time                   |
| - | ----------------------------------- | ------------------------- | -------------------------------- | ----------- | ------------ | -------------------------------- |
| 0 | deribit-BTC-30DEC22-10000-C-option  | 2022-05-11 14:09:00+00:00 | 2022-05-11 14:09:14.701194+00:00 | 0.695       | 31350.76     | 2022-05-11 14:09:13.336000+00:00 |
| 1 | deribit-BTC-30DEC22-10000-P-option  | 2022-05-11 14:09:00+00:00 | 2022-05-11 14:09:14.701194+00:00 | 0.007       | 31350.76     | 2022-05-11 14:09:13.329000+00:00 |
| 2 | deribit-BTC-30DEC22-100000-C-option | 2021-12-30 08:02:00+00:00 | 2021-12-30 08:02:03.247339+00:00 | 0.069329    | 47033.61     | 2021-12-30 08:02:02.591000+00:00 |
| 3 | deribit-BTC-30DEC22-100000-P-option | 2021-12-30 08:02:00+00:00 | 2021-12-30 08:02:04.257489+00:00 | 1.034568    | 47034.05     | 2021-12-30 08:02:03.416000+00:00 |
| 4 | deribit-BTC-30DEC22-11000-C-option  | 2022-11-16 09:06:00+00:00 | 2022-11-16 09:06:40.873351+00:00 | 0.3547      | 16744.61     | 2022-11-16 09:06:40.094000+00:00 |

#### Retrieving Open Interest

***

```python
oi_deribit = client.get_market_open_interest(
    markets='deribit-BTC-30DEC22-*-option',
    limit_per_market=1,
).to_dataframe()
oi_deribit.head()
```

|   | market                              | time                      | contract\_count | value\_usd | database\_time                   | exchange\_time            |
| - | ----------------------------------- | ------------------------- | --------------- | ---------- | -------------------------------- | ------------------------- |
| 0 | deribit-BTC-30DEC22-10000-C-option  | 2022-05-11 14:09:00+00:00 | 0               | 0          | 2022-05-11 14:09:39.584165+00:00 | 2022-05-11 14:09:00+00:00 |
| 1 | deribit-BTC-30DEC22-10000-P-option  | 2022-05-11 14:09:00+00:00 | 0               | 0          | 2022-05-11 14:09:39.584165+00:00 | 2022-05-11 14:09:00+00:00 |
| 2 | deribit-BTC-30DEC22-100000-C-option | 2021-12-30 08:02:00+00:00 | 0               | 0          | 2021-12-30 08:02:35.912527+00:00 | 2021-12-30 08:02:00+00:00 |
| 3 | deribit-BTC-30DEC22-100000-P-option | 2021-12-30 08:02:00+00:00 | 0               | 0          | 2021-12-30 08:02:37.918026+00:00 | 2021-12-30 08:02:00+00:00 |
| 4 | deribit-BTC-30DEC22-11000-C-option  | 2022-11-16 09:06:00+00:00 | 0               | 0          | 2022-11-16 09:06:24.566250+00:00 | 2022-11-16 09:06:00+00:00 |

## Plotting Options 'Volatility Smiles'

***

'Volatility smiles' are a popular options data visualization tool that help traders understand predicted asset volatility across various contract expiration dates. The 'smile' is plotted by mapping the strike price and implied volatility of a group of options with the same underlying asset and expiration date.

```python
asset = 'btc'
```

#### Catalog Endpoint

The Coin Metrics API contains two types of catalog endpoints (Python client functions in paranthesis): the `catalog` (`catalog_*`) and `catalog-all` (`catalog_full_*`). The `catalog` endpoint displays the set of data available to your API key. The `catalog-all` endpoint displays the full set of data for CM Pro users.

Catalog objects return a list of dictionaries. For `catalog_full_market_implied_volatility_v2`, each element of the list is an option market that supports implied volatility data.

```python
markets_deribit = client.catalog_full_market_implied_volatility_v2(
    exchange='deribit',
    market_type='option',
    base=asset,
    page_size=10000
).to_dataframe()
```

```python
markets_deribit.sort_values(by='max_time')
```

|       | market                             | min\_time                 | max\_time                 |
| ----- | ---------------------------------- | ------------------------- | ------------------------- |
| 29064 | deribit-BTC-2SEP21-53000-C-option  | 2021-09-01 13:24:00+00:00 | 2021-09-02 08:00:00+00:00 |
| 29049 | deribit-BTC-2SEP21-45000-P-option  | 2021-09-01 13:24:00+00:00 | 2021-09-02 08:00:00+00:00 |
| 29048 | deribit-BTC-2SEP21-45000-C-option  | 2021-09-01 13:24:00+00:00 | 2021-09-02 08:00:00+00:00 |
| 29046 | deribit-BTC-2SEP21-44000-C-option  | 2021-09-01 13:24:00+00:00 | 2021-09-02 08:00:00+00:00 |
| 29045 | deribit-BTC-2SEP21-43000-P-option  | 2021-09-01 13:24:00+00:00 | 2021-09-02 08:00:00+00:00 |
| ...   | ...                                | ...                       | ...                       |
| 24053 | deribit-BTC-27DEC24-61000-P-option | 2024-01-02 11:29:00+00:00 | 2024-02-13 17:43:00+00:00 |
| 24054 | deribit-BTC-27DEC24-62000-C-option | 2024-01-08 22:41:00+00:00 | 2024-02-13 17:43:00+00:00 |
| 24055 | deribit-BTC-27DEC24-62000-P-option | 2024-01-08 22:41:00+00:00 | 2024-02-13 17:43:00+00:00 |
| 24049 | deribit-BTC-27DEC24-59000-P-option | 2024-01-02 03:35:00+00:00 | 2024-02-13 17:43:00+00:00 |
| 27297 | deribit-BTC-29MAR24-26000-P-option | 2023-03-30 08:03:00+00:00 | 2024-02-13 17:43:00+00:00 |

40442 rows × 3 columns

```python
markets_deribit["min_time"] = pd.to_datetime(markets_deribit.min_time)
markets_deribit["max_time"] = pd.to_datetime(markets_deribit.max_time)
```

```python
# Select contracts that are still trading as of yesterday
end_date = (date.today() - timedelta(days=1)).strftime("%Y-%m-%d") 
deribit_current = markets_deribit.loc[(markets_deribit["max_time"] >= end_date)]
```

#### Collect Contract Reference Data

```python
ref_data = client.reference_data_markets(
    exchange = 'deribit',
    type = 'option',
    base = asset,
    page_size=10000
).to_dataframe()
```

```python
ref_data.head()
```

|   | market                            | exchange | type   | base | quote | pair    | symbol             | size\_asset | strike | option\_contract\_type | is\_european | contract\_size | listing                        | expiration                     | settlement\_price | status  | order\_amount\_min | order\_price\_increment | order\_taker\_fee | order\_maker\_fee |
| - | --------------------------------- | -------- | ------ | ---- | ----- | ------- | ------------------ | ----------- | ------ | ---------------------- | ------------ | -------------- | ------------------------------ | ------------------------------ | ----------------- | ------- | ------------------ | ----------------------- | ----------------- | ----------------- |
| 0 | deribit-BTC-10APR20-4750-C-option | deribit  | option | btc  | usd   | btc-usd | BTC-10APR20-4750-C | btc         | 4750   | call                   | True         | 1              | 2020-03-28T03:21:00.000000000Z | 2020-04-10T08:00:00.000000000Z | 6931.78           | offline | 0.1                | 0.0005                  | 0.0004            | 0.0004            |
| 1 | deribit-BTC-10APR20-4750-P-option | deribit  | option | btc  | usd   | btc-usd | BTC-10APR20-4750-P | btc         | 4750   | put                    | True         | 1              | 2020-03-28T03:21:00.000000000Z | 2020-04-10T08:00:00.000000000Z | 6931.78           | offline | 0.1                | 0.0005                  | 0.0004            | 0.0004            |
| 2 | deribit-BTC-10APR20-5000-C-option | deribit  | option | btc  | usd   | btc-usd | BTC-10APR20-5000-C | btc         | 5000   | call                   | True         | 1              | 2020-03-26T08:19:00.000000000Z | 2020-04-10T08:00:00.000000000Z | 6931.78           | offline | 0.1                | 0.0005                  | 0.0004            | 0.0004            |
| 3 | deribit-BTC-10APR20-5000-P-option | deribit  | option | btc  | usd   | btc-usd | BTC-10APR20-5000-P | btc         | 5000   | put                    | True         | 1              | 2020-03-26T08:19:00.000000000Z | 2020-04-10T08:00:00.000000000Z | 6931.78           | offline | 0.1                | 0.0005                  | 0.0004            | 0.0004            |
| 4 | deribit-BTC-10APR20-5250-P-option | deribit  | option | btc  | usd   | btc-usd | BTC-10APR20-5250-P | btc         | 5250   | put                    | True         | 1              | 2020-03-26T08:00:08.000000000Z | 2020-04-10T08:00:00.000000000Z | 6931.78           | offline | 0.1                | 0.0005                  | 0.0004            | 0.0004            |

```python
deribit_current = pd.merge(deribit_current, ref_data[['market','expiration','option_contract_type','strike']], on='market', how='left')
```

```python
# Set max expiration date
max_expiry = (date.today() + timedelta(days=365)).strftime("%Y-%m-%d")
max_expiry = (pd.to_datetime(max_expiry)).strftime("%Y-%m-%d")
deribit_current = pd.DataFrame(deribit_current.loc[(deribit_current["expiration"] < max_expiry)])
```

```python
deribit_current = deribit_current.sort_values(by=['expiration'])
```

```python
deribit_current
```

|     | market                              | min\_time                 | max\_time                 | expiration                     | option\_contract\_type | strike |
| --- | ----------------------------------- | ------------------------- | ------------------------- | ------------------------------ | ---------------------- | ------ |
| 0   | deribit-BTC-12FEB24-41000-C-option  | 2024-02-09 08:03:00+00:00 | 2024-02-12 08:00:00+00:00 | 2024-02-12T08:00:00.000000000Z | call                   | 41000  |
| 36  | deribit-BTC-12FEB24-48750-C-option  | 2024-02-11 08:03:00+00:00 | 2024-02-12 08:00:00+00:00 | 2024-02-12T08:00:00.000000000Z | call                   | 48750  |
| 37  | deribit-BTC-12FEB24-48750-P-option  | 2024-02-11 08:03:00+00:00 | 2024-02-12 08:00:00+00:00 | 2024-02-12T08:00:00.000000000Z | put                    | 48750  |
| 38  | deribit-BTC-12FEB24-49000-C-option  | 2024-02-09 08:03:00+00:00 | 2024-02-12 08:00:00+00:00 | 2024-02-12T08:00:00.000000000Z | call                   | 49000  |
| 39  | deribit-BTC-12FEB24-49000-P-option  | 2024-02-09 08:03:00+00:00 | 2024-02-12 08:00:00+00:00 | 2024-02-12T08:00:00.000000000Z | put                    | 49000  |
| ... | ...                                 | ...                       | ...                       | ...                            | ...                    | ...    |
| 557 | deribit-BTC-27DEC24-120000-P-option | 2023-12-28 08:02:00+00:00 | 2024-02-13 17:43:00+00:00 | 2024-12-27T08:00:00.000000000Z | put                    | 120000 |
| 558 | deribit-BTC-27DEC24-125000-C-option | 2023-12-28 08:02:00+00:00 | 2024-02-13 17:43:00+00:00 | 2024-12-27T08:00:00.000000000Z | call                   | 125000 |
| 559 | deribit-BTC-27DEC24-125000-P-option | 2023-12-28 08:02:00+00:00 | 2024-02-13 17:43:00+00:00 | 2024-12-27T08:00:00.000000000Z | put                    | 125000 |
| 547 | deribit-BTC-27DEC24-10000-P-option  | 2023-12-28 08:02:00+00:00 | 2024-02-13 17:43:00+00:00 | 2024-12-27T08:00:00.000000000Z | put                    | 10000  |
| 579 | deribit-BTC-27DEC24-28000-P-option  | 2023-12-28 18:57:00+00:00 | 2024-02-13 17:43:00+00:00 | 2024-12-27T08:00:00.000000000Z | put                    | 28000  |

1008 rows × 6 columns

### Retrieve Implied Volatility

```python
iv_asset_contracts = client.get_market_implied_volatility(
    markets='deribit-*-option',
    start_time = end_date,
    limit_per_market=1,
    page_size=10000
).to_dataframe()
```

```python
iv_asset_contracts = iv_asset_contracts.loc[iv_asset_contracts['market'].isin(deribit_current['market'].to_list())]
iv_asset_contracts
```

|      | market                             | time                      | database\_time                   | iv\_bid | iv\_ask | iv\_mark | exchange\_time                   |
| ---- | ---------------------------------- | ------------------------- | -------------------------------- | ------- | ------- | -------- | -------------------------------- |
| 0    | deribit-BTC-12FEB24-41000-C-option | 2024-02-12 00:00:00+00:00 | 2024-02-12 00:00:15.649992+00:00 | 0.0     | 0.0     | 0.677    | 2024-02-12 00:00:13.899000+00:00 |
| 1    | deribit-BTC-12FEB24-41000-P-option | 2024-02-12 00:00:00+00:00 | 2024-02-12 00:00:14.602653+00:00 | 0.0     | 2.1273  | 0.677    | 2024-02-12 00:00:13.900000+00:00 |
| 2    | deribit-BTC-12FEB24-42000-C-option | 2024-02-12 00:00:00+00:00 | 2024-02-12 00:00:03.599239+00:00 | 0.0     | 3.0076  | 0.6176   | 2024-02-12 00:00:02.821000+00:00 |
| 3    | deribit-BTC-12FEB24-42000-P-option | 2024-02-12 00:00:00+00:00 | 2024-02-12 00:00:03.599239+00:00 | 0.0     | 2.1175  | 0.6176   | 2024-02-12 00:00:00.808000+00:00 |
| 4    | deribit-BTC-12FEB24-42500-C-option | 2024-02-12 00:00:00+00:00 | 2024-02-12 00:00:12.040598+00:00 | 0.0     | 0.0     | 0.5786   | 2024-02-12 00:00:09.872000+00:00 |
| ...  | ...                                | ...                       | ...                              | ...     | ...     | ...      | ...                              |
| 1001 | deribit-BTC-29MAR24-80000-P-option | 2024-02-12 00:00:00+00:00 | 2024-02-12 00:00:16.038858+00:00 | 0.0     | 0.8866  | 0.6928   | 2024-02-12 00:00:13.898000+00:00 |
| 1002 | deribit-BTC-29MAR24-85000-C-option | 2024-02-12 00:00:00+00:00 | 2024-02-12 00:00:04.033371+00:00 | 0.7072  | 0.7288  | 0.7195   | 2024-02-12 00:00:03.827000+00:00 |
| 1003 | deribit-BTC-29MAR24-85000-P-option | 2024-02-12 00:00:00+00:00 | 2024-02-12 00:00:10.038068+00:00 | 0.0     | 0.8934  | 0.7194   | 2024-02-12 00:00:08.863000+00:00 |
| 1004 | deribit-BTC-29MAR24-90000-C-option | 2024-02-12 00:00:00+00:00 | 2024-02-12 00:00:04.033371+00:00 | 0.7248  | 0.7476  | 0.7409   | 2024-02-12 00:00:02.820000+00:00 |
| 1005 | deribit-BTC-29MAR24-90000-P-option | 2024-02-12 00:00:00+00:00 | 2024-02-12 00:00:11.038214+00:00 | 0.0     | 0.9518  | 0.7408   | 2024-02-12 00:00:09.870000+00:00 |

1006 rows × 7 columns

```python
iv_only = iv_asset_contracts.drop(['time', 'database_time','iv_bid','iv_ask','exchange_time'], axis=1).drop_duplicates()
iv_only
```

|      | market                             | iv\_mark |
| ---- | ---------------------------------- | -------- |
| 0    | deribit-BTC-12FEB24-41000-C-option | 0.677    |
| 1    | deribit-BTC-12FEB24-41000-P-option | 0.677    |
| 2    | deribit-BTC-12FEB24-42000-C-option | 0.6176   |
| 3    | deribit-BTC-12FEB24-42000-P-option | 0.6176   |
| 4    | deribit-BTC-12FEB24-42500-C-option | 0.5786   |
| ...  | ...                                | ...      |
| 1001 | deribit-BTC-29MAR24-80000-P-option | 0.6928   |
| 1002 | deribit-BTC-29MAR24-85000-C-option | 0.7195   |
| 1003 | deribit-BTC-29MAR24-85000-P-option | 0.7194   |
| 1004 | deribit-BTC-29MAR24-90000-C-option | 0.7409   |
| 1005 | deribit-BTC-29MAR24-90000-P-option | 0.7408   |

1006 rows × 2 columns

```python
merged = pd.merge(deribit_current, iv_only, on="market").drop_duplicates()
```

```python
calls = pd.DataFrame(merged.loc[merged['option_contract_type'] == 'call'])
```

```python
calls['expiration'] = pd.to_datetime(calls['expiration']).dt.strftime('%b %d, %Y')
calls = calls.dropna(subset=['strike'])
calls['strike'] = calls['strike'].astype('int64')
calls['iv_mark'] = calls['iv_mark'].astype('float64')
calls['expiration'] = calls['expiration'].astype('category')
calls = calls.dropna(subset=['strike', 'iv_mark'])
calls = calls[np.isfinite(calls['strike']) & np.isfinite(calls['iv_mark'])]
calls
```

|      | market                              | min\_time                 | max\_time                 | expiration   | option\_contract\_type | strike | iv\_mark |
| ---- | ----------------------------------- | ------------------------- | ------------------------- | ------------ | ---------------------- | ------ | -------- |
| 0    | deribit-BTC-12FEB24-41000-C-option  | 2024-02-09 08:03:00+00:00 | 2024-02-12 08:00:00+00:00 | Feb 12, 2024 | call                   | 41000  | 0.6770   |
| 1    | deribit-BTC-12FEB24-48750-C-option  | 2024-02-11 08:03:00+00:00 | 2024-02-12 08:00:00+00:00 | Feb 12, 2024 | call                   | 48750  | 0.3703   |
| 3    | deribit-BTC-12FEB24-49000-C-option  | 2024-02-09 08:03:00+00:00 | 2024-02-12 08:00:00+00:00 | Feb 12, 2024 | call                   | 49000  | 0.3908   |
| 5    | deribit-BTC-12FEB24-49250-C-option  | 2024-02-11 08:14:00+00:00 | 2024-02-12 08:00:00+00:00 | Feb 12, 2024 | call                   | 49250  | 0.4235   |
| 7    | deribit-BTC-12FEB24-49500-C-option  | 2024-02-09 08:03:00+00:00 | 2024-02-12 08:00:00+00:00 | Feb 12, 2024 | call                   | 49500  | 0.4815   |
| ...  | ...                                 | ...                       | ...                       | ...          | ...                    | ...    | ...      |
| 994  | deribit-BTC-27DEC24-105000-C-option | 2023-12-28 08:02:00+00:00 | 2024-02-13 17:43:00+00:00 | Dec 27, 2024 | call                   | 105000 | 0.6558   |
| 996  | deribit-BTC-27DEC24-110000-C-option | 2023-12-28 08:02:00+00:00 | 2024-02-13 17:43:00+00:00 | Dec 27, 2024 | call                   | 110000 | 0.6580   |
| 998  | deribit-BTC-27DEC24-115000-C-option | 2023-12-28 08:02:00+00:00 | 2024-02-13 17:43:00+00:00 | Dec 27, 2024 | call                   | 115000 | 0.6633   |
| 1000 | deribit-BTC-27DEC24-120000-C-option | 2023-12-28 08:02:00+00:00 | 2024-02-13 17:43:00+00:00 | Dec 27, 2024 | call                   | 120000 | 0.6656   |
| 1002 | deribit-BTC-27DEC24-125000-C-option | 2023-12-28 08:02:00+00:00 | 2024-02-13 17:43:00+00:00 | Dec 27, 2024 | call                   | 125000 | 0.6690   |

503 rows × 7 columns

```python
calls = calls.sort_values(by='expiration')
```

```python
calls.dtypes
```

```
market                       string[python]
min_time                datetime64[ns, UTC]
max_time                datetime64[ns, UTC]
expiration                         category
option_contract_type         string[python]
strike                                int64
iv_mark                             float64
dtype: object
```

```python
l = sns.lineplot(data=calls, x="strike", y="iv_mark", hue='expiration')
l.set_xlabel("\nStrike Price", fontsize = 17)
l.set_ylabel("Implied Volatility \n", fontsize = 17)
l.set_xlim([0, calls['strike'].max()])

l.set_xticks(l.get_xticks().tolist())
l.set_xticklabels(['${:,.0f}'.format(x) for x in l.get_xticks().tolist()],fontsize=14)
l.set_yticks(l.get_yticks().tolist())
l.set_yticklabels(['{:.2f}'.format(y) for y in l.get_yticks().tolist()],fontsize=14)
plt.setp(l.get_yticklabels()[0], visible=False)    
leg = plt.legend(loc='upper right',ncol=2,fontsize=13.5)
for text in leg.get_texts():
    text.set_color("white")
l.set_title('\n' + asset.upper() + ' Volatility Smiles\n', fontsize = 25)
plt.suptitle('\n\n         Deribit Options by Expiration',fontsize=16);
```

<figure><img src="/files/6HGpCCbAFE03vtsZCkZ0" alt=""><figcaption></figcaption></figure>

## Plotting Calls vs. Puts by Open Interest

```python
options_oi = client.get_market_open_interest(
    markets='deribit-*-option',
    limit_per_market=1,
    paging_from='end',
    start_time=end_date,
    page_size=10000
).to_dataframe()
```

```python
options_oi['value_usd'] = pd.to_numeric(options_oi['value_usd'])
options_oi = options_oi.loc[options_oi['value_usd'] > 0]
```

```python
options_oi = options_oi.sort_values('value_usd',ascending=False)
```

```python
oi_only = options_oi[['market','contract_count','value_usd']]
```

```python
oi_only
```

|      | market                             | contract\_count | value\_usd    |
| ---- | ---------------------------------- | --------------- | ------------- |
| 1356 | deribit-ETH-23FEB24-2400-C-option  | 97938.0         | 256834569.96  |
| 972  | deribit-BTC-29MAR24-50000-C-option | 5204.3          | 254888763.251 |
| 992  | deribit-BTC-29MAR24-60000-C-option | 4830.8          | 236604371.64  |
| 1716 | deribit-ETH-29MAR24-3000-C-option  | 86689.0         | 227343636.28  |
| 994  | deribit-BTC-29MAR24-65000-C-option | 4572.5          | 223940793.825 |
| ...  | ...                                | ...             | ...           |
| 1511 | deribit-ETH-27DEC24-6000-P-option  | 1.0             | 2622.57       |
| 1599 | deribit-ETH-27SEP24-7500-P-option  | 1.0             | 2622.53       |
| 1593 | deribit-ETH-27SEP24-6000-P-option  | 1.0             | 2622.52       |
| 1177 | deribit-ETH-15FEB24-2200-P-option  | 1.0             | 2622.37       |
| 1737 | deribit-ETH-29MAR24-5000-P-option  | 1.0             | 2622.27       |

1387 rows × 3 columns

```python
asset_deribit_oi = deribit_current[['market','expiration','strike','option_contract_type']]
```

```python
oi_merged = pd.merge(asset_deribit_oi, oi_only, on="market").drop_duplicates()
```

```python
oi_merged
```

|     | market                              | expiration                     | strike | option\_contract\_type | contract\_count | value\_usd  |
| --- | ----------------------------------- | ------------------------------ | ------ | ---------------------- | --------------- | ----------- |
| 0   | deribit-BTC-12FEB24-48750-C-option  | 2024-02-12T08:00:00.000000000Z | 48750  | call                   | 61.3            | 2959931.187 |
| 1   | deribit-BTC-12FEB24-48750-P-option  | 2024-02-12T08:00:00.000000000Z | 48750  | put                    | 4.7             | 226944.294  |
| 2   | deribit-BTC-12FEB24-49000-C-option  | 2024-02-12T08:00:00.000000000Z | 49000  | call                   | 141.1           | 6813157.422 |
| 3   | deribit-BTC-12FEB24-49250-C-option  | 2024-02-12T08:00:00.000000000Z | 49250  | call                   | 6.6             | 318687.732  |
| 4   | deribit-BTC-12FEB24-49500-C-option  | 2024-02-12T08:00:00.000000000Z | 49500  | call                   | 28.6            | 1380979.028 |
| ... | ...                                 | ...                            | ...    | ...                    | ...             | ...         |
| 820 | deribit-BTC-27DEC24-120000-P-option | 2024-12-27T08:00:00.000000000Z | 120000 | put                    | 1.3             | 63681.397   |
| 821 | deribit-BTC-27DEC24-125000-C-option | 2024-12-27T08:00:00.000000000Z | 125000 | call                   | 37.9            | 1856453.805 |
| 822 | deribit-BTC-27DEC24-125000-P-option | 2024-12-27T08:00:00.000000000Z | 125000 | put                    | 1.6             | 78372.704   |
| 823 | deribit-BTC-27DEC24-10000-P-option  | 2024-12-27T08:00:00.000000000Z | 10000  | put                    | 20.7            | 1013795.748 |
| 824 | deribit-BTC-27DEC24-28000-P-option  | 2024-12-27T08:00:00.000000000Z | 28000  | put                    | 132.1           | 6470647.695 |

825 rows × 6 columns

```python
oi_merged.expiration = pd.to_datetime(oi_merged.expiration).dt.strftime('%b %d, %Y')
oi_merged
```

|     | market                              | expiration   | strike | option\_contract\_type | contract\_count | value\_usd  |
| --- | ----------------------------------- | ------------ | ------ | ---------------------- | --------------- | ----------- |
| 0   | deribit-BTC-12FEB24-48750-C-option  | Feb 12, 2024 | 48750  | call                   | 61.3            | 2959931.187 |
| 1   | deribit-BTC-12FEB24-48750-P-option  | Feb 12, 2024 | 48750  | put                    | 4.7             | 226944.294  |
| 2   | deribit-BTC-12FEB24-49000-C-option  | Feb 12, 2024 | 49000  | call                   | 141.1           | 6813157.422 |
| 3   | deribit-BTC-12FEB24-49250-C-option  | Feb 12, 2024 | 49250  | call                   | 6.6             | 318687.732  |
| 4   | deribit-BTC-12FEB24-49500-C-option  | Feb 12, 2024 | 49500  | call                   | 28.6            | 1380979.028 |
| ... | ...                                 | ...          | ...    | ...                    | ...             | ...         |
| 820 | deribit-BTC-27DEC24-120000-P-option | Dec 27, 2024 | 120000 | put                    | 1.3             | 63681.397   |
| 821 | deribit-BTC-27DEC24-125000-C-option | Dec 27, 2024 | 125000 | call                   | 37.9            | 1856453.805 |
| 822 | deribit-BTC-27DEC24-125000-P-option | Dec 27, 2024 | 125000 | put                    | 1.6             | 78372.704   |
| 823 | deribit-BTC-27DEC24-10000-P-option  | Dec 27, 2024 | 10000  | put                    | 20.7            | 1013795.748 |
| 824 | deribit-BTC-27DEC24-28000-P-option  | Dec 27, 2024 | 28000  | put                    | 132.1           | 6470647.695 |

825 rows × 6 columns

```python
oi_merged_sum = oi_merged.groupby(
        ['expiration', 'option_contract_type']).value_usd.sum().reset_index()
```

```python
oi_merged_sum
```

|    | expiration   | option\_contract\_type | value\_usd     |
| -- | ------------ | ---------------------- | -------------- |
| 0  | Apr 26, 2024 | call                   | 746759409.804  |
| 1  | Apr 26, 2024 | put                    | 362391927.898  |
| 2  | Dec 27, 2024 | call                   | 327845484.001  |
| 3  | Dec 27, 2024 | put                    | 76852459.777   |
| 4  | Feb 12, 2024 | call                   | 61221827.396   |
| 5  | Feb 12, 2024 | put                    | 53636084.351   |
| 6  | Feb 13, 2024 | call                   | 60612528.457   |
| 7  | Feb 13, 2024 | put                    | 55888112.274   |
| 8  | Feb 14, 2024 | call                   | 62115453.667   |
| 9  | Feb 14, 2024 | put                    | 47578321.782   |
| 10 | Feb 15, 2024 | call                   | 15652452.769   |
| 11 | Feb 15, 2024 | put                    | 19036582.686   |
| 12 | Feb 16, 2024 | call                   | 486055096.137  |
| 13 | Feb 16, 2024 | put                    | 407674392.781  |
| 14 | Feb 23, 2024 | call                   | 1849252067.898 |
| 15 | Feb 23, 2024 | put                    | 1101826630.192 |
| 16 | Jun 28, 2024 | call                   | 1703153232.984 |
| 17 | Jun 28, 2024 | put                    | 446922981.015  |
| 18 | Mar 01, 2024 | call                   | 150328051.677  |
| 19 | Mar 01, 2024 | put                    | 105881633.482  |
| 20 | Mar 29, 2024 | call                   | 2641595742.536 |
| 21 | Mar 29, 2024 | put                    | 1245411237.802 |
| 22 | Sep 27, 2024 | call                   | 480871248.568  |
| 23 | Sep 27, 2024 | put                    | 169771991.037  |

```python
calls_oi = pd.DataFrame(oi_merged_sum.loc[oi_merged_sum['option_contract_type'] == 'call'])
puts_oi = pd.DataFrame(oi_merged_sum.loc[oi_merged_sum['option_contract_type'] == 'put'])
```

```python
# Convert 'expiration' to datetime and extract month
calls_oi['expiration'] = pd.to_datetime(calls_oi['expiration'])
calls_oi['Expiration Month'] = calls_oi['expiration'].dt.month

puts_oi['expiration'] = pd.to_datetime(puts_oi['expiration'])
puts_oi['Expiration Month'] = puts_oi['expiration'].dt.month

# Group by 'expiration_month' and sum 'value_usd'
calls_oi_grouped = calls_oi.groupby('Expiration Month')['value_usd'].sum()
puts_oi_grouped = puts_oi.groupby('Expiration Month')['value_usd'].sum()

# Convert Series to DataFrame and reset index
calls_oi_df = calls_oi_grouped.reset_index()
puts_oi_df = puts_oi_grouped.reset_index()

# Replace month numbers with month names
calls_oi_df['Expiration Month'] = calls_oi_df['Expiration Month'].apply(lambda x: calendar.month_name[x])
puts_oi_df['Expiration Month'] = puts_oi_df['Expiration Month'].apply(lambda x: calendar.month_name[x])
```

```python
calls_oi_df
```

|   | Expiration Month | value\_usd     |
| - | ---------------- | -------------- |
| 0 | February         | 2534909426.324 |
| 1 | March            | 2791923794.213 |
| 2 | April            | 746759409.804  |
| 3 | June             | 1703153232.984 |
| 4 | September        | 480871248.568  |
| 5 | December         | 327845484.001  |

```python
# Add a new column to distinguish between calls and puts
calls_oi_df['type'] = 'calls'
puts_oi_df['type'] = 'puts'

# Concatenate the dataframes
df = pd.concat([calls_oi_df, puts_oi_df])
df = df.rename(columns={"value_usd": "Open Interest (USD)"})

# Plot the bars side by side
p = sns.barplot(data=df, x='Expiration Month', y='Open Interest (USD)', hue='type', palette=['green', 'red'])
p.set_title('\nBTC Options Open Interest (USD)\nby Expiration Month\n',fontsize=16)
# Format y-axis in billions
fmt = '${x:,.0f}B'
p.legend_.remove()

tick = mtick.FuncFormatter(lambda x, pos: '${:,.2f}B'.format(x*1e-9))
p.yaxis.set_major_formatter(tick)
```

```
2024-02-13 13:18:16 INFO     Using categorical units to plot a list of strings that are all parsable as floats or dates. If these strings should be plotted as numbers, cast to the appropriate data type before plotting.
2024-02-13 13:18:16 INFO     Using categorical units to plot a list of strings that are all parsable as floats or dates. If these strings should be plotted as numbers, cast to the appropriate data type before plotting.

```

<figure><img src="/files/kkJyHjjMmVIsovQzCzx3" alt=""><figcaption></figcaption></figure>


# Calculating Total Value Locked in Liquidity Pools using DEX Data

![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/Demo%20Asset%20Resources/Demo%20Covers/CM-Demo-pool_tvl-Cover.png)

Automated Market Makers (AMMs) are an innovative new class of smart contracts introduced in decentralized exchange protocols like Uniswap, allowing users to permissionlessly provision liquidity for digital asset trading activity without needing a traditional central order book. However, an important aspect of providing users of these pools is understanding how the total USD value of the assets allocated to the contract can fluctuate over time, leading to impermanent loss for liquidity providers. In this notebook, we explore how Coin Metrics DEX market metadata can be combined with Reference Rates and ATLAS search engine capabilities to construct a timeseries representation pool TVL, allowing market participants to make more informed decisions about DEX market making and trading.

### Resources

This notebook demonstrates basic functionality offered by the Coin Metrics Python API Client, ATLAS blockchain search engine, and DEX Market Data.

Coin Metrics offers a vast assortment of data for hundreds of cryptoassets. The Python API Client allows for easy access to this data using Python without needing to create your own wrappers using `requests` and other such libraries.

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics.
* The [Coin Metrics Product Documentation](https://docs.coinmetrics.io/info) gives detailed, conceptual explanations of the data that Coin Metrics offers.
* The [API Spec](https://docs.coinmetrics.io/python-api-client/reference) contains a full list of functions.

### File Download

Download the entire notebook as either a jupyter notebook to run yourself or as a pdf from the two links below

{% file src="/files/aOmAbNeewMYhsViSFf9K" %}

{% file src="/files/Wy86yHAeJ6LFbafDlDpH" %}

### Notebook Setup

```python
from os import environ
import sys
import pandas as pd
import numpy as np
import logging
from datetime import date, datetime, timedelta
from coinmetrics.api_client import CoinMetricsClient
import plotly.graph_objs as go
import logging
from pytz import timezone as timezone_conv
from datetime import timezone as timezone_info
from dateutil.relativedelta import relativedelta
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
# %matplotlib inline
```

```python
logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S'
)
```

```python
# We recommend privately storing your API key in your local environment.
try:
    api_key = environ["CM_API_KEY"]
    logging.info("Using API key found in environment")
except KeyError:
    api_key = ""
    logging.info("API key not found. Using community client")
    
client = CoinMetricsClient(api_key)
```

```
2024-10-09 14:36:29 INFO     Using API key found in environment
```

## DEX Market Reference Data

The *reference-data/markets* endpoint returns a list of available markets meeting specified criteria. Users can pass in a list of markets, exchanges, or market types (spot, futures, options). For DEX markets, the endpoint also returns key liquidity pool metadata, such as fee tier and pool contract address.

```python
uni_v3_markets = client.reference_data_markets(
    exchange = 'uniswap_v3_eth'
).to_dataframe()
```

```python
uni_v3_markets
```

|      | market                                        | exchange         | base       | quote      | pair                  | symbol | type | size\_asset | margin\_asset | strike | ... | order\_price\_increment | order\_price\_min | order\_price\_max | order\_size\_min | order\_taker\_fee | order\_maker\_fee | margin\_trading\_enabled | experimental | base\_native | quote\_native |
| ---- | --------------------------------------------- | ---------------- | ---------- | ---------- | --------------------- | ------ | ---- | ----------- | ------------- | ------ | --- | ----------------------- | ----------------- | ----------------- | ---------------- | ----------------- | ----------------- | ------------------------ | ------------ | ------------ | ------------- |
| 0    | uniswap\_v3\_eth-1-1inch-dai-spot             | uniswap\_v3\_eth | 1inch      | dai        | 1inch-dai             | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 1    | uniswap\_v3\_eth-1-1inch-usdc-spot            | uniswap\_v3\_eth | 1inch      | usdc       | 1inch-usdc            | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 2    | uniswap\_v3\_eth-1-1inch-weth-spot            | uniswap\_v3\_eth | 1inch      | weth       | 1inch-weth            | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 3    | uniswap\_v3\_eth-1-ageur\_eth-eurcv\_eth-spot | uniswap\_v3\_eth | ageur\_eth | eurcv\_eth | ageur\_eth-eurcv\_eth | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 4    | uniswap\_v3\_eth-1-ageur\_eth-usdc-spot       | uniswap\_v3\_eth | ageur\_eth | usdc       | ageur\_eth-usdc       | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| ...  | ...                                           | ...              | ...        | ...        | ...                   | ...    | ...  | ...         | ...           | ...    | ... | ...                     | ...               | ...               | ...              | ...               | ...               | ...                      | ...          | ...          | ...           |
| 1638 | uniswap\_v3\_eth-agg-yfi-cvx-spot             | uniswap\_v3\_eth | yfi        | cvx        | yfi-cvx               | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 1639 | uniswap\_v3\_eth-agg-yfi-link-spot            | uniswap\_v3\_eth | yfi        | link       | yfi-link              | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 1640 | uniswap\_v3\_eth-agg-yfi-usdc-spot            | uniswap\_v3\_eth | yfi        | usdc       | yfi-usdc              | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 1641 | uniswap\_v3\_eth-agg-yfi-wbtc-spot            | uniswap\_v3\_eth | yfi        | wbtc       | yfi-wbtc              | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 1642 | uniswap\_v3\_eth-agg-yfi-weth-spot            | uniswap\_v3\_eth | yfi        | weth       | yfi-weth              | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |

1643 rows × 39 columns

```python
weth_usdc_markets = uni_v3_markets.loc[(uni_v3_markets['base']=='usdc') & (uni_v3_markets['quote']=='weth')]
```

```python
weth_usdc_pools = weth_usdc_markets.dropna(subset=['contract_address'])
weth_usdc_pools
```

|      | market                            | exchange         | base | quote | pair      | symbol | type | size\_asset | margin\_asset | strike | ... | order\_price\_increment | order\_price\_min | order\_price\_max | order\_size\_min | order\_taker\_fee | order\_maker\_fee | margin\_trading\_enabled | experimental | base\_native | quote\_native |
| ---- | --------------------------------- | ---------------- | ---- | ----- | --------- | ------ | ---- | ----------- | ------------- | ------ | --- | ----------------------- | ----------------- | ----------------- | ---------------- | ----------------- | ----------------- | ------------------------ | ------------ | ------------ | ------------- |
| 72   | uniswap\_v3\_eth-1-usdc-weth-spot | uniswap\_v3\_eth | usdc | weth  | usdc-weth | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 281  | uniswap\_v3\_eth-2-usdc-weth-spot | uniswap\_v3\_eth | usdc | weth  | usdc-weth | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 650  | uniswap\_v3\_eth-3-usdc-weth-spot | uniswap\_v3\_eth | usdc | weth  | usdc-weth | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 1045 | uniswap\_v3\_eth-4-usdc-weth-spot | uniswap\_v3\_eth | usdc | weth  | usdc-weth | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |

4 rows × 39 columns

### Fetch contract balances over time with ATLAS

Now that we have a list of target liquidity pool contracts, we can use ATLAS blockchain search engine to query for balance updates in the pool for each asset.

```python
assets = ['usdc','weth']
pools = weth_usdc_pools['contract_address'].to_list()
pools_tvl = pd.DataFrame()
start = datetime.now() - timedelta(days=30)

for asset in assets:
    tvl = client.get_list_of_balance_updates_v2(
        asset=asset,
        accounts=pools,
        start_time = start
    ).parallel(max_workers=10,time_increment=relativedelta(days=1)).to_dataframe()
    
    # Add the asset name to a new 'asset' column
    tvl['asset'] = asset
    pools_tvl = pd.concat([pools_tvl, tvl], axis=0)
```

```
Exporting to dataframe type: 100%|█████████████████████████████████████████████████████████████| 31/31 [00:28<00:00,  1.09it/s]
Exporting to dataframe type: 100%|█████████████████████████████████████████████████████████████| 31/31 [00:41<00:00,  1.34s/it]
```

```python
# Create a mapping from contract_address to market
contract_to_market = weth_usdc_pools.set_index('contract_address')['market']
contract_to_market
```

```
contract_address
e0554a476a092703abdb3ef35c80e0d76d32939f    uniswap_v3_eth-1-usdc-weth-spot
88e6a0c2ddd26feeb64f039a2c41296fcb3f5640    uniswap_v3_eth-2-usdc-weth-spot
8ad599c3a0ff1de082011efddc58f1908eb6e6d8    uniswap_v3_eth-3-usdc-weth-spot
7bea39867e4169dbe237d55c8242a8f2fcdcc387    uniswap_v3_eth-4-usdc-weth-spot
Name: market, dtype: string
```

```python
pools_tvl['market'] = pools_tvl['account'].map(contract_to_market)
```

```python
pools_tvl
```

|        | chain\_sequence\_number | account                                  | account\_creation\_height | change        | previous\_balance | new\_balance    | transaction\_sequence\_number | n\_debits | n\_credits | block\_hash                                       | ... | consensus\_time           | credit | total\_received     | total\_sent         | previous\_debit\_height | previous\_credit\_height | previous\_chain\_sequence\_number | txid                                              | asset | market                            |
| ------ | ----------------------- | ---------------------------------------- | ------------------------- | ------------- | ----------------- | --------------- | ----------------------------- | --------- | ---------- | ------------------------------------------------- | --- | ------------------------- | ------ | ------------------- | ------------------- | ----------------------- | ------------------------ | --------------------------------- | ------------------------------------------------- | ----- | --------------------------------- |
| 0      | 88964646899286016       | 88e6a0c2ddd26feeb64f039a2c41296fcb3f5640 | 12376729                  | -60426.466497 | 72674047.982769   | 72613621.516272 | 0                             | 4019999   | 3619510    | 96131a3e3702feb38e1ce25c71773962cdf6ed8beb5ee2... | ... | 2024-09-09 14:37:23+00:00 | False  | 738732040663.426392 | 738659427041.910034 | 20713695                | 20713694                 | 88964642604318722                 | a8f5e44bb9ae9f93a3d1b11b5fce58fe2bcad8ba73561f... | usdc  | uniswap\_v3\_eth-2-usdc-weth-spot |
| 1      | 88964646899286022       | 88e6a0c2ddd26feeb64f039a2c41296fcb3f5640 | 12376729                  | -551.745218   | 72613621.516272   | 72613069.771054 | 0                             | 4020000   | 3619510    | 96131a3e3702feb38e1ce25c71773962cdf6ed8beb5ee2... | ... | 2024-09-09 14:37:23+00:00 | False  | 738732040663.426392 | 738659427593.655396 | 20713696                | 20713694                 | 88964646899286016                 | 3072cd48442d1e61b7232590812737dabdd52d60ed2181... | usdc  | uniswap\_v3\_eth-2-usdc-weth-spot |
| 2      | 88964651194253318       | 88e6a0c2ddd26feeb64f039a2c41296fcb3f5640 | 12376729                  | -1189.382003  | 72613069.771054   | 72611880.389051 | 0                             | 4020001   | 3619510    | d1b93582ac0242d6c4d78a2e15fa7a14cb8f23cdd315a7... | ... | 2024-09-09 14:37:35+00:00 | False  | 738732040663.426392 | 738659428783.037231 | 20713696                | 20713694                 | 88964646899286022                 | 785845bb01a0c4c95a4fce1a5b684b607eff59db5e35a0... | usdc  | uniswap\_v3\_eth-2-usdc-weth-spot |
| 3      | 88964651194253320       | e0554a476a092703abdb3ef35c80e0d76d32939f | 13616454                  | -1185.605465  | 601863.20449      | 600677.599025   | 1                             | 231967    | 225267     | d1b93582ac0242d6c4d78a2e15fa7a14cb8f23cdd315a7... | ... | 2024-09-09 14:37:35+00:00 | False  | 5991391248.046802   | 5990790570.447777   | 20713695                | 20713695                 | 88964642604318733                 | 785845bb01a0c4c95a4fce1a5b684b607eff59db5e35a0... | usdc  | uniswap\_v3\_eth-1-usdc-weth-spot |
| 4      | 88964651194253338       | 88e6a0c2ddd26feeb64f039a2c41296fcb3f5640 | 12376729                  | -1178.099514  | 72611880.389051   | 72610702.289537 | 0                             | 4020002   | 3619510    | d1b93582ac0242d6c4d78a2e15fa7a14cb8f23cdd315a7... | ... | 2024-09-09 14:37:35+00:00 | False  | 738732040663.426392 | 738659429961.136841 | 20713697                | 20713694                 | 88964651194253318                 | e8c9bf688ee4d41f22d95f34936a425edb4f61244318b7... | usdc  | uniswap\_v3\_eth-2-usdc-weth-spot |
| ...    | ...                     | ...                                      | ...                       | ...           | ...               | ...             | ...                           | ...       | ...        | ...                                               | ... | ...                       | ...    | ...                 | ...                 | ...                     | ...                      | ...                               | ...                                               | ...   | ...                               |
| 273787 | 89893038440054825       | e0554a476a092703abdb3ef35c80e0d76d32939f | 13616454                  | 11.45984      | 2397.232798       | 2408.692638     | 1                             | 292522    | 301912     | de4360d0ae6f824e4ca7525da2268497de62906fec744c... | ... | 2024-10-09 18:33:11+00:00 | True   | 4128265.590843      | 4125856.898204      | 20929853                | 20929850                 | 89893034145087672                 | aefc38b1fa84766bb2e50b8565d7e6b23031d98a28ccd8... | weth  | uniswap\_v3\_eth-1-usdc-weth-spot |
| 273788 | 89893038440054892       | e0554a476a092703abdb3ef35c80e0d76d32939f | 13616454                  | -0.015523     | 2408.692638       | 2408.677115     | 0                             | 292523    | 301912     | de4360d0ae6f824e4ca7525da2268497de62906fec744c... | ... | 2024-10-09 18:33:11+00:00 | False  | 4128265.590843      | 4125856.913727      | 20929853                | 20929854                 | 89893038440054825                 | 9b83a0daab76cd6db6aedbafc5f1e61adc0f5d31e72e47... | weth  | uniswap\_v3\_eth-1-usdc-weth-spot |
| 273789 | 89893038440054968       | 88e6a0c2ddd26feeb64f039a2c41296fcb3f5640 | 12376729                  | -2.123209     | 27357.193086      | 27355.069877    | 0                             | 3685872   | 4078043    | de4360d0ae6f824e4ca7525da2268497de62906fec744c... | ... | 2024-10-09 18:33:11+00:00 | False  | 378530260.402821    | 378502905.332944    | 20929852                | 20929854                 | 89893038440054823                 | e79fe9981166fccb9fb15b872da4ee5f8ea4f581a86e0d... | weth  | uniswap\_v3\_eth-2-usdc-weth-spot |
| 273790 | 89893051324956808       | 88e6a0c2ddd26feeb64f039a2c41296fcb3f5640 | 12376729                  | -0.119392     | 27355.069877      | 27354.950485    | 0                             | 3685873   | 4078043    | 2823efc897ab6e43f4382e7670f1cfa4aa621571e79d9d... | ... | 2024-10-09 18:33:47+00:00 | False  | 378530260.402821    | 378502905.452336    | 20929854                | 20929854                 | 89893038440054968                 | a46cab246dea451a42d4b26c79994c5fc06ce1a10a53a7... | weth  | uniswap\_v3\_eth-2-usdc-weth-spot |
| 273791 | 89893051324956894       | 88e6a0c2ddd26feeb64f039a2c41296fcb3f5640 | 12376729                  | -0.825174     | 27354.950485      | 27354.125311    | 0                             | 3685874   | 4078043    | 2823efc897ab6e43f4382e7670f1cfa4aa621571e79d9d... | ... | 2024-10-09 18:33:47+00:00 | False  | 378530260.402821    | 378502906.27751     | 20929857                | 20929854                 | 89893051324956808                 | 3004b50008190b1b36f5cdf602b63b9f9792267d89f2fe... | weth  | uniswap\_v3\_eth-2-usdc-weth-spot |

547648 rows × 21 columns

```python
# Sort by 'consensus_time', 'market', and 'chain_sequence_number'
pools_tvl_sorted = pools_tvl.sort_values(by=['consensus_time', 'market', 'chain_sequence_number'], ascending=[True, True, False])

# Drop duplicates, keeping only the first occurrence (in this case, the highest 'chain_sequence_number')
pools_tvl_deduplicated = pools_tvl_sorted.drop_duplicates(subset=['consensus_time', 'market','asset'], keep='first')
```

```python
pools_tvl_clean = pools_tvl_deduplicated[['market','consensus_time','asset','new_balance']].copy()
pools_tvl_clean['new_balance'] = pools_tvl_clean.apply(
    lambda row: -row['new_balance'] if row['asset'] == 'weth' else row['new_balance'],
    axis=1
)
pools_tvl_clean
```

|        | market                            | consensus\_time           | asset | new\_balance  |
| ------ | --------------------------------- | ------------------------- | ----- | ------------- |
| 1      | uniswap\_v3\_eth-2-usdc-weth-spot | 2024-09-09 14:37:23+00:00 | weth  | -3.126659e+04 |
| 1      | uniswap\_v3\_eth-2-usdc-weth-spot | 2024-09-09 14:37:23+00:00 | usdc  | 7.261307e+07  |
| 3      | uniswap\_v3\_eth-1-usdc-weth-spot | 2024-09-09 14:37:35+00:00 | weth  | -4.664425e+02 |
| 3      | uniswap\_v3\_eth-1-usdc-weth-spot | 2024-09-09 14:37:35+00:00 | usdc  | 6.006776e+05  |
| 4      | uniswap\_v3\_eth-2-usdc-weth-spot | 2024-09-09 14:37:35+00:00 | weth  | -3.126763e+04 |
| ...    | ...                               | ...                       | ...   | ...           |
| 273850 | uniswap\_v3\_eth-2-usdc-weth-spot | 2024-10-09 18:36:11+00:00 | usdc  | 8.006068e+07  |
| 273853 | uniswap\_v3\_eth-1-usdc-weth-spot | 2024-10-09 18:36:23+00:00 | usdc  | 2.503766e+06  |
| 273851 | uniswap\_v3\_eth-2-usdc-weth-spot | 2024-10-09 18:36:23+00:00 | usdc  | 8.005964e+07  |
| 273854 | uniswap\_v3\_eth-2-usdc-weth-spot | 2024-10-09 18:36:47+00:00 | usdc  | 8.005916e+07  |
| 273855 | uniswap\_v3\_eth-1-usdc-weth-spot | 2024-10-09 18:36:59+00:00 | usdc  | 2.493272e+06  |

382679 rows × 4 columns

```python
df = pd.DataFrame(pools_tvl_clean)
df['consensus_time'] = pd.to_datetime(df['consensus_time'])
# Split the DataFrame by market and store in a dictionary
market_dfs = {market: group.pivot(index='consensus_time', columns='asset', values='new_balance').ffill()
              for market, group in df.groupby('market')}
```

```python
display(market_dfs)
```

```
{'uniswap_v3_eth-1-usdc-weth-spot': asset                              usdc         weth
 consensus_time                                      
 2024-09-09 14:37:35+00:00  6.006776e+05  -466.442498
 2024-09-09 14:37:47+00:00  5.927582e+05  -469.913266
 2024-09-09 14:38:11+00:00  5.834235e+05  -474.007791
 2024-09-09 14:38:23+00:00  5.852796e+05  -473.193522
 2024-09-09 14:38:35+00:00  5.783144e+05  -476.250599
 ...                                 ...          ...
 2024-10-09 18:35:11+00:00  2.504156e+06 -2408.677115
 2024-10-09 18:35:35+00:00  2.507156e+06 -2408.677115
 2024-10-09 18:36:11+00:00  2.503081e+06 -2408.677115
 2024-10-09 18:36:23+00:00  2.503766e+06 -2408.677115
 2024-10-09 18:36:59+00:00  2.493272e+06 -2408.677115
 
 [93275 rows x 2 columns],
 'uniswap_v3_eth-2-usdc-weth-spot': asset                              usdc          weth
 consensus_time                                       
 2024-09-09 14:37:23+00:00  7.261307e+07 -31266.590416
 2024-09-09 14:37:35+00:00  7.261070e+07 -31267.627526
 2024-09-09 14:37:47+00:00  7.244846e+07 -31338.733700
 2024-09-09 14:37:59+00:00  7.240161e+07 -31359.275300
 2024-09-09 14:38:11+00:00  7.227468e+07 -31414.964479
 ...                                 ...           ...
 2024-10-09 18:34:47+00:00  7.997092e+07 -27354.125311
 2024-10-09 18:35:35+00:00  7.998951e+07 -27354.125311
 2024-10-09 18:36:11+00:00  8.006068e+07 -27354.125311
 2024-10-09 18:36:23+00:00  8.005964e+07 -27354.125311
 2024-10-09 18:36:47+00:00  8.005916e+07 -27354.125311
 
 [89932 rows x 2 columns],
 'uniswap_v3_eth-3-usdc-weth-spot': asset                              usdc          weth
 consensus_time                                       
 2024-09-09 14:40:11+00:00  9.802691e+06 -22517.703981
 2024-09-09 15:06:59+00:00  9.815312e+06 -22512.198607
 2024-09-09 15:07:11+00:00  9.836937e+06 -22502.771507
 2024-09-09 15:13:23+00:00  9.817752e+06 -22511.184829
 2024-09-09 15:13:47+00:00  9.797839e+06 -22519.924545
 ...                                 ...           ...
 2024-10-09 18:15:47+00:00  1.306390e+07 -19482.217019
 2024-10-09 18:16:59+00:00  1.293324e+07 -19536.165795
 2024-10-09 18:17:11+00:00  1.276007e+07 -19607.732168
 2024-10-09 18:18:23+00:00  1.255446e+07 -19692.807793
 2024-10-09 18:23:47+00:00  1.255437e+07 -19692.792301
 
 [7850 rows x 2 columns],
 'uniswap_v3_eth-4-usdc-weth-spot': asset                               usdc        weth
 consensus_time                                      
 2024-09-09 15:17:35+00:00  288875.833924 -166.205531
 2024-09-09 16:12:35+00:00  291361.212465 -165.137952
 2024-09-09 16:56:47+00:00  293088.964462 -164.400079
 2024-09-09 17:10:23+00:00  293188.964462 -164.357478
 2024-09-09 19:54:35+00:00  293683.964462 -164.146777
 ...                                  ...         ...
 2024-10-08 21:45:59+00:00  311219.129512 -157.116899
 2024-10-08 21:56:11+00:00  311402.896623 -157.042040
 2024-10-09 01:33:23+00:00  312960.239993 -156.409115
 2024-10-09 01:38:11+00:00  314224.468721 -155.897241
 2024-10-09 18:30:11+00:00  313919.457241 -156.023085
 
 [435 rows x 2 columns]}
```

### Retrieve Reference Rates to calculate the equivalent USD value for TVL

To normalize pool TVL into USD-denominated terms, we'll leverage the Coin Metrics Reference Rate, which represents a volume-weighted median price across a subset of the asset's most highly-liquid markets.

```python
ref_rate = client.get_asset_metrics(
    assets=['usdc','weth'],
    metrics='ReferenceRateUSD',
    start_time=start,
    frequency='1m'
).parallel(max_workers=10,time_increment=relativedelta(days=1)).to_dataframe()
```

```
Exporting to dataframe type: 100%|█████████████████████████████████████████████████████████████| 62/62 [00:06<00:00,  8.93it/s]
```

```python
ref_rate = ref_rate.pivot(index='time', columns='asset', values='ReferenceRateUSD')
ref_rate
```

| asset                     | usdc     | weth        |
| ------------------------- | -------- | ----------- |
| time                      |          |             |
| 2024-09-09 14:38:00+00:00 | 1.000228 | 2281.628477 |
| 2024-09-09 14:39:00+00:00 | 1.000066 | 2278.047686 |
| 2024-09-09 14:40:00+00:00 | 0.99975  | 2279.877181 |
| 2024-09-09 14:41:00+00:00 | 0.999917 | 2278.211943 |
| 2024-09-09 14:42:00+00:00 | 0.999867 | 2279.118291 |
| ...                       | ...      | ...         |
| 2024-10-09 18:34:00+00:00 | 0.999862 | 2422.199211 |
| 2024-10-09 18:35:00+00:00 | 0.999822 | 2418.294121 |
| 2024-10-09 18:36:00+00:00 | 0.999827 | 2420.816853 |
| 2024-10-09 18:37:00+00:00 | 0.999789 | 2420.182517 |
| 2024-10-09 18:38:00+00:00 | 0.999873 | 2421.764058 |

43441 rows × 2 columns

```python
# Iterate over each market DataFrame
for market, df in market_dfs.items():
    # Resample the DataFrame to 1-minute intervals
    df_resampled = df.resample('min').last().dropna()

    # Reindex the market DataFrame to the ref_rate DataFrame's index
    aligned_df = df_resampled.reindex(ref_rate.index, method='nearest')

    # Multiply the 'usdc' and 'weth' columns by the corresponding rate
    aligned_df['usdc'] = aligned_df['usdc'] * ref_rate['usdc']
    aligned_df['weth'] = aligned_df['weth'] * ref_rate['weth']

    # Replace the original DataFrame in the dictionary with the updated one
    market_dfs[market] = aligned_df
```

```python
first_pool_key = list(market_dfs.keys())[0]
first_pool = market_dfs[first_pool_key]  
first_pool
```

| asset                     | usdc           | weth            |
| ------------------------- | -------------- | --------------- |
| time                      |                |                 |
| 2024-09-09 14:38:00+00:00 | 580007.558512  | -1085063.725878 |
| 2024-09-09 14:39:00+00:00 | 591547.333378  | -1071736.155646 |
| 2024-09-09 14:40:00+00:00 | 591664.869298  | -1072292.759274 |
| 2024-09-09 14:41:00+00:00 | 584444.264977  | -1078824.970611 |
| 2024-09-09 14:42:00+00:00 | 604433.557236  | -1059255.13815  |
| ...                       | ...            | ...             |
| 2024-10-09 18:34:00+00:00 | 2480138.279715 | -5834295.808101 |
| 2024-10-09 18:35:00+00:00 | 2506710.799699 | -5824889.708489 |
| 2024-10-09 18:36:00+00:00 | 2492840.090089 | -5830966.153299 |
| 2024-10-09 18:37:00+00:00 | 2492746.887517 | -5829438.242635 |
| 2024-10-09 18:38:00+00:00 | 2492954.27474  | -5833247.665283 |

43441 rows × 2 columns

### Plot USD-denominated TVL for target liquidity pools

```python
def generate_area_figure(df, layout, columns, diverging_colors=False):
    traces = []
    for series in columns:
        traces.append(
            go.Scatter(
                x=df.index,
                y=df[series],
                name=series,
                fill='tozeroy'  # Ensures filling to the zero line on the y-axis
            ))
    return go.Figure(data=traces, layout=layout)
```

```python
# Plotting for each market using Matplotlib
market_to_contract = contract_to_market.reset_index().set_index('market')
for market, data in market_dfs.items():
    address = market_to_contract.loc[market, 'contract_address']
    print(f'{market}')
    print(f'{address}')
    print(f'USDC: https://atlas.coinmetrics.io/address-details?asset=usdc&address={address}')
    print(f'WETH: https://atlas.coinmetrics.io/address-details?asset=weth&address={address}')

    # Create the figure and axis
    fig, ax = plt.subplots(figsize=(10, 6))

    # Plot the area chart for each series in the data
    for column in data.columns:
        ax.fill_between(data.index, data[column], label=column)

    # Set chart title and labels
    ax.set_title(f'{market.upper()}\nLiquidity Pool TVL', fontsize=16, color='grey')
    ax.set_xlabel('', color='grey')
    ax.set_ylabel('TVL Value (USD)', color='grey')

    # Set grid and background colors
    ax.set_facecolor('#49494a')
    ax.grid(True, color='white', linestyle='--', linewidth=0.5)

    # Customize tick parameters (color and size)
    ax.tick_params(axis='x', colors='grey', rotation=45)
    ax.tick_params(axis='y', colors='grey')
    ax.xaxis.set_major_locator(mdates.DayLocator(interval=4))
    ax.set_xlim([data.index.min(), data.index.max()])

    # Set legend and its appearance
    ax.legend(loc='upper right', fontsize=10)

    # Adjust the plot layout
    plt.tight_layout()

    # Show the plot
    plt.show()
```

```
uniswap_v3_eth-1-usdc-weth-spot
e0554a476a092703abdb3ef35c80e0d76d32939f
USDC: https://atlas.coinmetrics.io/address-details?asset=usdc&address=e0554a476a092703abdb3ef35c80e0d76d32939f
WETH: https://atlas.coinmetrics.io/address-details?asset=weth&address=e0554a476a092703abdb3ef35c80e0d76d32939f



```

```
uniswap_v3_eth-2-usdc-weth-spot
88e6a0c2ddd26feeb64f039a2c41296fcb3f5640
USDC: https://atlas.coinmetrics.io/address-details?asset=usdc&address=88e6a0c2ddd26feeb64f039a2c41296fcb3f5640
WETH: https://atlas.coinmetrics.io/address-details?asset=weth&address=88e6a0c2ddd26feeb64f039a2c41296fcb3f5640



```

```
uniswap_v3_eth-3-usdc-weth-spot
8ad599c3a0ff1de082011efddc58f1908eb6e6d8
USDC: https://atlas.coinmetrics.io/address-details?asset=usdc&address=8ad599c3a0ff1de082011efddc58f1908eb6e6d8
WETH: https://atlas.coinmetrics.io/address-details?asset=weth&address=8ad599c3a0ff1de082011efddc58f1908eb6e6d8



```

```
uniswap_v3_eth-4-usdc-weth-spot
7bea39867e4169dbe237d55c8242a8f2fcdcc387
USDC: https://atlas.coinmetrics.io/address-details?asset=usdc&address=7bea39867e4169dbe237d55c8242a8f2fcdcc387
WETH: https://atlas.coinmetrics.io/address-details?asset=weth&address=7bea39867e4169dbe237d55c8242a8f2fcdcc387



```

<figure><img src="/files/0k3UZtyNVeeBe9MtVsJ6" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/dCwEymc1Flxi81fpTosU" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/WhpqLgI5OJ7IGaQQK9MM" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/9kB6m5xbxke9cnmItmY4" alt=""><figcaption></figcaption></figure>


# Calculating DEX Liquidity Pool Fees and Volumes

![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/Demo%20Asset%20Resources/Demo%20Covers/CM-Demo-dex_data-Cover.png)

Decentralized exchanges are playing an increasingly important role in supporting cryptoasset trading, particularly when it comes to tokens using the ERC-20 standard. Coin Metrics has been actively working on collecting data from major DeFi protocols. For our first release, we have added support for all major liquidity pools on **Uniswap v2, Uniswap v3,** and **Sushiswap v1.**

### Resources

This notebook demonstrates basic functionality offered by the Coin Metrics Python API Client and DEX Market Data.

Coin Metrics offers a vast assortment of data for hundreds of cryptoassets. The Python API Client allows for easy access to this data using Python without needing to create your own wrappers using `requests` and other such libraries.

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics.
* The [Coin Metrics Product Documentation](https://docs.coinmetrics.io/info) gives detailed, conceptual explanations of the data that Coin Metrics offers.
* The [API Spec](https://docs.coinmetrics.io/python-api-client/reference) contains a full list of functions.

### File Download

Download the entire notebook as either a jupyter notebook to run yourself or as a pdf from the two links below

{% file src="/files/YTrMwaRRpeyhc9mFQHQ2" %}

{% file src="/files/le9V3l0eymRStGsqoNVq" %}

### Setup

```python
from os import environ
import sys
import pandas as pd
import numpy as np
import seaborn as sns
import logging
from datetime import date, datetime, timedelta
from coinmetrics.api_client import CoinMetricsClient
import json
import logging
from pytz import timezone as timezone_conv
from datetime import timezone as timezone_info
import matplotlib.dates as mdates
from IPython.display import Markdown as md
import matplotlib.pyplot as plt
import plotly.express as px 
# %matplotlib inline
```

```python
sns.set_theme()
sns.set_style('whitegrid')
sns.set(rc={'figure.figsize':(16,8)})
sns.set_context("notebook", font_scale=1.2, rc={"font.family": "Lato"});
```

```python
logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S'
)
```

```python
# We recommend privately storing your API key in your local environment.
try:
    api_key = environ["CM_API_KEY"]
    logging.info("Using API key found in environment")
except KeyError:
    api_key = ""
    logging.info("API key not found. Using community client")
    
client = CoinMetricsClient(api_key)
```

```
2024-10-09 11:26:54 INFO     Using API key found in environment
```

## DEX Market Catalog

The *catalog/markets* endpoint returns a list of available markets along with time ranges of available data. Users can pass in a list of markets, exchanges, or market types (spot, futures, options).

We can retrieve our DEX markets by fetching a list of all 'spot' markets, then filtering for the markets where the 'experimental' parameter equals *true*.

```python
spot_markets = pd.concat([client.reference_data_markets(
    type = 'spot',
    page_size = 10000,
    exchange = "uniswap_v3_eth",
).to_dataframe(), client.reference_data_markets(
    type = 'spot',
    page_size = 10000,
    exchange = "uniswap_v2_eth",
).to_dataframe(), client.reference_data_markets(
    type = 'spot',
    page_size = 10000,
    exchange = "sushiswap_v1_eth",
).to_dataframe()])
```

```python
exp_markets = spot_markets.loc[spot_markets['experimental']==True] 
```

```python
exp_markets
```

|     | market                                        | exchange           | base       | quote      | pair                  | symbol | type | size\_asset | margin\_asset | strike | ... | order\_price\_increment | order\_price\_min | order\_price\_max | order\_size\_min | order\_taker\_fee | order\_maker\_fee | margin\_trading\_enabled | experimental | base\_native | quote\_native |
| --- | --------------------------------------------- | ------------------ | ---------- | ---------- | --------------------- | ------ | ---- | ----------- | ------------- | ------ | --- | ----------------------- | ----------------- | ----------------- | ---------------- | ----------------- | ----------------- | ------------------------ | ------------ | ------------ | ------------- |
| 0   | uniswap\_v3\_eth-1-1inch-dai-spot             | uniswap\_v3\_eth   | 1inch      | dai        | 1inch-dai             | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 1   | uniswap\_v3\_eth-1-1inch-usdc-spot            | uniswap\_v3\_eth   | 1inch      | usdc       | 1inch-usdc            | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 2   | uniswap\_v3\_eth-1-1inch-weth-spot            | uniswap\_v3\_eth   | 1inch      | weth       | 1inch-weth            | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 3   | uniswap\_v3\_eth-1-ageur\_eth-eurcv\_eth-spot | uniswap\_v3\_eth   | ageur\_eth | eurcv\_eth | ageur\_eth-eurcv\_eth | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 4   | uniswap\_v3\_eth-1-ageur\_eth-usdc-spot       | uniswap\_v3\_eth   | ageur\_eth | usdc       | ageur\_eth-usdc       | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| ... | ...                                           | ...                | ...        | ...        | ...                   | ...    | ...  | ...         | ...           | ...    | ... | ...                     | ...               | ...               | ...              | ...               | ...               | ...                      | ...          | ...          | ...           |
| 220 | sushiswap\_v1\_eth-yfi-sushi-spot             | sushiswap\_v1\_eth | yfi        | sushi      | yfi-sushi             | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 221 | sushiswap\_v1\_eth-yfi-usdc-spot              | sushiswap\_v1\_eth | yfi        | usdc       | yfi-usdc              | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 222 | sushiswap\_v1\_eth-yfi-usdt\_eth-spot         | sushiswap\_v1\_eth | yfi        | usdt\_eth  | yfi-usdt\_eth         | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 223 | sushiswap\_v1\_eth-yfi-wbtc-spot              | sushiswap\_v1\_eth | yfi        | wbtc       | yfi-wbtc              | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |
| 224 | sushiswap\_v1\_eth-yfi-weth-spot              | sushiswap\_v1\_eth | yfi        | weth       | yfi-weth              | \<NA>  | spot | \<NA>       | \<NA>         | \<NA>  | ... | \<NA>                   | \<NA>             | \<NA>             | \<NA>            | \<NA>             | \<NA>             | \<NA>                    | True         | \<NA>        | \<NA>         |

2544 rows × 39 columns

```python
# Calculate number of markets (pools) per DEX
mkt_counts = pd.DataFrame(exp_markets['exchange'].value_counts()).reset_index()
```

```python
print (mkt_counts)
```

```
           exchange  count
0    uniswap_v3_eth   1643
1    uniswap_v2_eth    676
2  sushiswap_v1_eth    225
```

```python
# Plot number of markets (pools) per DEX
ax1 = plt.subplot()
# mkt_counts['exchange'].plot(kind='bar', width=0.8, color=sns.color_palette('tab10'))
ax1.bar(x = mkt_counts['exchange'], height = mkt_counts['count'], color=sns.color_palette('tab10'))
plt.setp(ax1.get_xticklabels(), rotation=0)
ax1.set_facecolor("white")
plt.grid(color='black', linestyle='--', linewidth=0.2)
plt.title('\nCount of Markets \nby Decentralized Exchange\n', fontdict={'fontsize': 24, 'font': 'arial'})
# for i, v in enumerate(mkt_counts['exchange']):
ax1.set_xticks(range(len(mkt_counts['exchange'])))
ax1.set_xticklabels([label.get_text().upper() for label in ax1.get_xticklabels()], rotation=0, ha='center', va='top', fontsize=17)
plt.xticks(fontweight='bold')
plt.show()
```

<figure><img src="/files/geTLdWovpJDyHOrNta58" alt=""><figcaption></figcaption></figure>

```python
# Show fields
pd.DataFrame(exp_markets.loc[exp_markets['exchange'] == 'uniswap_v3_eth'].iloc[0]).dropna()
```

|                      | 0                                        |
| -------------------- | ---------------------------------------- |
| market               | uniswap\_v3\_eth-1-1inch-dai-spot        |
| exchange             | uniswap\_v3\_eth                         |
| base                 | 1inch                                    |
| quote                | dai                                      |
| pair                 | 1inch-dai                                |
| type                 | spot                                     |
| pool\_config\_id     | 1                                        |
| contract\_address    | 063332bbf9f8385e4106919b5c6ae2e6a4f72228 |
| fee                  | 0.01                                     |
| price\_includes\_fee | False                                    |
| variable\_fee        | False                                    |
| base\_address        | 111111111117dc0aa78b770fa6a738034120c302 |
| quote\_address       | 6b175474e89094c44da98b954eedeac495271d0f |
| experimental         | True                                     |

#### DEX markets include metadata for 3 different smart contracts

* **contract\_address:** The address of the liquidity pool contract. Each liquidity pool is a unique instance of a smart contract, deployed at a dedicated address. The pool contract holds both the base and the quote asset.
* **base\_address:** The address of the ERC-20 token contract associated with the *base* asset.
* **quote\_address:** The address of the ERC-20 token contract associated with the *quote* asset.

```python
# DEX fields
exp_markets[['pool_config_id','contract_address','base_address','quote_address','fee']]
```

|     | pool\_config\_id | contract\_address                        | base\_address                            | quote\_address                           | fee  |
| --- | ---------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | ---- |
| 0   | 1                | 063332bbf9f8385e4106919b5c6ae2e6a4f72228 | 111111111117dc0aa78b770fa6a738034120c302 | 6b175474e89094c44da98b954eedeac495271d0f | 0.01 |
| 1   | 1                | 2ee7e6e459fffbbc655f09f2e1b3131abf98c397 | 111111111117dc0aa78b770fa6a738034120c302 | a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48 | 0.01 |
| 2   | 1                | 1d1284e43da1de5ee8dd6acbb03f3624cfbd872c | 111111111117dc0aa78b770fa6a738034120c302 | c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 | 0.01 |
| 3   | 1                | f339217aa24e70eddf900f3b1a78eb9efcdea115 | 1a7e4e63778b4f12a199c062f3efdd288afcbce8 | 5f7827fdeb7c20b443265fc2f40845b715385ff2 | 0.01 |
| 4   | 1                | 735a26a57a0a0069dfabd41595a970faf5e1ee8b | 1a7e4e63778b4f12a199c062f3efdd288afcbce8 | a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48 | 0.01 |
| ... | ...              | ...                                      | ...                                      | ...                                      | ...  |
| 220 | \<NA>            | f173a7a055340c91dbdf3083ce3babaa7535a03c | 0bc529c00c6401aef6d220be8c6ea1667f6ad93e | 6b3595068778dd592e39a122f4f5a5cf09c90fe2 | 0.3  |
| 221 | \<NA>            | 3a5747cf4e21861e2d0d3d51a0e8737ab4dfadc8 | 0bc529c00c6401aef6d220be8c6ea1667f6ad93e | a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48 | 0.3  |
| 222 | \<NA>            | f5fbc6ca5c677f1c977ed3a064b9dda14c5e241b | 0bc529c00c6401aef6d220be8c6ea1667f6ad93e | dac17f958d2ee523a2206206994597c13d831ec7 | 0.3  |
| 223 | \<NA>            | 1d108372a83fbc3a0bfb7ca4d0e427449e7a5ca2 | 0bc529c00c6401aef6d220be8c6ea1667f6ad93e | 2260fac5e5542a773aa44fbcfedf7c193bc2c599 | 0.3  |
| 224 | \<NA>            | 088ee5007c98a9677165d78dd2109ae4a3d04d0c | 0bc529c00c6401aef6d220be8c6ea1667f6ad93e | c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2 | 0.3  |

2544 rows × 5 columns

Each liquidity pool is also associated with a corresponding fee percentage. With each trade, fees are distributed pro-rata to the pool's liquidity providers.

```python
# Range of pool fees
pool_fees = pd.DataFrame(exp_markets.fee.unique().dropna())
pool_fees
```

|   | 0    |
| - | ---- |
| 0 | 0.01 |
| 1 | 0.05 |
| 2 | 0.3  |
| 3 | 1.0  |

Due to the permissionless nature of provisioning a liquidity pool, users can easily add arbitrary ERC-20 tokens to the decentralized exchange. There are over 50,000 trading pairs available on Uniswap today. To prioritize only the most relevant and liquid markets, we cover the subset of markets where both tokens are part of Coin Metrics [reference rate coverage](https://coverage.coinmetrics.io/asset-metrics-v2/ReferenceRateUSD).

```python
# Assets covered
asset_coverage = np.unique(exp_markets[['base', 'quote']].values)
print(asset_coverage)
print('\nTotal number of assets: \033[1m' + str(len(asset_coverage)) + '\033[0m\n')
```

```
['1inch' 'aave' 'ageur_eth' 'alcx' 'alpha' 'alusd' 'ampl_eth' 'ant' 'ape'
 'api3' 'audio' 'ausd_eth' 'axs_1_eth' 'axs_2_eth' 'badger' 'bal'
 'band_eth' 'bat' 'bit' 'bnb_eth' 'bnt' 'boost_eth' 'btm_eth' 'busd'
 'cbat' 'cbeth' 'ccomp' 'cdai' 'cel' 'cennz' 'ceth' 'chz_eth' 'comp' 'cro'
 'crv' 'crvusd_eth' 'cuni' 'cusdc' 'cusdcv3' 'cusdt' 'cvc' 'cvx' 'cwbtc'
 'czrx' 'dai' 'dar' 'degen_eth' 'deusd_eth' 'dgx' 'dorkl_eth' 'dpi' 'drgn'
 'eeth_eth' 'elf' 'eng' 'enj' 'ens' 'esd' 'ethos' 'ethx_eth' 'eul'
 'eurc_eth' 'eurcv_eth' 'eure_eth' 'eurs_eth' 'eurt_eth' 'fdusd_eth'
 'fei_eth' 'flx' 'fox_eth' 'frax_eth' 'frxeth_eth' 'ftm_eth' 'ftt' 'fun'
 'fwb' 'fxc_eth' 'fxs' 'gala' 'gbpt_eth' 'gho_eth' 'glm' 'gno' 'grt'
 'gt_eth' 'gusd' 'gyen_eth' 'hbot' 'hbtc' 'hedg' 'hex_eth' 'hpos10i_eth'
 'hpos1m_eth' 'ht' 'husd' 'idrt_eth' 'imx' 'inst' 'kin1' 'knc' 'ldo'
 'lend' 'leo_eth' 'link' 'linq_eth' 'looks' 'loom' 'lpt' 'ltx_eth'
 'lusd_eth' 'mana' 'matic_eth' 'mco' 'meth_eth' 'mim_eth' 'mkr_2_eth'
 'mnt' 'mpl' 'mtl_metal' 'myc' 'myth' 'nexo' 'nftx' 'nmr' 'ogn'
 'ohm_2_eth' 'okb' 'omg' 'ousd_eth' 'paid' 'parrot_eth' 'pax' 'paxg' 'pay'
 'pdt' 'pepe_eth' 'perp' 'pndc_eth' 'pog_eth' 'pol_eth' 'poly' 'pow_eth'
 'powr' 'ppt' 'pufeth_eth' 'pvpbot_eth' 'pxeth_eth' 'pyusd_eth' 'qash'
 'qnt' 'rad' 'radar' 'rai_eth' 'ren' 'renbtc' 'renfil_eth' 'rep_3_eth'
 'reth_eth' 'rev_eth' 'rez_eth' 'rlb_eth' 'rook' 'rseth_eth' 'rsr'
 'rsweth_eth' 'safe_eth' 'sai' 'salt' 'sand' 'sbtc_eth' 'sdai_eth'
 'seth_synthseth_eth' 'shepe_eth' 'shia_eth' 'shib' 'skl' 'slp_1_eth'
 'slp_2_eth' 'snt' 'snx_3_eth' 'socks' 'spell' 'srm' 'srn' 'steth_lido'
 'stg_eth' 'stkaave' 'stmx' 'stone_eth' 'storj' 'susd_eth' 'susde_eth'
 'sushi' 'sweth_eth' 'swise' 'swrv' 't_eth' 'taud_eth' 'tbtc_eth'
 'tcad_eth' 'tgbp_eth' 'thkd_eth' 'toke' 'trx_eth' 'tusd_2_eth' 'ubt'
 'uma' 'uni' 'univ2aaveweth_eth' 'univ2crvweth_eth' 'univ2daiweth_eth'
 'univ2snxweth_eth' 'univ2uniweth_eth' 'univ2wbtcweth_eth'
 'univ2yfiweth_eth' 'uqc_1_eth' 'uqc_2_eth' 'usd0_eth' 'usda_eth' 'usdc'
 'usdd_eth' 'usde_eth' 'usdk' 'usdn_eth' 'usdt_eth' 'usdv_eth' 'usdy_eth'
 'ustc.t_eth_wh' 'veri' 'wbtc' 'wcelo' 'wcusd' 'weeth_eth' 'weth' 'wluna'
 'wnxm' 'wsteth' 'wust' 'wzec' 'xai_silofinance_eth' 'xaut_1_eth'
 'xaut_2_eth' 'xchf' 'xidr_eth' 'xsgd_eth' 'xsushi' 'yama_eth' 'yfi' 'zrx']

Total number of assets: [1m249[0m

```

The majority of DEX assets trade against **Wrapped Ether (WETH)**. Note that Ethereum's native asset ETH is not supported in Uniswap V2/V3, as the asset was created prior to the ERC-20 standard. From the Uniswap documentation:

> "Unlike Uniswap V1 pools, V2 pairs do not support ETH directly, so ETH⇄ERC-20 pairs must be emulated with WETH. The motivation behind this choice was to remove ETH-specific code in the core, resulting in a leaner codebase. End users can be kept fully ignorant of this implementation detail, however, by simply wrapping/unwrapping ETH in the periphery."\
> [docs.uniswap.org](https://docs.uniswap.org/protocol/V2/concepts/protocol-overview/smart-contracts#weth)

```python
# Enter an asset ticker to see available 'base' and 'quote' markets
asset = 'weth'

selected_markets = exp_markets.loc[(exp_markets['base']==asset) | (exp_markets['quote']==asset)]
print('\nTotal number of ' + '\033[1m' + asset + '\033[0m' + ' markets: \n\033[1m' 
      + str(len(selected_markets)) + '\n')
```

```
Total number of [1mweth[0m markets: 
[1m847

```

#### Using the min\_time parameter, we can filter for the newest DEX liquidity pool deployed in our coverage

```python
defi_market_catalogs = pd.concat([client.catalog_market_trades_v2(
    market_type = 'spot',
    page_size = 10000,
    exchange = "uniswap_v3_eth",
).to_dataframe(), client.catalog_market_trades_v2(
    market_type = 'spot',
    page_size = 10000,
    exchange = "uniswap_v2_eth",
).to_dataframe(), client.catalog_market_trades_v2(
    market_type = 'spot',
    page_size = 10000,
    exchange = "sushiswap_v1_eth",
).to_dataframe()]).sort_values('min_time').reset_index()
```

```python
print (defi_market_catalogs)
```

```
      index                                      market  \
0       560               uniswap_v2_eth-usdc-weth-spot   
1       154                uniswap_v2_eth-dai-weth-spot   
2       152                uniswap_v2_eth-dai-usdc-spot   
3       387                uniswap_v2_eth-ren-usdc-spot   
4        85               uniswap_v2_eth-cdai-weth-spot   
...     ...                                         ...   
2012    207         uniswap_v3_eth-2-paxg-usdt_eth-spot   
2013    208       uniswap_v3_eth-2-paxg-xaut_2_eth-spot   
2014    302  uniswap_v3_eth-2-weeth_eth-pufeth_eth-spot   
2015     24    uniswap_v3_eth-1-deusd_eth-usdt_eth-spot   
2016    656   uniswap_v3_eth-3-usdt_eth-crvusd_eth-spot   

                      min_time                  max_time  
0    2020-05-05 21:09:32+00:00 2024-10-03 19:44:11+00:00  
1    2020-05-14 00:01:38+00:00 2024-10-03 19:22:47+00:00  
2    2020-05-15 02:18:16+00:00 2024-10-03 12:06:35+00:00  
3    2020-05-17 21:32:57+00:00 2024-09-03 22:31:59+00:00  
4    2020-05-18 17:18:03+00:00 2024-10-01 22:43:11+00:00  
...                        ...                       ...  
2012 2024-09-16 01:14:11+00:00 2024-09-17 01:00:23+00:00  
2013 2024-09-17 01:56:23+00:00 2024-09-28 12:37:23+00:00  
2014 2024-09-26 04:21:35+00:00 2024-10-03 09:49:59+00:00  
2015 2024-09-27 23:06:35+00:00 2024-10-03 10:26:47+00:00  
2016 2024-09-28 07:12:59+00:00 2024-10-03 18:50:35+00:00  

[2017 rows x 4 columns]
```

```python
# Check for the newest market
newest = defi_market_catalogs.loc[defi_market_catalogs['min_time'].idxmax()].dropna()
pd.DataFrame(newest)
```

|           | 2016                                          |
| --------- | --------------------------------------------- |
| index     | 656                                           |
| market    | uniswap\_v3\_eth-3-usdt\_eth-crvusd\_eth-spot |
| min\_time | 2024-09-28 07:12:59+00:00                     |
| max\_time | 2024-10-03 18:50:35+00:00                     |

## DEX Swaps Data

Swaps data is served through our existing */timeseries/market-trades* endpoint because swaps are conceptually identical to a trade. Users can see all the standard trade fields for a swap such as **time, price, and volume** but can also see defi-specific fields such as the **block height, block hash, transaction id, addresses involved** in the swap, and more.

```python
defi_market = 'uniswap_v3_eth-2-weth-usdt_eth-spot'
start = datetime.now() - timedelta(days=3)
end = datetime.now() - timedelta(hours=1)
```

```python
defi_trades = client.get_market_trades(
    markets=defi_market,
    start_time=start,
    end_time = end
).to_dataframe()
```

```python
defi_trades['amount'] = defi_trades['amount'].astype(float)
defi_trades.head()
```

|   | market                                 | time                      | coin\_metrics\_id                                 | amount   | price       | database\_time                   | side | block\_hash                                       | block\_height | txid                                              | initiator                                | sender                                   | beneficiary                              |
| - | -------------------------------------- | ------------------------- | ------------------------------------------------- | -------- | ----------- | -------------------------------- | ---- | ------------------------------------------------- | ------------- | ------------------------------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| 0 | uniswap\_v3\_eth-2-weth-usdt\_eth-spot | 2024-09-30 15:53:23+00:00 | 04V5RQT2E04FT3C4GH7U1MGVR9VR7AUFALO31HO6QSOKR9... | 0.128299 | 2607.212871 | 2024-09-30 15:53:34.441041+00:00 | sell | a27008fe8d84844fe0da1fda7fb3abcf557030c706d731... | 20864491      | ae1fd1a682a4acfaddd474f06d9cbc7fe903435b465b65... | 8249187b3b1f22da84b1c82eb876a2004d60e5a7 | 3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad | 3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad |
| 1 | uniswap\_v3\_eth-2-weth-usdt\_eth-spot | 2024-09-30 15:55:11+00:00 | 04V5RT664167K4H7OBE0IQ00JBU0GG2K0O9O102M1TS37N... | 8.010022 | 2605.89657  | 2024-09-30 15:55:23.154367+00:00 | sell | c6204c7a1227c2dc0968009afc08405406138080560f78... | 20864500      | a585c10e6fa329213cfc758189b3dee4fbdd11f84b0090... | a172577031eafd8b03dce022533863fe988159cd | 51c72848c68a965f66fa7a88855f9f7784502a7f | 51c72848c68a965f66fa7a88855f9f7784502a7f |
| 2 | uniswap\_v3\_eth-2-weth-usdt\_eth-spot | 2024-09-30 15:55:35+00:00 | 04V5RTJ008QUN6D495DB7M93HLAHH6RUCO7GALPGLR6JRU... | 3.275656 | 2605.139188 | 2024-09-30 15:55:48.193560+00:00 | buy  | 600235eb99a4495ab3d9238d55189b7e660f055730aecd... | 20864502      | 983dd154bcd17d715def39a8a46e36d5b8f765f73bde82... | 8ae57a027c63fca8070d1bf38622321de8004c67 | ef1c6e67703c7bd7107eed8303fbe6ec2554bf6b | ef1c6e67703c7bd7107eed8303fbe6ec2554bf6b |
| 3 | uniswap\_v3\_eth-2-weth-usdt\_eth-spot | 2024-09-30 15:55:59+00:00 | 04V5RU5PJI877ESIO9ET0AAEOBK5UBINH6ER8NCIB3U2KG... | 6.002656 | 2604.703261 | 2024-09-30 15:56:09.664424+00:00 | sell | b99c9073bb92c25dd0294ec2e85f2e57899db45d9258fc... | 20864504      | cb9eda573eef860fe7019837c23a66b881e5e4b28549e7... | d1fa51f2db23a9fa9d7bb8437b89fb2e70c60cb7 | d4bc53434c5e12cb41381a556c3c47e1a86e80e3 | d4bc53434c5e12cb41381a556c3c47e1a86e80e3 |
| 4 | uniswap\_v3\_eth-2-weth-usdt\_eth-spot | 2024-09-30 15:56:11+00:00 | 04V5RUDJMTR74RDCP4JUIDIL6UN9UTSE7MEBP0BR3USP60... | 0.399800 | 2603.679987 | 2024-09-30 15:56:23.744604+00:00 | sell | b3b776726dacc927e9365537ae9f778e3d9cbc817b1fb9... | 20864505      | 0083045534c1203964355113751c48cb79f262f70edcf7... | 81fe73a6fb28c49c14c82fcae2a4fe19f57d150c | 3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad | 3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad |

```python
color_map = {'buy': 'green', 'sell': 'red'}
defi_price = plt.scatter(x=defi_trades['time'], y=defi_trades['price'], s=defi_trades['amount'], c=defi_trades['side'].map(color_map))

plt.xlabel("", fontsize=15)
plt.ylabel("Price (USDT)\n", font='arial',fontsize=15)

market_string = defi_market.split("uniswap_v3_eth-", 1)[-1].split("-spot")[0].upper()
plt.title('\nUniswap V3\n Pool ' + market_string + '\nTrades\n', font='arial', size=20)

legend_labels = ['BUY', 'SELL']
legend_handles = [plt.Line2D([0], [0], marker='o', color='w', markerfacecolor=color_map['buy'], markersize=12),
                  plt.Line2D([0], [0], marker='o', color='w', markerfacecolor=color_map['sell'], markersize=12)]
legend = plt.legend(legend_handles, legend_labels, loc='lower right', fontsize=16, framealpha=0, bbox_to_anchor=(0.99, 1.02))

plt.gca().set_facecolor('white')
plt.grid(color='black', linestyle='dotted')
plt.show()

```

<figure><img src="/files/8wKt2i56Th4qwp20n7DV" alt=""><figcaption></figcaption></figure>

```python
pd.DataFrame(defi_trades.iloc[0])
```

|                   | 0                                                 |
| ----------------- | ------------------------------------------------- |
| market            | uniswap\_v3\_eth-2-weth-usdt\_eth-spot            |
| time              | 2024-09-30 15:53:23+00:00                         |
| coin\_metrics\_id | 04V5RQT2E04FT3C4GH7U1MGVR9VR7AUFALO31HO6QSOKR9... |
| amount            | 0.128299                                          |
| price             | 2607.212871                                       |
| database\_time    | 2024-09-30 15:53:34.441041+00:00                  |
| side              | sell                                              |
| block\_hash       | a27008fe8d84844fe0da1fda7fb3abcf557030c706d731... |
| block\_height     | 20864491                                          |
| txid              | ae1fd1a682a4acfaddd474f06d9cbc7fe903435b465b65... |
| initiator         | 8249187b3b1f22da84b1c82eb876a2004d60e5a7          |
| sender            | 3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad          |
| beneficiary       | 3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad          |

#### Unlike centralized exchanges, where there is an unknown buyer and a seller, each swap is associated with 3 different Ethereum addresses

* **Initiator** is the ethereum address which submitted the transaction as a result of which the swap/liquidity action occurred
* **Sender** is the ethereum address that invoked the uniswap pool smart contract's function for swapping or adding/removing liquidity
* **Beneficiary** is the ethereum address that got credited with the output tokens (in case of a swap or liquidity removal) or with liquidity (in case of liquidity addition)

```python
print('\nTotal number of ' + '\033[1m' + defi_market + '\033[0m' + ' trades (' + str(start.date()) + ' to ' + str(end.date()) + '): \n\033[1m' 
      + str(len(defi_trades)) + '\033[0m\n')

print('\nTotal number of ' + '\033[1m' + defi_market + '\033[0m' + ' buys (' + str(start.date()) + ' to ' + str(end.date())+ '): \n\033[1m' 
      + str(len(defi_trades.loc[(defi_trades['side']=='buy')])) + '\033[0m\n')

print('\nTotal number of ' + '\033[1m' + defi_market + '\033[0m' + ' unique buyers (' + str(start.date()) + ' to ' + str(end.date()) + '): \n\033[1m' 
      + str(len((defi_trades.loc[(defi_trades['side']=='buy')]).beneficiary.unique())) + '\n')
```

```
Total number of [1muniswap_v3_eth-2-weth-usdt_eth-spot[0m trades (2024-10-06 to 2024-10-09): 
[1m5874[0m


Total number of [1muniswap_v3_eth-2-weth-usdt_eth-spot[0m buys (2024-10-06 to 2024-10-09): 
[1m3003[0m


Total number of [1muniswap_v3_eth-2-weth-usdt_eth-spot[0m unique buyers (2024-10-06 to 2024-10-09): 
[1m351

```

```python
defi_buyers = pd.DataFrame(defi_trades)
defi_buyers['time'] = pd.to_datetime(defi_buyers['time'])
defi_buyers.set_index('time', inplace=True)
```

```python
hourly_unique_buyers = defi_buyers['beneficiary'].resample('h').nunique()
sns.set_style('whitegrid')
fig, ax = plt.subplots()
sns.lineplot(data=hourly_unique_buyers, ax=ax)
ax.set_xlabel('')
ax.set_ylabel('Unique Buyers per Hour')
ax.set_title('\nPool ' + str(market_string) + '\nUnique Buyers per Hour\n', font='arial', size=20)
plt.grid(color='black', linestyle='dotted')
plt.show()
```

<figure><img src="/files/duih9U93RfHJQG5f0inC" alt=""><figcaption></figcaption></figure>

```python
# Unique buyer addresses
((defi_trades.loc[(defi_trades['side']=='buy')]).beneficiary.unique())
```

```
<StringArray>
['1111111254eeb25477b68fb85ed929f73a960582',
 '5ced44f03ff443bbe14d8ea23bc24425fb89e3ed',
 '2bbf5243e49e8f0025988754dac6620ab0d3e162',
 '308c6fbd6a14881af333649f17f2fde9cd75e2a6',
 'def1c0ded9bec7f1a1670819833240f027b25eff',
 '313d26bf14c4362883cc798d4aa50352fc55c954',
 '3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad',
 '111111125421ca6dc452d289314280a0f8842a65',
 '2580916979353d3a40c71be00b0e197a98694cdf',
 'e37e799d5077682fa0a244d46e5649f71457bd09',
 ...
 '898fcb7b4e3bee37ebb0ca3a3fbd08cefdc8c995',
 '8ef79d6c328c25da633559c20c75f638a4863462',
 '309eac50cedc3909ce0f03c9725bb7a684b75829',
 '98c640aac6b88f5e1ab14073dd2d5baf71461e9c',
 '0f388ecdbc128083bfe317b00de2c25fbe9f24d5',
 '8583c58e3b0e02d2cdf45b06e437674f2fb47eb6',
 '6905fef2f9a7825f94018f4f989dc82f88be9181',
 '0b2b99d9fa762060fdbf1657984f7ece56ca5e5c',
 'f2b6525a3d7f28113cc57cb9b73dde9230073059',
 '051ef36e55875c08e4efaea6072c6d0f66fb0b9f']
Length: 351, dtype: string
```

```python
# Calculate approximate USD volume (NOTE: quote asset must be a stablecoin)
defi_trades['DEX Volume (USD)'] = (defi_trades['amount'])*(defi_trades['price'])

# Use only the amount field if base asset is a stablecoin
#defi_trades['DeFi Volume (USD)'] = (defi_trades['amount'])
```

```python
# Largest trade
largest = defi_trades.loc[defi_trades['amount'].idxmax()]
trade_size_usd = '${:,.2f}'.format(largest['DEX Volume (USD)'])
pd.DataFrame(largest)
```

|                   | 2628                                              |
| ----------------- | ------------------------------------------------- |
| market            | uniswap\_v3\_eth-2-weth-usdt\_eth-spot            |
| time              | 2024-10-07 18:39:35+00:00                         |
| coin\_metrics\_id | 04VIAJ3J2LDTBQKN8T3DB7MJM1EP7SID408V74DL4USTFL... |
| amount            | 1192.565431                                       |
| price             | 2274.221925                                       |
| database\_time    | 2024-10-07 18:39:54.427105+00:00                  |
| side              | buy                                               |
| block\_hash       | 73155bd5ea974746d59ed3b05d93f24d2011f391b527b9... |
| block\_height     | 20915532                                          |
| txid              | cb93842f093812b85469b576914d02907345d2624e1eee... |
| initiator         | b5eaac5a8649142dcdd13f981767913bcdf7ee42          |
| sender            | ddc25c965443834179438c2eb30e70f34b854a04          |
| beneficiary       | ddc25c965443834179438c2eb30e70f34b854a04          |
| DEX Volume (USD)  | 2712158.449637                                    |
| Datetime          | 2024-10-07 18:00:00                               |

```python
print('\nLARGEST TRADE: \n\n' + trade_size_usd + ' by address 0x' + largest['beneficiary'] + '\n')
```

```
LARGEST TRADE: 

$2,712,158.45 by address 0xddc25c965443834179438c2eb30e70f34b854a04

```

```python
# ATLAS links for blockchain metadata
md('<br>**ATLAS** by Coin Metrics <br> **Blockchain Search Engine** <br><br>**BUYER ADDRESS:** https://atlas.coinmetrics.io/address-details?asset=weth&address=' + str(largest['beneficiary']) + '<br><br>**TRANSACTION INFO:** https://atlas.coinmetrics.io/transaction-details?asset=weth&tx_hash=' + str(largest['txid']) + '<br><br>**BlOCK INFO:** https://atlas.coinmetrics.io/block-details?asset=weth&block_hash=' + str(largest['block_hash']) + '<br><br>For more info on **ATLAS** visit: https://coinmetrics.io/atlas/')
```

\
**ATLAS** by Coin Metrics\
**Blockchain Search Engine**\
\
**BUYER ADDRESS:** <https://atlas.coinmetrics.io/address-details?asset=weth\\&address=ddc25c965443834179438c2eb30e70f34b854a04\\>
\
**TRANSACTION INFO:** <https://atlas.coinmetrics.io/transaction-details?asset=weth\\&tx\\_hash=cb93842f093812b85469b576914d02907345d2624e1eee463999bade940a8851\\>
\
**BlOCK INFO:** <https://atlas.coinmetrics.io/block-details?asset=weth\\&block\\_hash=73155bd5ea974746d59ed3b05d93f24d2011f391b527b9d7d5c42e59752c6d41\\>
\
For more info on **ATLAS** visit: <https://coinmetrics.io/atlas/>

```python
defi_trades['Datetime'] = pd.to_datetime(defi_trades.time.dt.strftime('%m/%d/%y %H:00'))
defi_vol = defi_trades.groupby('Datetime')['DEX Volume (USD)'].sum()
```

```python
pd.DataFrame(defi_vol)
```

|                     | DEX Volume (USD) |
| ------------------- | ---------------- |
| Datetime            |                  |
| 2024-10-06 11:00:00 | 217166.26046     |
| 2024-10-06 12:00:00 | 438390.416765    |
| 2024-10-06 13:00:00 | 533070.744054    |
| 2024-10-06 14:00:00 | 1163987.797628   |
| 2024-10-06 15:00:00 | 705547.880282    |
| ...                 | ...              |
| 2024-10-09 06:00:00 | 625096.999423    |
| 2024-10-09 07:00:00 | 485056.495087    |
| 2024-10-09 08:00:00 | 553334.67282     |
| 2024-10-09 09:00:00 | 462252.636566    |
| 2024-10-09 10:00:00 | 102118.526838    |

72 rows × 1 columns

#### Retrieving volume for a centralized exchange via the market-candles endpoint

```python
cex_market = 'coinbase-eth-usd-spot'
```

```python
cex_vol = client.get_market_candles(
    markets=cex_market,
    frequency='1h',
    start_time=start,
    end_time=end- timedelta(hours=1)
).to_dataframe()

cex_vol = cex_vol.rename(columns={"candle_usd_volume": "CEX Volume (USD)"})
cex_vol['Datetime'] = pd.to_datetime(cex_vol.time.dt.strftime('%m/%d/%y %H:00'))
cex_vol = cex_vol.groupby('Datetime')['CEX Volume (USD)'].sum()
```

```python
vol_comp = pd.merge(defi_vol, cex_vol,on="Datetime", how="left").dropna()
vol_comp["DEX Volume (USD)"] = vol_comp['DEX Volume (USD)'].astype(int)
vol_comp["CEX Volume (USD)"] = vol_comp['CEX Volume (USD)'].astype(int)
```

```python
vol_comp
```

|                     | DEX Volume (USD) | CEX Volume (USD) |
| ------------------- | ---------------- | ---------------- |
| Datetime            |                  |                  |
| 2024-10-06 12:00:00 | 438390           | 946175           |
| 2024-10-06 13:00:00 | 533070           | 1258087          |
| 2024-10-06 14:00:00 | 1163987          | 3316466          |
| 2024-10-06 15:00:00 | 705547           | 2654936          |
| 2024-10-06 16:00:00 | 551985           | 1881551          |
| ...                 | ...              | ...              |
| 2024-10-09 05:00:00 | 550504           | 1912136          |
| 2024-10-09 06:00:00 | 625096           | 2814167          |
| 2024-10-09 07:00:00 | 485056           | 4493300          |
| 2024-10-09 08:00:00 | 553334           | 2393424          |
| 2024-10-09 09:00:00 | 462252           | 2559575          |

70 rows × 2 columns

```python
sns.set_style('whitegrid')
vc = sns.lineplot(data=vol_comp)
vc.yaxis.set_major_formatter('${x:,.0f}')
vc.set_title(str('\n' + defi_market.upper() + '\n vs. \n' + cex_market.upper() + '\n Hourly Volume \n'),font='arial',fontsize=17.5)
vc.set_ylabel("Volume (USD) \n", font='arial',fontsize = 14)
plt.grid(color='black', linestyle='dotted')
legend = vc.legend(fontsize=15, framealpha=0, bbox_to_anchor=(1.0, 1.2))
vc.set_xlabel("");
```

<figure><img src="/files/5IB5urFh4w1n0mEwahyN" alt=""><figcaption></figcaption></figure>


# Analyzing DeFi Protocol Balance Sheets

![](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/Demo%20Asset%20Resources/CM-Demo-balance_sheets-Cover.png)

Decentralized Finance (DeFi) is a rapidly emerging ecosystem of applications and protocols used for trading, lending, and various other financial services. Rather than relying on centralized intermediaries, these protocols utilize permissionless blockchains such as Ethereum to conduct the majority of their activities and transactions on-chain. While these protocols offer an unprecedented level of transparency, complex smart contract code and overlapping on-chain transactions can be difficult to interpret. Coin Metrics **DeFi Balance Sheets** endpoint attempts to distill these operations into a traditional accounting format, presenting protocol assets and liabilities in an intuitive, easy-to-understand schema.

### Resources

This notebook demonstrates basic functionality offered by the Coin Metrics Python API Client.

Coin Metrics offers a vast assortment of data for hundreds of cryptoassets. The Python API Client allows for easy access to this data using Python without needing to create your own wrappers using `requests` and other such libraries.

To understand the data that Coin Metrics offers, feel free to peruse the resources below.

* The [Coin Metrics API v4](https://docs.coinmetrics.io/api/v4) website contains the full set of endpoints and data offered by Coin Metrics.
* The [Coin Metrics Product Documentation](https://docs.coinmetrics.io/info) gives detailed, conceptual explanations of the data that Coin Metrics offers.
* The [API Spec](https://docs.coinmetrics.io/python-api-client/reference) contains a full list of functions.

### File Download

Download the entire notebook as either a jupyter notebook to run yourself or as a pdf from the two links below

{% file src="/files/YTrMwaRRpeyhc9mFQHQ2" %}

{% file src="/files/le9V3l0eymRStGsqoNVq" %}

### Notebook Setup

```python
from os import environ
import sys
import pandas as pd
import numpy as np
import seaborn as sns
import logging
from datetime import date, datetime, timedelta
from coinmetrics.api_client import CoinMetricsClient
import json
import logging
from pytz import timezone as timezone_conv
from datetime import timezone as timezone_info
import matplotlib.dates as mdates
from IPython.display import Markdown as md
import matplotlib.pyplot as plt
import requests
import locale
import ast
# %matplotlib inline
```

```python
sns.set_theme()
sns.set(rc={'figure.figsize':(12,8)})
sns.set_style("whitegrid",{'axes.grid' : True,'grid.linestyle': '--', 'grid.color': 'gray','axes.edgecolor': 'white','font.family': ['arial']})
```

```python
logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S'
)
```

```python
# We recommend privately storing your API key in your local environment.
try:
    api_key = environ["CM_API_KEY"]
    logging.info("Using API key found in environment")
except KeyError:
    api_key = ""
    logging.info("API key not found. Using community client")

client = CoinMetricsClient(api_key)
```

```
2024-10-16 09:31:03 INFO     Using API key found in environment
```

## Retrieve Balance Sheet

```python
aave_v2_eth = client.get_defi_balance_sheets(
    defi_protocols = "aave_v2_eth",
    start_time = '2023-10-15',
    end_time = '2024-10-15').to_dataframe()

# Creating Start and End Time Variables to Simplify Future Data Creation
start_time = pd.to_datetime('2023-10-15')
end_time = pd.to_datetime('2024-10-15')

number_of_days = (end_time - start_time).days

header_index = number_of_days

#Showing last few rows of our current DataFrame with time parameters
aave_v2_eth.tail()
```

|     | defi\_protocol | block\_height | time                      | assets\_total\_usd | assets\_total\_count | liabilities\_total\_usd | liabilities\_total\_count | loans\_lent\_total\_usd | tvl\_total\_usd | net\_working\_capital\_usd | assets                                              | liabilities                                         | protocol\_utilization\_ratio | liquid\_supply\_ratio | current\_ratio | debt\_to\_assets\_ratio |
| --- | -------------- | ------------- | ------------------------- | ------------------ | -------------------- | ----------------------- | ------------------------- | ----------------------- | --------------- | -------------------------- | --------------------------------------------------- | --------------------------------------------------- | ---------------------------- | --------------------- | -------------- | ----------------------- |
| 362 | aave\_v2\_eth  | 20938657      | 2024-10-11 00:00:00+00:00 | 1093532689.9828    | 49                   | 1093614333.6095         | 49                        | 351033529.7825          | 742499160.2003  | -351115173.4092            | \[{'asset': '1inch', 'total\_units': '56475.6927... | \[{'asset': '1inch', 'total\_units': '56085.2667... | 0.320985                     | 0.678941              | 0.678941       | 1.000075                |
| 363 | aave\_v2\_eth  | 20945811      | 2024-10-12 00:00:00+00:00 | 1111063638.7613    | 49                   | 1111174709.0494         | 49                        | 354732076.2007          | 756331562.5606  | -354843146.4888            | \[{'asset': '1inch', 'total\_units': '56476.3058... | \[{'asset': '1inch', 'total\_units': '56085.2668... | 0.319241                     | 0.68066               | 0.68066        | 1.0001                  |
| 364 | aave\_v2\_eth  | 20952957      | 2024-10-13 00:00:00+00:00 | 1124501751.5171    | 49                   | 1124630410.0842         | 49                        | 357832576.4653          | 766669175.0518  | -357961235.0324            | \[{'asset': '1inch', 'total\_units': '56476.9193... | \[{'asset': '1inch', 'total\_units': '56085.2669... | 0.318178                     | 0.681708              | 0.681708       | 1.000115                |
| 365 | aave\_v2\_eth  | 20960089      | 2024-10-14 00:00:00+00:00 | 1116858119.0506    | 49                   | 1117027224.2051         | 49                        | 356159715.5002          | 760698403.5504  | -356328820.6547            | \[{'asset': '1inch', 'total\_units': '56477.5331... | \[{'asset': '1inch', 'total\_units': '56085.2669... | 0.318847                     | 0.681003              | 0.681003       | 1.000152                |
| 366 | aave\_v2\_eth  | 20967244      | 2024-10-15 00:00:00+00:00 | 1167546255.9893    | 49                   | 1167839749.2056         | 49                        | 365325202.3638          | 802221053.6255  | -365618695.5801            | \[{'asset': '1inch', 'total\_units': '56478.1472... | \[{'asset': '1inch', 'total\_units': '56085.2670... | 0.312822                     | 0.686928              | 0.686928       | 1.000252                |

```python
last_row = pd.DataFrame(aave_v2_eth.sort_values(by='time',ascending=False).iloc[0])
last_row
```

|                              | 366                                                 |
| ---------------------------- | --------------------------------------------------- |
| defi\_protocol               | aave\_v2\_eth                                       |
| block\_height                | 20967244                                            |
| time                         | 2024-10-15 00:00:00+00:00                           |
| assets\_total\_usd           | 1167546255.9893                                     |
| assets\_total\_count         | 49                                                  |
| liabilities\_total\_usd      | 1167839749.2056                                     |
| liabilities\_total\_count    | 49                                                  |
| loans\_lent\_total\_usd      | 365325202.3638                                      |
| tvl\_total\_usd              | 802221053.6255                                      |
| net\_working\_capital\_usd   | -365618695.5801                                     |
| assets                       | \[{'asset': '1inch', 'total\_units': '56478.1472... |
| liabilities                  | \[{'asset': '1inch', 'total\_units': '56085.2670... |
| protocol\_utilization\_ratio | 0.312822                                            |
| liquid\_supply\_ratio        | 0.686928                                            |
| current\_ratio               | 0.686928                                            |
| debt\_to\_assets\_ratio      | 1.000252                                            |

```python
assets = last_row.loc["assets"].astype("str")
assets = assets.apply(lambda x: ast.literal_eval(x))
assets = assets.apply(pd.Series)
assets = assets.transpose()
assets = pd.json_normalize(assets[header_index])
assets = assets.set_index('asset').astype(float).sort_values('tvl_usd', ascending=False)
assets
```

|               | total\_units | loans\_lent\_units | tvl\_units   | total\_usd   | loans\_lent\_usd | tvl\_usd     | total\_share | loans\_lent\_share | tvl\_share |
| ------------- | ------------ | ------------------ | ------------ | ------------ | ---------------- | ------------ | ------------ | ------------------ | ---------- |
| asset         |              |                    |              |              |                  |              |              |                    |            |
| wbtc          | 4.848282e+03 | 5.466126e+02       | 4.301669e+03 | 3.198977e+08 | 3.606640e+07     | 2.838313e+08 | 0.273991     | 0.098724           | 0.353807   |
| steth\_lido   | 1.040132e+05 | NaN                | 1.040132e+05 | 2.735189e+08 | NaN              | 2.735189e+08 | 0.234268     | NaN                | 0.340952   |
| weth          | 9.980952e+04 | 3.763314e+04       | 6.217638e+04 | 2.625917e+08 | 9.901010e+07     | 1.635816e+08 | 0.224909     | 0.271019           | 0.203911   |
| dai           | 4.809159e+07 | 2.683005e+07       | 2.126154e+07 | 4.808146e+07 | 2.682440e+07     | 2.125706e+07 | 0.041182     | 0.073426           | 0.026498   |
| usdt\_eth     | 1.032573e+08 | 8.644445e+07       | 1.681281e+07 | 1.032206e+08 | 8.641379e+07     | 1.680685e+07 | 0.088408     | 0.236539           | 0.020950   |
| link          | 1.464885e+06 | 5.475866e+04       | 1.410127e+06 | 1.649758e+07 | 6.166937e+05     | 1.588089e+07 | 0.014130     | 0.001688           | 0.019796   |
| usdc          | 1.271867e+08 | 1.148692e+08       | 1.231756e+07 | 1.271589e+08 | 1.148440e+08     | 1.231486e+07 | 0.108911     | 0.314361           | 0.015351   |
| aave          | 4.722557e+04 | NaN                | 4.722557e+04 | 7.681909e+06 | NaN              | 7.681909e+06 | 0.006580     | NaN                | 0.009576   |
| mkr           | 1.280425e+03 | 1.074842e+00       | 1.279350e+03 | 1.783592e+06 | 1.497221e+03     | 1.782095e+06 | 0.001528     | 0.000004           | 0.002221   |
| crv           | 2.539174e+06 | 7.895537e+03       | 2.531279e+06 | 6.821795e+05 | 2.121230e+03     | 6.800583e+05 | 0.000584     | 0.000006           | 0.000848   |
| uni           | 8.171202e+04 | 2.884203e+03       | 7.882782e+04 | 6.628549e+05 | 2.339690e+04     | 6.394580e+05 | 0.000568     | 0.000064           | 0.000797   |
| snx           | 4.090228e+05 | 2.623178e+03       | 4.063996e+05 | 6.343925e+05 | 4.068537e+03     | 6.303239e+05 | 0.000543     | 0.000011           | 0.000786   |
| busd          | 7.909986e+05 | 2.157098e+05       | 5.752888e+05 | 7.890753e+05 | 2.151853e+05     | 5.738900e+05 | 0.000676     | 0.000589           | 0.000715   |
| frax          | 5.869414e+05 | 8.315375e+04       | 5.037876e+05 | 5.850664e+05 | 8.288812e+04     | 5.021783e+05 | 0.000501     | 0.000227           | 0.000626   |
| tusd          | 5.113231e+05 | 1.365453e+05       | 3.747778e+05 | 5.101233e+05 | 1.362249e+05     | 3.738985e+05 | 0.000437     | 0.000373           | 0.000466   |
| gusd          | 5.928732e+05 | 2.691468e+05       | 3.237263e+05 | 5.923533e+05 | 2.689108e+05     | 3.234425e+05 | 0.000507     | 0.000736           | 0.000403   |
| yfi           | 4.882787e+01 | 5.700117e-02       | 4.877086e+01 | 2.460453e+05 | 2.872309e+02     | 2.457580e+05 | 0.000211     | 0.000001           | 0.000306   |
| mana          | 9.075228e+05 | 1.570493e+05       | 7.504735e+05 | 2.807515e+05 | 4.858480e+04     | 2.321667e+05 | 0.000240     | 0.000133           | 0.000289   |
| rai           | 7.827556e+04 | 1.651545e+04       | 6.176010e+04 | 2.383428e+05 | 5.028824e+04     | 1.880546e+05 | 0.000204     | 0.000138           | 0.000234   |
| susd          | 3.454224e+05 | 1.701397e+05       | 1.752826e+05 | 3.448540e+05 | 1.698598e+05     | 1.749942e+05 | 0.000295     | 0.000465           | 0.000218   |
| ens           | 9.499343e+03 | 3.318105e+01       | 9.466162e+03 | 1.728763e+05 | 6.038542e+02     | 1.722725e+05 | 0.000148     | 0.000002           | 0.000215   |
| ust           | 6.382869e+06 | 2.446807e+05       | 6.138189e+06 | 1.395150e+05 | 5.348164e+03     | 1.341669e+05 | 0.000119     | 0.000015           | 0.000167   |
| pax           | 2.320820e+05 | 1.059562e+05       | 1.261257e+05 | 2.318035e+05 | 1.058291e+05     | 1.259744e+05 | 0.000199     | 0.000290           | 0.000157   |
| bal           | 6.257505e+04 | 3.488278e+03       | 5.908677e+04 | 1.290957e+05 | 7.196507e+03     | 1.218992e+05 | 0.000111     | 0.000020           | 0.000152   |
| zrx           | 2.935068e+05 | 5.396759e+03       | 2.881101e+05 | 9.856175e+04 | 1.812271e+03     | 9.674948e+04 | 0.000084     | 0.000005           | 0.000121   |
| lusd          | 1.440150e+05 | 5.852579e+04       | 8.548924e+04 | 1.437232e+05 | 5.840718e+04     | 8.531598e+04 | 0.000123     | 0.000160           | 0.000106   |
| ren           | 1.739052e+06 | 6.816859e+03       | 1.732235e+06 | 6.742399e+04 | 2.642933e+02     | 6.715970e+04 | 0.000058     | 0.000001           | 0.000084   |
| cvx           | 3.273132e+04 | 1.463298e+02       | 3.258499e+04 | 6.226566e+04 | 2.783670e+02     | 6.198729e+04 | 0.000053     | 0.000001           | 0.000077   |
| bat           | 3.405090e+05 | 6.836504e+03       | 3.336725e+05 | 6.146868e+04 | 1.234126e+03     | 6.023455e+04 | 0.000053     | 0.000003           | 0.000075   |
| enj           | 2.973739e+05 | 9.736583e+04       | 2.000080e+05 | 4.734441e+04 | 1.550145e+04     | 3.184295e+04 | 0.000041     | 0.000042           | 0.000040   |
| 1inch         | 5.647815e+04 | 1.121128e+03       | 5.535702e+04 | 1.533170e+04 | 3.043444e+02     | 1.502736e+04 | 0.000013     | 0.000001           | 0.000019   |
| ampl          | 2.545603e+05 | 2.457468e+05       | 8.813521e+03 | 3.521378e+05 | 3.399459e+05     | 1.219190e+04 | 0.000302     | 0.000931           | 0.000015   |
| knc           | 3.358496e+04 | 1.393234e+04       | 1.965262e+04 | 1.582542e+04 | 6.564995e+03     | 9.260421e+03 | 0.000014     | 0.000018           | 0.000012   |
| fei\_eth      | 1.075374e+04 | 3.299947e+03       | 7.453792e+03 | 1.045299e+04 | 3.207657e+03     | 7.245332e+03 | 0.000009     | 0.000009           | 0.000009   |
| BptBALWETH    | 2.422182e-09 | NaN                | 2.422182e-09 | NaN          | NaN              | NaN          | NaN          | NaN                | NaN        |
| BptWBTCWETH   | 3.185679e-03 | NaN                | 3.185679e-03 | NaN          | NaN              | NaN          | NaN          | NaN                | NaN        |
| GUniDAIUSDC   | 3.743267e+00 | NaN                | 3.743267e+00 | NaN          | NaN              | NaN          | NaN          | NaN                | NaN        |
| GUniUSDCUSDT  | 9.999975e-02 | NaN                | 9.999975e-02 | NaN          | NaN              | NaN          | NaN          | NaN                | NaN        |
| Univ2AAVEWETH | 1.346558e-01 | NaN                | 1.346558e-01 | NaN          | NaN              | NaN          | NaN          | NaN                | NaN        |
| Univ2CRVWETH  | 4.136273e-05 | NaN                | 4.136273e-05 | NaN          | NaN              | NaN          | NaN          | NaN                | NaN        |
| Univ2DAIUSDC  | 9.089043e-06 | NaN                | 9.089043e-06 | NaN          | NaN              | NaN          | NaN          | NaN                | NaN        |
| Univ2DAIWETH  | 3.669936e-01 | NaN                | 3.669936e-01 | NaN          | NaN              | NaN          | NaN          | NaN                | NaN        |
| Univ2LINKWETH | 8.050459e+01 | NaN                | 8.050459e+01 | NaN          | NaN              | NaN          | NaN          | NaN                | NaN        |
| Univ2UNIWETH  | 1.210293e+00 | NaN                | 1.210293e+00 | NaN          | NaN              | NaN          | NaN          | NaN                | NaN        |
| Univ2USDCWETH | 3.099794e-07 | NaN                | 3.099794e-07 | NaN          | NaN              | NaN          | NaN          | NaN                | NaN        |
| Univ2WBTCWETH | 1.887777e-07 | NaN                | 1.887777e-07 | NaN          | NaN              | NaN          | NaN          | NaN                | NaN        |
| dpi           | 8.275005e+02 | 4.202049e+02       | 4.072956e+02 | NaN          | NaN              | NaN          | NaN          | NaN                | NaN        |
| renfil        | 6.387879e+03 | 6.162561e+03       | 2.253174e+02 | NaN          | NaN              | NaN          | NaN          | NaN                | NaN        |
| xsushi        | 4.261961e+05 | 3.357735e+02       | 4.258604e+05 | NaN          | NaN              | NaN          | NaN          | NaN                | NaN        |

```python
assets_tvl_totals = assets['tvl_usd']
```

```python
#the top 7
assets_tvl_top7 = assets_tvl_totals[:7].copy()
# other
assets_tvl_top7.loc['other'] = assets['tvl_usd'][7:].sum()
```

```python
df = pd.DataFrame(assets_tvl_top7)
df['tvl_usd'] = df['tvl_usd'].apply(lambda x: "${:,.2f}".format((x)))
df
```

|             | tvl\_usd        |
| ----------- | --------------- |
| asset       |                 |
| wbtc        | $283,831,271.42 |
| steth\_lido | $273,518,949.72 |
| weth        | $163,581,616.37 |
| dai         | $21,257,057.15  |
| usdt\_eth   | $16,806,852.06  |
| link        | $15,880,889.36  |
| usdc        | $12,314,862.37  |
| other       | $15,029,555.17  |

```python
def my_autopct(pct):
    return ('%.2f' % pct + '%') if pct > 7 else ''

axes = assets_tvl_top7.plot(kind='pie', autopct=my_autopct, figsize=(16, 16), subplots=True, layout=(2, 2), legend=False, labeldistance=1.1)

for ax in axes.flat:
    yl = ax.get_ylabel()
    ax.set(ylabel='', title=yl)
    ax.set_title('Aave_v2_ETH \nEstimated TVL Share (USD) by Asset*',size=20, font='arial')

fig = axes[0, 0].get_figure()
fig.suptitle('\n*Assets with CM Reference Rate',size=11, font='arial')

fig.tight_layout()
plt.rcParams['font.size'] = 15.0
```

<figure><img src="/files/fU7vrfUKeip0vScvJmOQ" alt=""><figcaption></figcaption></figure>

```python
aave_v2_eth.index = (pd.to_datetime(aave_v2_eth.time)).dt.date
aave_v2_eth["Total Value Locked (USD)"] = aave_v2_eth.tvl_total_usd.astype(float)
aave_tvl = aave_v2_eth[['defi_protocol','Total Value Locked (USD)']]
```

```python
aave_tvl
```

|            | defi\_protocol | Total Value Locked (USD) |
| ---------- | -------------- | ------------------------ |
| time       |                |                          |
| 2023-10-15 | aave\_v2\_eth  | 1.989641e+09             |
| 2023-10-16 | aave\_v2\_eth  | 1.995368e+09             |
| 2023-10-17 | aave\_v2\_eth  | 2.032416e+09             |
| 2023-10-18 | aave\_v2\_eth  | 1.987327e+09             |
| 2023-10-19 | aave\_v2\_eth  | 1.970314e+09             |
| ...        | ...            | ...                      |
| 2024-10-11 | aave\_v2\_eth  | 7.424992e+08             |
| 2024-10-12 | aave\_v2\_eth  | 7.563316e+08             |
| 2024-10-13 | aave\_v2\_eth  | 7.666692e+08             |
| 2024-10-14 | aave\_v2\_eth  | 7.606984e+08             |
| 2024-10-15 | aave\_v2\_eth  | 8.022211e+08             |

367 rows × 2 columns

```python
ax = aave_tvl.plot.area()
plt.xlim([aave_tvl.index[0], aave_tvl.index[-1]])
plt.title('\n' + str(aave_tvl.defi_protocol.iloc[0]).upper() + '\n Total Value Locked \n',fontdict={'fontsize':19.5})
ax.set_xlabel("")
ax.set_ylabel("Total Value Locked (USD) \n",fontdict={'fontsize':13.5})
ax.yaxis.set_ticks(plt.gca().get_yticks())
ax.get_legend().remove()
plt.gca().set_yticklabels(['${:,.2f}B'.format(x/1000000000) for x in plt.gca().get_yticks()]);
```

<figure><img src="/files/0vqZCMhMCMpZi2z7dXMW" alt=""><figcaption></figcaption></figure>


# Obtaining Futures Market Liquidations

{% embed url="<https://www.youtube.com/watch?v=BzEHJc2mRto>" %}

{% embed url="<https://github.com/coinmetrics/demo/blob/master/Market_Liquidations.ipynb>" %}

### Instructions

The notebook linked above shows how to obtain liquidation metrics for futures. We show both REST API calls and web socket connections for the same.

The video also covers how to use Reference Data and Catalog. It is applicable for all market data / asset metrics.

The notebook was published for [Google Colab](https://colab.research.google.com/). If you want to use it in Colab, the easiest way is to open Colab and load the notebook from the Github URL (pasted into the open dialog). This method does not require cloning the repo first.

If you prefer to use the notebook with Jupyter, all you need to change is the way in which the API key is retrieved.


# Obtaining Predicted Funding Rates for Futures

{% embed url="<https://www.youtube.com/watch?v=8na389sEYK8>" %}

{% embed url="<https://github.com/coinmetrics/demo/blob/master/Predicted_Market_Funding_Rates.ipynb>" %}

### Instructions

The notebook linked above shows how to obtain predicted funding rates for futures. While the *actual* funding rates don't change very frequently, the *predicted* funding rate is calculated every minute or so and therefore can be a leading indicator for funding rate changes.

This video also compares two plotting libraries: matplotlib and plotly express.

The notebook was published for [Google Colab](https://colab.research.google.com/). If you want to use it in Colab, the easiest way is to open Colab and load the notebook from the Github URL (pasted into the open dialog). This method does not require cloning the repo first.

If you prefer to use the notebook with Jupyter, all you need to change is the way in which the API key is retrieved.


# Exploring Availability of Market Data for CME (Derivatives)

{% embed url="<https://www.youtube.com/watch?v=kiiuqkptxZU>" %}

{% embed url="<https://github.com/coinmetrics/demo/blob/master/cme_exploration.py>" %}

### Instructions

The notebook linked above shows how to explore data from CME (Chicago Mercantile Exchange), one of the big derivatives exchanges. Options on derivatives are probably the most complicated market instruments available on Coin Metrics, so this may be particularly interesting!

This notebook linked above is in [Marimo](https://marimo.io/) format. The code below is more readable, but does not preserve the cell breaks. We recommend using Marimo as new, modern Jupyter environment.

```python
from coinmetrics.api_client import CoinMetricsClient
import os
import marimo as mo
from datetime import datetime, timedelta, time, timezone
import matplotlib.pyplot as plt
import pandas as pd

client = CoinMetricsClient(os.getenv('CM_API_KEY'))

end_time = datetime.now(tz=timezone.utc)
start_time = end_time - timedelta(days=60)


cme = client.reference_data_markets(exchange='cme').to_dataframe()
cme


cme.loc[(cme.pair=='btc-usd') & (cme.expiration >= end_time)].groupby(['expiration', 'pair', 'type', 'contract_size'], observed=True).agg({
    'strike': ['count', 'min', 'max'],
    'market': ['count', 'first']
})


my_markets = cme.loc[(cme.symbol.apply(len)==5) 
    & (cme.expiration >= end_time)
    & (cme.size_asset.isin(['btc', 'eth']))
    ].sort_values(['expiration', 'size_asset']).loc[:, ['expiration', 'symbol', 'market']]
my_markets.set_index('symbol')


client.catalog_market_candles_v2(markets=list(my_markets.market)).to_dataframe().set_index(['market', 'frequency'])

df = client.get_market_candles(markets=['cme-BTCM5-future',  ],
                         start_time=start_time,
                         frequency='1d').to_dataframe() # 'cme-BTCK5-future', 'cme-BTCM5-future',




# Ensure we have a datetime index or 'time' column
if not isinstance(df.index, pd.DatetimeIndex):
    if 'time' in df.columns:
        _df_time = pd.to_datetime(df['time'])
    else:
        raise ValueError("No datetime index or 'time' column found.")
else:
    _df_time = df.index

# Cumulative sum of volume per day, starting at midnight
_df = df.copy()
_df['__date'] = _df_time.dt.date
_df['vol_current_day_'] = _df.groupby(['market','__date'])['volume'].cumsum()
_df = _df.drop(columns='__date')

_df



import plotly.graph_objs as go

candles_90 = df.sort_index().iloc[-90:].copy()
# If the index is not a DatetimeIndex, reset and use time column if available
if not isinstance(candles_90.index, pd.DatetimeIndex):
    if 'time' in candles_90.columns:
        candles_90['time'] = pd.to_datetime(candles_90['time'])
    else:
        # fallback to numeric index as x axis
        candles_90['time'] = candles_90.index

# Candle chart
fig = go.Figure()

fig.add_trace(go.Candlestick(
    x=candles_90.get('time', candles_90.index),
    open=candles_90['price_open'],
    high=candles_90['price_high'],
    low=candles_90['price_low'],
    close=candles_90['price_close'],
    name="Price",
    increasing_line_color='green',
    decreasing_line_color='red',
))

fig.add_trace(go.Bar(
    x=candles_90.get('time', candles_90.index),
    y=candles_90['volume'],
    name='Volume',
    marker_color='steelblue',
    opacity=0.35,
    yaxis='y2',
))

# Layout for dual y-axis
fig.update_layout(
    title="CME Candle Chart with Volume (BTCM5=June 2025 epxiry)",
    yaxis_title="Price",
    xaxis_title="Time",
    yaxis2=dict(title='Volume', overlaying='y', side='right', showgrid=False),
    xaxis_rangeslider_visible=False,
    height=500,
    legend=dict(orientation='h', yanchor="bottom", y=1.02, xanchor="right", x=1)
)

fig



client.catalog_market_contract_prices_v2(exchange='cme').to_dataframe()

client.catalog_market_open_interest_v2(exchange='cme').to_dataframe()

client.catalog_market_implied_volatility_v2(exchange='cme').to_dataframe()

client.catalog_market_funding_rates_v2(exchange='cme').to_dataframe()

client.catalog_market_greeks_v2(exchange='cme').to_dataframe()

ob = client.catalog_market_orderbooks_v2(markets=list(my_markets.market),
                         ).to_list()
ob[0]

unpack = []

for m in ob:
    for de in m['depths']:
        unpack.append(
            {
                "market": m['market'],
                "depth": de['depth'],
                "min_time": de['min_time'],
                "max_time": de['max_time'],
            }
        )
pd.DataFrame(unpack)

EAM = client.catalog_exchange_asset_metrics_v2().to_dataframe()

EAM.loc[(EAM.metric.str.contains('future')) & (EAM.exchange_asset.str.startswith('cme-'))]

EAM.loc[(EAM.metric.str.contains('option')) & (EAM.exchange_asset.str.startswith('cme-'))]

import plotly.express as px

# Prepare data
metric_name = "volume_reported_option_notional_usd_1d"
exchange_asset = "cme-usd"
freq = "1d"
series_px = client.get_exchange_asset_metrics(
    metrics=[metric_name], 
    frequency=freq, 
    exchange_assets=[exchange_asset],
).to_dataframe().reset_index()
series_px['time'] = pd.to_datetime(series_px['time'])

# Find top 3
top3 = series_px.nlargest(3, metric_name)

# Plot
fig_px = px.line(
    series_px,
    x='time',
    y=metric_name,
    title="CME Reported Option Notional Volume (Top 3 Labeled)",
    labels={
        "time": "Time",
        metric_name: "Option Notional Volume (USD)"
    },
    markers=True
)

# Add explicit text labels for top 3 values
for _, row in top3.iterrows():
    fig_px.add_annotation(
        x=row['time'],
        y=row[metric_name],
        text=f"{row['time'].date().isoformat()}/{row[metric_name]/1e6:,.0f} mUSD",
        showarrow=True,
        arrowhead=2,
        ay=-40,
        font=dict(color="crimson", size=13)
    )

fig_px.update_traces(line_color="indigo", marker=dict(size=7))
fig_px.update_layout(yaxis_title="Option Notional Volume (USD)", xaxis_title="Time")
fig_px
```


# Analyzing BTC Liquidity

{% embed url="<https://us06web.zoom.us/clips/share/gzuBnTrwSHqTRPB8SfSSmw>" %}

{% embed url="<https://github.com/coinmetrics/demo/blob/master/liquidity_analysis.py>" %}

Watch this 10 minute tutorial and inspect the attached [Marimo](https://marimo.io/) notebook to learn about:

* Difference between "market" and "exchange-asset" metrics
* Total volume of BTC traded, ranked by exchange (10 exchanges cover 90%)
* Slippage metrics (how much does the price change for a given size)
* Using Plotly Express to zoom into data


# How To Guides

Our How To Guides are used to achieve specific goals using our data.

### [How To Export Data](/tutorials-and-examples/user-guides/exporting-data)

A guide on how to export data using common tools, such as curl, HTTP, Google Sheets, and the Python API Client.

### [How To Migrate From Catalog to Catalog V2 and Reference Data](#how-to-migrate-from-catalog-to-catalog-v2-and-reference-data)

A guide on how to conver the deprecated `catalog` endpoints to `catalog-v2` and `reference-data`

### [How To Use the Coin Metrics API Efficently](#how-to-use-the-coin-metrics-api-efficently)

Tips and tricks for how to maximize the efficiency of using the Coin Metrics API and the Python API Client.

### [How to Troubleshoot Common Errors](#how-to-troubleshoot-common-errors)

A guide on how to bypass common errors such as SSLErrors and common HTTP Error codes returned by the API such as 400, 401, 414, 429.

### [How to Use Websockets](#how-to-use-websockets)

A template for how to use timeseries-stream endpoints using Python.


# How To Export Data

This guide will show you how to export data using the Coin Metrics API.

## HTTP API

On a web browser, you can append any valid API request URL with `&format=csv` or `&format=json` to download the data in CSV or JSON format, respectively.

For example:

```
https://api.coinmetrics.io/v4/timeseries/asset-metrics?assets=eth&metrics=PriceUSD&frequency=1d&end_time=2015-08-01&start_inclusive=false&format=csv&api_key=<your_key>
```

## Google Sheets

On the formula tab, you can use the `IMPORTDATA` function on the HTTP call on a cell:

```
=IMPORTDATA("https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=CapMrktEstUSD,SplyCur,PriceUSD,CapMrktCurUSD&assets=usdc&frequency=1d&limit_per_asset=1&format=csv&api_key=<your_key>")
```

## Python API Client

In the Python API client, you can use the `export_to_csv` and `export_to_json` methods to export data to a CSV or JSON file.

For example:

```python
from coinmetrics.api_client import CoinMetricsClient

client = CoinMetricsClient()

client.get_asset_metrics(
    assets = ["btc", "eth"], 
    metrics = ["PriceUSD"], 
    start_time = "2024-01-01",
    end_time = "2024-01-31"
).export_to_csv("sample_data.csv")

client.get_asset_metrics(
    assets = ["btc", "eth"], 
    metrics = ["PriceUSD"], 
    start_time = "2024-01-01",
    end_time = "2024-01-31"
).export_to_json("sample_data.json")
```

As of version 2025.9.17.17, exporting to JSON files using the Python API Client is as fast using a `curl` command. See these [release notes](https://github.com/coinmetrics/api-client-python/releases) for more on benchmarking.

Exporting data can be sped up significantly by splitting the API calls to parallel threads.

```python
client.get_asset_metrics(
    assets = ["btc", "eth"], 
    metrics = ["PriceUSD"], 
    start_time = "2024-01-01",
    end_time = "2024-01-31"
).parallel("assets").export_to_csv_files()

# Exporting to CSV: 100%|██████████| 2/2 [00:00<00:00, 14.22it/s]
# 2025-09-18 15:41:36 [INFO] Files saved in: 
# ./asset-metrics/*.csv
```

Note that the download speed is evenly divided between all active connections of a single api key. 10 parallel connections are allowed. Excessing connections will be queued (no data transfer will happen).


# How To Migrate From Catalog to Catalog V2 and Reference Data

This guide will help you migrate from using `catalog` ("Catalog V1") to `catalog-v2` ("Catalog V2") and `reference-data` ("Reference Data"). Catalog V1 contains both static metadata (name, category, product, etc.) and coverage for a given data type (e.g. `min_time` and `max_time` for `trades`). Due to growing complexity in data coverage and the resulting performance bottlenecks from surfacing all of this data, this metadata is being separated. Catalog V2 and Reference Data allow for more lightweight and flexible queries as they can be queried across several dimensions (for example, `catalog-v2/asset-metrics` lets you filter by both asset and metric).

Switching between Catalog to Catalog V2 requires a subtle change in how to think about and find the data you're looking for.

**In general:**

* Use catalog-v2 to get information on **when** a **data type** is present.
* Use reference-data to get information on **which** **entities** are available and descriptions of **what** they are.
* catalog-v2 and reference-data take **less time** to retrieve data per call and go through pagination (which the [Python API Client](/access-our-data/python-client) automatically takes care of).

For more information on the reasoning behind the catalog migration, see [Catalog V1 to Catalog V2 Migration](/access-our-data/api/catalog-v1-v2-migration)

## Examples

### How do I get the assets/markets/exchanges covered?

**V1:**

* Use catalog/assets, catalog/markets, or catalog/exchanges respectively

**V2:**

* Use reference-data/assets, reference-data/markets, or reference-data/exchanges respectively

{% tabs %}
{% tab title="V2" %}

```python
assets = client.reference_data_assets().to_list()
markets = client.reference_data_markets().to_list()
exchanges = client.reference_data_exchanges().to_list()
```

{% endtab %}

{% tab title="V1" %}

```python
assets = client.catalog_assets()
markets = client.catalog_markets()
exchanges = client.catalog_exchanges()
```

{% endtab %}
{% endtabs %}

### **How do I** get which assets have been on an exchange?

**V1**: Use catalog/assets and get the "exchanges" field. Note that due to the size of the response, this might take a while.

**V2**: Use reference-data/markets?asset=\<ASSET> and get the "exchange" field for each observation, loop through each observation. (Note that due to pagination, you will have to loop through the entire response).

{% tabs %}
{% tab title="V2" %}

```python
list_markets = client.reference_data_markets(asset="btc").to_list()
list_exchanges = set([market['exchange'] for market in list_markets])
```

{% endtab %}

{% tab title="V1" %}

```python
list_exchanges = client.catalog_assets(assets="btc")[0]['exchanges']
```

{% endtab %}
{% endtabs %}

Note that these responses includes exchanges or markets that are now defunct. To get a more precise real-time coverage, see [#how-do-i-get-which-the-min-and-max-times-an-asset-has-been-traded-in-an-exchange](#how-do-i-get-which-the-min-and-max-times-an-asset-has-been-traded-in-an-exchange "mention")

### How do I get which markets are on an exchange?

**V1**: Use catalog/exchanges and get "markets" field

**V2**: Use reference-data/markets?exchange=\<EXCHANGE> and get the "market" field for each observation, loop through each observation. (Note that due to pagination, you will have to loop through the entire response).

{% tabs %}
{% tab title="V2" %}

```python
list_markets = client.reference_data_markets(exchange="coinbase").to_list()
list_markets = set([market['market'] for market in list_markets])
```

{% endtab %}

{% tab title="V1" %}

```python
list_exchanges = client.catalog_exchanges(exchanges="coinbase")[0]['markets']
```

{% endtab %}
{% endtabs %}

### How do I get the markets for which an asset is a base/quote?

**V1:** For getting markets where the asset is only one of a base or quote, use `catalog/markets?base=<ASSET>` or `catalog/markets?quote=<ASSET>` respectively. For getting markets where the asset is either a base or quote, use `catalog/markets?asset=<ASSET>`.

**V2:** For getting markets where the asset is only one of a base or quote, use `reference-data/markets?base=<ASSET>` or `reference-data/markets?quote=<ASSET>` respectively. For getting markets where the asset is either a base or quote, use `reference-data/markets?asset=<ASSET>`.

{% tabs %}
{% tab title="V2" %}

```python
list_markets = client.reference_data_markets(base="<ASSET>").to_list()
```

{% endtab %}

{% tab title="V1" %}

```python
list_markets = client.catalog_markets(base='btc')
```

{% endtab %}
{% endtabs %}

### How do I get which metrics are covered for a given asset/pair/exchange/market/exchange-asset/institution?

**V1:** Use`catalog/*-metrics` respectively and pass asset, pair, exchange, or market where applicable. Then, loop through each element to search for the presence of that asset, pair, exchange, or market.

**V2:** Use`catalog-v2/*-metrics` respectively and pass asset, pair, exchange, or market where applicable.

Suppose you wanted to know which `asset-metrics` are available for `btc`:

{% tabs %}
{% tab title="V2" %}

```python
list_asset_metrics = client.catalog_asset_metrics_v2(assets='btc').to_list()[0]['metrics']
```

{% endtab %}

{% tab title="V1" %}

```python
list_asset_metrics = client.catalog_asset_metrics(assets='btc').to_list()
list_asset_metrics = [metric for metric in list_asset_metrics if 'btc' in metric['frequencies'][0]['assets']]
```

{% endtab %}
{% endtabs %}

### How do I get which assets/pairs/exchanges/markets are covered for a given metric?

**V1**: Use `catalog/*-metrics` and pass your metric(s). Each element will have a frequencies value with a nested `assets` value for each frequency. Find the appropriate frequency and grab that list of assets.

**V2**: Use `catalog-v2/*-metrics` and pass your metric(s). Loop through element and get the `asset` value.

Suppose you wanted to know what assets are covered by `PriceUSD`:

{% tabs %}
{% tab title="V2" %}

```python
list_asset_metrics = client.catalog_asset_metrics_v2(metrics="PriceUSD").to_dataframe()
list_assets = list(df_asset_metrics.loc[((df_asset_metrics.metric=='PriceUSD') & (df_asset_metrics.frequency=='1d')), 'asset'])
```

{% endtab %}

{% tab title="V1" %}

```python
list_asset_metrics = client.catalog_asset_metrics(metrics="PriceUSD").to_list()
list_assets = list_asset_metrics[0]['frequencies'][-1]['assets']
```

{% endtab %}
{% endtabs %}

### How do I get which raw observation data are covered for a given market?

**V1 and V2:** Use `catalog/market-*` and `catalog-v2/market-*` respectively and pass markets where applicable.

Below is an example of using market-trades:

{% tabs %}
{% tab title="V2" %}

```python
list_markets = client.catalog_market_trades_v2(markets='<MARKET>').to_list()
```

{% endtab %}

{% tab title="V1" %}

```python
list_markets = client.catalog_market_trades(markets='<MARKET>')
```

{% endtab %}
{% endtabs %}

### **How do I get min and max time for a market?**

**V1 and V2:** Use `catalog/market-trades?asset=<ASSET>&exchange=<EXCHANGE>` and `catalog-v2/market-trades?asset=<ASSET>&exchange=<EXCHANGE>` respectively and get the `min` and `max` times.

{% tabs %}
{% tab title="V2" %}

```python
trades = next(client.catalog_market_trades_v2(markets='coinbase-btc-usd-spot'))
min_time = trades['min_time']
max_time = trades['max_time']
```

{% endtab %}

{% tab title="V1" %}

```python
trades = client.catalog_market_trades(markets='coinbase-btc-usd-spot')
min_time = trades[0]['min_time']
max_time = trades[0]['max_time']
```

{% endtab %}
{% endtabs %}

### **How do I get which the min and max times an asset has been traded in an exchange?**

**V1 and V2:** Use `catalog/market-trades?asset=<ASSET>&exchange=<EXCHANGE>` and `catalog-v2/market-trades?asset=<ASSET>&exchange=<EXCHANGE>` respectively and get the `min` and `max` times.

{% tabs %}
{% tab title="V2" %}

```python
trades = client.catalog_market_trades_v2(exchange='coinbase', asset='btc').to_list()
min_time = min([market['min_time'] for market in trades])
max_time = max([market['max_time'] for market in trades])
```

{% endtab %}

{% tab title="V1" %}

```python
trades = client.catalog_market_trades(exchange='coinbase', asset='btc')
min_time = trades[0]['min_time']
max_time = trades[0]['max_time']
```

{% endtab %}
{% endtabs %}

### How do I get what metrics are available for a given product and frequency?

Suppose we wanted to get metrics for the Network Data product that are available at 1 hour frequency.

**V1:**

* Use catalog/asset-metrics, filter by frequency = '1h' and 'product' = 'Network Data'

**V2:**

* query `reference-data/asset-metrics`, filter for 'product' = 'Network Data'
* query `catalog-v2/asset-metrics?metrics=<LIST_OF_NETWORK_DATA_METRICS>`, filter for frequency = '1h'

{% tabs %}
{% tab title="V2" %}

```python
asset_metrics_reference = client.reference_data_asset_metrics().to_dataframe()
list_metrics_nd = list(asset_metrics_reference.loc[asset_metrics_reference['product']=='Network Data', 'metric'])

asset_metrics_catalog = client.catalog_asset_metrics_v2(metrics=list_metrics_nd).to_dataframe()
list_hourly_metrics_nd = list(asset_metrics_catalog.loc[asset_metrics_catalog.frequency=='1h', 'metric'].unique())
```

{% endtab %}

{% tab title="V1" %}

<pre class="language-python"><code class="lang-python"><strong>df_catalog_asset_metrics = client.catalog_asset_metrics().to_dataframe()
</strong>list_hourly_metrics_nd = list(df_catalog_asset_metrics.loc[
    (df_catalog_asset_metrics['frequency']=='1h') &#x26; (df_catalog_asset_metrics['product']=='Network Data')
])
</code></pre>

{% endtab %}
{% endtabs %}

## A Mapping of Catalog Endpoints to Catalog V2 and Reference Data Endpoints

| Existing Catalog Endpoint          | Catalog v2 Endpoints                                                                                                                                                                     | Reference Data Endpoints\*                                                                                                                                                                                 | Notes                                                                |
| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| /catalog/assets                    | /catalog-v2/asset-metrics                                                                                                                                                                | /reference-data/assets, /reference-data/markets                                                                                                                                                            |                                                                      |
| /catalog/metrics                   | /catalog-v2/asset-metrics, /catalog-v2/exchange-metrics, /catalog-v2/exchange-asset-metrics, /catalog-v2/pair-metrics, /catalog-v2/institution-metrics, /catalog-v2/market-metrics       | /reference-data/asset-metrics, /reference-data/exchange-metrics, /reference-data/exchange-asset-metrics, /reference-data/pair-metrics, /reference-data/institution-metrics, /reference-data/market-metrics |                                                                      |
| /catalog/asset-metrics             | /catalog-v2/asset-metrics                                                                                                                                                                | /reference-data/asset-metrics                                                                                                                                                                              |                                                                      |
| /catalog/exchange-metrics          | /catalog-v2/exchange-metrics                                                                                                                                                             | /reference-data/exchange-metrics                                                                                                                                                                           |                                                                      |
| /catalog/exchange-asset-metrics    | /catalog-v2/exchange-asset-metrics                                                                                                                                                       | /reference-data/exchange-asset-metrics                                                                                                                                                                     |                                                                      |
| /catalog/pair-metrics              | /catalog-v2/pair-metrics                                                                                                                                                                 | /reference-data/pair-metrics                                                                                                                                                                               |                                                                      |
| /catalog/institution-metrics       | /catalog-v2/institution-metrics                                                                                                                                                          | /reference-data/institution-metrics                                                                                                                                                                        |                                                                      |
| /catalog/exchanges                 |                                                                                                                                                                                          | /reference-data/exchanges, /reference-data/markets                                                                                                                                                         |                                                                      |
| /catalog/exchange-assets           | /catalog-v2/exchange-asset-metrics                                                                                                                                                       | /reference-data/exchange-asset-metrics                                                                                                                                                                     |                                                                      |
| /catalog/pairs                     | /catalog-v2/pair-metrics                                                                                                                                                                 | /reference-data/pair-metrics                                                                                                                                                                               |                                                                      |
| /catalog/pair-candles              | /catalog-v2/pair-candles                                                                                                                                                                 |                                                                                                                                                                                                            |                                                                      |
| /catalog/institutions              | /catalog-v2/institution-metrics                                                                                                                                                          | /reference-data/institution-metrics                                                                                                                                                                        |                                                                      |
| /catalog/markets                   | /catalog-v2/market-trades, /catalog-v2/market-orderbooks, /catalog-v2/market-quotes, /catalog-v2/market-funding-rates, /catalog-v2/market-open-interest, /catalog-v2/market-liquidations | /reference-data/markets                                                                                                                                                                                    | The existing catalog endpoint will be restricted to 170,000 markets. |
| /catalog/market-trades             | /catalog-v2/market-trades                                                                                                                                                                |                                                                                                                                                                                                            | The existing catalog endpoint will be restricted to 170,000 markets. |
| /catalog/market-candles            | /catalog-v2/market-candles                                                                                                                                                               |                                                                                                                                                                                                            | The existing catalog endpoint will be restricted to 170,000 markets. |
| /catalog/market-orderbooks         | /catalog-v2/market-orderbooks                                                                                                                                                            |                                                                                                                                                                                                            | The existing catalog endpoint will be restricted to 170,000 markets. |
| /catalog/market-quotes             | /catalog-v2/market-quotes                                                                                                                                                                |                                                                                                                                                                                                            | The existing catalog endpoint will be restricted to 170,000 markets. |
| /catalog/market-funding-rates      | /catalog-v2/market-funding-rates                                                                                                                                                         |                                                                                                                                                                                                            | The existing catalog endpoint will be restricted to 170,000 markets. |
| /catalog/market-contract-prices    | /catalog-v2/market-contract-prices                                                                                                                                                       |                                                                                                                                                                                                            | The existing catalog endpoint will be restricted to 170,000 markets. |
| /catalog/market-implied-volatility | /catalog-v2/market-implied-volatility                                                                                                                                                    |                                                                                                                                                                                                            | The existing catalog endpoint will be restricted to 170,000 markets. |
| /catalog/market-greeks             | /catalog-v2/market-greeks                                                                                                                                                                |                                                                                                                                                                                                            | The existing catalog endpoint will be restricted to 170,000 markets. |
| /catalog/market-openinterest       | /catalog-v2/market-openinterest                                                                                                                                                          |                                                                                                                                                                                                            | The existing catalog endpoint will be restricted to 170,000 markets. |
| /catalog/market-liquidations       | /catalog-v2/market-liquidations                                                                                                                                                          |                                                                                                                                                                                                            | The existing catalog endpoint will be restricted to 170,000 markets. |
| /catalog/market-metrics            | /catalog-v2/market-metrics                                                                                                                                                               | /reference-data/market-metrics                                                                                                                                                                             | The existing catalog endpoint will be restricted to 170,000 markets. |
| /catalog/indexes                   | /catalog-v2/index-levels, /catalog-v2/index-constituents                                                                                                                                 | /reference-data/indexes                                                                                                                                                                                    |                                                                      |
| /catalog/index-candles             | /catalog-v2/index-candles                                                                                                                                                                |                                                                                                                                                                                                            |                                                                      |
| /catalog/asset-alerts              |                                                                                                                                                                                          | /reference-data/asset-alerts                                                                                                                                                                               |                                                                      |
| /catalog/asset-chains              | /catalog-v2/asset-chains                                                                                                                                                                 |                                                                                                                                                                                                            |                                                                      |
| /catalog/mempool-feerates          | /catalog-v2/mempool-feerates                                                                                                                                                             |                                                                                                                                                                                                            |                                                                      |
| /catalog/minig-pool-tips-summary   | /catalog-v2/mining-pool-tips-summary                                                                                                                                                     |                                                                                                                                                                                                            |                                                                      |
| /catalog/transaction-tracker       | /catalog-v2/transaction-tracker                                                                                                                                                          |                                                                                                                                                                                                            |                                                                      |

*\*Note that reference-data endpoints will show all data covered for a given entity, not just those visible in catalog-v2. This contrasts that of the behavior of catalog-v2 showing just the data available with your API key and catalog-v2-all showing all data.*


# How To Use the Coin Metrics API Efficiently

## HTTP API

Please follow these rules to use API most efficiently and get the best API performance.

The rules are sorted in the priority order. The first ones make the biggest impact.

* Ensure that your HTTP client sends the proper request headers to enable HTTP compression. Your HTTP request should have an "Accept-Encoding: gzip" header.
* Use the line-delimited JSON format (`format=json_stream`) instead of the default `format=json`. It is supported across the timeseries, reference-data, and catalog-v2 endpoints. That format allows you to avoid paging so you can quickly request all data using only one HTTP request without facing page\_size limitations (10k elements per page) and related difficulties. The response is returned as `application/x-ndjson`, which is one JSON object per line rather than a single JSON document, so parse it a line at a time instead of passing the whole body to a JSON parser.
* If you have to use the format=json (default value), strive to use the `paging_from=start` query parameter instead of `paging_from=end` (default value). It always produces faster responses.
* Instead of sending individual requests for different entities, combine them in a single request using commas. For example, `assets=btc,eth&metrics=ReferenceRateUSD,ReferenceRateEUR`. However, avoid combining two lists, e.g. a list of assets and a list of metrics.
* Strive to use limit\_per\_\<entity> query parameters if you want to fetch recent metric values for multiple entities (for example, assets, markets, indexes) at the same time. For example, if you want to request recent reference rates for a set of assets, use the following request: `https://api.coinmetrics.io/v4/timeseries/asset-metrics?assets=btc,eth&frequency=1m&metrics=ReferenceRateUSD&limit_per_asset=1&page_size=2&api_key=<key>`. Note that `page_size` must be greater or equal to the number of requested entities (assets) multiplied by `limit_per_<entity>` value.
* Specify `start_time` and `end_time` query parameters instead of relying on their default values to narrow your results and improve API performance.
* Avoid the `sort=time` query parameter since it provides worse performance than default sorting.
* Avoid setting the granularity query parameter to any value other than "raw" (default). That parameter enables API-level downsampling of the raw data which is slow by design and, in some cases, can lead to a 524 timeout from Cloudflare.
* Avoid the `pretty=true` query parameter in production code because it's always slower than `pretty=false` (default value).

## Python API Client

The Python API Client can be optimized in many ways to speed up your queries.

### Page Size

Queries can be made much faster by increasing the `page_size` parameter. The higher the page\_size, the faster the query, with a maximum of `page_size=10000`. The default is 100, so a request that does not set `page_size` and does not follow `next_page_url` returns only the first 100 records of the result set.

### Data Formats

When a user calls the API using a `CoinMetricsClient`object, it returns a DataCollection. A DataCollection is an object that stores information about your client request.

<pre class="language-python"><code class="lang-python"><strong>from coinmetrics.api_client import CoinMetricsClient
</strong>
client = CoinMetricsClient()
data_collection = client.get_asset_metrics(assets='btc', metrics='PriceUSD', limit_per_asset=5)
</code></pre>

Responses can be returned in the following formats, in order of how fast they're returned:

* A Python Generator (`DataCollection`)
* A CSV/JSON file (`DataCollection.export_to_csv()`, `DataCollection.export_to_json()`)
* A list (`DataCollection.to_list()`)
* A dataframe (`DataCollection.to_dataframe()`)

### Parallelization

API requests can be parallelized by calling `.parallel()` on a `DataCollection` object. Requests can be partitioned in the following ways:

**By Column**

```python
# Parallelize on 'assets' column
data = client.get_asset_metrics(
    assets=['btc', 'eth'],
    metrics=['PriceUSD', 'FeeMeanNtv'],
    limit_per_asset=5
).parallel('assets').to_list()

# Parallelize on 'assets' and 'metrics' columns
data = client.get_asset_metrics(
    assets=['btc', 'eth'],
    metrics=['PriceUSD', 'FeeMeanNtv'],
    limit_per_asset=5
).parallel(['assets', 'metrics']).to_list()
```

**By Time or (Block) Height Increment**

```python
# Parallelize by time increment

from datetime import timedelta
from dateutil.relativedelta import relativedelta

# Parallelize request in 1 month chunks
data = client.get_asset_metrics(
    assets=['btc', 'eth'],
    metrics=['ReferenceRateUSD'],
    start_time='2024-01-01',
    end_time='2024-08-01',
    frequency='1h'
).parallel(time_increment=relativedelta(months=1)).to_list()

# Parallelize request in 1 day chunks
data = client.get_asset_metrics(
    assets=['btc', 'eth'],
    metrics=['ReferenceRateUSD'],
    start_time='2024-01-01',
    end_time='2024-08-01',
    frequency='1h'
).parallel(time_increment=timedelta(days=1))

# Parallelize by 1000 blocks
data = client.get_asset_metrics(
    assets=['btc', 'eth'],
    metrics=['FeeMeanNtv'],
    start_height=0,
    end_height=100_000,
    frequency='1b'
).parallel(height_increment=1000)
```

Note, it is **much faster** to get data the available entities by **first** using the catalog-v2 or reference-data endpoints and then passing that list to the client method as a parallelized call over using a wildcard. This method also bypasses the 414 error code [How to Troubleshoot Common Errors](/tutorials-and-examples/user-guides/how-to-troubleshoot-common-errors#id-414-uri-too-long).

```python
assets = [
    asset['asset'] 
    for asset in client.catalog_asset_metrics_v2(
    metrics="ReferenceRateUSD")
]
df_assets = client.get_asset_metrics(
    assets=assets,
    metrics=['ReferenceRateUSD'],
    limit_per_asset=1
).parallel().to_dataframe()

markets = [
    market['market']
    for market in client.reference_data_markets(
        base='btc', quote='usd', type='spot'
    )
]
df_markets = client.get_market_trades(
    markets=markets,
    limit_per_market=1
).parallel().to_dataframe()
```

### Wildcards

Wildcards (`*`) allow you to query several entities, such as assets, exchanges, and markets, as one parameter. For example:

```python
# Get prices for all assets
asset_metrics = client.get_asset_metrics(assets='*', metrics='PriceUSD', limit_per_asset=1)

# Get btc-usd candles for all exchanges
market_candles_btc_usd = client.get_market_candles(markets=['*-btc-usd-spot'], limit_per_market=10)

# Get all spot exchanges and pairs
exchanges_reference = client.reference_data_exchanges().to_list()

market_candles_spot = client.get_market_candles(markets=[f'{exchange}-*-spot' for exchange['exchange'] in exchanges_reference], limit_per_market=10)
```

Parallelization does **not** work for a wildcarded variable. `.parallel()` requires the parallelized variable to be **explicitly stated** in order to be chunked into parallel calls. If you need to get a set of all valid entities, you must use the reference\_data or catalog methods.

#### Persisting Large Data Requests

Given that parallelization allows you to request large amounts of data, the methods for non-parallelized data may run slower. The `export_to_json_files()` and `export_to_csv_files()` allow you to save parallelized data in an organized way in your local directory.

```python
### save data in local directory

data = client.get_asset_metrics(
    assets=['btc', 'eth'],
    metrics=['FeeMeanNtv'],
    start_height=0,
    end_height=100_000,
    frequency='1b'
).parallel(height_increment=1000).export_to_json_files()
```

For more information, see the guide for How to Export Data using the Python API Client:[How To Export Data](/tutorials-and-examples/user-guides/exporting-data#python-api-client) .


# How to Troubleshoot Common Errors

### Debugging the Python API Client

There are two additional options for the API Client - `debug_mode` and `verbose`. These two options log network calls to the console, and in the case of `debug_mode` it will generate a log file of all the network requests and the time it takes to call them. These tools can be used to diagnose issues in your code and also to get a better understanding of request times so that users can write more performant code. For example, running the below code:

```python
import os

from coinmetrics.api_client import CoinMetricsClient

api_key = os.environ['CM_API_KEY']

if __name__ == '__main__':
    client = CoinMetricsClient(api_key=api_key, debug_mode=True)
    reference_rates_example = client.get_asset_metrics(assets=['btc', 'algo', 'eth'], metrics=['ReferenceRateUSD'])
    for data in reference_rates_example:
        continue
```

The console output will look like:

```commandline
[DEBUG] 2023-01-09 11:01:02,044 - Starting API Client debugging session. logging to stdout and cm_api_client_debug_2023_01_09_11_01_02.txt
[DEBUG] 2023-01-09 11:01:02,044 - Using coinmetrics version 2022.11.14.16
[DEBUG] 2023-01-09 11:01:02,044 - Current state of API Client, excluding API KEY: {'_verify_ssl_certs': True, '_api_base_url': 'https://api.coinmetrics.io/v4', '_ws_api_base_url': 'wss://api.coinmetrics.io/v4', '_http_header': {'Api-Client-Version': '2022.11.14.16'}, '_proxies': {'http': None, 'https': None}, 'debug_mode': True, 'verbose': False}
[DEBUG] 2023-01-09 11:01:02,044 - Attempting to call url: timeseries/asset-metrics with params: {'assets': ['btc', 'algo', 'eth'], 'metrics': ['ReferenceRateUSD'], 'frequency': None, 'page_size': None, 'paging_from': 'start', 'start_time': None, 'end_time': None, 'start_height': None, 'end_height': None, 'start_inclusive': None, 'end_inclusive': None, 'timezone': None, 'sort': None, 'limit_per_asset': None}
[DEBUG] 2023-01-09 11:01:02,387 - Response status code: 200 for url: https://api.coinmetrics.io/v4/timeseries/asset-metrics?api_key=[REDACTED]&assets=btc%2Calgo%2Ceth&metrics=ReferenceRateUSD&paging_from=start took: 0:00:00.342874 response body size (bytes): 9832
[DEBUG] 2023-01-09 11:01:02,388 - Attempting to call url: timeseries/asset-metrics with params: {'assets': ['btc', 'algo', 'eth'], 'metrics': ['ReferenceRateUSD'], 'frequency': None, 'page_size': None, 'paging_from': 'start', 'start_time': None, 'end_time': None, 'start_height': None, 'end_height': None, 'start_inclusive': None, 'end_inclusive': None, 'timezone': None, 'sort': None, 'limit_per_asset': None, 'next_page_token': '0.MjAxOS0wOS0zMFQwMDowMDowMFo'}
[DEBUG] 2023-01-09 11:01:02,559 - Response status code: 200 for url: https://api.coinmetrics.io/v4/timeseries/asset-metrics?api_key=[REDACTED]&assets=btc%2Calgo%2Ceth&metrics=ReferenceRateUSD&paging_from=start&next_page_token=0.MjAxOS0wOS0zMFQwMDowMDowMFo took: 0:00:00.171487 response body size (bytes): 9857
```

Then it can be easier to understand what network calls the API Client is making, and where any issues may exist. If you wish to dig even deeper, you may consider modifying the `_send_request()` method of the API Client to log additional data about the state of your environment, or anything else that would help diagnose issues. You will notice a log file generated in the format `cm_api_client_debug_2023_01_09_11_01_02.txt`. This log file might be helpful for your own use or to give more context if you are working with Coin Metrics customer success.

### Proxy Error

Sometimes your organization has special rules on making requests to third parties and you have to use proxies in order to comply with the rules.

For proxies that don't require auth you can specify them similar to this example:

```python

client = CoinMetricsClient(proxy_url=f'http://<hostname>:<port>')
```

For proxies that require auth, you should be able to specify username and password similar to this example:

```python

client = CoinMetricsClient(proxy_url=f'http://<username>:<password>@<hostname>:<port>')
```

### SSLError: SSL Certs Verification

Sometimes your organization network have special rules on SSL certs verification and in this case you might face the following error when running the script:

```
SSLError: HTTPSConnectionPool(host='api.coinmetrics.io', port=443): Max retries exceeded with url: <some_url_path> (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1123)')))
```

In this case, you can pass an option during client initialization to disable ssl verification for requests like this:

```python

client = CoinMetricsClient(verify_ssl_certs=False)
```

We don't recommend setting it to False by default and you should make sure you understand the security risks of disabling SSL certs verification.

Additionally, you may choose to specify the path to the SSL certificates on your machine. This may cause errors where Python is unable to locate the certificates on your machine, particularly when using Python virtual environments.

```python
from coinmetrics.api_client import CoinMetricsClient
SSL_CERT_LOCATION = '/Users/<USER_NAME>/Library/Python/3.8/lib/python/site-packages/certifi/cacert.pem'
client = CoinMetricsClient(verify_ssl_certs=SSL_CERT_LOCATION)
```

A quick way to find the certs on your machine is:\
`python3 -c "import requests; print(requests.certs.where())"`\
And note that this will change based on whether or not you are using a [Python virtual environment or not](https://realpython.com/python-virtual-environments-a-primer/)

```python
from coinmetrics.api_client import CoinMetricsClient
import requests

SSL_CERT_LOCATION = requests.certs.where()
print(f"SSL Certs Location: {SSL_CERT_LOCATION}")

client = CoinMetricsClient(verify_ssl_certs=SSL_CERT_LOCATION)
```

### 400 Bad Parameter

This error occurs when an invalid parameter value is passed, e.g. `client.get_asset_metrics(assets='bad_asset_name')` yields `"Bad parameter 'assets'. Value 'bad_asset_name' is not supported."`. There are two ways to fix this:

1. If the endpoint supports the `ignore_unsupported_errors` parameter, set this value to True.
2. Else, you will need to use the `reference_data` and `catalog_v2` methods to properly construct a query with the valid parameter values. See [this tutorial](https://docs.coinmetrics.io/tutorials-and-examples/tutorials/walkthrough_community#market-observations) for an example.

### 401 Unauthorized

This error occurs when your credentials are invalid. You may be using an invalid API key. Check the [Getting Started](https://docs.coinmetrics.io/getting-started#id-1.-set-up-your-api-key) guide for instructions on how to get set up with the proper credentials.

### 403 Forbidden

This error occurs when your credentials are valid but you may not be authorized to access the data, e.g.

`{"error": {"type": "forbidden","message": "Requested metric 'SplyBMXNtv' with frequency '1d' for asset 'btc' is not available with supplied credentials."}}`

Reach out to <https://coinmetrics.io/contact/> to expand your existing credentials. Check that your key has proper access to the data by going to [coverage.coinmetrics.io](https://coverage.coinmetrics.io/).

To fix bypass this error with your current credentials, there are two options:

1. If the endpoint supports the `ignore_forbidden_errors` parameter, set this value to True.
2. Else, you will need to use the `reference_data` and `catalog_v2` methods to properly construct a query with the valid parameter values. See [this tutorial](https://docs.coinmetrics.io/tutorials-and-examples/tutorials/walkthrough_community#market-observations) for an example.

### 414 URI Too Long

This error occurs when the HTTP URI being passed using the Python API Client is too long. This is a common consequence of passing too many parameters in a given endpoints, e.g. `client.get_asset_metrics(assets=<long_list_of_assets>, ...)` or `client.get_list_of_balance_updates_v2(asset='btc', accounts=<long_list_of_accounts>)`.

Use the `.parallel()` method to bypass this issue, e.g.: `client.get_asset_metrics(assets=<long_list_of_assets>).parallel()`. Parallelization breaks up the HTTP requests into chunks by the variable it is being parallelized on, resulting in URI(s) well under the limit.

Note this workaround works only for endpoints which allow parallelization. See the attribute [`ParallelDataCollection._VALID_PARALLEIZATION_PARAMS`](https://github.com/coinmetrics/api-client-python/blob/027b464ffe4037eb730569ee4c33940c29b117ce/coinmetrics/_data_collection.py#L542-L546) for the list of parallelizable variables and [`ParallelDataCollection._ENDPOINT_FIRST_PARAM_DICT`](https://github.com/coinmetrics/api-client-python/blob/027b464ffe4037eb730569ee4c33940c29b117ce/coinmetrics/_data_collection.py#L547-L619) for the dict of endpoints and default set of parallelizable variables.

### 429 Too Many Requests

This error occurs when the rate limits are exceeded. See the [API Rate limits](https://docs.coinmetrics.io/api/v4/#tag/Rate-limits) for more information.

In version `2025.9.17.17`, retry logic was refactored to ensure that these errors are better handled by the API Client. If you are seeing this error often, we highly recommend upgrading to `2025.9.17.17` or later.


# How To Use Websockets

### How to use Websockets with the Python API Client

Below is a template for using the timeseries-stream endpoints using the Python API Client. The Python API Client websocket functionality is built on top of the [websocket](https://websockets.readthedocs.io/en/stable/) library.

```python
import sys
import websocket
from os import environ

import orjson

from coinmetrics.api_client import CoinMetricsClient, CmStream

api_key = (
        environ.get("CM_API_KEY") or sys.argv[1]
)  # sys.argv[1] is executed only if CM_API_KEY is not found

client = CoinMetricsClient(api_key)

# Replace this with any timeseries-stream methods
stream = client.get_stream_market_orderbooks(
    markets=['binance-btc-usdt-spot']
)

def on_message(
        stream: websocket.WebSocketApp, message: str
) -> None:
    """
    Custom message callable to be passed in the streaming object
    :param stream: CmStream, WebSocketApp connection
    :param message: str, The message relayed by the API
    :return: None
    """
    data = orjson.loads(message)
    print(data)
    sequence_id = int(data['cm_sequence_id'])
    
    # Optional: Close stream when a condition is met. For example, after receiving 10 messages.
    max_cm_sequence_id = 10
    if sequence_id >= max_cm_sequence_id:
        print(f"Closing the connection after {max_cm_sequence_id} messages...")
        stream.close()

# blocks until connection is closed or interrupted
if __name__ == '__main__':
    stream.run(on_message=on_message)
```


# Dashboards

## Overview

This page showcases examples of what you can do using CM data visualization tools. For more information on how to use the charting tool, see our [Data Visualization](/data-visualization) guide.

<table><thead><tr><th width="215">Dashboard</th><th width="244">Summary</th><th>Personas</th><th>Use-Case</th></tr></thead><tbody><tr><td><a href="https://charts.coinmetrics.io/dashboard?id=10833">Bitcoin ETFs</a></td><td>Tracks on-chain holdings, flows and deposit/withdrawal activity across U.S. listed spot Bitcoin ETFs</td><td>Researcher, Fund Administrator, Operations/Risk Analyst</td><td>Research, Asset Management, Risk Management</td></tr><tr><td><a href="https://charts.coinmetrics.io/dashboard/stablecoins-overview">Stablecoins Overview</a>*</td><td>The Stablecoin Sector Overview dashboard explores fundamental stablecoin metrics across the sector, with a focus on top assets like USDC &#x26; USDT.</td><td>Researcher, Operations/ Risk Analyst</td><td>Research, Risk Management</td></tr><tr><td><a href="https://charts.coinmetrics.io/dashboard/tokenized-rwa">Tokenized RWAs Dashboard</a>*</td><td>Tracks on-chain supply, market capitalization, holder activity, and transaction volume across covered tokenized treasuries, equities, and commodities.</td><td>Researcher, Operations/Risk Analyst, Fund Admin</td><td>Research, Asset Management, Risk Management</td></tr><tr><td><a href="https://charts.coinmetrics.io/dashboard/usdt-overview">Tether (USDT) Overview</a>*</td><td>Deep dive into USDT metrics across chains, including market share, supply, transfer volume, adoption and exchange trading volumes.</td><td>Researcher, Operations/ Risk Analyst</td><td>Research, Risk Management</td></tr><tr><td><a href="https://charts.coinmetrics.io/dashboard/usdc-overview">Circle (USDC) Overview</a>*</td><td>Deep dive into USDC metrics across chains, including market share, supply, transfer volume, adoption and exchange trading volumes.</td><td>Researcher, Operations/ Risk Analyst</td><td>Research, Risk Management</td></tr><tr><td><a href="https://charts.coinmetrics.io/dashboard/?id=8591">Layer-1 Overview</a></td><td>The Layer-1 dashboard showcases various fundamental metrics for comparing base-layer blockchains, as detailed in State of the Network 256.</td><td>Researcher, Operations/Risk Analyst, Fund Administrator</td><td>Research, Asset Management, Risk Management</td></tr><tr><td><a href="https://charts.coinmetrics.io/dashboard/btc-on-chain-indicators">On-Chain Indicators</a></td><td>The On-Chain Indicators dashboard provides a look at several fundamental on-chain metrics, as well as “valuation” indicators derived from these metrics, from MVRV to NVT.</td><td>Quant Trader, Researcher</td><td>Trading, Research</td></tr><tr><td><a href="https://charts.coinmetrics.io/dashboard?id=10574">Market Data</a></td><td>The Market Data dashboard showcases a variety of aggregated market data metrics, with a focus on BTC. Relevant charts include exchange volume share, realized volatility, perp vs. non-perp open interest, and more.</td><td>Researcher, Trading</td><td>Trading, Research</td></tr><tr><td><a href="https://charts.coinmetrics.io/dashboard?id=10736">Bitcoin Mining</a></td><td>The Bitcoin Mining dashboard highlights fundamental on-chain data types like hashrate, block time, and difficulty, in addition to entity-based metrics like miner supply and miner-exchange flows.</td><td>Researcher, Operations/Risk Analyst</td><td>Research, Risk Management</td></tr><tr><td><a href="https://charts.coinmetrics.io/dashboard?id=10531">Solana Metrics</a></td><td>The Solana Metrics dashboard introduces Coin Metrics’ cutting-edge suite of SOL metrics, from Layer-1 health monitoring to Solana stablecoin fundamentals.</td><td>Researcher, Operations/Risk Analyst, Fund Administrator</td><td>Research, Asset Management, Risk Management</td></tr><tr><td><a href="https://charts.coinmetrics.io/dashboard?id=10738">Solana Staking</a></td><td>Charts related to Validator and Delegator staking</td><td>Researcher, Fund Admin</td><td>Research, Asset Management</td></tr><tr><td><a href="https://charts.coinmetrics.io/dashboard/?id=8210">Bitcoin Decentralization</a></td><td>The Bitcoin Decentralization dashboard highlights metrics used to measure centralizing aspects of the ecosystem, from total blockchain storage size to wealth distribution metrics.</td><td>Researcher, Fund Admin</td><td>Research, Asset Management</td></tr><tr><td><a href="https://charts.coinmetrics.io/dashboard/?id=7375">ETH On-Chain Activity</a></td><td>The ETH On-Chain Activity dashboard presents a comprehensive overview of Network Data metrics available for Ethereum, with smart contract metrics, staking data, transfer value, and many other categories covered.</td><td>Researcher</td><td>Research</td></tr><tr><td><a href="https://charts.coinmetrics.io/dashboard?id=10133">Ethereum Layer-2s &#x26; Blobs</a></td><td>Tracks the adoption &#x26; economics of Ethereum Layer-2 scaling solutions and blob metrics (EIP-4844)</td><td>Researcher/Risk Analyst</td><td>Research, Risk Management</td></tr><tr><td><a href="https://charts.coinmetrics.io/dashboard?id=10567">DeFi Tokens</a></td><td>The DeFi Tokens dashboard highlights on-chain metrics for comparing health and performance of various DeFi governance tokens, drawing inspiration from SOTN 189.</td><td>Researcher, Fund Admin</td><td>Research, Asset Management</td></tr><tr><td><a href="https://charts.coinmetrics.io/dashboard?id=10777">Avalanche</a></td><td>The Avalanche (AVAX) dashboard highlights Coin Metrics’ new coverage of on-chain data for the Avalanche ecosystem, presenting various metrics across the 3 constituent blockchains: X-Chain, P-Chain, and C-Chain.</td><td>Researcher, Fund Admin</td><td>Research, Risk Management</td></tr><tr><td><a href="https://charts.coinmetrics.io/dashboard/?id=9250">Solana - SPL Token Dashboard</a></td><td>The Solana - SPL dasboard showcases a variety of metrics for SPL tokens, Solana's token standard, highlighting areas such as ROI, active users and velocity</td><td>Researcher, Fund Admin</td><td>Research, Asset Management</td></tr><tr><td><a href="https://charts.coinmetrics.io/dashboard?id=10747">Stablecoins: BUSD Deep Dive</a></td><td>The Stablecoin BUSD Deep Dive dashboard displays some of our most useful stablecoin metrics, with a focus on the recent collapse of Binance USD (BUSD) as a case study.</td><td>Researcher, Operations/Risk Analyst</td><td>Research, Risk Management</td></tr></tbody></table>

## Layer-1 Overview\*

The Layer-1 dashboard showcases various fundamental metrics for comparing base-layer blockchains, as detailed in State of the Network 256.

<figure><img src="/files/jkxO3uxpMrXQEkedR3ZW" alt=""><figcaption></figcaption></figure>

{% embed url="<https://charts.coinmetrics.io/dashboard/?id=8591>" %}

**Personas**

Researcher, Operations/Risk Analyst, Fund Administrator

**Use-Case**

Research, Asset Management, Risk Management

## Solana Metrics\*

The Solana Metrics dashboard introduces Coin Metrics’ cutting-edge suite of SOL metrics, from Layer-1 health monitoring to Solana stablecoin fundamentals.

<figure><img src="/files/tt0cyFLrgXpzISqA7B0O" alt=""><figcaption></figcaption></figure>

{% embed url="<https://charts.coinmetrics.io/dashboard?id=10531>" %}

**Personas**

Researcher, Operations/Risk Analyst, Fund Administrator

**Use-Case**

Research, Asset Management, Risk Management

## Stablecoins Overview\*

The Stablecoin Sector Overview dashboard explores fundamental stablecoin metrics across the sector, with a focus on top assets like USDC & USDT.

<figure><img src="/files/EEznnJMTY0ParhJWE6uU" alt=""><figcaption></figcaption></figure>

{% embed url="<https://charts.coinmetrics.io/dashboard?id=10497>" %}

#### Personas

Researcher, Operations/Risk Analyst

#### Use-Case

Research, Risk Management

## On-Chain Indicators\*

The On-Chain Indicators dashboard provides a look at several fundamental on-chain metrics, as well as “valuation” indicators derived from these metrics, from MVRV to NVT.

<figure><img src="/files/jzbd6rLINdgwCDUuJPbA" alt=""><figcaption></figcaption></figure>

{% embed url="<https://charts.coinmetrics.io/dashboard/btc-on-chain-indicators>" %}

**Personas**

Quant Trader, Researcher

**Use-Case**

Trading, Research

## Bitcoin Decentralization\*

The Bitcoin Decentralization dashboard highlights metrics used to measure centralizing aspects of the ecosystem, from total blockchain storage size to wealth distribution metrics.

<figure><img src="/files/MKWtgUnltAO3t9g98Eah" alt=""><figcaption></figcaption></figure>

{% embed url="<https://charts.coinmetrics.io/dashboard/?id=8210>" %}

**Personas**

Researcher, Fund Admin

**Use-Case**

Research, Asset Management

## DeFi Tokens\*

The DeFi Tokens dashboard highlights on-chain metrics for comparing health and performance of various DeFi governance tokens, drawing inspiration from SOTN 189.

<figure><img src="/files/R0RtFncyhNtaz2e6c9Ts" alt=""><figcaption></figcaption></figure>

{% embed url="<https://charts.coinmetrics.io/dashboard?id=10567>" %}

**Personas**

Researcher, Fund Administrator

**Use-Case**

Research, Asset Management

## Stablecoins: BUSD Deep Dive\*

<figure><img src="/files/yQE9LZIigT5UaGqOROsa" alt=""><figcaption></figcaption></figure>

The Stablecoin BUSD Deep Dive dashboard displays some of our most useful stablecoin metrics, with a focus on the recent collapse of Binance USD (BUSD) as a case study.

{% embed url="<https://charts.coinmetrics.io/dashboard?id=10747>" %}

**Personas**

Researcher, Operations/Risk Analyst

**Use-Case**

Research, Risk Management

## Bitcoin Mining\*

The Bitcoin Mining dashboard highlights fundamental on-chain data types like hashrate, block time, and difficulty, in addition to entity-based metrics like miner supply and miner-exchange flows.

<figure><img src="/files/4d8I6mqnOhGPPp0dSg8b" alt=""><figcaption></figcaption></figure>

{% embed url="<https://charts.coinmetrics.io/dashboard?id=10736>" %}

**Personas**

Researcher, Operations/Risk Analyst

**Use-Case**

Research, Risk Management

## ETH On-Chain Activity\*

The ETH On-Chain Activity dashboard presents a comprehensive overview of Network Data metrics available for Ethereum, with smart contract metrics, staking data, transfer value, and many other categories covered.

<figure><img src="/files/rUL7h0VkO2sP9wrwZmha" alt=""><figcaption></figcaption></figure>

{% embed url="<https://charts.coinmetrics.io/dashboard/?id=7375>" %}

**Personas**

Researcher

**Use-Case**

Research

## Avalanche\*

The Avalanche (AVAX) dashboard highlights Coin Metrics’ new coverage of on-chain data for the Avalanche ecosystem, presenting various metrics across the 3 constituent blockchains: X-Chain, P-Chain, and C-Chain.

<figure><img src="/files/saGmXzzZVoz7tB4Zsjyk" alt=""><figcaption></figcaption></figure>

{% embed url="<https://charts.coinmetrics.io/dashboard?id=10777>" %}

**Personas**

Researcher, Fund Admin

**Use-Case**

Research, Risk Management

## Market Data

The Market Data dashboard showcases a variety of aggregated market data metrics, with a focus on BTC. Relevant charts include exchange volume share, realized volatility, perp vs. non-perp open interest, and more.

<figure><img src="/files/BYOPGgqZw05tL2gluFbD" alt=""><figcaption></figcaption></figure>

{% embed url="<https://charts.coinmetrics.io/dashboard?id=10574>" %}

**Personas**

Researcher, Trader

**Use-Case**

Trading, Research

## Solana - SPL Tokens\*

The Solana - SPL dasboard showcases a variety of metrics for SPL tokens, Solana's token standard, highlighting areas such as ROI, active users and velocity

<figure><img src="/files/qWekCpJzAWhlnV93eff5" alt=""><figcaption></figcaption></figure>

{% embed url="<https://charts.coinmetrics.io/dashboard/?id=9250>" %}
Solana - SPL Token Dashboard
{% endembed %}

**Personas**

Researcher, Fund Admin

**Use-Case**

Research, Asset Management

*\*Requires Pro CM API Key*


# Video Tutorials & Content

Coin Metrics Youtube Videos and Tutorials

The Coin Metrics Solutions Engineering Team is regularly adding new videos to supplement our Data Tutorials. To browse our entire library please check out our Youtube.

Examples: Getting Started with our Data, Accessing our Catalog, Interviews with Research Team, Video from Conferences and more

{% embed url="<http://youtube.com/@coin-metrics>" %}


# Packages


# CM Labs

[CM Labs](https://coinmetrics.io/cm-labs/) is a place for our pioneering team to experiment. Here, you'll find associate passion projects, fun prototypes, test products/features and cutting edge efforts that are experimental in nature. Many of our most popular commercial products have their roots in these innovative, community-first efforts.

While CM Labs products and features are very cool, for one reason or another, we are not quite ready to incorporate them into our mainstream product offerings.

## Identification of CM Labs Efforts

In addition to the projects and prototypes you'll find on our CM Labs [site](https://coinmetrics.io/cm-labs/), you will also notice certain metrics and assets (e.g., ICP) flagged in our tools as CM Labs.

![](/files/-Mhu_Vi0MoqZCK1wqUUG)

This flag also exists in our catalogs. Experimental assets/metrics with have `"experimental": true` in the array of objects returned for that asset/metric.

```
 }, {
    "asset" : "icp",
    "full_name" : "Internet Computer",
    "experimental" : true,
    "metrics" : [ {
      "metric" : "AdrAct30dCnt",
      "frequencies" : [ {
        "frequency" : "1d",
        "min_time" : "2021-05-06T00:00:00.000000000Z",
        "max_time" : "2021-08-23T00:00:00.000000000Z"
      } ]
```

{% hint style="warning" %}
While we obviously feel there is value in making these experimental assets/metrics available, please exercise caution given their experimental nature.
{% endhint %}

## Examples of Labs Efforts

Below are some examples of Labs efforts:

* Experimental on-chain asset coverage in NDP and Atlas (e.g., ICP, DOT, ALGO, XTZ)
* DeFi Market Data (i.e., Uniswap and Sushiswap swaps, liquidity pool metadata, candles, and volume metrics)
* Farum Risk Management offerings (e.g., Mining Pool Monitor (`/mining-pool-tips-summary`), Reorg & Fork Tracker (`/asset-chains`)
* Flat Files Delivery System


# Coin Metrics Community Data

{% hint style="info" %}
Available to the community under the [Creative Commons](https://creativecommons.org/licenses/by-nc/4.0/) license.
{% endhint %}

## Community Data Offering

**Coin Metrics Community Metrics**(Community [API](https://docs.coinmetrics.io/access-our-data/api), [Data Visualization](/data-visualization)) is a subset of our Network Data Pro and Market Data Pro data available for free for community use.

**Atlas Community** (Community [API](https://docs.coinmetrics.io/api/v4/#tag/List-of-blockchain-entities-v2), [Atlas Explorer](https://atlas.coinmetrics.io/)) is a limited history access to our Atlas data set for free use by the community. This is available for limited assets and 30 days of history.

**Reference Rates Community** (Community[ API](https://docs.coinmetrics.io/access-our-data/api),[ Data Visualization](/data-visualization)) provides access to all of our reference rates with a limited amount of history for our more granular resolutions. This is available and limited to the last 7 data points.

For more info on our Community terms and offerings see our [Labs](https://coinmetrics.io/cm-labs/) page.

## Community Access Limits

The Community HTTP API root endpoint URL is `https://api.coinmetrics.io/v4`. API key is not required when accessing community endpoints.

## Rate limits

The community version of API has the limit of 10 requests per 6 seconds sliding window for an IP address.


# Access Our Data

Coin Metrics is setting the standard for cryptocurrency data usability.

As such, we offer a variety of ways for users to access Coin Metrics' real-time and historical network, market and index data. This includes a REST/HTTP API, a WebSocket API, a Python & R API client, Cloud Delivery of bulk datasets to Amazon S3 and Snowflake, and a front-end tool for displaying data coverage ("Coverage").


# API Conventions

## **API Endpoint Structure**

The Coin Metrics API is structured as the following:

1. **Reference data** is a handbook of the entities Coin Metrics ever supported, currently supports or plans to support in the future. This includes assets, exchanges, markets, their metrics etc.
2. **Catalog** data describes the availability for time series or time series-like endpoints. For more information on the catalog migration, see [Catalog V1 to Catalog V2 Migration](/access-our-data/api/catalog-v1-v2-migration)
3. **Timeseries** data is some of the most valuable data we provide for our customers: market data (trades, order books, candles etc.), metrics (asset metrics, exchange metrics, pair metrics etc.), index levels and so on.
4. **Timeseries Stream** data is time series data served in real-time through a Websocket connection.
5. **Custom endpoints** - endpoints that do not fit to any of the aforementioned. These endpoints follow the same design principles as the Timeseries data. Examples of custom endpoints:
   1. **Blockchain** endpoints (ATLAS)
   2. **Blockchain Metadata** (Tagging)
   3. Transaction tracker API
   4. Security Master
   5. Constituents

We will explain the different endpoints in depth below.

### Reference Data

**Reference Data** is a common starting point for new users. This endpoint gives the you an idea of what data types we support (assets, exchanges, markets, metrics), the format of data (like the format of market name or asset code) and other useful information (metric description, its data type etc). As an example, here is the response of `/reference-data/exchange-metrics` endpoint:

```json
{
 "data": [
   {
     "metric": "liquidations_reported_future_buy_units_1d",
   "full_name": "Liquidations, reported, future, buys, native units, one day",
   "description": "The sum of all buy liquidations from perpetual futures markets in native units of the underlying base asset.",
     "product": "Market Data",
     "category": "Liquidations",
     "subcategory": "Futures",
     "unit": "Native Units",
     "data_type": "decimal",
     "type": "Sum",
     "display_name": "Reported Futures Buy Liquidations, native units"
   }
 ]
}
```

### Catalog

The catalog endpoints allow you to know:

* what data types are available,
* min and max time of each data type that API can provide.

We have two subtypes of catalog endpoints:

* /catalog prefixed endpoints - provide time ranges of the time series data available for your API key.
* /catalog-all prefixed endpoints - provide time ranges of the time series data for our entire data set.

Catalog endpoints list all data types and possible entities and their combinations. The deepest part of each combination is the "min\_time" and "max\_time" values representing the availability of the corresponding time series(-like) endpoint. For example, `/catalog-v2/market-metrics`:

```json
{
 "data": [
   {
     "market": "binance-1000FLOKIUSDT-future",
     "metrics": [
       {
         "metric": "liquidations_reported_future_buy_units_1d",
         "frequencies": [
           {
             "frequency": "1d",
             "min_time": "2023-05-08T00:00:00.000000000Z",
             "max_time": "2023-06-27T00:00:00.000000000Z"
           }
         ]
       }
     ]
   }
 ]
}

```

or `/catalog-v2/exchange-metrics`:

```json

{
 "data": [
   {
     "exchange": "binance",
     "metrics": [
       {
         "metric": "liquidations_reported_future_buy_units_5m",
         "frequencies": [
           {
             "frequency": "1h",
             "min_time": "2023-06-04T00:00:00.000000000Z",
             "max_time": "2023-06-27T05:40:00.000000000Z"
           },
           {
             "frequency": "1d",
             "min_time": "2023-06-04T00:00:00.000000000Z",
             "max_time": "2023-06-27T05:40:00.000000000Z"
           }
         ]
       }
    }
  ]
}

```

*Note: This query was made on 2023-06-27. max\_time is subject to change depending on when a request is made.*

Catalog endpoints abide by the following guidelines:

1. Normally, each catalog endpoint has a corresponding time series-like endpoint (for example, /catalog-v2/market-metrics and /timeseries/market-metrics).
2. Each catalog endpoint supports pagination
3. Catalog endpoints do not require any filtering query parameters; by default, all records are being returned (paginated), but filtering query parameters (especially if they match the corresponding time series endpoint’s query parameters) are welcomed.
4. Each Catalog endpoint must support json\_stream format. While it is not required for Time series endpoints (the response size may be impractically large to use with json\_stream)), it is mandatory for Catalog ones.
5. Responses of endpoints for similar data types are consistent. For example, /catalog-v2/asset-metrics, /catalog-v2/exchange-metrics provide information about metrics and their availability, so the response schemas should not differ unnecessarily.
6. Response format assumes that multiple frequencies can be added in the future.

See [Catalog V1 to Catalog V2 Migration](/access-our-data/api/catalog-v1-v2-migration) for more details on the differences between catalog v1 and v2.

### Timeseries

Timeseries endpoints return data or metrics over time. We have a set of parameters to filter time series responses.

| Parameter        | Default value        | Description                                                         | Examples          |
| ---------------- | -------------------- | ------------------------------------------------------------------- | ----------------- |
| start\_time      | \<unix\_epoch>       | Start of the time interval.                                         | 2020-01-01        |
| end\_time        | \<current\_time>     | End of the time interval.                                           | 2020-01-02        |
| start\_inclusive | true                 | Inclusive or exclusive corresponding start\_\* parameters.          | false             |
| end\_inclusive   | true                 | Inclusive or exclusive corresponding end\_\* parameters.            | false             |
| timezone         | UTC                  | Timezone name for parsing the start\_time and end\_time timestamps. | America/New\_York |
| page\_size       | varies (usually 100) | Number of items per single page of results.                         | 100, 10000        |

Also, additional query parameters, apart from the pagination ones, can be specified to reduce the amount of returned data:

| Parameter             | Default value | Description                                        | Examples            |
| --------------------- | ------------- | -------------------------------------------------- | ------------------- |
| limit\_per\_\<entity> | <p><br></p>   | How many entries per entity result should contain. | limit\_per\_asset=1 |

#### Frequency vs. Granularity

Timeseries endpoints may return data via some fixed frequency (\*-metrics) or as raw observation (market-trades, market-orderbooks).

#### Nulls and Empty Strings In Responses

\
Usually, if some response field does not have a value, we don't include this field in the response.

But we have a set of exceptions for this rule. Nulls are included in the response if null is a correct metric value. It happens when the metrics can't be mathematically calculated due to, for example, division by zero or similar things. Multiple supported metrics are requested by a user but only some of the metrics have values calculated for the requested time.

API has a special query parameter null\_as\_zero=true that converts nulls to zero in the mentioned exceptional cases.

### Timeseries Stream

WebSocket endpoints are used to stream real-time data to clients. They send individual JSON messages/objects/events as soon as API becomes aware of them. Usually, they have the same names as regular time series endpoints. For example,

`/timeseries/asset-metrics` and `/timeseries-stream/asset-metrics`

But they can support different sets of query parameters because of the different nature of the data (historical vs real-time).

#### HTTP status codes & error messages

API has a standard set of errors and error message formats that it can send to clients.

| Code | Description                                                                                                                                                                                |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| 200  | A successful response.                                                                                                                                                                     |
| 400  | Indicates that request is invalid. Includes incorrect query parameter names and/or values, all of the requested resources are unsupported by API, required query parameters aren’t passed. |
| 401  | API key is not provided or is invalid/expired.                                                                                                                                             |
| 403  | API key is provided but the client doesn't have access to at least one of the requested resources.                                                                                         |
| 404  | The endpoint or request path is not found.                                                                                                                                                 |
| 414  | Request URI is too long                                                                                                                                                                    |
| 429  | Rate limits are violated. The client must slow down their requests.                                                                                                                        |
| 524  | User closed connection. This is not returned by the API but is generated by a web service providern due to prolonged waiting.                                                              |
| 500  | Something wrong happened in the API server.                                                                                                                                                |

## API Versions

* \*\*\*\*[**API v4**](https://docs.coinmetrics.io/api/v4) **(stable)**

## API Access

### Free Tier (Community API)

Our community data can be accessed without an API key. Simply run queries against the`community-api.coinmetrics.io` endpoint. This data is available for free for non-commercial use under a [Creative Commons](https://creativecommons.org/licenses/by-nc/4.0/) license. See our [Terms of Use](https://coinmetrics.io/terms-of-use/) for more details.

### Paid Tier (Pro API)

Our professional data is available to institutions via an API key. Please [contact us](https://share.hsforms.com/15lLsB4n2Tl-Jj9MS7P2utA34tym) if you wish to purchase our institutional data.

## Coin Metrics API Standards

### Timestamps

Coin Metrics formats time in accordance with the ISO 8601 standard. As such, the following formats for time parameters in the query string are supported:

* 2020-03-13
* 20060120
* 2020-03-13T15:25:15Z
* 2020-03-13T15:25:15.12345789Z
* 2020-03-13T525.999Z

Note the **Z** suffix in requests is optional. All dates in the query parameters are in the UTC timezone by default. All responses are always in the UTC timezone and with nanoseconds precision.

### Number Format

All numbers in API responses are surrounded by quotes, which allows JavaScript clients to work with numbers that have more than 53 bits. The decimal separator is always a "dot". The number of decimal places is defined by blockchain/exchange and not modified by the API.

### Monetary Amount Formats

Monetary amounts are provided as strings and with the same order of magnitude as the one used for pricing. For Bitcoin, the primary format is the native BTC unit (e.g., 1 BTC, 0.29938 BTC) as opposed to any subformat, such as satoshis, which represent one hundred millionth of a Bitcoin.

## Pagination

Large lists may be split into pages. In accordance with Coin Metrics' API v4, page size has a default value of **100** and can be changed using a `page_size` parameter. The **maximum** page size supported is **10,000**.

If a response contains the `next_page_url` field at the top level of the JSON response, it means the client can request the next page of results by fetching the provided URL without any modifications.

## HTTP/REST API

Coin Metrics' API v4 API uses the HTTP/2 protocol.

## Rate limits

To ensure the quality of Coin Metrics services, our API is subject to rate limiting. If you reach the limit, the API will begin to return `429 Too Many Requests` HTTP response status. The API also provides `X-RateLimit-*` response headers formatted according to <https://tools.ietf.org/html/draft-polli-ratelimit-headers-03>.

### Community API

The community version of API has a limit of 10 requests per 6 seconds sliding window for an **IP address**. It corresponds to 1.6 RPS.

### Paid Tier (Pro API)

The paid version of API has a limit of 6,000 requests per 20 seconds sliding window for an **API key**. It corresponds to 300 RPS.

## WebSocket

We use the default WS protocol ping/pong mechanism. There are some restarts occasionally because it goes through Cloudflare, so you should have some logic in place to automatically reconnect.

## Backward Compatibility

Our API is versioned using [Semantic Versioning](https://semver.org/). The API version number convention is `major.minor.patch`. The notation rules are:

* Backward incompatible changes increase the major number.
* Backward compatible changes increase the minor number.
* Backward compatible bug fixes increase the patch number.

### Versioning

Major versions of the API are run in parallel. The choice of what major API version to use is up to the client, although clients are advised to use the highest stable version.

Major versions can be marked as either stable or unstable. As backward-incompatible changes can be introduced only in unstable or development major versions, no breakage is expected when using fixed, stable major API versions (and adhering to safety guidelines below).

New major API releases are to be added alongside old major API versions, so clients of old (stable) versions are not affected. Old major API versions may be gradually deprecated and removed, following a (generally long-term) deprecation schedule. This should give clients time to adapt their implementations to the new major version.

Minor and patch releases replace old minor/patch API versions, under the same major version. Old minor/patch API versions become inaccessible following these releases.

#### Unstable Major Versions

Recently introduced versions of the API may be explicitly labeled "unstable". Unstable API versions are fully tested, usable by clients, and have complete documentation. However, an unstable API version is not covered by the backward compatibility rules below and can receive arbitrary changes at any time without any warning. Unstable API versions should be used only for evaluation of new features. It is not advised to use unstable versions in production systems.

New major versions of the API are expected to be marked unstable, and after a period of stabilization and testing become permanently stable.

#### Development Major Versions

The newest version of the API may be explicitly labeled "development". Development API versions may receive arbitrary changes at any time and may also have wrong/incomplete implementation, documentation, or other critical issues. Generally, development API versions should be completely avoided, as there are no guarantees about how well it works, or whether it works at all.

### Backward Compatible Changes

A change is considered backward compatible when an API client built for an old version of the API still works with the new version. Hence, it is important that clients use correct assumptions about what details of the API they can rely on.

#### Changes considered backward-compatible (can be introduced in a minor or patch API version)

{% hint style="danger" %}
These changes can be introduced in minor or patch API versions. Follow the below recommendations to avoid broken integrations:

* Addition of a new API method. Do not rely on the absence of a specific URL path or API method.
* Addition of new constant-named fields to response structures of the existing API method. Do not rely on the absence of unknown fields in API response structures.
* Addition of a new optional request parameter to a method, given that its absence has the same meaning as it was before the change. Do not add unsupported request parameters to API calls - they are ignored while unsupported, but may suddenly become "supported".
* Making previously mandatory request parameters optional.
* Addition of new possible values for enum-typed request parameters of the API method.
* Changes in human-friendly strings (i.e. asset/metric names/definitions, error descriptions). Do not make decisions in your code based on human-friendly strings. These strings can be changed for reasons like fixing misspelling or style. Use fields designed to be "stable", e.g. error codes, etc.
* Adding/removing/changing available resources: assets, metrics, etc. Availability of specific assets/metrics/etc is not part of the API interface and not covered by this policy. You should use the discovery API methods to get an accurate list of available resources.
* Fixes which technically should be considered backward-incompatible, when the affected part of the API was virtually unusable before the fix.
  {% endhint %}

#### Changes considered backward-incompatible

{% hint style="success" %}
These changes can only be introduced in a new major API version or unstable major API version. It is safe to assume that this will not happen to fixed, stable major API versions.

* Renaming or removing an API method.
* Removing mandatory request parameters of an API method.
* Making previously optional request parameters mandatory.
* Removing constant-named fields from API response structures.
* Renaming, removing, or changing the meaning of a request parameter.
* Renaming, removing, or changing the meaning of the possible value of enum-typed request parameters.
* Changing the response structure of an API method.
  {% endhint %}

### Emergency Changes <a href="#apibackwardcompatibilitypolicy-emergencychanges" id="apibackwardcompatibilitypolicy-emergencychanges"></a>

Generally, changes to the API interface and functionality will follow this policy as outlined above. However, breaking changes may still be made without introducing a new major version, if it is needed for continuous operation of Coin Metrics' services, for security reasons, or for other reasons, if following this policy is deemed to be infeasible. That may include, but is not limited to, the following: introducing or changing request rate limits, applying specific limits per specific API key, immediate disabling of specific methods or features, etc. Changes also can be made to this policy.

Such emergency changes are expected to be rare exceptions and would be conducted only after careful assessment of the impact to clients. In the event of such a change, Coin Metrics would provide as much advance notice as possible.


# Catalog V1 to Catalog V2 Migration

Coin Metrics would like to provide advance notice for an upcoming change to the catalog endpoints in our API. While these changes have been designed with backwards compatibility in mind, the change can lead to a breaking change in functionality for users that rely on the catalog endpoints to query historical option markets.

We are also announcing the upcoming release of a new set of catalog v2 and reference data endpoints which incorporate a significant number of enhancements that utilize a harmonious and consistent design. We hope these changes will allow our users to more easily understand all the data that Coin Metrics offers!

## Why are we making this change?

Our catalog endpoints describe our coverage universe and the time range of the data that we support. For instance, our /catalog/markets describes the available spot, futures, and options markets. We currently support over 150,000 markets of which over 110,000 markets are option markets.

On a typical day, more than 100 new option markets are added as old option markets expire and new option markets are listed with a variety of strike prices and expiration dates. Over time, this has caused certain of our catalog endpoints to have large response sizes, and the response sizes will continue to increase. Our /catalog/markets response size is currently 110 megabytes.

As our catalog endpoints have evolved over time, we have also detected minor inconsistencies in the schema of our catalog endpoint responses. Some catalog endpoints contain only the time availability of the available data while other catalog endpoints contain only reference data about the entities in our coverage universe. And some catalog endpoints contain a mixture of the two.

To deal with the problem of large response sizes and the schema inconsistencies, Coin Metrics plans on limiting the response size of existing catalog endpoints and introducing a new set of catalog v2 and reference data endpoints with an internally consistent schema to serve as a replacement.

## Which existing catalog endpoints will be affected?

The response size limit changes will affect the following endpoints:

* /catalog/markets
* /catalog/market-trades
* /catalog/market-candles
* /catalog/market-orderbooks
* /catalog/market-quotes
* /catalog/market-funding-rates
* /catalog/market-contract-prices
* /catalog/market-implied-volatility
* /catalog/market-greeks
* /catalog/market-openinterest
* /catalog/market-liquidations
* /catalog/market-metrics

The /catalog-all version of the above endpoints will also be affected. We will refer to endpoints identified in this section as the “affected catalog endpoints” below.

How will the response size be limited for the affected catalog endpoints?

The affected catalog endpoints will retain their existing functionality until the number of markets in the response exceeds 170,000. After the number of markets exceed this number, the response will begin to exclude the oldest option markets. The newest spot, futures, and option markets will still be included in the response. We expect the number of markets to exceed this threshold on about October 6, 2023.

This change will result in a breaking change if a user relies on the catalog endpoints to query historical option markets. For this reason, we encourage all users to switch to our new catalog v2 and reference data endpoints as soon as possible which are described in the sections below.

What data will be returned by the new catalog v2 and reference data endpoints?

Our existing catalog endpoints contain a mixture of both reference data and time availability data with inconsistent response schema. To resolve this inconsistency, Coin Metrics is introducing a new set of catalog v2 and reference data endpoints with an internally consistent schema.

Coin Metrics considers time availability data to be the time range of the timeseries we support and reference data to be metadata about all the entities in our coverage universe. Under our new design, our catalog v2 endpoints will solely contain time availability data and our reference data endpoints will contain solely our reference data.

Let us examine the response from our /catalog-v2/asset-metrics as an example:

```
{
  "data": [
    {
      "asset": "btc",
      "metrics": [
        {
          "metric": "PriceUSD",
          "frequencies": [
            {
              "frequency": "1d",
              "min_time": "2010-07-18T00:00:00.000000000Z",
              "max_time": "2023-07-09T00:00:00.000000000Z"
            },
            {
              "frequency": "1b",
              "min_time": "2009-01-03T18:15:05.000000000Z",
              "max_time": "2023-07-10T21:51:32.000000000Z"
            }
          ]
        }
      ]
    }
  ]
}
```

The /catalog-v2/asset-metrics endpoint describes the time availability for the PriceUSD metric for our btc asset. It describes the two frequencies we offer for this metric as well as the time range of the available data for each frequency.

Now let us examine the response from our /reference-data/asset-metrics endpoint:

```
{
  "data": [
    {
      "metric": "PriceUSD",
      "full_name": "Price, USD",
      "description": "The fixed closing price of the asset as of 00:00 UTC the following day (i.e., midnight UTC of the current day) denominated in USD. This price is generated by Coin Metrics' fixing/reference rate service. Real-time PriceUSD is the fixed closing price of the asset as of the timestamp set by the block's miner.",
      "product": "Network Data",
      "category": "Market",
      "subcategory": "Price",
      "unit": "USD",
      "data_type": "decimal",
      "type": "NA",
      "display_name": "USD Denominated Closing Price"
    }
  ]
}
```

The /reference-data/asset-metrics endpoint describes the metadata for the PriceUSD metric such as the full name and description. It does not contain data about the time availability of the metric by asset.

All of our catalog v2 and reference data endpoints will follow a similar schema. All of our catalog v2 and reference data endpoints will support pagination in a manner identical to our /timeseries endpoints. These new endpoints will support a page\_size parameter with default value of 10,000. This means the response will by default contain the first 10,000 observations. To get the next set of 10,000 observations, the user should use the next\_page\_url to fetch the next page of results.

## I currently use one of the existing catalog endpoints. How do I switch to the new catalog v2 and reference data endpoints?

We have created a mapping of how existing catalog endpoints will map to our new endpoints [here](/tutorials-and-examples/user-guides/how-to-migrate-from-catalog-v1-to-catalog-v2). The new endpoints should contain the same data as the existing catalog endpoint.

If you have any questions or have any use cases that may be adversely impacted by this change, please contact us.

## What happened to \`catalog/\<markets, assets, asset-pairs, exchanges, indexes>\`?

Under v2, the metadata returned by these endpoints are split into reference-data and catalog-v2. Metadata around when data is covered per data type, such as `min/max_time` , can be found on `catalog-v2/<data-type>` . Metadata around which entities are covered under what (e.g., markets in an exchange) can be found on `reference-data`.


# Python API Client

The CM Python API Client provides a simple way to access all data available via the Coin Metrics' API. D Use this client to query all kinds of data. In just a few lines of code, *anyone* can access clean cryptocurrency data in a familiar form, such as a pandas dataframe. Detailed documentation & installation instructions can be found on [GitHub](https://docs.coinmetrics.io/python-api-client/).

For a thorough walkthrough of what you can do with the community client, check out our [walkthrough](/tutorials-and-examples/tutorials/walkthrough_community). Examples of exporting data can be found in How to Export Data > [How To Export Data](/tutorials-and-examples/user-guides/exporting-data#python-api-client).

## Installation

To install the client you can run the following command:

`pip install coinmetrics-api-client`

Note that the client is updated regularly to reflect the changes made in API v4. Ensure that your latest version matches with what's in PyPI

To update your version, run the following command:

`pip install coinmetrics-api-client -U`

For more in depth information on how to use the Python API Client, see the [Python API Client docs.](https://docs.coinmetrics.io/python-api-client/)

## Walkthrough

See: [Python API Client Walkthrough](/tutorials-and-examples/tutorials/walkthrough_community)#

### Tips and Tricks

{% embed url="<https://youtu.be/YR1nVNWt5Ds?feature=shared>" %}
Tips and Tricks for Python Client
{% endembed %}


# R API Client

R is an open-source programming language, popularly used for statistical computing and data analysis. The CM official R client provides a simple way to access all data available via the Coin Metrics' API using the R programming language. **Please note this is an initial implementation and is considered a beta product.**

Detailed documentation & installation instructions can be found on [GitHub](https://github.com/coinmetrics/api-client-r). Use this client to query all kinds of data. By default, data from the API is returned as a tibble so it can be easily manipulated. For every API endpoint supported in the Coin Metrics [API Reference](https://docs.coinmetrics.io/api/v4), there is a related function that follows the same format.


# Cloud Delivery

{% hint style="info" %}
**Cloud Delivery is in limited availability.** To request access, reach out to your sales or account manager.
{% endhint %}

## Overview

Cloud Delivery publishes Coin Metrics market data as Apache Parquet files in Amazon S3, refreshed daily, and exposes the same files as tables in Snowflake. Rather than paging through an API, you read whole datasets directly from object storage or query them in your warehouse. Quantitative researchers, data engineers, and analytics teams use it to load multi-year histories of trades, candles, quotes, and order books into their own environment once, then work with the data locally.

The same objects back both destinations. Choosing S3 or Snowflake changes how you reach the data, not what the data contains.

## At a Glance

<table data-full-width="true"><thead><tr><th>Delivery targets</th><th>Datasets</th><th width="159">Update cadence</th><th>Format</th><th>Partitioning</th><th>Access model</th></tr></thead><tbody><tr><td>Amazon S3 and Snowflake</td><td>Trades, candles, quotes, order books, reference rates, and reference data</td><td>Daily, covering the previous UTC day</td><td>Apache Parquet, Snappy compressed</td><td>Hive-style <code>key=value</code> prefixes by market type, exchange, and date</td><td>Cross-account IAM for S3. Secure Data Sharing for Snowflake</td></tr></tbody></table>

## When to use Cloud Delivery

Cloud Delivery and the API serve different shapes of work. The API is the right tool for interactive queries, narrow slices, and anything real time. Cloud Delivery is the right tool when the volume of data makes repeated API calls impractical.

| Use Cloud Delivery when                                                    | Use the [API](/access-our-data/api) when                   |
| -------------------------------------------------------------------------- | ---------------------------------------------------------- |
| You want a full history of a dataset in your own storage or warehouse      | You need a specific market and time range on demand        |
| You are loading data into Spark, Snowflake, DuckDB, Athena, or a data lake | You are building an application that queries interactively |
| Your volumes make repeated API paging impractical                          | You need real-time data over websockets                    |
| You want columnar files you can scan and filter locally                    | You want the newest observation within seconds             |

Cloud Delivery does not replace API access. Most customers use both.

## Datasets

Ten tables are published. Each maps to one prefix in S3 and one table in Snowflake. Field definitions live on the existing dataset pages, since the columns delivered here are the same ones the API returns.

<table data-full-width="true"><thead><tr><th>Dataset</th><th>S3 prefix</th><th>Snowflake table</th><th>Field reference</th></tr></thead><tbody><tr><td>Market trades</td><td><code>data-type=market-trades/</code></td><td><code>market_trades</code></td><td><a href="/pages/PWJorhGD9UVnYdHTPnid">Market Trades</a></td></tr><tr><td>Market candles</td><td><code>data-type=market-candles/</code></td><td><code>market_candles</code></td><td><a href="/pages/GLBS1gm5NVEDVegLT7Q4">Market Candles</a></td></tr><tr><td>Market quotes</td><td><code>data-type=market-quotes/</code></td><td><code>market_quotes</code></td><td><a href="/pages/E9wKM1KxYCuAqP181Cfx">Market Quotes</a></td></tr><tr><td>Order book snapshots</td><td><code>data-type=market-orderbooks/…/dataset=snapshots/</code></td><td><code>market_orderbooks_snapshots</code></td><td><a href="/pages/AOKHK8BuJTAaIalcX8Z2">Market Order Books</a></td></tr><tr><td>Order book updates</td><td><code>data-type=market-orderbooks/…/dataset=updates/</code></td><td><code>market_orderbooks_updates</code></td><td><a href="/pages/AOKHK8BuJTAaIalcX8Z2">Market Order Books</a></td></tr><tr><td>Reference rates</td><td><code>data-type=reference-rates/</code></td><td><code>reference_rates</code></td><td><a href="/pages/dv9kmrucPmWYmh87Ntjc">Reference Rate</a></td></tr><tr><td>Reference data: markets</td><td><code>data-type=reference-data/dataset=markets/</code></td><td><code>reference_data_markets</code></td><td><a href="/pages/MwBy23kfst4BamorFse0">Market Reference Data</a></td></tr><tr><td>Reference data: assets</td><td><code>data-type=reference-data/dataset=assets/</code></td><td><code>reference_data_assets</code></td><td>See below</td></tr><tr><td>Reference data: exchanges</td><td><code>data-type=reference-data/dataset=exchanges/</code></td><td><code>reference_data_exchanges</code></td><td>See below</td></tr><tr><td>Reference data: pairs</td><td><code>data-type=reference-data/dataset=pairs/</code></td><td><code>reference_data_pairs</code></td><td>See below</td></tr></tbody></table>

### Schema differences

Two tables carry fewer fields than the API returns for the same dataset. Everything else matches the linked pages field for field.

| Table                    | Fields not delivered                                                                                              | Effect                                                                                                                              |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `market_trades`          | `mark_price`, `index_price`, `iv_trade`, `liquidation`                                                            | Futures and options trades arrive without their derivatives-specific fields. Spot and decentralized exchange trades are unaffected. |
| `reference_data_markets` | `pool_config_id`, `fee`, `price_includes_fee`, `variable_fee`, `base_address`, `quote_address`, `multiplier_size` | Decentralized exchange pool metadata is absent from the market catalog.                                                             |

These fields remain available over the API if you need them.

### Reference data schemas

The assets, exchanges, and pairs catalogs each carry two columns, matching the `/reference-data/assets`, `/reference-data/exchanges`, and `/reference-data/pairs` endpoints.

| Table                      | Column      | Type   | Description                                       |
| -------------------------- | ----------- | ------ | ------------------------------------------------- |
| `reference_data_assets`    | `asset`     | string | Asset identifier, for example `btc`.              |
|                            | `full_name` | string | Display name of the asset, for example `Bitcoin`. |
| `reference_data_exchanges` | `exchange`  | string | Exchange identifier, for example `coinbase`.      |
|                            | `full_name` | string | Display name of the exchange.                     |
| `reference_data_pairs`     | `pair`      | string | Pair identifier, for example `btc-usd`.           |
|                            | `full_name` | string | Display name of the pair.                         |

The markets catalog is much wider. See [Market Reference Data](/market-data/market-data-overview/market-reference-data) for its fields.

## Coverage

Cloud Delivery carries a curated subset of the Coin Metrics market data universe rather than every market on every venue. The scheduled datasets cover the following.

| Dataset              | Exchanges            | Market types           | Notes                                                                                                             |
| -------------------- | -------------------- | ---------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Market trades        | 48                   | Spot, futures, options |                                                                                                                   |
| Market candles       | 48                   | Spot, futures, options | Eight frequencies: `1m`, `5m`, `10m`, `15m`, `30m`, `1h`, `4h`, `1d`                                              |
| Market quotes        | 29                   | Spot, futures          | Raw granularity                                                                                                   |
| Order book snapshots | 29                   | Spot, futures          | Full book depth, raw granularity                                                                                  |
| Order book updates   | 5                    | Spot, futures          | Full book depth, raw granularity. Additional exchanges can be added on request                                    |
| Reference rates      | All covered assets   |                        | Frequencies `1s` and `1h`. Metrics `ReferenceRateUSD`, `ReferenceRateEUR`, `ReferenceRateETH`, `ReferenceRateBTC` |
| Reference data       | All covered entities |                        | Current catalog only, refreshed daily                                                                             |

Two of these are narrower than the corresponding product documented elsewhere in this knowledge base. Reference rates are delivered at two frequencies against four quote currencies, where the [Reference Rate](/coin-metrics-prices/coin-metrics-prices/reference-rate-metrics) product covers more of both. Market quotes and order books cover spot and futures only, with no options.

For the market-level universe behind each dataset, see the [coverage tool](https://coverage.coinmetrics.io/). If a market, frequency, or quote currency you need is not in the delivered set, your account manager can arrange a backfill, and the API carries the full set in the meantime.

{% hint style="warning" %}
**Reference data has no history.** The four reference-data catalogs are current snapshots that are overwritten each day. They carry no date partition, so you cannot reconstruct the catalog as it stood on a past date. Retain your own copies if you need point-in-time catalog history.
{% endhint %}

## Update schedule

Every dataset runs once a day and covers the previous UTC day. Jobs start on a stagger to spread load.

| Dataset              | Start time (UTC) |
| -------------------- | ---------------- |
| Reference data       | 00:00            |
| Reference rates      | 00:08            |
| Market trades        | 00:10            |
| Market quotes        | 00:20            |
| Market candles       | 00:30            |
| Order book snapshots | 00:45            |

A file's `dt` partition is the UTC date of the data it contains, not the date the job ran. Data for `dt=2026-07-28` is produced by the run that begins early on 2026-07-29. Larger datasets take longer to complete, so allow for processing time after the preceding start times before expecting a full day to be present.

## File format

Every object is an Apache Parquet file with Snappy compression applied inside the file, which is the Parquet default and is handled transparently by every Parquet reader. There is no outer `.gz` wrapper, so files end in `.parquet` and can be opened directly.

Numeric fields are stored as native Parquet types rather than the JSON strings the API returns. Timestamps are stored as nanosecond epoch values in UTC.

## Getting access

Access is provisioned per customer. To get started, reach out to your sales or account manager and tell them which destination you want.

1. Confirm your entitlements and the datasets you need.
2. Provide the details for your destination. For S3 this is your AWS account ID and, preferably, an IAM role ARN. For Snowflake this is your Snowflake organization and account identifier.
3. Coin Metrics grants read access and confirms the bucket, prefixes, or share name you have been given.
4. Validate the connection using the examples on the destination page below.

## Choose your destination

{% content-ref url="/pages/YQhrVUMx8LheNbUS8uFb" %}
[Amazon S3](/access-our-data/cloud-delivery/amazon-s3)
{% endcontent-ref %}

{% content-ref url="/pages/qUeMlTjUcGsI7v2w450Q" %}
[Snowflake](/access-our-data/cloud-delivery/snowflake)
{% endcontent-ref %}

## Related

* [Downloading Our Data](/access-our-data/downloading-our-data): browser and spreadsheet tools for smaller extracts.
* [API Conventions](/access-our-data/api): the HTTP API, for interactive and real-time access.
* [Status Page](/access-our-data/status-page): incident and change notifications.


# Amazon S3

{% hint style="info" %}
**Cloud Delivery is in limited availability.** To request access, reach out to your sales or account manager.
{% endhint %}

## Overview

Coin Metrics publishes Cloud Delivery datasets to an S3 bucket that Coin Metrics owns and operates. You read objects from that bucket directly using your own AWS account, with standard tooling such as the AWS CLI, the AWS SDKs, DuckDB, Spark, Athena, or Glue. Nothing is copied into your account unless you copy it yourself.

This page covers granting your account access, the layout of the bucket, and reading the files. For which datasets exist and how far back they go, see [Cloud Delivery](/access-our-data/cloud-delivery).

## Get access

Access is granted per customer through cross-account IAM. Anonymous and public access are not supported.

### What to provide

Send your account manager the following.

| Input           | Required  | Notes                                                                         |
| --------------- | --------- | ----------------------------------------------------------------------------- |
| AWS account ID  | Yes       | The account that will read the data.                                          |
| IAM role ARN    | Preferred | Scoping the grant to a single role is safer than granting to a whole account. |
| Datasets needed | Yes       | Determines which prefixes are opened to you.                                  |

Coin Metrics grants read-only access to the prefixes covering your entitled datasets. You receive `s3:GetObject` on those prefixes and `s3:ListBucket` scoped to them. Write, delete, and ACL operations are never granted.

### Requester Pays

The bucket runs in **Requester Pays** mode. Coin Metrics pays to store the data. You pay the S3 request and data-transfer charges for what you read, billed to your own AWS account.

This has a practical consequence: every request must declare that you accept the charges, or S3 rejects it with `403 Access Denied`. How you declare it depends on the tool.

{% tabs %}
{% tab title="AWS CLI" %}

```shell
aws s3 ls s3://talos-data-daily/data-type=market-trades/ --request-payer requester
```

{% endtab %}

{% tab title="boto3" %}

```python
import boto3

s3 = boto3.client("s3")

response = s3.get_object(
    Bucket="talos-data-daily",
    Key="data-type=market-trades/market-type=spot/exchange=coinbase/dt=2026-07-28/coinbase-all-spot-2026-07-28-2026-07-29.parquet",
    RequestPayer="requester",
)
```

{% endtab %}

{% tab title="s3fs / PyArrow" %}

```python
import s3fs

fs = s3fs.S3FileSystem(requester_pays=True)
fs.ls("talos-data-daily/data-type=market-trades/market-type=spot/exchange=coinbase/")
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
**A missing request-payer flag looks like a permissions error.** If reads fail with `403 Access Denied` even though your grant is in place, confirm the flag is set. Many libraries default it to off.
{% endhint %}

To read the bucket you must use an AWS account that can accept Requester Pays charges. If you cannot bill through AWS, talk to your account manager about alternatives.

## Understand the layout

Objects use Hive-style partitioning, where each directory level is a `key=value` pair. Query engines including Athena, Glue, Spark, DuckDB, and PyArrow discover these partitions automatically and skip prefixes that cannot match your filters.

A trades object looks like this.

```
s3://talos-data-daily/
  data-type=market-trades/
    market-type=spot/
      exchange=coinbase/
        dt=2026-07-28/
          coinbase-all-spot-2026-07-28-2026-07-29.parquet
```

Partition values are lowercase, with any character outside `a-z0-9` collapsed to an underscore. An exchange such as `binance.us` therefore appears as `exchange=binance_us`.

### Path templates

Levels differ by dataset. The order is always coarsest first, so filtering on an early level eliminates the most work.

| Dataset         | Prefix template                                                                                                                                      |
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| Market trades   | `data-type=market-trades/market-type={type}/exchange={exchange}/dt={date}/`                                                                          |
| Market candles  | `data-type=market-candles/market-type={type}/exchange={exchange}/frequency={frequency}/dt={date}/`                                                   |
| Market quotes   | `data-type=market-quotes/market-type={type}/exchange={exchange}/granularity={granularity}/dt={date}/`                                                |
| Order books     | `data-type=market-orderbooks/market-type={type}/exchange={exchange}/depth={depth}/granularity={granularity}/dataset={snapshots\|updates}/dt={date}/` |
| Reference rates | `data-type=reference-rates/frequency={frequency}/dt={date}/`                                                                                         |
| Reference data  | `data-type=reference-data/dataset={assets\|exchanges\|markets\|pairs}/`                                                                              |

Two shapes are worth noting. Reference rates carry no `market-type` or `exchange` level, because the dataset is keyed by asset rather than by market. Reference data carries no `dt` level at all, so each of its four objects is overwritten in place every day.

### Partition values

| Key           | Values                                                                                         |
| ------------- | ---------------------------------------------------------------------------------------------- |
| `market-type` | `spot`, `future`, `option`                                                                     |
| `exchange`    | Normalized exchange identifier, for example `coinbase`, `binance`, `binance_us`                |
| `frequency`   | Candles: `1m`, `5m`, `10m`, `15m`, `30m`, `1h`, `4h`, `1d`. Reference rates: `1s`, `1h`        |
| `granularity` | `raw`                                                                                          |
| `depth`       | `full_book`                                                                                    |
| `dataset`     | Order books: `snapshots`, `updates`. Reference data: `assets`, `exchanges`, `markets`, `pairs` |
| `dt`          | UTC date of the data, formatted `YYYY-MM-DD`                                                   |

{% hint style="warning" %}
**Two partition keys contain hyphens.** When an engine derives columns from the prefix, `data-type` and `market-type` keep their hyphens, which most SQL dialects treat as subtraction. Quote them: backticks in Spark, double quotes in DuckDB and Athena. The Snowflake tables are unaffected, since they expose the same partitions as `market_type` with an underscore.
{% endhint %}

### Files

Each partition holds Parquet files covering that day for that slice of the market universe. Filenames encode the markets requested and the date range covered, for example `coinbase-all-spot-2026-07-28-2026-07-29.parquet`. Treat filenames as opaque. Read every `.parquet` object under a partition prefix rather than reconstructing a name, since names can change as coverage expands.

Snappy compression is applied inside the Parquet file, which is the format default and is handled transparently by readers. There is no outer `.gz` wrapper.

A day on which a market produced nothing is skipped rather than written as an empty file, so a missing partition means no activity rather than missing data.

## Read the data

Point any Parquet reader at a prefix. The examples below read one day of Coinbase spot trades.

{% tabs %}
{% tab title="AWS CLI" %}

```shell
# List what is available for a day
aws s3 ls \
  s3://talos-data-daily/data-type=market-trades/market-type=spot/exchange=coinbase/dt=2026-07-28/ \
  --request-payer requester

# Download the partition
aws s3 cp \
  s3://talos-data-daily/data-type=market-trades/market-type=spot/exchange=coinbase/dt=2026-07-28/ \
  ./trades/ --recursive --request-payer requester
```

{% endtab %}

{% tab title="pandas / PyArrow" %}

```python
import pyarrow.dataset as ds
import pyarrow.fs as fs

s3 = fs.S3FileSystem(request_payer="requester", region="us-east-1")

dataset = ds.dataset(
    "talos-data-daily/data-type=market-trades",
    filesystem=s3,
    format="parquet",
    partitioning="hive",
)

# Partition column names carry the hyphens used in the prefix, so quote them.
table = dataset.to_table(
    filter=(ds.field("market-type") == "spot")
    & (ds.field("exchange") == "coinbase")
    & (ds.field("dt") == "2026-07-28")
)

df = table.to_pandas()
print(df.head())
```

{% endtab %}

{% tab title="DuckDB" %}

```sql
INSTALL httpfs;
LOAD httpfs;

SET s3_region = 'us-east-1';
SET s3_requester_pays = true;

SELECT market, time, price, amount, side
FROM read_parquet(
  's3://talos-data-daily/data-type=market-trades/market-type=spot/exchange=coinbase/dt=2026-07-28/*.parquet'
)
ORDER BY time
LIMIT 10;
```

{% endtab %}

{% tab title="Spark" %}

```python
spark.conf.set("fs.s3a.requester-pays.enabled", "true")

df = (
    spark.read.parquet("s3a://talos-data-daily/data-type=market-trades/")
    .filter("`market-type` = 'spot' AND exchange = 'coinbase' AND dt = '2026-07-28'")
)

df.show(10)
```

{% endtab %}
{% endtabs %}

### Reading efficiently

Because you pay per request and per byte transferred, how you scan matters.

* **Filter on partition keys first.** A query filtered to one exchange and one date reads a handful of objects. The same query without those filters lists and reads the whole dataset.
* **Point readers at the deepest prefix you can.** Passing the full `dt=` prefix avoids listing every exchange.
* **Select only the columns you need.** Parquet is columnar, so projecting a few columns transfers far less than reading whole rows.
* **Avoid repeated full-bucket listings.** Listing calls are billed like any other request.

## Limits and notes

* **You pay for reads.** Requester Pays means request and transfer charges land on your AWS account. Broad scans across many exchanges and dates can be expensive.
* **The data is read-only.** Write, delete, and ACL permissions are never granted.
* **Reference data has no history.** Its four objects are overwritten daily and carry no date partition. Keep your own copies if you need point-in-time catalog history.
* **Order book files are large.** Full-book snapshots at raw granularity produce the biggest objects in the bucket. Filter tightly and expect long transfers.
* **File names are not a stable interface.** Read every `.parquet` object under a partition rather than depending on a naming pattern.
* **Encryption and transport.** Objects are encrypted at rest with server-side encryption, and the bucket policy requires TLS.

## Related

* [Cloud Delivery](/access-our-data/cloud-delivery): datasets, coverage, and the update schedule.
* [Snowflake](/access-our-data/cloud-delivery/snowflake): the same data as tables in your warehouse.
* [AWS documentation on Requester Pays buckets](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RequesterPaysBuckets.html)


# Snowflake

{% hint style="info" %}
**Cloud Delivery is in limited availability.** To request access, reach out to your sales or account manager.
{% endhint %}

## Overview

Coin Metrics exposes Cloud Delivery datasets as tables in Snowflake through Secure Data Sharing. You mount a read-only database in your own Snowflake account and query it with SQL. No data is copied into your account and you are not charged Snowflake storage for it. You pay only for the compute you use to run queries.

The tables are Snowflake **external tables** over the same Parquet objects described on the [Amazon S3](/access-our-data/cloud-delivery/amazon-s3) page. That means you never handle S3 paths or AWS credentials, but it also shapes query performance, which is covered under [Limits and notes](#limits-and-notes).

For which datasets exist and how far back they go, see [Cloud Delivery](/access-our-data/cloud-delivery).

## Get access

### What to provide

Send your account manager your Snowflake **organization name** and **account name**. You can find both by running the following in your account.

```sql
SELECT CURRENT_ORGANIZATION_NAME(), CURRENT_ACCOUNT_NAME();
```

Coin Metrics adds your account to a share. Shares are curated per customer, so you see the tables covered by your entitlements rather than every table published.

### Mount the share

Once you have been added, confirm the share is visible.

```sql
SHOW SHARES;
```

Create a database from it. You choose the database name, so pick whatever fits your naming conventions.

```sql
CREATE DATABASE coin_metrics
  FROM SHARE <provider_account>.<share_name>;
```

Grant your reader roles access to it.

```sql
GRANT IMPORTED PRIVILEGES ON DATABASE coin_metrics TO ROLE analyst;
```

Tables live in the `EXTERNAL` schema, so a fully qualified name looks like `coin_metrics.EXTERNAL.market_trades`. Verify the mount worked.

```sql
SHOW TABLES IN SCHEMA coin_metrics.EXTERNAL;

SELECT COUNT(*) FROM coin_metrics.EXTERNAL.market_trades WHERE dt = '2026-07-28';
```

{% hint style="info" %}
**Shares are region-bound.** A direct share works when your account is in the same cloud region as the provider account. If yours is elsewhere, your account manager will arrange a listing that handles cross-region fulfillment.
{% endhint %}

### Marketplace listings

Coin Metrics also publishes Cloud Delivery datasets as private listings. A listing is the better route when you need cross-region or cross-cloud delivery, or when you prefer to discover and request the data through the Snowflake interface rather than by exchanging account identifiers. Ask your account manager which route suits you.

## Understand the layout

Ten tables are published in the `EXTERNAL` schema.

| Table                         | Contents                       |
| ----------------------------- | ------------------------------ |
| `market_trades`               | Executed trades                |
| `market_candles`              | OHLCV bars                     |
| `market_quotes`               | Best bid and ask               |
| `market_orderbooks_snapshots` | Point-in-time order book state |
| `market_orderbooks_updates`   | Incremental order book changes |
| `reference_rates`             | Coin Metrics reference rates   |
| `reference_data_markets`      | Market catalog                 |
| `reference_data_assets`       | Asset catalog                  |
| `reference_data_exchanges`    | Exchange catalog               |
| `reference_data_pairs`        | Pair catalog                   |

### Partition columns

Every market dataset carries partition columns in addition to its data columns. These are derived from the underlying file layout rather than stored in the file body, and filtering on them is what keeps queries fast.

| Table                         | Partition columns                                       |
| ----------------------------- | ------------------------------------------------------- |
| `market_trades`               | `market_type`, `exchange`, `dt`                         |
| `market_candles`              | `market_type`, `exchange`, `frequency`, `dt`            |
| `market_quotes`               | `market_type`, `exchange`, `granularity`, `dt`          |
| `market_orderbooks_snapshots` | `market_type`, `exchange`, `depth`, `granularity`, `dt` |
| `market_orderbooks_updates`   | `market_type`, `exchange`, `depth`, `granularity`, `dt` |
| `reference_rates`             | `frequency`, `dt`                                       |
| Reference data tables         | None                                                    |

`dt` is a `DATE` holding the UTC date of the data. `market_type` is one of `spot`, `future`, or `option`. `exchange` is the normalized exchange identifier, lowercase with non-alphanumeric characters replaced by underscores, so `binance.us` appears as `binance_us`.

### Data columns

Column names and meanings match the API fields documented on the dataset pages linked from [Cloud Delivery](/access-our-data/cloud-delivery), except for the omissions listed under [Schema differences](/access-our-data/cloud-delivery#schema-differences). Two further differences are worth knowing.

**Types are native, not strings.** The API returns prices and amounts as JSON strings to preserve precision. Here they are `FLOAT`, and timestamps are `TIMESTAMP_NTZ` in UTC rather than ISO-8601 strings. If you need exact decimal arithmetic, cast to `NUMBER` with an explicit scale.

**Order book sides are semi-structured.** In `market_orderbooks_snapshots` and `market_orderbooks_updates`, `asks` and `bids` are `VARIANT` columns holding arrays of price and size objects. Use `LATERAL FLATTEN` to expand them, as shown below. The updates table additionally carries a `type` column that the snapshots table does not.

## Read the data

### Trades for one market and day

```sql
SELECT market, time, price, amount, side
FROM coin_metrics.EXTERNAL.market_trades
WHERE market_type = 'spot'
  AND exchange = 'coinbase'
  AND dt = '2026-07-28'
  AND market = 'coinbase-btc-usd-spot'
ORDER BY time
LIMIT 100;
```

### Daily candles over a date range

```sql
SELECT dt, market, price_open, price_high, price_low, price_close, volume
FROM coin_metrics.EXTERNAL.market_candles
WHERE market_type = 'spot'
  AND exchange = 'binance'
  AND frequency = '1d'
  AND dt BETWEEN '2026-01-01' AND '2026-06-30'
  AND market = 'binance-btc-usdt-spot'
ORDER BY dt;
```

### Reference rates

Metric columns are named after the metric, for example `ReferenceRateUSD`. Snowflake identifiers are case-insensitive unless quoted, so you can write them in any case.

```sql
SELECT asset, time, ReferenceRateUSD
FROM coin_metrics.EXTERNAL.reference_rates
WHERE frequency = '1h'
  AND dt = '2026-07-28'
  AND asset IN ('btc', 'eth')
ORDER BY asset, time;
```

### Flattening an order book

Expanding the `asks` array gives one row per price level.

```sql
SELECT
  ob.market,
  ob.time,
  level.index                     AS level_index,
  level.value:price::FLOAT        AS price,
  level.value:size::FLOAT         AS size
FROM coin_metrics.EXTERNAL.market_orderbooks_snapshots AS ob,
     LATERAL FLATTEN(input => ob.asks) AS level
WHERE ob.market_type = 'spot'
  AND ob.exchange = 'coinbase'
  AND ob.dt = '2026-07-28'
  AND ob.market = 'coinbase-btc-usd-spot'
  AND ob.time = '2026-07-28 00:00:00'
ORDER BY level_index
LIMIT 20;
```

### Joining to the market catalog

```sql
SELECT t.market, m.base, m.quote, m.type, COUNT(*) AS trade_count
FROM coin_metrics.EXTERNAL.market_trades AS t
JOIN coin_metrics.EXTERNAL.reference_data_markets AS m
  ON t.market = m.market
WHERE t.market_type = 'spot'
  AND t.exchange = 'coinbase'
  AND t.dt = '2026-07-28'
GROUP BY t.market, m.base, m.quote, m.type
ORDER BY trade_count DESC;
```

### Querying efficiently

External tables read from object storage at query time, so pruning matters more than it would on a native table.

* **Always filter on `dt`.** It is the highest-leverage filter available. An unfiltered query scans every day of history.
* **Filter on `exchange` and `market_type` too.** Each one eliminates a large share of the files before any are opened.
* **Filter on `frequency` for candles.** Eight frequencies share the table, so omitting it reads roughly eight times more data than you need.
* **Compare `dt` to date literals, not expressions.** Wrapping the column in a function can prevent partition elimination.
* **Materialize hot queries.** If you run the same aggregation repeatedly, create a native table or materialized view from the result rather than rescanning the external table each time.

## Limits and notes

* **The tables are read-only.** External tables do not support `INSERT`, `UPDATE`, `DELETE`, or `MERGE`. To modify data, copy it into your own table first with `CREATE TABLE ... AS SELECT`.
* **Queries are slower than on native tables.** Every query reads Parquet from object storage. Pruning is at file level rather than micro-partition level, and there is no automatic clustering. For repeated heavy analytics, copy the slice you need into a native table.
* **You pay for compute.** Snowflake storage is not charged for shared data, but every query runs on your warehouse and is billed to you.
* **No Time Travel on shared external tables.** If you need historical snapshots of the data as it stood, materialize your own copies.
* **Reference data has no history.** The four catalog tables reflect the current state and are overwritten daily. They have no `dt` column.
* **Shares cannot be re-shared.** Snowflake does not permit a consumer to re-share a database created from a share. If another account in your organization needs access, ask your account manager to add it to the share.

## Related

* [Cloud Delivery](/access-our-data/cloud-delivery): datasets, coverage, and the update schedule.
* [Amazon S3](/access-our-data/cloud-delivery/amazon-s3): the same data as files in object storage.
* [Snowflake documentation on consuming shares](https://docs.snowflake.com/en/user-guide/data-share-consumers)


# Downloading Our Data

Coin Metrics Data can be downloaded thru a variety of methods below are our guides for a few ways to easily do this.

## [Google Sheet Integration](#google-sheet-integration)

Import directly through Formulas in Google Sheets. Leverage this guide to quickly set yourself up to download with a pre-formatted Google Sheet.

## [Download Data via Front End Tools](#download-data-via-front-end-tools)

Our Coin Metrics charting tool enables a multitude of methods for downloading visualizations of charts or csv and excel file formats of the data charted in the Tool.

## [Data Downloader User Interface](/access-our-data/downloading-our-data/data-downloader-user-interface)

Our Data Downloader portal is available to permissioned users to bulk download a varitey of Market Data and On-Chain Data sets. If you are interested in accessing data this way please reach out to your sales or account manager.


# Google Sheets Integration

## Importing Coin Metrics Data to Google Sheets

Where our Coin Metrics API includes a csv format option data can be directly loaded into google sheets.

To do this input you API call into the `=IMPORTDATA()` formula.

Below is an example Once included there is warning that requires you to allow access: steps for setting this up yourself

1. Open a new google sheet
2. Add API Parameters to cells in columns A and add results to column B
   1. Example using time series asset-metrics endpoint

| A           | B                    |
| ----------- | -------------------- |
| API KEY     | {API\_KEY}           |
| ASSETS      | btc                  |
| METRICS     | PriceUSD             |
| PAGE SIZE   | 1000                 |
| START TIME  | 2025-01-01T00:00:00Z |
| END TIME    | 2025-01-31T00:00:00Z |
| PAGING FROM | end                  |
| FREQUENCY   | 1d                   |

3. Leverage this formula for creating your API Query

```
= "https://api.coinmetrics.io/v4/timeseries/asset-metrics?" &
"api_key="& B1 &
"&assets=" & B2 &
"&metrics=" & B3 &
"&page_size=" & B4 &
"&start_time=" & B5 &
"&end_time=" & B6 &
"&paging_from=" & B7 &
"&frequency=" & B8 &
"&format=csv"



```

4. In a new cell enter: `=IMPORTDATA({Cell with API Call})`

At this point you will see a warning where you need to allow access for the API Call

<figure><img src="/files/86GBbjn8a9RFAPxevT7o" alt=""><figcaption></figcaption></figure>

Example results:

<figure><img src="/files/fa88m43PfCstJHhkO08c" alt=""><figcaption></figcaption></figure>


# Download Data via Front End

Directly download data to CSV or Excel format via our Charting tool and Atlas Front Ends

## Downloading in Charting Tool

<a href="https://charts.coinmetrics.io/crypto-data/" class="button primary" data-icon="chart-line-up">Charting Tool</a>

After navigating to [charts.coinmetrics.io](https://charts.coinmetrics.io) and selecting the data set, assets and metrics you are looking to chart there are a few options to directly download the data avalable.

The First is directly within the Charting Frame by selecting the download button in the top left and selecting csv or excel. Additionally we offer downloads of the chart images as .jpeg. by default these are downloaded with the legends attached.

<figure><img src="/files/0p4p74sz5ar5QUrNrX6G" alt=""><figcaption></figcaption></figure>

If you would like to exclude the legends you can navigate to the side bar on the right and through that download button you can select to remove legends.

<figure><img src="/files/ruRKHhq8gnNS2ZiyoLjZ" alt=""><figcaption></figcaption></figure>


# Data Downloader User Interface

<a href="https://download.coinmetrics.io/" class="button primary" data-icon="file-arrow-down">Data Downloader</a>

With the Data Downloader at [download.coinmetrics.io](https://download.coinmetrics.io/), traders, researchers, and analysts can quickly retrieve large datasets directly from their browser in convenient formats like CSV, line-delimited JSON, or Apache Parquet. Whether you’re backtesting strategies, building models, or conducting research, the Data Downloader provides a faster, more intuitive way to get the data you need.

Data sets available include:

* Market trades
* Market Open Interest
* Market Liquidations
* Market Funding Rates
* Predicted Market Funding Rates
* Market Orderbooks
* Market Quotes
* Market Candles
* Market Contract Prices
* Market Implied Volatility
* Market Greeks
* Blockchain Account Balance Updates
* Blockchain Account Balances

<figure><img src="/files/epYgICCQ1eCaio4XIZk7" alt=""><figcaption></figcaption></figure>

Within each of the selected data types there are parameters to select the data you would like to download and formatting information.

<figure><img src="/files/061JprXiDa57fA4N8X48" alt=""><figcaption></figcaption></figure>


# Status Page

Subscribe to our Status Page for updates on our services, infrastructure, data quality and historical data changes.

Ensuring uninterrupted data feeds and customer satisfaction is our top priority. To achieve this, we employ automated bots across our data production systems, enabling us to monitor pipelines continuously.

If any unexpected delays or issues arise, we promptly alert our clients through our Status Page. Our dedicated team works diligently to resolve the problems as quickly as possible, providing timely updates along the way. Additionally, we maintain a change-log for historical recalculations and data cleanses, keeping our clients informed at all times.

We highly recommend that our customers subscribe to our [Status Page](https://status.coinmetrics.io/) for the operational statuses of anything that impacts the usage of our products:

#### Market Data Products

* Market Data Feed: Information and updates on incidents affecting CM’s market data feed.
* CM Prices: Information and updates on incidents affecting CM Prices.
* CMBI Indexes: Information and updates on incidents affecting CM’s Bletchley Indexes.
* Reference Data: Information and updates on incidents affecting CM’s Reference Data

#### Onchain Products

* Network Data Pro: Information and updates on incidents affecting CM’s Network Datapro.
* ATLAS: Information and updates on incidents affecting CM’s ATLAS.
* FARUM: Information and updates on incidents affecting CM’s FARUM.

#### Services

* Pro API V4: Information and updates on incidents affecting our Pro API v4 data only.
* Community API V4: Information and updates on incidents affecting our Community API v4 data only.
* Website: Information and updates on incidents affecting our website.
* Mobile App: Information and updates on incidents affecting our mobile app.
* Flat Files: Information and updates on incidents affecting our Flat Files.
* Charting Tools: Information and updates on incidents affecting our charting tool functionality

#### Data Change Notifications

* Market Data Feed Changes: Changes regarding Market Data Feed data.
* CM Prices Changes: Changes regarding Reference Rates data.
* Network Data Pro Changes: Changes regarding Network Data Pro data.
* ATLAS Changes: Changes regarding Atlas data.
* FARUM Changes: Changes regarding FARUM data.
* CMBI Indexes Changes: Data changes regarding the Coin Metrics Bletchley Indexes.
* Reference Data Changes: Changes regarding Datonomy data.
* Flat Files Changes: Changes regarding Flat Files data.

#### Labs

#### Third Party Data

* Market Data Vendor: Incidents originating from our supported exchanges.
* Network Data Vendor: Incidents originating from our supported nodes.

#### Maintenance

* Data Center Maintenance: Coin Metrics Data Centre Maintenance.

#### Subscriber Feeds

To subscribe to our Status Page, please go[ here](http://status.coinmetrics.io). We push our updates through a variety of channels that you can manage to your preference:

* Email
* Phone
* Slack
* Webhooks
* RSS Feed
* [Twitter](https://twitter.com/CM__Status)

#### Navigating the Status Page

Our Status Page displays any ongoing incidents at the top of the browser. If there are no issues, all components display "Operational" written in green text, in the status column as shown in the image below.

<figure><img src="https://lh7-us.googleusercontent.com/QjARDgfCkgWuIJuR65YLzLH9lClGZZYe_JisNNijyDQOWDcm1ir6uKcUUAJ1h0eCRoD1gzfbHBXb1Eeh-9EAZuMG7cDFEBQnJwMm8SJnbRiUcoAjEagtC1mZmzELi4iLaYe8B2Ukv28Fu6_IeqQsvHI" alt=""><figcaption></figcaption></figure>

However, if there is an ongoing issue, there won’t be an “operational” green text. Ongoing issues are written in either yellow, orange or red text, depending on the degree of severity of the issue, while a component undergoing maintenance is written in blue text as shown in the image below.

<figure><img src="https://lh7-us.googleusercontent.com/4SIRgx2ndbcbA8I1ThCg34fkMBpwZVytez-lgbegg5QC4CYuHNtK79Dj-_TYjxLbiOAyKZ1VKkeleQ_0vuqbDiyqcT4dofyUb3oGAup7wbK_rn7uaQeiGGmq8z4XeNrex8A6QHr6_6ELuTGy0vfUe8U" alt=""><figcaption></figcaption></figure>

You can click into each issue for additional information on the time it was reported, the affected products, and all historical updates to that particular issue. At the bottom of the Status Page, you can also see a stream of our incident history.

If you have any questions about our Status Page, please feel free to reach out through our[ Support Center](https://coinmetrics.io/support/).

\\


# Data Visualization

Introduction

Our Data Visualization offering includes three tools:

* [Charting tool](/data-visualization/charting-tool)
* [Formula builder](/data-visualization/charting-tool/formula-builder)
* [Correlation tool](/data-visualization/charting-tool/correlation-tool)

CM provides data visualization tools and user interfaces as a convenience to our customers. We are an API-first data company, but our user interfaces help our clients visualize and explore our datasets, download data into XLS/CSV formats, create charts for social media and help users along in their journey to API usage. We have two primary data visualization offerings: Our Charting Tools and Our Dashboards. In addition, we have several Labs/Demo UIs including Atlas and our Farum Transaction Tracker.

These tools allow for easy exploration of our network (on-chain data). Users can select multiple assets and metrics to identify trends and insights or leverage our powerful formula builder to transform data series. The correlation tool makes for simple correlation analysis. All charts can be downloaded as PNGs and the charted data can be exported to CSV or XLS files. And, you can save your charts for later or share them with others.

## Data Sources

All data is sourced from the CM v4 API.

* **Network Data (EOD)**: Available through our Network Data Pro product
* **Reference Rates**: Specifically our daily 00:00 UTC, 12pm NYC, 4pm NYC, 10:30am London, 11:00am London, 3:15 Chicago
* **Indexes (Daily Levels)**: Available through our CMBI product

We also offer three external benchmarks sourced from the FRED API. This data is not endorsed or certified by the Federal Reserve Bank of St. Louis. These benchmarks include the

* S\&P 500 Index (<https://fred.stlouisfed.org/series/SP500>), which is an S\&P Dow Jones Indices LLC product; note the daily value for this index is as of 4pm NY time
* Trade Weighted US Dollar Index (<https://fred.stlouisfed.org/series/DTWEXBGS>), which is a Board of Governors of the Federal Reserve System (US) product; note that the daily value for this index is 12:00pm NY time
* CBOE Volatility Index (<https://fred.stlouisfed.org/series/VIXCLS>), which is a Chicago Board Options Exchange product; note that the daily value for this index is 3:15pm Chicago time

## Getting Started

This suite of charting tools can be accessed directly at [Charts](https://network-charts.coinmetrics.io/) with or without an API key. Without an API key, you will have access to the community data from the above[ data sources.](#data-sources)

### Using an API Key

If you are a client of our professional data and you have an API Viz key, you can enter your key by selecting the "key" on the top of the right toolbar. If you are a client, and you do not have a Viz key, contact us to obtain one. Each user needs their own Viz key, as these keys have special permisssions. Also, any charts saved to our cloud are saved to your user-specific key.

<figure><img src="/files/-MP17GcTX56PCKKMzGfL" alt=""><figcaption></figcaption></figure>

## Saving Charts

You can save your charts in all three of our tools. Simply select the "save" image on the right toolbar. There are two options for saving your charts:

* Save as... (only available to users with a Viz API key) - save your chart to your API key and reload it later from any device. Charts saved to your API key can be "named" (given a title) and can be shared via a chart-specific URL.
* Save to local drive - save your chart to your local drive in a json format and reload it for later use.

![Click on the "disk" to find the Save Options](/files/-MP5DPWHQxplqfYHYmG4)

## Loading Charts

To load a previously saved chart, select the "folder" image on the right toolbar. If you saved your chart to your API key (to the Cloud), then "Load from cloud". If you saved your chart to your local drive, then "Load from file".

![](/files/-MezHGfG8YTDD1x9c8TE)

If you "Load from file", then find your file/chart using the explorer window.

## Sharing Charts

If you'd like to share a chart via a URL, you need an API via key. Once your API key is set, then, click the "share" button.

![Click on the "share" button to copy a sharable URL to the desktop](/files/-MPohVtognt4As1F15Hd)

If you've already saved your chart, then ensure that "Sharing on" is green, and click the copy button to copy the URL to the clipboard. If you haven't yet saved your chart, name the chart and then copy the URL to the clipboard.

![](/files/-MPoiWvxtptST6w-G6Qm)

## Downloading Charts

Charts can be downloaded to data files (CSV or XLS) or image files (PNG with our without a legend). Simply select the "download" button on the right toolbar. If you'd like to see a title on your chart, save your chart and assign a name. The assigned name will be your title.

![Click on the "download" button to find the Download Options](/files/-MPoeqLjTC39GCWg508s)

## Chart Options

There are several ways to adjust your plot in both the "Charting Tool" and the "Formula Builder". These features are located on the bottom toolbar. From left to right below:

* Lin/Log - adjust the vertical axes to a Linear or Logarithmic scale (the choice applies to both right and left axes)
* Line/Stacked Area/100% Stacked Area - chose a different chart type
* Average - select no average, a 7-day moving average, a 14-day moving average, a 30-day moving average, a 50-day moving average, a 90-day moving average and a 200-day moving average
* Right axis - chose which series you'd like to see on the right hand axis (RHS) (only on the primary charting tool, not in Formula Builder or Correlation Tool)
* All/1M/3M/1Y/YTD - chose your preferred X-axis range

![](/files/-M_ey3a_kUT3l5D5BLjs)


# Charting Tool

https\://charts.coinmetrics.io/network-data/

## Selecting a Data Series

The Charting Tool allows you to easily visualize our [Asset Metrics](https://coverage.coinmetrics.io/asset-metrics-v2). Simply select the "Add" button from the top left selection dialogs.

<figure><img src="/files/SHhktRb1agbWTTDsfiSV" alt=""><figcaption></figcaption></figure>

Upon clicking the "Add" button, the Assets dialog will open to display the available assets. Assets can be searched by category or by typing the symbol or name into the "Asset Name or ID..." search window.

Once you've made your asset selection, you can click on the "Proceed to Metrics" button, which will open the Metrics dialog to display the metrics available for the selected assets.

Instead of selecting the assets first, you can also select the "Start With Metrics" button in the bottom left of the dialog window and the list of all available metrics will be shown.

<figure><img src="/files/pXXeBD9fBNBtMBZCl8Ev" alt=""><figcaption></figcaption></figure>

If "Start With Metrics" was selected, navigate back to select assets by selecting the "Back To Assets" button in the bottom left.

<figure><img src="/files/weSQje4i97avVbSlGXC3" alt=""><figcaption></figcaption></figure>

The metric will be displayed in black will be "selectable" if it is available for all selected asset. Metrics that are not available for all of the assets selected will be hidden and will not be shown.

Metrics or Assets that are not available with API key entered will show a lock symbol.

![](/files/-MVOq2xTl8-N--27JA-L)

The metric definition can be expanded via the "question symbol" to the right of the metric name as shown below. To collapse it, click the "up arrow".

![](/files/-MVOqiEE4C-BcekhJxzM)

Once all desired assets and metrics have been selected, continue by selecting the "+ Add to Chart" button in the bottom right of the dialog.

<figure><img src="/files/BjntjvoeW20IdOnaCexm" alt=""><figcaption></figcaption></figure>

You will then see the selected asset-metric pairs plotted in the charting tool as well as the selected combinations at the top of the chart. Additional items can be shown by selecting the down arrow next to the row of asset-metric pairs.

<figure><img src="/files/PD7rL9jlZlpqq1YdAMQw" alt=""><figcaption></figcaption></figure>

Grayed out items are hidden from the plotted chart. Select an item to show/hide that asset-metric combination. To remove an item from the chart completely, click the "X" in each item to remove it.

<figure><img src="/files/8m4JWeRfglxvWEOcC5d3" alt=""><figcaption></figcaption></figure>

## Handling of Data Gaps

On occasion, you may want to compare a continuous data series with one with gaps (such as when you compare cryptoasset returns with a traditional index like S\&P500 that has no values on the weekends or holidays). The tool gives you two options for handling this:

* Linearly interpolate the data to derive a value for the data gap prior to calculating the returns
* Exclude the observations on the dates where one data series has a gap, but the other doesn't prior to calculating the returns (note: this results in fewer observations for the non-gapped series)

The tool will default to "excluding" data where gaps are identified. You can adjust this setting from the settings menu on the right toolbar.

![Click on the "gear" to find the settings for Data Gaps](/files/-MOwyYU_e8Z4iVfNO8Ru)

## **Charting Tool Tutorial Series**

*Please note: the below tutorial series utilizes the legacy layout for asset-metric selections. While slightly different the core functionality is the same across the two.*

### **Part 1 - Tool Basics**

In the first segment of our tutorial series, we explore the basic features and functions you'll need to get started with our Network Data visualization tool.

[**Charting Tool Tutorial Series - Part 1**](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/Charting%20Tool%20Demo%20\(Part%201\)%20-%20Tool%20Basics.mp4)

### **Part 2 - Assets & Metrics**

The second segment of the series explores the wide array of assets and metrics available in the Coin Metrics coverage universe, and demonstrates the variety of charting tool settings that can be used to visualize this data.

[**Charting Tool Tutorial Series - Part 2**](https://5264302.fs1.hubspotusercontent-na1.net/hubfs/5264302/Charting%20Tool%20Demo%20\(Part%202\)%20-%20Assets%20&%20Metrics.mp4)


# Formula Builder

https\://charts.coinmetrics.io/formulas/

### Formula Builder Overview

The formula builder allows you to transform the available Coin Metrics' data series. For example, you can create your own ratios, add together USDT metrics, slice or splice time series, even customize the line colors and many more things.

The formula builder editor and information can be found via the menu in the top left by clicking on the CM logo and selecting the "Formulas" button.

<figure><img src="/files/hiCpybGxtmJIIZiFPeWb" alt="" width="132"><figcaption></figcaption></figure>

If you are unfamiliar with the formula builder and syntax, the "Help" tab is a good place to start.

<figure><img src="/files/njETnmaL4SuSBfsx4uIG" alt="" width="563"><figcaption></figcaption></figure>

### Formula Editor

The formula editor is under the "Formulas" tab. An example of a very simple formula is shown below.

<figure><img src="/files/43FVLa0cKgl64iIEiYmN" alt=""><figcaption></figcaption></figure>

### Syntax

Specific **syntax** and **syntax** **examples** can be found on the "Syntax" tab. You can search for the specific "formula" in the "Search..." window or scroll through the list of available formulas. Once a formula is selected, further information on that formula (including the "syntax" and often an example) show up in the window.

<figure><img src="/files/qyYGbAHSifCPQh192Jcs" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/TqN6IRlEuZ96k99vZGN0" alt=""><figcaption></figcaption></figure>

### Chart/Formula Example

A great example of a Formula Builder Chart is this *BTC Market Cap Dominance* chart. This chart can be built easily in our Formula Builder.

![BTC Dominance (Free Float Market Cap)](/files/-MgRg13UdY-wyXYjvlpb)

If you click into the Formula Editor on the right side of the [charts](https://charts.coinmetrics.io/formulas/#1394), you can see the syntax used to create a combined time-series of Market Cap across all of the assets supported in our universe.

![BTC Dominance (Formula Editor Syntax)](/files/-MgRgrAxvSSmHZL4hUYu)

This just scratches the surface, as there are many other ways you can use this tool to transform our time-series. Here are a few more examples:

* [ETH HODL Waves](https://charts.coinmetrics.io/formulas/#297)
* [BTC Active Supply Bands](https://charts.coinmetrics.io/formulas/#212)
* [USDT\_ETH Supply Distribution](https://charts.coinmetrics.io/formulas/#212)
* [USDT\_ETH Address Distribution](https://charts.coinmetrics.io/formulas/#163)


# Correlation Tool

https\://charts.coinmetrics.io/correlations/

## Correlation Coefficient

A correlation coefficient is a number between -1 and 1 measuring the strength of a relationship between two variables. A positive correlation means that returns move together. If you plotted returns of two cryptoassets on a scatterplot, dots sloping upwards and right in a diagonal line would imply a positive correlation. Note that no causality is inferred. The actual derivation involves taking the covariance of two variables. Covariance tells you whether two variables move together or not, but it is unbounded and unstandardized. Finding a correlation involves standardizing those arbitrarily large figures by dividing by the sample standard deviations of both variables. This reduces covariance to a range between -1 and 1, and it is now informative as to the magnitude of moves between two assets. Put simply correlation tells you:

1. whether two variables are related, and
2. the magnitude of their inter-relatedness

## Tool Options

The tool offers the user several options for determining the correlation coefficient:

* Pearson vs. Spearman
* Log vs. Arithmetic Returns
* Timeframe: 30/60/90/180/360 days
* Handing of Data Gaps: Linearly Interpolate or Exclude

## Pearson and Spearman Correlation

Our tool presents two options for correlation: Pearson and Spearman Correlation.

![Find this toggle below the chart](/files/-MOwpCYN2mhxCOdS8-S1)

The orthodox and conventional way of doing things in finance is to take the **Pearson** correlation of **logarithmic daily** asset **returns**, preferably over a long period. If you aren’t interested in getting into any additional complexity, you can stop there and use those settings on the charts.

(A common mistake in correlating assets is to use raw prices rather than returns. This is a mistake, as prices are often trended and non-stationary, meaning that you often get spurious positive correlations. Our tool uses the asset returns.)

### Pearson

Pearson correlation basically assumes that the relationship between the two variables is linear, and it measures it on this basis. If you have nonlinear yet meaningful relationships, Pearson will report a weak correlation, when in fact there may be something interesting going on behind the scenes.

One solution to this problem is using [log daily returns](https://mathbabe.org/2011/08/30/why-log-returns/), which helps in processing data, and has some other useful properties if the data is normally distributed.

### Spearman

To give our users an alternative, we introduced Spearman correlation.

Spearman correlation takes a ranking of all the data points in the sample, and then it runs a Pearson correlation on the rankings data. It then compares the two variables based on how much their *rankings* move together. This enables the ability to capture co-movements in datasets that are nonlinear. Spearman would find the correlation between a perfect exponential relationship as 1, whereas Pearson would declare it positive but not perfectly correlated.

For more on this, we suggest reading this [excellent breakdown](http://support.minitab.com/en-us/minitab-express/1/help-and-how-to/modeling-statistics/regression/supporting-topics/basics/a-comparison-of-the-pearson-and-spearman-correlation-methods/) in the differences between the two. To put it simply: if you think your variables are linearly related, and you want to measure the strength of those co-movements, use Pearson correlation. If you want to capture variables which move together, but not at a constant rate (as with an exponential relationship), consider Spearman correlation. Spearman makes no assumptions as to linearity but simply assesses the relationship in terms of whether one variable increases when the other increases, and vice versa.

## Arithmetic vs Logarithmic Returns

While Arithmetic Returns are easily understood, as mentioned above, there are some good reasons for using a Logarithmic Return in certain occasions. Our took allows you to choose Arithmetic or Logarithmic returns.

![Find this toggle below the chart](/files/-MOx42iaaCunyFwrgx37)

## Timeframe

The tool allows you to select the number of daily observations to consider when comparing returns to determine the data sets' correlation.

![Find the timeframe options below the chart](/files/-MOwy0amMnhQtaEs3HTf)

If, for example, you picked 180 days, the 180 daily returns prior to the point/date on the chart were considered when determining the correlation coefficient returned for the two data series at that point/date on the chart. In other words, the number you see for *today* refers to a sample of the previous 180 days.

Keep in mind that if you "exclude gaps" in the data set (see below), then the number of days selected will reflect only the number of days for which there are observations.

## Handling of Data Gaps

On occasion, you may want to compare a continuous data series with one with gaps (such as when you compare cryptoasset returns with a traditional index like S\&P500 that has no values on the weekends or holidays). The tool gives you two options for handling this:

* Linearly interpolate the data to derive a value for the data gap prior to calculating the returns
* Exclude the observations on the dates where one data series has a gap, but the other doesn't prior to calculating the returns (note: this results in fewer observations for the non-gapped series)

The tool will default to "excluding" data where gaps are identified. You can adjust this setting from the settings menu on the right toolbar.

<figure><img src="/files/aHBdA43MZW9sYdlEE2R9" alt=""><figcaption></figcaption></figure>

## Interpretation

Let’s say you select a Pearson correlation of the logarithmic returns for the previous 180 days. This number means “in the 180 days leading up to the point on the chart you’re looking at, the two assets that you have selected had co-movement in their daily returns of a magnitude corresponding to x.” If x is 1, their daily returns were perfectly positively correlated in the 180-day period leading up to the date where you observe the coefficient of 1. If x is 0.3, their returns moved together more often than not, but they weren’t particularly closely linked.

## Constraints

Attempting to predict the future by looking at historical returns is always somewhat fraught. There’s no guarantee that a historical correlation will persist into the future. Because of this, we recommend looking for useful correlations over longer periods.

Things that should grab your attention:

1. Very positive correlations between two assets, especially over longer periods of time. Consistently high correlations deserve investigation.
2. Persistent negative correlations of any sort are tremendously interesting, albeit rare. The strength of the signal increases with the quantity of historical evidence.

Be aware that different market phases exist. Longstanding correlations can break down during certain market conditions.

Try to discern when your correlation analysis holds little explanatory power. Avoid mistaking noise for signal. And use this tool with caution.

It’s also worth reading more about the statistical underpinnings of correlation measures. \\


# Embedded Charts

https\://charts.coinmetrics.io/embed/

You can use our powerful charting tool on your website. Our Embedded Charts allow you to add a plot of Coin Metrics’ data – similar to our [Network Data Charting](https://charts.coinmetrics.io/network-data/) tool. Just add a script to your page, specify your chart options, and voila.

For more details on how to use our Embedded Charts, go to [charts.coinmetrics.io/embed/](http://charts.coinmetrics.io/embed/).

And remember to follow our [attribution guidelines](https://coinmetrics.io/media/).


# Troubleshooting

#### Why am I unable to access certain metrics?

While we offer hundreds of metrics to our Community users, the metrics with a "lock" are Pro metrics. If you are a Pro user and you still see a "lock", this metric is likely not included with your subscription. If you see a "warning" sign, that metric is not compatible with any of the assets you've selected (e.g., UTXO metrics for a ETH).

#### How do I unselect an asset that was pre-selected in the chart?

When you first load the charting tool, several commonly used asset-metric pairs are in the top toolbar. The "greyed" out assets are not shown in the chart, but they are technically still selected. To unselect them, click "X" next to them to remove them.

#### Why can't I select Price USD or several of the other prices for GOLD (or LIBOR or VIX)?

The traditional indexes (Gold, Libor, etc.) only offer a single closing time. Therefore there is no Price USD (which is a 00:00 UTC price) for these indexes. The closing times/prices for each of these indexes are as follows:

| Index    | Available Price                          |
| -------- | ---------------------------------------- |
| S\&P 500 | USD 4:00pm New York Price / Index Value  |
| Gold     | USD 10:30am London Price / Index Value   |
| Dollar   | USD 12:00pm New York Price / Index Value |
| VIX      | USD 3:15pm Chicago Price / Index Value   |
| LIBOR    | USD 11:00am London Price / Index Value   |

#### How can I zoom into a specific date range?

You can leverage our pre-selected zooms (All, 1 month, 3 months, 1 year or YTD) or you can drag the handles on the grey bar to zoom in on your desired range. Unfortunately, these handles aren't particularly precise. If you aren't getting to the range you desire, you the Formula builder slice the series using the Subseries formula.

Bitcoin Price in USD from January 1, 2015 through January 31, 2015:`slice(BTC.PriceUSD, date(2015, 1, 1), date(2018, 1, 31))`

We hope to have a calendar selector in a future version of the tool.

#### I am unable to use MetricIDs containing decimal points in the Formula Builder. Help.

If a MetricID has a “.” (e.g., SplyAdrBalNtv0.1), use the AssetID.metric("Metric.ID") notation.

Example: `BTC.metric("SplyAdrValNtv.01")`

Note: quotation marks must be "straight quotes" and not "fancy quotes".


# Dashboard

https\://charts.coinmetrics.io/dashboard/

The Dashboard enables you to organize and quickly view your saved charts (from our [Data Visualization](/data-visualization) suite). You can create a thematic dashboard (e.g., a Mining Dashboard), an asset-specific dashboard (e.g., Favorite BTC charts) or really any mashup that you'd like.

When you arrive at our Dashboard home page, you will need to enter your API key in the top right corner (we will soon allow our community users to load the charts they've saved locally). **Note: This tool does require that you have previously created and saved charts.**

<figure><img src="/files/iNwKijkxYd44gHZbXGlj" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/BXC5eZsla6zIiZGi79BX" alt=""><figcaption></figcaption></figure>

## Creating a Dashboard

Upon entering your key, you will be able to create your personalized dashboard. Simply click the "Add Chart" button to add one of your pre-saved charts to a dashboard.

![](/files/q21DsmqrTLEx7aoysCpG)

If you do not have any saved charts, simply return to the Network Data Charts, Formula Builder or Correlation Chart by utilizing the top left menu and start making and saving some charts.

<figure><img src="/files/OSqTcpx4J6OHeNXToDJT" alt=""><figcaption></figcaption></figure>

Also, if you created your chart prior to July 2021, you will need to "re-save" them to enable our dashboard features. You will see older charts *greyed out* in the list of charts when importing (see *Needs to be resaved* below).

![](/files/G1mjHSSEbvpf0DC3I8Cb)

Click on the "chart" button corresponding to the chart type to easily navigate to the chart itself, re-save and return to the import chart dialog.

<figure><img src="/files/DwM8Migk2gVBCKHudGqr" alt=""><figcaption><p>Buttons to go to chart</p></figcaption></figure>

## Saving Dashboards

![](/files/tZOqp5ITxWr5NSAcsg7N)

You can save your Dashboard by selecting the "save" image on the right toolbar. There are two options for saving your dashboard:

* Save as... (only available to users with a Viz API key) - save your dashboard to your API key and reload it later from any device. Dashboards saved to your API key can be "named" (given a title).
* To local drive - save your dashboard to your local drive in a json format and reload it for later use.

<figure><img src="/files/nZGxtu3X5Y45EUr49kqH" alt=""><figcaption></figcaption></figure>

## Loading Dashboards

![](/files/01GZg1z7D4KJoFpSqDRW)

To load a previously saved dashboard, select the "folder" image on the right toolbar. If you saved your dashboard to your API key (to the Cloud), then it will show up in the list of dashboards. If you saved your dashboard to your local drive, then select load "From Local Drive".

<figure><img src="/files/0bx45Q3UvKCoqsCzrLLG" alt=""><figcaption></figcaption></figure>

If you load from local drive then find your file/dashboard using the explorer window.

## Configuring Dashboards

Once you've added a chart to a dashboard, you can continue adding charts using the "Add Chart +" button.

To get the Dashboard looking just the way you want it you can:

* Drag and drop charts to different positions in the Dashboard: simply click the header of a chart and drag to a new spot
* Delete charts: use the "X" in the top right hand corner of the chart
* Replace charts: use the swap button in the top right hand corner of the chart
* Maximize (to consume the entire width of the dashboard) or minimize (to consume half the dashboard width): use the minimize and maximize buttons in the top right hand corner of the chart

If you've made changes to the underlying charts that you'd like to see reflected in your dashboard, use the refresh button in the right hand toolbar.

![](/files/mBIrUuVkV14pWtuXP0dQ)

## Download Dashboard or Dashboard Charts

To download the dashboard or charts in your dashboard (either as PNGs, CSVs or XLS files), use the download button on the left toolbar.

![](/files/fdN2IXpwio0dUvs1N259)

You will then see several options. The first three options (CSV Files, Excel Files, PNG Files) download the information in the format selected for each **individual** chart. The fourth option (PNG Dashboard), downloads a PNG of the entire dashboard.

{% hint style="info" %}
Note: Please allow your dashboard to fully load before downloading.
{% endhint %}

<figure><img src="/files/Sg2fQyGky3SiYNboF8QJ" alt=""><figcaption></figcaption></figure>

## Sharing Dashboards

To share a dashboard, you must first "save" it. Once it is saved, the share button will activate.

<figure><img src="/files/5cXlgnorgVviIums5R1G" alt=""><figcaption></figcaption></figure>

Upon clicking on the button, you will see the chart's "shared" status. If this is a new chart, the status defaults to "sharing: off". If you'd like to share the dashboard, click the radio button and the chart will become sharable and "public". You can then use the copy button to obtain a shareable URL.

{% hint style="info" %}
Note: Individual charts within a dashboard that have not been made "shareable" will not be visible if they are included in a shared dashboard. You will first need to enable "sharing" on those specific charts if you want to share them.
{% endhint %}

<figure><img src="/files/ar87yjVvXGOciIvmkhB7" alt=""><figcaption></figcaption></figure>


# Troubleshooting

#### Why am I unable to add my chart to the dashboard (e.g., why is it greyed out when I try to load it)?

We had to add a new feature to our charts to enable the dashboard inclusion. As a result, charts saved prior to the release of the dashboards need to be "resaved". You can use the "open" feature in the dialog (the "folder") to navigate to your chart to resave. Once you've saved the chart, it will be selectable in the "load" dialog.

**Can I load charts saved locally (JSON) to the dashboard?**

Not yet, but we are working on it.


# Atlas Explorer

https\://atlas.coinmetrics.io/

## Searching: First Select an Asset

Click on the button to the left of the search field and select an asset from the drop down menu.

![](/files/I3MaOKkjhbu24Bx7IKsX)

Please note an orange "beaker" symbol to the right side of certain cryptoassets indicates that the particular cryptoasset is experimental and should be used with caution.

![](/files/MpbqrH1ARxYd4gv9WvzL)

## Searching Blocks

To search for a block, enter the block hash or block height after selecting the appropriate asset chain. Click the Search button to return results.

![](/files/wOeaLBc8n0vjO67ZJhYD)

The Search Results page will return the block and transactions applicable to that Block.

You can filter your Search Results by "Type" to see just the Block or just the Transactions.

The Search Results can also be downloaded for review by clicking the Download button to the right side of the screen from Search Results.

![](/files/RG678rS6r2fYxcKqdNnC)

Clicking on the Block will bring you to the Block Detail page. Clicking on a transaction will bring you to the Transaction Detail page.

The Block Detail page contains summary metrics attributed to the Block as well as all the Transactions applicable to the Block

The top portion of the page has summary metrics for the block.

* Transfer Value: The total amount transferred (sent) by all transactions in the block. The amount transferred is shown in both the native value of the coin and the current USD value.
* Number of Transactions: Total number of transactions in the block.
* Balance Updates: Number of changes to the balance of an account/address as a result of the transactions in the block.
* Total Fees: Sum of all fees paid within the block.
* Mean Fee: Average fee paid for a transaction within the block.
* New Coin Issuance: Reward issued to the miner/validator who produced the block.
* Block Size: Total size in bytes of all transactions included in the block.
* Block Virtual Size: A block weight/size measurement (for SegWit transactions) with one vsize/vbyte being equal to four weight units.
* Reported Time: Timestamp put in the block header by the miner/validator.
* Normalized Time: Timestamp that provides accurate ordering - i.e., it is always greater than or equal to the parent timestamp.

![](/files/z5s9BilfmSCXN62vfPXV)

The bottom portion of the page will display the Transactions for the given Block. Included here is high-level information for each transaction, like the amount of cryptoasset transferred for the given transaction (in native value and current USD value) and the fee for the transaction (in native value and current USD value). To download all the transactions for the block into a csv file, click the Download button. To sort transactions by one of the column headings, click the heading name.

For detailed transaction information, click the Transaction Hash hyperlink. This will bring you to the Transactions Details page.

![](/files/7SC1yzQpYCyuKL4Cr6C4)

The block height details on the right side of the screen show the applicable block height number as well as the Reported Time (Miner/Validator timestamp). The Parent Block can be navigated to by clicking the down arrow icon (or clicking on the Parent Hash hyperlink). The Child Block can be navigated to by clicking the up arrow icon. The Chain Tip can be navigated to by clicking the endpoint icon.

![](/files/xYsgdefkqda6h8KhdqJi)

## **Searching Addresses/Accounts**

To search for an address/account, enter the address after selecting the appropriate asset chain. Click the Search button to return results.

![](/files/VHVnNNpJnvMhP4h3hkfW)

The search will bring back the Address if it exists. High level information such as the current balance will be displayed amongst other data points. To get further details on the Address, click on the result to go to the Address Details page.

![](/files/beTTlN5wdbUtN521396h)

The Address Details page will display summary metrics for the address, balance updates, and a balance overtime graph.

The summary metrics for the address includes the following:

* Balance: Sum total value for this address/account (in both native units and current USD value).
* Number of Debits/Credits: Number of times this account/address has been debited and credited (i.e., number of balance updates).
* Creation Height: Number of confirmed blocks in the blockchain at the creation of account/address.
* Last Credit Height: Number of confirmed blocks in the blockchain at the last credit for account/address.
* Total Received: Sum total this account/address has been credited (in both native units and current USD value).
* Total Sent: Sum total this account/address has debited (in both native units and current USD value).
* Creation Time: Time at creation of account.
* First Received: Time of first credit.
* First Sent: Time of first debit.
* Last Received: Time of last credit.
* Last Sent: Time of last debit.

![](/files/R6xCqw1fCAYEdziFCPkY)

The lower half of the Address Details shows the Balance Updates. The Balance Updates are each debit and credit to the account/address (note: a transaction may have more than one balance update, so you may see the same transaction hash for more than one balance update). This section is essentially the book of record for the address/account, displaying information attributed to each transaction in a double-entry bookkeeping format.

All the Balance Updates for the Address can also be downloaded into a csv file by clicking the Download button. To sort balance updates by one of the column headings, click the heading name.

For further information on the Transaction containing the balance update, click on the Transaction Hash hyperlink, which will bring you to the Transaction Details page.

![](/files/z12Y9fCQkcs8QJNT5KRc)

The Balance Over Time on the right hand side is a graph depicting the amount of the native cryptoasset (blue line) in the address/account at the point in time on the horizontal axis. The account/address amount is also shown in USD price (the orange line) at the given time.

![](/files/pp9HwtGpoHGlLYJWfSc6)

For navigation within the graph you can do the below with the icons in the top right of the chart\*\*.\*\*

* Zoom to a specific time range with the Magnifying Glass icon
* Zoom in with the + icon
* Zoom out with the - icon
* To navigate left or right while zoomed in click the Pan Direction icon
* To restore the original scaling, click the autoscale button

## **Searching Transactions**

To search for a transaction, enter the transaction hash after selecting the appropriate asset chain. Click the Search button to return results.

![](/files/dEkqzDjjZKWF1VUjOnqm)

The search will bring back the Transaction if it exists. Clicking on the Transaction will bring you to the Transactions Detail page. The results can also be downloaded by clicking the Download button.

![](/files/0RSd5quaWGog8zppgMEq)

The Transaction Details page is going to display summary metrics, balance updates, and block height details.

The summary metrics for the transaction includes:

* Amount Transacted: Sum total in native units and current value USD of the amount transferred as part of this transaction
* Balance Updates: Number of individual account debits and credits as part of this transaction.
* Block Hash: Hash of the block (unique per block) containing the transaction.
* Parent Hash: Hash of the parent block - i.e., the block at the previous height.
* Normalized Time: Time of the transaction. This "normalized" timestamp provides accurate ordering - i.e., it is always greater than or equal to the parent block timestamp.

For further details on the transaction Block or its Parent, click on the Block Hash hyperlink which will bring you to the Block Details page.

![](/files/YwVju4r7hBVuxIB68uoN)

The Balance Updates section shows all the debits/credits to/from addresses/accounts for the given Transaction. Fees are All the debits/credits can be downloaded into a csv file by clicking the Download button.

For further information on the Addresses click on the Address Hash hyperlink which will bring you to the Address Details page.

![](/files/xvN4MpBXvJH5f54kgXyg)

The Block Height detail shows the details (fees, confor the block containing the transaction. The Parent Block can be navigated to by clicking the down arrow icon. The Child Block can be navigated to by clicking the up arrow icon. The Chain Tip can be navigated to by clicking the endpoint icon.

![](/files/JyYGIv6OuJFAGiJBOU3g)

## Icon Glossary

| Item                      | Applicable Icon                                                 |
| ------------------------- | --------------------------------------------------------------- |
| Block                     | <img src="/files/1DNJoFPu4YMd3OFap0E1" alt="" data-size="line"> |
| Address                   | <img src="/files/PAn0BzQU3Zt8iXeJz3lz" alt="" data-size="line"> |
| Transaction               | <img src="/files/hLVEOmt7Fq6VhtufGfgl" alt="" data-size="line"> |
| Info/Tool Tip             | <img src="/files/zesoqTUHDFxGT3E0hE7O" alt="" data-size="line"> |
| Experimental Crypto Asset | <img src="/files/TJ0ExvYVGWhXRf108LXC" alt="" data-size="line"> |
| Download                  | <img src="/files/WW9BAYlaLmwdKnuyGEvm" alt="" data-size="line"> |


# Network Data Pro Overview

Network Data Pro (NDP) provides insightful, aggregate network data metrics for a wide-variety of cryptoasset networks. We run blockchain nodes to collect and harmonize information from dozens of blockchains.

Our Network Data Pro metrics are aggregated at the asset level.

## Network Data Asset Coverage

Coin Metrics calculates Network Data Pro metrics for over 200 assets. A high-level view of our asset coverage can be found in the [CM Coverage Tool](https://coverage.coinmetrics.io/asset-metrics-v2/PriceUSD).

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/PriceUSD>" %}

\
The specific asset availability for each metric can be found by:

* querying our [`/catalog-v2/asset-metrics`](https://api.coinmetrics.io/v4/catalog-v2/asset-metrics) API endpoint **or**
* selecting a metric from our [Asset Metrics Coverage Page ](https://coverage.coinmetrics.io/asset-metrics-v2?)(Products = Network Data)

Similarly you can also view the metrics available for a particular asset by viewing our [Asset Coverage Page](https://coverage.coinmetrics.io/assets-v2) (select the asset of interest).

## Data Available at Asset Level

Network Data Pro metrics are available at the asset level through the [`/timeseries/asset-metrics`](https://docs.coinmetrics.io/api/v4#operation/getTimeseriesAssetMetrics) API endpoint.

Details on the specific metrics are described in the pages linked in this section.

## Change Log

{% updates format="full" %}
{% update date="2026-08-03" %}

## Added Network Data Metrics for New Solana Tokens

Added Network Data metrics for 11 new Solana tokens. For full asset coverage details refer to the [coverage page](https://coverage.coinmetrics.io/assets-v2).

<details>

<summary>Assets Added</summary>

* ARX\_SOL - Arcium SPL Token on Solana
* BP\_BACKPACK\_SOL - Backpack on Solana
* ECOR\_ECORPAY\_SOL - Ecorpay Token on Solana
* HOME\_SOL - Home on Solana
* HUMA\_SOL - Huma Finance on Solana
* LAYER\_SOLAYER\_SOL - Solayer on Solana
* MET\_METEORA\_SOL - Meteora on Solana
* PST\_PAYFI\_SOL - PayFi Strategy Token on Solana
* PUMP\_SOL - Pump on Solana
* WET\_HUMIDIFI\_SOL - HumidiFi on Solana
* WLFI\_SOL - World Liberty Financial on Solana

</details>
{% endupdate %}

{% update date="2026-08-03" %}

## Expanded CapMrktEstUSD to New Assets

Added estimated market cap to the following new assets:

<details>

<summary>Estimated Market Cap added to the following assets:</summary>

1. aztec
2. based
3. bill
4. birb
5. blend
6. bob\_buildonbitcoin
7. brev
8. ctr
9. esp
10. fight
11. fogo
12. imu
13. ir
14. mega
15. mezo
16. opg
17. rls
18. rnbw
19. robo
20. scor
21. thq
22. tria
23. u
24. us
25. usat
26. vooi
27. zama

</details>
{% endupdate %}

{% update date="2026-07-30" %}

## Added Pairwise Flow Metrics for USDC

Released directional pairwise flow metrics capturing value moving between tagged entities (e.g. Coinbase, Binance, Bitfinex, Kraken, OKX, KuCoin), including value that passes through untagged intermediary wallets before reaching its destination. Available at the 1d and 1h frequency for USDC on Ethereum. For details on the supported metrics please refer to the [Pairwise Flows](/network-data/network-data-overview/exchange/pairwise-flows) page. For details on asset coverage please refer to the [coverage page](https://coverage.coinmetrics.io/asset-metrics-v2/FlowFromCBSToBNBNtv).
{% endupdate %}

{% update date="2026-07-06" %}

## Expanded Estimated Market Cap Dominance to ETH

Added the `CapMrktEstDomPct` metric for Ethereum, previously only available for Bitcoin. For full coverage details please refer to the [coverage page](https://coverage.coinmetrics.io/asset-metrics-v2/CapMrktEstDomPct).
{% endupdate %}

{% update date="2026-06-22" %}

## Expanded Exchange Flows to New Stablecoins

Released exchange flow metrics at the 1d and 1h frequency for four stablecoin assets on Ethereum. For details on the supported metrics please refer to the [Exchange](/network-data/network-data-overview/exchange) page. For details on Exchange Flow metric coverage please refer to the [coverage page](https://coverage.coinmetrics.io/asset-metrics-v2/FlowInExNtv).

<details>

<summary>Assets Added:</summary>

* DAI - Dai
* USDE\_ETH - Ethena USDe ETH
* USDG\_ETH - Global Dollar on Ethereum
* USDS\_ETH - USDS on Ethereum

</details>
{% endupdate %}

{% update date="2026-06-09" %}

## Added Age-Band Realized Capitalization Metrics for Bitcoin

Added 13 new metrics that decompose Bitcoin's realized capitalization by UTXO age. Each band captures the realized cap attributable to UTXOs within that age range, and the sum of all bands equals `CapRealUSD`. For full details on the methodology please refer to the [metric documentation page](/network-data/network-data-overview/market/market-capitalization#cap-real-age-bands). For full coverage details refer to the [coverage page](https://coverage.coinmetrics.io/asset-metrics-v2/CapRealUSD1d).

<details>

<summary>Metrics Added:</summary>

* `CapRealUSD1d` - UTXOs aged 0-1 days
* `CapRealUSD1w` - UTXOs aged 1-7 days
* `CapRealUSD1m` - UTXOs aged 7-30 days
* `CapRealUSD3m` - UTXOs aged 30-90 days
* `CapRealUSD6m` - UTXOs aged 90-180 days
* `CapRealUSD1y` - UTXOs aged 180-365 days
* `CapRealUSD2y` - UTXOs aged 1-2 years
* `CapRealUSD3y` - UTXOs aged 2-3 years
* `CapRealUSD4y` - UTXOs aged 3-4 years
* `CapRealUSD5y` - UTXOs aged 4-5 years
* `CapRealUSD7y` - UTXOs aged 5-7 years
* `CapRealUSD10y` - UTXOs aged 7-10 years
* `CapRealUSD10yPlus` - UTXOs aged 10+ years

</details>
{% endupdate %}

{% update date="2026-05-26" %}

## Expanded CapMrktEstUSD to New Assets

Added estimated market cap to the following new assets:

<details>

<summary>Estimated Market Cap added to the following assets:</summary>

1. anime
2. aurora
3. b2
4. cpool
5. ctx
6. cyber
7. enso
8. holo
9. honey
10. huma
11. meme
12. mira
13. mplx
14. neon
15. newt
16. order
17. paal
18. plume
19. prompt
20. sats
21. sundog
22. xai

</details>
{% endupdate %}

{% update date="2026-05-01" %}

## Added Network Data Metrics for Stellar Tokens

Added Network Data metrics at the 1d frequency for 10 Stellar-based tokens, including stablecoins and tokenized real-world assets. For full asset coverage details refer to the [coverage page](https://coverage.coinmetrics.io/assets-v2).

Additionally, added support for aggregated tickers benji & wtgxx. benji aggregates benji\_eth + benji\_xlm. wtgxx aggregates wtgxx\_eth & wtgxx\_xlm.

<details>

<summary>Assets Added:</summary>

* BENJI\_XLM - Franklin OnChain U.S. Government Money Fund On Stellar
* CETES\_XLM - CETES Etherfuse on Stellar
* CRDYX\_XLM - WisdomTree Private Credit and Alternative Income Digital Fund on Stellar
* EURC\_XLM - EURO Coin on Stellar
* PYUSD\_XLM - Paypal USD on Stellar
* SPXUX\_XLM - WisdomTree 500 Digital Fund on Stellar
* TESOURO\_XLM - TESOURO Etherfuse on Stellar
* USDC\_XLM - USDC on Stellar
* USTRY\_XLM - USTRY Etherfuse on Stellar
* WTGXX\_XLM - WisdomTree Treasury Money Market Digital Fund on Stellar

</details>
{% endupdate %}

{% update date="2026-05-01" %}

## Expanded Exchange Flows to 1h for USDC on Base and USD1

Expanded exchange flow metrics for **usdc\_base.eth** and **usd1\_eth** to the 1h frequency. For details on Exchange Flow metric coverage please refer to the [coverage page](https://coverage.coinmetrics.io/asset-metrics-v2/FlowInExNtv).
{% endupdate %}

{% update date="2026-04-23" %}

## Expanded Exchange Flows to new Stablecoins

Released exchange flows for **usdc\_base.eth** and **usd1\_eth** at the 1d frequency. For details on the supported metrics please refer to the [Exchange](/network-data/network-data-overview/exchange)page. For details on Exchange Flow metric coverage please refer to the [coverage page](https://coverage.coinmetrics.io/asset-metrics-v2/FlowInExNtv).
{% endupdate %}

{% update date="2026-04-22" %}

## Added Tokenized RWA Assets on Ethereum to ND Metrics

Added Network Data metrics for tokenized Real World Asset (RWA) tokens on Ethereum, including tokenized US Treasury funds and money market funds. For full asset coverage details refer to the [coverage page](https://coverage.coinmetrics.io/assets-v2).

<details>

<summary>RWA tokens added:</summary>

1. BENJI\_ETH - Franklin OnChain U.S. Government Money Fund on Ethereum
2. FDIT\_ETH - Fidelity Digital Interest Token on Ethereum
3. JAAA\_ETH - Janus Henderson Anemoy AAA CLO Fund Token on Ethereum
4. JTRSY\_ETH - Janus Henderson Anemoy Treasury Fund on Ethereum
5. OUSG\_ETH - Ondo Short-Term U.S. Government Bond Fund on Ethereum
6. TBILL\_ETH - OpenEden T-Bills on Ethereum
7. USDY\_ETH - Ondo U.S. Dollar Yield on Ethereum
8. USTB\_ETH - Superstate Short Duration U.S. Government Securities Fund on Ethereum
9. VBILL\_ETH - VanEck Treasury Fund on Ethereum

</details>
{% endupdate %}

{% update date="2026-04-16" %}

## Added BUIDL\_SOL to Network Data Metrics

Added metrics support for BlackRock's BUIDL tokenized money market fund on Solana (`buidl_sol`). For full asset coverage details refer to the [coverage page](https://coverage.coinmetrics.io/assets-v2/buidl_sol).
{% endupdate %}

{% update date="2026-04-07" %}

## Added Network Data Metrics for BNB Smart Chain (Experimental)

Added Network Data metrics for the BNB Smart Chain (`bnb_bsc`) at the 1d frequency for a set of MVP metrics. For full asset coverage details refer to the [coverage page](https://coverage.coinmetrics.io/assets-v2/bnb_bsc).
{% endupdate %}

{% update date="2026-04-02" %}

## Added Huobi Exchange Flows for ETH

Released exchange flow metrics for ETH on the Huobi (HTX) exchange. For details on the supported metrics please refer to the [Exchange](/network-data/network-data-overview/exchange) page. For details on Exchange Flow metric coverage please refer to the [coverage page](https://coverage.coinmetrics.io/asset-metrics-v2/FlowInExNtv).
{% endupdate %}

{% update date="2026-04-02" %}

## Expand CapMrktEstUSD to New Assets

Added estimated market cap to the following new assets:

<details>

<summary>Estimated Market Cap added to the following assets:</summary>

1. apr
2. dmc
3. obol
4. pro
5. ssv
6. tut
7. zerebro

</details>
{% endupdate %}

{% update date="2026-04-01" %}

## Added xStocks on Ethereum to ND Metrics

Added Network Data metrics for xStock tokenized equities on Ethereum for 79 new assets. For full asset coverage details refer to the [coverage page](https://coverage.coinmetrics.io/assets-v2).

<details>

<summary>xStock tokens on Ethereum added:</summary>

1. AAPLX\_ETH - Apple xStock on Ethereum
2. ABBVX\_ETH - AbbVie xStock on Ethereum
3. ABTX\_ETH - Abbott xStock on Ethereum
4. ACNX\_ETH - Accenture xStock on Ethereum
5. AMBRX\_ETH - Ambarella xStock on Ethereum
6. AMDX\_ETH - AMD xStock on Ethereum
7. AMZNX\_ETH - Amazon xStock on Ethereum
8. APPX\_ETH - Appian xStock on Ethereum
9. AVGOX\_ETH - Avago xStock on Ethereum
10. AZNX\_ETH - AstraZeneca xStock on Ethereum
11. BACX\_ETH - Bank of America xStock on Ethereum
12. BMNRX\_ETH - Bowman xStock on Ethereum
13. BRK.BX\_ETH - Berkshire Hathaway xStock on Ethereum
14. BTBTX\_ETH - Bit Digital xStock on Ethereum
15. BTGOX\_ETH - Bitgold xStock on Ethereum
16. CMCSAX\_ETH - Comcast xStock on Ethereum
17. COINX\_ETH - Coinbase xStock on Ethereum
18. COPXX\_ETH - ConocoPhillips xStock on Ethereum
19. CRCLX\_ETH - Circle xStock on Ethereum
20. CRMX\_ETH - Salesforce xStock on Ethereum
21. CRWDX\_ETH - CrowdStrike xStock on Ethereum
22. CSCOX\_ETH - Cisco xStock on Ethereum
23. CVXX\_ETH - CVS xStock on Ethereum
24. DFDVX\_ETH - DeFi Dev xStock on Ethereum
25. DHRX\_ETH - Danaher xStock on Ethereum
26. GLDX\_ETH - Gold ETF xStock on Ethereum
27. GMEX\_ETH - GM xStock on Ethereum
28. GOOGLX\_ETH - Alphabet xStock on Ethereum
29. GSX\_ETH - Goldman Sachs xStock on Ethereum
30. HDX\_ETH - Home Depot xStock on Ethereum
31. HONX\_ETH - Honeywell xStock on Ethereum
32. HOODX\_ETH - Robinhood xStock on Ethereum
33. IBMX\_ETH - IBM xStock on Ethereum
34. IEMGX\_ETH - iShares Emerging Markets ETF xStock on Ethereum
35. IJRX\_ETH - iShares Small Cap ETF xStock on Ethereum
36. INTCX\_ETH - Intel xStock on Ethereum
37. IWMX\_ETH - iShares Russell 2000 ETF xStock on Ethereum
38. JNJX\_ETH - Johnson & Johnson xStock on Ethereum
39. JPMX\_ETH - JPMorgan xStock on Ethereum
40. KOX\_ETH - Coca-Cola xStock on Ethereum
41. KRAQX\_ETH - Kraken xStock on Ethereum
42. LINX\_ETH - Linkedin xStock on Ethereum
43. LLYX\_ETH - Lilly xStock on Ethereum
44. MAX\_MASTERCARDXSTOCK\_ETH - Mastercard xStock on Ethereum
45. MCDX\_ETH - McDonald's xStock on Ethereum
46. MDTX\_ETH - Medtronic xStock on Ethereum
47. MRKX\_ETH - Merck xStock on Ethereum
48. MRVLX\_ETH - Marvell xStock on Ethereum
49. MSFTX\_ETH - Microsoft xStock on Ethereum
50. MSTRX\_ETH - MicroStrategy xStock on Ethereum
51. NFLXX\_ETH - Netflix xStock on Ethereum
52. NVDAX\_ETH - NVIDIA xStock on Ethereum
53. NVOX\_ETH - Novo Nordisk xStock on Ethereum
54. OPENX\_ETH - OpenAI xStock on Ethereum
55. ORCLX\_ETH - Oracle xStock on Ethereum
56. PALLX\_ETH - Palladium ETF xStock on Ethereum
57. PEPX\_ETH - PepsiCo xStock on Ethereum
58. PFEX\_ETH - Pfizer xStock on Ethereum
59. PGX\_ETH - Procter & Gamble xStock on Ethereum
60. PLTRX\_ETH - Palantir xStock on Ethereum
61. PMX\_ETH - Philip Morris xStock on Ethereum
62. PPLTX\_ETH - PPL xStock on Ethereum
63. QQQX\_ETH - Nasdaq 100 ETF xStock on Ethereum
64. SCHFX\_ETH - Schwab International ETF xStock on Ethereum
65. SLVX\_ETH - Silver ETF xStock on Ethereum
66. SPYX\_ETH - S\&P 500 ETF xStock on Ethereum
67. STRCX\_ETH - Strategy xStock on Ethereum
68. TBLLX\_ETH - T-Bill xStock on Ethereum
69. TMOX\_ETH - Thermo Fisher xStock on Ethereum
70. TONXX\_ETH - TON xStock on Ethereum
71. TQQQX\_ETH - 3x Nasdaq ETF xStock on Ethereum
72. TSLAX\_ETH - Tesla xStock on Ethereum
73. UNHX\_ETH - UnitedHealth xStock on Ethereum
74. VTIX\_ETH - Viti xStock on Ethereum
75. VTX\_ETH - Vertex xStock on Ethereum
76. VX\_ETH - Vega xStock on Ethereum
77. WMTX\_WALMARTXSTOCK\_ETH - Walmart xStock on Ethereum
78. WTGXX\_ETH - WisdomTree Government Money Market Digital Fund on Ethereum
79. XOMX\_ETH - ExxonMobil xStock on Ethereum

</details>
{% endupdate %}

{% update date="2026-03-31" %}

## Expanded CapMrktEstUSD to 150+ New Assets

Added estimated market cap to over 150 new assets.

<details>

<summary>Estimated Market Cap added to the following assets:</summary>

a2z\
a8\
ace\_fusionist\
acs\
act\
acx\
aero\
aevo\
aixbt\
allo\
arty\
awe\
b3\
ban\
bananas31\
babydoge\
beamx\
bigtime\
blast\
bluai\
blue\
bmt\
camp\
carv\
cat\
cati\
cetus\
cgpt\
chillguy\
clanker\
cloud\
cookie\
coq\
cow\
cspr\
cta\
cxt\
degen\
dogs\
dolo\
dood\
duck\
dym\
ela\
elizaos\
ept\
era\
es\
f\
fhe\
fitfi\
flock\
fort\
g\
giga\
goat\
gps\
griffain\
gtai\
gun\
haedal\
high\
hippo\
hmstr\
home\
house\
hpos10i\
htx\
hyper\
init\
io\
j\
kas\
kernel\
lat\
linea\
lista\
lmwr\
lrds\
manta\
mavia\
melania\
memefi\
mew\
michi\
mmt\
mubarak\
naka\
navx\
neirocto\
nil\
nom\_nomina\
ntrn\
obt\
one\_harmony\
open\_openledger\
parti\
planck\
polyx\
ponke\
prcl\
puffer\
rdnt\
resolv\
rez\
rss3\
saga\
sapien\
saros\
sca\
sfund\
shell\
sign\
solv\
somi\
sonic\
soph\
spa\
sqd\
sto\
swarms\
sweat\
swell\
sxt\
syn\
synd\
taiko\
time\
token\
towns\
trump\
trust\
turbo\
usual\
uxlink\
vanry\
velo\_velodromefinance\
vic\
vine\
vinu\
vvv\
wct\
well\
win\_wink\
wmtx\
xan\
xch\
xion\
xter\
yb\
zbt\
zeus\
zig\
zkc\
zora\
zrx

</details>
{% endupdate %}

{% update date="2026-03-16" %}

## Added XRP Token Metrics

Added Network Data metrics support for tokens on the XRP Ledger. For full asset coverage details refer to the [coverage page](https://coverage.coinmetrics.io/assets-v2).

<details>

<summary>XRP tokens added:</summary>

* EURCV\_XRP - EUR CoinVertible on XRP
* OUSG\_XRP - Ondo Short-Term U.S. Government Bond Fund on XRP
* RLUSD\_XRP - Ripple USD on XRP
* TBILL\_XRP - OpenEden T-Bill on XRP
* USDC\_XRP - USD Coin on XRP
* XSGD\_XRP - XSGD on XRP

</details>
{% endupdate %}

{% update date="2026-03-10" %}

## Extended Economically Active Addresses to BTC

Extended the `AdrActUSD1Cnt` metric to Bitcoin, capturing addresses that transacted at least 1 USD in a single transfer. This metric was previously available for Ethereum and Solana. For full details refer to the [documentation](https://docs.coinmetrics.io/network-data/network-data-overview/addresses/active-addresses#economically-active-addresses). For full coverage details refer to the [coverage page](https://coverage.coinmetrics.io/asset-metrics-v2/AdrActUSD1Cnt).
{% endupdate %}

{% update date="2026-02-24" %}

## Added Economically Relevant Addresses

Added a new metric for Ethereum and Solana that captures the count of economically relevant addresses, defined as any address that transacted at least 1 USD in a single transfer - **`AdrActUSD1Cnt`**. For full details and examples refer to the [documentation](https://docs.coinmetrics.io/network-data/network-data-overview/addresses/active-addresses#economically-active-addresses). For full coverage details refer to the coverage page [here](https://coverage.coinmetrics.io/asset-metrics-v2/AdrActUSD1Cnt).
{% endupdate %}

{% update date="2026-02-17" %}

## Release Hourly Exchange and ETF Flow Metrics

Expanded our exchange flow and BTC ETF coverage with hourly flows metrics for all existing assets and exchanges/ETFs. For the full list of exchange please refer to our [Exchange coverage](/network-data/network-data-overview/exchange#on-chain-exchange-coverage) and for a full coverage of our ETF coverage please refer to our [ETF Coverage](/network-data/network-data-overview/exchange-traded-fund#on-chain-etf-coverage). For details on asset coverage for Exchange Flows and ETF Flows metric please refer to our coverage page ([Exchanges](https://coverage.coinmetrics.io/asset-metrics-v2/FlowInExNtv), [ETFs](https://coverage.coinmetrics.io/asset-metrics-v2/FlowInEtfNtv))
{% endupdate %}

{% update date="2026-01-19" %}

## Released Exchange Flows for USDT\_ETH

Released exchange flows for the usdt\_eth asset at the 1d frequency. For details on the supported metrics please refer to the [Exchange](/network-data/network-data-overview/exchange)page. For details on Exchange Flow metric coverage please refer to the [coverage page](https://coverage.coinmetrics.io/asset-metrics-v2/FlowInExNtv).
{% endupdate %}

{% update date="2026-01-12" %}

## $FLOW asset categorized as experimental

All `flow` assets and metrics have been categorized as experimental due to ongoing issues with reliably of the nodes. This imacts the `flow`, `flow_evm` and `flow_native` tickers.
{% endupdate %}

{% update date="2026-01-08" %}

## Added Real Time Exchange Flows for ERC20s

Added block by block support for Exchange flow metrics for USDC\_ETH & PYUSD\_ETH. For details on Exchange Flow metric coverage please refer to the [coverage page](https://coverage.coinmetrics.io/asset-metrics-v2/FlowInExNtv). For details on exchange metrics please refer to the [Exchange](/network-data/network-data-overview/exchange)documentation page.
{% endupdate %}

{% update date="2026-01-05" %}

## Expand CapMrktEstUSD to new Assets

Added estimated market cap to new assets

<details>

<summary>Estimated Market Cap added to the following assets:</summary>

1. a
2. adi
3. beat
4. cusd
5. dog
6. fbtc
7. frxusd
8. icnt
9. lit
10. me
11. moodeng
12. pieverse
13. prime
14. rlp
15. sdai
16. soon
17. stable
18. wsol
19. xpr

</details>
{% endupdate %}

{% update date="2025-12-08" %}

## Added CapMrktEstUSD for 85 New Asset

Added Estimated Market Cap for 85 new assets to fill out top 500 by market cap.

<details>

<summary>Estimated market cap added to the following assets:</summary>

0g\
2z\
ab\
alch\
aleo\
apepe\
aster\
ath\
ausd\
avnt\
b\
bard\
bera\
bfusd\
bianrensheng\
bio\
bmx\
bnsol\
cheems\
dbr\
deep\
drift\
eigen\
fartcoin\
ff\
fluid\
folks\
frxeth\
giggle\
gomining\
grass\
h\
hsk\
hype\
ip\
kaia\
kaito\
kite\
kmno\
kta\
lbtc\
lseth\
merl\
met\_meteora\
meta\_metadao\
meth\
moca\
mon\_monad\
morpho\
move\
myx\
npc\
nxpc\
pengu\
pippin\
pnut\
prove\
pump\
qubic\
recall\
red\
river\
s\
sahara\
sky\_sky\
snek\
solvbtc\
soso\
spx\
strx\
syrup\
toshi\
ub\
uds\
usdr\
useless\
vana\
virtual\
vsn\
wal\
wbeth\
wlfi\
xpl\
zano\
zbcn

</details>
{% endupdate %}

{% update date="2025-12-03" %}

## Added xStocks on Solana to ND Metrics

Added xStocks on Solana to Network Data Metrics.

<details>

<summary>xStocks on Solana added:</summary>

* AAPLX\_SOL - Apple xStock on Solana
* AMZNX\_SOL - Amazon xStock on Solana
* COINX\_SOL - Coinbase xStock on Solana
* CRCLX\_SOL - Circle xStock on Solana
* GOOGLX\_SOL - Alphabet xStock on Solana
* HOODX\_SOL - Robinhood xStock on Solana
* MAX\_MASTERCARDXSTOCK\_SOL - Mastercard xStock on Solana
* MSFTX\_SOL - Microsoft xStock on Solana
* MSTRX\_SOL - MicroStrategy xStock on Solana
* NVDAX\_SOL - NVIDIA xStock on Solana
* QQQX\_SOL - Nasdaq xStock on Solana
* SPYX\_SOL - SP500 xStock on Solana
* TSLAX\_SOL - Tesla xStock on Solana

</details>
{% endupdate %}

{% update date="2025-11-19" %}

## Release Exchange Flows for USDC & PYUSD on Ethereum

Added Exchange flow metrics for USDC\_ETH and PYUSD\_ETH at the daily frequency. For details on Exchange Flow metric coverage please refer to the [coverage page](https://coverage.coinmetrics.io/asset-metrics-v2/FlowInExNtv). For details on exchange metrics please refer to the [Exchange](/network-data/network-data-overview/exchange)documentation page.
{% endupdate %}

{% update date="2025-11-10" %}

## Added New Assets to ND Metrics

<details>

<summary>New Assets Added</summary>

arb\_arb.eth\
audio\_eth\
axs\_eth\
band\_eth\
chz\_eth\
eurs\_eth\
ftm\_eth\
gbpt\_eth\
gho\_eth\
grt\_eth\
gyen\_eth\
idrt\_eth\
musd\_metamask\_eth\
rad\_eth\
rlusd\
rlusd\_eth\
sdai\_eth\
slp\_eth\
susde\_eth\
susdf\_eth\
toke\_eth\
usd0\
usd0\_eth\
usd1\
usd1\_eth\
usdcv\_eth\
usdf\_eth\
usdg\
usdg\_eth\
usds\
usds.e\_arb.eth\
usdx\_eth\
xidr\_eth\
xsgd\_eth

</details>
{% endupdate %}
{% endupdates %}


# Availability

Availability metrics describe the completeness and coverage of Coin Metrics data for a given asset and interval. They are useful for auditing data pipelines and understanding when metric calculations have finished processing.

[**Asset Completion Time**](/network-data/network-data-overview/availability/asseteodcompletiontime)

* AssetEODCompletionTime

[**Aggregation**](/network-data/network-data-overview/availability/aggregation)

* AggAssetCnt


# Asset Completion Time

## Definition

The time that the last metric for the asset was calculated, indicating that all metrics for that asset have been calculated.

| Name            | MetricID               | Unit         | Interval |
| --------------- | ---------------------- | ------------ | -------- |
| Completion Time | AssetEODCompletionTime | EPOC seconds | 1d       |

## Details

Our metric calculation begins at 00:00 UTC. Given that our asset metrics finish calculating at different times each asset AND each asset's last metric calculation will occur at different times, we've created a metric so users can determine when the entire metric set for a given asset is fully calculated (has completed its daily processing).

The result provides a "time" string in EPOC seconds.

## Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/AssetEODCompletionTime>" %}


# Aggregation

## Definition

The count of underlying assets aggregated to compute metrics for that aggregate asset in that interval.

| Name                    | MetricID    | Unit   | Interval       |
| ----------------------- | ----------- | ------ | -------------- |
| Aggregated Assets Count | AggAssetCnt | Assets | 1 day, 1 block |

## Details

* Coin Metrics computes metrics for aggregate assets (e.g. combined or composite assets) by aggregating data across a set of underlying constituent assets.
* `AggAssetCnt` reports how many underlying assets were included in that aggregation for a given interval.
* This metric is useful for auditing completeness — if the count drops unexpectedly, it may indicate that one or more underlying assets did not report data for that interval.

## Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/AggAssetCnt>" %}


# Addresses

Address metrics provide a proxy for **users** on a blockchain/network.

Increases in the number of active addresses suggests more users of the network. Similarly, looking at addresses by tranche/cohort (e.g., counts of addresses with balances >X) can give a *sense* for the *type* of users in a blockchain network.

## Metrics

[Active Addresses](/network-data/network-data-overview/addresses/active-addresses)

* AdrActCnt
* AdrAct7dCnt
* AdrAct30dCnt
* AdrActContCnt
* AdrActRecCnt
* AdrActSentCnt
* WalActCnt
* WalActRecCnt
* WalActSentCnt

[Active Addresses](/network-data/network-data-overview/addresses/address-balances)

* AdrBal1in100KCnt
* AdrBal1in100MCnt
* AdrBal1in10BCnt
* AdrBal1in10KCnt
* AdrBal1in10MCnt
* AdrBal1in1BCnt
* AdrBal1in1KCnt
* AdrBal1in1MCnt
* AdrBalCnt
* AdrBalNtv0.001Cnt
* AdrBalNtv0.01Cnt
* AdrBalNtv0.01Cnt
* AdrBalNtv100Cnt
* AdrBalNtv100KCnt
* AdrBalNtv10Cnt
* AdrBalNtv10KCnt
* AdrBalNtv1Cnt
* AdrBalNtv1KCnt
* AdrBalNtv1MCnt
* AdrBalUSD100Cnt
* AdrBalUSD100KCnt
* AdrBalUSD10Cnt
* AdrBalUSD10KCnt
* AdrBalUSD10MCnt
* AdrBalUSD1Cnt
* AdrBalUSD1KCnt
* AdrBalUSD1MCnt

[New Addresses](/network-data/network-data-overview/addresses/new-addresses)

* AdrNewBalCnt
* AdrNewCnt


# Active Addresses

## Active Addresses

### Contents

* [Active Monthly, Weekly, Daily Addresses (AdrActXdCnt)](#adract)
* [Active Addresses (Sent) (AdrActSentCnt)](#adractsent)
* [Active Addresses (Received) (AdrActRecCnt)](#adractrec)
* [Active Smart Contract Addresses (AdrActContCnt)](#adractcont)
* [Active Blob Addresses (AdrActBlobCnt)](#adractcont-1)
* [Active Blob Addresses (Sent) (AdrActBlobSendCnt)](#adractcont-2)
* [Active Blob Addresses (Received) (AdrActBlobRecCnt)](#adractcont-3)
* [MEV Active Address Count (MevAdrActCnt)](#adractcont-4)
* [Economically Active Addresses (AdrActUSDXCnt)](#economically-active-addresses)

### **Interpretation**

Active addresses is a popular measure to proxy the number of users on a blockchain, since it is typically less sensitive to stress-tests (which often focus on transaction count). However, active addresses inherit idiosyncrasies from the structure of the particular blockchain, and care must be taken to understand structural differences in active address counts. In blockchains where address creation is cheap or free, and transacting is cheap or free, active addresses can still be trivially forged.

## Active Monthly, Weekly, Daily Addresses <a href="#adract" id="adract"></a>

<table><thead><tr><th width="177">Name</th><th width="157">MetricID</th><th width="124">Unit</th><th>Interval</th></tr></thead><tbody><tr><td><a href="#active">Active Monthly Addresses</a></td><td><a href="https://coverage.coinmetrics.io/search-results?query=AdrAct30dCnt">AdrAct30dCnt</a></td><td>Addresses</td><td>1 Day</td></tr><tr><td><a href="#active">Active Weekly Addresses</a></td><td><a href="https://coverage.coinmetrics.io/search-results?query=AdrAct7dCnt">AdrAct7dCnt</a></td><td>Addresses</td><td>1 Day</td></tr><tr><td><a href="#active">Active Daily Addresses</a></td><td><a href="https://coverage.coinmetrics.io/search-results?query=AdrActCnt">AdrActCnt</a></td><td>Addresses</td><td>1 Day</td></tr></tbody></table>

### Definition

The sum count of unique addresses that were active in the network (either as a recipient or originator of a ledger change) in the trailing X days up to the end of that interval. All parties in a ledger change action (recipients and originators) are counted. Individual addresses are not double-counted if active several times in the considered interval.

### Details

* Active addresses count the number of unique addresses that participated in a ledger change.
* Ledger changes can include activities such as transacting, signing of blocks, claiming of mining or staking rewards, voting, creating accounts, and more dependent on whether the underlying protocol supports the activity (different protocols vary in the types of activities that are supported).
* All participants of a ledger change activity are included.
* If an address was active multiple times during the aggregation interval (e.g., 30 days), it is counted only once.
* For ETH, miners receiving fees from the original sender of a failed transaction are counted as active (receiving) addresses.
* Any address that's active (even if sending 0 ETH, or sending ETH to itself, or involved in failed transactions) is counted towards active addresses.
* The null address (issuance address) is excluded from this metric.

### **Asset-Specific Details**

* This metric is not available for assets that have full privacy, like Monero and Grin. For assets that have opt-in privacy features, like ZCash, it only takes the non-private activities into account.
* For Solana, includes both owner accounts as well as sub accounts

### Coverage

* [AdrAct30dCnt](https://coverage.coinmetrics.io/search-results?query=AdrAct30dCnt)
* [AdrAct7dCnt](https://coverage.coinmetrics.io/search-results?query=AdrAct7dCnt)
* [AdrActCnt](https://coverage.coinmetrics.io/search-results?query=AdrActCnt)

## Economically Active Addresses <a href="#economically-active-addresses" id="economically-active-addresses"></a>

<table><thead><tr><th width="177">Name</th><th width="157">MetricID</th><th width="124">Unit</th><th>Interval</th></tr></thead><tbody><tr><td><a href="https://coverage.coinmetrics.io/asset-metrics-v2/AdrActUSD1Cnt">Economically Active Addr Cnt >1 USD</a></td><td><a href="https://coverage.coinmetrics.io/asset-metrics-v2/AdrActUSD1Cnt">AdrActUSD1Cnt</a></td><td>Addresses</td><td>1 day</td></tr></tbody></table>

### Definition

The sum count of unique addresses that were active in the network (either as a recipient or originator of a ledger change) that interval for any transfer worth more than the USD threshold for that metric in native units. All parties in a ledger change action (recipients and originators) are counted. Individual addresses are not double-counted if previously active.

### Details

* The same [details](#details) as for AdrActCnt apply to this metric with the exception of the USD threshold being added to this metric.
* To be counted, an address needs to have at least one ledger change that is larger than the threshold for the metric. The USD equivalent price is calculated based on the `PriceUSD` metric for the given day.

### Examples

* Address A has participated in 10 ledger changes for BTC, each for 1 BTC on a given day. The PriceUSD value on that day for BTC is $70,000.
  * Address A is counted as 1 address for the AdrActUSD1Cnt for BTC
* Address B has 1 ledger change for BTC for 0.000001 at a PriceUSD of $70,000. This ledger change is worth $0.07. For this metric this address will not be counted.
* Address C has 10 ledger changes in the given interval that are each for the equivalent of $0.11. While the sum of these ledger changes adds up to $1.10 the address is not counted since none of the individual transfers is worth more than the threshold of 1 USD.

### Coverage

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/AdrActUSD1Cnt>" %}

## Active Addresses (Sent) <a href="#adractsent" id="adractsent"></a>

<table><thead><tr><th width="177">Name</th><th width="157">MetricID</th><th width="124">Unit</th><th>Interval</th></tr></thead><tbody><tr><td><a href="#sent">Active Addresses (Sent)</a></td><td><a href="https://coverage.coinmetrics.io/search-results?query=AdrActSentCnt">AdrActSentCnt</a></td><td>Addresses</td><td>1 day, 1 hour</td></tr></tbody></table>

### Definition

The sum count of unique addresses that were active in the network (as a sender of a ledger change) that day. Individual destination addresses are counted. Individual addresses are not double-counted if previously active.

### **Details**

* Active Addresses (sent) is the sum count of unique addresses that where the sending side of a ledger change
* For this unadjusted version of the metric, all ledger change scenarios are considered.
* Such ledger changes can include mining, staking, transacting, account creation, etc..
* If an address was active multiple times as sender during that interval, it is counted only once.
* The null address (issuance address) is excluded from this metric.

### **Asset-Specific Details**

* This metric is not available for assets that have full privacy, like Monero, Grin. For assets that have opt-in privacy features, like ZCash, it only takes the non-private activities into account.
* For SOL, all accounts that sent SOL tokens in the period. Includes owner accounts and sub accounts. Owner accounts are always counted since they are paying and signing for the transaction, even if the owner account itself doesn't send more SOL than just the fee.
* For SPL tokens, all accounts that sent the SPL token in the period. This includes validators & delegators. Includes owner accounts and sub accounts.

### **Examples**

In a given day:

* Address A mines 10 coins
  * A was recipient, no sender
* Address B sends 2 coins to each C and D
  * C and D were recipients, B was sender
* Address D delegates 20 coins to E
  * D is the sender, E is recipient
* Address A burns 1 coin
  * A is the sender, no recipient
* Address F votes on a protocol change
  * F is the sender/initiator

We would count as active senders: A, B, D and F. The value of the metric would therefore be: 4.

### Coverage

* [AdrActSentCnt](https://coverage.coinmetrics.io/search-results?query=AdrActSentCnt)

## Active Addresses (Received) <a href="#adractrec" id="adractrec"></a>

<table><thead><tr><th width="177">Name</th><th width="157">MetricID</th><th width="124">Unit</th><th>Interval</th></tr></thead><tbody><tr><td><a href="#received">Active Addresses (Received)</a></td><td><a href="https://coverage.coinmetrics.io/search-results?query=AdrActRecCnt">AdrActRecCnt</a></td><td>Addresses</td><td>1 day, 1 hour</td></tr></tbody></table>

### **Definition**

The sum count of unique addresses that were active in the network (as a recipient of a ledger change) that day. Individual destination addresses are counted. Individual addresses are not double-counted if previously active.

### **Details**

* Active Addresses (Received) is the sum count of unique addresses that where the receiving end of a ledger change
* For this unadjusted version of the metric, all ledger change scenarios are considered.
* Such ledger changes can include mining, staking, transacting, account creation, etc..
* If an address was active multiple times as recipient during that interval, it is counted only once.
* For ETH, miners receiving fees from the original sender of a failed transaction are counted as active receiving addresses.
* The null address (issuance address) is excluded from this metric.

### **Asset-Specific Details**

* This metric is not available for assets that have full privacy, like Monero, Grin. For assets that have opt-in privacy features, like ZCash, it only takes the non-private activities into account.
* For SOL, all accounts that received SOL tokens (balance updates or rewards) in the period. This includes validators & delegators. Includes owner accounts and sub accounts.
* For SPL tokens, all accounts that received the SPL token in the period. This includes validators & delegators. Includes owner accounts and sub accounts.

### **Examples**

In a given day:

* Address A mines 10 coins
  * A was recipient, no sender
* Address B sends 2 coins to each C and D
  * C and D were recipients, B was sender
* Address D delegates 20 coins to E
  * D is the sender, E is recipient
* Address A burns 1 coin
  * A is the sender, no recipient
* Address F votes on a protocol change
  * F is the sender/initiator

We would count as active recipients: A, C, D and E. The value of the metric would therefore be: 4.

### Coverage

* [AdrActRecCnt](https://coverage.coinmetrics.io/search-results?query=AdrActRecCnt)

## Active Smart Contract Addresses <a href="#adractcont" id="adractcont"></a>

<table><thead><tr><th width="177">Name</th><th width="157">MetricID</th><th width="124">Unit</th><th>Interval</th></tr></thead><tbody><tr><td><a href="#smart">Active Smart Contract Addr Cnt</a></td><td><a href="https://coverage.coinmetrics.io/search-results?query=AdrActContCnt">AdrActContCnt</a></td><td>Smart Contract Addresses</td><td>1 day</td></tr></tbody></table>

### Definition

The sum count of unique smart contract addresses that were active in the network (either as a recipient or originator of a ledger change) that interval. All unique smart contracts involved in a ledger change action (recipients and originators) are counted. This metric does not double-count contracts. In other words, if a contract has been deemed active by being part of a ledger change, it is not counted again if is subsequently invoked during the same time interval.

### Details

* Active smart contact [address](/network-data/on-chain-basics#address) count represents the number of unique smart contract addresses that participated in a ledger change.
* For this unadjusted version of the metric, all ledger changes are considered.
* Ledger changes can include activities such as Decentralized Finance (DeFi) trades, DAO votes, token transfers, as well as any other activity facilitated by a smart contract.
* All participants of a ledger change activity are included.
* If an address was active multiple times during the aggregation interval (e.g., 1 day), it is counted only once.

### **Asset-Specific Details**

* This metric is only available for assets that feature the notion of smart contract addresses, such as Ethereum.

### Coverage

* [AdrActContCnt](https://coverage.coinmetrics.io/search-results?query=AdrActContCnt)

## Active Blob Addresses <a href="#adractcont" id="adractcont"></a>

<table><thead><tr><th width="177">Name</th><th width="157">MetricID</th><th width="124">Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Active Blob Addresses</td><td>AdrActBlobCnt</td><td>Blobs</td><td>1 day</td></tr></tbody></table>

### Definition

The sum count of unique addresses that were active either initiating or receiving blob transactions in the network that interval. Individual addresses are not double-counted if previously active.

### Coverage

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/AdrActBlobCnt>" %}

## Active Blob Addresses (Sent) <a href="#adractcont" id="adractcont"></a>

<table><thead><tr><th width="177">Name</th><th width="157">MetricID</th><th width="124">Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Active Blob Addresses (Sent)</td><td>AdrActBlobSendCnt</td><td>Blobs</td><td>1 day</td></tr></tbody></table>

### Definition

The sum count of unique addresses that were active initiating blob transactions in the network that interval. Individual addresses are not double-counted if previously active.

### Coverage

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/AdrActBlobSendCnt>" %}

## Active Blob Addresses (Received) <a href="#adractcont" id="adractcont"></a>

<table><thead><tr><th width="177">Name</th><th width="157">MetricID</th><th width="124">Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Active Blob Addresses (Received)</td><td>AdrActBlobRecCnt</td><td>Blobs</td><td>1 day</td></tr></tbody></table>

### Definition

The sum count of unique addresses that were active receiving blob transactions in the network that interval. Individual addresses are not double-counted if previously active.

### Coverage

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/AdrActBlobRecCnt>" %}

## MEV Active Address Count <a href="#adractcont" id="adractcont"></a>

<table><thead><tr><th width="177">Name</th><th width="157">MetricID</th><th width="124">Unit</th><th>Interval</th></tr></thead><tbody><tr><td>MEV Active Address Count</td><td>MevAdrActCnt</td><td>Addresses</td><td>1 day</td></tr></tbody></table>

### Definition

The sum count of unique addresses that were active in a MEV-enabled transaction in the network. An MEV-enabled transaction is one that paid an MEV tip to miners/validators in exchange for specific block ordering. Individual addresses are not double-counted if previously active.

### Details

* Ledger changes can include activities such as Decentralized Finance (DeFi) trades, DAO votes, token transfers, as well as any other activity facilitated by a smart contract.
* All participants of a ledger change activity are included.
* If an address was active multiple times during the aggregation interval (e.g., 1 day), it is counted only once.

### **Asset-Specific Details**

* For Solana, slots proposed by validators running the Jito-Solana client are considered as MEV slots. Further, in Solana it is possible to identify which transactions paid MEV tip in addition to simply identifying the slot. For this metric each individual transaction is evaluated to determine which are MEV-enabled and which aren't.

### Coverage

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/MevAdrActCnt>" %}

## API Endpoints

Active Addresses can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `AdrAct30dCnt`, `AdrAct7dCnt`, etc. in the `metrics` parameter.

{% openapi src="/files/kc3C7O6zTLYNBA0AcsZt" path="/timeseries/asset-metrics" method="get" %}
[openapi.yaml](https://2398817338-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MO23j33wWGzm0NrZseN%2Fuploads%2Fgit-blob-a236d0d04b3b155748ce07a17aca8108fce9b7c2%2Fopenapi.yaml?alt=media)
{% endopenapi %}

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=AdrAct30dCnt&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=AdrAct30dCnt&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="AdrAct30dCnt", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}

### **Release History**

* Release Version: 1.0 (X, 2019)


# Address Balances

## Address Balances

Addresses that hold a balance of X amount for a given asset.

### Contents

* [Address Count with ≥ X% Supply (AdrBal1inXCnt)](#adrbal1in)
* [Address Count with Balance ≥ X (native units) (AdrBalNtvXCnt)](#adrbalntv)
* [Address Count with Balance ≥ $X (AdrBalUSDXCnt)](#adrbalusd)

## Address Count with ≥ X% Supply <a href="#adrbal1in" id="adrbal1in"></a>

### Definition

The sum count of unique addresses holding at least one in Xth of the current supply of native units as of the end of that day. Only native units are considered (e.g., an address with less than one ten-billionth ETH but with ERC-20 tokens would not be considered).

| Name                               | MetricID                                                                                  | Unit      | Interval |
| ---------------------------------- | ----------------------------------------------------------------------------------------- | --------- | -------- |
| Addr Cnt with ≥ 0.00000001% Supply | [AdrBal1in10BCnt](https://coverage.coinmetrics.io/search-results?query=AdrBal1in10BCnt)   | Addresses | 1 day    |
| Addr Cnt with ≥ 0.0000001% Supply  | [AdrBal1in1BCnt](https://coverage.coinmetrics.io/search-results?query=AdrBal1in1BCnt)     | Addresses | 1 day    |
| Addr Cnt with ≥ 0.000001% Supply   | [AdrBal1in100MCnt](https://coverage.coinmetrics.io/search-results?query=AdrBal1in100MCnt) | Addresses | 1 day    |
| Addr Cnt with ≥ 0.00001% Supply    | [AdrBal1in10MCnt](https://coverage.coinmetrics.io/search-results?query=AdrBal1in10MCnt)   | Addresses | 1 day    |
| Addr Cnt with ≥ 0.0001% Supply     | [AdrBal1in1MCnt](https://coverage.coinmetrics.io/search-results?query=AdrBal1in1MCnt)     | Addresses | 1 day    |
| Addr Cnt with ≥ 0.001% Supply      | [AdrBal1in100KCnt](https://coverage.coinmetrics.io/search-results?query=AdrBal1in100KCnt) | Addresses | 1 day    |
| Addr Cnt with ≥ 0.01% Supply       | [AdrBal1in10KCnt](https://coverage.coinmetrics.io/search-results?query=AdrBal1in10KCnt)   | Addresses | 1 day    |
| Addr Cnt with ≥ 0.1% Supply        | [AdrBal1in1KCnt](https://coverage.coinmetrics.io/search-results?query=AdrBal1in1KCnt)     | Addresses | 1 day    |

### Details

* These metrics are a breakdown of the addresses with balance by relative ownership of the total current supply
* In this unadjusted version, the total current supply is used.
* The state of the ledger is the one at the last available block for that day.
* Only the native units balance is considered, L2 tokens (ERC-20, etc..) are not taken into account.
* The computation uses greater than or equal comparison: owning exactly 1 billionth of the current supply qualifies an address for AdrBal1in1BCnt

### Asset-Specific Details

* For XRP, escrowed amounts are not taken into account for balances but are counted towards total current supply.
* This metric is not available for assets that have full privacy, like Monero, Grin.
* For assets that have opt-in privacy features, like ZCash, it only takes the non-private balances into account. The shielded balances are taken into account for the supply component of the metric.

### Examples

If the total current supply of the token is 10,000,000,000 units (10 billion units):

* Addresses with less than 1 native unit (or 0.00000001% of supply) don't appear in any of these metrics
* Addresses with a balance of 1 native unit (or 0.00000001% of supply) are counted only in AdrBal1in10BCnt
* Addresses with a balance of 10 native units (or 0.0000001% of supply) are counted in AdrBal1in10BCnt and AdrBal1in1BCnt
* Addresses with 10,000,000 native units (0.1% of supply) are counted in all of these metrics

### Release History

* All but AdrBal1in10KCnt and AdrBal1in1KCnt were released in the 4.0 release of NDP
* AdrBal1in10KCnt and AdrBal1in1KCnt were released in the 4.2 release of NDP

### Interpretation

In contrast with Addresses, with balance, greater than X native units, count, this metric seeks to facilitate direct comparisons between blockchains, even if they have widely varying supply counts. This metric allows you to determine how many addresses own a given fraction of supply, rather than a given number of units of supply. Keep in mind that in blockchains where transacting is cheap or free, this metric can be gamed.

### Coverage

* [AdrBal1in10BCnt](https://coverage.coinmetrics.io/search-results?query=AdrBal1in10BCnt)
* [AdrBal1in1BCnt](https://coverage.coinmetrics.io/search-results?query=AdrBal1in1BCnt)
* [AdrBal1in100MCnt](https://coverage.coinmetrics.io/search-results?query=AdrBal1in100MCnt)
* [AdrBal1in10MCnt](https://coverage.coinmetrics.io/search-results?query=AdrBal1in10MCnt)
* [AdrBal1in1MCnt](https://coverage.coinmetrics.io/search-results?query=AdrBal1in1MCnt)
* [AdrBal1in100KCnt](https://coverage.coinmetrics.io/search-results?query=AdrBal1in100KCnt)
* [AdrBal1in10KCnt](https://coverage.coinmetrics.io/search-results?query=AdrBal1in10KCnt)
* [AdrBal1in1KCnt](https://coverage.coinmetrics.io/search-results?query=AdrBal1in1KCnt)

## Address Count with Balance ≥ X (native units) <a href="#adrbalntv" id="adrbalntv"></a>

### Definition

The sum count of unique addresses holding at least X native units as of the end of that day. Only native units are considered (e.g., an address with less than X ETH but with more than X in ERC-20 tokens would not be considered).

| Name                                   | MetricID                                                                                    | Unit      | Interval |
| -------------------------------------- | ------------------------------------------------------------------------------------------- | --------- | -------- |
| Addr Cnt of Bal ≥ 0.001 (native units) | [AdrBalNtv0.001Cnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv0.001cnt) | Addresses | 1 day    |
| Addr Cnt of Bal ≥ 0.01 (native units)  | [AdrBalNtv0.01Cnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv0.01cnt)   | Addresses | 1 day    |
| Addr Cnt of Bal ≥ 0.1 (native units)   | [AdrBalNtv0.1Cnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv0.1cnt)     | Addresses | 1 day    |
| Addr Cnt of Bal ≥ 1 (native units)     | [AdrBalNtv1Cnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv1cnt)         | Addresses | 1 day    |
| Addr Cnt of Bal ≥ 10 (native units)    | [AdrBalNtv10Cnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv10cnt)       | Addresses | 1 day    |
| Addr Cnt of Bal ≥ 100 (native units)   | [AdrBalNtv100Cnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv100cnt)     | Addresses | 1 day    |
| Addr Cnt of Bal ≥ 1K (native units)    | [AdrBalNtv1KCnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv1kcnt)       | Addresses | 1 day    |
| Addr Cnt of Bal ≥ 10K (native units)   | [AdrBalNtv10KCnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv10kcnt)     | Addresses | 1 day    |
| Addr Cnt of Bal ≥ 100K (native units)  | [AdrBalNtv100KCnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv100kcnt)   | Addresses | 1 day    |
| Addr Cnt of Bal ≥ 1M (native units)    | [AdrBalNtv1MCnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv1mcnt)       | Addresses | 1 day    |

### Details

* These metrics provide a count of addresses with balance by equal or higher than a native unit threshold.
* The state of the ledger is the one at the last available block for that day.
* Only the native units balance is considered, L2 tokens (ERC-20, etc..) are not taken into account.
* The computation uses greater than or equal comparison: owning exactly 1 native unit qualifies an address for AdrBalNtv1Cnt.

### Asset-Specific Details

* For XRP, escrowed amounts are not taken into account.
* This metric is not available for assets that have full privacy, like Monero, Grin.
* For assets that have opt-in privacy features, like ZCash, it only takes the non-private activities into account.

### Release History

* Released in the 4.0 release of NDP

### Interpretation

* This is a potent set of metrics which can elucidate the dispersion of ownership of the address space in a cryptocurrency. The trend can demonstrate whether or not a cryptocurrency is in a concentrative or distributive phase. It should be noted that supply is arbitrary, and for large-cap assets varies between tens of millions to hundreds of billions; so unit dispersion is often not directly comparable between chains. Put otherwise: it is cheaper to accumulate addresses with 100 XRP than 100 BTC since those are so different in fiat terms. This metric can also be gamed to a degree by adding dust to many thousands of addresses.

### Coverage

* [AdrBalNtv0.001Cnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv0.001cnt)
* [AdrBalNtv0.01Cnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv0.01cnt)
* [AdrBalNtv0.1Cnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv0.1cnt)
* [AdrBalNtv1Cnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv1cnt)
* [AdrBalNtv10Cnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv10cnt)
* [AdrBalNtv100Cnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv100cnt)
* [AdrBalNtv1KCnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv1kcnt)
* [AdrBalNtv10KCnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv10kcnt)
* [AdrBalNtv100KCnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv100kcnt)
* [AdrBalNtv1MCnt](https://coverage.coinmetrics.io/search-results?query=adrbalntv1mcnt)

## Address Count with Balance ≥ $X <a href="#adrbalusd" id="adrbalusd"></a>

### Definition

The sum count of unique addresses holding at least X dollar's worth of native units as of the end of that day. Only native units are considered (e.g., an address with less than X dollar's worth of ETH but with more than X dollar's worth of ERC-20 tokens would not be considered).

| Name                       | MetricID                                                                                  | Unit      | Interval |
| -------------------------- | ----------------------------------------------------------------------------------------- | --------- | -------- |
| Address Cnt of Bal ≥ $1    | [AdrBalUSD1Cnt](https://coverage.coinmetrics.io/search-results?query=adrbalusd1cnt)       | Addresses | 1 day    |
| Address Cnt of Bal ≥ $10   | [AdrBalUSD10Cnt](https://coverage.coinmetrics.io/search-results?query=adrbalusd10cnt)     | Addresses | 1 day    |
| Address Cnt of Bal ≥ $100  | [AdrBalUSD100Cnt](https://coverage.coinmetrics.io/search-results?query=adrbalusd100cnt)   | Addresses | 1 day    |
| Address Cnt of Bal ≥ $1K   | [AdrBalUSD1KCnt](https://coverage.coinmetrics.io/search-results?query=adrbalusd1kcnt)     | Addresses | 1 day    |
| Address Cnt of Bal ≥ $10K  | [AdrBalUSD10KCnt](https://coverage.coinmetrics.io/search-results?query=adrbalusd10kcnt)   | Addresses | 1 day    |
| Address Cnt of Bal ≥ $100K | [AdrBalUSD100KCnt](https://coverage.coinmetrics.io/search-results?query=adrbalusd100kcnt) | Addresses | 1 day    |
| Address Cnt of Bal ≥ $1M   | [AdrBalUSD1MCnt](https://coverage.coinmetrics.io/search-results?query=adrbalusd1mcnt)     | Addresses | 1 day    |
| Address Cnt of Bal ≥ $10M  | [AdrBalUSD10MCnt](https://coverage.coinmetrics.io/search-results?query=adrbalusd10mcnt)   | Addresses | 1 day    |

### Details

* These metrics are a breakdown of the addresses with balance count with USD balance thresholds.
* The state of the ledger is the one at the last available block for that day.
* The price used is the daily close price.
* Only the native units balance is considered, L2 tokens (ERC-20, etc..) are not taken into account.
* The computation uses greater than or equal comparison: owning exactly $1 qualifies an address for AdrBalUSD1Cnt.

### Asset-Specific Details

* For XRP, escrowed amounts are not taken into account.
* This metric is not available for assets that have full privacy, like Monero, Grin.
* For assets that have opt-in privacy features, like ZCash, it only takes the non-private activities into account.

### Release History

* Released in the 4.0 release of NDP

### Interpretation

* This metric standardizes wealth cohorts across multiple blockchains for easy comparison, although differences in address creation must be taken into account. Some wallets in UTXO chains tend to fragment user balances into multiple addresses to preserve privacy. Note that this metric is sensitive to changes in unit price; common address sizes combined with price changes can lead to large numbers of addresses hitting a new threshold at the same time. This can lead to sharp discontinuities in the metric. For a purer measure of holder dispersion (albeit not as directly comparable), see addresses, with balance, greater than X native units, count.

### Coverage

* [AdrBalUSD1Cnt](https://coverage.coinmetrics.io/search-results?query=adrbalusd1cnt)
* [AdrBalUSD10Cnt](https://coverage.coinmetrics.io/search-results?query=adrbalusd10cnt)
* [AdrBalUSD100Cnt](https://coverage.coinmetrics.io/search-results?query=adrbalusd100cnt)
* [AdrBalUSD1KCnt](https://coverage.coinmetrics.io/search-results?query=adrbalusd1kcnt)
* [AdrBalUSD10KCnt](https://coverage.coinmetrics.io/search-results?query=adrbalusd10kcnt)
* [AdrBalUSD100KCnt](https://coverage.coinmetrics.io/search-results?query=adrbalusd100kcnt)
* [AdrBalUSD1MCnt](https://coverage.coinmetrics.io/search-results?query=adrbalusd1mcnt)
* [AdrBalUSD10MCnt](https://coverage.coinmetrics.io/search-results?query=adrbalusd10mcnt)

## API Endpoints

Address Balances can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric IDs in the `metrics` parameter.

{% openapi src="/files/kc3C7O6zTLYNBA0AcsZt" path="/timeseries/asset-metrics" method="get" %}
[openapi.yaml](https://2398817338-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MO23j33wWGzm0NrZseN%2Fuploads%2Fgit-blob-a236d0d04b3b155748ce07a17aca8108fce9b7c2%2Fopenapi.yaml?alt=media)
{% endopenapi %}

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=AdrBal1in10BCnt&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=AdrBal1in10BCnt&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="AdrBal1in10BCnt", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# New Addresses

## Address Balances

Addresses that hold a balance of X amount for a given asset.

### Contents

* [New Funded Address Count (AdrNewBalCnt)](#adrnewbal)
* [New Address Count (AdrNewCnt)](#adrnewcnt)

## New Funded Address Count <a href="#adrnewbal" id="adrnewbal"></a>

### **Definition**

The sum count of all unique addresses that were newly created and funded (e.g. have a non-zero balance) that interval.

### **Dictionary**

| Name          | **MetricID**                                                                      | **Unit**  | **Interval** |
| ------------- | --------------------------------------------------------------------------------- | --------- | ------------ |
| New Addresses | [AdrNewBalCnt](https://coverage.coinmetrics.io/search-results?query=AdrNewBalCnt) | Addresses | 1 day        |

### **Details**

* [Addresses](/network-data/on-chain-basics#address) are the user-identifiers in a ledger change.
* New addresses are addresses identified in the blockchain that did not exist prior to the observation period (e.g. 1 day).
* Depending upon how a blockchain stores address information, new addresses might not be funded with any tokens. In other words, they have a balance of zero.
* This metric only accounts for new addresses that have been funded.

### **Chart**

[New Addr Cnt](https://coverage.coinmetrics.io/asset-metrics-v2/AdrNewCnt) showcases all new addresses observed in the network over the previous day, and New Funded Addr Cnt is a subset of New Addr Cnt that only counts addresses with a balance greater than 0.

### **Asset-Specific Details**

This metric is not available for assets that have full privacy, like Monero and Grin. For assets that have opt-in privacy features, like ZCash, it only takes the non-private activities into account.

### **Examples**

Consider the following example:

* Both Addreses A and Address B are seen on the ledger for the first time.
* Address A was referred by a smart contract application, perhaps as user identifier, but it was not funded or otherwise engaged by the smart contract. Its balance is zero.
* During that same interval, Address B received funds from an exhange for the first time. Its balance is 0.002.

If the above was the only activity observed in the network during that interval, AdrNewBalCnt would showcase a value of 1. This value only aggregates activity that is economically relevant (Address B), and excludes non-monetary activity (Address A).

### **Release History**

* Release Version: 5.0 (August, 2021)

### **Interpretation**

* Like Active Addresses, New Funded Addresses is a popular measure to proxy the number of new users on a blockchain. Unlike New Addr Cnt, this only showcases addresses with a non-zero balance .

### **See Also**

* [New Addr Cnt](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/addresses/adrnewcnt.md)
* [Address](/network-data/on-chain-basics#address)
* [Active Addresses (Received)](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/addresses/adractreccnt.md)
* [Active Addresses (Sent)](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/addresses/adractsentcnt.md)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/AdrActCnt>" %}

## New Address Count <a href="#adrnewcnt" id="adrnewcnt"></a>

### **Definition**

The sum count of all unique addresses that were newly created that interval.

### **Dictionary**

| Name          | **MetricID**                                                                | **Unit**  | **Interval** |
| ------------- | --------------------------------------------------------------------------- | --------- | ------------ |
| New Addresses | [AdrNewCnt](https://coverage.coinmetrics.io/search-results?query=AdrNewCnt) | Addresses | 1 day        |

### **Details**

* [Addresses](/network-data/on-chain-basics#address) are the user-identifiers in a ledger change.
* New addresses are addresses identified in the blockchain that did not exist prior to the observation period (e.g. 1 day).
* Depending upon how a blockchain stores address information, new addresses might not be funded with any tokens. In other words, they have a balance of zero.
* As such, a caveat of this metric is that it can be inflated by activity that is not economicallt relevant.
* For new addresses that are funded and are economically relevant, please refer to New Funded Adrr Cnt (AdrNewBalCnt).

### **Chart**

New Addr Cnt showcases all new addresses observed in the network over the previous day, and [New Funded Addr Cnt](https://coverage.coinmetrics.io/asset-metrics-v2/AdrNewBalCnt) is a subset of New Addr Cnt that only counts addresses with a balance greater than 0.

### **Asset-Specific Details**

* This metric is not available for assets that have full privacy, like Monero and Grin. For assets that have opt-in privacy features, like ZCash, it only takes the non-private activities into account.

### **Examples**

Consider the following example:

* Both Addreses A and Address B are seen on the ledger for the first time.
* Address A was referred by a smart contract application, perhaps as user identifier, but it was not funded or otherwise engaged by the smart contract. Its balance is zero.
* During that same interval, Address B received funds from an exhange for the first time. Its balance is 0.002.

If the above was the only activity observed in the network during that interval, AdrNewCnt would showcase a value of 2. This value aggregates activity that is economically relevant (Address B) as well as non monetary (Address A).

### **Release History**

* Release Version: 5.0 (August, 2021)

### **Interpretation**

* Like Active Addresses, New Addresses is a popular measure to proxy the number of *new* users on a blockchain. However, in blockchains where address creation is cheap, or free, new addresses can still be trivially forged.

### **See Also**

* [New Funded Addr Cnt](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/addresses/adrnewbalcnt.md)
* [Address](/network-data/on-chain-basics#address)
* [Active Addresses (Received)](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/addresses/adractreccnt.md)
* [Active Addresses (Sent)](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/addresses/adractsentcnt.md)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/AdrActCnt>" %}

## API Endpoints

New Address metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric IDs `AdrNewBalCnt` `AdrNewCnt` in the `metrics` parameter.

{% openapi src="/files/kc3C7O6zTLYNBA0AcsZt" path="/timeseries/asset-metrics" method="get" %}
[openapi.yaml](https://2398817338-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MO23j33wWGzm0NrZseN%2Fuploads%2Fgit-blob-a236d0d04b3b155748ce07a17aca8108fce9b7c2%2Fopenapi.yaml?alt=media)
{% endopenapi %}

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=AdrNewBalCnt&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=AdrNewBalCnt&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="AdrNewBalCnt", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Economics

## Metrics

[Mining](/network-data/network-data-overview/economics/mining)

* MCRC
* MCTC
* MOMR

[Valuation](/network-data/network-data-overview/economics/valuation)

* NVTAdj
* NVTAdj90
* NVTAdjFF
* NVTAdjFF90
* RCTC
* RVTAdj
* RVTAdj90
* SOPR
* SOPROut


# Mining

### Contents

* [Miner Cap to Realized Cap (MCRC)](#mcrc)
* [Miner Cap to Thermo Cap (MCTC)](#mctc)
* [Miner Outflow to Miner Revenue (MOMR)](#momr)

## Miner Cap to Realized Cap (MCRC) <a href="#mcrc" id="mcrc"></a>

### Definition

The ratio of Miner Cap over Realized Cap at the end of that interval. Miner Cap represents all funds held by mining pools and miners and is calculated as the sum of SplyMiner0HopAllUSD (supply held by mining pools) and SplyMiner1HopAllUSD (supply held by miners). [Realized Cap](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/network-data-overview/economics/broken-reference/README.md) (CapRealUSD) is defined as the sum USD value based on the USD closing price on the day that a native unit last moved (i.e., last transacted) for all native units.

| Name                             | IMetricD | Unit          | Interval |
| -------------------------------- | -------- | ------------- | -------- |
| Miner Cap to Realized Cap (MCRC) | MCRC     | Dimensionless | 1 day    |

### Details

* This metric shows the ratio between the assets that miners hold in custody relative to the "cost basis" of the entire network.
* Like [MVRV](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/network-data-overview/economics/broken-reference/README.md), it can be used to better understand the market cycle as it identifies moments where the value of the supply held by miners is higher than the cost basis of the entire network.
* Similarly, it may showcase when miners are capitulating and potentially selling at a loss.
* Miners are speculators as they are naturally exposed to the price of the currency they are mining. As such, they collectively make buy or sell decisions that ultimately impact the market.

### Chart

![](/files/-Mh-Ex9F9qZPFjHy44mn)

### Interpretation

* When comparing the USD value of what miners have in custody relative to the cost basis of the network as a whole, a natural threshold of 1 is relevant.
* When this threshold is breached, it might indicate that miners are more willing to sell their assets, as their profit margins have widened.
* Conversely, as this ratio nears zero, it might indicate miners are selling at a loss.

### Asset-Specific Details

Only applicable to assets for which we have SplyMiner0HopAllUSD (supply held by mining pools), SplyMiner1HopAllUSD (supply held by miners) and Realized Cap (CapRealUSD).

### Release History

* Release Version: NDP 5.0 (August, 2021)

### See Also:

* [MCTC (Miner Cap / Thermo Cap)](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/economics/mctc.md)
* [MVRV (Market Cap / Realized Market Cap)](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/network-data-overview/economics/broken-reference/README.md)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/MCTC>" %}

## Miner Cap to Thermo Cap (MCTC) <a href="#mctc" id="mctc"></a>

### Definition

The ratio of Miner Cap relative to Thermo Cap at the end of that interval. Miner Cap represents all funds held by mining pools and miners and is calculated as the sum of SplyMiner0HopAllUSD (supply held by mining pools) and SplyMiner1HopAllUSD (supply held by miners). Thermo Cap is RevAllTimeUSD and represents the USD value of all funds disbursed to miners at the time of issuance.

| Name                           | MetricID | Unit          | Interval |
| ------------------------------ | -------- | ------------- | -------- |
| Miner Cap to Thermo Cap (MCTC) | MCTC     | Dimensionless | 1 day    |

### Details

* This metric shows the ratio between the assets that miners hold in custody relative to the assets that miners have been issued by the protocol as mining rewards.
* Like [MVRV](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/network-data-overview/economics/broken-reference/README.md), it can be used to better understand the market cycle as it identifies moments where the value of the supply held by miners is higher than what was issued to them.
* Similarly, it may showcase when miners are capitulating and potentially selling at a loss.
* Miners are speculators as they are naturally exposed to the price of the currency they are mining. As such, they collectively make buy or sell decisions that ultimately impact the market.

### Chart

![](/files/-Mh-J_Dy8V2HHfOGoQCV)

### Interpretation

* Historically, a threshold of 10 has been indicative of market tops.
* When this threshold is breached, it might indicate that miners are more willing to sell their assets, as their profit margins have widened.
* Conversely, as this ratio dips below 2, it might indicate market bottoms as miner's willingness to sell decreases.

### Asset-Specific Details

Only applicable to assets for which we have SplyMiner0HopAllUSD (supply held by mining pools), SplyMiner1HopAllUSD (supply held by miners) and Thermo Cap (RevAllTimeUSD).

### Release History

* Release Version: NDP 5.0 (August, 2021)

### See Also:

* [MCRC (Market Cap / Realized Cap)](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/economics/mcrc.md)
* [MVRV (Market Cap / Realized Market Cap)](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/network-data-overview/economics/broken-reference/README.md)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/MCRC>" %}

## Miner Outflow to Miner Revenue <a href="#momr" id="momr"></a>

### Definition

The ratio of Miner Outflows over Miner Revenue at the end of that interval. Miner outflows represent the sum of funds being sent by miner addresses (1-hop from the coinbase) and are calculated as FlowMinerOut1HopAllNtv. Miner Revenue represents the sum of funds (new coins and transaction fees) sent to miners over a time window and is calculated as RevNtv.

| Name                      | MetricID                                                          | Unit          | Interval |
| ------------------------- | ----------------------------------------------------------------- | ------------- | -------- |
| Miner Cap to Realized Cap | [MOMR](https://coverage.coinmetrics.io/search-results?query=MOMR) | Dimensionless | 1 day    |

### Details

* This metric shows the ratio between the assets leaving miner addresses relative to how much miners have received as revenue.
* The FlowMinerOut1HopAllNtv is part of our Miner Flows family of metrics, which takes into account the custody structures within mining pools and their constituents who are individually mining.

### Interpretation

* When comparing the USD value of what miners are sending relative to the funds they are receiving, there appears to be a negative relationship with price.
* That makes intuitive sense as it might indicate that miners are sending more funds out (which might show higher willingness to sell) relative to what they are receiving as revenue.
* As such, this ratio might serve as a barometer for miner sentiment and identify liquidity events when miners might be bearish.
* It is important to note that the mere act of sending funds from one address to another does not necessary signify the act of selling.
* Only when there is a clear & noticeable uptick in this metric that the speculation that miners are selling is defensible, given that outflows might signify more mundane events such as a cold wallet shuffle.
* Miner outflows are naturally very volatile. As such, we recommend using a monthly (30d) Moving Average when visualizing this metric.

### Asset-Specific Details

Only applicable to assets for which we have SplyMiner0HopAllUSD (supply held by mining pools), SplyMiner1HopAllUSD (supply held by miners) and Realized Cap (CapRealUSD).

### Release History

* Release Version: NDP 5.0 (August, 2021)

### See Also:

* [MCTC (Miner Cap / Thermo Cap)](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/economics/mctc.md)
* [MVRV (Market Cap / Realized Market Cap)](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/network-data-overview/economics/broken-reference/README.md)

### Coverage

* [MOMR](https://coverage.coinmetrics.io/asset-metrics/MOMR)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/MOMR>" %}

## API Endpoints

Address Balances can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `MCRC` , `MCTC` and `MOMR` in the `metrics` parameter.

{% openapi src="/files/kc3C7O6zTLYNBA0AcsZt" path="/timeseries/asset-metrics" method="get" %}
[openapi.yaml](https://2398817338-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MO23j33wWGzm0NrZseN%2Fuploads%2Fgit-blob-a236d0d04b3b155748ce07a17aca8108fce9b7c2%2Fopenapi.yaml?alt=media)
{% endopenapi %}

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=MCRC&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=MCRC&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="MCRC", 
        assets='btc',
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Valuation

### Contents

* [Network Value to Transactions (NVTAdj)](#nvt)
* [Network Value to Transactions Free Float (NVTAdjFF)](#nvtff)
* [Realized Cap to Thermo Cap (RCTC)](#rctc)
* [RVT Ratio (RVT)](#rvt)
* [Spent Output Price Ratio (SOPR)](#sopr)
* [Net Unrealized Profit/Loss (NUPL)](#nupl)
* Long-Term and Short-Term Holder SOPR (SOPRLthX)

## Network Value to Transactions <a href="#nvt" id="nvt"></a>

### Definition

The ratio of the network value (or market capitalization, current supply) divided by the adjusted transfer value. Also referred to as NVT.

| Name                  | MetricID                                                                  | Unit          | Interval |
| --------------------- | ------------------------------------------------------------------------- | ------------- | -------- |
| NVT                   | [NVTAdj](https://coverage.coinmetrics.io/search-results?query=NVTAdj)     | Dimensionless | 1 day    |
| NVT 90-day Moving Avg | [NVTAdj90](https://coverage.coinmetrics.io/search-results?query=NVTAdj90) | Dimensionless | 1 day    |

### Details

* This metric uses the native units network value and adjusted transaction volume. It is therefore available at the asset’s genesis, unlike if it was using USD values.
* It can be thought of as a rough P/E (price to earnings) ratio proxy for crypto assets.
* First conceptualized by Willy Woo (2017) with the introduction of the network value to transactions (NVT) ratio, calculated as a cryptoasset’s market capitalization divided by its daily value transacted over the network. The logic behind the ratio is that value transacted over an asset’s network represents the utility of a cryptoasset. High values of the NVT ratio have detected bubbles and low values have indicated attractive entry points in the past.
* NVTAdj90 is computed as the current market cap over the 90-day moving average of USD adjusted transfer volume.
* Inspired by Kalichkin’s work. [Kalichkin (2018a)](https://medium.com/cryptolab/https-medium-com-kalichkin-rethinking-nvt-ratio-2cf810df0ab0) extended the idea behind the NVT ratio by introducing additional smoothing to correct for certain shortcomings in the original formulation that prevent it from being used as a real-time trading indicator.

### **Release History**

* Released in the 1.0 release of NDP

### Interpretation

NVT has been much discussed; in short, it compares market capitalization to on-chain transactional usage. Blockchains with low usage relative to market cap have a higher NVT. In this sense it can be understood as the opposite of velocity. Due to structural dissimilarities in blockchain usage modes, NVTs among all assets are not directly comparable. Our formulation employs adjusted transaction volume, as we understand this to be a purer measure of the actual usage of the chain.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/NVTAdj>" %}

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/NVTAdj90>" %}

## Network Value to Transactions Free Float <a href="#nvtff" id="nvtff"></a>

### Definition

The ratio of the free float network value (or market capitalization, free float) divided by the adjusted transfer value. Also referred to as FFNVT.

| Name                             | MetricID                                                                  | Unit          | Interval |
| -------------------------------- | ------------------------------------------------------------------------- | ------------- | -------- |
| Free Float NVT                   | [NVTAdjFF](https://coverage.coinmetrics.io/search-results?query=NVTAdj)   | Dimensionless | 1 day    |
| Free Float NVT 90-day Moving Avg | [NVTAdjFF90](https://coverage.coinmetrics.io/search-results?query=NVTAdj) | Dimensionless | 1 day    |

### Details

* This metric provides an important adjustment to the Network Value to Transaction (NVT) Ratio using Free Float Supply (SplyFF)
* For more details on the significance of this improvement, please refer to the following [blog post](https://coinmetrics.io/introducing-free-float-supply/).
* This metric uses the native units network value and adjusted transaction volume. It is therefore available at the asset’s genesis, unlike if it was using USD values.
* It can be thought of as a rough P/E (price to earnings) ratio proxy for crypto assets.
* NVT was first conceptualized by Willy Woo (2017) with the introduction of the network value to transactions (NVT) ratio, calculated as a cryptoasset’s market capitalization divided by its daily value transacted over the network. The logic behind the ratio is that value transacted over an asset’s network represents the utility of a cryptoasset. High values of the NVT ratio have detected bubbles and low values have indicated attractive entry points in the past.

### **Release History**

* Release Version: NDP-EOD 4.8 (Nov, 2020)

### Interpretation

NVT has been much discussed; in short, it compares market capitalization to on-chain transactional usage. Blockchains with low usage relative to market cap have a higher NVT. In this sense it can be understood as the opposite of velocity. Due to structural dissimilarities in blockchain usage modes, NVTs among all assets are not directly comparable. Our formulation employs adjusted transaction volume, as we understand this to be a purer measure of the actual usage of the chain.

### See Also

* [NVT](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/economics/nvtadj.md)
* [Free Float NVT 90-day Moving Avg](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/economics/nvtadjff90.md)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/NVTAdjFF>" %}
[<br>](https://docs.coinmetrics.io/asset-metrics/economics/nvtadjff)
{% endembed %}

## Realized Cap to Thermo Cap (RCTC) <a href="#rctc" id="rctc"></a>

### Definition

The ratio of the Realized Cap over Thermo Cap at the end of that interval. [Realized Cap](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/network-data-overview/economics/broken-reference/README.md) (CapRealUSD) is defined as the sum USD value based on the USD closing price on the day that a native unit last moved (i.e., last transacted) for all native units. Thermo Cap is calculated as RevAllTimeUSD and it represents the USD value of all funds disbursed to miners at the time of issuance.

| Name                              | IMetricD                                                          | Unit          | Interval |
| --------------------------------- | ----------------------------------------------------------------- | ------------- | -------- |
| Realized Cap to Thermo Cap (RCTC) | [RCTC](https://coverage.coinmetrics.io/search-results?query=RCTC) | Dimensionless | 1 day    |

### Details

* Like [MVRV](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/network-data-overview/economics/broken-reference/README.md), RCTC can be used to better understand the market cycle as it identifies the ralationship between the network's overall cost basis (CapRealUSD) relative to the USD amount issued to miners by the protocol (RevAllTimeUSD).
* When evaluating market tops, RCTC provides a view on the realization of profits relative to the liquidity that is being issued to miners.
* Miners are speculators as they are naturally exposed to the price of the currency they are mining. As such, they collectively make buy or sell decisions that ultimately impact the market.

### Chart

![](/files/SOdzdJ3U4TuOsLFuE1de)

### Interpretation

* This metric fundamentally showcases the impact of miner liquity in the overall market. When the USD value of miner income is low relative to what is being realized on-chain, this could be interpreted as a sign of market tops.
* This metric could also be interpreted as the profit margin that might be realized by miners as it showcases the gap between profit taking.
* Historically, a threshold of 10 has been indicative of market tops as a wide profit margins are being realized relative to the USD value being issued to miners.

### Asset-Specific Details

Only applicable to assets for which we have RevAllTimeUSD and CapRealUSD.

### Release History

* Release Version: NDP 5.0 (August, 2021)

### See Also:

* [MCRC (Market Cap / Realized Cap)](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/economics/miner-cap-to-realized-cap-mcrc.md)
* [MVRV (Market Cap / Realized Market Cap)](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/network-data-overview/economics/broken-reference/README.md)

### Availability for Assets

{% embed url="<https://docs.coinmetrics.io/info/metrics/CapMVRVFF>" %}

## RVT <a href="#rvt" id="rvt"></a>

### Definition

The ratio of the network's realized value to its adjusted transfer value. Also referred to as RVT.

| Name                  | MetricID                                                                  | Unit          | Interval |
| --------------------- | ------------------------------------------------------------------------- | ------------- | -------- |
| RVT                   | [RVT](https://coverage.coinmetrics.io/search-results?query=RVTAdj90)      | Dimensionless | 1 day    |
| RVT 90-day Moving Avg | [RVTAdj90](https://coverage.coinmetrics.io/search-results?query=RVTAdj90) | Dimensionless | 90 days  |

### Details

* Computed as realized value (aka realized market cap) over adjusted transfer value.
* [Checkmate (2019)](https://medium.com/@_Checkmatey_/the-bitcoin-rvt-ratio-a-high-conviction-macro-indicator-615b68715b77) formulates the realized capitalization to transaction value (RVT) ratio which uses the same fundamental principles behind the NVT ratio but uses realized capitalization instead of market capitalization in the numerator of the ratio.
* RVTAdj90 is computed as the network's realized value (aka realized market cap) over the 90-day moving average of USD adjusted transfer volume.

### Release History

* Release Version: NDP-EOD 4.8 (Nov, 2020)

### Interpretation

RVT is based on the same principles as NVT but uses Realized Cap in the numerator. Realized Cap can be a smoother measure of network valuation than the Market Cap as it is concerned with the price at which the coin was last moved on-chain. As a result, both Realized Cap and the RVT are shielded from day-to-day market sentiment and speculation that are reflected in Market Cap.

RVT can be a slower moving, higher conviction signal tuned to the macro sentiment of HODLers.

### See Also

* [Realized Market Cap (USD)](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/network-data-overview/economics/broken-reference/README.md)
* [RVT 90-day Moving Avg](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/economics/rvtadj90.md)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/RVTAdj>" %}

## Spent Output Profit Ratio (SOPR) <a href="#sopr" id="sopr"></a>

### Definition

The ratio of the sum of spent value over the sum of creation value of all spent and created outputs for that interval. There are two versions of this metric. For this version, a spent output’s “spent value” is the market value of the sum of all native units of that output (i.e., price multiplied by the sum of native units). A created output’s “creation value” is the market value of the sum of all native units of that output (i.e., price multiplied by the sum of native units).

| Name     | MetricID                                                             | Unit          | Interval |
| -------- | -------------------------------------------------------------------- | ------------- | -------- |
| SOPR     | [SOPR](https://coverage.coinmetrics.io/search-results?query=SOPR)    | Dimensionless | 1 day    |
| SOPR Out | [SOPROut](https://coverage.coinmetrics.io/search-results?query=SOPR) | Dimensionless | 1 day    |

### Details

* (Sum of spent value) / (Sum of creation value) of all spent and created outputs for that interval)
* Sum of creation value = Sum of all transactional outputs that interval multiplied by the closing price for that interval
* SOPR was introduced by Renato Shirakashi.
* It oscillates around 1, if below it, people spending are realizing losses, above it, realizing gains.
* SOPROut is our first implementation of SOPR which doesn’t weight outputs by their value.
* SOPROut oscillates around 1, if it is below 1, people spending are realizing losses, above 1, realizing gains.

### Asset-Specific Details

* This metric is not available for assets that have full privacy, like Monero, Grin.
* For assets that have opt-in privacy features, like ZCash, it only takes the non-private balances into account.

### Chart

![](/files/-MY0oebCGfoLEWr1qO6B)

The chart above shows the combined SOPR ratio of all UTXOs spent, aggregated on a daily basis. The metric is also smoothed with a 7-day rolling average as SOPR tends to be relatively volatile.

On January 8th 2021, as BTC price topped $40K, BTC SOPR (7-day average) reached 1.048, its highest level since December 2017. The following day BTC price began to decline, and SOPR bottomed out at 1.004 on January 26th with BTC price at $32.6K. It has since rebounded to about 1.015.

### Example

* If in a given day, 3 outputs are spent:
  * \*\* Output A, value 10 BTC, created when BTC was worth $10
  * \*\* Output B, value 1 BTC, created when BTC was worth $500
  * \*\* Output C, value 2 BTC, created when BTC was worth $20,000
* If market price is $7,500, SOPR for that day is computed as:
  * \*\* Sum creation values: $10 \* 10 BTC + $500 \* 1 BTC + $20,000 \* 2 BTC = $40,600
  * \*\* Sum spent values: $7,500 \* 10 BTC + $7,500 \* 1 BTC + $7,500 \* 2 BTC = $97,500
  * \*\* SOPR = $97,500 /$40,600 = 2.4014

### Release History

* Released in the 5.0 release of NDP

### Interpretation

Spent Output Profit Ratio (SOPR) gives another vantage point into bitcoin market cycles. Introduced [by Renato Shirakashi in 2019](https://medium.com/unconfiscatable/introducing-sopr-spent-outputs-to-predict-bitcoin-lows-and-tops-ceb4536b3b9), SOPR can act as a proxy for gauging whether holders are selling at a profit or at a loss.

SOPR is a ratio of bitcoin’s price at the time UTXOs are spent to its price at the time they were created. In other words, it’s a proxy for price sold divided by price paid. Every time a transaction occurs, we can compare bitcoin’s price at the time the UTXOs in that transaction were created to the price at which they were spent. Creating a ratio of the two gives a simple way to estimate whether the bitcoin in the UTXO was sold at a profit or loss.

SOPR can be computed for individual UTXOs, but it can also be computed for a group of UTXOs.

Historically, a high SOPR has signaled that bitcoin price is reaching a local maximum. Conversely, a low SOPR theoretically signals that holders are selling at a loss, which has historically indicated a good time to buy. A SOPR of 1 is also particularly important to watch, as it signals the tipping point from selling in profit to selling at a loss.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/SOPR>" %}

## Net Unrealized Profit/Loss (NUPL) <a href="#nupl" id="nupl"></a>

### Definition

NUPL measures the proportion of an asset's market cap that represents unrealized profit or loss among all coins in circulation.

| Name | MetricID | Unit          | Interval |
| ---- | -------- | ------------- | -------- |
| NUPL | NUPL     | Dimensionless | 1 day    |

### Details

* Calculated as: (CapMrktCurUSD - CapRealUSD)/CapMrktCurUSD

### Interpretation

It indicates whether the market, on average, is in a state of unrealized gain (positive) or loss (negative), reflecting investor sentiment and potential market phases.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/NUPL>" %}

## Long-Term and Short-Term Holder SOPR

### Definition

Long-Term and Short-Term Holder SOPR metrics segment the traditional SOPR calculation based on the age of the UTXOs being spent. These metrics separate profit/loss realization behavior between holders who have held their positions for different time periods, providing deeper insights into market dynamics by distinguishing between committed long-term investors and more active short-term traders.

There are two versions of this metric, one weighted by the value of each output and the other unweighted.

| Name                                                                                         | MetricID                                  | Unit          | Interval |
| -------------------------------------------------------------------------------------------- | ----------------------------------------- | ------------- | -------- |
| Spent Output Profit Ratio (SOPR) 30 day Long-Term Holder / Short-Term Holder                 | SOPRLth30d / SOPRSth30d                   | Dimensionless | 1 day    |
| Spent Output Profit Ratio (SOPR) 90 day Long-Term Holder / Short-Term Holder                 | <p>SOPRLth90d /<br>SOPRSth90d</p>         | Dimensionless | 1 day    |
| Spent Output Profit Ratio (SOPR) 155 day Long-Term Holder / Short-Term Holder                | <p>SOPRLth155d /<br>SOPRSth155d</p>       | Dimensionless | 1 day    |
| Spent Output Profit Ratio (SOPR) 1 year Long-Term Holder / Short-Term Holder                 | <p>SOPRLth1y /<br>SOPRSth1y</p>           | Dimensionless | 1 day    |
| Spent Output Profit Ratio (SOPR) 5 years Long-Term Holder / Short-Term Holder                | <p>SOPRLth5y /<br>SOPRSth5y</p>           | Dimensionless | 1 day    |
| Spent Output Profit Ratio Unweighted (SOPR Out) 30 day Long-Term Holder / Short-Term Holder  | <p>SOPRLthOut30d /<br>SOPRSthOut30d</p>   | Dimensionless | 1 day    |
| Spent Output Profit Ratio Unweighted (SOPR Out) 90 day Long-Term Holder / Short-Term Holder  | <p>SOPRLthOut90d /<br>SOPRSthOut90d</p>   | Dimensionless | 1 day    |
| Spent Output Profit Ratio Unweighted (SOPR Out) 155 day Long-Term Holder / Short-Term Holder | <p>SOPRLthOut155d /<br>SOPRSthOut155d</p> | Dimensionless | 1 day    |
| Spent Output Profit Ratio Unweighted (SOPR Out) 1 year Long-Term Holder / Short-Term Holder  | <p>SOPRLthOut1y /<br>SOPRSthOut1y</p>     | Dimensionless | 1 day    |
| Spent Output Profit Ratio Unweighted (SOPR Out) 5 years Long-Term Holder / Short-Term Holder | <p>SOPRLthOut5y /<br>SOPRSthOut5y</p>     | Dimensionless | 1 day    |

### Details

The Long-Term and Short-Term Holder SOPR metrics use the same fundamental calculation as the traditional SOPR but apply filters based on the age of UTXOs:

**For SOPRLth (Long-Term Holders):**

* Only includes UTXOs that were created more than X days/years ago
* Calculation: (Sum of spent value of old UTXOs) / (Sum of creation value of old UTXOs)

**For SOPRSth (Short-Term Holders):**

* Only includes UTXOs that were created X days/years ago or less
* Calculation: (Sum of spent value of recent UTXOs) / (Sum of creation value of recent UTXOs)

**Weighted vs Unweighted Versions:**

Like the traditional SOPR, these metrics come in two variants:

1. **Weighted (SOPR):** Value-weighted by the size of each output
2. **Unweighted (SOPROut):** Each output is treated equally regardless of size

The unweighted versions are denoted with "Out" suffix (e.g., SOPRLthOut155d, SOPRSthOut155d).

Both versions oscillate around 1:

* Values > 1 indicate holders are realizing gains on average
* Values < 1 indicate holders are realizing losses on average
* Values = 1 indicate break-even realization

### Example

Using data from October 15, 2023, with a 155-day threshold:

* **SOPR (All):** 1.0019 - Overall market slightly profitable
* **SOPR Long-Term Holders (155d):** 1.0953 - Long-term holders realizing \~9.5% profits
* **SOPR Short-Term Holders (155d):** 1.0084 - Short-term holders barely profitable at \~0.8%
* **SOPR Out (All):** 0.9732 - Unweighted average shows slight losses
* **SOPR Out Long-Term Holders (155d):** 0.9133 - Most long-term holder transactions at loss
* **SOPR Out Short-Term Holders (155d):** 1.0064 - Most short-term holder transactions slightly profitable

This example demonstrates how the weighted vs unweighted versions can tell different stories. While large long-term holders were realizing substantial profits (SOPRLth155d = 1.0953), the majority of long-term holder transactions by count were actually at a loss (SOPRLthOut155d = 0.9133), suggesting that smaller holders were selling at losses while larger holders captured gains.

### Interpretation

Long-Term and Short-Term Holder SOPR metrics provide nuanced insights into market behavior:

**Long-Term Holder SOPR Patterns:**

* High values often coincide with market tops, as committed holders finally take profits
* Sharp increases can signal capitulation events where even long-term holders sell
* Sustained values above 1.5-2.0 historically indicate overheated market conditions
* Values consistently below 1 may suggest strong conviction among long-term holders to hold despite losses

**Short-Term Holder SOPR Patterns:**

* Generally more range-bound and closer to 1 due to frequent trading
* Quick oscillations around 1 reflect active trading and price discovery
* Extreme values (very high or low) are less common but can signal intense short-term sentiment
* Divergences with long-term holder SOPR can indicate shifts in market regime

**Time Threshold Selection:**

* **30d/90d:** Captures very short-term vs medium-term holder behavior
* **155d:** Approximately one market cycle, widely used benchmark
* **1y:** Separates annual traders from multi-year investors
* **5y:** Distinguishes true long-term hodlers from shorter-term positions

**Analytical Applications:**

* **Market Timing:** Extreme divergences between LTH and STH SOPR can signal regime changes
* **Sentiment Analysis:** LTH SOPR spikes may indicate distribution phases
* **Risk Management:** High STH SOPR with low LTH SOPR suggests short-term speculation
* **Cycle Analysis:** Compare across different time thresholds to understand holder behavior evolution

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/SOPRLth30d>" %}

## API Endpoints

Address Balances can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `NVT*` , `RVT*` and `SOPR*` in the `metrics` parameter.

{% openapi src="/files/kc3C7O6zTLYNBA0AcsZt" path="/timeseries/asset-metrics" method="get" %}
[openapi.yaml](https://2398817338-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MO23j33wWGzm0NrZseN%2Fuploads%2Fgit-blob-a236d0d04b3b155748ce07a17aca8108fce9b7c2%2Fopenapi.yaml?alt=media)
{% endopenapi %}

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=MCRC&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=MCRC&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="NVTAdj", 
        assets='btc',
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Exchange

The following lists the exchanges we cover in our on-chain metrics calculations for on-chain supply, on-chain deposits, on-chain withdrawals, and net flows as part of our Network Data Pro product.

## Exchange

Exchange metrics showcase the on-chain fingerprint provided by **coin movement into/out of exchange addresses**.

## On-Chain Exchange Coverage

### Exchange On-Chain Flows & Supply Metrics Coverage

{% hint style="info" %}
Exchange On-Chain Supply, Deposits, Withdrawals and Net Flows can be found in the [Asset Metrics endpoint](https://docs.coinmetrics.io/api/v4#operation/getTimeseriesAssetMetrics)
{% endhint %}

| Exchange   | Short Name |
| ---------- | ---------- |
| Binance    | BNB        |
| Bitfinex   | BFX        |
| BitMEX     | BMX        |
| Bitstamp   | BSP        |
| Bittrex    | BTX        |
| Bybit      | BIT        |
| Crypto.com | CRO        |
| Coinbase   | CBS        |
| Deribit    | DER        |
| Gate.io    | GIO        |
| Gemini     | GEM        |
| HitBTC     | HBT        |
| Huobi      | HUO        |
| Korbit     | KOR        |
| Kraken     | KRK        |
| Kucoin     | KCN        |
| MEXC       | MXC        |
| NBX        | NBX        |
| OKX        | OKX        |
| Poloniex   | POL        |
| SwissBorg  | SBG        |

For more details on asset coverage for exchange supply or flows metrics, see the individual metric in the Asset Metrics section of this Data Encyclopedia.

## Metrics

[**Deposits**](/network-data/network-data-overview/exchange/deposits)

[**Exchange Supply**](/network-data/network-data-overview/exchange/exchange-supply)

[**Net Flows**](/network-data/network-data-overview/exchange/net-flows)

[**Transaction Count**](/network-data/network-data-overview/exchange/transaction-count)

[**Withdrawals**](/network-data/network-data-overview/exchange/withdrawals)


# Deposits

## Contents

* [Exchange Deposits (FlowInXNtv, FlowInXUSD)](#flowin)
* [Exchange Deposit Count (FlowTfrInXCnt)](#flowtfrin)

## Exchange Deposits <a href="#flowin" id="flowin"></a>

### Definition

The sum of assets sent to an exchange that interval.

| Name                                             | MetricID        | Unit         | Interval       |
| ------------------------------------------------ | --------------- | ------------ | -------------- |
| Bitfinex Deposits (native units)                 | FlowInBFXNtv    | Native units | 1 block, 1 day |
| Bitfinex Deposits (USD)                          | FlowInBFXUSD    | USD          | 1 block, 1 day |
| BitMEX Deposits (native units)                   | FlowInBMXNtv    | Native units | 1 block, 1 day |
| BitMEX Deposits (USD)                            | FlowInBMXUSD    | USD          | 1 block, 1 day |
| Binance Deposits (native units)                  | FlowInBNBNtv    | Native units | 1 block, 1 day |
| Binance Deposits (USD)                           | FlowInBNBUSD    | USD          | 1 block, 1 day |
| Bitstamp Deposits (native units)                 | FlowInBSPNtv    | Native units | 1 block, 1 day |
| Bitstamp Deposits (USD)                          | FlowInBSPUSD    | USD          | 1 block, 1 day |
| Bitget Deposits (native units)                   | FlowInBGTNtv    | Native units | 1 day          |
| Bitget Deposits (USD)                            | FlowInBGTUSD    | USD          | 1 day          |
| Bithumb Deposits (native units)                  | FlowInBHMNtv    | Native units | 1 day          |
| Bithumb Deposits (USD)                           | FlowInBHMUSD    | USD          | 1 day          |
| Bittrex Deposits (native units)                  | FlowInBTXNtv    | Native units | 1 block, 1 day |
| Bittrex Deposit (USD)                            | FlowInBTXUSD    | USD          | 1 block, 1 day |
| Bybit Deposit (native units)                     | FlowInBITNtv    | Native units | 1 day          |
| Bybit Deposit (USD)                              | FlowInBITUSD    | USD          | 1 day          |
| Cex.io Deposit (native units)                    | FlowInCEXNtv    | Native units | 1 day          |
| Cex.io Deposit (USD)                             | FlowInCEXUSD    | USD          | 1 day          |
| Coinbase Deposit (native units)                  | FlowInCBSNtv    | Native units | 1 day          |
| Coinbase Deposit (USD)                           | FlowInCBSUSD    | USD          | 1 day          |
| Crypto.com Deposit (native units)                | FlowInCRONtv    | Native units | 1 day          |
| Crypto.com Deposit (USD)                         | FlowInCROUSD    | USD          | 1 day          |
| Deribit Deposit (native units)                   | FlowInDERNtv    | Native units | 1 day          |
| Deribit Deposit (USD)                            | FlowInDERUSD    | USD          | 1 day          |
| Gate.io Deposit (native units)                   | FlowInGIONtv    | Native units | 1 day          |
| Gate.io Deposit (USD)                            | FlowInGIOUSD    | USD          | 1 day          |
| Gemini Deposits (native units)                   | FlowInGEMNtv    | Native units | 1 block, 1 day |
| Gemini Deposits (USD)                            | FlowInGEMUSD    | USD          | 1 block, 1 day |
| HitBTC Deposits (native units)                   | FlowInHBTNtv    | Native units | 1 day          |
| HitBTC Deposits (USD)                            | FlowInHBTUSD    | USD          | 1 day          |
| Huobi Deposits (native units)                    | FlowInHUONtv    | Native units | 1 block, 1 day |
| Huobi Deposits (USD)                             | FlowInHUOUSD    | USD          | 1 block, 1 day |
| Korbit Deposits (native units)                   | FlowInKORNtv    | Native units | 1 day          |
| Korbit Deposits (USD)                            | FlowInKORUSD    | USD          | 1 day          |
| Kraken Deposits (native units)                   | FlowInKRKNtv    | Native units | 1 block, 1 day |
| Kraken Deposits (USD)                            | FlowInKRKUSD    | USD          | 1 block, 1 day |
| Kucoin Deposits (native units)                   | FlowInKCNNtv    | Native units | 1 day          |
| Kucoin Deposits (USD)                            | FlowInKCNUSD    | USD          | 1 day          |
| MEXC Deposits (native units)                     | FlowInMXCNtv    | Native units | 1 day          |
| MEXC Deposits (USD)                              | FlowInMXCUSD    | USD          | 1 day          |
| NBX Deposits (native units)                      | FlowInNBXNtv    | Native units | 1 day          |
| NBX Deposits (USD)                               | FlowInNBXUSD    | USD          | 1 day          |
| OKX Deposits (native units)                      | FlowInOKXNtv    | Native units | 1 day          |
| OKX Deposits (USD)                               | FlowInOKXUSD    | USD          | 1 day          |
| Poloniex Deposits (native units)                 | FlowInPOLNtv    | Native units | 1 block, 1 day |
| Poloniex Deposits (USD)                          | FlowInPOLUSD    | USD          | 1 block, 1 day |
| SwissBorg Deposits (native units)                | FlowInSBGNtv    | Native units | 1 day          |
| SwissBorg Deposits (USD)                         | FlowInSBGUSD    | USD          | 1 day          |
| All Exchanges Deposits (USD)                     | FlowInExUSD     | USD          | 1 day          |
| All Exchanges Deposits incl. EtoE (native units) | FlowInExInclNtv | Native units | 1 day          |
| All Exchanges Deposits incl. EtoE (USD)          | FlowInExInclUSD | USD          | 1 day          |

### Details

* Native units are considered as sent to an exchange if they are sent to an address we identify as being owned by an exchange.
* USD flows are computed as FlowIn{Exchange}Ntv \* PriceUSD

### Chart

<figure><img src="/files/27XxL7i08nMyaoCGoglw" alt=""><figcaption></figcaption></figure>

### Asset-Specific Details

* This metric might not be available for all assets. Either the exchange doesn’t support this asset, or we deemed that our coverage of the exchange was not complete enough to release the metric for it.
* For Bitcoin, this metric excludes the effect of change outputs:
  * If a transaction sends 90 BTC to exchange A but also withdraws 50 BTC from it, the flow is +40 BTC, not +90 BTC and -50 BTC.

### Examples

* During times of market stress or uncertainty, we see an uptick in BTC/funds being moved to exchanges. During the Luna collapse in spring 2021, we can see a rise in BTC being sent to both Bitfinex and Binance which is a precursor for more downside pressure as often times users are converting their funds into fiat or stable coins.

### Release History

* Released in the 4.0 release of NDP

### Interpretation

* This metric looks at the flow of funds being sent to Bitfinex and can give us a sense of market sentiment.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FlowInBFXNtv>" %}

## Exchange Depoosit Count <a href="#flowtfrin" id="flowtfrin"></a>

### Definition

The sum count of transfers to any address belonging to an exchange in that interval. If the sender address also belongs to Binfinex, the transfer is not counted.

<table><thead><tr><th>Name</th><th width="181">MetricID</th><th>Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Bitfinex Deposit Cnt</td><td>FlowTfrInBFXCnt</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>BitMEX Deposit Cnt</td><td>FlowTfrInBMXCnt</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>Binance Deposit Cnt</td><td>FlowTfrInBNBCnt</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>Bitstamp Deposit Cnt</td><td>FlowTfrInBSPCnt</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>Bitget Deposit Cnt</td><td>FlowTfrInBGTCnt</td><td>Native units</td><td>1 day</td></tr><tr><td>Bithumb Deposit Cnt</td><td>FlowTfrInBHMCnt</td><td>Native units</td><td>1 day</td></tr><tr><td>Bittrex Deposit Cnt</td><td>FlowTfrInBTXCnt</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>Bybit Deposit Cnt</td><td>FlowTfrInBITCnt</td><td>Native units</td><td>1 day</td></tr><tr><td>Cex.io Deposit Cnt</td><td>FlowTfrInCEXCnt</td><td>Native units</td><td>1 day</td></tr><tr><td>Coinbase Deposit Cnt</td><td>FlowTfrInCBSCnt</td><td>Native units</td><td>1 day</td></tr><tr><td>Crypto.com Deposit Cnt</td><td>FlowTfrInCROCnt</td><td>Native units</td><td>1 day</td></tr><tr><td>Deribit Deposit Cnt</td><td>FlowTfrInDERCnt</td><td>Native units</td><td>1 day</td></tr><tr><td>Gate.io Deposit Cnt</td><td>FlowTfrInGIOCnt</td><td>Native units</td><td>1 day</td></tr><tr><td>Gemini Deposit Cnt</td><td>FlowTfrInGEMCnt</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>HitBTC Deposit Cnt</td><td>FlowTfrInHBTCnt</td><td>Native Units</td><td>1 day</td></tr><tr><td>Huobi Deposit Cnt</td><td>FlowTfrInHUOCnt</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>Korbit Deposit Cnt</td><td>FlowTfrInKORCnt</td><td>Native units</td><td>1 day</td></tr><tr><td>Kraken Deposit Cnt</td><td>FlowTfrInKRKCnt</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>Kucoin Deposit Cnt</td><td>FlowTfrInKCNCnt</td><td>Native units</td><td>1 day</td></tr><tr><td>MEXC Deposit Cnt</td><td>FlowTfrInMXCCnt</td><td>Native units</td><td>1 day</td></tr><tr><td>NBX Deposit Cnt</td><td>FlowTfrInNBXCnt</td><td>Native units</td><td>1 day</td></tr><tr><td>OKX Deposit Cnt</td><td>FlowTfrInOKXCnt</td><td>Native units</td><td>1 day</td></tr><tr><td>Poloniex Deposit Cnt</td><td>FlowTfrInPOLCnt</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>SwissBorg Deposit Cnt</td><td>FlowTfrInSBGCnt</td><td>Native units</td><td>1 day</td></tr><tr><td>All Exchanges Deposit Cnt incl. EtoE</td><td>FlowTfrToExInclCnt</td><td>Transfers</td><td>1 day</td></tr></tbody></table>

### Details

* Coinbase (i.e., miner reward) transactions are not counted.

### Asset-Specific Details

* For UTXO-based protocols, this metric does not count change outputs:
* * If the input addresses belong to Bitfinex, then the outputs belonging to Bitfinex are not counted as transfers to Bitfinex
* For account-based protocols, if both sender and recipient belong to Bitfinex, then the transfer is not counted.

### Release History

* Version 4.2 of CM Network Data Pro Daily Macro (End of Day)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FlowTfrInBFXCnt>" %}

## API Endpoints

Exhange Deposits metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `FlowIn*` and `FlowTfrIn*` in the `metrics` parameter.

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=FlowInBFXNtv&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=FlowInBFXNtv&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="FlowInBFXNtv", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Exchange Supply

## Contents

* [Exchange Supply (SplyXNtv, SplyXUSD)](#splyex)

## Exchange Supply <a href="#splyex" id="splyex"></a>

### Definition

The sum held by an exchange at the end of that interval.

| Name                             | MetricID   | Unit         | Interval |
| -------------------------------- | ---------- | ------------ | -------- |
| Bitfinex Supply (native units)   | SplyBFXNtv | Native units | 1 day    |
| Bitfinex Supply (USD)            | SplyBFXUSD | USD          | 1 day    |
| BitMEX Supply (native units)     | SplyBMXNtv | Native units | 1 day    |
| BitMEX Supply (USD)              | SplyBMXUSD | USD          | 1 day    |
| Binance Supply (native units)    | SplyBNBNtv | Native units | 1 day    |
| Binance Supply (USD)             | SplyBNBUSD | USD          | 1 day    |
| Bitstamp Supply (native units)   | SplyBSPNtv | Native units | 1 day    |
| Bitstamp Supply (USD)            | SplyBSPUSD | USD          | 1 day    |
| Bittrex Supply (native units)    | SplyBTXNtv | Native units | 1 day    |
| Bittrex Supply (USD)             | SplyBTXUSD | USD          | 1 day    |
| Bybit Supply (native units)      | SplyBITNtv | Native units | 1 day    |
| Bybit Supply (USD)               | SplyBITUSD | USD          | 1 day    |
| Coinbase Supply (native units)   | SplyCBSNtv | Native units | 1 day    |
| Coinbase Supply (USD)            | SplyCBSUSD | USD          | 1 day    |
| Crypto.com Supply (native units) | SplyCRONtv | Native units | 1 day    |
| Crypto.com Supply (USD)          | SplyCROUSD | USD          | 1 day    |
| Deribit Supply (native units)    | SplyDERNtv | Native units | 1 day    |
| Deribit Supply (USD)             | SplyDERUSD | USD          | 1 day    |
| Exchange Supply (native units)   | SplyExNtv  | Native units | 1 day    |
| Exchange Supply (USD)            | SplyExUSD  | USD          | 1 day    |
| Gate.io Supply (native units)    | SplyGIONtv | Native units | 1 day    |
| Gate.io Supply (USD)             | SplyGIOUSD | USD          | 1 day    |
| Gemini Supply (native units)     | SplyGEMNtv | Native units | 1 day    |
| Gemini Supply (USD)              | SplyGEMUSD | USD          | 1 day    |
| HitBTC Supply (native units)     | SplyHBTNtv | Native units | 1 day    |
| HitBTC Supply (USD)              | SplyHBTUSD | USD          | 1 day    |
| Huobi Supply (native units)      | SplyHUONtv | Native units | 1 day    |
| Huobi Supply (USD)               | SplyHUOUSD | USD          | 1 day    |
| Korbit Supply (native units)     | SplyKORNtv | Native units | 1 day    |
| Korbit Supply (USD)              | SplyKORUSD | USD          | 1 day    |
| Kraken Supply (native units)     | SplyKRKNtv | Native units | 1 day    |
| Kraken Supply (USD)              | SplyKRKUSD | USD          | 1 day    |
| Kucoin Supply (native units)     | SplyKCNNtv | Native units | 1 day    |
| Kucoin Supply (USD)              | SplyKCNUSD | USD          | 1 day    |
| MEXC Supply (native units)       | SplyMXCNtv | Native units | 1 day    |
| MEXC Supply (USD)                | SplyMXCUSD | USD          | 1 day    |
| NBX Supply (native units)        | SplyNBXNtv | Native units | 1 day    |
| NBX Supply (USD)                 | SplyNBXUSD | USD          | 1 day    |
| OKX Supply (native units)        | SplyOKXNtv | Native units | 1 day    |
| OKX Supply (USD)                 | SplyOKXUSD | USD          | 1 day    |
| Poloniex Supply (native units)   | SplyPOLNtv | Native units | 1 day    |
| Poloniex Supply (USD)            | SplyPOLUSD | USD          | 1 day    |
| SwissBorg Supply (native units)  | SplySBGNtv | Native units | 1 day    |
| SwissBorg Supply (USD)           | SplySBGUSD | USD          | 1 day    |

### Details

* All wallets (hot and cold) are considered to count towards the supply held by an exchange.
* This metric should be seen as an underestimation of the actual figure, as our heuristics and sources might not discover all addresses owned by an exchange.
* USD metrics computed as SplyBFXNtv \* PriceUSD.
* `SplyEx*` includes the balances of all addresses we have flagged as being controlled by an exchange, even if our coverage of the exchange is not complete.

### Asset-Specific Details

* This metric might not be available for all assets. Either that exchange doesn’t support this asset (BitMEX only trades in BTC for example), or we deemed that our coverage of the exchange was not complete enough to release the metric for it.

### Release History

* Released in the 4.0 release of NDP

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/SplyBFXNtv>" %}

## API Endpoints

Exchange Supply metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `Sply{Exchange}*` in the `metrics` parameter.

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=SplyBFXNtv&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=SplyBFXNtv&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="SplyBFXNtv", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Net Flows

## Contents

* [Net Flows (FlowNetXNtv)](#flownet)

## Net Flows <a href="#flownet" id="flownet"></a>

## Definiton

The net unit value sent or withdrawn to/from an exchange in that interval.

<table><thead><tr><th>Name</th><th width="197">MetricID</th><th>Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Bitfinex Net Flows (native units)</td><td>FlowNetBFXNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Bitfinex Net Flows (USD)</td><td>FlowNetBFXUSD</td><td>USD</td><td>1 day</td></tr><tr><td>BitMEX Net Flows (native units)</td><td>FlowNetBMXNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>BitMEX Net Flows (USD)</td><td>FlowNetBMXUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Binance Net Flows (native units)</td><td>FlowNetBNBNtvFlow</td><td>Native units</td><td>1 day</td></tr><tr><td>Binance Net Flows (USD)</td><td>FlowNetBNBUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Bitstamp Net Flows (native units)</td><td>FlowNetBSPNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Bitstamp Net Flows (USD)</td><td>FlowNetBSPUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Bitget Net Flows (native units)</td><td>FlowNetBGTNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Bitget Net Flows (USD)</td><td>FlowNetBGTUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Bithumb Net Flows (native units)</td><td>FlowNetBHMNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Bithumb Net Flows (USD)</td><td>FlowNetBHMUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Bittrex Net Flows (native units)</td><td>FlowNetBTXNtvFlow</td><td>Native units</td><td>1 day</td></tr><tr><td>Bittrex Net Flows (USD)</td><td>FlowNetBTXUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Bybit Net Flows (native units)</td><td>FlowNetBITNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Bybit Net Flows (USD)</td><td>FlowNetBITUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Cex.io Net Flows (native units)</td><td>FlowNetCEXNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Cex.io Net Flows (USD)</td><td>FlowNetCEXUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Coinbase Net Flows (native units)</td><td>FlowNetCBSNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Coinbase Net Flows (USD)</td><td>FlowNetCBSUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Crypto.com Net Flows (native units)</td><td>FlowNetCRONtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Crypto.com Net Flows (USD)</td><td>FlowNetCROUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Deribit Net Flows (native units)</td><td>FlowNetDERNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Deribit Net Flows (USD)</td><td>FlowNetDERUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Gate.io Net Flows (native units)</td><td>FlowNetGIONtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Gate.io Net Flows (USD)</td><td>FlowNetGIOUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Gemini Net Flows (native units)</td><td>FlowNetGEMNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Gemini Net Flows (USD)</td><td>FlowNetGEMUSD</td><td>USD</td><td>1 day</td></tr><tr><td>HitBTC Net Flows (native units)</td><td>FlowNetHBTNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>HitBTC Net Flows (USD)</td><td>FlowNetHBTUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Huobi Net Flows (native units)</td><td>FlowNetHUONtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Huobi Net Flows (USD)</td><td>FlowNetHUOUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Korbit Net Flows (native units)</td><td>FlowNetKORNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Korbit Net Flows (USD)</td><td>FlowNetKORUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Kraken Net Flows (native units)</td><td>FlowNetKRKNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Kraken Net Flows (USD)</td><td>FlowNetKRKUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Kucoin Net Flows (native units)</td><td>FlowNetKCNNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Kucoin Net Flows (USD)</td><td>FlowNetKCNUSD</td><td>USD</td><td>1 day</td></tr><tr><td>MEXC Net Flows (native units)</td><td>FlowNetMXCNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>MEXC Net Flows (USD)</td><td>FlowNetMXCUSD</td><td>USD</td><td>1 day</td></tr><tr><td>NBX Net Flows (native units)</td><td>FlowNetNBXNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>NBX Net Flows (USD)</td><td>FlowNetNBXUSD</td><td>USD</td><td>1 day</td></tr><tr><td>OKX Net Flows (native units)</td><td>FlowNetOKXNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>OKX Net Flows (USD)</td><td>FlowNetOKXUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Poloniex Net Flows (native units)</td><td>FlowNetPOLNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Poloniex Net Flows (USD)</td><td>FlowNetPOLUSD</td><td>USD</td><td>1 day</td></tr><tr><td>SwissBorg Net Flows (native units)</td><td>FlowNetSBGNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>SwissBorg Net Flows (USD)</td><td>FlowNetSBGUSD</td><td>USD</td><td>1 day</td></tr></tbody></table>

### Details

* Native units are considered as sent to an exchange if they are sent to an address we identify as being owned by an exchange.
* Native units are considered as withdrawn if they leave the control of an address we identify as being owned by an exchange.
* This metric is the net of the sends and withdrawals that interval.
* USD metrics are computed as FlowNet{Exchange}Ntv \* PriceUSD

### Asset-Specific Details

* This metric might not be available for all assets. Either that exchange doesn’t support this asset (BitMEX only trades in BTC for example), or we deemed that our coverage of the exchange was not complete enough to release the metric for it.
* For Bitcoin, this metric excludes the effect of change outputs:
  * If a transaction sends 90 BTC to exchange A but also withdraws 50 BTC from it, the flow is +40 BTC, not +90 BTC and -50 BTC.

### Release History

* Released in the 4.0 release of NDP

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FlowNetBFXNtv>" %}

## API Endpoints

Net Flow metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `FlowNet*` in the `metrics` parameter.

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=FlowNetBFXNtv&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=FlowNetBFXNtv&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="FlowNetBFXNtv", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Pairwise Flows

## Overview

Pairwise flow metrics measure the directional value moving from one tagged entity to another, for example from Coinbase to Binance. Each metric covers a specific ordered pair of entities and includes value that moves indirectly through untagged intermediary wallets for up to two hops, not only direct transfers between the two entities. These metrics can be used to track capital movement between exchanges.

## At a Glance

<table data-full-width="true"><thead><tr><th>Data type</th><th>Entities</th><th width="159">Frequency / cadence</th><th>Unit</th><th>Primary endpoint</th></tr></thead><tbody><tr><td>Metric</td><td>Assets</td><td>1 day, 1 hour</td><td>Native units, USD, transfer count</td><td><code>/timeseries/asset-metrics</code></td></tr></tbody></table>

## Metrics

Each supported ordered entity pair emits three metrics, named with the pair's entity codes in place of `{EntityA}` and `{EntityB}`:

<table data-full-width="true"><thead><tr><th width="360">Metric</th><th>Description</th><th>Frequency</th><th>Coverage</th></tr></thead><tbody><tr><td><code>FlowFrom{EntityA}To{EntityB}Ntv</code></td><td>Native-unit value attributed as flowing from EntityA to EntityB, including value routed through untagged intermediary wallets for up to two hops.</td><td>1d, 1h</td><td><a href="https://coverage.coinmetrics.io/asset-metrics-v2/FlowFromCBSToBNBNtv">🔗</a></td></tr><tr><td><code>FlowFrom{EntityA}To{EntityB}USD</code></td><td>USD value of the same flow, derived from the Ntv metric and the asset's reference rate.</td><td>1d, 1h</td><td><a href="https://coverage.coinmetrics.io/asset-metrics-v2/FlowFromCBSToBNBUSD">🔗</a></td></tr><tr><td><code>FlowTfrFrom{EntityA}To{EntityB}Cnt</code></td><td>Expected number of transfers attributed to this flow, emitted as a whole transfer count. Direct entity-to-entity transfers contribute exact counts and value routed through untagged wallets contributes a fractional expected count; the two are summed and rounded to the nearest whole transfer, with any positive value below one rounded up to one.</td><td>1d, 1h</td><td><a href="https://coverage.coinmetrics.io/asset-metrics-v2/FlowTfrFromCBSToBNBCnt">🔗</a></td></tr></tbody></table>

As of the current release, supported pairs cover six major centralized exchanges — **30 ordered pairs** among them — on USDC on Ethereum. Each pair emits the three metrics above, for **90** metrics in total. The data spans from genesis up to the present. See [Supported pairs](#supported-pairs) for the entity codes and pair matrix.

## Methodology

Each pairwise flow combines two attribution paths over the metric's interval.

### Direct transfers

A transfer sent directly from an address belonging to the source entity to an address belonging to the destination entity is counted in full, with an exact integer transfer count. Transfers with a negative native-unit amount are included when summing flow values, but they do not contribute to the transfer count.

### Through-user attribution

Value that passes through one or more untagged wallets before reaching the destination entity is attributed back to a source entity using a haircut method (Moser, Böhme & Breuker, 2014). When an untagged wallet forwards value onward, each source's share of that outgoing value is proportional to the source's share of the wallet's total available funds at that point:

$$
\text{share}\_{\text{source}} = \frac{\text{value received from source}}{\text{closing balance} + \text{total outflow}}
$$

This keeps attribution conservative in two ways. A source's attributed flow can never exceed what it actually sent, since attribution is capped per entity pair. And because closing balances are never negative, a wallet's denominator is always at least its total outflow, so attribution can only be diluted across multiple destinations, never inflated.

Each supported pair has an independently configured maximum hop depth: direct pairs only match tagged-to-tagged transfers, while other pairs also follow chains of untagged wallet-to-wallet hops (source, then one or more intermediary wallets, then destination) up to that pair's configured depth.

Every tagged address, whether an exchange, a lending protocol, an ETF, a layer-2 bridge, or another tagged category, acts as a boundary that attribution cannot pass through. This keeps flow from being misattributed through a different known entity that happens to sit along the path.

### Transfer counts

Direct transfers contribute an exact integer count, while through-user attribution contributes a fractional expected count in which each wallet-to-destination deposit adds the source's attributed share at that hop. The direct and through-user counts are summed, and the emitted metric is rounded to the nearest whole transfer (ties rounded up), except that any positive value below one is rounded up to one so a small but real attributed flow is never reported as zero.

### Lookback window

Multi-hop chains can span more than one interval, since an intermediary wallet may hold funds for a period before forwarding them. Both the 1-hour and 1-day metrics account for this using a trailing lookback window so these chains are still attributed correctly, while only deposits landing inside the target interval are counted toward that interval's value. Each deposit is counted in exactly one interval, though its source attribution can reach back across the lookback window.

For more information, see [Pairwise Flow Lookback Window](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/tree/master/docs/methodologies/pairwise-flow-lookback-window.md).

## Accessing the Data

{% tabs %}
{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        assets="usdc_eth",
        metrics=["FlowFromCBSToBNBNtv", "FlowFromCBSToBNBUSD", "FlowTfrFromCBSToBNBCnt"],
        frequency="1d",
    ).to_dataframe()
)
```

{% endtab %}

{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?assets=usdc_eth&metrics=FlowFromCBSToBNBNtv,FlowFromCBSToBNBUSD,FlowTfrFromCBSToBNBCnt&frequency=1d&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

response = requests.get(
    "https://api.coinmetrics.io/v4/timeseries/asset-metrics",
    params={
        "assets": "usdc_eth",
        "metrics": "FlowFromCBSToBNBNtv,FlowFromCBSToBNBUSD,FlowTfrFromCBSToBNBCnt",
        "frequency": "1d",
        "api_key": "YOUR_API_KEY",
    },
).json()
print(response)
```

{% endtab %}
{% endtabs %}

Full parameter reference: see the API Reference for [`/timeseries/asset-metrics`](https://docs.coinmetrics.io/api/v4/#operation/getTimeseriesAssetMetrics).

## Supported pairs

Pairwise flow metrics are available for every ordered pair among the following six exchanges. Self-pairs (an exchange to itself) are not included.

| Exchange | Code |
| -------- | ---- |
| Binance  | BNB  |
| Bybit    | BIT  |
| Coinbase | CBS  |
| Kraken   | KRK  |
| KuCoin   | KCN  |
| OKX      | OKX  |

Metric names use these codes in place of `{EntityA}` and `{EntityB}`. For example, Coinbase to Binance native units is `FlowFromCBSToBNBNtv`.

The grid below shows every supported direction. Rows are the source exchange; columns are the destination. A filled cell is an available ordered pair.

<table data-full-width="true"><thead><tr><th></th><th>BNB</th><th>BIT</th><th>CBS</th><th>KRK</th><th>KCN</th><th>OKX</th></tr></thead><tbody><tr><td><strong>BNB</strong></td><td></td><td>●</td><td>●</td><td>●</td><td>●</td><td>●</td></tr><tr><td><strong>BIT</strong></td><td>●</td><td></td><td>●</td><td>●</td><td>●</td><td>●</td></tr><tr><td><strong>CBS</strong></td><td>●</td><td>●</td><td></td><td>●</td><td>●</td><td>●</td></tr><tr><td><strong>KRK</strong></td><td>●</td><td>●</td><td>●</td><td></td><td>●</td><td>●</td></tr><tr><td><strong>KCN</strong></td><td>●</td><td>●</td><td>●</td><td>●</td><td></td><td>●</td></tr><tr><td><strong>OKX</strong></td><td>●</td><td>●</td><td>●</td><td>●</td><td>●</td><td></td></tr></tbody></table>


# Transaction Count

## Contents

* [Exchange Tx Cnt (TxExCnt)](#txexcnt)

## Exchange Tx Cnt <a href="#txexcnt" id="txexcnt"></a>

### Definition

The sum count of transactions that involved any address belonging to an exchange, as a sender or recipient of a non-zero transfer of native units, in that interval. If a transaction involves multiple exchanges, it is only counted once.

| Name            | ID      | Unit         | Interval |
| --------------- | ------- | ------------ | -------- |
| Exchange Tx Cnt | TxExCnt | Transactions | 1 day    |

### Details

* Coinbase (i.e., miner reward) transactions are not counted.
* Only exchanges and their addresses that Coin Metrics has identified are included (i.e., not all exchanges and their addresses have been identified) so this metric should be thought of as a minimum potential value.

### Release History

* Version 4.2 of CM Network Data Pro Daily Macro (End of Day)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/TxExCnt>" %}

## API Endpoints

Exchange Transaction Count metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `TxExCnt` in the `metrics` parameter.

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=TxExCnt&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=TxExCnt&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="TxExCnt", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Withdrawals

## Contents

* [Exchange Withdrawals (FlowOutXNtv, FlowOutXUSD)](#flowout)
* [Exchange Withdrawals (Total) (FlowOutExNtv, FlowOutExUSD)](#flowoutex)
* [Exchange Withdrawals, Incl EtoE (FlowOutExInclUSD)](#flowoutexincl)
* [Withdrawal Count (FlowTfrOutXCnt)](#flowtfrout)

## Exchange Withdrawals <a href="#flowout" id="flowout"></a>

### Definition

The sum withdrawn from an exchange that day.

<table><thead><tr><th>Name</th><th width="181">MetricID</th><th>Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Bitfinex Withdrawals (native units)</td><td>FlowOutBFXNtv</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>Bitfinex Withdrawals (USD)</td><td>FlowOutBFXUSD</td><td>USD</td><td>1 block, 1 day</td></tr><tr><td>BitMEX Withdrawals (native units)</td><td>FlowOutBMXNtv</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>BitMEX Withdrawals (USD)</td><td>FlowOutBMXUSD</td><td>USD</td><td>1 block, 1 day</td></tr><tr><td>Binance Withdrawals (native units)</td><td>FlowOutBNBNtv</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>Binance Withdrawals (USD)</td><td>FlowOutBNBUSD</td><td>USD</td><td>1 block, 1 day</td></tr><tr><td>Bitstamp Withdrawals (native units)</td><td>FlowOutBSPNtv</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>Bitstamp Withdrawals (USD)</td><td>FlowOutBSPUSD</td><td>USD</td><td>1 block, 1 day</td></tr><tr><td>Bitget Withdrawals (native units)</td><td>FlowOutBGTNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Bitget Withdrawals (USD)</td><td>FlowOutBGTUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Bithumb Withdrawals (native units)</td><td>FlowOutBHMNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Bithumb Withdrawals (USD)</td><td>FlowOutBHMUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Bittrex Withdrawals (native units)</td><td>FlowOutBTXNtv</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>Bittrex Withdrawals (USD)</td><td>FlowOutBTXUSD</td><td>USD</td><td>1 block, 1 day</td></tr><tr><td>Bybit Withdrawals (native units)</td><td>FlowOutBITNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Bybit Withdrawals (USD)</td><td>FlowOutBITUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Cex.io Withdrawals (native units)</td><td>FlowOutCEXNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Cex.io Withdrawals (USD)</td><td>FlowOutCEXUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Coinbase Withdrawals (native units)</td><td>FlowOutCBSNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Coinbase Withdrawals (USD)</td><td>FlowOutCBSUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Crypto.com Withdrawals (native units)</td><td>FlowOutCRONtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Crypto.com Withdrawals (USD)</td><td>FlowOutCROUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Deribit Withdrawals (native units)</td><td>FlowOutDERNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Deribit Withdrawals (USD)</td><td>FlowOutDERUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Gate.io Withdrawals (native units)</td><td>FlowOutGIONtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Gate.io Withdrawals (USD)</td><td>FlowOutGIOUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Gemini Withdrawals (native units)</td><td>FlowOutGEMNtv</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>Gemini Withdrawals (USD)</td><td>FlowOutGEMUSD</td><td>USD</td><td>1 block, 1 day</td></tr><tr><td>HitBTC Withdrawals (native units)</td><td>FlowOutHBTNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>HitBTC Withdrawals (USD)</td><td>FlowOutHBTUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Huobi Withdrawals (native units)</td><td>FlowOutHUONtv</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>Huobi Withdrawal (USD)</td><td>FlowOutHUOUSD</td><td>USD</td><td>1 block, 1 day</td></tr><tr><td>Korbit Withdrawals (native units)</td><td>FlowOutKORNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Korbit Withdrawals (USD)</td><td>FlowOutKORUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Kraken Withdrawals (native units)</td><td>FlowOutKRKNtv</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>Kraken Withdrawals (USD)</td><td>FlowOutKRKUSD</td><td>USD</td><td>1 block, 1 day</td></tr><tr><td>Kucoin Withdrawals (native units)</td><td>FlowOutKCNNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Kucoin Withdrawals (USD)</td><td>FlowOutKCNUSD</td><td>USD</td><td>1 day</td></tr><tr><td>MEXC Withdrawals (native units)</td><td>FlowOutMXCNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>MEXC Withdrawals (USD)</td><td>FlowOutMXCUSD</td><td>USD</td><td>1 day</td></tr><tr><td>NBX Withdrawals (native units)</td><td>FlowOutNBXNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>NBX Withdrawals (USD)</td><td>FlowOutNBXUSD</td><td>USD</td><td>1 day</td></tr><tr><td>OKX Withdrawals (native units)</td><td>FlowOutOKXNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>OKX Withdrawals (USD)</td><td>FlowOutOKXUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Poloniex Withdrawals (native units)</td><td>FlowOutPOLNtv</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>Poloniex Withdrawals (USD)</td><td>FlowOutPOLUSD</td><td>USD</td><td>1 block, 1 day</td></tr><tr><td>SwissBorg Withdrawals (native units)</td><td>FlowOutSBGNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>SwissBorg Withdrawals (USD)</td><td>FlowOutSBGUSD</td><td>USD</td><td>1 day</td></tr></tbody></table>

### Details

* Native units are considered as withdrawn if they leave the control of an address we identify as being owned by an exchange.

### Asset-Specific Details

* This metric might not be available for all assets. Either that exchange doesn’t support this asset (BitMEX only trades in BTC for example), or we deemed that our coverage of the exchange was not complete enough to release the metric for it.
* For Bitcoin, this metric excludes the effect of change outputs:
  * If a transaction spends 100 BTC from exchange A but 90 BTC are sent back to it as change, the flow is -10 BTC, not -100 BTC and +90 BTC.

### Release History

* Released in the 4.0 release of NDP

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FlowOutBFXNtv>" %}

## Exchange Withdrawals (Total) <a href="#flowoutex" id="flowoutex"></a>

### Definition

The sum withdrawn from exchanges that day, excluding exchange to exchange activity.

| Name                                | MetricID     | Unit         | Interval       |
| ----------------------------------- | ------------ | ------------ | -------------- |
| Exchange Withdrawals (native units) | FlowOutExNtv | Native units | 1 block, 1 day |
| Exchange Withdrawals (USD)          | FlowOutExUSD | USD          | 1 block, 1 day |

### Details

* This metric captures interactions between users of a cryptoasset and exchanges supporting that market. It excludes inter-exchange activity.
* If a transaction sends 90 units from exchange B to exchange A, it doesn’t count towards this metric.
* If a transaction spends 10 units from exchange A and sends 5 units to exchange B and 5 units to unknown destination, it counts as a 5 units outflow for exchanges overall, 10 units outflow for exchange A, 5 units inflow for exchange B

### Release History

* Released in the 4.0 release of NDP

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FlowOutExNtv>" %}

## Exchange Withdrawals, Incl EtoE (USD) <a href="#flowoutexincl" id="flowoutexincl"></a>

### Definition

The sum USD value withdrawn from exchanges that day, including exchange to exchange activity.

<table><thead><tr><th>Name</th><th width="180">MetricID</th><th width="116">Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Exchange Withdrawals, Incl EtoE (USD)</td><td>FlowOutExInclUSD</td><td>USD</td><td>1 block, 1 day</td></tr></tbody></table>

### Details

* Computed as FlowOutExInclNtv \* PriceUSD
* If a transaction sends 90 units from exchange B to exchange A, it counts towards this metric.
* If a transaction moves 90 units inside exchange A (cold to hot or equivalent), it doesn’t count towards this metric.

### Release History

* Released in the 4.0 release of NDP

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FlowOutExInclUSD>" %}

## Withdrawal Cnt <a href="#flowtfrout" id="flowtfrout"></a>

### Definition

The sum count of transfers from any address belonging to an exchange in that interval. If the recipient address also belongs to the same exchange, the transfer is not counted.

<table><thead><tr><th>Name</th><th width="186">MetricID</th><th>Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Bitfinex Withdrawal Cnt</td><td>FlowTfrOutBFXCnt</td><td>Transfers</td><td>1 block, 1 day</td></tr><tr><td>BitMEX Withdrawal Cnt</td><td>FlowTfrOutBMXCnt</td><td>Transfers</td><td>1 block, 1 day</td></tr><tr><td>Binance Withdrawal Cnt</td><td>FlowTfrOutBNBCnt</td><td>Transfers</td><td>1 block, 1 day</td></tr><tr><td>Bitstamp Withdrawal Cnt</td><td>FlowTfrOutBSPCnt</td><td>Transfers</td><td>1 block, 1 day</td></tr><tr><td>Bitget Withdrawal Cnt</td><td>FlowTfrOutBGTCnt</td><td>Transfers</td><td>1 day</td></tr><tr><td>Bithumb Withdrawal Cnt</td><td>FlowTfrOutBHMCnt</td><td>Transfers</td><td>1 day</td></tr><tr><td>Bittrex Withdrawal Cnt</td><td>FlowTfrOutBTXCnt</td><td>Transfers</td><td>1 block, 1 day</td></tr><tr><td>ByBit Withdrawal Cnt</td><td>FlowTfrOutBITCnt</td><td>Transfers</td><td>1 day</td></tr><tr><td>Cex.io Withdrawal Cnt</td><td>FlowTfrOutCEXCnt</td><td>Transfers</td><td>1 day</td></tr><tr><td>Coinbase Withdrawal Cnt</td><td>FlowTfrOutCBSCnt</td><td>Transfers</td><td>1 day</td></tr><tr><td>Crypto.com Withdrawal Cnt</td><td>FlowTfrOutCROCnt</td><td>Transfers</td><td>1 day</td></tr><tr><td>Deribit Withdrawal Cnt</td><td>FlowTfrOutDERCnt</td><td>Transfers</td><td>1 day</td></tr><tr><td>Gate.io Withdrawal Cnt</td><td>FlowTfrOutGIOCnt</td><td>Transfers</td><td>1 day</td></tr><tr><td>Gemini Withdrawal Cnt</td><td>FlowTfrOutGEMCnt</td><td>Transfers</td><td>1 block, 1 day</td></tr><tr><td>HitBTC Withdrawal Cnt</td><td>FlowTfrOutHBTCnt</td><td>Transfers</td><td>1 day</td></tr><tr><td>Huobi Withdrawal Cnt</td><td>FlowTfrOutHUOCnt</td><td>Transfers</td><td>1 block, 1 day</td></tr><tr><td>Korbit Withdrawal Cnt</td><td>FlowTfrOutKORCnt</td><td>Transfers</td><td>1 day</td></tr><tr><td>Kraken Withdrawal Cnt</td><td>FlowTfrOutKRKCnt</td><td>Transfers</td><td>1 block, 1 day</td></tr><tr><td>Kucoin Withdrawal Cnt</td><td>FlowTfrOutKCNCnt</td><td>Transfers</td><td>1 day</td></tr><tr><td>MEXC Withdrawal Cnt</td><td>FlowTfrOutMXCCnt</td><td>Transfers</td><td>1 day</td></tr><tr><td>NBX Withdrawal Cnt</td><td>FlowTfrOutNBXCnt</td><td>Transfers</td><td>1 day</td></tr><tr><td>OKX Withdrawal Cnt</td><td>FlowTfrOutOKXCnt</td><td>Transfers</td><td>1 day</td></tr><tr><td>Poloniex Withdrawal Cnt</td><td>FlowTfrOutPOLCnt</td><td>Transfers</td><td>1 block, 1 day</td></tr><tr><td>SwissBorg Withdrawal Cnt</td><td>FlowTfrOutSBGCnt</td><td>Transfers</td><td>1 day</td></tr><tr><td>All Exchanges Withdrawal Cnt</td><td>FlowTfrFromExCnt</td><td>Transfers</td><td>1 day</td></tr><tr><td>All Exchanges Withdrawal Cnt incl. EtoE</td><td>FlowTfrFromExInclCnt</td><td>Transfers</td><td>1 day</td></tr></tbody></table>

### Details

* Coinbase (i.e., miner reward) transactions are not counted.

### Asset-Specific Details

* For account-based protocols, if both sender and recipient belong to the same exchange, then the transfer is not counted.
* For UTXO-based protocols, this metric applies the following logic:
  * If the input addresses belong to an exchange, then only the outputs where the address doesn’t belong to the same exchange are counted as transfers from that exchange.

### Release History

* Version 4.2 of CM Network Data Pro Daily Macro (End of Day)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FlowTfrOutBFXCnt>" %}

## API Endpoints

Withdrawal metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `FlowOut*` and `FlowTfrOut*` in the `metrics` parameter.

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=FlowOutBFXUSD&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=FlowOutBFXUSD&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="FlowOutBFXUSD", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Exchange Traded Fund

The following lists the exchanges we cover in our on-chain metrics calculations for on-chain supply, on-chain deposits, on-chain withdrawals, and net flows as part of our Network Data Pro product.

## Exchange

Exchange Traded Fund (ETF) metrics showcase the on-chain fingerprint provided by **coin movement into/out of ETF addresses**.

## On-Chain ETF Coverage

### ETF On-Chain Flows & Supply Metrics Coverage

{% hint style="info" %}
Exchange On-Chain Supply, Deposits, Withdrawals and Net Flows can be found in the [Asset Metrics endpoint](https://docs.coinmetrics.io/api/v4#operation/getTimeseriesAssetMetrics)
{% endhint %}

| BlackRock           | BLK |
| ------------------- | --- |
| ARK Invest          | ARK |
| Franklin Templeton  | TMP |
| Grayscale           | GSC |
| Invesco             | INV |
| Valkyrie            | VLK |
| VanEck              | VAN |
| WisdomTree          | WDT |
| Bitwise             | BWS |
| Aggregate ETF Flows | Etf |

For more details on asset coverage for ETF supply or flows metrics, see the individual metric in the Asset Metrics section of this Data Encyclopedia.

## Metrics

[**Deposits**](/network-data/network-data-overview/exchange-traded-fund/deposits)

[**Exchange Supply**](/network-data/network-data-overview/exchange-traded-fund/exchange-traded-fund-supply)

[**Net Flows**](/network-data/network-data-overview/exchange-traded-fund/net-flows)

[**Transaction Count**](/network-data/network-data-overview/exchange-traded-fund/transaction-count)

[**Withdrawals**](/network-data/network-data-overview/exchange-traded-fund/withdrawals)


# Deposits

## Contents

* [ETF Deposits (FlowInXNtv, FlowInXUSD)](#flowin)
* [ETF Deposit Count (FlowTfrInXCnt)](#flowtfrin)

## ETF Deposits <a href="#flowin" id="flowin"></a>

### Definition

The sum of assets sent to an ETF that interval.

| Name                                                         | MetricID         | Unit         | Interval |
| ------------------------------------------------------------ | ---------------- | ------------ | -------- |
| ARK Invest Deposits (native units)                           | FlowInARKNtv     | Native units | 1 day    |
| ARK Invest Deposits (USD)                                    | FlowInARKUSD     | USD          | 1 day    |
| BlackRock Deposits (native units)                            | FlowInBLKNtv     | Native units | 1 day    |
| BlackRock Deposits (USD)                                     | FlowInBLKUSD     | USD          | 1 day    |
| Bitwise Deposits (native units)                              | FlowInBWSNtv     | Native units | 1 day    |
| Bitwise Deposits (USD)                                       | FlowInBWSUSD     | USD          | 1 day    |
| Exchange Traded Fund deposits, Including EtoE (native units) | FlowInEtfInclNtv | Native units | 1 day    |
| Exchange Traded Fund deposits, Including EtoE (USD)          | FlowInEtfInclUSD | USD          | 1 day    |
| Exchange Traded Fund Deposits (native units)                 | FlowInEtfNtv     | Native units | 1 day    |
| Exchange Traded Fund Deposits (USD)                          | FlowInEtfUSD     | USD          | 1 day    |
| Grayscale Deposits (native units)                            | FlowInGSCNtv     | Native units | 1 day    |
| Grayscale Deposits (USD)                                     | FlowInGSCUSD     | USD          | 1 day    |
| Invesco Deposits (native units)                              | FlowInINVNtv     | Native units | 1 day    |
| Invesco Deposits (USD)                                       | FlowInINVUSD     | USD          | 1 day    |
| Franklin Templeton Deposits (native units)                   | FlowInTMPNtv     | Native units | 1 day    |
| Franklin Templeton Deposits (USD)                            | FlowInTMPUSD     | USD          | 1 day    |
| VanEck Deposits (native units)                               | FlowInVANNtv     | Native units | 1 day    |
| VanEck Deposits (USD)                                        | FlowInVANUSD     | USD          | 1 day    |
| Valkyrie Deposits (native units)                             | FlowInVLKNtv     | Native units | 1 day    |
| Valkyrie Deposits (USD)                                      | FlowInVLKUSD     | USD          | 1 day    |
| WisdomTree Deposits (native units)                           | FlowInWDTNtv     | Native units | 1 day    |
| WisdomTree Deposits (USD)                                    | FlowInWDTUSD     | USD          | 1 day    |

### Details

* Native units are considered as sent to an ETF if they are sent to an address we identify as being owned by an ETF.
* USD flows are computed as FlowIn{ETF}Ntv \* PriceUSD

### Asset-Specific Details

* For Bitcoin, this metric excludes the effect of change outputs:
  * If a transaction sends 90 BTC to exchange A but also withdraws 50 BTC from it, the flow is +40 BTC, not +90 BTC and -50 BTC.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FlowInEtfInclNtv>" %}

## ETF Deposit Count <a href="#flowtfrin" id="flowtfrin"></a>

### Definition

The sum count of transfers to any address belonging to an ETF in that interval. If the sender address also belongs to an ETF, the transfer is not counted.

<table><thead><tr><th>Name</th><th width="181">MetricID</th><th>Unit</th><th>Interval</th></tr></thead><tbody><tr><td>ARK Invest Deposit Count</td><td>FlowTfrInARKCnt</td><td>Deposits</td><td>1 day</td></tr><tr><td>BlackRock Deposit Count</td><td>FlowTfrInBLKCnt</td><td>Deposits</td><td>1 day</td></tr><tr><td>Bitwise Deposit Count</td><td>FlowTfrInBWSCnt</td><td>Deposits</td><td>1 day</td></tr><tr><td>Grayscale Deposit Count</td><td>FlowTfrInGSCCnt</td><td>Deposits</td><td>1 day</td></tr><tr><td>Invesco Deposit Count</td><td>FlowTfrInINVCnt</td><td>Deposits</td><td>1 day</td></tr><tr><td>Franklin Templeton Deposit Count</td><td>FlowTfrInTMPCnt</td><td>Deposits</td><td>1 day</td></tr><tr><td>VanEck Deposit Count</td><td>FlowTfrInVANCnt</td><td>Deposits</td><td>1 day</td></tr><tr><td>Valkyrie Deposit Count</td><td>FlowTfrInVLKCnt</td><td>Deposits</td><td>1 day</td></tr><tr><td>WisdomTree Deposit Count</td><td>FlowTfrInWDTCnt</td><td>Deposits</td><td>1 day</td></tr><tr><td>Exchange Traded Fund Deposits Count</td><td>FlowTfrToEtfCnt</td><td>Deposits</td><td>1 day</td></tr><tr><td>Exchange Traded Fund Deposits Count, incl EtoE</td><td>FlowTfrToEtfInclCnt</td><td>Deposits</td><td>1 day</td></tr></tbody></table>

### Details

* Coinbase (i.e., miner reward) transactions are not counted.

### Asset-Specific Details

* For UTXO-based protocols, this metric does not count change outputs:
  * If the input addresses belong to a given ETF, then the outputs belonging to the same ETF are not counted as transfers to that ETF

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FlowTfrInARKCnt>" %}

## API Endpoints

ETF Deposits metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `FlowIn*` and `FlowTfrIn*` in the `metrics` parameter.

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=FlowInARKNtv&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=FlowInARKNtv&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="FlowInARKNtv", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Exchange Traded Fund Supply

## Contents

* [ETF Supply (SplyXNtv, SplyXUSD)](#splyex)

## ETF Supply <a href="#splyex" id="splyex"></a>

### Definition

The sum held by an ETF at the end of that interval.

| Name                                       | MetricID   | Unit         | Interval |
| ------------------------------------------ | ---------- | ------------ | -------- |
| ARK Invest Supply (native units)           | SplyARKNtv | Native units | 1 day    |
| ARK Invest Supply (USD)                    | SplyARKUSD | USD          | 1 day    |
| BlackRock Supply (native units)            | SplyBLKNtv | Native units | 1 day    |
| BlackRock Supply (USD)                     | SplyBLKUSD | USD          | 1 day    |
| Bitwise Supply (native units)              | SplyBWSNtv | Native units | 1 day    |
| Bitwise Supply (USD)                       | SplyBWSUSD | USD          | 1 day    |
| Exchange Traded Fund Supply (native units) | SplyEtfNtv | Native units | 1 day    |
| Exchange Traded Fund Supply (USD)          | SplyEtfUSD | USD          | 1 day    |
| Grayscale Supply (native units)            | SplyGSCNtv | Native units | 1 day    |
| Grayscale Supply (USD)                     | SplyGSCUSD | USD          | 1 day    |
| Invesco Supply (native units)              | SplyINVNtv | Native units | 1 day    |
| Invesco Supply (USD)                       | SplyINVUSD | USD          | 1 day    |
| Franklin Templeton Supply (native units)   | SplyTMPNtv | Native units | 1 day    |
| Franklin Templeton Supply (USD)            | SplyTMPUSD | USD          | 1 day    |
| VanEck Supply (native units)               | SplyVANNtv | Native units | 1 day    |
| VanEck Supply (USD)                        | SplyVANUSD | USD          | 1 day    |
| Valkyrie Supply (native units)             | SplyVLKNtv | Native units | 1 day    |
| Valkyrie Supply (USD)                      | SplyVLKUSD | USD          | 1 day    |
| WisdomTree Supply (native units)           | SplyWDTNtv | Native units | 1 day    |
| WisdomTree Supply (USD)                    | SplyWDTUSD | USD          | 1 day    |

### Details

* All wallets (hot and cold) are considered to count towards the supply held by an ETF.
* USD metrics computed as `Sply{ETF}Ntv * PriceUSD`.
* `SplyEtf*` includes the balances of all addresses we have flagged as being controlled by an ETF.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/SplyEtfNtv>" %}

## API Endpoints

Exchange Supply metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `Sply{ETF}*` in the `metrics` parameter.

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=SplyARKNtv&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=SplyARKNtv&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="SplyARKNtv", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Net Flows

## Contents

* [Net Flows (FlowNetXNtv)](#flownet)

## Net Flows <a href="#flownet" id="flownet"></a>

## Definiton

The net unit value sent or withdrawn to/from an ETF in that interval.

<table><thead><tr><th>Name</th><th width="197">MetricID</th><th>Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Ark Invest Net Flows (native units)</td><td>FlowNetARKNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Ark Invest Net Flows (USD)</td><td>FlowNetARKUSD</td><td>USD</td><td>1 day</td></tr><tr><td>BlackRock Net Flows (native units)</td><td>FlowNetBLKNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>BlackRock Net Flows (USD)</td><td>FlowNetBLKUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Bitwise Net Flows (native units)</td><td>FlowNetBWSNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Bitwise Net Flows (USD)</td><td>FlowNetBWSUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Grayscale Net Flows (native units)</td><td>FlowNetGSCNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Grayscale Net Flows (USD)</td><td>FlowNetGSCUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Invesco Net Flows (native units)</td><td>FlowNetINVNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Invesco Net Flows (USD)</td><td>FlowNetINVUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Franklin Templeton Net Flows (native units)</td><td>FlowNetTMPNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Franklin Templeton Net Flows (USD)</td><td>FlowNetTMPUSD</td><td>USD</td><td>1 day</td></tr><tr><td>VanEck Net Flows (native units)</td><td>FlowNetVANNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>VanEck Net Flows (USD)</td><td>FlowNetVANUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Valkyrie Net Flows (native units)</td><td>FlowNetVLKNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Valkyrie Net Flows (USD)</td><td>FlowNetVLKUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Wisdomtree Net Flows (native units)</td><td>FlowNetWDTNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Wisdomtree Net Flows (USD)</td><td>FlowNetWDTUSD</td><td>USD</td><td>1 day</td></tr></tbody></table>

### Details

* Native units are considered as sent to an ETF if they are sent to an address we identify as being owned by an ETF.
* Native units are considered as withdrawn if they leave the control of an address we identify as being owned by an ETF.
* This metric is the net of the sends and withdrawals that interval.
* USD metrics are computed as `FlowNet{ETF}Ntv * PriceUSD`

### Asset-Specific Details

* For Bitcoin, this metric excludes the effect of change outputs:
  * If a transaction sends 90 BTC to ETF A but also withdraws 50 BTC from it, the flow is +40 BTC, not +90 BTC and -50 BTC.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FlowNetARKNtv>" %}

## API Endpoints

Net Flow metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `FlowNet*` in the `metrics` parameter.

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=FlowNetARKNtv&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=FlowNetARKNtv&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="FlowNetARKNtv", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Transaction Count

## Contents

* ETF Tx Cnt (TxEtfCnt)

## ETF Tx Cnt <a href="#txexcnt" id="txexcnt"></a>

### Definition

The sum count of transactions that involved any address belonging to an ETF, as a sender or recipient of a non-zero transfer of native units, in that interval. If a transaction involves multiple exchanges, it is only counted once.

| Name                        | ID       | Unit         | Interval |
| --------------------------- | -------- | ------------ | -------- |
| Exchange Traded Fund Tx Cnt | TxEtfCnt | Transactions | 1 day    |

### Details

* Coinbase (i.e., miner reward) transactions are not counted.
* Only ETFs and their addresses that Coin Metrics has identified are included so this metric should be thought of as a minimum potential value.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/TxEtfCnt>" %}

## API Endpoints

Exchange Transaction Count metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `TxEtfCnt` in the `metrics` parameter.

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=TxEtfCnt&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=TxEtfCnt&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="TxEtfCnt", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Withdrawals

## Contents

* [ETF Withdrawals (FlowOutXNtv, FlowOutXUSD)](#flowin)
* [ETF Withdrawals Count (FlowTfrOutXCnt)](#flowtfrin)

## ETF Withdrawals <a href="#flowout" id="flowout"></a>

### Definition

The sum of assets withdrawn from an ETF that interval.

| Name                                                            | MetricID          | Unit         | Interval |
| --------------------------------------------------------------- | ----------------- | ------------ | -------- |
| ARK Invest Withdrawals (native units)                           | FlowOutARKNtv     | Native units | 1 day    |
| ARK Invest Withdrawals (USD)                                    | FlowOutARKUSD     | USD          | 1 day    |
| BlackRock Withdrawals (native units)                            | FlowOutBLKNtv     | Native units | 1 day    |
| BlackRock Withdrawals (USD)                                     | FlowOutBLKUSD     | USD          | 1 day    |
| Bitwise Withdrawals (native units)                              | FlowOutBWSNtv     | Native units | 1 day    |
| Bitwise Withdrawals (USD)                                       | FlowOutBWSUSD     | USD          | 1 day    |
| Exchange Traded Fund Withdrawals, Including EtoE (native units) | FlowOutEtfInclNtv | Native units | 1 day    |
| Exchange Traded Fund Withdrawals, Including EtoE (USD)          | FlowOutEtfInclUSD | USD          | 1 day    |
| Exchange Traded Fund Withdrawals (native units)                 | FlowOutEtfNtv     | Native units | 1 day    |
| Exchange Traded Fund Withdrawals (USD)                          | FlowOutEtfUSD     | USD          | 1 day    |
| Grayscale Withdrawals (native units)                            | FlowOutGSCNtv     | Native units | 1 day    |
| Grayscale Withdrawals (USD)                                     | FlowOutGSCUSD     | USD          | 1 day    |
| Invesco Withdrawals (native units)                              | FlowOutINVNtv     | Native units | 1 day    |
| Invesco Withdrawals (USD)                                       | FlowOutINVUSD     | USD          | 1 day    |
| Franklin Templeton Withdrawals (native units)                   | FlowOutTMPNtv     | Native units | 1 day    |
| Franklin Templeton Withdrawals (USD)                            | FlowOutTMPUSD     | USD          | 1 day    |
| VanEck Withdrawals (native units)                               | FlowOutVANNtv     | Native units | 1 day    |
| VanEck Withdrawals (USD)                                        | FlowOutVANUSD     | USD          | 1 day    |
| Valkyrie Withdrawals (native units)                             | FlowOutVLKNtv     | Native units | 1 day    |
| Valkyrie Withdrawals (USD)                                      | FlowOutVLKUSD     | USD          | 1 day    |
| WisdomTree Withdrawals (native units)                           | FlowOutWDTNtv     | Native units | 1 day    |
| WisdomTree Withdrawals (USD)                                    | FlowOutWDTUSD     | USD          | 1 day    |

### Details

* Native units are considered as withdrawn if they leave the control of an address we identify as being owned by an ETF.
* USD flows are computed as `FlowOut{ETF}Ntv * PriceUSD`

### Asset-Specific Details

* For Bitcoin, this metric excludes the effect of change outputs:
  * If a transaction spends 100 BTC from ETF A but 90 BTC are sent back to it as change, the flow is -10 BTC, not -100 BTC and +90 BTC.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FlowOutEtfInclNtv>" %}

## ETF Withdrawal Count <a href="#flowtfrout" id="flowtfrout"></a>

### Definition

The sum count of transfers from any address belonging to an exchange in that interval. If the recipient address also belongs to the same exchange, the transfer is not counted.

<table><thead><tr><th>Name</th><th width="181">MetricID</th><th>Unit</th><th>Interval</th></tr></thead><tbody><tr><td>ARK Invest Withdrawal Count</td><td>FlowTfrOutARKCnt</td><td>Withdrawals</td><td>1 day</td></tr><tr><td>BlackRock Withdrawal Count</td><td>FlowTfrOutBLKCnt</td><td>Withdrawals</td><td>1 day</td></tr><tr><td>Bitwise Withdrawal Count</td><td>FlowTfrOutBWSCnt</td><td>Withdrawals</td><td>1 day</td></tr><tr><td>Grayscale Withdrawal Count</td><td>FlowTfrOutGSCCnt</td><td>Withdrawals</td><td>1 day</td></tr><tr><td>Invesco Withdrawal Count</td><td>FlowTfrOutINVCnt</td><td>Withdrawals</td><td>1 day</td></tr><tr><td>Franklin Templeton Withdrawal Count</td><td>FlowTfrOutTMPCnt</td><td>Withdrawals</td><td>1 day</td></tr><tr><td>VanEck Withdrawal Count</td><td>FlowTfrOutVANCnt</td><td>Withdrawals</td><td>1 day</td></tr><tr><td>Valkyrie Withdrawal Count</td><td>FlowTfrOutVLKCnt</td><td>Withdrawals</td><td>1 day</td></tr><tr><td>WisdomTree Withdrawal Count</td><td>FlowTfrOutWDTCnt</td><td>Withdrawals</td><td>1 day</td></tr><tr><td>Exchange Traded Fund Withdrawal Count</td><td>FlowTfrFromEtfCnt</td><td>Withdrawals</td><td>1 day</td></tr><tr><td>Exchange Traded Fund Withdrawal Count, Incl EtoE</td><td>FlowTfrFromEtfInclCnt</td><td>Withdrawals</td><td>1 day</td></tr></tbody></table>

### Details

* Coinbase (i.e., miner reward) transactions are not counted.

### Asset-Specific Details

* For UTXO-based protocols, this metric does not count change outputs:
  * If the input addresses belong to a given ETF, then the outputs belonging to the same ETF are not counted as transfers to that ETF

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FlowTfrFromEtfCnt>" %}

## API Endpoints

ETF Withdrawal metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `FlowOut*` and `FlowTfrOut*` in the `metrics` parameter.

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=FlowOutARKNtv&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=FlowOutARKNtv&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="FlowOutARKNtv", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Fees and Revenue

## Metrics

[Fees](/network-data/network-data-overview/fees-and-revenue/fees)

* FeeByteMeanNtv
* FeeMeanNtv
* FeeMeanUSD
* FeeMedNtv
* FeeMedUSD
* FeePrioMeanNtv
* FeePrioMeanUSD
* FeePrioMedNtv
* FeePrioMedUSD
* FeePrioTotNtv
* FeePrioTotUSD
* FeeRevPct
* FeeTotNtv
* FeeTotUSD
* FeeWghtMeanNtv
* GasBaseBlkMean
* GasLmtBlk
* GasLmtBlkMean
* GasLmtTx
* GasLmtTxMean
* GasUsedTx
* GasUsedTxMean
* FeeBlobTotNtv
* FeeBlobTotUSD
* FeeBlobMeanNtv
* FeeBlobMeanUSD
* FeeBlobMedNtv
* FeeBlobMedUSD
* FeeBlobByteMeanNtv
* FeeBlobByteMeanUSD
* FeeBlobTxMeanNtv
* FeeBlobTxMeanUSD

[Revenue](/network-data/network-data-overview/fees-and-revenue/revenue)

* RevAllTimeUSD
* RevNtv
* RevUSD


# Fees

### Contents

* [Mean Tx Fee per Byte (native units) (FeeByteMeanNtv)](#mean-tx-fee-per-byte-native-units)
* [Mean Tx Fee (native units, USD) (FeeMeanNtv, FeeMeanUSD)](#feemean)
* [Median Tx Fee (native units, USD) (FeeMedNtv, FeeMedUSD)](#feemed)
* [Mean Miner Tip (native units, USD) (FeePrioMeanNtv, FeePrioMeanUSD)](#feepriomean)
* [Median Miner Tip (native units, USD) (FeePrioMedNtv, FeePrioMedUSD)](#e)
* [Total Miner Tips (native units, USD) (FeePrioTotNtv, FeePrioTotUSD)](#feepriotot)
* [Miner Revenue from Fees (%) (FeeRevPct)](#feerevpct)
* [Total Fees (native units, USD) (FeeTotNtv, FeeTotUSD)](#feetot)
* [Mean Tx Fee per Block Weight (native units) (FeeWghtMeanNtv)](#feewghtmean)
* [Mean Base Fee (Wei) (GasBaseBlkMean)](#gasbaseblkmean)
* [Block Gas Limit (GasLmtBlk)](#gaslmtblk)
* [Mean Block Gas Limit (GasLmtBlkMean)](#gasbaseblkmean)
* [Tx Gas Limit (GasLmtTx)](#gaslmttx)
* [Mean Gas Limit per Tx (GasLmtTxMean)](#gaslmttxmean)
* [Tx Gas Used (GasUsedTx)](#gasusedtx)
* [Mean Gas Used per Tx (GasUsedTxMean)](#gaslmttxmean-1)
* [Network State Storage Fees](#network-state-storage-fees)

## Mean Tx Fee per Byte (native units)

### Definition

The mean transaction fee per byte of all blocks that interval in native units.

| Name                                | MetricID       | Unit         | Interval |
| ----------------------------------- | -------------- | ------------ | -------- |
| Mean Tx Fee per Byte (native units) | FeeByteMeanNtv | Native units | 1 day    |

### Details

* 0-fee transactions are included
* Computed as FeeTotNtv / BlkSizeByte
* If there were no transactions that interval, this metric isn’t computed
* For SOL, this metric does not include vote transactions. Includes successful and unsuccessful transactions.

### Chart

<figure><img src="/files/-MlRpOnIxIaqBL7mVgW6" alt=""><figcaption></figcaption></figure>

### Asset Specific Details

Any blockchain where users are paying for block space rather than computation.

### Examples

During the BTC mining ban in China in 2021, we saw an influx of miners turn off their operations so the block interval time increased significantly due to less hash power on the network. In effect, because less miners were online, we saw a spike in the mean transaction fee per byte since less miners were available to include transactions in the blocks, therefore transactions costs higher before the next difficulty adjustment.

### Release History

* Release Version: NDP-EOD 4.8 (Nov, 2020)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FeeByteMeanNtv>" %}

## Mean Tx Fee <a href="#feemean" id="feemean"></a>

### Definition

The mean fee per transaction in native units in that interval.

| Name                       | MetricID   | Unit         | Interval      |
| -------------------------- | ---------- | ------------ | ------------- |
| Mean Tx Fee (native units) | FeeMeanNtv | Native units | 1 day, 1 hour |
| Mean Tx Fee (USD)          | FeeMeanUSD | USD          | 1 day, 1 hour |

### Details

* 0-fee transactions are included
* If there were no transactions that interval, this metric isn’t computed
* FeeMeanUSD is Computed as FeeMeanNtv \* PriceUSD
* The price used is the daily close price

### Asset Specific Details

* Any blockchain where users are paying for block space rather than computation.
* For SOL, this metric does not include vote transactions. Includes successful and unsuccessful transactions.

### Release History

* Release Version: NDP-EOD 4.8 (Nov, 2020)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FeeByteMeanNtv>" %}

## Median Tx Fee <a href="#feemed" id="feemed"></a>

### Definition

The median fee per transaction in native units that interval.

| Name                         | MetricID  | Unit         | Interval      |
| ---------------------------- | --------- | ------------ | ------------- |
| Median Tx Fee (native units) | FeeMedNtv | Native units | 1 day, 1 hour |
| Median Tx Fee (USD)          | FeeMedUSD | USD          | 1 day, 1 hour |

### Details

* 0-fee transactions are included
* If there were no transactions that interval, this metric isn’t computed
* If there’s an even number of fees, the median is computed by averaging the middle values of the sorted fees
* FeeMedUSD is computed as FeeMedNtv \* PriceUSD
* Price used is the daily close price
* 0-fee transactions are included

### Asset Specific Details

* For SOL, this metric does not include vote transactions. Includes successful and unsuccessful transactions.

### Release History

* Released in the 1.0 release of NDP

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FeeMedNtv>" %}

## Mean Miner Tip <a href="#feepriomean" id="feepriomean"></a>

### Definition

The average (mean) Miner Tip, a.k.a. *priority fee,* paid for transactions during a time interval (e.g. 1 day).

The concept of a Miner Tip was introduced as part of [EIP-1559](https://notes.ethereum.org/@vbuterin/eip-1559-faq) and it represents the portion of the total transaction fees that rewards miners. This serves as an added incentive so that miners prioritize transactions that have opted-in and paid a tip. The other portion is called the Base Fee, and it is burnt (destroyed) after the transaction is included in a block.

Ethereum post-1559 requires users to pay for a Base Fee as a prerequisite to include transactions in a block. The Base Fee can go up or down on the basis of the size (in gas units) of the previous block. In times of congestion, where blocks are sequentially increasing in size, paying a Base Fee does not guarantee that a transaction will be included in a block. In such events, users can optionally pay an additional miner tip to nudge miners to include their transactions in their block.

| Name                          | MetricID       | Unit         | Interval      |
| ----------------------------- | -------------- | ------------ | ------------- |
| Mean Miner Tip (native units) | FeePrioMeanNtv | Native units | 1 day, 1 hour |
| Mean Miner Tip (USD)          | FeePrioMeanUSD | USD          | 1 day, 1 hour |

### Details

* EIP1559 was a highly anticipated proposal that changes how transaction fees are priced in Ethereum, as well as the dynamics of block sizes.
* The proposal activated on the Ethereum Network in August of 2021 and marks one of the biggest changes in monetary policy in the history of cryptoassets.
* Instead of the legacy *gas price*, 1559 splits transaction fees into two distinct fields: a Base Fee and an optional Tip (also known as a *Priority Fee*).
* This metric calculates the average Tip in transactions that have occurred in the network over the measuring period (e.g. 1 day).
* For a thorough review of EIP1559 and the design of its pricing mechanism, please refer to [this paper](https://arxiv.org/pdf/2012.00854.pdf).

### Chart

<figure><img src="/files/iCRAATd4goYcvF9L1YfZ" alt=""><figcaption></figcaption></figure>

### Interpretation

* Miner tips are optional and showcase demand for block space (i.e. transaction settlement) in the short-term.
* Changes in average miner tip over time can depict changes in demand for block space. When miner tips have to be used due to Base Fees not being enough, the fee market reverts back to first-price auction (like other Crypto assets).
* In such scenarios, this metric should see an increase as users bid up fees as they did prior to the activation of EIP1559.

### Asset-Specific Details

* Only available for ETH, this metric was introduced following the EIP-1559 upgrade

### Examples

We saw a major drop in gas used in Spring 2022 due to the built in difficulty bomb. In the early days of Ethereum, core developers implemented this difficulty bomb mechanism to hold everyone accountable to the PoS timeline. The idea was that the bomb would go off making mining extremely difficult/unprofitable. So each time the bomb started to go off, less blocks were being found so less gas used. Therefore, less priority fees were needed since network activity was low.

### Release History

* Released in the 5.0 release of NDP (August, 2021)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FeePrioMeanNtv>" %}

## Median Miner Tip <a href="#e" id="e"></a>

### Definition

The median Miner Tip, a.k.a. *priority fee,* paid for transactions during a time interval (e.g. 1 day), shown in native units (e.g. units of ETH).

The concept of a Miner Tip was introduced as part of [EIP-1559](https://notes.ethereum.org/@vbuterin/eip-1559-faq) and it represents the portion of the total transaction fees that rewards miners. This serves as an added incentive so that miners prioritize transactions that have opted-in and paid a tip. The other portion is called the Base Fee, and it is burnt (destroyed) after the transaction is included in a block.

Ethereum post-1559 requires users to pay for a Base Fee as a prerequisite to include transactions in a block. The Base Fee can go up or down on the basis of the size (in gas units) of the previous block. In times of congestion, where blocks are sequentially increasing in size, paying a Base Fee does not guarantee that a transaction will be included in a block. In such events, users can optionally pay an additional miner tip to nudge miners to include their transactions in their block.

| Name                            | MetricID      | Unit         | Interval      |
| ------------------------------- | ------------- | ------------ | ------------- |
| Median Miner Tip (native units) | FeePrioMedNtv | Native units | 1 day, 1 hour |
| Median Miner Tip (USD)          | FeePrioMedUSD | USD          | 1 day, 1 hour |

### Details

* EIP1559 was a highly anticipated proposal that changes how transaction fees are priced in Ethereum, as well as the dynamics of block sizes.
* The proposal activated on the Ethereum Network in August of 2021 and marks one of the biggest changes in monetary policy in the history of cryptoassets.
* Instead of the legacy *gas price*, 1559 splits transaction fees into two distinct fields: a Base Fee and an optional Tip (also known as a *Priority Fee*).
* This metric calculates the median Tip in transactions that have occurred in the network over the measuring period (e.g. 1 day).
* For a thorough review of EIP1559 and the design of its pricing mechanism, please refer to [this paper](https://arxiv.org/pdf/2012.00854.pdf).

### Asset-Specific Details

* Only available for ETH, this metric was introduced following the EIP-1559 upgrade
* For Solana transactions, priority fees are fees paid on top of the 5000 lamport base fee per signature. This includes both setting a higher price per compute unit and setting a higher total compute budget

### Examples

* We saw a major drop in gas used in Spring 2022 due to the built in difficulty bomb. In the early days of Ethereum, core developers implemented this difficulty bomb mechanism to hold everyone accountable to the PoS timeline. The idea was that the bomb would go off making mining extremely difficult/unprofitable. So each time the bomb started to go off, less blocks were being found so less gas used. Therefore, less priority fees were needed since network activity was low.

### Interpretation

* Miner tips are optional and showcase demand for block space (i.e. transaction settlement) in the short-term.
* Changes in median miner tip over time can depict changes in demand for block space. When miner tips have to be used due to Base Fees not being enough, the fee market reverts back to first-price auction (like other cryptoassets).
* In such scenarios, this metric should see an increase as users bid up fees as they did prior to the activation of EIP1559.

### Release History

* Released in the 5.0 release of NDP (August, 2021)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FeePrioMedNtv>" %}

## Total Miner Tips <a href="#feepriotot" id="feepriotot"></a>

### Definition

The total value of Miner Tips, a.k.a. *priority fees,* paid for all transactions during a time interval (e.g. 1 day), shown in native units (e.g. units of ETH).

The concept of a Miner Tip was introduced as part of [EIP-1559](https://notes.ethereum.org/@vbuterin/eip-1559-faq) and it represents the portion of the total transaction fees that rewards miners. This serves as an added incentive so that miners prioritize transactions that have opted-in and paid a tip. The other portion is called the Base Fee, and it is burnt (destroyed) after the transaction is included in a block.

Ethereum post-1559 requires users to pay for a Base Fee as a prerequisite to include transactions in a block. The Base Fee can go up or down on the basis of the size (in gas units) of the previous block. In times of congestion, where blocks are sequentially increasing in size, paying a Base Fee does not guarantee that a transaction will be included in a block. In such events, users can optionally pay an additional miner tip to nudge miners to include their transactions in their block.

| Name                            | MetricID      | Unit         | Interval      |
| ------------------------------- | ------------- | ------------ | ------------- |
| Total Miner Tips (native units) | FeePrioTotNtv | Native units | 1 day, 1 hour |
| Total Miner Tips (USD)          | FeePrioTotUSD | USD          | 1 day, 1 hour |

### Details

* EIP1559 was a highly anticipated proposal that changes how transaction fees are priced in Ethereum, as well as the dynamics of block sizes.
* The proposal activated on the Ethereum Network in August of 2021 and marks one of the biggest changes in monetary policy in the history of cryptoassets.
* Instead of the legacy *gas price*, 1559 splits transaction fees into two distinct fields: a Base Fee and an optional Tip (also known as a *Priority Fee*).
* This metric calculates the total value paid for Tips in transactions that have occurred in the network over the measuring period (e.g. 1 day).
* For a thorough review of EIP1559 and the design of its pricing mechanism, please refer to [this paper](https://arxiv.org/pdf/2012.00854.pdf).

### Asset Specific Details

* For Solana transactions, priority fees are fees paid on top of the 5000 lamport base fee per signature. This includes both setting a higher price per compute unit and setting a higher total compute budget

### Interpretation

* Miner tips are optional and showcase demand for block space (i.e. transaction settlement) in the short-term.
* Changes in total miner tip over time can depict changes in demand for block space. When miner tips have to be used due to Base Fees not being enough, the fee market reverts back to first-price auction (like other cryptoassets).
* In such scenarios, this metric should see an increase as users bid up fees as they did prior to the activation of EIP1559.

### Release History

* Released in the 5.0 release of NDP (August, 2021)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FeePrioTotNtv>" %}

## Revenue from Fees (%) <a href="#feerevpct" id="feerevpct"></a>

### Definition

The percentage of revenue derived from fees that interval. This is equal to the fees divided by the revenue.

| Name                  | MetricID  | Unit          | Interval |
| --------------------- | --------- | ------------- | -------- |
| Revenue from Fees (%) | FeeRevPct | Dimensionless | 1 day    |

### Details

* For most assets: computed as `100 × FeeTotNtv / RevNtv`
* For Ethereum post-London hardfork (EIP-1559): computed as `100 × FeePrioTotNtv / RevNtv`, using priority fees only, since base fees are burned and do not accrue to validators.
* For Solana: computed as `100 × (RevNtv − IssContNtv − FeeStorTotNtv) / RevNtv`

### Release History

* Released in the 1.0 release of NDP

### Interpretation

For blockchains aiming to retain a limited supply by weaning themselves off an issuance-based validator subsidy, fees are expected to be a critical part of the long-term security model. This metric gives you an indication of how prepared a blockchain is to transition from an issuance-based compensation model for validators to a fee-based model.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FeeRevPct>" %}

## Total Fees <a href="#feetot" id="feetot"></a>

### Definition

The sum of all fees paid to miners, transaction validators, stakers and/or block producers that interval. In certain cryptonetworks, fees might be burned (destroyed), but they are still accounted for in this metric.

| Name                      | MetricID  | Unit         | Interval      |
| ------------------------- | --------- | ------------ | ------------- |
| Total Fees (native units) | FeeTotNtv | Native units | 1 day, 1 hour |
| Total Fees (USD)          | FeeTotUSD | USD          | 1 day, 1 hour |

### Details

* This metric includes fees that are burned as part of the protocol.
* For chains that use median time, the day is defined using it, otherwise, it’s defined using the block’s timestamps.

### Asset Specific Details

* For Solana transactions, priority fees are fees paid on top of the 5000 lamport base fee per signature. This includes both setting a higher price per compute unit and setting a higher total compute budget.
* For Ethereum this fee includes fees for transaction execution as well as blob fees. It is made up of base fees, priority fees and blob fees. Fees paid for the execution of transactions only can be calculated by subtracting [total blob fees](#total-blob-fees) from total fees.

### Release History

* Released in the 1.0 release of NDP

### Interpretation

Fees in USD terms (see Fees, Transaction, Median, USD; Fees, Transaction, Mean, USD, and Fees, Total, USD) are often biased by volatility in unit price, making it difficult to determine trends in fee pressure. Evaluating fees in native unit terms removes the noise from exchange rate volatility and enables more consistent time series comparisons.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FeeTotNtv>" %}

## Mean Tx Fee per Block Weight (native units) <a href="#feewghtmean" id="feewghtmean"></a>

### Definition

The mean transaction fee per weight unit in that interval in native units. Weight is a dimensionless measure of a block’s “size”. It is only applicable for chains that use SegWit (segregated witness).

| Name                                        | MetricID       | Unit         | Interval |
| ------------------------------------------- | -------------- | ------------ | -------- |
| Mean Tx Fee per Block Weight (native units) | FeeWghtMeanNtv | Native units | 1 day    |

### Details

* For more details on SegWit, check the [Bitcoin Wiki Entry](https://en.bitcoin.it/wiki/Segregated_Witness)

### Asset-Specific Details

* Only relevant to cryptoassets that have implemented Segregated Witness (SegWit)

### Examples

* During the BTC mining ban in China in 2021, we saw an influx of miners turn off their operations so the block interval time increased significantly due to less hash power on the network. In effect, because less miners were online, we saw a spike in the mean transaction fee per byte since less miners were available to include transactions in the blocks, therefore transactions costs were more competitive.

### Release History

* Release Version: NDP-EOD 4.8 (Nov, 2020)

### Interpretation

* The Segwit upgrade replaced the concept of block size with block weight . While Bitcoins block weight is 4 MB, the mean block time is still slower than other chains such as Litecoin resulting

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FeeWghtMeanNtv>" %}

## Mean Base Fee (Wei) <a href="#gasbaseblkmean" id="gasbaseblkmean"></a>

### Definition

The average (mean) Base Fee paid for transactions during a time interval (e.g. 1 day), shown in the smallest denomination of Ether, [Wei units](https://ethdocs.org/en/latest/ether.html#denominations).

The concept of a Base Fee was introduced as part of [EIP-1559](https://notes.ethereum.org/@vbuterin/eip-1559-faq) and it represents the portion of the total transaction fees that is destroyed and taken out of circulation (i.e. *burnt)*. Ethereum post-1559 requires users to pay for a Base Fee as a prerequisite to include transactions in a block. The Base Fee can go up or down on the basis of the size (in gas units) of the previous block. In times of congestion, where blocks are sequentially increasing in size, paying a Base Fee does not guarantee that a transaction will be included in a block. In such events, users can optionally pay an additional Miner Tip to nudge miners to include their transactions in their block.

| Name                | MetricID       | Unit | Interval |
| ------------------- | -------------- | ---- | -------- |
| Mean Base Fee (Wei) | GasBaseBlkMean | Wei  | 1 day    |

### Details

* EIP1559 was a highly anticipated proposal that changes how transaction fees are priced in Ethereum, as well as the dynamics of block sizes.
* The proposal activated on the Ethereum Network in August of 2021 and marks one of the biggest changes in monetary policy in the history of cryptoassets.
* Instead of the legacy *gas price*, 1559 splits transaction fees into two distinct fields: a Base Fee and an optional Tip (also known as a *Priority Fee*).
* This metric calculates the average Base Fee in transactions that have occurred in the network over the measuring period (e.g. 1 day).
* For a thorough review of EIP1559 and the design of its pricing mechanism, please refer to [this paper](https://arxiv.org/pdf/2012.00854.pdf).

### Interpretation

* Base Fees fluctuate on the basis of network utilization. If there is high demand for transaction settlement, Base Fees go up, and as demand fades, Base Fees go down.
* The pricing of Base Fees is inextricably connected to size of blocks in the blockchain. Upon the the activation fo EIP-1559, the maximum size of blocks in Ethereum (measured in units of gas) was more than doubled to 30M.
* Although blocks are larger, this pricing mechanism attempts to target an average of 15M gas units per block, and an exponential function is used to increase or decrease Base Fees so that this target is hit.
* If, for example, the previous block was above 15M units of gas, the base fee is increased. If there are several sequential blocks above the 15M target, Base Fees increase exponentially which disincentivizes users from transacting.
* Changes in Base Fees over time can depict changes in demand for block space. When miner tips have to be used due to Base Fees not being enough, this is a sign of network congestion.

### Release History

* Released in the 5.0 release of NDP (August, 2021)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/GasBaseBlkMean>" %}

## Block Gas Limit <a href="#gaslmtblk" id="gaslmtblk"></a>

### Definition

The sum gas limit of all blocks that day.

| Name            | MetricID  | Unit | Interval       |
| --------------- | --------- | ---- | -------------- |
| Block Gas Limit | GasLmtBlk | Gas  | 1 block, 1 day |

### Details

* Gas is a dimensionless unit measuring the computational cost of operations for ETH-based assets. Each transaction spends gas when being processed.
* Each block has a limit of how much gas can be expanded when processing its operations. It is the scaling limit for ETH-based assets, just as block size is for BTC-based ones.

### Chart

<figure><img src="/files/BOcUGQTsvpxugZjYvlH3" alt=""><figcaption></figcaption></figure>

### Asset-Specific Details

* Only relevant for ETH and ETC.

### Interpretation

* Ethereum blocks are mined roughly every 15 seconds. Each Ethereum block has a maximum size, which limits the amount of data that can be included. The current maximum block size is set at about 15M gas per block on April 22 (seen in green on the chart above). Prior to that, the gas limit was 12.5M per block, which set in July 2020. Since the maximum block size is denominated in gas and different transactions have different gas usages based on complexity, there isn’t a consistent maximum number of transactions that can be included in a block. But on average, about 160-200 transactions are included per block.
* The greater the gas limit, the more space is available per block, which can help push down the average gas price.

### Release History

* Released in the 1.0 release of NDP

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/GasLmtBlk>" %}

## Mean Block Gas Limit <a href="#gaslmtblkmean" id="gaslmtblkmean"></a>

### Definition

The mean gas limit per block that day.

| Name                 | MetricID      | Unit | Interval |
| -------------------- | ------------- | ---- | -------- |
| Mean Block Gas Limit | GasLmtBlkMean | Gas  | 1 day    |

### Details

* Computed as GasLmtBlk / BlkCnt
* Gas is a dimensionless unit measuring the computational cost of operations for ETH-based assets. Each transaction spends gas when being processed.

### Asset-Specific details

* Only relevant for ETH and ETC.

### Release History

* Released in the 1.0 release of NDP

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/GasLmtBlkMean>" %}

## Tx Gas Limit <a href="#gaslmttx" id="gaslmttx"></a>

### Definition

The sum gas limit of all transactions that day.

| Name         | MetricID | Unit | Interval       |
| ------------ | -------- | ---- | -------------- |
| Tx Gas Limit | GasLmtTx | Gas  | 1 block, 1 day |

### Details

* Gas is a dimensionless unit measuring the computational cost of operations for ETH-based assets. Each transaction uses gas when being processed. As it’s impossible to know how much gas every transaction will use before executing it, each transaction specifies a gas limit it’s willing to use.

### Asset-Specific Details

* Only relevant for ETH and ETC.

### Release History

* Released in the 1.0 release of NDP

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/GasLmtTx>" %}

## Mean Block Gas Limit <a href="#gaslmtblkmean" id="gaslmtblkmean"></a>

### Definition

The mean gas limit per block that day.

| Name                 | MetricID      | Unit | Interval |
| -------------------- | ------------- | ---- | -------- |
| Mean Block Gas Limit | GasLmtBlkMean | Gas  | 1 day    |

### Details

* Computed as GasLmtBlk / BlkCnt
* Gas is a dimensionless unit measuring the computational cost of operations for ETH-based assets. Each transaction spends gas when being processed.

### Asset-Specific details

* Only relevant for ETH and ETC.

### Release History

* Released in the 1.0 release of NDP

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/GasLmtBlkMean>" %}

## Mean Gas Limit per Tx <a href="#gaslmttxmean" id="gaslmttxmean"></a>

### Definition

The mean gas limit per transaction that day.

| Name                  | MetricID     | Unit | Interval       |
| --------------------- | ------------ | ---- | -------------- |
| Mean Gas Limit per Tx | GasLmtTxMean | Gas  | 1 block, 1 day |

### Details

* Computed as GasLmtTx / TxCnt
* Gas is a dimensionless unit measuring the computational cost of operations for ETH-based assets. Each transaction uses gas when being processed. As it’s impossible to know how much gas every transaction will use before executing it, each transaction specifies a gas limit it’s willing to use.

### Asset-Specific Details

* Only relevant for ETH and ETC.

### Release History

* Released in the 1.0 release of NDP

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/GasLmtTxMean>" %}

## Tx Gas Used <a href="#gasusedtx" id="gasusedtx"></a>

### Definition

The sum gas used (i.e., paid) across all transactions that day.

| Name        | MetricID  | Unit | Interval       |
| ----------- | --------- | ---- | -------------- |
| Tx Gas Used | GasUsedTx | Gas  | 1 block, 1 day |

### Details

* Gas is a dimensionless unit measuring the computational cost of operations for ETH-based assets. Each transaction uses gas when being processed.

### Asset-Specific details

* Only relevant for ETH and ETC.

### Release History

* Released in the 1.0 release of NDP

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/GasUsedTx>" %}

## Mean Gas Used per Tx <a href="#gaslmttxmean" id="gaslmttxmean"></a>

### Definition

The mean gas used (i.e., paid) per transaction that day.

| Name                 | MetricID      | Unit | Interval       |
| -------------------- | ------------- | ---- | -------------- |
| Mean Gas Used per Tx | GasUsedTxMean | Gas  | 1 block, 1 day |

### Details

* Computed as GasUsedTx / TxCnt
* Gas is a dimensionless unit measuring the computational cost of operations for ETH-based assets. Each transaction uses gas when being processed.

### Asset-Specific Details

* Only relevant for ETH and ETC.

### Release History

* Released in the 1.0 release of NDP

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/GasUsedTxMean>" %}

## Network State Storage Fees

### Definition

Total fees paid for storing state on the network within an interval in native units.

<table><thead><tr><th>Name</th><th width="216">MetricID</th><th>Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Network state storage fees (native units)</td><td>FeeStorTotNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Network state storage fees (USD)</td><td>FeeStorTotUSD</td><td>USD</td><td>1 day</td></tr></tbody></table>

#### Details

* Solana removed network state storage fees in November of 2023 as of which time they are 0

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FeeStorTotNtv>" %}

### API Endpoints

Fee metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `Fee*` and `Gas*` in the `metrics` parameter.

<mark style="color:blue;">`GET`</mark> `undefined/timeseries/asset-metrics`

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=FeeByteMeanNtv&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=FeeByteMeanNtv&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="FeeByteMeanNtv", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Blob Fees

### Contents

* [Total blob fees (FeeBlobTotNtv, FeeBlobTotUSD)](#total-blob-fees)
* [Mean blob fees (FeeBlobMeanNtv, FeeBlobMeanUSD)](#mean-blob-fees)
* [Median blob fees (FeeBlobMedNtv, FeeBlobMedUSD)](#median-blob-fees)
* [Mean fee per blob byte (FeeBlobByteMeanNtv, FeeBlobByteMeanUSD)](#mean-fee-per-blob-byte)
* [Mean fee per blob carrying transaction (FeeBlobTxMeanNtv, FeeBlobTxMeanUSD)](#mean-fee-per-blob-carrying-transaction)
* [Total Blob Fees Paid by Layer 2s (FeeBlob\*TotNtv, FeeBlob\*TotUSD)](#total-blob-fees-paid-by-layer-2s)
* [Mean Blob Fees Paid by Layer 2s (FeeBlob\*MeanNtv, FeeBlob\*MeanUSD)](#mean-blob-fees-paid-by-layer-2s)

## Total blob fees

### Definition

Total amount of Fees paid for blob space (available in native units and USD)

<table><thead><tr><th width="222">Name</th><th>MetricID</th><th>Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Total blob fees (native units)</td><td>FeeBlobTotNtv</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>Total blob fees (USD)</td><td>FeeBlobTotUSD</td><td>USD</td><td>1 block, 1 day</td></tr></tbody></table>

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FeeBlobTotNtv>" %}

## Mean blob fees

### Definition

Mean fees paid per blob, shown (available in native units and USD)

<table><thead><tr><th width="249">Name</th><th width="174">MetricID</th><th>Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Mean blob fees (native units)</td><td>FeeBlobMeanNtv</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>Mean blob fees (USD)</td><td>FeeBlobMeanUSD</td><td>USD</td><td>1 block, 1 day</td></tr></tbody></table>

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FeeBlobMeanNtv>" %}

## Median blob fees

### Definition

Median fees paid per blob, shown (available in native units and USD)

<table><thead><tr><th width="219">Name</th><th>MetricID</th><th>Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Median blob fees (native units)</td><td>FeeBlobMedNtv</td><td>Native Units</td><td>1 block, 1 day</td></tr><tr><td>Median blob fees (USD)</td><td>FeeBlobMedUSD</td><td>USD</td><td>1 block, 1 day</td></tr></tbody></table>

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FeeBlobMedNtv>" %}

## Mean Fee per blob Byte

### Definition

Mean fee paid per byte of used blob space (available in native units and USD)

<table><thead><tr><th>Name</th><th width="205">MetricID</th><th width="200">Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Mean Fee per blob Byte (native units)</td><td>FeeBlobByteMeanNtv</td><td>Native units</td><td>1 block, 1 day</td></tr><tr><td>Mean Fee per blob Byte (USD)</td><td>FeeBlobByteMeanUSD</td><td>USD</td><td>1 block, 1 day</td></tr></tbody></table>

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FeeBlobByteMeanNtv>" %}

## Mean fee per blob carrying transaction

### Definition

Mean fee paid in blob fees per blob carrying transaction (available in native units and USD)

| Name                                                  | MetricID         | Unit         | Interval       |
| ----------------------------------------------------- | ---------------- | ------------ | -------------- |
| Mean fee per blob carrying transaction (native units) | FeeBlobTxMeanNtv | Native units | 1 block, 1 day |
| Mean fee per blob carrying transaction (USD)          | FeeBlobTxMeanUSD | USD          | 1 block, 1 day |

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FeeBlobTxMeanNtv>" %}

## Total Blob Fees paid by Layer 2s

### Definition

The sum of all fees paid by tagged Layer 2 sequencers for blob space, shown in native units and USD.

<table><thead><tr><th>Name</th><th width="197">MetricID</th><th>Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Total Blob Fees (layer 2, native units)</td><td>FeeBlobL2TotNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Total Blob Fees (layer 2, USD)</td><td>FeeBlobL2TotUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Total Blob Fees (Arbitrum, native units)</td><td>FeeBlobARBTotNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Total Blob Fees (Arbitrum, USD)</td><td>FeeBlobARBTotUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Total Blob Fees (Optimism, native units)</td><td>FeeBlobOPTotNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Total Blob Fees (Optimism, USD)</td><td>FeeBlobOPTotUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Total Blob Fees (Base, native units)</td><td>FeeBlobBASETotNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Total Blob Fees (Base, USD)</td><td>FeeBlobBASETotUSD</td><td>USD</td><td>1 day</td></tr></tbody></table>

#### Details

* The aggregate L2 metrics (FeeBlobL2TotNtv & FeeBlobL2TotUSD) include all tagged L2 sequencers. This list includes additional L2s that do not have dedicated metrics.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FeeBlobL2TotNtv>" %}

## Mean Blob Fees paid by Layer 2s

### Definition

The mean fee paid by tagged Layer 2 sequencers for blob space, shown in native units and USD.

<table><thead><tr><th>Name</th><th width="216">MetricID</th><th>Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Mean Blob Fees (layer 2, native units)</td><td>FeeBlobL2MeanNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Mean Blob Fees (layer 2, USD)</td><td>FeeBlobL2MeanUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Mean Blob Fees (Arbitrum, native units)</td><td>FeeBlobARBMeanNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Mean Blob Fees (Arbitrum, USD)</td><td>FeeBlobARBMeanUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Mean Blob Fees (Optimism, native units)</td><td>FeeBlobOPMeanNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Mean Blob Fees (Optimism, USD)</td><td>FeeBlobOPMeanUSD</td><td>USD</td><td>1 day</td></tr><tr><td>Mean Blob Fees (Base, native units)</td><td>FeeBlobBASEMeanNtv</td><td>Native units</td><td>1 day</td></tr><tr><td>Mean Blob Fees (Base, USD)</td><td>FeeBlobBASEMeanUSD</td><td>USD</td><td>1 day</td></tr></tbody></table>

#### Details

* The aggregate L2 metrics (FeeBlobL2MeanNtv & FeeBlobL2MeanUSD) include all tagged L2 sequencers. This list includes additional L2s that do not have dedicated metrics.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/FeeBlobL2MeanNtv>" %}

### API Endpoints

Blob Fee metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `FeeBlob*` in the `metrics` parameter.

<mark style="color:blue;">`GET`</mark> `undefined/timeseries/asset-metrics`

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=FeeBlobTotNtv&assets=eth&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=FeeBlobTotNtv&assets=eth&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="FeeBlobTotNtv", 
        assets="eth",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# MEV Fees

### Contents

* [Total MEV Tips (FeeMevTotNtv, FeeMevTotUSD)](#adractcont)
* [Mean MEV Tips (FeeMevMeanNtv, FeeMevMeanUSD)](#adractcont-1)
* [Median MEV Tips (FeeMevMedNtv, FeeMevMedUSD)](#adractcont-2)
* [Total Miner Tips Among MEV Transactions (FeePrioTotMevNtv, FeePrioTotMevUSD)](#total-miner-tips-among-mev-transactions)
* [Mean Miner Tips Among MEV Transactions (FeePrioMeanMevNtv, FeePrioMeanMevUSD)](#mean-miner-tips-among-mev-transactions)
* [Median Miner Tips Among MEV Transactions (FeePrioMeanMevNtv, FeePrioMeanMevUSD)](#median-miner-tips-among-mev-transactions)
* [Miner Revenue from MEV tips (%) (FeeMevRevPct)](#miner-revenue-from-mev-tips)

## Total MEV Tips <a href="#adractcont" id="adractcont"></a>

<table><thead><tr><th width="177">Name</th><th width="157">MetricID</th><th width="124">Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Total MEV Tips (native units)</td><td>FeeMevTotNtv</td><td>Native Units</td><td>1 day</td></tr><tr><td>Total MEV Tips (USD)</td><td>FeeMevTotUSD</td><td>USD</td><td>1 day</td></tr></tbody></table>

### Definition

The sum of all MEV tips in native units and USD that interval. The MEV tip represents the non-native transaction fee that goes to miners or validators as an incentive mechanism for transaction ordering. MEV tips are excluded from total native fee metrics.

### Details

* This fee is not included in `FeeTotNtv`. Total fees paid for transactions (MEV + protocol fees) can be obtained by leveraging the following formula: $$TotalFees=FeeTotNtv+FeeMevTotNtv$$

### **Asset-Specific Details**

* For Solana, slots proposed by validators running the Jito-Solana client are considered as MEV slots. Further, in Solana it is possible to identify which transactions paid MEV tip in addition to simply identifying the slot. For this metric each individual transaction is evaluated to determine which are MEV-enabled and which aren't.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FeeMevTotNtv>" %}
FeeMevTotNtv
{% endembed %}

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FeeMevTotUSD>" %}
FeeMevTotUSD
{% endembed %}

## Mean MEV Tips <a href="#adractcont" id="adractcont"></a>

<table><thead><tr><th width="177">Name</th><th width="157">MetricID</th><th width="124">Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Mean MEV Tips (native units)</td><td>FeeMevMeanNtv</td><td>Native Units</td><td>1 day</td></tr><tr><td>Mean MEV Tips (USD)</td><td>FeeMevMeanUSD</td><td>USD</td><td>1 day</td></tr></tbody></table>

### Definition

The mean MEV tip per transaction in native units that interval. The MEV tip represents the non-native transaction fee that goes to miners or validators as an incentive mechanism for transaction ordering. MEV tips are excluded from total native fee metrics.

### Details

* This fee is not included in `FeeMeanNtv`.

### **Asset-Specific Details**

* For Solana, slots proposed by validators running the Jito-Solana client are considered as MEV slots. Further, in Solana it is possible to identify which transactions paid MEV tip in addition to simply identifying the slot. For this metric each individual transaction is evaluated to determine which are MEV-enabled and which aren't.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FeeMevMeanNtv>" %}
FeeMevMeanNtv
{% endembed %}

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FeeMevMeanUSD>" %}
FeeMevMeanUSD
{% endembed %}

## Median MEV Tips <a href="#adractcont" id="adractcont"></a>

<table><thead><tr><th width="177">Name</th><th width="157">MetricID</th><th width="124">Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Median MEV Tips (native units)</td><td>FeeMevMedNtv</td><td>Native Units</td><td>1 day</td></tr><tr><td>Median MEV Tips (USD)</td><td>FeeMevMedUSD</td><td>USD</td><td>1 day</td></tr></tbody></table>

### Definition

The median MEV tip per transaction in native units that interval. The MEV tip represents the non-native transaction fee that goes to miners or validators as an incentive mechanism for transaction ordering. MEV tips are excluded from total native fee metrics.

### Details

* This fee is not included in `FeeMedNtv`.

### **Asset-Specific Details**

* For Solana, slots proposed by validators running the Jito-Solana client are considered as MEV slots. Further, in Solana it is possible to identify which transactions paid MEV tip in addition to simply identifying the slot. For this metric each individual transaction is evaluated to determine which are MEV-enabled and which aren't.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FeeMevMedNtv>" %}
FeeMevMedNtv
{% endembed %}

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FeeMevMedUSD>" %}
FeeMevMedUSD
{% endembed %}

## Total Miner Tips Among MEV Transactions

<table><thead><tr><th width="177">Name</th><th width="157">MetricID</th><th width="124">Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Total Miner Tips Among MEV txs (native units)</td><td>FeePrioTotMevNtv</td><td>Native Units</td><td>1 day</td></tr><tr><td>Total Miner Tips Among MEV txs (USD)</td><td>FeePrioTotMevUSD</td><td>USD</td><td>1 day</td></tr></tbody></table>

### Definition

The sum native units value of all priority fees in that interval among MEV-enabled transactions. An MEV-enabled transaction is one that paid an MEV tip to miners/validators in exchange for specific block ordering.

### Details

* This fee is not included in `FeePrioTotNtv`.
* Generally, MEV transactions to not also pay an additional protocol native priority fee. While this can happen this would be the exception.

### **Asset-Specific Details**

* For Solana, slots proposed by validators running the Jito-Solana client are considered as MEV slots. Further, in Solana it is possible to identify which transactions paid MEV tip in addition to simply identifying the slot. For this metric each individual transaction is evaluated to determine which are MEV-enabled and which aren't.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FeePrioTotMevNtv>" %}
FeePrioTotMevNtv
{% endembed %}

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FeePrioTotMevUSD>" %}
FeePrioTotMevUSD
{% endembed %}

## Mean Miner Tips Among MEV Transactions

<table><thead><tr><th width="177">Name</th><th width="157">MetricID</th><th width="124">Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Mean Miner Tips Among MEV txs (native units)</td><td>FeePrioMeanMevNtv</td><td>Native Units</td><td>1 day</td></tr><tr><td>Mean Miner Tips Among MEV txs (USD)</td><td>FeePrioMeanMevUSD</td><td>USD</td><td>1 day</td></tr></tbody></table>

### Definition

The mean priority fee per MEV-enabled transaction in native units that interval. An MEV-enabled transaction is one that paid an MEV tip to miners/validators in exchange for specific block ordering.

### Details

* This fee is not included in `FeePrioMeanNtv`.
* Generally, MEV transactions to not also pay an additional protocol native priority fee. While this can happen this would be the exception.

### **Asset-Specific Details**

* For Solana, slots proposed by validators running the Jito-Solana client are considered as MEV slots. Further, in Solana it is possible to identify which transactions paid MEV tip in addition to simply identifying the slot. For this metric each individual transaction is evaluated to determine which are MEV-enabled and which aren't.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FeePrioMeanMevNtv>" %}
FeePrioMeanMevNtv
{% endembed %}

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FeePrioMeanMevUSD>" %}
FeePrioMeanMevUSD
{% endembed %}

## Median Miner Tips Among MEV Transactions

<table><thead><tr><th width="177">Name</th><th width="157">MetricID</th><th width="124">Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Median Miner Tips Among MEV txs (native units)</td><td>FeePrioMedMevNtv</td><td>Native Units</td><td>1 day</td></tr><tr><td>Median Miner Tips Among MEV txs (USD)</td><td>FeePrioMedMevUSD</td><td>USD</td><td>1 day</td></tr></tbody></table>

### Definition

The median priority fee per MEV-enabled transaction in native units that interval. An MEV-enabled transaction is one that paid an MEV tip to miners/validators in exchange for specific block ordering.

### Details

* This fee is not included in `FeePrioMedNtv`.
* Generally, MEV transactions to not also pay an additional protocol native priority fee. While this can happen this would be the exception.

### **Asset-Specific Details**

* For Solana, slots proposed by validators running the Jito-Solana client are considered as MEV slots. Further, in Solana it is possible to identify which transactions paid MEV tip in addition to simply identifying the slot. For this metric each individual transaction is evaluated to determine which are MEV-enabled and which aren't.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FeePrioMedMevNtv>" %}
FeePrioMedMevNtv
{% endembed %}

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FeePrioTedMevUSD>" %}
FeePrioMedMevUSD
{% endembed %}

## Miner Revenue from MEV tips (%)

<table><thead><tr><th width="177">Name</th><th width="157">MetricID</th><th width="124">Unit</th><th>Interval</th></tr></thead><tbody><tr><td>Miner Revenue from MEV tips</td><td>FeeMevRevPct</td><td>Percent</td><td>1 day</td></tr></tbody></table>

### Definition

The percentage of miner revenue derived from MEV tips that interval. This is equal to the MEV tips divided by the native miner revenue plus non-native revenue (MEV tips).

### Details

* This fee is not included in `FeeRevPct`.
* Generally, MEV transactions to not also pay an additional protocol native priority fee. While this can happen this would be the exception.

### **Asset-Specific Details**

* For Solana, slots proposed by validators running the Jito-Solana client are considered as MEV slots. Further, in Solana it is possible to identify which transactions paid MEV tip in addition to simply identifying the slot. For this metric each individual transaction is evaluated to determine which are MEV-enabled and which aren't.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/FeeMevRevPct>" %}

### API Endpoints

MEV Fee metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `Fee*` and `FeeMev*` in the `metrics` parameter.

<mark style="color:blue;">`GET`</mark> `undefined/timeseries/asset-metrics`

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=FeeMevTotNtv&assets=sol&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=FeeMevTotNtv&assets=sol&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="FeeMevTotNtv", 
        assets="sol",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Revenue

### Contents

* [All Time Miner Revenue (USD) (RevAllTimeUSD)](#a)
* [Miner Revenue (native units) (RevNtv)](#b)
* [Miner Revenue (USD) (RevUSD)](#miner-revenue-usd)

## All Time Miner Revenue (USD) <a href="#a" id="a"></a>

### Definition

The sum USD value of all revenue (fees plus newly issued native units) for all time. This is measured for consensus participants (miners, stakers, validators or delegators).

| Name                   | MetricID      | Unit | Interval |
| ---------------------- | ------------- | ---- | -------- |
| All Time Revenue (USD) | RevAllTimeUSD | USD  | All time |

### Details

* This metric is defined as the cumulative sum of RevUSD.
* It’s also known as thermocap

### Release History

* Released in the 1.0 release of NDP

### Interpretation

* The cumulative miner revenue for an asset, also called Thermocap, can be interpreted as an estimate of fiat inflows into an asset. The assumption behind this is that miners have fiat expenses but crypto revenue. To cover their expenses (mining hardware, electricity, wages, etc..), they must sell some or most of their crypto revenue for fiat. Given that, we know that the other party of this transaction must sell fiat for crypto and is therefore a new inflow in the asset. While this holds for large assets, miners of smaller assets might sell their mined crypto for BTC/ETH and then sell this for USD. This is a naive heuristic and presumes that miners do not mine speculatively, hoarding their coins without selling them off.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/RevAllTimeUSD>" %}

## Revenue (native units) <a href="#b" id="b"></a>

### Definition

The sum native units of revenue (fees plus newly issued native units) that interval. This is measured for consensus participants (miners, stakers, validators or delegators).

| Name                             | MetricID        | Unit         | Interval       |
| -------------------------------- | --------------- | ------------ | -------------- |
| Revenue (native units)           | RevNtv          | Native units | 1 day, 1 block |
| Validator Revenue (native units) | RevValidatorNtv | Native units | 1 day          |
| Delegator Revenue (native units) | RevDelegatorNtv | Native units | 1 day          |

### Details

* Revenue doesn’t include founders reward/community funds issuance.

### Asset-Specific Details

* Post Ethereum Merge, RevNtv includes only Priority Fees for ETH
* For SOL, sum of all rewards earned for Voting, Staking, Fees & Rent by validators.

### Release History

* Released in the 4.3 release of NDP

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/RevNtv>" %}

## Miner Revenue (USD)

### Definition

The sum USD value of all revenue (fees plus newly issued native units) that day. This is measured for consensus participants (miners, stakers, validators or delegators).

| Name                    | MetricID        | Unit | Interval       |
| ----------------------- | --------------- | ---- | -------------- |
| Revenue (USD)           | RevUSD          | USD  | 1 day, 1 block |
| Validator Revenue (USD) | RevValidatorUSD | USD  | 1 day          |
| Delegator Revenue (USD) | RevDelegatorUSD | USD  | 1 day          |

### Details

* Revenue doesn’t include founders reward/community funds issuance.
* Price used is PriceUSD

### Asset-Specific Details

* Post Ethereum Merge, RevUSD includes only Priority Fees for ETH
* For SOL, sum of all rewards earned for Voting, Staking, Fees & Rent by validators.

### Release History

* Released in the 1.0 release of NDP

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/RevUSD>" %}

### API Endpoints

Revenue metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `Rev*` in the `metrics` parameter.

<mark style="color:blue;">`GET`</mark> `undefined/timeseries/asset-metrics`

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=RevAllTimeUSD&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=RevAllTimeUSD&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="RevAllTimeUSD", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Market

## Metrics

[Market Capitalization](/network-data/network-data-overview/market/market-capitalization)

* CapAct1yrUSD
* CapFutExp10yrUSD
* CapMrktCurUSD
* CapMrktEstUSD
* CapMrktFFUSD
* CapMVRVCur
* CapMVRVFF
* CapRealUSD

[Price](/network-data/network-data-overview/market/price)

* PriceBTC
* PriceUSD

[Profitability](/network-data/network-data-overview/market/profitability)

* UTXOLossUnrealUSD
* UTXOProfUnrealUSD

[Returns](/network-data/network-data-overview/market/returns)

* ROI1yr
* ROI30d

[Volatility](/network-data/network-data-overview/market/volatility)

* VtyDayRet180d
* VtyDayRet60d
* VtyDayRet30d


# Market Capitalization

### Contents

* [Capitalization, active supply, 1yr, USD](#a)
* [Capitalization, future expected supply, next 10yr, USD](#b)
* [Capitalization, market, current supply, USD](#c)
* [Capitalization, market, estimated supply, USD](#d)
* [Capitalization, market, free float](#e)
* [Capitalization, MVRV, free float](#g)
* [Capitalization, realized, USD](#h)
* Estimated Market Cap Dominance
* [Capitalization, realized, USD, age bands](#cap-real-age-bands)

## Active Market Cap (1yr) (USD) <a href="#a" id="a"></a>

### Definition

The sum USD value of all active native units in the last year. Native units that transacted more than once are only counted once.

| Name                          | MetricID     | Unit | Interval |
| ----------------------------- | ------------ | ---- | -------- |
| Active Market Cap (1yr) (USD) | CapAct1yrUSD | USD  | 1 year   |

### Details

* The state of the ledger is the one at the last available block for that day.
* Only the native units balance is considered, on-top tokens (e.g., ERC-20) are not included.
* Addresses owning 0 native units are not considered.
* For UTX-based protocols, last activity is the date of creation of the output. Mining reward outputs are not considered active.
* For account-based protocols, last activity is defined as either the time of the last debit of native units from this account, or the time at which it was created (if that creation wasn’t due to a genesis event or mining).

### Asset-Specific Details

* This metric is not available for assets that have full privacy, like Monero, Grin.
* For assets that have opt-in privacy features, like ZCash, it only takes the non-private balances into account.

### Release History

* Version 1.0 of CM Network Data Pro Daily Macro (End of Day)

### Interpretation

In contrast with Capitalization, realized, USD,this metric counts as valid on the fraction of supply which has moved in the prior 12 months. The intuition is to devise a measure of the economic significance of liquid and market-available supply, as evidenced by units that have made recent on-chain transactions. This metric can be volatile as large tranches of supply fall out of the eligibility window or as large sections move for the first time in over a year.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/CapAct1yrUSD>" %}

## Future Market Cap (USD) <a href="#b" id="b"></a>

### Definition

The sum USD value of all native units counting the current supply and including those that will be issued over the next 10 years if the current known issuance schedule is followed.

| Name                    | MetricID         | Unit | Interval |
| ----------------------- | ---------------- | ---- | -------- |
| Future Market Cap (USD) | CapFutExp10yrUSD | USD  | 10 years |

### Details

* Only continuous, predictable issuance is taken into account.
* Only information known at the time for which the metric is computed is used: unpredictable changes in monetary policy are taken into account only when they become effective. ETH’s reward changes from 5 ETH to 3 and from 3 ETH to 2 are not taken into account for values of the metric computed before they became effective. This metric doesn’t add forward knowledge.
* Price used is the daily close.
* The state of the ledger used is the one at the last available block for that day.
* It’s computed as SplyFutExp10yr \* PriceUSD

### Asset-Specific Details

* For ETH/ETC, uncle rate is fixed at 0.90625 uncle per block

### Release History

* Released in the 1.0 release of NDP

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/CapFutExp10yrUSD>" %}

## Market Cap (USD) <a href="#c" id="c"></a>

### Definition

The sum USD value of the current supply. Also referred to as network value or market capitalization.

| Name             | MetricID      | Unit | Interval |
| ---------------- | ------------- | ---- | -------- |
| Market Cap (USD) | CapMrktCurUSD | USD  | 1 day    |

### Details

* Computed as SplyCur \* PriceUSD
* The price used is the daily close price

### Asset-Specific Details

* For XRP, amounts under escrow are included in current supply

### Release History

* Released in the 1.0 release of NDP

### Interpretation

Informally called ‘market cap,’ our formulation differs in that we do consider all historically issued supply and does not exclude illiquid supply held in escrow or foundation accounts. In this respect, our formulation of this metric diverges from other sources who discount coins held in escrow or treasuries.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/CapMrktCurUSD>" %}

## Estimated Market Cap (USD) <a href="#d" id="d"></a>

### Definition

The sum USD value of the circulating supply. Also referred to as network value or market capitalization. Circulating supply is reported by the projects or other derived sources.

| Name                       | MetricID      | Unit | Interval |
| -------------------------- | ------------- | ---- | -------- |
| Estimated Market Cap (USD) | CapMrktEstUSD | USD  | 1 day    |

### Details

* Computed as Circulating Supply \* PriceUSD
* The price used is the daily close price (PriceUSD) at 00:00:00 UTC
* The circulating supply used is sourced through third party APIs

### Asset-Specific Details

* For ERC-20 assets, the circulating supply is sourced from EtherScan via CoinGecko
* Where available circulating supply was sourced from the projects circulating supply API end point via CoinGecko

### Interpretation

Informally called ‘Market Cap,’ our Estimated Market Cap aligns with the industry convention for Market Cap. We called this "Estimated Market Cap" because this is a reported amount and not sourced directly from what is seen on-chain.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/CapMrktEstUSD>" %}

## Free Float Market Cap (USD) <a href="#e" id="e"></a>

### Definition

The sum USD value of the free float supply. Also referred to as free float network value or free float market capitalization.

| Name                        | MetricID     | Unit | Interval |
| --------------------------- | ------------ | ---- | -------- |
| Free Float Market Cap (USD) | CapMrktFFUSD | USD  | 1 day    |

### Details

* Free Float Market Capitalization is a measure of the market value of an asset’s supply that is issued and available to market participants. This excludes supply that is held by company insiders, controlling investors and long term strategic holders.
* This metric is calculated by multiplying SplyFF by PriceUSD.
* For more details on Free Float Supply, please refer to our blog post [Introducing Free Float Supply](https://coinmetrics.io/introducing-free-float-supply/)

### Asset-Specific Details

* Only applicable to assets for which we have Free Float Supply (SplyFF) data available.
* ETH Free Float Supply includes tokens on the Consensus Layer and Execution Layer

### Release History

* Release Version: NDP-EOD 4.8 (Nov, 2020)

### See Also

* Free Float Supply

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/CapMrktFFUSD>" %}

## MVRV (Market Cap / Realized Market Cap) <a href="#f" id="f"></a>

### Definition

The ratio of the sum USD value of the current supply to the sum "realized" USD value of the current supply.

| Name                                    | MetricID   | Unit          | Interval |
| --------------------------------------- | ---------- | ------------- | -------- |
| MVRV (Market Cap / Realized Market Cap) | CapMVRVCur | Dimensionless | 1 day    |

### Details

* Computed as CapMrktCurUSD / CapRealUSD

### Chart

<figure><img src="/files/dHKAT4vfE4HfeOTtZiyR" alt=""><figcaption></figcaption></figure>

### Asset-Specific Details

* This metric is not available for assets that have full privacy, like Monero, Grin.
* For assets that have opt-in privacy features, like ZCash, it only takes the non-private balances into account, see Realized Cap’s entry for more details

### Release History

* Conceptualized by [Adaptive Capital](https://medium.com/adaptivecapital/bitcoin-market-value-to-realized-value-mvrv-ratio-3ebc914dbaee)
* Released in the 1.0 release of NDP

### Interpretation

Market value to realized value (MVRV) has historically been one of the most reliable on-chain indicators of bitcoin market tops and bottoms. MVRV is calculated by dividing bitcoin’s market capitalization by its [realized capitalization](https://coinmetrics.io/realized-capitalization/). Realized capitalization can also be thought of as a gross approximation of bitcoin’s aggregate cost basis.

The intuition behind the creation of this ratio was to divide a price function by a ‘fundamental’ - Realized Capitalization. This gives you a ratio potentially indicating periods of overvaluation (when network value far exceeds its historical relationship to realized cap) and undervaluation.

Historically, a high ratio of market capitalization to realized capitalization has signaled that bitcoin price was near a local maximum, while a low ratio has indicated that price is near a local minimum. The few times that MVRV has dropped below one have historically been some of the best times to buy bitcoin. An increasing MVRV indicates that current sentiment is increasing fast relative to estimated aggregate cost basis, while decreasing MVRV signals the opposite.

### See Also

* Free Float MVRV

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/CapMVRVCur>" %}

## Free Float MVRV (Free Float Market Cap / Realized Market Cap) <a href="#g" id="g"></a>

### Definition

The ratio of the free float market capitalization (CapMrktFFUSD) to the sum "realized" USD value of the current supply (CapRealUSD).

| Name                                                          | IMetricD  | Unit          | Interval |
| ------------------------------------------------------------- | --------- | ------------- | -------- |
| Free Float MVRV (Free Float Market Cap / Realized Market Cap) | CapMVRVFF | Dimensionless | 1 day    |

### Details

* This metric provides an important adjustment to the how MVRV is calculated.
* It improves upon the Market Value numerator of the MVRV formula (Market Cap/Realized Cap) by proving a more accurate representation of liquidity via CapMrktFFUSD.
* For more details on the significance of this improvement, please refer to the following blog post [Introducing Free Float Supply](https://coinmetrics.io/introducing-free-float-supply/)

### Chart

<figure><img src="/files/ZVdlbYCSYbELymyu0Y3T" alt=""><figcaption></figcaption></figure>

### Asset-Specific Details

Only applicable to assets for which we have Free Float Supply (SplyFF) data available.

### Release History

* Release Version: NDP-EOD 4.8 (Nov, 2020)

### Interpretation

Market value to realized value (MVRV) has historically been one of the most reliable on-chain indicators of bitcoin market tops and bottoms. MVRV is calculated by dividing bitcoin’s market capitalization by its [realized capitalization](https://coinmetrics.io/realized-capitalization/). Realized capitalization can also be thought of as a gross approximation of bitcoin’s aggregate cost basis. In our variant of the MVRV calculation, we use free float market capitalization which is calculated using [liquid supply as opposed to total supply](https://coinmetrics.substack.com/p/coin-metrics-state-of-the-network-7d0).

Historically, a high ratio of market capitalization to realized capitalization has signaled that bitcoin price was near a local maximum, while a low ratio has indicated that price is near a local minimum. The few times that MVRV has dropped below one have historically been some of the best times to buy bitcoin. An increasing MVRV indicates that current sentiment is increasing fast relative to estimated aggregate cost basis, while decreasing MVRV signals the opposite.

### See Also

* MVRV (Market Cap / Realized Market Cap)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/CapMVRVFF>" %}

## MVRV Z-Score <a href="#g" id="g"></a>

### Definition

The ratio of the current market capitalization minus the realized market capitalization to the standard deviation of the current market capitalization.

| Name         | IMetricD | Unit          | Interval |
| ------------ | -------- | ------------- | -------- |
| MVRV Z-Score | CapMVRVZ | Dimensionless | 1 day    |

### Details

* This metric is calculated as: (CapMrktCurUSD - CapRealUSD) / std(CapMrktCurUSD)
* MVRV Z-Score adjusts for the long-term volatility in market cap, making it easier to compare across different market cycles and identify extreme deviations from historical norms.
* Unlike regular MVRV (CapMVRVCur) or Free Float MVRV (CapMVRVFF), which are a raw ratio of market to realized value, MVRV Z-Score tells you how unusually high or low that relationship is compared to the asset's own historical behavior.

### Interpretation

The MVRV Z-Score measures how far Bitcoin’s market cap deviates from its realized cap, normalized by the historical volatility of market cap. It highlights periods where Bitcoin may be significantly overvalued or undervalued relative to its past trends, making it useful for spotting potential market tops and bottoms.

### See Also

* MVRV (Market Cap / Realized Market Cap)
* Free Float MVRV (Free Float Market Cap / Realized Market Cap)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/CapMVRVZ>" %}

## Realized Market Cap (USD) <a href="#h" id="h"></a>

### Definition

The sum USD value based on the USD closing price on the day that a native unit last moved (i.e., last transacted) for all native units.

| Name                      | MetricID   | Unit | Interval |
| ------------------------- | ---------- | ---- | -------- |
| Realized Market Cap (USD) | CapRealUSD | USD  | 1 day    |

### Details

* This metric takes the ledger state of the asset, assigns a date of last movement for each account/unspent output, multiplies the balance of the account/value of the output by the price at the date of last movement and sums all of those numbers for the asset’s ledger.
* The state of the ledger is the one at the last available block for that day.
* Only the native units balance is considered, L2 tokens (ERC-20, etc.) are not taken into account.
* For UTXO chains, last activity is the date of creation of the output.
* For account-based chains, last activity is either the last date the account was the sender of a ledger change, or its time of creation, whichever is more recent.

### Chart

<figure><img src="/files/GhhjoxCOoKiVrUERUDKn" alt=""><figcaption></figcaption></figure>

### Asset-Specific Details

* This metric is not available for assets that have full privacy, like Monero, Grin.
* For assets that have opt-in privacy features, like ZCash, it only takes the non-private balances into account. The realized cap is first computed over the non-private balances, then scaled so that ratios like MVRV can be computed: Realized Cap = Non-private realized Cap + Private Supply \* (Non-private realized cap/ (Total Current Supply - Private supply)) This can be understood as taking the non-private supply’s price implied by the realized cap (Non-private realized cap / Non private supply) and assigning that price to the private supply.

### Example

For an asset whose ledger is:

| Account | Balance | Time of last movement | Price at last movement | Realized balance |
| ------- | ------- | --------------------- | ---------------------- | ---------------- |
| A       | 100     | 2010-01-01            | $0                     | $0               |
| B       | 1000    | 2016-01-01            | $10                    | $10,000          |
| C       | 500     | 2019-01-01            | $100                   | $50,000          |

The realized cap would be $0 + $10,000 + $50,000 = $60,000

For assets like ZEC, assuming there’s 5M native units outstanding, 1M private, 4M non-private. If the realized cap of the non-private supply is $1B, the total realized cap is computed as: $1B \* (1M \* ($1B / (5M - 1M)) = $1.25B

### Release History

* Conceptualized by [Coin Metrics](https://coinmetrics.io/realized-capitalization/)
* Released in the 1.0 release of NDP

### Interpretation

Realized capitalization (sometimes referred to as Realized Value) is one of Coin Metrics’ flagship metrics, first introduced in a [talk by Nic Carter](https://medium.com/@RainDogDance/bitcoin-as-a-novel-market-institution-nic-carter-talk-at-baltic-honeybadger-2018-e085f163b213) in 2018. Realized cap aggregates units of supply according to their market price when they last moved on-chain. The original intent was to discount the weight of long-lost coins, in particular in Bitcoin, as a significant fraction of supply is inert and has not moved since 2010 (and can be presumed lost). Additionally, realized cap is a more faithful measure of economic significance for forks with limited uptake, as conventional measures like market cap naively presume that the entire stock of coins is liquid and market-available. Interpretations vary, but realized cap is perhaps best-understood as a metric which captures the average cost basis of all current holders. It has been used to devise popular oscillators and derivative metrics.

### See Also

* [Introduction to Realized Cap](https://coinmetrics.io/realized-capitalization/)
* [SOTN: Realized Cap Passes $100B](https://coinmetrics.substack.com/p/coin-metrics-state-of-the-network-fe8)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/CapRealUSD>" %}

## Estimated Market Cap Dominance

### Definition

The relative share of the total crypto market cap for the asset in question, measured in percent.

| Name                           | MetricID         | Unit    | Interval |
| ------------------------------ | ---------------- | ------- | -------- |
| Estimated Market Cap Dominance | CapMrktEstDomPct | Percent | 1 day    |

### Details

* Measures the relative share of a single assets market cap compared to the total crypto market cap as covered by Coin Metrics.
* Calculated as `ASSET.CapMrktEstUSD/SUM(CapMrktEstUSD)*100`

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics-v2/CapMrktEstDomPct>" %}

## Realized Market Cap Age Bands (USD) <a href="#cap-real-age-bands" id="cap-real-age-bands"></a>

### Definition

The sum USD value based on the USD closing price on the day that a native unit last moved, segmented by the time elapsed since that movement. Each band captures the portion of the Realized Market Cap attributable to native units whose most recent on-chain transaction falls within a specific age window.

| Name                             | MetricID          | Unit | Interval |
| -------------------------------- | ----------------- | ---- | -------- |
| Realized Cap (USD) 1 day Band    | CapRealUSD1d      | USD  | 1 day    |
| Realized Cap (USD) 1 week Band   | CapRealUSD1w      | USD  | 1 day    |
| Realized Cap (USD) 1 month Band  | CapRealUSD1m      | USD  | 1 day    |
| Realized Cap (USD) 3 month Band  | CapRealUSD3m      | USD  | 1 day    |
| Realized Cap (USD) 6 month Band  | CapRealUSD6m      | USD  | 1 day    |
| Realized Cap (USD) 1 year Band   | CapRealUSD1y      | USD  | 1 day    |
| Realized Cap (USD) 2 year Band   | CapRealUSD2y      | USD  | 1 day    |
| Realized Cap (USD) 3 year Band   | CapRealUSD3y      | USD  | 1 day    |
| Realized Cap (USD) 4 year Band   | CapRealUSD4y      | USD  | 1 day    |
| Realized Cap (USD) 5 year Band   | CapRealUSD5y      | USD  | 1 day    |
| Realized Cap (USD) 7 year Band   | CapRealUSD7y      | USD  | 1 day    |
| Realized Cap (USD) 10 year Band  | CapRealUSD10y     | USD  | 1 day    |
| Realized Cap (USD) 10 year+ Band | CapRealUSD10yPlus | USD  | 1 day    |

Each band covers a specific age range, where age is the number of days elapsed since the UTXO was created (i.e., since the native unit last moved):

| MetricID          | Age Range (Days Since Last Movement) |
| ----------------- | ------------------------------------ |
| CapRealUSD1d      | Less than 1 day                      |
| CapRealUSD1w      | 1 to 6 days                          |
| CapRealUSD1m      | 7 to 29 days                         |
| CapRealUSD3m      | 30 to 89 days                        |
| CapRealUSD6m      | 90 to 179 days                       |
| CapRealUSD1y      | 180 to 364 days                      |
| CapRealUSD2y      | 365 to 729 days                      |
| CapRealUSD3y      | 730 to 1,094 days                    |
| CapRealUSD4y      | 1,095 to 1,459 days                  |
| CapRealUSD5y      | 1,460 to 1,824 days                  |
| CapRealUSD7y      | 1,825 to 2,554 days                  |
| CapRealUSD10y     | 2,555 to 3,649 days                  |
| CapRealUSD10yPlus | 3,650 days or more                   |

### Details

* Follows the same methodology as Realized Market Cap (USD) (CapRealUSD), but partitions supply by UTXO age at the time of computation.
* UTXO age is the number of days between the date of creation of the output and the computation date.
* Each UTXO is assigned to exactly one band. The sum of all age band values equals the total Realized Market Cap (CapRealUSD).
* The state of the ledger is the one at the last available block for that day.
* Only native units balance is considered; on-top tokens (e.g., ERC-20) are not included.

### Asset-Specific Details

* Currently only available for Bitcoin.

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/CapRealUSD1d>" %}

### API Endpoints

Exhange Deposits metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `Cap*` in the `metrics` parameter.

<mark style="color:blue;">`GET`</mark> `undefined/timeseries/asset-metrics`

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=CapAct1yrUSD&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=CapAct1yrUSD&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="CapAct1yrUSD", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Price

### Contents

* [Price, BTC](#btc-denominated-closing-price)
* [Price, USD](#usd-denominated-closing-price)

## BTC Denominated Closing Price

### Definition

The price of the asset denominated in Bitcoin units.

| Name                  | MetricID | Unit | Interval      |
| --------------------- | -------- | ---- | ------------- |
| BTC Denominated Price | PriceBTC | BTC  | 1 day, 1 hour |

### Details

* This metric is available in both daily and block frequencies. The daily frequency represents the price as of the end of the day in UTC time. The block frequency represents the price at the time the block was added to the blockchain.\\
* This metric is identical to `ReferenceRateBTC` but with different timestamp conventions. Please see the frequently asked questions below for more information on this topic.\\
* This price is computed using our CM Reference Rates. Please see our CM Prices Overview for more information on methodology and policies.

### Example

A sample of the `PriceBTC` metric for Ethereum with daily frequency is shown below:

```
{
  "data" : [ {
    "asset" : "eth",
    "time" : "2023-03-18T00:00:00.000000000Z",
    "PriceBTC" : "0.06538140200862749"
  }, {
    "asset" : "eth",
    "time" : "2023-03-19T00:00:00.000000000Z",
    "PriceBTC" : "0.06392540140433825"
  }, {
    "asset" : "eth",
    "time" : "2023-03-20T00:00:00.000000000Z",
    "PriceBTC" : "0.062418493975669356"
  }, {
    "asset" : "eth",
    "time" : "2023-03-21T00:00:00.000000000Z",
    "PriceBTC" : "0.06407211604389325"
  }, {
    "asset" : "eth",
    "time" : "2023-03-22T00:00:00.000000000Z",
    "PriceBTC" : "0.06357608845321447"
  }
}
```

A sample of the `PriceBTC` metric for Ethereum with block frequency is shown below:

```
{
  "data" : [ {
    "block_hash" : "cf604b220ea0f3fba67244573f33a36919b6cf2ff7ea210a86377d229bb9b0d8",
    "parent_block_hash" : "152ca610b2f68643c43dd82dcdb79519ee26f490cf29c14456ac23f9489eaa1b",
    "height" : "16890992",
    "asset" : "eth",
    "time" : "2023-03-23T15:01:35.000000000Z",
    "PriceBTC" : "0.06447664"
  }, {
    "block_hash" : "7f279840f5f4cf23a7a6c880531f1dd2858b2a6ad220dc7123600c064c700db9",
    "parent_block_hash" : "cf604b220ea0f3fba67244573f33a36919b6cf2ff7ea210a86377d229bb9b0d8",
    "height" : "16890993",
    "asset" : "eth",
    "time" : "2023-03-23T15:01:47.000000000Z",
    "PriceBTC" : "0.0644538"
  }, {
    "block_hash" : "2051a0dba9018764e8469f4f5de4845c5c7333e34b84e258f088f6b7ceb5369e",
    "parent_block_hash" : "7f279840f5f4cf23a7a6c880531f1dd2858b2a6ad220dc7123600c064c700db9",
    "height" : "16890994",
    "asset" : "eth",
    "time" : "2023-03-23T15:01:59.000000000Z",
    "PriceBTC" : "0.0644743"
  }, {
    "block_hash" : "fb45b96b4527c535a957754ef81b603e878da31d05f20010497914177cd0c2b0",
    "parent_block_hash" : "2051a0dba9018764e8469f4f5de4845c5c7333e34b84e258f088f6b7ceb5369e",
    "height" : "16890995",
    "asset" : "eth",
    "time" : "2023-03-23T15:02:11.000000000Z",
    "PriceBTC" : "0.06449479"
  }, {
    "block_hash" : "e5f672e9accdcedc0c319de63037a25102b47efdfd794bf4e3e5124bcc20b8c4",
    "parent_block_hash" : "fb45b96b4527c535a957754ef81b603e878da31d05f20010497914177cd0c2b0",
    "height" : "16890996",
    "asset" : "eth",
    "time" : "2023-03-23T15:02:23.000000000Z",
    "PriceBTC" : "0.06443347"
  }
}
```

* **`asset`**: The ID of the asset.\\
* **`time`**: The reference rate time in ISO 8601 date-time format.\\
* **`PriceBTC`**: The published reference rate value in Bitcoin units.\\
* **`block_hash`**: The hash of the block.\\
* **`parent_block_hash`**: The hash of the parent block.\\
* **`height`**: The block height.

### Release History

* Released in the version 1.0 release of NDP

### Availability for Assets

Please see our Coin Metrics Coverage below for our asset coverage universe.

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/PriceBTC>" %}

## USD Denominated Closing Price

### Definition

The price of the asset denominated in U.S. Dollars.

| Name                          | MetricID | Unit | Interval              |
| ----------------------------- | -------- | ---- | --------------------- |
| USD Denominated Closing Price | PriceUSD | USD  | 1 day, 1block, 1 hour |

### Details

* This metric is available in both daily and block frequencies. The daily frequency represents the price as of the end of the day in UTC time. The block frequency represents the price at the time the block was added to the blockchain.\\
* This metric is identical to `ReferenceRate` and `ReferenceRateUSD` but with different timestamp conventions. Please see the frequently asked questions below for more information on this topic.\\
* This price is computed using our CM Reference Rates. Please see our CM Prices Overview for more information on methodology and policies.

### Example

A sample of the `PriceUSD` metric for Bitcoin with daily frequency is shown below:

```
{
  "data" : [ {
    "asset" : "btc",
    "time" : "2023-03-18T00:00:00.000000000Z",
    "PriceUSD" : "26985.7359915254"
  }, {
    "asset" : "btc",
    "time" : "2023-03-19T00:00:00.000000000Z",
    "PriceUSD" : "28185.2043319696"
  }, {
    "asset" : "btc",
    "time" : "2023-03-20T00:00:00.000000000Z",
    "PriceUSD" : "27834.3361090006"
  }, {
    "asset" : "btc",
    "time" : "2023-03-21T00:00:00.000000000Z",
    "PriceUSD" : "28172.7950558153"
  }, {
    "asset" : "btc",
    "time" : "2023-03-22T00:00:00.000000000Z",
    "PriceUSD" : "27341.5571297487"
  }
}
```

A sample of the `PriceUSD` metric for Bitcoin with block frequency is shown below:

```
{
  "data" : [ {
    "block_hash" : "000000000000000000061ade334ac0403c9473001639a16d4ff93bb822d30e92",
    "parent_block_hash" : "00000000000000000003c4583ecf8f90eefc404e8fb42e035649b7ed3010936d",
    "height" : "782143",
    "asset" : "btc",
    "time" : "2023-03-23T13:33:46.000000000Z",
    "PriceUSD" : "27520.25"
  }, {
    "block_hash" : "000000000000000000063ca1e45712d631ae9daa0bca98fd2d42229471d5abd6",
    "parent_block_hash" : "000000000000000000061ade334ac0403c9473001639a16d4ff93bb822d30e92",
    "height" : "782144",
    "asset" : "btc",
    "time" : "2023-03-23T13:36:23.000000000Z",
    "PriceUSD" : "27493.35"
  }, {
    "block_hash" : "000000000000000000040f8e246619bea33b4e22a4f797daa78ef721c727885f",
    "parent_block_hash" : "000000000000000000063ca1e45712d631ae9daa0bca98fd2d42229471d5abd6",
    "height" : "782145",
    "asset" : "btc",
    "time" : "2023-03-23T13:48:09.000000000Z",
    "PriceUSD" : "27404.86"
  }, {
    "block_hash" : "0000000000000000000391940aa48790413a38ec3834d299a05eaaa797f2336b",
    "parent_block_hash" : "000000000000000000040f8e246619bea33b4e22a4f797daa78ef721c727885f",
    "height" : "782146",
    "asset" : "btc",
    "time" : "2023-03-23T13:49:45.000000000Z",
    "PriceUSD" : "27384.94"
  }, {
    "block_hash" : "000000000000000000006b582725ac8e609305e3b5643afe0a92205220cf7fa6",
    "parent_block_hash" : "0000000000000000000391940aa48790413a38ec3834d299a05eaaa797f2336b",
    "height" : "782147",
    "asset" : "btc",
    "time" : "2023-03-23T14:20:06.000000000Z",
    "PriceUSD" : "27463"
  }
}
```

* **`asset`**: The ID of the asset.\\
* **`time`**: The reference rate time in ISO 8601 date-time format.\\
* **`PriceUSD`**: The published reference rate value in U.S. Dollars.\\
* **`block_hash`**: The hash of the block.\\
* **`parent_block_hash`**: The hash of the parent block.\\
* **`height`**: The block height.

### Release History

* Released in the version 1.0 release of NDP

### Availability for Assets

Please see our Coin Metrics Coverage below for our asset coverage universe.

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/PriceUSD>" %}

### API Endpoints

Exhange Deposits metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `Price*` in the `metrics` parameter.

<mark style="color:blue;">`GET`</mark> `undefined/timeseries/asset-metrics`

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=PriceUSD&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=PriceUSD&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="PriceUSD", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Profitability

### Contents

* [UTXO set, gross unrealized loss, USD](#unrealized-utxo-losses-usd)
* [UTXO set, gross unrealized profit, USD](#unrealized-utxo-profits-usd)

## Unrealized UTXO Losses (USD)

### Definition

The total unrealized loss of unspent transaction outputs on the network.

| Name                         | MetricID          | Unit | Interval |
| ---------------------------- | ----------------- | ---- | -------- |
| Unrealized UTXO Losses (USD) | UTXOLossUnrealUSD | USD  | 1 day    |

### Release History

* Release Version: NDP-EOD 4.8 (Nov, 2020)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/UTXOLossUnrealUSD>" %}

## Unrealized UTXO Profits (USD)

### Definition

The total unrealized profit of unspent transaction outputs on the network.

| Name                          | MetricID          | Unit | Interval |
| ----------------------------- | ----------------- | ---- | -------- |
| Unrealized UTXO Profits (USD) | UTXOProfUnrealUSD | USD  | 1 day    |

### Release History

* Release Version: NDP-EOD 4.8 (Nov, 2020)

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/UTXOProfUnrealUSD>" %}

### API Endpoints

Exhange Deposits metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `UTXO*` in the `metrics` parameter.

<mark style="color:blue;">`GET`</mark> `undefined/timeseries/asset-metrics`

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=UTXOLossUnrealUSD&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=UTXOLossUnrealUSD&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="UTXOLossUnrealUSD", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Returns

### Contents

* [ROI, percent](#roi)

## ROI

### Definition

The return on investment for the asset assuming a purchase 12 months prior.[<br>](https://docs.coinmetrics.io/info/metrics/ROI1yr)

| Name         | MetricID | Unit          | Interval      |
| ------------ | -------- | ------------- | ------------- |
| ROI, 1 Year  | ROI1yr   | Dimensionless | 1 day, 1 hour |
| ROI, 30 Days | ROI30d   | Dimensionless | 1 day, 1 hour |

### Details

Calculated as PriceUSD Change/PriceUSD Previous\*100

### Release History

* Released in the 1.0 release of NDP

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/ROI1yr>" %}

### API Endpoints

Exchange Deposits metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `ROI*` in the `metrics` parameter.

<mark style="color:blue;">`GET`</mark> `undefined/timeseries/asset-metrics`

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=ROI1yr&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=ROI1yr&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="ROI1yr", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Volatility

### Contents

* [Volatility, daily returns](#x-day-volatility)

## X Day Volatility

### Definition

The X days volatility, measured as the deviation of log returns

| Name               | MetricID      | Unit          | Interval |
| ------------------ | ------------- | ------------- | -------- |
| 180 Day Volatility | VtyDayRet180d | Dimensionless | 180 days |
| 60 Day Volatility  | VtyDayRet60d  | Dimensionless | 60 days  |
| 30 Day Volatility  | VtyDayRet30d  | Dimensionless | 30 days  |

### Details

* Computed as the standard deviation of the daily natural log returns over X days.

### Release History

* Released in the 1.0 release of NDP

### Availability for Assets

{% embed url="<https://coverage.coinmetrics.io/asset-metrics/VtyDayRet180d>" %}

### API Endpoints

Exhange Deposits metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `VtyDayRet*` in the `metrics` parameter.

<mark style="color:blue;">`GET`</mark> `undefined/timeseries/asset-metrics`

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=VtyDayRet180d&assets=btc&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=VtyDayRet180d&assets=btc&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="VtyDayRet180d", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Key Risk Indicator (KRI) Feed

**A Background on Network Risk**

Bitcoin is the first successful implementation of a blockchain with its own native cryptocurrency. It solved a fundamental problem in computer science abstractly expressed by Lamport, Shostak, and Pease in 1982 as the Byzantine Generals Problem, or BGP. The crux of this problem is that, in networks where participants do not trust each other, it is hard to discern statements that are true from those that are false. If enough network participants are malicious or are acting erratically, it becomes impossible for honest participants to converge on what is true. It took decades for this problem to be effectively solved in an open network with the advent of Bitcoin’s Nakamoto Consensus. Beyond providing a solution to the BGP, Bitcoin effectively gave birth to an entire industry as it demonstrated a novel way to issue and settle assets.\\

A fundamental property of Nakamoto Consensus that was key in solving the BGP is the ability for the ordering of blocks in the blockchain to be changed if certain conditions are met. The most common of such events are Chain Reorganizations, or “reorgs”. When reorgs occur, transactions may be removed from the blockchain. Previously valid blocks are removed and transactions are sent back to the memory pool or the mempool, the space within a blockchain node where unprocessed transactions are temporarily stored. A drawback of this system is that if fee conditions in the network change by the time such transactions return to the mempool, their final settlement might be impeded without additional action by users. Cryptoasset exchanges have historically been impacted by this in times of network fee volatility, especially during the 2017 bull market.\\

The very same property also makes it possible for network attacks, such as so-called “51% attacks,” in which an attacker attains enough mining power to trigger reorgs for personal gain. The feasibility of these attacks depends on the number of honest miners securing a network: while these attacks have never been successfully performed on a large network like Bitcoin, smaller networks such as Bitcoin Gold, Vertcoin, and Ethereum Classic have been targeted. In most cases, cryptoasset exchanges are the main targets of these attacks. By simply reverting exchange deposits, attackers have been able to net millions of dollars worth of cryptoassets. Unfortunately, just like naturally occurring reorgs, market participants such as exchanges have few resources to manage such risks and assess the likelihood of their transactions being affected.\\

FARUM solves this problem by tracking the full spectrum of possible risks by making use of both conventional and unconventional data sources. Raw data on blockchain transactions across all supported networks is formatted in accordance with Coin Metric’s Universal Blockchain Data Model (UBDM), which is provisioned via the [Atlas API](https://coinmetrics.io/atlas/). In order to also provide alerts on unprocessed transactions, FARUM employs Coin Metric’s Mempool Collector, a low-latency mempool querying engine built from the ground up to maximize performance. These sources provide a complete view of both processed and unprocessed transactions from which network risk can be managed and alerts can be created.\\

Given the wide spectrum of risk vectors that must be covered, FARUM looks beyond transactional data flowing through a cryptoasset’s peer-to-peer network. Since observing mining pool protocols can provide a view on future blocks, additional data sources include the Mining Pool Collector, which connects to several mining pools via the Stratum protocol to obtain information about blocks being mined and/or impending network attacks. In order to evaluate potential attack vectors and/or ongoing attacks, FARUM employs many other collectors that will be described in this document.

See:

* [Network Risk Overview](https://gitlab.com/coinmetrics/front-end/knowledge-base/-/blob/master/docs/network-data/network-data-overview/key-risk-indicator-kri-feed/broken-reference/README.md)

[**Block Attributes**](/network-data/network-data-overview/kri/block-attributes)

* block\_base\_fee
* block\_priority\_fee

[**Block Size**](/network-data/network-data-overview/kri/block-size)

* block\_size

[**Block Times**](/network-data/network-data-overview/kri/block-times)

* time\_inter\_block
* time\_since\_last\_block

[**Blocks**](/network-data/network-data-overview/kri/blocks)

* block\_count\_at\_tip
* block\_count\_by\_same\_miner\_6b
* block\_count\_by\_unknown\_miners\_6b
* block\_count\_without\_segwit

[**Empty Blocks**](/network-data/network-data-overview/kri/empty-blocks)

* block\_count\_consecutive\_empty
* block\_count\_empty\_6b
* block\_missed\_slots

[**Feerates**](/network-data/network-data-overview/kri/feerates)

* mempool\_feerate\_mean
* mempool\_feerate\_median
* mempool\_next\_block\_approx\_feerate\_max
* mempool\_next\_block\_approx\_feerate\_mean
* mempool\_next\_block\_approx\_feerate\_median
* mempool\_next\_block\_approx\_feerate\_min
* mempool\_next\_block\_inclusion\_approx\_feerate\_min

[**Fees**](/network-data/network-data-overview/kri/fees)

* mempool\_fee
* mempool\_fee\_entered\_1m
* mempool\_fee\_mean
* mempool\_fee\_mean\_entered\_1m
* mempool\_fee\_median

[**Hashrate**](/network-data/network-data-overview/kri/hashrate)

* block\_hashrate\_mean\_1d

[**Outputs**](/network-data/network-data-overview/kri/outputs)

* mempool\_output\_value
* mempool\_output\_value\_entered\_1m

[**Rewards**](/network-data/network-data-overview/kri/rewards)

* mining\_reward\_mean
* mining\_reward\_spread

[**Transaction Feerates**](/network-data/network-data-overview/kri/transaction-feerates)

* block\_feerate\_max
* block\_feerate\_mean
* block\_feerate\_median
* block\_feerate\_min

[**Transaction Fees**](/network-data/network-data-overview/kri/transaction-fees)

* block\_fee\_max
* block\_fee\_mean
* block\_fee\_median
* block\_fee\_min
* block\_fees

[**Transaction Sizes**](/network-data/network-data-overview/kri/transaction-sizes)

* mempool\_size
* mempool\_size\_entered\_1m
* mempool\_size\_left\_1m
* mempool\_vsize
* mempool\_vsize\_entered\_1m
* mempool\_vsize\_left\_1m

[**Transactions**](/network-data/network-data-overview/kri/transactions)

* block\_tx\_count
* mempool\_count
* mempool\_count\_entered\_1m


# Blocks

## Contents

* [Block Count at Tip (block\_count\_at\_tip)](#block_count_at_tip)
* [Block Count by Same Miner (block\_count\_by\_same\_miner\_6b)](#block_count_by_same_miner)
* [Blocks by Unknown Miners (block\_count\_by\_unknown\_miners\_6b)](#block_count_by_unknown_miners)
* [Blocks Without Segwit (block\_count\_without\_segwit\_6b)](#block_count_without_segwit)

## Block Count at Tip <a href="#block_count_at_tip" id="block_count_at_tip"></a>

**Definition**

The number of blocks identified at the chain tip.

**Dictionary**

| Name               | MetricID              | Category | Sub-category     | Type | Unit          | Interval |
| ------------------ | --------------------- | -------- | ---------------- | ---- | ------------- | -------- |
| Block Count at Tip | block\_count\_at\_tip | KRI      | Block Attributes | Sum  | Count of tips | 1b       |

**Methodology**

Counts the number of unique block hashes at the tip of the chain and returns that number. More than one block count at the tip of the chain indiciates a fork in the chain.

**Available Assets**

Bitcoin (BTC), Ethereum (ETH)

**Sample Query**

{% embed url="<https://api.coinmetrics.io/v4/timeseries/asset-metrics?api_key=%3Cyour_key%3E&assets=btc,eth&frequency=1b&metrics=block_count_at_tip&pretty=true>" %}

## Block Count by Same Miner <a href="#block_count_by_same_miner" id="block_count_by_same_miner"></a>

**Definition**

The number of blocks mined by the same miner in the past 6 blocks.

**Dictionary**

<table data-header-hidden><thead><tr><th width="179"></th><th width="282"></th><th width="112"></th><th width="142"></th><th></th><th width="155"></th><th></th></tr></thead><tbody><tr><td>Name</td><td>MetricID</td><td>Category</td><td>Sub-category</td><td>Type</td><td>Unit</td><td>Interval</td></tr><tr><td>Block Count by Same Miner</td><td>block_count_by_same_miner_6b</td><td>KRI</td><td>Block Attributes</td><td>Sum</td><td>Coun of Blocks</td><td>1b</td></tr></tbody></table>

**Methodology**

The 6 blocks from the tip of the blockchain (including the most recent block) are assessed. Coin Metric employs a proprietary entity clustering methodology in order to identify major mining pools & miners. The coinbase output field used by miners to self-identify is also used to help assess miner identities.

**Available Assets**

Bitcoin (BTC), *Ethereum (ETH)\*.*

*\* Historical data covering the pre-merge timeframe only (up to 9/15/2022). With the merge ETH switched from Proof of Work and miners to Proof of Stake and validators meaning the network no longer has any miners as of the merge date.*

**Sample Query**

{% embed url="<https://api.coinmetrics.io/v4/timeseries/asset-metrics?api_key=%3Cyour_key%3E&assets=btc&frequency=1b&metrics=block_count_by_same_miner_6b&pretty=true>" %}

## Blocks by Unknown Miners <a href="#block_count_by_unknown_miners" id="block_count_by_unknown_miners"></a>

**Definition**

The count of blocks that have been mined by unknown miners 6 blocks from the tip of the blockchain.

**Dictionary**

| Name                    | MetricID                              | Category | Sub-category | Type | Unit            | Interval |
| ----------------------- | ------------------------------------- | -------- | ------------ | ---- | --------------- | -------- |
| Blocks by unknown miner | block\_count\_by\_unknown\_miners\_6b | KRI      | Mining Pools | Sum  | Count of blocks | 1 block  |

**Methodology**

The 6 blocks from the tip of the blockchain (including the most recent block) are assessed. Coin Metric employs a proprietary entity clustering methodology in order to identify major mining pools & miners. The coinbase output field used by miners to self-identify is also used to help assess miner identities.

**Available Assets (v1)**

Bitcoin (BTC), *Ethereum (ETH)\*.*

*\* Historical data covering the pre-merge timeframe only (up to 9/15/2022). With the merge ETH switched from Proof of Work and miners to Proof of Stake and validators meaning the network no longer has any miners as of the merge date.*

**Sample Query**

{% embed url="<https://api.coinmetrics.io/v4/timeseries/asset-metrics?api_key=%3Cyour_key%3E&assets=btc&frequency=1b&limit_per_asset=1&metrics=block_count_by_unknown_miners_6b&pretty=true>" %}

## Non SegWit Blocks <a href="#block_count_without_segwit" id="block_count_without_segwit"></a>

**Definition**

The number of blocks without [SegWit](https://en.bitcoin.it/wiki/Segregated_Witness) transactions in the past 6 blocks.

**Dictionary**

| Name              | MetricID                          | Category | Sub-category     | Type | Unit             | Interval |
| ----------------- | --------------------------------- | -------- | ---------------- | ---- | ---------------- | -------- |
| Non segwit blocks | block\_count\_without\_segwit\_6b | KRI      | Block Attributes | Sum  | Number of blocks | 1 block  |

**Methodology**

The 6 blocks from the tip of the blockchain (including the most recent block) are assessed, and the number of blocks without SegWit transactions is counted.

**Available Assets**

Bitcoin (BTC)

**Sample Query**

{% embed url="<https://api.coinmetrics.io/v4/timeseries/asset-metrics?api_key=%3Cyour_key%3E&assets=btc&frequency=1b&limit_per_asset=1&metrics=block_count_without_segwit_6b&pretty=true>" %}

## API Endpoints

Blocks metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `block_count*` in the `metrics` parameter.

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=block_count_at_tip&assets=btc&frequency=1b&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=block_count_at_tip&assets=btc&frequency=1b&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="block_count_at_tip", 
        assets="btc",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}


# Block Attributes

## Contents

* [Base Fee for Block (block\_base\_fee)](#block_base_fee)
* [Priority Fee for Block (block\_priority\_fee)](#block_priority_fee)

## Base Fee for Block <a href="#block_base_fee" id="block_base_fee"></a>

**Definition**

The base fee of the most recent block processed.

**Dictionary**

| Name               | MetricID         | Unit | Interval |
| ------------------ | ---------------- | ---- | -------- |
| Base Fee for Block | block\_base\_fee | ETH  | 1b       |

**Methodology**

The most recent block we processed within a 1-minute window is evaluated and its Base Fee captured. The concept of a Base Fee was introduced as part of EIP-1559 and it represents the portion of the total transaction fees that is destroyed and taken out of circulation (i.e. burnt). Ethereum post-1559 requires users to pay for a Base Fee as a prerequisite to include transactions in a block. The Base Fee can go up or down on the basis of the size (in gas units) of the previous block.

**Available Assets**

Ethereum (ETH)

**Sample Query**

{% embed url="<https://api.coinmetrics.io/v4/timeseries/asset-metrics?api_key=%3Cyour_key%3E&assets=eth&frequency=1b&metrics=block_base_fee&pretty=true>" %}

## Priority Fee for Block <a href="#block_priority_fee" id="block_priority_fee"></a>

**Definition**

The priority fee, or tip, of the most recent block processed.

**Dictionary**

| Name                   | MetricID             | Unit | Interval |
| ---------------------- | -------------------- | ---- | -------- |
| Priority Fee for Block | block\_priority\_fee | ETH  | 1b       |

**Methodology**

The most recent block we processed within a 1-minute window is evaluated and its Priority Fee, or tip, is captured. The concept of a Miner Tip was introduced as part of EIP-1559 and it represents the portion of the total transaction fees that rewards miners. This serves as an added incentive so that miners prioritize transactions that have opted-in and paid a tip. The other portion is called the Base Fee, and it is burnt (destroyed) after the transaction is included in a block.

**Available Assets**

Ethereum (ETH)

**Sample Query**

{% embed url="<https://api.coinmetrics.io/v4/timeseries/asset-metrics?api_key=%3Cyour_key%3E&assets=eth&frequency=1b&metrics=block_priority_fee&pretty=true>" %}

## API Endpoints

metrics can be accessed using these endpoints:

* `timeseries/asset-metrics`

and by passing in the metric ID's `block_*_fee` in the `metrics` parameter.

{% openapi src="/files/kc3C7O6zTLYNBA0AcsZt" path="/timeseries/asset-metrics" method="get" %}
[openapi.yaml](https://2398817338-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MO23j33wWGzm0NrZseN%2Fuploads%2Fgit-blob-a236d0d04b3b155748ce07a17aca8108fce9b7c2%2Fopenapi.yaml?alt=media)
{% endopenapi %}

{% tabs %}
{% tab title="Shell" %}

```shell
curl --compressed "https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=block_base_fee&assets=eth&frequency=1b&pretty=true&api_key=<your_key>"
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
response = requests.get('https://api.coinmetrics.io/v4/timeseries/asset-metrics?metrics=block_base_fee&assets=eth&frequency=1b&pretty=true&api_key=<your_key>').json()
print(response)
```

{% endtab %}

{% tab title="Python Client" %}

```python
from coinmetrics.api_client import CoinMetricsClient

api_key = "<API_KEY>"
client = CoinMetricsClient(api_key)

print(
    client.get_asset_metrics(
        metrics="block_base_fee", 
        assets="eth",
    ).to_dataframe()
)
```

{% endtab %}
{% endtabs %}




---

[Next Page](/llms-full.txt/1)

