Skip to main content

Orderbook

License Python PyPi coverage-lines coverage-functions

A fast L2/L3 orderbook data structure, in C, for Python

Installation

Python 3.12+ supported. In general, uv is preferred and will be utilized throughout this document.

To add it to a project uv add order-book or, to install it into an environment directly, uv pip install order-book

Installing from a checkout of this repository: uv pip install . (note a C compiler is required).

Basic Usage

from decimal import Decimal

import requests
from order_book import OrderBook

ob = OrderBook()

# get some orderbook data
data = requests.get("https://api.exchange.coinbase.com/products/BTC-USD/book?level=2").json()

ob.bids = {Decimal(price): size for price, size, _ in data['bids']}
ob.asks = {Decimal(price): size for price, size, _ in data['asks']}

# OR

for side in data:
    # there is additional data we need to ignore
    if side in {'bids', 'asks'}:
        ob[side] = {Decimal(price): size for price, size, _ in data[side]}


# Data is accessible by .index(), which returns a tuple of (price, size) at that level in the book
price, size = ob.bids.index(0)
print(f"Best bid price: {price} size: {size}")

price, size = ob.asks.index(0)
print(f"Best ask price: {price} size: {size}")

print(f"The spread is {ob.asks.index(0)[0] - ob.bids.index(0)[0]}\n\n")

# Negative indexes work as well, so the worst bid/ask is index -1
print(f"Worst bid: {ob.bids.index(-1)}")

# Data is accessible via iteration
# Note: bids/asks are iterators
print("Top 10 bids")
for count, price in enumerate(ob.bids):
    if count == 10:
        break
    print(f"Price: {price} Size: {ob.bids[price]}")


print("\n\nTop 10 asks")
for count, price in enumerate(ob.asks):
    if count == 10:
        break
    print(f"Price: {price} Size: {ob.asks[price]}")


# Membership tests and len() work as expected
print(f"\nBest bid still in book: {ob.bids.index(0)[0] in ob.bids}")
print(f"Bid levels: {len(ob.bids)}, ask levels: {len(ob.asks)}, both sides: {len(ob)}")


# Data can be exported to a sorted dictionary
# In Python3.7+ dictionaries remain in insertion ordering. The
# dict returned by .to_dict() has had its keys inserted in sorted order
print("\n\nTop 3 asks, as a dictionary")
print(dict(list(ob.asks.to_dict().items())[:3]))


# Data can also be exported as an ordered list
# .to_list() returns a list of (price, size) tuples
print("\nTop 5 Asks")
print(ob.asks.to_list()[:5])
print("\nTop 5 Bids")
print(ob.bids.to_list()[:5])


# .keys() returns the sorted prices as a tuple
print("\nTop 5 ask prices")
print(ob.asks.keys()[:5])


# .items() returns an iterator over price, size pairs
print("\nTop 5 asks as (price, size) pairs")
for count, (price, size) in enumerate(ob.asks.items()):
    if count == 5:
        break
    print(f"Price: {price} Size: {size}")


# The entire book can be exported at once. The keys are 'bid' and 'ask' (singular)
book = ob.to_dict()
print(f"\nto_dict() keys: {list(book)}")

Both sides accept any of bid, bids, BID, BIDS (and the ask equivalents), as attributes or as keys:

from order_book import OrderBook

ob = OrderBook()

ob.bids[100] = "1.5"     # attribute access
ob['bids'][99] = "2.0"   # key access
ob['BID'][98] = "0.5"    # case does not matter

print(ob.bid.to_list())  # [(100, '1.5'), (99, '2.0'), (98, '0.5')]

# assigning a dict to a side replaces that side wholesale
ob.asks = {101: "1.0", 102: "3.0"}
print(ob.asks.to_list())  # [(101, '1.0'), (102, '3.0')]

# levels are removed with del
del ob.asks[101]
print(ob.asks.to_list())  # [(102, '3.0')]

Max Depth

max_depth limits how many levels are visible. len(), iteration, keys(), index(), to_dict() and to_list() all respect it.

from order_book import OrderBook

ob = OrderBook(max_depth=3)
ob.bids = {price: price for price in range(10)}

print(len(ob.bids))        # 3
print(ob.bids.to_list())   # [(9, 9), (8, 8), (7, 7)]
print(ob.max_depth)        # 3

By default the levels beyond max_depth are still retained internally, they are just hidden. Pass max_depth_strict=True to have them deleted as the book is updated, which caps memory use but means out-of-depth levels can no longer be accessed:

from order_book import OrderBook

ob = OrderBook(max_depth=3, max_depth_strict=True)
for price in range(10):
    ob.bids[price] = price

print(ob.bids.to_list())   # [(9, 9), (8, 8), (7, 7)]

try:
    del ob.bids[0]         # level 0 was dropped, not merely hidden
except KeyError:
    print("level 0 is gone")

Checksums

Several exchanges publish a CRC32 checksum of the top of book so clients can detect a desynchronized book. Construct the book with checksum_format set to the exchange, then compare ob.checksum() against the value the exchange sent.

Supported formats: KRAKEN, OKX/OKCOIN, BITGET, and BITFINEX.

from decimal import Decimal

from order_book import OrderBook

ob = OrderBook(checksum_format='KRAKEN')

ob.bids = {Decimal(f"{100 - i}.{i:02d}"): Decimal(f"{i + 1}.5") for i in range(10)}
ob.asks = {Decimal(f"{101 + i}.{i:02d}"): Decimal(f"{i + 1}.5") for i in range(10)}

print(ob.checksum())

Type conversion

to_dict() on either an OrderBook or a SortedDict accepts from_type and to_type keyword arguments, which convert keys and values as the dictionary is built. from_type restricts the conversion to values of that type; omit it to convert everything.

from order_book import OrderBook

ob = OrderBook()
ob.bids = {'1.1': 2, '3.3': 4}
ob.asks = {'5.5': 6, '7.7': 8}

print(ob.to_dict(from_type=str, to_type=float))
# {'bid': {3.3: 4, 1.1: 2}, 'ask': {5.5: 6, 7.7: 8}}
# note the bid side is in descending order, as always

API Summary

OrderBook(max_depth=0, max_depth_strict=False, checksum_format=None)

Member Description
.bids / .bid / .asks / .ask the SortedDict for that side; assigning a dict replaces the side
ob[key] same sides, by key. bid, bids, ask, asks, any case
.max_depth the configured max depth (read only)
.to_dict(from_type=None, to_type=None) {'bid': {...}, 'ask': {...}}
.checksum() CRC32 checksum in the configured exchange's format
len(ob) total number of levels across both sides

SortedDict(data=None, ordering='ASC', max_depth=0, truncate=False)

Member Description
.keys() tuple of keys in sorted order
.index(n) (key, value) tuple at position n; negative indexes supported
.to_dict(from_type=None, to_type=None) dict with keys inserted in sorted order
.to_list() list of (key, value) tuples in sorted order
.truncate() drop everything past max_depth
sd[key], sd[key] = v, del sd[key], key in sd, len(sd), iteration as expected; iteration yields keys in sorted order

Main Features

  • Sides maintained in correct order
  • Can perform orderbook checksums
  • Supports max depth and depth truncation

Running code coverage

The script coverage.sh will compile the source using the -coverage CFLAG, run the unit tests, and build a coverage report in HTML. It manages its own environment via uv, so it can be run directly.

Note that it rebuilds .venv with an instrumented, unoptimized-for-timing build, so re-run uv pip install ".[tests]" afterwards to get back to a normal development environment.

Performance

perf/performance_test.py replays realistic exchange activity against real BTC-USD order books captured from Coinbase and cached in perf/data/, so runs are reproducible and need no network access. The event streams are generated deterministically from a seed and modeled on how feeds actually behave: 90% of activity clusters near the top of book and the rest spreads across the whole window, L2 traffic is mostly size updates with level adds and deletes held in balance so depth stays stationary, L3 traffic is order-level against the book's real resting orders with adds and cancels likewise balanced.

uv run perf/performance_test.py                       # everything
uv run perf/performance_test.py --scenario l3         # one scenario
uv run perf/performance_test.py --ops 1000000 --depth 5000 --seed 7
uv run perf/capture.py                                # refresh the cached snapshots

Numbers below are from Python 3.14, a replay window of the top 2,000 levels per side, a top-of-book read every 10 events, 200,000 events (20,000 for the pure Python book, which only degrades further the longer it runs). Throughput is the median of 5 passes.

L2 replay

library ns/event throughput
order_book 137 7.3M events/s
sortedcontainers 314 3.2M events/s
pure python 5,676 176K events/s

L3 replay

library ns/event throughput
order_book 190 5.3M events/s
sortedcontainers 416 2.4M events/s
pure python 2,839 352K events/s

Snapshot load

library time
order_book 3.8 ms
sortedcontainers 25.4 ms
pure python 5.7 ms

Exchange checksums L2 books: KRAKEN 1.9 µs, OKX 4.6 µs, BITGET 4.3 µs, BITFINEX 4.3 µs per checksum() L3 books: Bitfinex 5.3 µs per checksum()

Changelog

1.0.2

  • Feature: Bitfinex checksum support for L3 books
  • Bugfix: symbol collision between orderbook's crc32 and zlib's

1.0.1 (2026-08-13)

  • Feature: Bitfinex checksum support

1.0.0 (2026-08-07)

  • Feature: issue #14 .items() iterator on book sides
  • Update: Add more unit tests to increase code coverage
  • Bugfix: reference / memory leaks
  • Bugfix: .index() not properly respecting max_depth
  • Bugfix: failed delete no longer invalidates the cached keys
  • Bugfix: issue #31 sortedDict iterator revamp
  • Performance: change setitem to only do one lookup vs two (remove pydict_contains lookup)
  • Performance: checksum now requires hardware support
  • Performance: simplify side lookups
  • Performance: to_dict special path when no type conversion needed
  • Performance: incremental key cache for small changes between reads

0.7.0 (2026-08-05)

  • Update: Modernize project (uv, pyproject.toml, etc)
  • Update: Update readme, tests, examples, etc
  • Update: revamp wheel building

0.6.1 (2024-04-22)

  • Update: to_list's behavior matches that of to_dict (respects max_depth, if set).
  • Update: resolve build warnings on some compilers.

0.6.0 (2022-10-19)

  • Update: Drop support for python 3.7
  • Feature: to_list method
  • Bugfix: Initialize iterator correctly

0.5.0 (2022-08-23)

  • Bugfix: fix segmentation fault when calculating checksum on empty orderbook
  • Bugfix: fix missing reference decrement
  • Performance: Improvement to marking dirty keys

0.4.3 (2022-05-29)

  • Bugfix: handle scientific notation of small values in Kraken checksum
  • Update: calculate Kraken checksum on order books less than 10 levels deep
  • Bugfix: fix occasional incorrect checksums for OKX, FTX and Bitget

0.4.2 (2022-04-17)

  • Update: OKEx renamed OKX (for checksum validation)
  • Feature: Add support for orderbook checksums with Bitget

0.4.1 (2021-10-12)

  • Bugfix: unnecessary reference counting prevented sorted dictionaries from being deallocated
  • Bugfix: setting ordering on a sorted dict before checking that it was created successfully

0.4.0 (2021-09-16)

  • Feature: changes to code and setup.py to enable compiling on windows
  • Feature: add from_type/to_type kwargs to the to_dict methods, allowing for type conversion when creating the dictionary

0.3.2 (2021-09-04)

  • Bugfix: depth was incorrectly ignored when converting sorteddict to python dict

0.3.1 (2021-09-01)

  • Bugfix: truncate and max_depth not being passed from orderbook to sorteddict object correctly
  • Feature: let checksum_format kwarg be set to None

0.3.0 (2021-07-16)

  • Update classifiers to indicate this projects only supports MacOS/Linux
  • Bugfix: Using less than the minimum number of levels for a checksum with Kraken not raising error correctly
  • Update: add del examples to test code

0.2.1 (2021-03-29)

  • Bugfix: Invalid deallocation of python object

0.2.0 (2021-03-12)

  • Feature: Add branch prediction hints around error handling code
  • Bugfix: Fix regression from adding branch predictors
  • Bugfix: Fix error corner case when iterating twice on an empty dataset
  • Feature: Add contains function for membership test
  • Bugfix: Fix issues around storing L3 data
  • Feature: Enhance testing, add in L3 book test cases

0.1.1 (2021-02-12)

  • Feature: Checksum support for orderbooks
  • Feature: FTX checksum support
  • Feature: Kraken checksum support
  • Feature: OkEX/OKCoin checksum support
  • Perf: Use CRC32 table to improve performance of checksum code

0.1.0 (2021-01-18)

  • Minor: Use enums to make code more readable
  • Bugfix: Add manifest file to ensure headers and changes file are included in sdist builds
  • Feature: Add support for max depth and depth truncation

0.0.2 (2020-12-27)

  • Bugfix: Fix sorted dictionary arg parsing
  • Feature: Coverage report generation for C library
  • Bugfix: Fix reference counting in index method in SortedDict
  • Feature: New unit tests to improve SortedDict coverage
  • Feature: Modularize files
  • Feature: Add ability to set bids/asks to dictionaries via attributes or [ ]
  • Docs: Update README with simple usage example

0.0.1 (2020-12-26)

  • Initial Release

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

order_book-1.0.2.tar.gz (50.2 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

order_book-1.0.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl (121.8 kB view details)

Uploaded CPython 3.14manylinux: glibc 2.17+ x86-64manylinux: glibc 2.28+ x86-64

order_book-1.0.2-cp314-cp314-macosx_26_0_arm64.whl (37.8 kB view details)

Uploaded CPython 3.14macOS 26.0+ ARM64

order_book-1.0.2-cp314-cp314-macosx_11_0_arm64.whl (37.8 kB view details)

Uploaded CPython 3.14macOS 11.0+ ARM64

order_book-1.0.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl (122.8 kB view details)

Uploaded CPython 3.13manylinux: glibc 2.17+ x86-64manylinux: glibc 2.28+ x86-64

order_book-1.0.2-cp313-cp313-macosx_11_0_arm64.whl (37.6 kB view details)

Uploaded CPython 3.13macOS 11.0+ ARM64

order_book-1.0.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl (122.6 kB view details)

Uploaded CPython 3.12manylinux: glibc 2.17+ x86-64manylinux: glibc 2.28+ x86-64

order_book-1.0.2-cp312-cp312-macosx_11_0_arm64.whl (37.6 kB view details)

Uploaded CPython 3.12macOS 11.0+ ARM64

File details

Details for the file order_book-1.0.2.tar.gz.

File metadata

  • Download URL: order_book-1.0.2.tar.gz
  • Upload date:
  • Size: 50.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.14.7

File hashes

Hashes for order_book-1.0.2.tar.gz
Algorithm Hash digest
SHA256 95ebdd0c676c03f3937ed25292eb74819ac3ab9be5bb0dd083300e33cf456fb8
MD5 25600a6686ae568f791c381164e57d80
BLAKE2b-256 390bad3087b80381eb34047f0796bcf5e95e29a75fe98fd3f5820bd8f2d14704

See more details on using hashes here.

File details

Details for the file order_book-1.0.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for order_book-1.0.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 49f6a82cdc7947cc5712317b322429ef322c139b905b8619b53837d7b0f184b3
MD5 9c629b4622331c28c13359ea7b84f48f
BLAKE2b-256 9efba7d6eb0959aece9b2c425c4db7445e31bc36c6106ef2be6641ce2ddde237

See more details on using hashes here.

File details

Details for the file order_book-1.0.2-cp314-cp314-macosx_26_0_arm64.whl.

File metadata

File hashes

Hashes for order_book-1.0.2-cp314-cp314-macosx_26_0_arm64.whl
Algorithm Hash digest
SHA256 ce1c4019e063d48cba0cb138601b6a83e056648e5277a027fb0e71a8f0ba6082
MD5 fd322880e48496a479e4a38b6857a217
BLAKE2b-256 ef55445e8ab60197a6329e1d24c2154f5bc4ad9c2788da96bedbc69411d12246

See more details on using hashes here.

File details

Details for the file order_book-1.0.2-cp314-cp314-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for order_book-1.0.2-cp314-cp314-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 5373b2f1ab71baefaf1eabf803fa8edf46d821a02fc9e006dcc270733de42039
MD5 96e20ac92a7ecc0a97a8ae564c1dda5d
BLAKE2b-256 8380a9213ecf266e229086b8739bea2e324858f42dcb19654df1e958dbfc2531

See more details on using hashes here.

File details

Details for the file order_book-1.0.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for order_book-1.0.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 584847b7e34c390d696e72447d037a972b123e2f88dbe77a910273413725955f
MD5 faec5a360ee401a4317fe847f0d5aa48
BLAKE2b-256 6bb5df8f296fdbc009652ded67de5f30e2c0ae44c7abce83a491dd0024a5d1d0

See more details on using hashes here.

File details

Details for the file order_book-1.0.2-cp313-cp313-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for order_book-1.0.2-cp313-cp313-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 a696b6fe8cd224f0c323f1a665b0cf4124d3ec60bf11ca5d475b09d7be617199
MD5 59219728cfbfb1b0d5f85fe6f21be0c3
BLAKE2b-256 e6966818e9ca8a0a9dcc65a2256ef4fb9bf532624373eb3496723bf7c4715caf

See more details on using hashes here.

File details

Details for the file order_book-1.0.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for order_book-1.0.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 bfc27e02286a49dbf9467ea3dc50bdc27fef067ac36ed772dc991fa829235abe
MD5 c2711be50371b25c680a0f72654c3c55
BLAKE2b-256 00752f330942548cf8cbfb69e8901671e88d9819beaf1a3671e7c0ac5cfcd34a

See more details on using hashes here.

File details

Details for the file order_book-1.0.2-cp312-cp312-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for order_book-1.0.2-cp312-cp312-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 b37116d27dbc36f27acda8edfe59e5a18d7494cb12a14ada81d82f5b96dbc78c
MD5 abdc0a958c9fbff5f997000410dff479
BLAKE2b-256 ce60bbda478f13c223b578a26791436a312ef589dd46a27ddaa458961543e790

See more details on using hashes here.

Release history Release notifications | RSS feed

This release

1.0.2 This release

8 files

1.0.1

7 files

1.0.0

6 files

0.7.0

7 files

0.6.1

5 files

0.6.0

7 files

0.5.0

7 files

0.4.3

7 files

0.4.2

7 files

0.4.1

7 files

0.4.0

7 files

0.3.2

7 files

0.3.1

7 files

0.3.0

7 files

0.2.1

10 files

0.2.0

9 files

0.1.1

10 files

0.1.0

10 files

0.0.2

10 files

0.0.1

2 files

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page