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 newsletter.
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 website contains the full set of endpoints and data offered by Coin Metrics.
The Coin Metrics Product Docs gives detailed, conceptual explanations of the data that Coin Metrics offers.
from os import environimport sysfrom datetime import date, datetime, timedeltaimport loggingimport pandas as pdimport numpy as npimport seaborn as snsfrom coinmetrics.api_client import CoinMetricsClientimport loggingimport matplotlib.pyplot as plt%matplotlib inline
# 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")exceptKeyError: 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.
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
Fig. 1 - 7 Day Price Change chart from State of the Market
# Get all assets that have a reference rate assets_refrate = client.catalog_asset_metrics_v2(metrics="ReferenceRateUSD").to_dataframe()assets_refrate[["metric","frequency","asset"]]
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.
# Retrieve Reference Ratedf_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 pricesdf_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 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....
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.
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()
Fig. 3 - Binance order book depth from State of the Market
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.
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()
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.
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
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.
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:
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.
Fig. 5 - Bitcoin perpetual futures funding rates from State of the Market
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.
Fig. 6 - Bitcoin futures basis from State of the Market
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.
Fig. 7 - Bitcoin perpetual futures liquidations from State of the Market
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.