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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
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 ...