Available languages: [Python](https://databento.com/docs/examples/order-book/limit-order-book.python.md) · [C++](https://databento.com/docs/examples/order-book/limit-order-book.cpp.md) · [Rust](https://databento.com/docs/examples/order-book/limit-order-book.rust.md) · [HTTP](https://databento.com/docs/examples/order-book/limit-order-book.http.md) · [Raw](https://databento.com/docs/examples/order-book/limit-order-book.raw.md)

Source: https://databento.com/docs/examples/order-book/limit-order-book


# Limit order book construction

## Overview

This example demonstrates a complete limit order book implementation for Databento's MBO normalization schema.
It handles multiple instruments, here `GOOG` and `GOOGL`, across multiple venues that make up Databento Equities Basic:

- Investors Exchange (`IEXG`)
- NYSE Texas (`XCHI`)
- NYSE National (`XCIS`)
  We use `publisher_id` to disambiguate between venues.

While this example uses the Historical API, the same implementation can be used with live data by forwarding every `MBOMsg` to `market.Apply`.

> **See also**
>
> It's recommended to first start with the [Order tracking example](https://databento.com/docs/examples/order-book/order-tracking.md#order-events), which explains each event more in depth.

## Design

The `unordered_map` stores the price and side of each order for quick retrieval by ID.
Each side of the book is a `map` to balance random access of a price's level with retrieving the lowest and highest price level for determining the BBO.
The values in the book map are `vector`s of orders sorted by priority.

Investors Exchange and NYSE National only provide top-of-book information meaning their MBO data is [normalized differently](https://databento.com/docs/conventions/common-fields-enums-types.md#top-of-book-datasets).
Each **A**dd message indicates the new top-of-book and replaces all levels on that side.
Add messages with an `kUndefPrice` price indicate there's no depth for that side of the book.
The final special case comes when calculating the number of orders for a level since top-of-book updates don't correspond with individual orders.

## Example

```cpp
#include <algorithm>
#include <cstdint>
#include <databento/constants.hpp>  // dataset, kUndefPrice
#include <databento/datetime.hpp>   // ToIso8601, UnixNanos
#include <databento/dbn_store.hpp>
#include <databento/enums.hpp>  // Action, Side
#include <databento/flag_set.hpp>
#include <databento/historical.hpp>  // HistoricalBuilder
#include <databento/pretty.hpp>      // Px
#include <databento/record.hpp>      // BidAskPair, MboMsg, Record
#include <databento/symbol_map.hpp>  // TsSymbolMap
#include <fstream>
#include <iostream>
#include <iterator>
#include <map>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

namespace db = databento;

struct PriceLevel {
  int64_t price{db::kUndefPrice};
  uint32_t size{0};
  uint32_t count{0};

  bool IsEmpty() const { return price == db::kUndefPrice; }
  operator bool() const { return !IsEmpty(); }
};

std::ostream& operator<<(std::ostream& stream, const PriceLevel& level) {
  stream << level.size << " @ " << db::pretty::Px{level.price} << " | "
         << level.count << " order(s)";
  return stream;
}

class Book {
 public:
  std::pair<PriceLevel, PriceLevel> Bbo() const {
    return {GetBidLevel(), GetAskLevel()};
  }

  PriceLevel GetBidLevel(std::size_t idx = 0) const {
    if (bids_.size() > idx) {
      // Reverse iterator to get highest bid prices first
      auto level_it = bids_.rbegin();
      std::advance(level_it, idx);
      return GetPriceLevel(level_it->first, level_it->second);
    }
    return PriceLevel{};
  }

  PriceLevel GetAskLevel(std::size_t idx = 0) const {
    if (offers_.size() > idx) {
      auto level_it = offers_.begin();
      std::advance(level_it, idx);
      return GetPriceLevel(level_it->first, level_it->second);
    }
    return PriceLevel{};
  }

  PriceLevel GetBidLevelByPx(int64_t px) const {
    auto level_it = bids_.find(px);
    if (level_it == bids_.end()) {
      throw std::invalid_argument{"No bid level at " +
                                  db::pretty::PxToString(px)};
    }
    return GetPriceLevel(px, level_it->second);
  }

  PriceLevel GetAskLevelByPx(int64_t px) const {
    auto level_it = offers_.find(px);
    if (level_it == offers_.end()) {
      throw std::invalid_argument{"No ask level at " +
                                  db::pretty::PxToString(px)};
    }
    return GetPriceLevel(px, level_it->second);
  }

  const db::MboMsg& GetOrder(uint64_t order_id) {
    auto order_it = orders_by_id_.find(order_id);
    if (order_it == orders_by_id_.end()) {
      throw std::invalid_argument{"No order with ID " +
                                  std::to_string(order_id)};
    }
    auto& level = GetLevel(order_it->second.side, order_it->second.price);
    return *GetLevelOrder(level, order_id);
  }

  uint32_t GetQueuePos(uint64_t order_id) {
    auto order_it = orders_by_id_.find(order_id);
    if (order_it == orders_by_id_.end()) {
      throw std::invalid_argument{"No order with ID " +
                                  std::to_string(order_id)};
    }
    const auto& level_it =
        GetLevel(order_it->second.side, order_it->second.price);
    uint32_t prior_size = 0;
    for (const auto& order : level_it) {
      if (order.order_id == order_id) {
        break;
      }
      prior_size += order.size;
    }
    return prior_size;
  }

  std::vector<db::BidAskPair> GetSnapshot(std::size_t level_count = 1) const {
    std::vector<db::BidAskPair> res;
    for (size_t i = 0; i < level_count; ++i) {
      db::BidAskPair ba_pair{db::kUndefPrice, db::kUndefPrice, 0, 0, 0, 0};
      auto bid = GetBidLevel(i);
      if (bid) {
        ba_pair.bid_px = bid.price;
        ba_pair.bid_sz = bid.size;
        ba_pair.bid_ct = bid.count;
      }
      auto ask = GetAskLevel(i);
      if (ask) {
        ba_pair.ask_px = ask.price;
        ba_pair.ask_sz = ask.size;
        ba_pair.ask_ct = ask.count;
      }
      res.emplace_back(ba_pair);
    }
    return res;
  }

  void Apply(const db::MboMsg& mbo) {
    switch (mbo.action) {
      case db::Action::Clear: {
        Clear();
        break;
      }
      case db::Action::Add: {
        Add(mbo);
        break;
      }
      case db::Action::Cancel: {
        Cancel(mbo);
        break;
      }
      case db::Action::Modify: {
        Modify(mbo);
        break;
      }
      case db::Action::Trade:
      case db::Action::Fill:
      case db::Action::None: {
        break;
      }
      default: {
        throw std::invalid_argument{std::string{"Unknown action: "} +
                                    db::ToString(mbo.action)};
      }
    }
  }

 private:
  using LevelOrders = std::vector<db::MboMsg>;
  struct PriceAndSide {
    int64_t price;
    db::Side side;
  };
  using Orders = std::unordered_map<uint64_t, PriceAndSide>;
  using SideLevels = std::map<int64_t, LevelOrders>;

  static PriceLevel GetPriceLevel(int64_t price, const LevelOrders& level) {
    PriceLevel res{price};
    for (const auto& order : level) {
      if (!order.flags.IsTob()) {
        ++res.count;
      }
      res.size += order.size;
    }
    return res;
  }

  static LevelOrders::iterator GetLevelOrder(LevelOrders& level,
                                             uint64_t order_id) {
    auto order_it = std::find_if(level.begin(), level.end(),
                                 [order_id](const db::MboMsg& order) {
                                   return order.order_id == order_id;
                                 });
    if (order_it == level.end()) {
      throw std::invalid_argument{"No order with ID " +
                                  std::to_string(order_id)};
    }
    return order_it;
  }

  void Clear() {
    orders_by_id_.clear();
    offers_.clear();
    bids_.clear();
  }

  void Add(db::MboMsg mbo) {
    if (mbo.flags.IsTob()) {
      SideLevels& levels = GetSideLevels(mbo.side);
      levels.clear();
      // kUndefPrice indicates the side's book should be cleared
      // and doesn't represent an order that should be added
      if (mbo.price != db::kUndefPrice) {
        LevelOrders level = {mbo};
        levels.emplace(mbo.price, level);
      }
    } else {
      LevelOrders& level = GetOrInsertLevel(mbo.side, mbo.price);
      level.emplace_back(mbo);
      auto res = orders_by_id_.emplace(mbo.order_id,
                                       PriceAndSide{mbo.price, mbo.side});
      if (!res.second) {
        throw std::invalid_argument{"Received duplicated order ID " +
                                    std::to_string(mbo.order_id)};
      }
    }
  }

  void Cancel(db::MboMsg mbo) {
    LevelOrders& level = GetLevel(mbo.side, mbo.price);
    auto order_it = GetLevelOrder(level, mbo.order_id);
    if (order_it->size < mbo.size) {
      throw std::logic_error{
          "Tried to cancel more size than existed for order ID " +
          std::to_string(mbo.order_id)};
    }
    order_it->size -= mbo.size;
    if (order_it->size == 0) {
      orders_by_id_.erase(mbo.order_id);
      level.erase(order_it);
      if (level.empty()) {
        RemoveLevel(mbo.side, mbo.price);
      }
    }
  }

  void Modify(db::MboMsg mbo) {
    auto price_side_it = orders_by_id_.find(mbo.order_id);
    if (price_side_it == orders_by_id_.end()) {
      // If order not found, treat it as an add
      Add(mbo);
      return;
    }
    if (price_side_it->second.side != mbo.side) {
      throw std::logic_error{"Order " + std::to_string(mbo.order_id) +
                             " changed side"};
    }
    auto prev_price = price_side_it->second.price;
    LevelOrders& prev_level = GetLevel(mbo.side, prev_price);
    auto level_order_it = GetLevelOrder(prev_level, mbo.order_id);
    if (prev_price != mbo.price) {
      price_side_it->second.price = mbo.price;
      prev_level.erase(level_order_it);
      if (prev_level.empty()) {
        RemoveLevel(mbo.side, prev_price);
      }
      LevelOrders& level = GetOrInsertLevel(mbo.side, mbo.price);
      // Changing price loses priority
      level.emplace_back(mbo);
    } else if (level_order_it->size < mbo.size) {
      LevelOrders& level = prev_level;
      // Increasing size loses priority
      level.erase(level_order_it);
      level.emplace_back(mbo);
    } else {
      level_order_it->size = mbo.size;
    }
  }

  SideLevels& GetSideLevels(db::Side side) {
    switch (side) {
      case db::Side::Ask: {
        return offers_;
      }
      case db::Side::Bid: {
        return bids_;
      }
      case db::Side::None:
      default: {
        throw std::invalid_argument{"Invalid side"};
      }
    }
  }

  LevelOrders& GetLevel(db::Side side, int64_t price) {
    SideLevels& levels = GetSideLevels(side);
    auto level_it = levels.find(price);
    if (level_it == levels.end()) {
      throw std::invalid_argument{
          std::string{"Received event for unknown level "} +
          db::ToString(side) + " " + db::pretty::PxToString(price)};
    }
    return level_it->second;
  }

  LevelOrders& GetOrInsertLevel(db::Side side, int64_t price) {
    SideLevels& levels = GetSideLevels(side);
    return levels[price];
  }

  void RemoveLevel(db::Side side, int64_t price) {
    SideLevels& levels = GetSideLevels(side);
    levels.erase(price);
  }

  Orders orders_by_id_;
  SideLevels offers_;
  SideLevels bids_;
};

class Market {
 public:
  struct PublisherBook {
    uint16_t publisher_id;
    Book book;
  };

  const std::vector<PublisherBook>& GetBooksByPub(uint32_t instrument_id) {
    return books_[instrument_id];
  }

  const Book& GetBook(uint32_t instrument_id, uint16_t publisher_id) {
    const std::vector<PublisherBook>& books = GetBooksByPub(instrument_id);
    auto book_it = std::find_if(books.begin(), books.end(),
                                [publisher_id](const PublisherBook& pub_book) {
                                  return pub_book.publisher_id == publisher_id;
                                });
    if (book_it == books.end()) {
      throw std::invalid_argument{"No book for publisher ID " +
                                  std::to_string(publisher_id)};
    }
    return book_it->book;
  }

  std::pair<PriceLevel, PriceLevel> Bbo(uint32_t instrument_id,
                                        uint16_t publisher_id) {
    const auto& book = GetBook(instrument_id, publisher_id);
    return book.Bbo();
  }

  std::pair<PriceLevel, PriceLevel> AggregatedBbo(uint32_t instrument_id) {
    PriceLevel agg_bid;
    PriceLevel agg_ask;
    for (const auto& pub_book : GetBooksByPub(instrument_id)) {
      const auto bbo = pub_book.book.Bbo();
      const auto& bid = bbo.first;
      const auto& ask = bbo.second;
      if (bid) {
        if (agg_bid.IsEmpty() || bid.price > agg_bid.price) {
          agg_bid = bid;
        } else if (bid.price == agg_bid.price) {
          agg_bid.count += bid.count;
          agg_bid.size += bid.size;
        }
      }
      if (ask) {
        if (agg_ask.IsEmpty() || ask.price < agg_ask.price) {
          agg_ask = ask;
        } else if (ask.price == agg_ask.price) {
          agg_ask.count += ask.count;
          agg_ask.size += ask.size;
        }
      }
    }
    return {agg_bid, agg_ask};
  }

  void Apply(const db::MboMsg& mbo_msg) {
    auto& instrument_books = books_[mbo_msg.hd.instrument_id];
    auto book_it =
        std::find_if(instrument_books.begin(), instrument_books.end(),
                     [&mbo_msg](const PublisherBook& pub_book) {
                       return pub_book.publisher_id == mbo_msg.hd.publisher_id;
                     });
    if (book_it == instrument_books.end()) {
      instrument_books.emplace_back(PublisherBook{mbo_msg.hd.publisher_id, {}});
      book_it = std::prev(instrument_books.end());
    }
    book_it->book.Apply(mbo_msg);
  }

 private:
  std::unordered_map<uint32_t, std::vector<PublisherBook>> books_;
};

int main() {
  // First, create a historical client
  auto client = db::Historical::Builder().SetKey("$YOUR_API_KEY").Build();

  // Next, we'll set up the books and book handlers
  Market market;
  // We'll parse symbology from the DBN metadata
  db::TsSymbolMap symbol_map;
  auto metadata_callback = [&symbol_map](db::Metadata metadata) {
    symbol_map = metadata.CreateSymbolMap();
  };
  // For each book update...
  auto record_callback = [&market, &symbol_map](const db::Record& record) {
    if (auto* mbo = record.GetIf<db::MboMsg>()) {
      // We'll apply
      market.Apply(*mbo);
      // If it's the last update in an event, print the state of the aggregated
      // book
      if (mbo->flags.IsLast()) {
        const auto& symbol = symbol_map.At(*mbo);
        auto bbo = market.AggregatedBbo(mbo->hd.instrument_id);
        std::cout << symbol << " Aggregated BBO | "
                  << db::ToIso8601(mbo->ts_recv) << "\n    " << bbo.second
                  << "\n    " << bbo.first << '\n';
      }
    }
    return db::KeepGoing::Continue;
  };

  auto file_path = "dbeq-basic-20240403.mbo.dbn.zst";
  // Check if file exists
  auto file_store = std::ifstream(file_path).good()
                        // And open it if it does
                        ? db::DbnStore{file_path}
                        // Or we'll request the data starting from the beginning
                        // of pre-market trading hours
                        : client.TimeseriesGetRangeToFile(
                              db::dataset::kDbeqBasic,
                              {"2024-04-03T08:00:00", "2024-04-03T14:00:00"},
                              {"GOOG", "GOOGL"}, db::Schema::Mbo, file_path);
  // Finally, we'll replay each book update
  file_store.Replay(metadata_callback, record_callback);
  return 0;
}
```
## Results

```plaintext
GOOGL Aggregated BBO | 2024-04-03T11:00:00.903881953Z
    0 @ kUndefPrice | 0 order(s)
    200 @ 152.800000000 | 1 order(s)
GOOGL Aggregated BBO | 2024-04-03T11:00:00.903887026Z
    200 @ 155.200000000 | 1 order(s)
    200 @ 152.800000000 | 1 order(s)
GOOGL Aggregated BBO | 2024-04-03T11:00:00.914731635Z
    200 @ 155.200000000 | 1 order(s)
    200 @ 152.800000000 | 1 order(s)
GOOGL Aggregated BBO | 2024-04-03T11:00:00.925739296Z
    200 @ 155.200000000 | 1 order(s)
    200 @ 152.800000000 | 1 order(s)
GOOGL Aggregated BBO | 2024-04-03T11:00:00.925744379Z
    200 @ 155.200000000 | 1 order(s)
    200 @ 152.800000000 | 1 order(s)
GOOGL Aggregated BBO | 2024-04-03T11:03:55.585836619Z
    200 @ 155.200000000 | 1 order(s)
    200 @ 152.800000000 | 1 order(s)
GOOGL Aggregated BBO | 2024-04-03T11:03:55.585841782Z
    200 @ 155.400000000 | 1 order(s)
    200 @ 152.800000000 | 1 order(s)
...
```


# Limit order book construction

## Overview

This example demonstrates a complete limit order book implementation for Databento's MBO normalization schema.
It handles multiple instruments, here `GOOG` and `GOOGL`, across multiple venues that make up Databento Equities Basic:

- Investors Exchange (`IEXG`)
- NYSE Texas (`XCHI`)
- NYSE National (`XCIS`)
  We use `publisher_id` to disambiguate between venues.

While this example uses the Historical API, the same implementation can be used with live data by forwarding every `MBOMsg` to `market.apply`.

> **See also**
>
> It's recommended to first start with the [Order tracking example](https://databento.com/docs/examples/order-book/order-tracking.md#order-events), which explains each event more in depth.

## Design

Orders are stored in a `dict` for quick retrieval.
Each side of the book is a `SortedDict` to support both random access by price to add, modify, or cancel an order,
as well as retrieving the lowest or highest price level for determining the BBO.
The values in the `SortedDict` represent one level and are lists of orders sorted by priority.

Investors Exchange and NYSE National only provide top-of-book information meaning their MBO data is [normalized differently](https://databento.com/docs/conventions/common-fields-enums-types.md#top-of-book-datasets).
Each **A**dd message indicates the new top-of-book and replaces all levels on that side.
Add messages with an `UNDEF_PRICE` price indicate there's no depth for that side of the book.
The final special case comes when calculating the number of orders for a level since top-of-book updates don't correspond with individual orders.

## Dependencies

This example takes advantage of the [sortedcontainers](https://grantjenks.com/docs/sortedcontainers/) package for performant lists and dicts.
The `SortedDict` hybrid data structures balances the performance of random access to handle order book events with the typical pattern of checking the top of book.

## Example

```python
from __future__ import annotations
import os
from collections import defaultdict
from dataclasses import dataclass, field
from itertools import takewhile
import databento as db
from sortedcontainers import SortedDict

@dataclass(slots=True)
class PriceLevel:
    price: int
    size: int = 0
    count: int = 0

    def __str__(self) -> str:
        price = self.price / db.FIXED_PRICE_SCALE
        return f"{self.size:4} @ {price:6.2f} | {self.count:2} order(s)"

@dataclass(slots=True)
class LevelOrders:
    price: int
    orders: list[db.MBOMsg] = field(default_factory=list, compare=False)

    def __bool__(self) -> bool:
        return bool(self.orders)

    @property
    def level(self) -> PriceLevel:
        return PriceLevel(
            price=self.price,
            count=sum(1 for o in self.orders if not o.flags & db.RecordFlags.F_TOB),
            size=sum(o.size for o in self.orders),
        )

@dataclass(slots=True)
class Book:
    orders_by_id: dict[int, db.MBOMsg] = field(default_factory=dict)
    offers: SortedDict[int, LevelOrders] = field(default_factory=SortedDict)
    bids: SortedDict[int, LevelOrders] = field(default_factory=SortedDict)

    def bbo(self) -> tuple[PriceLevel | None, PriceLevel | None]:
        return self.get_bid_level(), self.get_ask_level()

    def get_bid_level(self, idx: int = 0) -> PriceLevel | None:
        if self.bids and len(self.bids) > idx:
            # Reverse for bids to get highest prices first
            return self.bids.peekitem(-(idx + 1))[1].level
        return None

    def get_ask_level(self, idx: int = 0) -> PriceLevel | None:
        if self.offers and len(self.offers) > idx:
            return self.offers.peekitem(idx)[1].level
        return None

    def get_bid_level_by_px(self, px: int) -> PriceLevel | None:
        try:
            return self._get_level(px, "B").level
        except KeyError:
            return None

    def get_ask_level_by_px(self, px: int) -> PriceLevel | None:
        try:
            return self._get_level(px, "A").level
        except KeyError:
            return None

    def get_order(self, id: int) -> db.MBOMsg | None:
        return self.orders_by_id.get(id)

    def get_queue_pos(self, id: int) -> int | None:
        order = self.get_order(id)
        if not order:
            return None
        level = self._get_level(order.price, order.side)
        return sum(order.size for order in takewhile(lambda o: o.order_id != id, level.orders))

    def get_snapshot(self, level_count: int = 1) -> list[db.BidAskPair]:
        snapshots = []
        for level in range(level_count):
            ba_pair = db.BidAskPair()
            bid = self.get_bid_level(level)
            if bid:
                ba_pair.bid_px = bid.price
                ba_pair.bid_sz = bid.size
                ba_pair.bid_ct = bid.count
            ask = self.get_ask_level(level)
            if ask:
                ba_pair.ask_px = ask.price
                ba_pair.ask_sz = ask.size
                ba_pair.ask_ct = ask.count
            snapshots.append(ba_pair)
        return snapshots

    def apply(self, mbo: db.MBOMsg) -> None:
        # Trade, Fill, or None: no change
        if mbo.action in ("T", "F", "N"):
            return
        # Clear book: remove all resting orders
        if mbo.action == "R":
            self._clear()
            return
        # side=N is only valid with Trade, Fill, and Clear actions
        assert mbo.side in ("A", "B")
        # UNDEF_PRICE indicates the book level should be removed
        if mbo.price == db.UNDEF_PRICE and mbo.flags & db.RecordFlags.F_TOB:
            self._side_levels(mbo.side).clear()
            return
        # Add: insert a new order
        if mbo.action == "A":
            self._add(mbo)
        # Cancel: partially or fully cancel some size from a resting order
        elif mbo.action == "C":
            self._cancel(mbo)
        # Modify: change the price and/or size of a resting order
        elif mbo.action == "M":
            self._modify(mbo)
        else:
            raise ValueError(f"Unknown action={mbo.action}")

    def _clear(self) -> None:
        self.orders_by_id.clear()
        self.offers.clear()
        self.bids.clear()

    def _add(self, mbo: db.MBOMsg) -> None:
        if mbo.flags & db.RecordFlags.F_TOB:
            levels = self._side_levels(mbo.side)
            levels.clear()
            levels[mbo.price] = LevelOrders(price=mbo.price, orders=[mbo])
        else:
            level = self._get_or_insert_level(mbo.price, mbo.side)
            assert mbo.order_id not in self.orders_by_id
            self.orders_by_id[mbo.order_id] = mbo
            level.orders.append(mbo)

    def _cancel(self, mbo: db.MBOMsg) -> None:
        order = self.orders_by_id[mbo.order_id]
        level = self._get_level(mbo.price, mbo.side)
        assert order.size >= mbo.size
        order.size -= mbo.size
        # If the full size is cancelled, remove the order from the book
        if order.size == 0:
            self.orders_by_id.pop(mbo.order_id)
            level.orders.remove(order)
            # If the level is now empty, remove it from the book
            if not level:
                self._remove_level(mbo.price, mbo.side)

    def _modify(self, mbo: db.MBOMsg) -> None:
        order = self.orders_by_id.get(mbo.order_id)
        if order is None:
            # If order not found, treat it as an add
            self._add(mbo)
            return
        assert order.side == mbo.side, f"Order {order} changed side to {mbo.side}"
        level = self._get_level(order.price, order.side)
        if order.price != mbo.price:
            # Changing price loses priority
            level.orders.remove(order)
            if not level:
                self._remove_level(order.price, mbo.side)
            level = self._get_or_insert_level(mbo.price, mbo.side)
            level.orders.append(mbo)
        elif order.size < mbo.size:
            # Increasing size loses priority
            level.orders.remove(order)
            level.orders.append(mbo)
        else:
            # Update in place
            level.orders[level.orders.index(order)] = mbo
        self.orders_by_id[mbo.order_id] = mbo

    def _side_levels(self, side: str) -> SortedDict:
        if side == "A":
            return self.offers
        if side == "B":
            return self.bids
        raise ValueError(f"Invalid {side =}")

    def _get_level(self, price: int, side: str) -> LevelOrders:
        levels = self._side_levels(side)
        if price not in levels:
            raise KeyError(f"No price level found for {price =} and {side =}")
        return levels[price]

    def _get_or_insert_level(self, price: int, side: str) -> LevelOrders:
        levels = self._side_levels(side)
        if price in levels:
            return levels[price]
        level = LevelOrders(price=price)
        levels[price] = level
        return level

    def _remove_level(self, price: int, side: str) -> None:
        levels = self._side_levels(side)
        levels.pop(price)

@dataclass(slots=True)
class Market:
    books: defaultdict[int, defaultdict[int, Book]] = field(
        default_factory=lambda: defaultdict(lambda: defaultdict(Book)),
    )

    def get_books_by_pub(self, instrument_id: int) -> defaultdict[int, Book]:
        return self.books[instrument_id]

    def get_book(self, instrument_id: int, publisher_id: int) -> Book:
        return self.books[instrument_id][publisher_id]

    def bbo(
        self,
        instrument_id: int,
        publisher_id: int,
    ) -> tuple[PriceLevel | None, PriceLevel | None]:
        return self.books[instrument_id][publisher_id].bbo()

    def aggregated_bbo(
        self,
        instrument_id: int,
    ) -> tuple[PriceLevel | None, PriceLevel | None]:
        agg_bbo: list[PriceLevel | None] = [None, None]
        # max for bids, min for asks
        for idx, reducer in [(0, max), (1, min)]:
            all_best = [b.bbo()[idx] for b in self.books[instrument_id].values()]
            all_best = [b for b in all_best if b]
            if not all_best:
                continue
            best_price = reducer(b.price for b in all_best)
            best = [b for b in all_best if b.price == best_price]
            agg_bbo[idx] = PriceLevel(
                price=best_price,
                size=sum(b.size for b in best),
                count=sum(b.count for b in best),
            )
        return tuple(agg_bbo)

    def apply(self, mbo: db.MBOMsg) -> None:
        book = self.books[mbo.instrument_id][mbo.publisher_id]
        book.apply(mbo)

if __name__ == "__main__":
    # First, create a historical client
    client = db.Historical("$YOUR_API_KEY")

    # Next, we will request MBO data starting from the beginning of pre-market trading hours
    # or load the file if we've already downloaded it.
    data_path = "dbeq-basic-20240403.mbo.dbn.zst"
    if os.path.exists(data_path):
        data = db.DBNStore.from_file(data_path)
    else:
        data = client.timeseries.get_range(
            dataset="DBEQ.BASIC",
            start="2024-04-03T08:00:00",
            end="2024-04-03T14:00:00",
            symbols=["GOOG", "GOOGL"],
            schema="mbo",
            path=data_path,
        )

    # Then we parse the symbology into a more usable format
    instrument_map = db.common.symbology.InstrumentMap()
    instrument_map.insert_metadata(data.metadata)

    # Finally, we iterate over each book update
    market = Market()
    for mbo in data:
        # And apply it
        market.apply(mbo)
        # If it's the last update in an event, print the state of the aggregated book
        if mbo.flags & db.RecordFlags.F_LAST:
            symbol = instrument_map.resolve(mbo.instrument_id, mbo.pretty_ts_recv.date()) or ""
            print(f"{symbol} Aggregated BBO | {mbo.pretty_ts_recv}")
            best_bid, best_offer = market.aggregated_bbo(mbo.instrument_id)
            print(f"    {best_offer}")
            print(f"    {best_bid}")
```
## Results

```plaintext
GOOGL Aggregated BBO | 2024-04-03 11:00:00.903881953+00:00
    None
     200 @ 152.80 |  1 order(s)
GOOGL Aggregated BBO | 2024-04-03 11:00:00.903887026+00:00
     200 @ 155.20 |  1 order(s)
     200 @ 152.80 |  1 order(s)
GOOGL Aggregated BBO | 2024-04-03 11:00:00.914731635+00:00
     200 @ 155.20 |  1 order(s)
     200 @ 152.80 |  1 order(s)
GOOGL Aggregated BBO | 2024-04-03 11:00:00.925739296+00:00
     200 @ 155.20 |  1 order(s)
     200 @ 152.80 |  1 order(s)
GOOGL Aggregated BBO | 2024-04-03 11:00:00.925744379+00:00
     200 @ 155.20 |  1 order(s)
     200 @ 152.80 |  1 order(s)
GOOGL Aggregated BBO | 2024-04-03 11:03:55.585836619+00:00
     200 @ 155.20 |  1 order(s)
     200 @ 152.80 |  1 order(s)
GOOGL Aggregated BBO | 2024-04-03 11:03:55.585841782+00:00
     200 @ 155.40 |  1 order(s)
     200 @ 152.80 |  1 order(s)
...
```


# Limit order book construction

## Overview

This example demonstrates a complete limit order book implementation for Databento's MBO normalization schema.
It handles multiple instruments, here `GOOG` and `GOOGL`, across multiple venues that make up Databento Equities Basic:

- Investors Exchange (`IEXG`)
- NYSE Texas (`XCHI`)
- NYSE National (`XCIS`)
  We use `publisher_id` to disambiguate between venues.

While this example uses the Historical API, the same implementation can be used with live data by forwarding every `MBOMsg` to `market.apply`.

> **See also**
>
> It's recommended to first start with the [Order tracking example](https://databento.com/docs/examples/order-book/order-tracking.md#order-events), which explains each event more in depth.

## Design

The `HashMap` stores the price and side of each order for quick retrieval by ID.
Each side of the book is a `BTreeMap` to balance random access of a price's level with retrieving the lowest and highest price level for determining the BBO.
The values in the book map are `VecDeque`s of orders sorted by priority.

Investors Exchange and NYSE National only provide top-of-book information meaning their MBO data is [normalized differently](https://databento.com/docs/conventions/common-fields-enums-types.md#top-of-book-datasets).
Each **A**dd message indicates the new top-of-book and replaces all levels on that side.
Add messages with an `UNDEF_PRICE` price indicate there's no depth for that side of the book.
The final special case comes when calculating the number of orders for a level since top-of-book updates don't correspond with individual orders.

## Example

```rust
use std::{
    collections::{BTreeMap, HashMap, VecDeque},
    fmt::Display,
};

use databento::{
    HistoricalClient,
    dbn::{
        Action, BidAskPair, Dataset, MboMsg, MboRec, Publisher, Record, Schema, Side, SymbolIndex,
        UNDEF_PRICE,
        decode::{AsyncDbnDecoder, DbnMetadata},
        pretty,
    },
    historical::timeseries::GetRangeToFileParams,
};
use time::macros::datetime;
use tokio::fs;

#[tokio::main]
async fn main() -> Result<(), databento::Error> {
    let mut client = HistoricalClient::builder().key_from_env()?.build()?;
    let mut market = Market::default();
    let path = "dbeq-basic-20240403.mbo.dbn.zst";
    if !fs::try_exists(path).await? {
        client
            .timeseries()
            .get_range_to_file(
                &GetRangeToFileParams::builder()
                    .dataset(Dataset::DbeqBasic)
                    .symbols(vec!["GOOG", "GOOGL"])
                    .date_time_range(
                        datetime!(2024-04-03 08:00:00 UTC)..datetime!(2024-04-03 14:00:00 UTC),
                    )
                    .schema(Schema::Mbo)
                    .path(path)
                    .build(),
            )
            .await?;
    };
    let mut decoder = AsyncDbnDecoder::from_zstd_file(path).await?;
    let symbol_map = decoder.metadata().symbol_map()?;
    while let Some(mbo) = decoder.decode_record::<MboMsg>().await? {
        market.apply(mbo.clone());
        // If it's the last update in an event, print the state of the aggregated book
        if mbo.flags.is_last() {
            let symbol = symbol_map.get_for_rec(mbo).unwrap();
            let (best_bid, best_offer) = market.aggregated_bbo(mbo.hd.instrument_id);
            println!("{symbol} Aggregated BBO | {}", mbo.ts_recv().unwrap());
            if let Some(best_offer) = best_offer {
                println!("    {best_offer}");
            } else {
                println!("    None");
            }
            if let Some(best_bid) = best_bid {
                println!("    {best_bid}");
            } else {
                println!("    None");
            }
        }
    }
    Ok(())
}

#[derive(Debug, Default)]
pub struct Market {
    books: HashMap<u32, Vec<(Publisher, Book)>>,
}

#[derive(Debug, Default)]
pub struct Book {
    orders_by_id: HashMap<u64, (Side, i64)>,
    offers: BTreeMap<i64, Level>,
    bids: BTreeMap<i64, Level>,
}

#[derive(Debug, Clone)]
pub struct PriceLevel {
    pub price: i64,
    pub size: u32,
    pub count: u32,
}

type Level = VecDeque<MboMsg>;

impl Market {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn books_by_pub(&self, instrument_id: u32) -> Option<&[(Publisher, Book)]> {
        self.books
            .get(&instrument_id)
            .map(|pub_books| pub_books.as_slice())
    }

    pub fn book(&self, instrument_id: u32, publisher: Publisher) -> Option<&Book> {
        let books = self.books.get(&instrument_id)?;
        books.iter().find_map(|(book_pub, book)| {
            if *book_pub == publisher {
                Some(book)
            } else {
                None
            }
        })
    }

    pub fn bbo(
        &self,
        instrument_id: u32,
        publisher: Publisher,
    ) -> (Option<PriceLevel>, Option<PriceLevel>) {
        self.book(instrument_id, publisher)
            .map(|book| book.bbo())
            .unwrap_or_default()
    }

    pub fn aggregated_bbo(&self, instrument_id: u32) -> (Option<PriceLevel>, Option<PriceLevel>) {
        let mut agg_bid = None;
        let mut agg_ask = None;
        let Some(books_by_pub) = self.books_by_pub(instrument_id) else {
            return (None, None);
        };
        for (_, book) in books_by_pub.iter() {
            let (bid, ask) = book.bbo();
            if let Some(bid) = bid {
                match &mut agg_bid {
                    None => agg_bid = Some(bid),
                    Some(ab) if bid.price > ab.price => agg_bid = Some(bid),
                    Some(ab) if bid.price == ab.price => {
                        ab.size += bid.size;
                        ab.count += bid.count;
                    }
                    Some(_) => {}
                }
            }
            if let Some(ask) = ask {
                match &mut agg_ask {
                    None => agg_ask = Some(ask),
                    Some(aa) if ask.price < aa.price => agg_ask = Some(ask),
                    Some(aa) if ask.price == aa.price => {
                        aa.size += ask.size;
                        aa.count += ask.count;
                    }
                    Some(_) => {}
                }
            }
        }
        (agg_bid, agg_ask)
    }

    pub fn apply(&mut self, mbo: MboMsg) {
        let publisher = mbo.publisher().unwrap();
        let books = self.books.entry(mbo.hd.instrument_id).or_default();
        let book = if let Some((_, book)) = books
            .iter_mut()
            .find(|(book_pub, _)| *book_pub == publisher)
        {
            book
        } else {
            books.push((publisher, Book::default()));
            &mut books.last_mut().unwrap().1
        };
        book.apply(mbo);
    }
}

impl Book {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn bbo(&self) -> (Option<PriceLevel>, Option<PriceLevel>) {
        (self.bid_level(0), self.ask_level(0))
    }

    pub fn bid_level(&self, idx: usize) -> Option<PriceLevel> {
        self.bids
            .iter()
            // Reverse to get highest first
            .rev()
            .nth(idx)
            .map(|(price, orders)| PriceLevel::new(*price, orders.iter()))
    }

    pub fn ask_level(&self, idx: usize) -> Option<PriceLevel> {
        self.offers
            .iter()
            .nth(idx)
            .map(|(price, orders)| PriceLevel::new(*price, orders.iter()))
    }

    pub fn bid_level_by_px(&self, px: i64) -> Option<PriceLevel> {
        self.bids
            .get(&px)
            .map(|orders| PriceLevel::new(px, orders.iter()))
    }

    pub fn ask_level_by_px(&self, px: i64) -> Option<PriceLevel> {
        self.offers
            .get(&px)
            .map(|orders| PriceLevel::new(px, orders.iter()))
    }

    pub fn order(&self, order_id: u64) -> Option<&MboMsg> {
        let (side, price) = self.orders_by_id.get(&order_id)?;
        let levels = self.side_levels(*side);
        let level = levels.get(price)?;
        level.iter().find(|order| order.order_id == order_id)
    }

    pub fn queue_pos(&self, order_id: u64) -> Option<u32> {
        let (side, price) = self.orders_by_id.get(&order_id)?;
        let levels = self.side_levels(*side);
        let level = levels.get(price)?;
        Some(
            level
                .iter()
                .take_while(|order| order.order_id != order_id)
                .fold(0, |acc, order| acc + order.size),
        )
    }

    pub fn snapshot(&self, level_count: usize) -> Vec<BidAskPair> {
        (0..level_count)
            .map(|i| {
                let mut ba_pair = BidAskPair::default();
                if let Some(bid) = self.bid_level(i) {
                    ba_pair.bid_px = bid.price;
                    ba_pair.bid_sz = bid.size;
                    ba_pair.bid_ct = bid.count;
                }
                if let Some(ask) = self.ask_level(i) {
                    ba_pair.ask_px = ask.price;
                    ba_pair.ask_sz = ask.size;
                    ba_pair.ask_ct = ask.count;
                }
                ba_pair
            })
            .collect()
    }

    pub fn apply(&mut self, mbo: MboMsg) {
        let action = mbo.action().unwrap();
        match action {
            Action::Modify => self.modify(mbo),
            Action::Trade | Action::Fill | Action::None => {}
            Action::Cancel => self.cancel(mbo),
            Action::Add => self.add(mbo),
            Action::Clear => self.clear(),
        }
    }

    fn clear(&mut self) {
        self.orders_by_id.clear();
        self.offers.clear();
        self.bids.clear();
    }

    fn add(&mut self, mbo: MboMsg) {
        let price = mbo.price;
        let side = mbo.side().unwrap();
        if mbo.flags.is_tob() {
            let levels: &mut BTreeMap<i64, Level> = self.side_levels_mut(side);
            levels.clear();
            // UNDEF_PRICE indicates the side's book should be cleared
            // and doesn't represent an order that should be added
            if mbo.price != UNDEF_PRICE {
                levels.insert(price, VecDeque::from([mbo]));
            }
        } else {
            assert_ne!(price, UNDEF_PRICE);
            assert!(
                self.orders_by_id
                    .insert(mbo.order_id, (side, price))
                    .is_none()
            );
            let level: &mut Level = self.get_or_insert_level(side, price);
            level.push_back(mbo);
        }
    }

    fn cancel(&mut self, mbo: MboMsg) {
        let side = mbo.side().unwrap();
        let level = self.level_mut(side, mbo.price);
        let order_idx = Self::find_order(level, mbo.order_id);
        let existing_order = level.get_mut(order_idx).unwrap();
        assert!(existing_order.size >= mbo.size);
        existing_order.size -= mbo.size;
        if existing_order.size == 0 {
            level.remove(order_idx).unwrap();
            if level.is_empty() {
                self.remove_level(side, mbo.price);
            }
            self.orders_by_id.remove(&mbo.order_id).unwrap();
        }
    }

    fn modify(&mut self, mbo: MboMsg) {
        let order_id = mbo.order_id;
        let side = mbo.side().unwrap();
        let Some((id_side, id_price)) = self.orders_by_id.get_mut(&order_id) else {
            // If order not found, treat it as an add
            return self.add(mbo);
        };
        let prev_side = *id_side;
        let prev_price = *id_price;
        // Update orders by ID
        *id_side = side;
        *id_price = mbo.price;
        // Update level order
        let level = self.level_mut(prev_side, prev_price);
        let order_idx = Self::find_order(level, order_id);
        let existing_order = level.get_mut(order_idx).unwrap();
        let should_keep_priority = prev_price == mbo.price && existing_order.size >= mbo.size;
        existing_order.size = mbo.size;
        if should_keep_priority {
            return;
        }
        if prev_price != mbo.price {
            let prev_level = level;
            Self::remove_order(prev_level, order_id);
            if prev_level.is_empty() {
                self.remove_level(prev_side, prev_price);
            }
            let level = self.get_or_insert_level(side, mbo.price);
            level.push_back(mbo);
        } else {
            Self::remove_order(level, order_id);
            level.push_back(mbo);
        }
    }

    fn get_or_insert_level(&mut self, side: Side, price: i64) -> &mut Level {
        let levels = self.side_levels_mut(side);
        levels.entry(price).or_default()
    }

    fn level_mut(&mut self, side: Side, price: i64) -> &mut Level {
        let levels = self.side_levels_mut(side);
        levels.get_mut(&price).unwrap()
    }

    fn remove_level(&mut self, side: Side, price: i64) {
        self.side_levels_mut(side).remove(&price).unwrap();
    }

    fn find_order(level: &VecDeque<MboMsg>, order_id: u64) -> usize {
        level.iter().position(|o| o.order_id == order_id).unwrap()
    }

    fn remove_order(level: &mut VecDeque<MboMsg>, order_id: u64) {
        let index = Self::find_order(level, order_id);
        level.remove(index).unwrap();
    }

    fn side_levels_mut(&mut self, side: Side) -> &mut BTreeMap<i64, Level> {
        match side {
            Side::Ask => &mut self.offers,
            Side::Bid => &mut self.bids,
            Side::None => panic!("Invalid side None"),
        }
    }

    fn side_levels(&self, side: Side) -> &BTreeMap<i64, Level> {
        match side {
            Side::Ask => &self.offers,
            Side::Bid => &self.bids,
            Side::None => panic!("Invalid side None"),
        }
    }
}

impl PriceLevel {
    fn new<'a>(price: i64, orders: impl Iterator<Item = &'a MboMsg>) -> Self {
        orders.fold(
            PriceLevel {
                price,
                size: 0,
                count: 0,
            },
|  | mut level, order | { |
                if !order.flags.is_tob() {
                    level.count += 1;
                }
                level.size += order.size;
                level
            },
        )
    }
}

impl Display for PriceLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{:4} @ {:6.2} | {:2} order(s)",
            self.size,
            pretty::Px(self.price),
            self.count
        )
    }
}
```
## Results

```plaintext
GOOGL Aggregated BBO | 2024-04-03 11:00:00.903881953 +00:00:00
    None
     200 @ 152.80 |  1 order(s)
GOOGL Aggregated BBO | 2024-04-03 11:00:00.903887026 +00:00:00
     200 @ 155.20 |  1 order(s)
     200 @ 152.80 |  1 order(s)
GOOGL Aggregated BBO | 2024-04-03 11:00:00.914731635 +00:00:00
     200 @ 155.20 |  1 order(s)
     200 @ 152.80 |  1 order(s)
GOOGL Aggregated BBO | 2024-04-03 11:00:00.925739296 +00:00:00
     200 @ 155.20 |  1 order(s)
     200 @ 152.80 |  1 order(s)
GOOGL Aggregated BBO | 2024-04-03 11:00:00.925744379 +00:00:00
     200 @ 155.20 |  1 order(s)
     200 @ 152.80 |  1 order(s)
GOOGL Aggregated BBO | 2024-04-03 11:03:55.585836619 +00:00:00
     200 @ 155.20 |  1 order(s)
     200 @ 152.80 |  1 order(s)
GOOGL Aggregated BBO | 2024-04-03 11:03:55.585841782 +00:00:00
     200 @ 155.40 |  1 order(s)
     200 @ 152.80 |  1 order(s)
...
```
