Real-time Limit Order Book from Kraken on Jupyter Notebook

Sarp Nalcin
3 min readDec 5, 2022

--

Photo by Kelly Sikkema on Unsplash

A limit order book or LOB, in short, is a list of buy and sell orders of a specific security or financial product organized by price levels. Most electronic exchanges, stock or cryptocurrency, use LOB to match orders. Although for newcomers it may look intimidating, in this article I will demystify a typical LOB you would see in exchanges. Most importantly, I will share with you the code to extract a real-time limit order book on your Jupyter Notebook from Kraken, a major cryptocurrency exchange.

Quick Intro to Limit Order Book

A standard LOB consists of the following:

  • Bid price: The buyer is ready to buy the instrument at this price
  • Ask/Offer price: The seller is ready to sell the instrument at this price
  • Bid size: The size that the buyer wants to buy at the bid price
  • Ask/Offer size: The size that the seller wants to sell at the ask price

For the sake of this article, the terminology above is sufficient to grasp the organization in LOB. If a buyer wants to buy for a higher price (bid price), then he has priority over the buyer who is willing to buy for a lower price. Likewise, if a seller wants to sell for a lower price (ask price), then he has priority over the seller who sells for a higher price. Therefore, bid prices are ordered in descending and ask prices are ordered in ascending. The highest bid is the best bid and the lowest ask is the best ask. To illustrate it, you can check the visual below.

Image 1: Illustration of a limit order book

Level 2 Order book: Instead of visualizing each order separately, the orders are aggregated on price levels as demonstrated in the above image. This is the most common order book type and it is named Level 2 Order Book.

Bid-Ask Spread: It is the difference between the best ask and the best bid. The small the Bid-Ask Spread is, the more efficient the market is.

Let’s get in the code!

You can access the code from the Github page below:

Once you are on the page, follow the steps and watch the real-time LOB flowing in your notebook.

  1. Place the krakenwsbook.py file in the same folder as the Jupyter notebook you are working on
  2. Run the following one line in a shell in your notebook: %run ./krakenwsbook.py BTC/USD 10
  3. 10 highest Bids and 10 lowest Asks for BTC/USD pair with their sizes in parentheses will be presented at every second!
  4. To stop the execution, interrupt the kernel
  5. Modify the one line of code in your choice of pair and the number of price levels you want to see extracting
  6. Run the modified one-line again to have the real-time LOB!

Here is a snapshot of the output:

I hope you enjoyed reading this article. If you like, do not forget to clap from the button below!

References:

Image 1: https://www.reddit.com/r/algotrading/comments/pll069/limit_order_book_or_ledger/

--

--