btgsolutions_dataservices.websocket package

Submodules

btgsolutions_dataservices.websocket.broker_analytics module

class btgsolutions_dataservices.websocket.broker_analytics.BrokerAnalyticsWebSocketClient(api_key: str, ssl: bool | None = True, **kwargs)[source]

Bases: object

This class connects with BTG Solutions Data Services Broker Analytics WebSocket, receiving broker analytics events (top tickers by broker and top brokers by ticker).

  • Main use case:

>>> from btgsolutions_dataservices import BrokerAnalyticsWebSocketClient
>>> ws = BrokerAnalyticsWebSocketClient(
>>>     api_key='YOUR_API_KEY',
>>>     ssl=True
>>> )
>>> ws.run()
>>> ws.available_tickers()
>>> ws.available_brokers()
>>> ws.subscribe_top_tickers(n=10, brokers=['85'])
>>> ws.subscribe_top_brokers(n=5)
>>> ws.subscribed_to()
>>> ws.get_last_event(analytics_type='top_tickers', n=3, brokers=['85', '3'])
>>> ws.get_last_event(analytics_type='top_brokers', n=5)
>>> ws.unsubscribe_top_tickers(brokers=['85'])
>>> ws.unsubscribe_top_brokers()
>>> ws.close()
Parameters:
  • api_key (str) – User identification key. Field is required.

  • ssl (bool) – Enable or disable ssl configuration. Field is not required. Default: True (enable).

available_brokers()[source]

Returns available brokers.

available_tickers()[source]

Returns available tickers.

close()[source]

Closes connection with websocket.

get_last_event(analytics_type: str | None = None, n: int | None = None, brokers: List[str] | None = None, tickers: List[str] | None = None)[source]

Returns latest broker analytics event.

Parameters:
  • analytics_type (str) – Analytics type. Options: ‘top_tickers’ or ‘top_brokers’. Field is not required.

  • n (int) – Number of results. Field is not required.

  • brokers (list) – Broker ids filter. Field is not required.

  • tickers (list) – Ticker symbols filter. Field is not required.

run(on_open=None, on_message=None, on_error=None, on_close=None, reconnect=True)[source]

Initializes a connection to websocket and starts to receive Broker Analytics events.

Parameters:
  • on_open (function) –

    • Called at opening connection to websocket.

    • Field is not required.

    • Default: prints that the connection was opened in case of success.

  • on_message (function) –

    • Called every time it receives a message.

    • Arguments:
      1. Data received from the server.

    • Field is not required.

    • Default: prints the data.

  • on_error (function) –

    • Called when a error occurs.

    • Arguments:
      1. Exception object.

    • Field is not required.

    • Default: prints the error.

  • on_close (function) –

    • Called when connection is closed.

    • Arguments:
      1. close_status_code.

      2. close_msg.

    • Field is not required.

    • Default: prints a message that the connection was closed.

  • reconnect (bool) – Try reconnect if connection is closed. Field is not required. Default: True.

subscribe_top_brokers(n: int = 5, tickers: List[str] | None = None)[source]

Subscribes to top brokers by ticker.

Parameters:
  • n (int) – Number of results. Field is not required. Default: 5.

  • tickers (list) – Ticker symbols filter. Field is not required.

subscribe_top_tickers(n: int = 10, brokers: List[str] | None = None)[source]

Subscribes to top tickers by broker.

Parameters:
  • n (int) – Number of results. Field is not required. Default: 10.

  • brokers (list) – Broker ids filter. Field is not required.

subscribed_to()[source]

Returns current subscriptions.

unsubscribe_top_brokers(tickers: List[str] | None = None)[source]

Unsubscribes from top brokers by ticker.

Parameters:

tickers (list) – Ticker symbols filter. Field is not required.

unsubscribe_top_tickers(brokers: List[str] | None = None)[source]

Unsubscribes from top tickers by broker.

Parameters:

brokers (list) – Broker ids filter. Field is not required.

btgsolutions_dataservices.websocket.hfn_websocket_client module

class btgsolutions_dataservices.websocket.hfn_websocket_client.HFNWebSocketClient(api_key: str, ssl: bool | None = True, **kwargs)[source]

Bases: object

This class connects with the BTG Solutions Data Services HFN WebSocket, providing a bidirectional real-time news stream with rich subscription filters, on-demand queries, and reader engagement metrics.

Lifecycle:

  1. Connect via run() — the server immediately sends a message event with the assigned clientId.

  2. Call subscribe() with filter settings to start receiving live broadcasts. The server replies with a subscription confirmation followed by a latest-news snapshot.

  3. New matching news items are pushed as broadcast events via the on_message callback.

  4. Call unsubscribe() to stop broadcasts without closing the connection.

  5. A ping heartbeat is sent by the server every 30 seconds to keep the connection alive.

  6. All connections are terminated daily at midnight (America/Sao_Paulo).

  • Main use case:

>>> from btgsolutions_dataservices import HFNWebSocketClient
>>> ws = HFNWebSocketClient(
>>>     api_key='YOUR_API_KEY',
>>> )
>>> ws.run()
>>> # Subscribe to live economy news in Portuguese
>>> ws.subscribe(settings={'feed': 'economy', 'text_language': 'portuguese'})
>>> # Request latest news on demand (without subscribing)
>>> ws.latest_news(settings={'feed': 'crypto', 'limit': '10'})
>>> # Retrieve available filter values
>>> ws.available_filters()
>>> # Stop receiving broadcasts (keeps connection open)
>>> ws.unsubscribe()
>>> ws.close()
Parameters:
  • api_key (str) – User identification key. Field is required.

  • ssl (bool) – Enable or disable SSL verification. Field is not required. Default: True (enabled).

available_filters(settings: Dict[str, Any] | None = None)[source]

Request all distinct filter values currently available in the cache. The server responds with an available-filters event listing each filter dimension and its distinct available values.

Parameters:

settings (dict) – Optional narrowing filters. All fields are optional. Accepts the same keys as latest_news() settings. Field is not required. Default: {} (returns all available filter values).

close()[source]

Closes the connection with the WebSocket.

latest_news(settings: Dict[str, Any] | None = None)[source]

Fetch a batch of news items matching the given filters on demand, without subscribing to a live stream. The server responds with a latest-news event containing the matching items.

Parameters:

settings (dict) –

Query parameters for the news request. All fields are optional. Accepted keys:

  • countries (list of str): Filter by country codes. Example: ['BR'].

  • source_type (str): Filter by ingestion source type. Values: 'rss', 'html', 'pdf'.

  • source (str): Filter by a specific source name.

  • feed (str): Filter by thematic feed. Values: 'politics', 'economy', 'crypto', 'technology', 'sports', 'health', 'commodities', 'energy', 'general'.

  • text_language (str): Filter by content language.

  • start_date (str): ISO 8601 start datetime filter (inclusive). Example: '2025-01-01T00:00:00.000Z'.

  • end_date (str): ISO 8601 end datetime filter (inclusive). Example: '2025-12-31T23:59:59.999Z'.

  • status (str): Filter by pipeline processing status. Values: 'raw', 'ingested', 'processed'.

  • limit (str): Maximum number of results to return (as string). Example: '20'.

  • categories (list of str): Filter by category keywords. Example: ['Petrobras', 'Vale'].

  • text (str): Full-text search filter.

  • tags (list of str): Filter by tag values. Example: ['PETR4', 'VALE3'].

Field is not required. Default: {} (returns latest news without filters).

post_metrics(tracking: Dict[str, Any])[source]

Report a user engagement event for analytics tracking. view events trigger incremental metrics broadcasts to all clients currently watching metrics via watch_metrics().

The server responds with a post-metrics acknowledgement event.

Parameters:

tracking (dict) –

Engagement event record. Required keys:

  • event_type (str): Type of engagement. Values: 'view', 'filter'.

  • origin (str): Application or page that generated the event. Example: 'mobile-app'.

Optional keys:

  • news_id (str): ID of the news item. Required for view events. Example: '664f1a2b3c4d5e6f7a8b9c0d'.

  • session_id (str): Client session identifier for deduplication. Example: 'abc123'.

  • metadata (dict): Arbitrary extra information about the event.

Field is required.

run(on_open=None, on_message=None, on_error=None, on_close=None, reconnect: bool = True)[source]

Initializes a connection to the HFN WebSocket.

Upon successful connection the server sends a message event containing the server-assigned clientId. Use subscribe() afterwards to start receiving live news broadcasts.

Parameters:
  • on_open (function) – Called when the connection is opened. Field is not required. Default: prints a confirmation message.

  • on_message (function) –

    Called every time a message is received from the server. Arguments:

    1. Data received from the server (JSON string).

    Field is not required. Default: prints the data.

  • on_error (function) –

    Called when an error occurs. Arguments:

    1. Exception object.

    Field is not required. Default: prints the error.

  • on_close (function) –

    Called when the connection is closed. Arguments:

    1. close_status_code.

    2. close_msg.

    Field is not required. Default: prints a closure message.

  • reconnect (bool) – Automatically attempt to reconnect if the connection drops. Field is not required. Default: True.

subscribe(settings: Dict[str, Any] | None = None)[source]

Subscribe to live news matching the provided filter settings. The server will immediately send a subscription confirmation followed by a latest-news snapshot of recent matching news. Subsequent matching news items will be pushed as broadcast events.

Parameters:

settings (dict) –

Filter settings that control which news items are broadcast. All fields are optional; omitting a field disables that filter. Accepted keys:

  • countries (list of str): Filter by country codes. Example: ['BR'].

  • source_type (str): Filter by ingestion source type. Values: 'rss', 'html', 'pdf'.

  • source (str): Filter by a specific news source name. Example: 'Exame - Mercado'.

  • feed (str): Filter by thematic feed. Values: 'politics', 'economy', 'crypto', 'technology', 'sports', 'health', 'commodities', 'energy', 'general'.

  • text_language (str): Filter by content language. Values: 'portuguese', 'english', 'spanish', 'german', 'french'.

  • categories (list of str): Filter by category keywords. Example: ['Bitcoin', 'Ethereum'].

  • text (str): Full-text search filter applied to title and content.

Field is not required. Default: {} (no filters — receive all news).

unsubscribe()[source]

Stop receiving live news broadcast events without closing the connection.

watch_metrics()[source]

Start receiving incremental view-count updates for news items seen during the current session. Requires an active subscription (call subscribe() first).

The server responds with a watch-metrics event containing the full view-count snapshot for the current session. Subsequent view-count changes are pushed automatically as incremental-watch-metrics events.

btgsolutions_dataservices.websocket.market_data_feed module

class btgsolutions_dataservices.websocket.market_data_feed.LogConstFilter(consts)[source]

Bases: Filter

filter(record)[source]

Determine if the specified record is to be logged.

Returns True if the record should be logged, or False otherwise. If deemed appropriate, the record may be modified in-place.

class btgsolutions_dataservices.websocket.market_data_feed.MarketDataFeed(api_key: str, stream_type: str | None = 'realtime', exchange: str | None = 'b3', data_type: str | None = 'trades', data_subtype: str | None = None, feed: str | None = 'A', ssl: bool | None = True, reconnect: bool = True, on_open: Callable | None = None, on_message: Callable | None = None, on_error: Callable | None = None, on_close: Callable | None = None, log_level: str = 'DEBUG')[source]

Bases: object

WebSocket client that connects with BTG Solutions Data Services WebSocket servers. The servers streams realtime and delayed market data, such as trades and book events. This is a multiprocessing-based WebSocket client designed for high-performance, scalable message handling applications. It leverages a system of inter-process communication to efficiently separate concerns and prevent the main application thread from blocking during WebSocket operations or message processing.

  • Main use case:

>>> from btgsolutions_dataservices import MarketDataFeed
>>> ws = MarketDataFeed(
>>>     api_key='YOUR_API_KEY',
>>>     stream_type='realtime',
>>>     exchange='b3',
>>>     data_type='trades',
>>>     data_subtype='stocks',
>>>     ssl=True
>>> )
>>> ws.run()
>>> ws.subscribe(['MGLU3'])
>>> ws.unsubscribe(['PETR4'])
>>> ws.close()
Parameters:
  • api_key (str) – User identification key. Field is required.

  • stream_type (str) – Websocket connection feed. Options: ‘realtime’, ‘delayed’. Field is not required. Default: ‘realtime’.

  • exchange (str) – Exchange name. Options: ‘b3’ or ‘bmv’. Field is not required. Default: ‘b3’.

  • data_type (str) – Market Data type. Options: ‘trades’, ‘processed-trades’, ‘books’, ‘indices’, ‘securities’, ‘stoploss’, ‘candles-1S’, ‘candles-1M’, ‘instrument_status’, ‘settlement-price’. Field is not required. Default: ‘trades’.

  • data_subtype (str) – Market Data subtype (when applicable). Options: ‘stocks’, ‘options’, ‘derivatives’. Field is not required. Default: None.

  • feed (str) – Market Data Feed. Options: ‘A’, ‘B’. Field is not required. Default: ‘A’ (enable).

  • ssl (bool) – Enable or disable ssl configuration. Field is not required. Default: True (enable).

  • reconnect (bool) – Try reconnect if connection is closed. Field is not required. Default: True.

  • on_open (function) –

    • Called at opening connection to websocket.

    • Field is not required.

    • Default: prints that the connection was opened in case of success.

  • on_message (function) –

    • Called every time it receives a message.

    • Arguments:
      1. Data received from the server.

    • Field is not required.

    • Default: prints the data.

  • on_error (function) –

    • Called when a error occurs.

    • Arguments:
      1. Exception object.

    • Field is not required.

    • Default: prints the error.

  • on_close (function) –

    • Called when connection is closed.

    • Arguments:
      1. close_status_code.

      2. close_msg.

    • Field is not required.

    • Default: prints a message that the connection was closed.

  • log_level (str) – Log level sets how much information the program will print to the log file. Options: ‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’, ‘CRITICAL’, ‘NOTSET’. ‘DEBUG’ provides the most detailed logs, with verbosity decreasing through each level down to ‘NOTSET’, which disables all logging. Field is not required. Default: ‘DEBUG’.

available_to_subscribe()[source]

Return avaiable tickers to subscribe.

close()[source]

Closes the connection with the websocket server.

get_last_event(ticker: str)[source]

Get the last event for the provided ticker.

Parameters:

ticker (str) – Field is required.

run()[source]

Opens a new connection with the websocket server.

set_instruments(instruments: List[str])[source]
subscribe(list_instruments: List[str], n=None, initial_snapshot: bool = False)[source]

Subscribes a list of instruments.

Parameters:
  • list_instruments (list) – Field is required.

  • n (int) – Field is not required. For books data_type only. Maximum book level. It must be between 1 and 10.

  • initial_snapshot (float) – If True, client receives ticker last event (snapshot) of the provided ticker. Field is not required. Default: False

subscribed_to()[source]

Return client subscribed tickers.

unsubscribe(list_instruments: List[str])[source]

Unsubscribes a list of instruments.

Parameters:

list_instruments (list) – Field is required.

btgsolutions_dataservices.websocket.market_data_websocket_client module

class btgsolutions_dataservices.websocket.market_data_websocket_client.MarketDataWebSocketClient(api_key: str, stream_type: str | None = 'realtime', exchange: str | None = 'b3', data_type: str | None = 'trades', data_subtype: str | None = None, instruments: List[str] | None = [], ssl: bool | None = True, feed: str | None = 'A', **kwargs)[source]

Bases: object

This class connects with BTG Solutions Data Services WebSocket, receiving trade and index data, in real time or delayed.

  • Main use case:

>>> from btgsolutions_dataservices import MarketDataWebSocketClient
>>> ws = MarketDataWebSocketClient(
>>>     api_key='YOUR_API_KEY',
>>>     stream_type='realtime',
>>>     exchange='b3',
>>>     data_type='trades',
>>>     data_subtype='stocks',
>>>     instruments=['PETR4'],
>>>     ssl=True
>>> )
>>> ws.run()
>>> ws.subscribe(['MGLU3'])
>>> ws.unsubscribe(['PETR4'])
>>> ws.close()
Parameters:
  • api_key (str) – User identification key. Field is required.

  • stream_type (str) – Websocket connection feed. Options: ‘realtime’, ‘delayed’. Field is not required. Default: ‘realtime’.

  • exchange (str) – Exchange name. Options: ‘b3’ or ‘bmv’. Field is not required. Default: ‘b3’.

  • data_type (str) – Market Data type. Options: ‘trades’, ‘processed-trades’, ‘books’, ‘indices’, ‘securities’, ‘stoploss’, ‘candles-1S’, ‘candles-1M’, ‘instrument_status’, ‘settlement-price’. Field is not required. Default: ‘trades’.

  • data_subtype (str) – Market Data subtype (when applicable). Options: ‘stocks’, ‘options’, ‘derivatives’. Field is not required. Default: None.

  • instruments (list) – List of tickers or indexes to subscribe. Field is not required. Default: [].

  • ssl (bool) – Enable or disable ssl configuration. Field is not required. Default: True (enable).

  • feed (str) – Market Data Feed. Options: ‘A’, ‘B’. Field is not required. Default: ‘A’ (enable).

available_to_subscribe()[source]

Return avaiable tickers to subscribe.

candle_subscribe(list_instruments: list, candle_type: str)[source]

Subscribes a list of instruments, for partial/closed candle updates.

Parameters:
  • list_instruments (list) – Field is required.

  • candle_type (str) – Field is required.

candle_unsubscribe(list_instruments: list, candle_type: str)[source]

Unsubscribes a list of instruments, for partial/closed candle updates.

Parameters:
  • list_instruments (list) – Field is required.

  • candle_type (str) – Field is required.

clear_stoploss()[source]

Clears client stop loss notifications.

close()[source]

Closes connection with websocket.

get_last_event(ticker: str)[source]

Get the last event for the provided ticker.

Parameters:

ticker (str) – Field is required.

instrument_status(ticker: str)[source]

Returns the instrument latest status.

instrument_status_history(ticker: str)[source]

Returns the latest 10 status of the instrument.

notify_stoploss(instrument_params)[source]

Create a stoploss notification routine on the provided instrument(s).

Parameters:

instrument_params (dict) – Field is required.

run(on_open=None, on_message=None, on_error=None, on_close=None, reconnect=True, spawn_thread: bool = True, default_logs: bool = True)[source]

Initializes a connection to websocket and subscribes to the instruments, if it was passed in the class initialization.

Parameters:
  • on_open (function) –

    • Called at opening connection to websocket.

    • Field is not required.

    • Default: prints that the connection was opened in case of success.

  • on_message (function) –

    • Called every time it receives a message.

    • Arguments:
      1. Data received from the server.

    • Field is not required.

    • Default: prints the data.

  • on_error (function) –

    • Called when a error occurs.

    • Arguments:
      1. Exception object.

    • Field is not required.

    • Default: prints the error.

  • on_close (function) –

    • Called when connection is closed.

    • Arguments:
      1. close_status_code.

      2. close_msg.

    • Field is not required.

    • Default: prints a message that the connection was closed.

  • reconnect (bool) – Try reconnect if connection is closed. Field is not required. Default: True.

  • spawn_thread (bool) – Spawn a new thread for incoming server messages (on_message callback function) Field is not required. Default: True.

  • default_logs (bool) – Default non-required logs, detailing messages sent from the client to the WebSocket server. Field is not required. Default: True.

stoploss_status()[source]

Return client stop loss status.

subscribe(list_instruments, n=None, initial_snapshot: bool = False)[source]

Subscribes a list of instruments.

Parameters:
  • list_instruments (list) – Field is required.

  • n (int) – Field is not required. For books data_type only. Maximum book level. It must be between 1 and 10.

  • initial_snapshot (float) – If True, client receives ticker last event (snapshot) of the provided ticker. Field is not required. Default: False

subscribed_to()[source]

Return client subscribed tickers.

unsubscribe(list_instruments)[source]

Unsubscribes a list of instruments.

Parameters:

list_instruments (list) – Field is required.

btgsolutions_dataservices.websocket.websocket_default_functions module

Module contents