Explore and Visualize Crypto Order Book Snapshots

Crypto Chassis
Open Crypto Trading Initiative
3 min readSep 15, 2023
Photo by Joshua Earle on Unsplash

Greetings, Ladies and Gentlemen! Hope you are doing well. Based on our community’s feedback, in this article, we will explore how to stream real-time order book snapshots through cryptochassis’s ccapi and visualize an individual order book snapshot using Python. ccapi is a header-only C++ library for interacting with crypto exchanges. Bindings for Python, Java, C#, Go, and Javascript are provided. In this example, we will use the library’s Python bindings and leverage the ample choices of Python’s data visualization packages. The full example is located at https://github.com/crypto-chassis/ccapi/blob/v6.4.4/binding/python/example/data_visualization/main.py.

We will first have to build the ccapi Python bindings by following the instructions in https://github.com/crypto-chassis/ccapi/tree/v6.4.4#non-c. From an end user’s perspective, the process is super simple and boils down to running just two commands:

cmake -DBUILD_PYTHON=ON -DBUILD_VERSION=1.0.0 ..
cmake --build .

After the commands complete, we should be able to import ccapi successfully in the Python interactive console. At this moment, we are ready to use ccapi and the usage is also super simple:

option = SessionOptions()
config = SessionConfigs()
session = Session(option, config)
exchange = "okx"
instrument = "BTC-USDT"
subscription = Subscription(exchange, instrument, "MARKET_DEPTH", "MARKET_DEPTH_MAX=400&CONFLATE_INTERVAL_MILLISECONDS=100")
session.subscribe(subscription)

The only explanation needed is for “MARKET_DEPTH_MAX=400&CONFLATE_INTERVAL_MILLISECONDS=100” which means that we’d like to subscribe to 400 levels of order book data with a data push frequency of every 100 milliseconds. Our library ccapi does all the heavy-lifting work behind the scene. The end user receives the real-time data as Eventsand can choose either to process those Events immediately or in small batches (https://github.com/crypto-chassis/ccapi/tree/v6.4.4#handle-events-in-immediate-vs-batching-mode). For the purpose of data visualization, we can process the Events in small batches via “eventList = session.getEventQueue().purge()”:

while True:
bids = {"price": [], "size": []}
asks = {"price": [], "size": []}
eventList = session.getEventQueue().purge()
if eventList:
event = eventList[-1]
if event.getType() == Event.Type_SUBSCRIPTION_DATA:
for message in event.getMessageList():
for element in message.getElementList():
elementNameValueMap = element.getNameValueMap()
for name, value in elementNameValueMap.items():
if name == "BID_PRICE":
bids["price"].append(float(value))
if name == "BID_SIZE":
bids["size"].append(float(value))
if name == "ASK_PRICE":
asks["price"].append(float(value))
if name == "ASK_SIZE":
asks["size"].append(float(value))
ax.clear()
ax.set_title(f"{instrument} Order Book On {exchange.title()} at {message.getTimeISO()}")
ax.set_xlabel("Price")
ax.set_ylabel("Amount")
sns.ecdfplot(
x="price",
weights="size",
legend=False,
stat="count",
complementary=True,
data={"price": bids["price"], "size": bids["size"]},
ax=ax,
color="g",
)
sns.ecdfplot(x="price", weights="size", legend=False, stat="count", data={"price": asks["price"], "size": asks["size"]}, ax=ax, color="r")
plt.pause(0.1)

It is very straightforward to extract the data from the Eventsto build the bids and the asks as shown in the code, and directly feed those as the arguments for seaborn’s ECDF plot (https://seaborn.pydata.org/generated/seaborn.ecdfplot.html). Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. Its ECDF plot is exactly what is needed to produce a classical order book depth chart via just one line of code “ecdfplot(…)”. The depth chart is the most common visualization of the order book snapshots. It takes a single state of an order book and plots the cumulative amount, i.e. the cumulative quote quantity (in this example, the cumulative USDT quantity), against the price level for all bids and asks. The visualization illustrates supply and demand: the green line represents buy-side and the red line represents sell-side.

Order Book Depth Chart

The technique that we use for ECDF is to set “x” as “price”, “weights” as “size”, and “stats” as “count”.

sns.ecdfplot(
x="price",
weights="size",
legend=False,
stat="count",
complementary=True,
data={"price": bids["price"], "size": bids["size"]},
ax=ax,
color="g",
)

And we use “plt.pause(0.1)” to refresh the plot every 0.1 second so that we can see an animation of the evolving order book states.

Super simple! If you are interested in our work or collaborating with us, join us on Discord: https://discord.gg/b5EKcp9s8T and find us on Github: https://github.com/crypto-chassis/ccapi 🎉. We specialize in market data collection, high speed trading system, infrastructure optimization, and proprietary market making.

Disclaimer: This is an educational article rather than investment/financial advice.

--

--