How to retrieve and analyze crypto order book data using Python and a cryptocurrency API
Tags: tutorial, api, cryptocurrency, python
Published: 2023-11-27 13:09:17


In this guide, we'll explore how to access and examine order book data for cryptocurrencies by utilizing Python and CoinAPI.

## Agenda🔥:

- Fundamentals of crypto order books: grasping the essentials of cryptocurrency trading order books.
- Data retrieval: employing Python and CoinAPI for acquiring real-time crypto order book information.
- Data interpretation: gleaning insights from cryptocurrency API information.
- Data visualization: utilizing Python's [Matplotlib](https://matplotlib.org/) for visualizing order book information.
- Metrics calculation: deriving important metrics from cryptocurrency API data.

## CoinAPI: Your go-to source for comprehensive cryptocurrency data 🚀

Before we jump into the tutorial, it's important to highlight what CoinAPI brings to the table. CoinAPI is a robust resource for a vast array of financial data, offering both real-time and historical information from numerous exchanges.

If you need in-depth trading data, OHLCV (Open, High, Low, Close, Volume) stats, or specific event details, CoinAPI has you covered. It stands out by providing detailed crypto order book data, positioning itself as a top-tier crypto API choice.

Moreover, CoinAPI's compatibility with various data delivery methods, such as REST and WebSocket, adds to its flexibility. This makes it an ideal tool for developers who are working on trading algorithms or visualizations of crypto market data.

## Let's Begin 🚀

Utilizing the powerful features of CoinAPI, an advanced cryptocurrency API, in combination with Python's strengths in data analysis and statistics, allows us to deeply explore the complexities of the cryptocurrency market.


This guide will take you through the process of retrieving and examining crypto order book data in real-time, making full use of the extensive data available through the cryptocurrency API.

## Setting up the API request

To fetch real-time order book data, you'll first need an API key from the [CoinAPI website](https://www.coinapi.io/). Once you have it, you can proceed to retrieve the data using Python.

## Fetching the data

```
import requests
import json

API_KEY = "YOUR_API_KEY_HERE"
url = f"https://rest.coinapi.io/v1/orderbooks/current?symbol=KRAKEN_SPOT_BTC_USD&apikey={API_KEY}"

response = requests.get(url)

if response.status_code == 200:
    # The request was successful
    data = response.json()
    
    # Save the data to a file
    with open("order-books-kraken-spot-btc-usd.json", "w") as file:
        json.dump(data, file, indent=4)
    print("Data saved to order-books-kraken-spot-btc-usd.json")
else:
    # Handle error cases
    print(f"Error: Status code {response.status_code}")
    print(response.text)
```

## Response

```
{
    "symbol_id": "KRAKEN_SPOT_BTC_USD",
    "time_exchange": "2023-11-24T08:26:46.6928657Z",
    "time_coinapi": "2023-11-24T08:26:46.6928657Z",
    "asks": [
        {
            "price": 37549.1,
            "size": 19.23618731
        },
        {
            "price": 37549.9,
            "size": 0.08242079
        },
        /// other entries omitted for brevity
    ],
    "bids": [
        {
            "price": 37549.0,
            "size": 0.136004
        },
        {
            "price": 37545.1,
        }
        /// other entries omitted for brevity
    ]
}
```
## Data Analysis and Metrics

Once the data is retrieved, the subsequent phase is its analysis using `Python`.

The data you gather usually reflects a momentary picture of the market's buy and sell orders. It includes two principal elements: bids and asks. Bids indicate the prices buyers are prepared to pay for an asset, whereas asks show the prices sellers are ready to accept. The gap between the top bid and the bottom ask is known as the `spread`.

Here is a comprehensive list of common metrics and analytical procedures:

- `Order Book Depth` - visualize the liquidity available at various price levels.
- `Order Imbalance` - analyze the disparity between bids and asks to gain insights into market sentiment.
- `Price Levels` - identify significant price levels characterized by substantial volumes of bids or asks.
- `Market Spread` - compute the current bid-ask spread as an indicator of market liquidity.

## Order book depth visualization

In this `Python` code, we demonstrate how to visualize the order book depth of a cryptocurrency trading pair using `Matplotlib`.

```
import json
import matplotlib.pyplot as plt

# Function to read order book data from a JSON
def read_order_book_data(file_path):
    with open(file_path, 'r') as file:
        order_book_data = json.load(file)
    return order_book_data

file_path = 'order-books-kraken-spot-btc-usd.json'

# Read order book data from the file we've obtained in the previous step
order_book_data = read_order_book_data(file_path)

# Function to visualize order book depth chart
def visualize_order_book_depth(order_book_data):
    bids = order_book_data["bids"]
    asks = order_book_data["asks"]
    
    bid_prices = [entry["price"] for entry in bids]
    bid_sizes = [entry["size"] for entry in bids]
    
    ask_prices = [entry["price"] for entry in asks]
    ask_sizes = [entry["size"] for entry in asks]
    
    plt.figure(figsize=(10, 6))
    plt.plot(bid_prices, bid_sizes, label="Bids (buyers)", color="green")
    plt.plot(ask_prices, ask_sizes, label="Asks (sellers)", color="red")
    plt.xlabel("Price")
    plt.ylabel("Size")
    plt.title("Order Book Depth")
    plt.legend()
    plt.show()

# Visualize the order book depth
visualize_order_book_depth(order_book_data)
```
The following visualization is the result of the `Python` script demonstrated above.

![Cryptocurrency order book data from CoinAPI](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dif27k5yn08sut3jnqkd.jpg)

Order Book depth visualization:

- is a measure of the quantity of buy and sell orders available for a particular financial asset
- it provides insight into market liquidity and the willingness of traders to buy or sell at different prices
- may be used for trading decisions, as it reveals potential price trends

## Order imbalance, price levels, market spread

In this `Python` code, we explore `order imbalance`, `significant bids & asks`, and `market spread` metrics for a `BTC/USD` trading pair.

```
import json

# Function to read order book data from a JSON
def read_order_book_data(file_path):
    with open(file_path, 'r') as file:
        order_book_data = json.load(file)
    return order_book_data

file_path = 'order-books-kraken-spot-btc-usd.json'

# Read order book data from the file we've obtained in the previous step
order_book_data = read_order_book_data(file_path)

# Function to calculate order imbalance
def calculate_order_imbalance(order_book_data):
    bids = sum(entry["size"] for entry in order_book_data["bids"])
    asks = sum(entry["size"] for entry in order_book_data["asks"])

    order_imbalance = (bids - asks) / (bids + asks)
    return order_imbalance

# Function to identify significant price levels
def identify_significant_price_levels(order_book_data, threshold=50):
    bids = order_book_data["bids"]
    asks = order_book_data["asks"]
    
    significant_bids = [entry for entry in bids if entry["size"] > threshold]
    significant_asks = [entry for entry in asks if entry["size"] > threshold]
    return significant_bids, significant_asks

# Function to calculate market spread
def calculate_market_spread(order_book_data):
    best_bid = order_book_data["bids"][0]["price"]
    best_ask = order_book_data["asks"][0]["price"]
    
    spread = best_ask - best_bid
    return spread

# Common metrics calculation
order_imbalance = calculate_order_imbalance(order_book_data)
significant_price_threshold = 20
significant_bids, significant_asks = identify_significant_price_levels(order_book_data, significant_price_threshold)
spread = calculate_market_spread(order_book_data)

print("******************************")
print("Order Imbalance:", order_imbalance)
print("***************************")
print("Significant Bids:", significant_bids)
print("***************************")
print("Significant Asks:", significant_asks)
print("***************************")
print("Market Spread:", spread)
print("***************************")
```

## Result

```
> ******************************
> Order Imbalance: -0.012400502029283922
> ***************************
> Significant Bids: [{'price': 37440.7, 'size': 24.73909889}, {'price': 36451.0, 'size': 25.0}]
> ***************************
> Significant Asks: [{'price': 37749.0, 'size': 25.0}, {'price': 37840.0, 'size': 24.08119208}, {'price': 38000.0, 'size': 29.60579175}, {'price': 39000.0, 'size': 21.75395535}, {'price': 40000.0, 'size': 58.28620718}]
> ***************************
> Market Spread: 0.09999999999854481
> ***************************
```

## Calculated metrics:

- `order_imbalance` - it measures the difference between the total volume of buy orders and sell orders. It provides insights into the overall market sentiment by indicating whether there is an excess of buying or selling interest.
- `significant_price_threshold` is a predetermined value (set to 20 in this case) used to identify price levels in the order book that are considered significant. It helps traders focus on specific price points that may have a more substantial impact on the market.
- `significant_bids and significant_asks` are lists of price levels derived from the order book data that meet or exceed the significant_price_threshold. These levels are typically associated with higher trading activity and may be seen as key support and resistance levels.
- `spread` is a metric that calculates the difference between the best bid and best ask prices. It represents the cost of executing a market order and is a fundamental factor for traders to consider when entering or exiting positions.

## Summary

This guide has provided you with essential skills and tools to retrieve and analyze cryptocurrency order book data using Python and CoinAPI. You've acquired the ability to access up-to-the-minute order book data, create visual representations of order book depth, and compute key trading metrics.

With this newfound knowledge, you're now better equipped to delve into the crypto markets, making more educated trading choices and crafting strategies based on solid data.

Keep in mind that the crypto market is ever-changing, so constant vigilance and analysis are key to staying on top of this vibrant and fast-paced sector.

Wishing you successful trading! 🚀📈💰

Thank you for reading!

The source code for this tutorial is available [here](https://docs.coinapi.io/how-to-guides/python-based-retrieval-and-analysis-of-crypto-order-book-data-through-a-cryptocurrency-API)