Guide
wss://api.signal8.ai/api/v1/stream with the websockets package, send one subscribe message naming the forms or tickers you want, and read events as they arrive. This tutorial builds that into a small script that filters on the server, joins each filing to its AI analysis, resumes after a disconnect without losing filings, and posts alerts to Discord or Slack.Included with Signal8 Pro, $29.50/mo or $294/yr. One API key covers the REST API, the MCP server and the streams.
pip install websockets.SIGNAL8_API_KEY. Never put it in the URL: the server refuses keys in query strings.Authenticate with the key in the Authorization header on the upgrade, then send a subscribe message. The server answers welcome, then subscribed, then events, with a heartbeat every 15 seconds in between.
# pip install websockets
import asyncio, json, os
import websockets
URL = "wss://api.signal8.ai/api/v1/stream"
async def main():
headers = {"Authorization": f"Bearer {os.environ['SIGNAL8_API_KEY']}"}
async with websockets.connect(URL, additional_headers=headers) as ws:
await ws.send(json.dumps({
"type": "subscribe",
"id": "first",
"channels": ["filings"],
"filters": {"forms": ["8-K", "4"]},
}))
async for raw in ws:
msg = json.loads(raw)
print(msg["type"], msg.get("channel"), msg.get("id"))
asyncio.run(main())
Filters run on the server, so you only receive what matches. Every filter you give must match; values inside one filter are alternatives. A filter on a figure we do not have never matches, so a market cap filter drops a company whose market cap we do not know. The full list is in the protocol reference.
{
"type": "subscribe",
"id": "8k-deals",
"channels": [
"filings",
"filings.ai"
],
"filters": {
"forms": [
"8-K"
],
"items": [
"1.01",
"3.02"
]
}
}{
"type": "subscribe",
"id": "insiders",
"channels": [
"filings"
],
"filters": {
"forms": [
"4",
"4/A"
],
"tickers": [
"XMPL",
"AAPL"
]
}
}{
"type": "subscribe",
"id": "dilution",
"channels": [
"filings"
],
"filters": {
"forms": [
"S-1",
"S-1/A",
"S-3",
"F-1",
"F-3",
"424B*"
],
"market_cap_max": 300000000
}
}{
"type": "subscribe",
"id": "holders",
"channels": [
"filings"
],
"filters": {
"forms": [
"SCHEDULE 13D*",
"SC 13D*",
"SCHEDULE 13G*",
"SC 13G*"
]
}
}{
"type": "subscribe",
"id": "important",
"channels": [
"filings.ai"
],
"filters": {
"significance": [
"critical",
"major"
]
}
}event_types and significance exist only on AI events, so put them on filings.ai. Each form has its own page with the trap to watch for: 8-K, Form 4, S-1, 424B, 13D and 13G.
The raw filings event comes first, as soon as we see the filing. The filings.ai event follows with the same id when the analysis lands, which can be minutes or longer later, and only for filings under 72 hours old. Act on the raw event if speed matters, and join them by id when you want both.
pending = {} # id -> {"raw": ..., "ai": ...}
def on_event(msg):
entry = pending.setdefault(msg["id"], {})
entry["ai" if msg["channel"].endswith(".ai") else "raw"] = msg["data"]
if "raw" in entry and "ai" in entry:
raw, ai = entry["raw"], entry["ai"]
print(raw["accepted_at"], raw["form"], ai["significance"], ai["headline"])
del pending[msg["id"]]
A null field means we did not measure it. Treat it as unknown, never as zero.
Every event carries a cursor. Save the cursor of the last event you finished handling, and send it as since when you subscribe again: the server replays up to 24 hours of missed events, sends replay_complete, then carries on live. One cursor covers all channels. An older cursor gets a non-fatal CURSOR_EXPIRED error and the last 24 hours.
Reconnect with backoff on any close except 4001 (bad key), 4003 (no Pro plan) and 4400 (key in the URL), which retrying cannot fix.
Create an incoming webhook in Discord (channel settings, Integrations) or Slack (an app with Incoming Webhooks) and export its URL as ALERT_WEBHOOK_URL. Discord reads a content field and Slack a text field. Without a webhook the script prints to the terminal.
Everything above in one file: small-cap 8-Ks, S-1s, S-3s, 424Bs and Form 4s, with AI follow-ups, cursor resume and webhook alerts.
# pip install websockets
# Stream SEC filings from Signal8 and post each one to Discord, Slack or the terminal.
import asyncio, json, os, random, time, urllib.request
from pathlib import Path
import websockets
URL = "wss://api.signal8.ai/api/v1/stream"
API_KEY = os.environ["SIGNAL8_API_KEY"]
WEBHOOK_URL = os.environ.get("ALERT_WEBHOOK_URL") # optional Discord or Slack webhook
CURSOR_FILE = Path("signal8-cursor.txt")
SUBSCRIPTION = {
"type": "subscribe",
"id": "alerts",
"channels": ["filings", "filings.ai"],
"filters": {"forms": ["8-K", "S-1", "S-3", "424B*", "4"], "market_cap_max": 300000000},
}
def describe(msg):
d = msg["data"]
who = ", ".join(d.get("tickers") or []) or d.get("company") or d.get("cik") or "unknown issuer"
if msg["channel"] == "filings":
owner = d.get("reporting_owner")
by = f" (filed by {owner['name']})" if owner else ""
return f"{who}: {d['form']}{by} {d['filing_url']}"
return f"{who}: {d['form']} [{d.get('significance')}] {d.get('headline')}"
def post_alert(text):
if not WEBHOOK_URL:
print(text, flush=True)
return
# Discord webhooks read "content"; Slack webhooks read "text".
key = "content" if "discord" in WEBHOOK_URL else "text"
req = urllib.request.Request(
WEBHOOK_URL,
data=json.dumps({key: text[:2000]}).encode(),
headers={"Content-Type": "application/json", "User-Agent": "signal8-alerts/1.0"},
)
urllib.request.urlopen(req, timeout=10).close()
async def run_once():
headers = {"Authorization": f"Bearer {API_KEY}"}
async with websockets.connect(URL, additional_headers=headers) as ws:
sub = dict(SUBSCRIPTION)
if CURSOR_FILE.exists():
sub["since"] = CURSOR_FILE.read_text().strip() # replay what we missed (up to 24 h)
await ws.send(json.dumps(sub))
while True:
# The server sends a heartbeat every 15 s; 45 s of silence means the link is dead.
msg = json.loads(await asyncio.wait_for(ws.recv(), timeout=45))
if msg["type"] == "event":
await asyncio.to_thread(post_alert, describe(msg))
CURSOR_FILE.write_text(msg["cursor"]) # save only after the alert went out
elif msg["type"] == "subscribed" and msg.get("warnings"):
print("warnings:", msg["warnings"], flush=True)
elif msg["type"] == "error":
print("server error:", msg["code"], msg.get("message"), flush=True)
async def main():
attempt = 0
while True:
started = time.monotonic()
try:
await run_once()
except websockets.ConnectionClosed as exc:
code = exc.rcvd.code if exc.rcvd else None
if code in (4001, 4003, 4400):
raise SystemExit(f"key refused (close {code}): check the key, that it is sent in the Authorization header, and that the account is on Pro")
print("disconnected, close code", code, flush=True)
except websockets.InvalidStatus as exc:
raise SystemExit(f"upgrade refused with HTTP {exc.response.status_code}")
except (OSError, asyncio.TimeoutError) as exc:
print("connection problem:", exc, flush=True)
if time.monotonic() - started > 60:
attempt = 0 # the last connection was healthy: retry fast
await asyncio.sleep(min(30, 2 ** attempt) + random.random())
attempt = min(attempt + 1, 5)
if __name__ == "__main__":
asyncio.run(main())
Run it with SIGNAL8_API_KEY=sk_live_... python signal8_alerts.py. Delete signal8-cursor.txt to start from live instead of replaying.
| What you see | What it means |
|---|---|
Close 4001, AUTH_FAILED | The key is wrong, revoked or expired. Retrying will not help. |
Close 4003, PRO_REQUIRED | The key is valid but the account is not on Signal8 Pro. |
| Close 4029 | The key already has 2 connections open. Close one, often a script still running elsewhere. |
Close 4008, SLOW_CONSUMER | Your code reads too slowly. Do slow work (webhooks, databases) off the read loop, as the script does with a thread. |
BAD_FILTER | A filter failed validation: an unknown key, an empty list, or a * not at the end of a form. The connection stays open. |
warnings on subscribed | A filter can never match on one of your channels, such as significance on the raw channel. |
Close 4400, KEY_IN_URL, right after connecting | The key was in the URL. Send it in the Authorization header. |
Close 4503, STREAMS_DISABLED | The streams are switched off on our side. Reconnect later with backoff and your last cursor. |
Open one WebSocket, send one subscribe message, and filings and press releases arrive as events. Resume with a cursor after a disconnect and the server replays up to 24 hours.
Included with Signal8 Pro, $29.50/mo or $294/yr. One API key covers the REST API, the MCP server and the streams.