From 5c2d74aa525f1513563e57241ef575bb6d363aaf Mon Sep 17 00:00:00 2001 From: fumoboy007 <2100868+fumoboy007@users.noreply.github.com> Date: Mon, 27 Mar 2023 12:51:44 -0700 Subject: [PATCH] Fix streaming news article event dispatching. (#691) News article events are different from other types of events (e.g. stock trades) because a single news article could be applicable to multiple symbols. For that reason, the streamed event does not have the usual `S` field that contains a single symbol; instead, the event has a `symbols` field that contains a list of symbols. #555 mistakenly assumes that the event has an `S` field. This commit changes the dispatching logic to instead use the `symbols` field. (There is a similar [commit](https://github.com/alpacahq/alpaca-trade-api-csharp/commit/be67b62d0225551c828c8a1ed5985a7e760c8acd) for the C# library.) --- alpaca_trade_api/stream.py | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/alpaca_trade_api/stream.py b/alpaca_trade_api/stream.py index afb3e37b..3376fa4c 100644 --- a/alpaca_trade_api/stream.py +++ b/alpaca_trade_api/stream.py @@ -565,12 +565,20 @@ def _cast(self, msg_type, msg): async def _dispatch(self, msg): msg_type = msg.get('T') - symbol = msg.get('S') if msg_type == 'n': - handler = self._handlers['news'].get( - symbol, self._handlers['news'].get('*', None)) - if handler: - await handler(self._cast(msg_type, msg)) + symbols = msg.get('symbols', []) + # A news article could be unrelated to any symbols, resulting in an empty symbols list. Those news articles + # should still be dispatched to the wildcard event handler. + if not symbols: + symbols.append('*') + + for symbol in symbols: + handler = self._handlers['news'].get(symbol) + if handler is None: + handler = self._handlers['news'].get('*') + + if handler is not None: + await handler(self._cast(msg_type, msg)) else: await super()._dispatch(msg)