Support

Handle multiple record types

Overview

In this example we will use the Live client to process order book data using a callback function. We will use Python's functools.singledispatch to make handling different record types easier.

MBO schema

We will use the MBO schema in this example but any schema's records can be dispatched this way.

Example

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

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
...