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 snsFetching 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()| side | count | mean | std | min | 25% | 50% | 75% | max |
|---|---|---|---|---|---|---|---|---|
| asks | 100 | 1057.86 | 0.696146 | 1056.64 | 1057.2 | 1057.91 | 1058.49 | 1059.04 |
| bids | 100 | 1055.06 | 0.832385 | 1053.7 | 1054.4 | 1054.85 | 1055.82 | 1056.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.64The 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 | |
|---|---|
| bidPrice | 1056.58 |
| bidQty | 7.555 |
| askPrice | 1056.64 |
| askQty | 7.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.