Callback Streaming
A convenient wrapper around the Streaming API
IMPORTANT Polygon.io allows one simultaneous connection to one cluster at a time (clusters: stocks, options, forex, crypto). which means 4 total concurrent streams (Of course you need to have subscriptions for them).
Connecting to a cluster which already has an existing stream connected to it would result in existing connection getting dropped and new connection would be established
Note that This page describes the callback based streaming client. If you’re looking for async based streaming client, See Async Streaming
Also note that callback based streamer is supposed to get a builtin functionality to reconnect in the library. Async streamer has it already. It’s on TODO for this client. Have a reconnect mechanism to share? Share in discussions or on the wiki.
Creating the client
Creating a client is just creating an instance of polygon.StreamClient
. Note that this expects a few arguments where most of them have default values.
This is how the initializer looks like:
- StreamClient.__init__(api_key: str, cluster, host='socket.polygon.io', on_message=None, on_close=None, on_error=None, enable_connection_logs: bool = False)
Initializes the callback function based stream client Official Docs
- Parameters:
api_key – Your API Key. Visit your dashboard to get yours.
cluster – Which market/cluster to connect to. See
polygon.enums.StreamCluster
for choices. NEVER connect to the same cluster again if there is an existing stream connected to it. The existing connection would be dropped and new one will be established. You can have up to 4 concurrent streams connected to 4 different clusters.host – Host url to connect to. Default is real time. See
polygon.enums.StreamHost
for choices.on_message – The function to be called when data is received. This is primary function you’ll write to process the data from the stream. The function should accept one and only one
arg
(message). Default handler is_default_on_msg()
.on_close – The function to be called when stream is closed. Function should accept two args ( close_status_code, close_message). Default handler is
_default_on_close()
on_error – Function to be called when an error is encountered. Function should accept one arg ( exception object). Default handler is
_default_on_error()
enable_connection_logs – whether to print debug info related to the stream connection. Helpful for debugging.
Example use:
import polygon
stream_client = polygon.StreamClient('KEY', 'stocks', on_message=my_own_handler_function) # in the simplest form
Note that you don’t have to call login methods as the library does it internally itself.
Starting the Stream
Once you have a stream client, you can start the stream thread by calling the method: start_stream_thread
.
This method has default values which should be good enough for most people. For those who need customization, here is how it looks like:
- StreamClient.start_stream_thread(ping_interval: int = 21, ping_timeout: int = 20, ping_payload: str = '', skip_utf8_validation: bool = True)
Starts the Stream. This will not block the main thread and it spawns the streamer in its own thread.
- Parameters:
ping_interval – client would send a
ping
every specified number of seconds to server to keep connection alive. Set to 0 to disable pinging. Defaults to 21 secondsping_timeout – Timeout in seconds if a
pong
(response to ping from server) is not received. The Stream is terminated as it is considered to be dead if no pong is received within the specified timeout. default: 20 secondsping_payload – The option message to be sent with the ping. Better to leave it empty string.
skip_utf8_validation – Whether to skip utf validation of messages. Defaults to True. Setting it to False may result in performance downgrade
- Returns:
None
Example use:
import polygon
stream_client = polygon.StreamClient('KEY', 'stocks', on_message=my_own_handler_function)
stream_client.start_stream_thread()
# subscriptions here.
Important Concepts
Important stuff to know before you connect your first stream. Note that when writing applications, you should create the client and start the stream thread before subscribing.
Subscribing/Unsubscribing to Streams
All subscription methods have names in pattern subscribe_service_name
and unsubscribe_service_name
(listed below)
Symbols names must be specified as a list of symbols: ['AMD', 'NVDA', 'LOL']
is the correct way to specify symbols.
Not specifying a list of symbols results in the action being applied to ALL
tickers in that service.
Note that either of []
, None
, ['*']
or 'all'
as value of symbols would also results in ALL tickers.
The library allows specifying a string for symbol argument (that string is sent exactly as it is without processing), but only do that if you have the absolute need to. Most people should just specify a list. Note that a list of single ticker is accepted.
Options and Crypto stream endpoints expect prefixes ``O:, X:`` respectively in front of every ticker. The library handles this for you so you can pass symbols with or without those prefixes.
By default, the library will also enforce upper case for all symbols being passed. To disable this enforcement, just
pass in force_uppercase_symbols=False
when subscribing in the methods below.
Handling messages
Your handler function should accept two arguments. You can ignore the first argument which is going to be the websocket instance itself. The second argument is the actual message.
In callback streaming, the library can’t do the json decoding for you internally, and you will always receive a raw string as received from the websocket server.
messages). You will have to do json decoding
yourself.
def sample_handler(ws, msg):
print(msg) # here msg is the raw string which contains the msg. to convert it to a list/dict, it needs to be decoded.
# DECODING the msg from string to list/dict
# ensure you have 'import json' at the top of file in imports
msg = json.loads(msg) # now msg is a python object which you can use easily to access data from.
Once you have the message in your callback handler function, you can process it the way you want. print it out, write it to a file, push it to a redis queue, write to a database, offload to a multi-threaded queue. Just whatever.
The default handler for the messages is _default_on_msg
which does some checks on messages having event as status
. and prints out other messages.
Messages from polygon having the key ev
equal to status
are status updates from polygon about login and relevant actions you take (ev indicates event)
The data messages will have different ev
value than the string ‘status’. The ev values for those would match the polygon.enums.StreamServicePrefix
values.
You can specify your own handlers for other callbacks (on_error
, on_close
etc) too or leave those to defaults.
if you choose to override default handlers for on_error
and on_close
, here is how they need to be written
on_error
handler must accept two arguments. You can ignore the first argument which is just the websocket instance itself. The second argument is going to be the actual error
def sample_error_handler(ws, error):
print(error)
on_close
handler must accept three arguments. you can ignore the first arg which is just the websocket instance itself. The second arg is close code, and third would be the
close message. note that this handler is only called when the stream is being closed.
def sample_close_handler(ws, close_code, close_msg):
print(f'Stream close with code: {close_code} || msg: {close_msg}')
Closing Stream
To turn off the streamer and shut down the websockets connection gracefully, it is advised to call stream_client.close_stream()
method
when closing the application. Not an absolute necessity but a good software practice.
Streams
Stocks Streams
Stock Trades
- StreamClient.subscribe_stock_trades(symbols: list | None = None, force_uppercase_symbols: bool = True)
Stream real-time trades for given stock ticker symbol(s).
- Parameters:
symbols – A list of tickers. Default is
*
which subscribes to ALL tickers in the marketforce_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- StreamClient.unsubscribe_stock_trades(symbols: list | None = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
Stock Quotes
- StreamClient.subscribe_stock_quotes(symbols: list | None = None, force_uppercase_symbols: bool = True)
Stream real-time Quotes for given stock ticker symbol(s).
- Parameters:
symbols – A list of tickers. Default is * which subscribes to ALL tickers in the market
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- StreamClient.unsubscribe_stock_quotes(symbols: list | None = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
Stock Minute Aggregates (OCHLV)
- StreamClient.subscribe_stock_minute_aggregates(symbols: list | None = None, force_uppercase_symbols: bool = True)
Stream real-time minute aggregates for given stock ticker symbol(s).
- Parameters:
symbols – A list of tickers. Default is * which subscribes to ALL tickers in the market
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- StreamClient.unsubscribe_stock_minute_aggregates(symbols: list | None = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
Stock Second Aggregates (OCHLV)
- StreamClient.subscribe_stock_second_aggregates(symbols: list | None = None, force_uppercase_symbols: bool = True)
Stream real-time second aggregates for given stock ticker symbol(s).
- Parameters:
symbols – A list of tickers. Default is * which subscribes to ALL tickers in the market
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- StreamClient.unsubscribe_stock_second_aggregates(symbols: list | None = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
Stock Limit Up Limit Down (LULD)
- StreamClient.subscribe_stock_limit_up_limit_down(symbols: list | None = None, force_uppercase_symbols: bool = True)
Stream real-time LULD events for given stock ticker symbol(s).
- Parameters:
symbols – A list of tickers. Default is * which subscribes to ALL tickers in the market
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- StreamClient.unsubscribe_stock_limit_up_limit_down(symbols: list | None = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
Stock Imbalances
- StreamClient.subscribe_stock_imbalances(symbols: list | None = None, force_uppercase_symbols: bool = True)
Stream real-time Imbalance Events for given stock ticker symbol(s).
- Parameters:
symbols – A list of tickers. Default is * which subscribes to ALL tickers in the market
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- StreamClient.unsubscribe_stock_imbalances(symbols: list | None = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
Options Streams
Options Trades
- StreamClient.subscribe_option_trades(symbols: list | None = None, force_uppercase_symbols: bool = True)
Stream real-time Options Trades for given Options contract.
- Parameters:
symbols – A list of symbols. Default is * which subscribes to ALL symbols in the market. you can pass with or without the prefix
O:
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- StreamClient.unsubscribe_option_trades(symbols: list | None = None)
Unsubscribe real-time Options Trades for given Options contract.
- Parameters:
symbols – A list of symbols. Default is * which subscribes to ALL symbols in the market. you can pass with or without the prefix
O:
- Returns:
None
Options Quotes
- StreamClient.subscribe_option_quotes(symbols: list | None = None, force_uppercase_symbols: bool = True)
Stream real-time Options Quotes for given Options contract.
- Parameters:
symbols – A list of symbols. Default is * which subscribes to ALL symbols in the market. you can pass with or without the prefix
O:
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- StreamClient.unsubscribe_option_quotes(symbols: list | None = None)
Unsubscribe real-time Options Quotes for given Options contract.
- Parameters:
symbols – A list of symbols. Default is * which subscribes to ALL symbols in the market. you can pass with or without the prefix
O:
- Returns:
None
Options Minute Aggregates (OCHLV)
- StreamClient.subscribe_option_minute_aggregates(symbols: list | None = None, force_uppercase_symbols: bool = True)
Stream real-time Options Minute Aggregates for given Options contract(s).
- Parameters:
symbols – A list of symbols. Default is * which subscribes to ALL tickers in the market. you can pass with or without the prefix
O:
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- StreamClient.unsubscribe_option_minute_aggregates(symbols: list | None = None)
Unsubscribe real-time Options Minute aggregates for given Options contract.
- Parameters:
symbols – A list of symbols. Default is * which subscribes to ALL symbols in the market. you can pass with or without the prefix
O:
- Returns:
None
Options Second Aggregates (OCHLV)
- StreamClient.subscribe_option_second_aggregates(symbols: list | None = None, force_uppercase_symbols: bool = True)
Stream real-time Options Second Aggregates for given Options contract(s).
- Parameters:
symbols – A list of symbols. Default is * which subscribes to ALL tickers in the market. you can pass with or without the prefix
O:
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- StreamClient.unsubscribe_option_second_aggregates(symbols: list | None = None)
Unsubscribe real-time Options Second Aggregates for given Options contract.
- Parameters:
symbols – A list of symbols. Default is * which subscribes to ALL symbols in the market. you can pass with or without the prefix
O:
- Returns:
None
Forex Streams
Forex Quotes
- StreamClient.subscribe_forex_quotes(symbols: list | None = None, force_uppercase_symbols: bool = True)
Stream real-time forex quotes for given forex pair(s).
- Parameters:
symbols – A list of forex tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from/to
. For example:USD/CNH
.force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- StreamClient.unsubscribe_forex_quotes(symbols: list | None = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
- Parameters:
symbols – A list of forex tickers. Default is * which unsubscribes to ALL tickers in the market. each Ticker must be in format:
from/to
. For example:USD/CNH
.
Forex Minute Aggregates (OCHLV)
- StreamClient.subscribe_forex_minute_aggregates(symbols: list | None = None, force_uppercase_symbols: bool = True)
Stream real-time forex Minute Aggregates for given forex pair(s).
- Parameters:
symbols – A list of forex tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from/to
. For example:USD/CNH
.force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- StreamClient.unsubscribe_forex_minute_aggregates(symbols: list | None = None)
Unsubscribe from the stream service for the symbols specified. Defaults to all symbols.
- Parameters:
symbols – A list of forex tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from/to
. For example:USD/CNH
.
Crypto Streams
Crypto Trades
- StreamClient.subscribe_crypto_trades(symbols: list | None = None, force_uppercase_symbols: bool = True)
Stream real-time Trades for given cryptocurrency pair(s).
- Parameters:
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- StreamClient.unsubscribe_crypto_trades(symbols: list | None = None)
Unsubscribe real-time trades for given cryptocurrency pair(s).
- Parameters:
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
- Returns:
None
Crypto Quotes
- StreamClient.subscribe_crypto_quotes(symbols: list | None = None, force_uppercase_symbols: bool = True)
Stream real-time Quotes for given cryptocurrency pair(s).
- Parameters:
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- StreamClient.unsubscribe_crypto_quotes(symbols: list | None = None)
Unsubscribe real-time quotes for given cryptocurrency pair(s).
- Parameters:
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
- Returns:
None
Crypto Minute Aggregates (OCHLV)
- StreamClient.subscribe_crypto_minute_aggregates(symbols: list | None = None, force_uppercase_symbols: bool = True)
Stream real-time Minute Aggregates for given cryptocurrency pair(s).
- Parameters:
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- StreamClient.unsubscribe_crypto_minute_aggregates(symbols: list | None = None)
Unsubscribe real-time minute aggregates for given cryptocurrency pair(s).
- Parameters:
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
- Returns:
None
Crypto Level 2 Book
- StreamClient.subscribe_crypto_level2_book(symbols: list | None = None, force_uppercase_symbols: bool = True)
Stream real-time level 2 book data for given cryptocurrency pair(s).
- Parameters:
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
force_uppercase_symbols – Set to
False
if you don’t want the library to make all symbols upper case
- Returns:
None
- StreamClient.unsubscribe_crypto_level2_book(symbols: list | None = None)
Unsubscribe real-time level 2 book data for given cryptocurrency pair(s).
- Parameters:
symbols – A list of Crypto tickers. Default is * which subscribes to ALL tickers in the market. each Ticker must be in format:
from-to
. For example:BTC-USD
. you can pass symbols with or without the prefixX:
- Returns:
None