Skip to content

Commit

Permalink
Fix streaming news article event dispatching. (#691)
Browse files Browse the repository at this point in the history
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](alpacahq/alpaca-trade-api-csharp@be67b62) for the C# library.)
  • Loading branch information
fumoboy007 authored Mar 27, 2023
1 parent dc3cf7a commit 5c2d74a
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions alpaca_trade_api/stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down

0 comments on commit 5c2d74a

Please sign in to comment.