Skip to content

Async patterns

Same helper shape, real concurrency.

Every request helper has an a-prefixed async counterpart. The async functions are the implementation; the sync helpers run them for you.

Sync and async pairs ​

SyncAsync
bdp, bds, bdhabdp, abds, abdh
bdib, bdtickabdib, abdtick
bql, bsrch, beqs, blkp, bportabql, absrch, abeqs, ablkp, abport
bqr, bcurves, bgovts, bfldsabqr, abcurves, abgovts, abflds
bta, bops, bschemaabta, abops, abschema
requestarequest
delay_status, seat_type, check_entitlements, identity_is_authorizedadelay_status, aseat_type, acheck_entitlements, aidentity_is_authorized
subscribe, streamasubscribe, astream

xbbg.ext follows the same convention (dividend/adividend, yas/ayas, ...). Async functions take the same arguments and return the same result types as their sync counterparts.

Scripts ​

python
import asyncio

from xbbg import blp

async def main():
    return await blp.abdp(tickers='AAPL US Equity', flds=['PX_LAST', 'VOLUME'])

data = asyncio.run(main())

Concurrent requests ​

asyncio.gather() sends requests together; the engine spreads them across its request workers.

python
import asyncio

from xbbg import blp

async def main():
    return await asyncio.gather(
        blp.abdp(tickers='AAPL US Equity', flds=['PX_LAST']),
        blp.abdp(tickers='MSFT US Equity', flds=['PX_LAST']),
        blp.abdh(tickers='GOOGL US Equity', flds=['PX_LAST'], start_date='2024-01-01'),
    )

apple, microsoft, alphabet = asyncio.run(main())

With the default request_pool_size=2, two requests run at once and the third waits for a free worker. Raise the pool size before the first request to increase the ceiling:

python
import xbbg

xbbg.configure(request_pool_size=4)

Wide multi-security bdp/bdh requests can also be split into concurrent shards by the engine; see Request Options.

Notebooks ​

In Jupyter, VS Code Interactive, and marimo the notebook already runs an event loop. Every sync helper detects this and runs through a background loop managed by xbbg, so ordinary calls keep working:

python
from xbbg import blp

df = blp.bdp(tickers='AAPL US Equity', flds=['PX_LAST', 'VOLUME'])
result = blp.bql("get(px_last) for('AAPL US Equity')")

Top-level await works too:

python
from xbbg import blp

df = await blp.abdp(tickers='AAPL US Equity', flds=['PX_LAST', 'VOLUME'])

WARNING

The bridge is only for notebooks. Inside any other running event loop — FastAPI and other ASGI apps, async workers — sync helpers raise RuntimeError naming the async function to use instead. Call the a-prefixed functions there.

Scoped engines (with xbbg.Engine(...)) carry over into the bridge, and exceptions propagate back to the cell.

Waiting without holding the GIL ​

The native engine performs Bloomberg I/O on its own runtime threads, so awaiting a request does not hold the Python GIL: other Python threads and tasks keep running while requests are in flight.

Errors in concurrent code ​

asyncio.gather() cancels the remaining awaitables and re-raises the first exception. Pass return_exceptions=True to collect results and errors together:

python
import asyncio

from xbbg import blp
from xbbg.exceptions import BlpError

async def fetch_all(tickers: list[str]):
    results = await asyncio.gather(
        *(blp.abdp(tickers=t, flds=['PX_LAST']) for t in tickers),
        return_exceptions=True,
    )
    for ticker, result in zip(tickers, results):
        if isinstance(result, BlpError):
            print(f'failed: {ticker}: {result}')
        elif isinstance(result, BaseException):
            raise result
        else:
            print(f'ok: {ticker}, rows={len(result)}')

asyncio.run(fetch_all(['AAPL US Equity', 'INVALID US Equity', 'MSFT US Equity']))

The exception classes and their attributes are described in Errors and Warnings.

Best practices ​

  • Batch securities in one call. abdp() and abdh() take lists; one request for many securities is cheaper than many parallel single-security requests. Use gather() for genuinely different requests (fields, dates, services).
  • Use the async API in async applications. It participates in the event loop instead of blocking it.
  • Size the pool deliberately. Bloomberg servers also limit concurrent requests per connection, so measure before raising request_pool_size far.
  • Bound long requests. There is no request deadline by default; set request_timeout_ms if a service must not wait indefinitely (Configuration).

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