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

Source: https://databento.com/docs/examples/basics-live/live-dispatch


# Handle multiple record types

## Overview

In this example we will use the [LiveThreaded client](https://databento.com/docs/api-live/client/live-threaded.md) to process order book data using a callback function.
We'll use the `GetIf` templated method on `Record` which returns a pointer to the specified type if the record is that type, otherwise `nullptr`.
We'll chain calls to this method to handle the various record types we might receive from the live gateway.

## MBO schema

We will use the [MBO schema](https://databento.com/docs/schemas/mbo.md) in this example but any schema's records can be dispatched this way.

## Example

```cpp
#include <chrono>                    // seconds
#include <databento/live.hpp>        // LiveBuilder
#include <databento/pretty.hpp>      // Px
#include <databento/publishers.hpp>  // Dataset
#include <databento/record.hpp>  // Record, SymbolMappingMsg, MboMsg, ErrorMsg
#include <iomanip>
#include <iostream>

namespace db = databento;

// First, we create our callback function, pulling out different record types
// with GetIf
db::KeepGoing RecordHandler(const db::Record& record) {
  if (auto* sym = record.GetIf<db::SymbolMappingMsg>()) {
    std::cout << sym->STypeInSymbol() << " has an instrument ID of "
              << sym->hd.instrument_id << '\n';
  } else if (auto* mbo = record.GetIf<db::MboMsg>()) {
    std::cout << mbo->order_id << '\t' << mbo->side << '\t' << mbo->size << '\t'
              << std::setprecision(6) << db::pretty::Px{mbo->price} << '\n';
  } else if (auto* error = record.GetIf<db::ErrorMsg>()) {
    std::cerr << error->Err() << '\n';
  } else if (auto* system = record.GetIf<db::SystemMsg>()) {
    std::cout << system->Msg() << '\n';
  }
  return db::KeepGoing::Continue;
}

int main() {
  auto client = db::LiveThreaded::Builder()
                    .SetKey("$YOUR_API_KEY")
                    .SetDataset(db::Dataset::GlbxMdp3)
                    .BuildThreaded();
  // First we subscribe to the MBO schema
  client.Subscribe({"ZN.c.0"}, db::Schema::Mbo, db::SType::Continuous);
  // Now, add our callback function and start the streaming session
  client.Start(RecordHandler);
  // Finally, we will wait for 5 seconds before closing the connection
  client.BlockForStop(std::chrono::seconds{5});
  return 0;
}
```
## Result

```plaintext
Subscription request 1 for mbo data succeeded
ZN.c.0 has an instrument ID of 42066706
8416556618490	Bid	1	112.015625
8416556618521	Bid	35	112.046875
8416556618538	Bid	4	112.046875
```


# Handle multiple record types

## Overview

In this example we will use the [Live client](https://databento.com/docs/api-live/client/live.md) to process order book data using [a callback](https://databento.com/docs/api-live/client/add-callback.md) function. We will use Python's [functools.singledispatch](https://docs.python.org/3/library/functools.html#functools.singledispatch) to make handling different record types easier.

## MBO schema

We will use the [MBO schema](https://databento.com/docs/schemas/mbo.md) in this example but any schema's records can be dispatched this way.

## Example

```python
from functools import singledispatch
import databento as db

# First, we will create our callback function using singledispatch
@singledispatch
def dbn_handler(_: db.DBNRecord):
    pass

@dbn_handler.register
def _(sym: db.SymbolMappingMsg):
    instrument_id = sym.instrument_id
    symbol = sym.stype_in_symbol
    print(f"{symbol} has an instrument ID of {instrument_id}")

@dbn_handler.register
def _(mbo: db.MBOMsg):
    order_id = f"{mbo.order_id:13d}"
    side = mbo.side
    size = mbo.size
    price = f"${mbo.pretty_price:,.06f}"
    print(order_id, side, size, price, sep="\t")

@dbn_handler.register
def _(sys: db.SystemMsg):
    print(f"{sys.msg}")

@dbn_handler.register
def _(error: db.ErrorMsg):
    print(f"ERROR: {error.err}")

# Then, create a live client and connect
live_client = db.Live(key="$YOUR_API_KEY")

# Next, we will subscribe to the MBO schema
live_client.subscribe(
    dataset="GLBX.MDP3",
    schema="mbo",
    stype_in="continuous",
    symbols="ZN.c.0",
)

# Now, add our callback function and start the streaming session
live_client.add_callback(dbn_handler)
live_client.start()

# Finally, we will wait for 5 seconds before closing the connection
live_client.block_for_close(timeout=5)
```
## Result

```plaintext
Subscription request 1 for mbo data succeeded
ZN.c.0 has an instrument ID of 42066706
8416556628429	A	4	$112.062500
8416556628472	A	3	$112.046875
8416556625196	B	1	$112.046875
8416556625202	B	1	$112.046875
8416556625204	B	1	$112.046875
8416556625196	B	1	$112.046875
8416556625202	B	1	$112.046875
8416556625204	B	1	$112.046875
8416556628476	A	1	$112.062500
8416556628477	A	1	$112.062500
8416556628479	A	1	$112.062500
8416556628482	A	1	$112.125000
8416556628483	A	1	$112.125000
8416556628484	B	1	$112.046875
8416556628128	B	5	$112.046875
8416556628379	B	4	$112.046875
...
```


# Handle multiple record types

## Overview

In this example we will use the [Live client](https://databento.com/docs/api-live/client/live.md) to process order book data using a callback function.
We'll use the generic `get` method on `RecordRef` which returns a reference to the specified record type `T`, otherwise `None`.
We'll chain calls to this method with `if let` to handle the various record types we might receive from the live gateway.

## MBO schema

We will use the [MBO schema](https://databento.com/docs/schemas/mbo.md) in this example but any schema's records can be dispatched this way.

## Example

```rust
use databento::{
    LiveClient,
    dbn::{
        Dataset::GlbxMdp3, ErrorMsg, ErrorRec, MboMsg, MboRec, SType, Schema, SymbolMappingMsg,
        SymbolMappingRec, SystemMsg, SystemRec, pretty,
    },
    live::Subscription,
};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let mut client = LiveClient::builder()
        .key_from_env()?
        .dataset(GlbxMdp3)
        .build()
        .await?;
    // First we subscribe to the MBO schema
    client
        .subscribe(
            Subscription::builder()
                .schema(Schema::Mbo)
                .symbols("ZN.c.0")
                .stype_in(SType::Continuous)
                .build(),
        )
        .await?;
    client.start().await?;
    // Then, we iterate over the first 5 records
    for _ in 0..5 {
        let Some(rec) = client.next_record().await? else {
            break;
        };
        // We handle different record types by chaining calls to `rec.get()`
        if let Some(sym) = rec.get::<SymbolMappingMsg>() {
            println!(
                "{} has an instrument ID of {}",
                sym.stype_in_symbol()?,
                sym.hd.instrument_id,
            );
        } else if let Some(mbo) = rec.get::<MboMsg>() {
            println!(
                "{}\t{:?}\t{}\t{:.6}",
                mbo.order_id,
                mbo.side()?,
                mbo.size,
                pretty::Px(mbo.price)
            );
        } else if let Some(error) = rec.get::<ErrorMsg>() {
            eprintln!("{}", error.err()?);
        } else if let Some(system) = rec.get::<SystemMsg>() {
            println!("{}", system.msg()?);
        }
    }
    Ok(())
}
```
## Result

```plaintext
ZN.c.0 has an instrument ID of 42002321
8414557391806	Ask	1	113.328125000
8414557387367	Bid	5	113.234375000
8414557378440	Bid	5	113.234375000
8414557375529	Bid	5	113.234375000
```
