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:
objectThis 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).
- 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:
Data received from the server.
Field is not required.
Default: prints the data.
on_error (function) –
Called when a error occurs.
- Arguments:
Exception object.
Field is not required.
Default: prints the error.
on_close (function) –
Called when connection is closed.
- Arguments:
close_status_code.
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.
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:
objectThis 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:
Connect via
run()— the server immediately sends amessageevent with the assignedclientId.Call
subscribe()with filter settings to start receiving live broadcasts. The server replies with a subscription confirmation followed by alatest-newssnapshot.New matching news items are pushed as
broadcastevents via theon_messagecallback.Call
unsubscribe()to stop broadcasts without closing the connection.A
pingheartbeat is sent by the server every 30 seconds to keep the connection alive.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-filtersevent 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).
- 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-newsevent 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.
viewevents trigger incremental metrics broadcasts to all clients currently watching metrics viawatch_metrics().The server responds with a
post-metricsacknowledgement 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 forviewevents. 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
messageevent containing the server-assignedclientId. Usesubscribe()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:
Data received from the server (JSON string).
Field is not required. Default: prints the data.
on_error (function) –
Called when an error occurs. Arguments:
Exception object.
Field is not required. Default: prints the error.
on_close (function) –
Called when the connection is closed. Arguments:
close_status_code.
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-newssnapshot of recent matching news. Subsequent matching news items will be pushed asbroadcastevents.- 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).
- 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-metricsevent containing the full view-count snapshot for the current session. Subsequent view-count changes are pushed automatically asincremental-watch-metricsevents.
btgsolutions_dataservices.websocket.market_data_feed module
- class btgsolutions_dataservices.websocket.market_data_feed.LogConstFilter(consts)[source]
Bases:
Filter
- 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:
objectWebSocket 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:
Data received from the server.
Field is not required.
Default: prints the data.
on_error (function) –
Called when a error occurs.
- Arguments:
Exception object.
Field is not required.
Default: prints the error.
on_close (function) –
Called when connection is closed.
- Arguments:
close_status_code.
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’.
- get_last_event(ticker: str)[source]
Get the last event for the provided ticker.
- Parameters:
ticker (str) – Field is required.
- 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
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:
objectThis 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).
- 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.
- get_last_event(ticker: str)[source]
Get the last event for the provided ticker.
- Parameters:
ticker (str) – Field is required.
- 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:
Data received from the server.
Field is not required.
Default: prints the data.
on_error (function) –
Called when a error occurs.
- Arguments:
Exception object.
Field is not required.
Default: prints the error.
on_close (function) –
Called when connection is closed.
- Arguments:
close_status_code.
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.
- 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