# Python Example | Stream API > Python code example demonstrating how to connect to the real-time SEC filings Stream API using socket.io. The example prints new filings in real-time to your console. Source: https://sec-api.io/docs/stream-api/python-example This guide provides a step-by-step approach to connect to the Stream API with Python, enabling you to receive newly published SEC filings in real-time. Begin with the installation of the [WebSocket library](https://websockets.readthedocs.io/en/stable/) by executing the following command in your terminal: `pip install websockets` After installation, proceed to copy the Python script provided below into a file on your local machine. Ensure you replace `YOUR_API_KEY` with your actual API key obtained from your account. With these preparations complete, you're ready to execute the Python script. The script will continuously listen for new filings and output their metadata in your terminal as soon as they are made available on EDGAR. Python ```python import asyncio import websockets import json API_KEY = "YOUR_API_KEY" # Replace this with your actual API key SERVER_URL = "wss://stream.sec-api.io" WS_ENDPOINT = SERVER_URL + "?apiKey=" + API_KEY async def websocket_client(): try: async with websockets.connect(WS_ENDPOINT) as websocket: print("✅ Connected to:", SERVER_URL) while True: message = await websocket.recv() filings = json.loads(message) for f in filings: print(f["accessionNo"], f["formType"], f["filedAt"], f["cik"]) except Exception as e: print(f"An unexpected error occurred: {e}") asyncio.run(websocket_client()) ``` ## Advanced Example: Auto-Reconnect, Heartbeats, and Keep-Alives This advanced Python code sample introduces a robust reconnection mechanism. It enables the client to monitor the connection status actively and perform an automatic reconnection if the connection drops. The strategy involves dispatching a heartbeat ping to the server at 30-second intervals, awaiting a pong response. Should the server fail to reply within a 5-second window, the client terminates the current connection and initiates a new connection process, thereby maintaining continuous connectivity. Python ```python import asyncio import websockets import json API_KEY = "YOUR_API_KEY" # Replace this with your actual API key SERVER_URL = "wss://stream.sec-api.io" WS_ENDPOINT = SERVER_URL + "?apiKey=" + API_KEY async def send_ping(websocket): while True: try: pong_waiter = await websocket.ping() await asyncio.wait_for(pong_waiter, timeout=5) # Wait for a pong within 5 seconds await asyncio.sleep(30) # Send ping every 30 seconds except Exception as e: print(f"An error occurred while sending ping: {e}") await websocket.close() # Close the connection if an error occurs return async def websocket_client(): retry_counter = 0 max_retries = 5 ping_task = None while retry_counter < max_retries: try: async with websockets.connect(WS_ENDPOINT) as websocket: print("✅ Connected to:", SERVER_URL) retry_counter = 0 # Start the ping/pong keep-alive routine ping_task = asyncio.create_task(send_ping(websocket)) # Start the message-receiving loop while True: message = await websocket.recv() filings = json.loads(message) for f in filings: print(f["accessionNo"], f["formType"], f["filedAt"], f["cik"]) except Exception as e: retry_counter += 1 print(f"Connection closed with message: {e}") print(f"Reconnecting in 5 sec... (Attempt {retry_counter}/{max_retries})") # Cancel the ping task if ping_task is not None: try: ping_task.cancel() await ping_task except Exception: pass # Ignore any exceptions ping_task = None await asyncio.sleep(5) # Wait for 5 seconds before reconnecting print("Maximum reconnection attempts reached. Stopping client.") asyncio.run(websocket_client()) ``` ## Example for Connecting to Deprecated Legacy Endpoints This example illustrates the process of connecting to legacy streaming endpoints that are marked for deprecation. Please be advised that these endpoints will be phased out on April 5, 2024. To ensure uninterrupted access and take advantage of enhanced functionality, we strongly recommend migrating to the newly available endpoint as soon as possible. `pip install python-engineio==3.14.2 python-socketio[client]==4.6.0` Python ```python import socketio sio = socketio.Client() @sio.on('connect', namespace='/all-filings') def on_connect(): print("Connected to https://api.sec-api.io:3334/all-filings") @sio.on('filing', namespace='/all-filings') def on_filings(filing): print(filing) sio.connect('https://api.sec-api.io:3334?apiKey=YOUR_API_KEY', namespaces=['/all-filings'], transports=["websocket"]) sio.wait() ```