Exploring the Binance API in Python: The Order Book

·

In this tutorial, we'll dive into fetching and analyzing live order book data from Binance using Python. We'll interact directly with Binance's official API, process the data with pandas, and visualize it using matplotlib and seaborn.


Prerequisites

To follow along, ensure you have these Python libraries installed:

import requests
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

Fetching Order Book Data

We'll start by making a GET request to Binance's /depth endpoint for the ETHBUSD trading pair:

r = requests.get("https://api.binance.com/api/v3/depth",
                 params=dict(symbol="ETHBUSD"))
results = r.json()

Processing the Data

Loading Bids and Asks into DataFrames

We'll organize the bids (buy orders) and asks (sell orders) into separate pandas DataFrames:

frames = {
    side: pd.DataFrame(data=results[side], columns=["price", "quantity"], dtype=float)
    for side in ["bids", "asks"]
}

Combining DataFrames

Next, we'll concatenate these DataFrames for easier analysis:

frames_list = [frames[side].assign(side=side) for side in frames]
data = pd.concat(frames_list, axis="index", ignore_index=True, sort=True)

Analyzing Price Levels

Let's examine statistical summaries of the bid and ask prices:

price_summary = data.groupby("side").price.describe()
sidecountmeanstdmin25%50%75%max
asks1001057.860.6961461056.641057.21057.911058.491059.04
bids1001055.060.8323851053.71054.41054.851055.821056.58

Note: Binance's API provides only the top 100 bids and asks.


Understanding the Top of the Book

The top of the book represents the most competitive prices:

>>> frames["bids"].price.max()
1056.58
>>> frames["asks"].price.min()
1056.64

The difference between these values is the _bid-ask spread_.

We can also fetch this information directly:

r = requests.get("https://api.binance.com/api/v3/ticker/bookTicker", 
                 params=dict(symbol="ETHBUSD"))
book_top = r.json()
ETHBUSD
bidPrice1056.58
bidQty7.555
askPrice1056.64
askQty7.43152

👉 Learn more about Binance's API structure


Visualizing the Order Book

Scatter Plot

Show all order book entries with price vs. quantity:

fig, ax = plt.subplots()
sns.scatterplot(x="price", y="quantity", hue="side", data=data, ax=ax)
ax.set_xlabel("Price")
ax.set_ylabel("Quantity")
plt.show()

Histogram Plot

Compress information into price point frequencies:

fig, ax = plt.subplots()
sns.histplot(x="price", hue="side", binwidth=0.5, data=data, ax=ax)
plt.show()

Weighted Histogram

Account for order quantities:

fig, ax = plt.subplots()
sns.histplot(x="price", weights="quantity", hue="side", binwidth=0.5, data=data, ax=ax)
plt.show()

Depth Chart (ECDF Plot)

Create the classic depth chart visualization:

fig, ax = plt.subplots()
sns.ecdfplot(x="price", weights="quantity", stat="count", complementary=True, data=frames["bids"], ax=ax)
sns.ecdfplot(x="price", weights="quantity", stat="count", data=frames["asks"], ax=ax)
plt.show()

👉 Discover advanced trading strategies


FAQ

What is an order book?

An order book is a real-time list of buy and sell orders for a specific asset, organized by price level.

How many price levels does Binance's API return?

Binance returns the top 100 bids and asks for each trading pair.

What's the difference between bids and asks?

Bids represent buy orders (demand), while asks represent sell orders (supply). The market price forms where these meet.

Why use weighted visualizations?

Weighting by quantity gives a more accurate picture of market depth compared to just counting orders.

How often does the order book update?

Binance's order book updates continuously as new orders are placed, modified, or filled.


This tutorial covered essential techniques for working with Binance's order book API. For more advanced trading tools, check out python-binance, an excellent third-party library.

👉 Explore more crypto trading resources