Start a Market Data Stream
Example Code
#!/usr/bin/env python3
import asyncio
from datetime import datetime
import requests
import sys
import websockets
import Tokens #Tokens stored separately for security
# Tokens stored separately for security
API_TOKEN = Tokens.API_TOKEN
TEST_TOKEN = Tokens.TEST_TOKEN
# Potential lists of equities to track
TOP10 = '["AAPL","MSFT","NVDA","AMZN","META","GGOGL","GOOG","BRK.B","LLY","AVGO"]'
TOP15 = '["AAPL","MSFT","NVDA","AMZN","META","GGOGL","GOOG","BRK.B","LLY","AVGO","TSLA", "JPM","UNH","XOM","V"]'
SINGLE = '["SPCX"]'
async def reconnect():
timestamp = 0
while(True):
if isinstance(timestamp, datetime):
delta = (datetime.now() - timestamp)
if (timestamp == 0 or ((delta.seconds % 3600) // 60) > 5):
response = requests.post('https://api.tradier.com/v1/markets/events/session',
data={},
headers={'Authorization': f'Bearer {API_TOKEN}', 'Accept': 'application/json'}
)
if response.status_code == 401:
print("Token request respsponse: {}".format(response))
print(response.text)
sys.exit(1)
else:
json_response = response.json()
SESSION_ID = json_response['stream']['sessionid']
timestamp = datetime.now()
PAYLOAD = '{"symbols": ' + SINGLE + ', "filter": ["quote"], "sessionid": "' + SESSION_ID + '", "linebreak": true, "validOnly": false, "advancedDetails": true}'
uri = "wss://ws.tradier.com/v1/markets/events"
try:
async with websockets.connect(uri, ssl=True, compression=None) as websocket:
payload = PAYLOAD
print(payload)
await websocket.send(payload)
print(f">>> {payload}")
async for message in websocket:
print(f"<<< {datetime.now()}{message}")
except websockets.ConnectionClosed:
print("WebSocket connection closed. Reconnecting...")
await asyncio.sleep(5)
asyncio.run(reconnect())
Example Response
>>> {"symbols": ["SPCX"], "filter": ["quote"], "sessionid": "b54d1f03-3ffc-425a-855d-2c9218c75f0b", "linebreak": true, "validOnly": false, "advancedDetails": true}
<<< 2026-08-09 23:11:25.436888{"type":"quote","symbol":"SPCX","bid":134.07,"bidsz":500,"bidexch":"P","biddate":"1786147198000","ask":134.11,"asksz":300,"askexch":"Q","askdate":"1786147199000"}
Step-by-step explainer:
Imports, Tokens, and Assets:
Our initial setup is to import the packages we need for a WebSocket connection and utilities to understand time and make an HTTP call for a sessionID in order to open the WebSocket connection. We also have a few example lists of equities to track.
Get A sessionID
To establish a WebSocket streaming connection, we need a sessionID. This token is good for 5 minutes in which time you can establish a connection or reconnect if you lose your connection. Once established the stream will run indefinitely but the sessionID used to connect will only be valid for 5 minutes. Here we have logic to check how old the sessionID is and call for a new one if it has been 5 minutes or greater.
Build your payload
Here we build our payload with the symbols we want to track, the filter for items like "quotes" "timesales", "trades", etc. See the streaming guide for full details.
Establish the connection and output the data
We establish the connection based on our payload in our "try: async with" block, and we output the data returned asynchronously.
On this page
- Start a Market Data Stream