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

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


# State management of resting orders

## Overview
This example shows how to track orders and update them according to the different MBO actions.
Order tracking is simpler to implement than a full [limit order book](https://databento.com/docs/examples/order-book/limit-order-book.md): it keeps track of all resting orders, but not the book levels.
The book levels such as the top of book (BBO) can be constructed from a map of resting orders, but it requires inefficiently iterating over all the orders.

> **Info**
>
> This example works for a single instrument.
> To use it with multiple instruments, will need to extend it to keep separate books for each instrument.

## Order events

| Name | Value | Action |
| Add | `A` | Insert a new order into the book. |
| Modify | `M` | Change an order's price and/or size. |
| Cancel | `C` | Fully or partially cancel an order from the book. |
| Clear | `R` | Remove all resting orders for the instrument. |
| Trade | `T` | An aggressing order traded. Does not affect the book. |
| Fill | `F` | A resting order was filled. Does not affect the book. |
| None | `N` | No action: does not affect the book, but may carry `flags` or other information. |

Trade and Fill actions do not affect the book because all fills will be accompanied by cancel actions that do update the book.

## Handling FlagSet::IsLast
A single event from a publisher can be normalized into multiple records.
Databento sets the flag `kLast` to denote the last record for an instrument in a packet.
The book state should only be examined _after_ a record with `kLast` set.
The `IsLast()` method is used to check the value of the bit flag.

## Example
```cpp
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <databento/constants.hpp>   // kUndefPrice
#include <databento/datetime.hpp>    // UnixNanos
#include <databento/enums.hpp>       // Action, Side
#include <databento/historical.hpp>  // HistoricalBuilder
#include <databento/pretty.hpp>      // Px
#include <functional>
#include <iomanip>
#include <iostream>
#include <unordered_map>
#include <utility>

namespace db = databento;

struct Order {
  Order() = default;
  Order(db::Side side, int64_t price, uint32_t size, db::UnixNanos ts_event)
      : side{side}, price{price}, size{size}, ts_event{ts_event} {}

  db::Side side{db::Side::None};
  int64_t price{db::kUndefPrice};
  uint32_t size{};
  db::UnixNanos ts_event{};
};

struct PriceLevel {
  PriceLevel() = default;
  explicit PriceLevel(const Order& order)
      : price{order.price}, size{order.size}, count{1} {}

  int64_t price{db::kUndefPrice};
  uint32_t size{};
  uint32_t count{};
};

class Book {
 public:
  std::pair<PriceLevel, PriceLevel> Bbo() const {
    PriceLevel best_bid;
    PriceLevel best_ask;
    for (const auto& order_pair : orders_) {
      const auto& order = order_pair.second;
      PriceLevel* side_best = &best_bid;
      std::function<bool(int64_t, int64_t)> is_improvement =
          std::greater<int64_t>{};
      if (order.side == db::Side::Ask) {
        side_best = &best_ask;
        is_improvement = std::less<int64_t>{};
      }
      if (side_best->price == db::kUndefPrice ||
          is_improvement(order.price, side_best->price)) {
        *side_best = PriceLevel(order);
      } else if (side_best->price == order.price) {
        side_best->size += order.size;
      }
    }
    return {best_bid, best_ask};
  }

  void Apply(db::UnixNanos ts_event, db::Action action, db::Side side,
             uint64_t order_id, int64_t price, uint32_t size,
             db::FlagSet flags) {
    switch (action) {
      // Trade, Fill, or None: no change
      case db::Action::Trade:
      case db::Action::Fill:
      case db::Action::None:
        break;

      case db::Action::Clear:  // Clear book: remove all resting orders
        orders_.clear();
        break;

      case db::Action::Add: {  // Add: insert a new order
        if (flags.IsTob()) {
          // For top-of-book publishers, remove previous order associated with
          // this side
          auto order_it = std::find_if(
              orders_.begin(), orders_.end(),
              [side](auto pair) { return pair.second.side == side; });
          if (order_it != orders_.end()) {
            orders_.erase(order_it->first);
          }
          // kUndefPrice indicates the price level was removed. There's no new
          // level to add
          if (price == db::kUndefPrice) {
            break;
          }
        }
        orders_[order_id] = Order{side, price, size, ts_event};
        break;
      }
      case db::Action::Modify: {  // Modify: change the price and/or size of a
                                  // resting order
        auto& existing_order = orders_.at(order_id);
        // The order loses its priority if the price changes or the size
        // increases
        if (existing_order.price != price || existing_order.size < size) {
          existing_order.ts_event = ts_event;
        }
        existing_order.size = size;
        existing_order.price = price;
        break;
      }
      case db::Action::Cancel: {  // Cancel: partially or fully cancel some size
                                  // from a resting order
        auto order_it = orders_.find(order_id);
        if (order_it == orders_.end()) {
          break;
        }
        assert(order_it->second.size >= size);
        order_it->second.size -= size;
        // If the full size is cancelled, remove the order from the book
        if (order_it->second.size == 0) {
          orders_.erase(order_it);
        }
        break;
      }
    }
  }

 private:
  std::unordered_map<uint64_t, Order> orders_;
};

int main() {
  auto client = db::Historical::Builder().SetKey("$YOUR_API_KEY").Build();
  // First, we request MBO data starting from the beginning of pre-market
  // trading hours
  Book book;
  bool book_is_ready = false;
  client.TimeseriesGetRange(
      "XNAS.ITCH", {"2022-08-26T08:00:00", "2022-08-26T14:30:00"}, {"MSFT"},
      db::Schema::Mbo, [&book, &book_is_ready](const db::Record& rec) {
        const auto& mbo = rec.Get<db::MboMsg>();
        book.Apply(mbo.hd.ts_event, mbo.action, mbo.side, mbo.order_id,
                   mbo.price, mbo.size, mbo.flags);
        book_is_ready = mbo.flags.IsLast();
        return db::KeepGoing::Continue;
      });
  if (book_is_ready) {
    auto bbo = book.Bbo();
    std::cout << "Best ask  " << std::setprecision(2)
              << db::pretty::Px{bbo.second.price} << " x " << bbo.second.size
              << '\n';
    std::cout << "Best bid  " << std::setprecision(2)
              << db::pretty::Px{bbo.first.price} << " x " << bbo.first.size
              << '\n';
  }
  return 0;
}
```
## Result
```plaintext
Best ask  276.07 x 62
Best bid  276.01 x 19
```


# State management of resting orders

## Overview
This example shows how to track orders and update them according to the different MBO actions.
Order tracking is simpler to implement than a full [limit order book](https://databento.com/docs/examples/order-book/limit-order-book.md): it keeps track of all resting orders, but not the book levels.
The book levels such as the top of book (BBO) can be constructed from a map of resting orders, but it requires inefficiently iterating over all the orders.

> **Info**
>
> This example works for a single instrument.
> To use it with multiple instruments, you will need to extend it to keep separate books for each instrument.

## Order events

| Name | Value | Action |
| Add | `A` | Insert a new order into the book. |
| Modify | `M` | Change an order's price and/or size. |
| Cancel | `C` | Fully or partially cancel an order from the book. |
| Clear | `R` | Remove all resting orders for the instrument. |
| Trade | `T` | An aggressing order traded. Does not affect the book. |
| Fill | `F` | A resting order was filled. Does not affect the book. |
| None | `N` | No action: does not affect the book, but may carry `flags` or other information. |

Trade and Fill actions do not affect the book because all fills will be accompanied by cancel actions that do update the book.

## Handling F_LAST
A single event from a publisher can be normalized into multiple records.
Databento sets the flag `F_LAST` to denote the last record for an instrument in an event.
The book state should only be examined _after_ a record with `F_LAST` set.

## Example
```python
from dataclasses import dataclass, field
import databento as db

OrderId = int
UnixTimestamp = int

@dataclass(slots=True)
class Order:
    side: str
    price: int
    size: int
    ts_event: UnixTimestamp

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

@dataclass(slots=True)
class Book:
    orders: dict[OrderId, Order] = field(default_factory=dict)

    def bbo(self) -> tuple[PriceLevel, PriceLevel]:
        best_ask = PriceLevel()
        best_bid = PriceLevel()
        for order in self.orders.values():
            if order.side == "A":
                if best_ask.price is None or best_ask.price > order.price:
                    best_ask = PriceLevel(
                        price=order.price,
                        size=order.size,
                        count=1,
                    )
                elif best_ask.price == order.price:
                    best_ask.size += order.size
                    best_ask.count += 1
            elif order.side == "B":
                if best_bid.price is None or best_bid.price < order.price:
                    best_bid = PriceLevel(
                        price=order.price,
                        size=order.size,
                        count=1,
                    )
                elif best_bid.price == order.price:
                    best_bid.size += order.size
                    best_bid.count += 1
        return best_bid, best_ask

    def apply(
        self,
        ts_event: UnixTimestamp,
        action: str,
        side: str,
        order_id: int,
        price: int,
        size: int,
        flags: db.RecordFlags,
    ) -> None:
        # Trade, Fill, or None: no change
        if action in ("T", "F", "N"):
            return

        # Clear book: remove all resting orders
        if action == "R":
            self.orders.clear()

        # Add: insert a new order
        elif action == "A":
            # For top-of-book publishers, remove previous order associated with this side
            if flags & db.RecordFlags.F_TOB:
                self.orders = {i: o for i, o in self.orders.items() if o.side != side}
                # UNDEF_PRICE indicates the price level was removed. There's no new level to add
                if price == db.UNDEF_PRICE:
                    return
            self.orders[order_id] = Order(side, price, size, ts_event)

        # Cancel: partially or fully cancel some size from a resting order
        elif action == "C":
            existing_order = self.orders[order_id]
            assert existing_order.size >= size
            existing_order.size -= size
            # If the full size is cancelled, remove the order from the book
            if existing_order.size == 0:
                self.orders.pop(order_id)

        # Modify: change the price and/or size of a resting order
        elif action == "M":
            existing_order = self.orders[order_id]
            # The order loses its priority if the price changes or the size increases
            if existing_order.price != price or existing_order.size < size:
                existing_order.ts_event = ts_event
            existing_order.size = size
            existing_order.price = price

# 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
data = client.timeseries.get_range(
    dataset="XNAS.ITCH",
    start="2022-08-26T08:00:00",
    end="2022-08-26T14:30:00",
    symbols="MSFT",
    schema="mbo",
)

# Then, we replay the data, updating the book with each record
book = Book()
book_is_ready = False
for mbo in data:
    book.apply(mbo.ts_event, mbo.action, mbo.side, mbo.order_id, mbo.price, mbo.size, mbo.flags)
    book_is_ready = mbo.flags & db.RecordFlags.F_LAST

# Finally we inspect the final BBO
if book_is_ready:
    best_bid, best_ask = book.bbo()
    print(f"Best ask  {float(best_ask.price) / db.FIXED_PRICE_SCALE} × {best_ask.size}")
    print(f"Best bid  {float(best_bid.price) / db.FIXED_PRICE_SCALE} × {best_bid.size}")
```
## Result
```plaintext
Best ask  276.07 × 62
Best bid  276.01 × 19
```


# State management of resting orders

## Overview
This example shows how to track orders and update them according to the different MBO actions.
Order tracking is simpler to implement than a full [limit order book](https://databento.com/docs/examples/order-book/limit-order-book.md): it keeps track of all resting orders, but not the book levels.
The book levels such as the top of book (BBO) can be constructed from a map of resting orders, but it requires inefficiently iterating over all the orders.

> **Info**
>
> This example works for a single instrument.
> To use it with multiple instruments, you will need to extend it to keep separate books for each instrument.

## Order events

| Name | Value | Action |
| Add | `A` | Insert a new order into the book. |
| Modify | `M` | Change an order's price and/or size. |
| Cancel | `C` | Fully or partially cancel an order from the book. |
| Clear | `R` | Remove all resting orders for the instrument. |
| Trade | `T` | An aggressing order traded. Does not affect the book. |
| Fill | `F` | A resting order was filled. Does not affect the book. |

Trade and Fill actions do not affect the book because all fills will be accompanied by cancel actions that do update the book.

## Handling flags::LAST
A single event from a publisher can be normalized into multiple records.
Databento sets the bit flag `LAST` to denote the last record for an instrument in a packet.
The book state should only be examined _after_ a record with `LAST` set, which can be checked with the `is_last()` method.

## Example
```rust
use std::collections::HashMap;

use databento::{
    HistoricalClient,
    dbn::{
        Action, Dataset::XnasItch, MboMsg, MboRec, RecordHeader, Schema, Side, UNDEF_PRICE,
        pretty::Px,
    },
    historical::timeseries::GetRangeParams,
};
use time::macros::datetime;

#[derive(Default)]
struct Book {
    orders: HashMap<u64, Order>,
}

struct Order {
    side: Side,
    price: i64,
    size: u32,
    ts_event: u64,
}

struct PriceLevel {
    price: i64,
    size: u32,
    count: u32,
}

impl Book {
    fn bbo(&self) -> (PriceLevel, PriceLevel) {
        self.orders.values().fold(
            <(PriceLevel, PriceLevel)>::default(),
|  | (mut best_bid, mut best_ask), order | { |
                if order.side == Side::Ask {
                    if best_ask.price == UNDEF_PRICE || best_ask.price > order.price {
                        best_ask = PriceLevel::from(order);
                    } else if best_ask.price == order.price {
                        best_ask.size += order.size;
                        best_ask.count += 1;
                    }
                } else if best_bid.price == UNDEF_PRICE || best_bid.price < order.price {
                    best_bid = PriceLevel::from(order);
                } else if best_bid.price == order.price {
                    best_bid.size += order.size;
                    best_bid.count += 1;
                }
                (best_bid, best_ask)
            },
        )
    }

    fn apply(&mut self, mbo: MboMsg) -> anyhow::Result<()> {
        let action = mbo.action()?;
        let side = mbo.side()?;
        let MboMsg {
            hd: RecordHeader { ts_event, .. },
            order_id,
            price,
            size,
            flags,
            ..
        } = mbo;
        match action {
            // Trade, Fill, or None: no change
            Action::Trade | Action::Fill | Action::None => (),
            // Clear book: remove all resting orders
            Action::Clear => self.orders.clear(),
            Action::Add => {
                // Add: insert a new order
                if flags.is_tob() {
                    // For top-of-book publishers, remove previous order associated with this side
                    self.orders.retain(|_, order| order.side != side);
                    // UNDEF_PRICE indicates the price level was removed. There's
                    // no new level to add
                    if price == UNDEF_PRICE {
                        return Ok(());
                    }
                }
                self.orders.insert(
                    order_id,
                    Order {
                        side,
                        price,
                        size,
                        ts_event,
                    },
                );
            }
            Action::Cancel => {
                // Cancel: partially or fully cancel some size from a resting order
                let existing_order = self.orders.get_mut(&order_id).unwrap();
                assert!(existing_order.size >= size);
                existing_order.size -= size;
                // If the full size is cancelled, remove the
                // order from the book
                if existing_order.size == 0 {
                    self.orders.remove(&order_id);
                }
            }
            Action::Modify => {
                // Modify: change the price and/or size of a resting order
                let existing_order = self.orders.get_mut(&order_id).unwrap();
                // The order loses its priority if the price changes or the size increases
                if existing_order.price != price || existing_order.size < size {
                    existing_order.ts_event = ts_event;
                }
                existing_order.size = size;
                existing_order.price = price;
            }
        }
        Ok(())
    }
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let mut client = HistoricalClient::builder().key_from_env()?.build()?;
    // First, we request MBO data starting from the beginning of pre-market trading hours
    let mut decoder = client
        .timeseries()
        .get_range(
            &GetRangeParams::builder()
                .dataset(XnasItch)
                .date_time_range(
                    datetime!(2022-08-26 08:00:00 UTC)..datetime!(2022-08-26 14:30:00 UTC),
                )
                .symbols("MSFT")
                .schema(Schema::Mbo)
                .build(),
        )
        .await?;
    // Then, we replay the data, updating the book with each record
    let mut book = Book::default();
    let mut book_is_ready = false;
    while let Some(mbo) = decoder.decode_record::<MboMsg>().await? {
        book.apply(mbo.clone())?;
        book_is_ready = mbo.flags.is_last();
    }
    if book_is_ready {
        let (best_bid, best_ask) = book.bbo();
        println!("Best ask  {:.2} × {}", Px(best_ask.price), best_ask.size);
        println!("Best bid  {:.2} × {}", Px(best_bid.price), best_bid.size);
    }

    Ok(())
}

impl Default for PriceLevel {
    fn default() -> Self {
        Self {
            price: UNDEF_PRICE,
            size: 0,
            count: 0,
        }
    }
}

impl From<&Order> for PriceLevel {
    fn from(order: &Order) -> Self {
        Self {
            price: order.price,
            size: order.size,
            count: 1,
        }
    }
}
```
## Result
```plaintext
Best ask  276.07 × 62
Best bid  276.01 × 19
```
