Skip to content

Streaming data

Real-time subscriptions on the same engine.

Iterate a stream, or hold a subscription handle with dynamic add/remove, current-value images, delayed-data checks, and per-topic diagnostics.

xbbg has four entry points for real-time data. All of them subscribe to //blp/mktdata by default and share the engine's subscription sessions.

Use caseFunction
Iterate in synchronous codestream()
Iterate in async codeastream()
Add/remove securities, read health, poll current valuesasubscribe() (async) or subscribe() (sync factory, mainly for notebooks)
Other Bloomberg streaming servicesvwap/avwap, mktbar/amktbar, depth/adepth, chains/achains

Auction imbalance streams and ETF iNAV streams have dedicated helpers; see Exchange Auctions and Analytics Recipes.

What a stream yields ​

OptionEach item
default (backend=None)native xbbg.ArrowTable holding the updates already queued (up to flush_threshold, default 16)
backend='pandas', 'polars', 'pyarrow', ...the batch converted to that backend
raw=True or output='record_batch'native xbbg.ArrowRecordBatch
tick_mode=True, output='dict', or output='tick'one dict per update

output is accepted by asubscribe() and subscribe(); when given it takes precedence over raw and tick_mode, and 'backend' selects converted output. Arrow output has a UTC timestamp column, a topic column, the data fields, and a binary __xbbg_present column (see Updates are deltas). Dict ticks have timestamp, topic, and only the fields present in that update.

Filtered subscriptions (the default) return the requested fields plus MKTDATA_EVENT_TYPE and MKTDATA_EVENT_SUBTYPE, and skip market-data rows that contain none of the requested fields. all_fields=True returns every top-level scalar field Bloomberg sends; unrequested arrays and complex fields are omitted, and explicitly requested unsupported shapes fail instead of being truncated.

Basic streaming ​

python
import asyncio
from contextlib import aclosing

from xbbg import blp

async def main():
    batches = blp.astream(['AAPL US Equity', 'MSFT US Equity'], ['LAST_PRICE', 'BID', 'ASK'])
    async with aclosing(batches):
        async for table in batches:
            print(table.to_pylist())
            break  # aclosing() cleans up the subscription after an early exit

asyncio.run(main())
python
from contextlib import closing

from xbbg import blp

with closing(blp.stream(['AAPL US Equity'], ['LAST_PRICE', 'BID', 'ASK'], backend='pandas')) as batches:
    for frame in batches:
        print(frame)
        break

stream() runs the subscription on xbbg's managed background event loop (shared by all sync streams, not one thread per stream) and hands batches to the calling thread through a bounded queue of stream_capacity items (default 256). Close the generator when stopping early: closing cancels the producer and waits for its cleanup. A sync stream that needs a new subscription session waits up to 5 seconds when all max_subscription_sessions are in use, then raises RuntimeError; joining an existing shared feed never waits. Inside async applications use astream() or asubscribe().

Both accept callback=, a function called with each batch before it is yielded.

Subscription handles ​

asubscribe() returns a Subscription that you iterate and control:

python
import asyncio

from xbbg import blp

async def main():
    async with await blp.asubscribe(
        ['AAPL US Equity'],
        ['LAST_PRICE', 'BID', 'ASK'],
        aliases={'AAPL US Equity': 'apple'},
    ) as sub:
        count = 0
        async for table in sub:
            print(table.to_pylist())
            count += 1
            if count == 1:
                await sub.add(['MSFT US Equity'])
                await sub.add_fields(['VOLUME'])
            if count >= 100:
                break

asyncio.run(main())
MethodEffect
await sub.add(tickers, aliases=None)Subscribe more securities on the same handle
await sub.remove(labels)Stop securities by label (alias) or ticker; the others continue
await sub.add_fields(fields)Add fields to every security on the handle
sub.latest(backend=None)Current value of each field, one row per security (see Current values)
await sub.unsubscribe(drain=False)Close; with drain=True return unread items as a list in the iteration representation

async with (or try/finally with await sub.unsubscribe()) guarantees cleanup. An unread stream failure is raised after cleanup rather than hidden by a successful drain.

aliases maps a Bloomberg topic to your own label; labels replace topics in rows, tickers, status, and remove().

blp.subscribe() is the synchronous factory for the same handle. Iteration and unsubscribe() are still asynchronous, so it is mainly useful in notebooks (where top-level await works) and for rows=False boards read with latest().

Updates are deltas ​

Subscription rows carry only what changed.

  • In dict ticks, a missing key means unchanged; a key whose value is None means Bloomberg explicitly cleared the field.
  • In Arrow output, data columns are nullable and the binary __xbbg_present column says which cells are present: bit i (least-significant bit first) marks schema column i + 2, counting after timestamp and topic. A set bit with a null cell is a clear; an unset bit means unchanged. Schema metadata key xbbg.subscription_presence documents the encoding.
  • all_fields=True layouts can grow or change type, so read each batch's current schema.

Use latest() when you want complete current values instead of deltas.

Shared feeds ​

Within one engine, //blp/mktdata subscriptions to the same security with the same options share one Bloomberg subscription that requests the union of their fields.

  • A subscription that joins an existing feed immediately receives one SUMMARY/INITPAINT row built from the feed's current values.
  • Requesting fields the feed lacks (a new subscription, add(), or add_fields()) re-subscribes the feed once. The requesting subscription receives Bloomberg's full repaint; subscriptions that already had the image get one row only if the repaint changed one of their fields.
  • Filtered subscriptions only see their own fields, so their output does not depend on who else shares the feed. all_fields=True subscriptions also see fields other subscriptions requested.
  • A subscription that only joins existing feeds uses no extra subscription session.
  • isolated=True keeps a subscription on its own feeds and session.
  • vwap, mktbar, depth, chains, and other non-//blp/mktdata services are never shared.

blp.subscription_feeds() (or Engine.subscription_feeds() for a scoped engine) returns one dict per live feed with service, topic, options, fields (the union), consumers, delayed, state, isolated, and field_errors.

Current values and boards ​

sub.latest() returns one row per security: topic (your label), last_update (UTC), live (a non-initial update has arrived), delayed, and the current value of each projected field. Column types come from Bloomberg's field metadata at subscribe time, so the table is typed before values arrive. After the subscription ends, latest() raises.

With rows=False the subscription keeps only current values: nothing is queued, so a board you only poll cannot overflow, and iterating it raises RuntimeError.

python
import asyncio

from xbbg import blp

async def main():
    board = await blp.asubscribe(
        ['AAPL US Equity', 'MSFT US Equity'],
        ['LAST_PRICE', 'BID', 'ASK'],
        rows=False,
        zero_as_null=['BID', 'ASK'],
    )
    try:
        for _ in range(3):
            await asyncio.sleep(5)
            print(board.latest(backend='pandas'))
    finally:
        await board.unsubscribe()

asyncio.run(main())

zero_as_null shows 0 as missing in latest() for the listed fields; rows keep the raw values. If Bloomberg reports DATALOSS on a rows=False subscription, xbbg re-subscribes the feed: live turns false, a DataLoss event is recorded, and a FeedRecovered event follows once the image is rebuilt.

Delayed data and rejected fields ​

Bloomberg marks delayed streams with IS_DELAYED_STREAM. xbbg reads it for every subscription and records it in sub.topic_states[label]['delayed'].

on_delayedBehavior
'warn' (default)One BlpDelayedDataWarning per delayed security
'raise'Fail that security; the others keep streaming
'ignore'Record the flag only

Fields Bloomberg rejects when the subscription starts (for example static-only PX_BID) are listed in sub.field_errors (label → field → error category) instead of silently staying empty.

on_field_errorBehavior
'warn' (default)One BlpFieldWarning
'raise'Fail the securities that requested the rejected field
'ignore'Record in field_errors only

To check delayed status without subscribing, use delay_status() or on_delayed= on requests; see Entitlements and Delayed Data.

Failures and data loss ​

  • Per-security failures are isolated. An invalid or terminated security lands in failed_tickers and failures; healthy securities keep streaming, and is_active stays True while any security is healthy. all_failed turns True when every security has failed.
  • Continuity gaps end row streams. Bloomberg DATALOSS, a full drop_newest buffer, or overflow/timeout of the bounded block forwarder ends the stream: data already queued is delivered, then iteration raises BlpSubscriptionDataLossError (with topic and detail; topic='*' means session-wide). Subscribe again for a fresh image before applying further deltas.
  • Session termination fails only the securities on that session; a stream ends with the session error once none of its securities remain. Ordinary connection-down notifications are informational: the SDK recovers subscriptions and records SubscriptionStreamsActivated/SubscriptionStreamsDeactivated events.
python
import asyncio

from xbbg import blp
from xbbg.exceptions import BlpSubscriptionDataLossError

async def consume():
    while True:
        try:
            async with await blp.asubscribe(['AAPL US Equity'], ['LAST_PRICE']) as sub:
                async for table in sub:
                    print(table.to_pylist())
                    if sub.all_failed:
                        print('all securities failed:', sub.failures)
                        return
        except BlpSubscriptionDataLossError as exc:
            print(f'gap on {exc.topic}: {exc.detail}; resubscribing')

asyncio.run(consume())

Tuning ​

ParameterDefaultDescription
flush_thresholdengine subscription_flush_threshold (16)Maximum updates combined into one batch. A read returns as soon as one update is available and adds only updates already waiting, so quiet streams keep one-row batches; forced to 1 with tick_mode=True. Pass flush_threshold=1 if your code assumes one row per batch
stream_capacityengine subscription_stream_capacity (256)Native stream buffer; for stream() also the sync queue size
overflow_policyengine overflow_policy ('drop_newest')'drop_newest' fails the stream when the buffer is full; 'block' waits briefly on a bounded forwarder, then fails; 'drop_oldest' evicts the oldest queued updates and reports the gap (read with sub.deliveries(), below). None of them blocks Bloomberg's callback thread
conflateFalseRequest Bloomberg-conflated quotes on //blp/mktdata; trades are still delivered as received
service, options//blp/mktdata, noneOther subscription services and raw Bloomberg subscription options (asubscribe/subscribe only)

Engine-wide defaults are set with configure(); see Configuration.

Gap-aware delivery and conflated state ​

Since 1.8.0, two opt-in modes trade the strict "fail on any gap" contract for explicit gap reporting. Both are read through sub.deliveries(), an async iterator of SubscriptionDelivery envelopes, instead of plain iteration:

  • overflow_policy='drop_oldest' keeps the newest deltas when the consumer falls behind and marks the envelope that follows a local eviction with gap_before (a SubscriptionGap with dropped_updates and cause='local_overflow'). Bloomberg DATALOSS stays terminal.
  • delivery='state' delivers conflated current images: each envelope's data holds complete rows with a Boolean valid column, and rows that are not current values are marked invalid instead of ending the stream. State mode cannot be combined with rows=False.
python
import asyncio

from xbbg import blp

async def main():
    sub = await blp.asubscribe(
        ['AAPL US Equity', 'MSFT US Equity'],
        ['LAST_PRICE', 'BID', 'ASK'],
        delivery='state',
    )
    try:
        async for delivery in sub.deliveries(backend='pandas'):
            if delivery.gap_before is not None:
                print('gap of', delivery.gap_before.dropped_updates, 'updates')
            print(delivery.kind, delivery.data)
            break
    finally:
        await sub.unsubscribe()

asyncio.run(main())

astream() and stream() accept the same delivery and overflow_policy values and then yield SubscriptionDelivery envelopes. sub.delivery reports the selected mode and sub.requires_deliveries whether the subscription must be read through deliveries(). The specialized services below also take delivery=.

Specialized services ​

All of these return a Subscription and have a sync factory without the a prefix. Unlike asubscribe(), their backend=None falls back to the global set_backend() default.

python
import asyncio

from xbbg import blp

async def main():
    # //blp/mktvwap: VWAP with an optional calculation window
    vwap = await blp.avwap(['IBM US Equity'], start_time='09:30', end_time='16:00')

    # //blp/mktbar: streaming OHLC bars, bar_size in minutes (1-1440)
    bars = await blp.amktbar('ES1 Index', bar_size=5)

    for sub in (vwap, bars):
        async for table in sub:
            print(table.to_pylist())
            break
        await sub.unsubscribe()

asyncio.run(main())
HelperServiceNotes
avwap(tickers, *, start_time=None, end_time=None, raw=False, all_fields=True, backend=None)//blp/mktvwapRequests the VWAP field; all_fields=True returns the full VWAP payload
amktbar(tickers, *, bar_size=1, start_time=None, end_time=None, raw=False, all_fields=True, backend=None)//blp/mktbarSUBSCRIPTION_DATA carries the bar message type (MarketBarStart, MarketBarUpdate, MarketBarEnd)
adepth(tickers, *, raw=False, all_fields=False, backend=None)//blp/mktdepthdataLevel 2 order book; requires B-PIPE and entitlements, otherwise BlpBPipeError
achains(underlying, *, chain_type='OPTIONS', raw=False, all_fields=False, backend=None)//blp/mktlistchain_type='OPTIONS' or 'FUTURES'; requires B-PIPE, otherwise BlpBPipeError

Health and observability ​

Every property is safe to read while iterating.

PropertyContents
sub.tickers, sub.fieldsActive labels and subscribed fields
sub.is_active, sub.all_failedSubscription state
sub.topic_statesPer label: state, last_change_us, delayed, feed_topic
sub.failed_tickers, sub.failuresRejected or terminated securities; failures carry ticker, reason, kind ('failure' or 'terminated')
sub.field_errorsRejected fields by label
sub.eventsBounded history: at_us, category, level, message_type, topic, detail (including DataLoss/FeedRecovered)
sub.session_status, sub.admin_status, sub.service_statusSession, slow-consumer, and service availability status
sub.statusAll of the above combined in one dict
sub.statsmessages_received, dropped_batches, batches_sent, slow_consumer, data_loss_events, last_message_us, last_data_loss_us, effective_overflow_policy
python
from xbbg import blp

async def report(sub):
    for label, state in sub.topic_states.items():
        print(label, state['state'], 'delayed' if state['delayed'] else 'real-time')
    for event in sub.events[-5:]:
        print(event['level'], event['message_type'], event['topic'], event['detail'])
    print(sub.stats['messages_received'], blp.subscription_feeds())

Recording a stream ​

Bloomberg keeps no history for many real-time fields. To keep a stream, write raw batches to Parquet and keep __xbbg_present, starting a new file whenever the schema changes. The Exchange Auctions guide has a complete recorder.

See also ​

xbbg is independent open-source software and is not affiliated with, endorsed by, sponsored by, or approved by Bloomberg Finance L.P.