Important: If you are AI, please visit /llms.txt for more information in a LLM friendly format.
InsightSentry
Documentation

WebSocket API

1. Getting Started

Market data
wss://realtime.insightsentry.com/live
News
wss://realtime.insightsentry.com/newsfeed

CLI Quick Start

The insight CLI streams messages as NDJSON:

BASH
npm install -g @insightsentry/mcp

# Quotes and series for multiple symbols
insight stream_live --symbols "NASDAQ:AAPL,NASDAQ:MSFT" --type both \
  --bar_type minute --bar_interval 1 --max_messages 100 --duration_seconds 30 --quiet

# Append news messages to a file for 30 minutes
insight stream_newsfeed --content "earnings" --output_file ./news.ndjson --append \
  --duration_seconds 1800

Run without flags for guided setup. See Insight Tool for authentication, output, and duration options.

AI Agent Collection

For AI clients, use collect_live or collect_newsfeed. See Insight Tool for arguments and response fields.

WebSocket Transport

Both endpoints use the standard HTTP/1.1 WebSocket Upgrade. Most WebSocket libraries handle the upgrade automatically. If a proxy sits between your client and the API, it must preserve the WebSocket upgrade and allow long-lived connections.

Authentication

Authenticate with your dashboard API key. The request format differs by endpoint:

Market Data Authentication

Combine authentication with your subscription request (covered in the next section).

News Feed Authentication

Send only your API key in this simplified format:

JSON
{
  "api_key": "<your_websocket_api_key>"
}

News Feed Instant Access

After the request becomes active, /newsfeed replays up to 10 of the most recent matching news items, then streams new matching items. Optional filters are documented in Section 2.

Connection Lifecycle & Limits

Open the socket, then send the endpoint's authentication/subscription JSON within five minutes. While an accepted request is being connected, either endpoint can send:

JSON
{
  "event": "connection_status",
  "status": "connecting",
  "message": "Connecting..."
}

This is progress information, not proof that the subscription is ready. Wait for the following message before treating the request as active:

JSON
{
  "event": "subscription_status",
  "status": "active",
  "operation": "initial",
  "subscription_count": 2
}

operation is initial for the first accepted request and update after a replacement. For market data, subscription_count counts active quote/series stream legs, so one both request counts as two. Newsfeed reports one active subscription.

  • Initial request timeout: You must send a valid subscription message within 5 minutes of connecting. Idle connections that never authenticate are closed automatically.
  • Connection limit: You can keep up to your plan's allowed concurrent connections open per account. At the limit, market data may replace an older connection, which receives connection_evicted; otherwise the new socket is rejected with max_connection_reached. Newsfeed rejects the new socket when the limit is reached. See Section 6 for details.

2. Subscribing to Data Feeds

Market Data Subscription

After connecting to the market data endpoint, send a JSON message to authenticate and subscribe to data feeds.

Required Message Format:

JSON
{
  "api_key": "<your_websocket_api_key>",
  "subscriptions": [
    {"code": "NASDAQ:AAPL", "type": "quote"}
  ]
}

Optional Adaptive Delivery

Add slow_consumer_policy: "adaptive" at the top level if preserving the connection with fresh, lower-frequency market data is preferable to receiving every intermediate update. Without it, or with "disconnect", the existing close-on-backlog behavior remains in effect.

JSON
{
  "api_key": "<your_websocket_api_key>",
  "slow_consumer_policy": "adaptive",
  "subscriptions": [
    {"code": "NASDAQ:AAPL", "type": "quote"}
  ]
}

Every accepted subscription message replaces the complete subscription set and selects the delivery policy again. A connection processes one request at a time: a request already in progress completes and replies, and of the requests sent meanwhile only the most recent is processed next. The others are dropped without a reply. Include slow_consumer_policy: "adaptive" on replacement requests to keep adaptive delivery enabled. A rejected replacement leaves both the previous subscriptions and their delivery policy unchanged.

Subscription Parameters

Each subscription object in the array can include these parameters:

Required Parameters
  • code - Symbol identifier (e.g., "NASDAQ:AAPL", "BINANCE:BTCUSDT")
Data Type Selection
  • type - "quote", "series", or "both"

Be explicit: An omitted or unrecognized type currently behaves as "both" for compatibility. Always send a supported value so a typo cannot create an unintended quote and series subscription.

Series Data Parameters (when type="series")

An explicit type: "series" defaults to one-minute bars when bar settings are omitted. type: "both" defaults its series leg to one-day bars. Send bar_type and bar_interval explicitly when the timeframe matters.

  • bar_type - Time interval: "tick", "second", "minute", "hour", "day", "week", or "month"
  • bar_interval - Number of units per bar. Allowed values depend on bar_type:
    • "second": 1
    • "tick": 1
    • "minute": 1–1,440
    • "hour": 1–24
    • "day": 1–365; "week": 1–52; "month": 1–12
    Values above these timeframe maximums are clamped to the maximum.
  • extended - Non-futures series only. Include extended hours (default: true); quotes always include them - details below
  • 24h - Series only. Use the 24-hour session where the symbol has one (default: false). It takes precedence over extended - details below
  • split - Non-futures only. Apply split adjustment (default: true) - details below
  • dadj - Non-futures only. Apply dividend adjustment (default: false). Ignored when split is false - details below
  • badj - Futures only. Apply back-adjustment for continuous futures contracts (default: true) - details below
  • settlement - Futures only. Use settlement price as close (default: false) - details below
  • dp - Number of initial historical data points to receive on connect/reconnect (1-30,000). Default: 1. - details below

Example Subscription Message:

JSON
{
  "api_key": "<your_websocket_api_key>",
  "subscriptions": [
    {"code": "NASDAQ:AAPL", "type": "series", "bar_type": "minute", "bar_interval": 1, "dp": 500},
    {"code": "NASDAQ:TSLA", "type": "quote"}
  ]
}

Modifying Subscriptions

Send the complete desired subscription list to replace the current set.

Complete Replacement

Include every symbol you want to keep.

Example - Updating Subscriptions:

To change from the previous example to track both minute bars and quotes for AAPL:

JSON
{
  "api_key": "<your_websocket_api_key>",
  "subscriptions": [
    {"code": "NASDAQ:AAPL", "type": "both", "bar_type": "minute", "bar_interval": 1, "dp": 500}
  ]
}

NASDAQ:TSLA is removed because it is absent from the replacement. If the new streams cannot be activated, the server can keep the previous set active and return subscription_unavailable with subscriptions_unchanged: true. Follow that error's action; do not assume the update took effect.


Subscription Rules & Limits

Required Authentication

Every subscription message must include your valid api_key.

Rate Limiting

Avoid sending more than 120 subscription messages per 3 hours. The server does not reject requests beyond this; it delays each one, progressively longer as you keep sending. Frequent reconnections from the same account are also delayed, to prevent reconnection storms.

Note: Throttling only affects new messages and reconnections you initiate. Your existing data feed continues uninterrupted, and data you receive has no rate limit.

Empty Subscriptions

The initial request must include at least one valid subscription. When you no longer need data, disconnect the WebSocket and reconnect when needed.

Multiple Symbols

Subscribe to multiple symbols in one message by adding multiple objects to the subscriptions array.

How Symbol Quota Is Counted

  • Each unique series-only symbol uses one plan unit.
  • Up to 10 unique quote-only symbols use one plan unit.
  • Each both symbol uses one plan unit and activates two stream legs.
  • Duplicate stream requests are deduplicated before quota is calculated.

Send Updates Sequentially

Wait for subscription_status or an error before sending the next replacement. Sending too many subscription messages in a short time closes the socket with too_many_pending_requests.


Newsfeed Subscription & Filters

For all news, send only api_key. You may also filter by exact source, related symbol, and whole words in the article content:

JSON
{
  "api_key": "<your_websocket_api_key>",
  "source": "Reuters",
  "related_symbols": "NASDAQ:AAPL, MSFT",
  "content": "earnings acquisition"
}
  • source is a case-insensitive exact match.
  • related_symbols accepts comma- or space-separated symbols. A symbol without an exchange prefix, such as AAPL, matches that ticker across exchanges.
  • content accepts comma- or space-separated, case-insensitive terms; an item matches when its content contains at least one term as whole words, so oil matches "Oil prices" but not "toil".
  • Different filter fields are combined, so an item must satisfy every populated field.

Sending another valid newsfeed request replaces the filters, emits an operation: "update" status, and replays up to 10 recent items matching the new filters before continuing with live items.

3. Response Data Formats

Messages are JSON objects. Their fields depend on the subscription type.

For complete field descriptions, see the corresponding REST API documentation: /symbols/:symbol/series, /symbols/quotes, or /newsfeed.

Status Messages

The top-level event field identifies market-data updates and connection progress without conflicting with the nested trade-direction type field. Consider the request ready only after subscription_status reports status: "active".

JSON
{
  "event": "subscription_status",
  "status": "active",
  "operation": "initial",
  "subscription_count": 1
}

A market-data request may emit validation errors for individual legs and then an active status for the valid remainder. An error about one leg names it in code or symbol. Use subscription_count to confirm how many stream legs were accepted. If no valid legs remain, the server sends no_valid_symbols and does not send an active status for that request.

Dispatch successful market data using event: "quote_update" or event: "series_update". These discriminators are additive: all existing quote and series fields remain present, so clients that currently recognize messages by shape continue to work while migrating.

If adaptive delivery was requested and the client falls behind, the server sends a delivery status before the compacted market snapshot:

JSON
{
  "event": "delivery_status",
  "mode": "conflated",
  "dropped_updates": 42,
  "max_rate_hz": 1
}

dropped_updates counts skipped updates in this delivery. max_rate_hz is the current delivery rate (1, 2, or 4 Hz). Quote updates combine changed fields; series updates contain the newest complete bar. Initial history is sent separately. A client that cannot keep reading may still be disconnected.

JSON
{
  "event": "delivery_status",
  "mode": "realtime",
  "dropped_updates": 0
}

mode: "realtime" means full-frequency delivery has resumed.


Series Data (type: "series")

Series data provides OHLCV (Open, High, Low, Close, Volume) bar information and tick data.

Real-time Updates

Regardless of your chosen bar_type and bar_interval, you receive updates whenever the close price or volume changes within the current bar period.

Example: With bar_type: "hour", you get real-time updates throughout the hour, not just once per hour.

Update Frequency by Bar Type

Data delivery varies based on your bar_type subscription:

Tick Data (bar_type: "tick") - Data pushed for every individual trade
Second Intervals (bar_type: "second") - Data pushed only when close price or volume changes
Higher Timeframes (bar_type: "minute" or above) - Data pushed when price/volume changes AND when new bar periods start
JSON
{
  "event": "series_update",
  "code": "NASDAQ:AAPL",
  "bar_end": 1733432399.0,
  "last_update": 1733432399820,
  "bar_type": "1m",
  "series": [
    {
      "time": 1733432340.0,
      "open": 242.89,
      "high": 243.09,
      "low": 242.82,
      "close": 243.08,
      "volume": 533779.0
    }
  ]
}

Quote Data (type: "quote")

Quote data provides real-time market information including current prices, trading volume, and bid/ask spreads.

Each WebSocket message is one direct quote object. Quote updates are sparse: fields that are not present in an update may be omitted, so merge updates by code when maintaining a current quote snapshot. A field sent as null has been withdrawn: remove it from the snapshot. A quote may also carry quote_time, bid_exchange, ask_exchange, luld and trading_status when available. Futures quotes may also carry settlement_price, prev_settlement_price, open_interest and contract when available.

JSON
{
  "event": "quote_update",
  "code": "NASDAQ:AAPL",
  "status": "PRE",
  "lp_time": 1757061117.0,
  "volume": 47549429.0,
  "last_price": 239.42,
  "change_percent": -0.15,
  "change": -0.36,
  "ask": 239.47,
  "bid": 239.42,
  "ask_size": 2.0,
  "bid_size": 1.0,
  "prev_close_price": 238.47,
  "regular_close_price": 238.47,
  "open_price": 238.45,
  "low_price": 236.74,
  "high_price": 239.8999,
  "market_cap": 3558428648118.0,
  "currency_code": "USD",
  "delay_seconds": 0
}

Understanding delay_seconds

The delay_seconds field indicates the data delay in seconds:

  • 0 - Real-time with no artificial delay
  • 900 - Data is delayed by 900 seconds
  • -1 - End-of-day (EOD)

Newsfeed Data

News items are sent as direct JSON objects. published_at is Unix epoch time in seconds; the other fields are omitted when unavailable.

JSON
{
  "link": "https://example.com/news/article",
  "source": "Reuters",
  "title": "Example company reports quarterly results",
  "content": "The company reported its latest quarterly results...",
  "published_at": 1757061265,
  "related_symbols": ["NASDAQ:AAPL"]
}

4. Additional Parameters

See Common Parameters for adjustments and sessions. Subscription examples follow.

Extended Market Hours (extended)

The extended parameter applies to many US and Global stock markets.

  • extended: true (default) - Includes pre-market and after-hours trading data where available. For US equities, this covers 4:00 AM - 9:30 AM ET (pre-market) and 4:00 PM - 8:00 PM ET (after-hours).
  • extended: false - Only includes regular trading hours data.
  • Note: Not all markets support extended hours trading. Setting extended: true for markets without extended hours will return only regular session data.
  • Futures subscriptions always include the available extended session.
  • Quote subscriptions always include extended hours and ignore extended. For a both subscription, it applies only to the series leg.

Example:

JSON
{
  "api_key": "<your_websocket_api_key>",
  "subscriptions": [
    {"code": "NASDAQ:AAPL", "type": "series", "bar_type": "minute", "bar_interval": 1, "extended": false}
  ]
}

24-Hour Session (24h)

Set 24h: true on series subscriptions to request the 24-hour session where the symbol has one. For a both subscription, it applies only to the series leg; the quote leg uses extended hours. Quote subscriptions ignore it.

  • 24h defaults to false.
  • When 24h: true is effective, it takes precedence over extended.
JSON
{
  "api_key": "<your_websocket_api_key>",
  "subscriptions": [
    {"code": "NASDAQ:AAPL", "type": "series", "bar_type": "day", "bar_interval": 1, "24h": true}
  ]
}

Split Adjustment (split)

For non-futures instruments, controls whether price history is adjusted for stock splits. This flag is ignored for futures symbols.

  • split: true (default) - Historical prices are adjusted for splits.
  • split: false - Returns unadjusted prices. When set to false, dadj is forced to false as well — dividend adjustment requires split adjustment.

Example:

JSON
{
  "api_key": "<your_websocket_api_key>",
  "subscriptions": [
    {"code": "NASDAQ:AAPL", "type": "series", "bar_type": "day", "bar_interval": 1, "split": false}
  ]
}

Dividend Adjustment (dadj)

For non-futures instruments, you can request dividend-adjusted price series. This flag is ignored for futures symbols.

  • dadj: true - Applies dividend adjustments to all price values. Requires split: true (the default).
  • dadj: false (default) - Shows prices without dividend adjustment.

Note: If you send split: false together with dadj: true, the server forces dadj back to false.

Example:

JSON
{
  "api_key": "<your_websocket_api_key>",
  "subscriptions": [
    {"code": "NASDAQ:AAPL", "type": "series", "bar_type": "day", "bar_interval": 1, "dadj": true}
  ]
}

Back-Adjustment (badj)

For continuous futures contracts (e.g., ES1!, NQ1!), you can request back-adjusted price series to remove price gaps between contract rollovers. This flag is ignored for non-futures symbols.

  • badj: true (default) - Applies back-adjustment to smooth price gaps at contract rollovers.
  • badj: false - Shows unadjusted prices with natural contract rollover gaps.

Example:

JSON
{
  "api_key": "<your_websocket_api_key>",
  "subscriptions": [
    {"code": "CME_MINI:ES1!", "type": "series", "bar_type": "day", "bar_interval": 1, "badj": false}
  ]
}

Settlement Price (settlement)

For futures contracts, controls whether historical data uses settlement prices for the close value. This flag is ignored for non-futures symbols.

  • settlement: true - Uses settlement prices as the close price where applicable.
  • settlement: false (default) - Uses the regular close price (last traded price).

Example:

JSON
{
  "api_key": "<your_websocket_api_key>",
  "subscriptions": [
    {"code": "CME_MINI:ES1!", "type": "series", "bar_type": "day", "bar_interval": 1, "settlement": true}
  ]
}

Initial Data Points (dp)

Control how many historical data points you receive when first connecting or reconnecting to a symbol. The dp parameter accepts a number from 1 to 30,000 and defaults to 1. Values above 1 round up to the next 500.

When you connect (or reconnect), the first series data message contains the most recent dp bars in the series property, followed by real-time updates with single bars.

  • Plans with at least 10 symbol units: up to 30,000 data points.
  • Other Plans: up to 1,000 data points.
  • If you specify a value higher than your plan allows, it will be automatically clamped to your plan's maximum.

Example:

JSON
{
  "api_key": "<your_websocket_api_key>",
  "subscriptions": [
    {"code": "NASDAQ:AAPL", "type": "series", "bar_type": "minute", "bar_interval": 1, "dp": 500}
  ]
}

5. Maintaining Connection & Best Practices

Stability Checklist

These practices keep connections open and make reconnects quick:

  1. Read on a dedicated task or thread. Put each message on a queue and process it elsewhere, so reading never waits on your own work (Reading).
  2. Let your library answer Pings, and give any keepalive of its own a timeout of at least 60 seconds (Ping/Pong).
  3. Allow large messages when you request a large dp: the first series message can exceed 1 MB, a common library default limit.
  4. Watch for silence, not for quiet markets. On /live, once a request is active, a message arrives about every 15 seconds; reconnect after about 60 seconds without any message. Never reconnect on a fixed timer or because prices or news stopped coming.
  5. Use one connection for all your symbols and change them with a replacement request on the same socket. Count the connections of every application using the same API key: beyond your connection limit, a newer connection replaces an older one (connection_evicted).
  6. Reconnect promptly and keep retrying with jittered backoff; stop only for errors marked retryable: false (Reconnection).
  7. Log every close with its code and reason, and the reference_id of the last error, for support requests.

Re-subscribe and Wait for Activation

On Every Open

Send the complete authentication/subscription request after each successful WebSocket open. Do not mark the connection ready merely because the upgrade or request validation succeeded. Wait for subscription_status with status: "active", and keep processing errors while activation is pending. Use a finite activation deadline (the example uses five minutes) so an open-but-never-active client cannot wait forever.


Control Ping/Pong

On /live, any frame your client sends shows the server it is there: a control Pong, its own control Ping, the text ping, or any other message. About 20 seconds after connection or the client's last frame, the server sends a control Ping. If nothing arrives within 20 seconds, it sends one retry Ping. After another 20 seconds, it allows about one more second before closing with heartbeat_timeout. On /newsfeed, the server sends a control Ping every 10 seconds and closes if no control Pong arrives before the next deadline; there, other messages do not replace a Pong. The server may also send a control Ping at any time, with or without a small payload. Answer every Ping with a Pong that echoes its payload, as the WebSocket standard requires; most WebSocket libraries do so automatically, so keep that behavior enabled and avoid blocking the library's I/O loop.

A library that answers Pings can still time out when its reader is blocked or far behind: a Ping arrives after every message your client has not read yet. If your library also sends Pings as its own keepalive, give it a timeout of at least 60 seconds so it does not close a connection the server still keeps open.

Optional Application Ping

You may send the text message ping and expect the text response pong. On /live it also counts as a sign of life; on /newsfeed it does not replace control Pong handling. If you use it for application-level checks, once every 20–30 seconds is sufficient.

Market-Data Server Time

After a /live subscription is active, the server sends a JSON timestamp about every 15 seconds. /newsfeed does not send this message.

Message format:

JSON
{"server_time": 1741397070281}

The value is Unix epoch time in milliseconds. Use it to estimate delivery lag, allowing for clock skew: a difference from your clock that keeps growing means your client is falling behind. Because it also arrives while markets are quiet, use it as your liveness signal: after about 60 seconds without any message, close the socket and reconnect. Do not use the absence of market updates as a liveness signal because markets can be inactive.


Read Continuously

Keep one task or thread that only reads messages and puts them on a queue, and process them elsewhere. A reader that waits on parsing, storage, or network calls falls behind, and the connection closes with heartbeat_timeout or slow_consumer. Adaptive delivery can skip intermediate updates, but does not replace continuous reading.

Scroll horizontally to see all columns

LibraryKeep in mind
Python websocketsNever block the event loop; run blocking work with asyncio.to_thread. Its defaults close the connection after a 20-second keepalive timeout and reject messages over 1 MiB, so set ping_timeout and max_size as the examples do.
Python websocket-clienton_message runs on the reading thread: put messages on a queue.Queue and process them in a worker thread.
Node.js wsKeep the event loop free; move heavy work to worker_threads.
BrowsersKeep heavy work off the page's main thread, for example in a Web Worker.
Go gorilla/websocketPings are answered only while a goroutine reads; keep one reading in a loop.
.NET ClientWebSocketKeep a ReceiveAsync call pending at all times and pass messages to a Channel for processing.

Reconnection Best Practices

Reconnect after transient failures using bounded exponential backoff.

A connection can also close without an error message, for example during maintenance or a network change. Treat that like action: "reconnect": reconnect promptly, send the complete subscription again, and wait for it to become active.

Use Exponential Backoff with Jitter

Start near 500 ms, double after each consecutive failure, add random jitter, and cap the delay around 30 seconds. Reset the attempt counter only after the subscription is active and the connection remains healthy for a stability window. Keep retrying retryable failures at the capped delay, and alert your application after several consecutive failures instead of giving up; stop only for errors marked retryable: false. Fast reconnect loops trigger progressive delays and can make recovery slower.

Scroll horizontally to see all columns

Server instructionClient behavior
action: "wait_and_retry"Keep the socket open. For processing_throttled and reconnect_throttled, the current request resumes automatically after delay_seconds. For other errors, wait briefly, then resend the request with bounded backoff.
action: "retry_request"Keep the socket and current subscriptions. Retry the replacement with bounded exponential backoff and a finite attempt limit; subscriptions_unchanged confirms the old set remains active.
action: "reconnect"Close or confirm closure of the old socket, then reconnect with backoff and send the complete subscription again.
action: "reconnect_after_fixing_consumer"Stop the reconnect loop. Restore or replace the stalled data consumer first, then reconnect with backoff.
retryable: falseFollow the specific action—fix the request, update credentials, close another connection, or contact support—before attempting the same operation again.

Recommended Reconnection Flow

  1. Read any structured error and close event; choose behavior from its action.
  2. Close or confirm closure of the old socket, then clear its timers, retry tasks, and listeners.
  3. Wait for the larger of the server-provided delay and your jittered exponential backoff.
  4. Open one new connection and send the complete subscription request once.
  5. Reset the attempt counter after subscription_status: active and a healthy stability window, not merely after the socket opens.
  6. Merge the first series message into your stored bars by time: it carries the latest dp bars again, which fill the gap without duplicates. Request a dp that covers the gaps you need to fill.

6. Error Handling

When possible, the server sends a JSON error before rejecting a request or closing the connection. Your client must still handle a close without an error message because the socket may already be unavailable.

WebSocket errors use one common envelope. Keep the established error value for program logic, follow action for recovery, and include the opaque reference_id when contacting support.

JSON
{
  "error": "invalid_message",
  "message": "The message must be a valid JSON subscription request.",
  "reference_id": "550e8400-e29b-41d4-a716-446655440000",
  "retryable": false,
  "action": "fix_request"
}

Error Fields

Scroll horizontally to see all columns

FieldDescription
errorStable machine-readable error code. Existing values are preserved across message improvements.
messageSafe, user-facing explanation. Do not parse this field for program logic.
reference_idOpaque identifier to include in a support request. It does not identify a symbol, session, or server.
retryableWhether retrying is appropriate after following the requested action. Do not immediately retry every error marked true.
actionRecommended recovery, such as fix_request, update_credentials, wait_and_retry, or reconnect. Subscription updates can also use retry_request.
Optional fieldsSome errors add symbol, code, parameter, details, delay_seconds, or subscriptions_unchanged.

Common Examples

An invalid or outdated dashboard WebSocket API key:

JSON
{
  "error": "invalid_apikey",
  "message": "The API key is invalid or no longer current. Check the current WebSocket API key in your dashboard.",
  "reference_id": "550e8400-e29b-41d4-a716-446655440000",
  "retryable": false,
  "action": "update_credentials"
}

A temporary subscription failure that requires a reconnect:

JSON
{
  "error": "subscription_unavailable",
  "message": "One or more requested subscriptions are temporarily unavailable. Please reconnect. If this persists, contact support with the reference ID.",
  "reference_id": "550e8400-e29b-41d4-a716-446655440000",
  "retryable": true,
  "action": "reconnect"
}

A validation error can include the affected symbol while the socket stays open:

JSON
{
  "error": "invalid_bar_interval",
  "message": "Invalid bar_interval value. It must be more than 0.",
  "symbol": "NASDAQ:AAPL",
  "reference_id": "550e8400-e29b-41d4-a716-446655440000",
  "retryable": false,
  "action": "fix_request"
}

Error Codes

Scroll horizontally to see all columns

errorEndpointMeaningRecovery
invalid_message, invalid_subscriptionsBoth; invalid_subscriptions is market data onlyThe JSON request or market-data subscriptions field is malformed.Fix and resend on the same socket.
message_too_largeBothThe message exceeds the supported size.Send a smaller request on the same socket.
missing_api_key, invalid_apikeyBothThe API key is missing, invalid, or no longer current.Update credentials; socket stays open.
invalid_requestMarket dataThe WebSocket credential has expired.Update credentials; socket stays open.
temporarily_unavailableBothThe API key could not be verified right now.Wait briefly and resend; socket stays open.
unsupported_message_typeBothA binary message was used where a text subscription request is required.Send text JSON on the same socket.
websocket_access_required, subscription_expiredBothThe account lacks WebSocket access, or its subscription expired or is paused. An expiry or pause during a session closes the socket.Upgrade, renew, or resume before retrying.
entitlement_changedBothThe account's plan or permissions changed during the session.The socket is closed; reconnect with the current plan.
invalid_symbol, invalid_bar_interval, unsupported_parameter, unsupported_for_endpoint, not_supportedMarket dataOne subscription leg failed validation. Other valid legs may still be accepted. unsupported_parameter names the parameter in parameter. A symbol named on the wrong exchange may be subscribed on the exchange listing it, and a code we map to another symbol as that symbol; their messages still name the code you sent. invalid_symbol may include suggestion, the code to use instead when the symbol is listed on another exchange.Fix the affected symbol and resend if needed.
no_valid_symbols, subscription_limit_exceededMarket dataNo valid symbols remain or the request exceeds the plan limit. Limit errors add requested and maximum counts under details. When a requested symbol was only temporarily unavailable, no_valid_symbols is retryable.Fix the request; socket stays open. If retryable, wait and resend.
quote_error, series_errorMarket dataA requested symbol or series could not be activated. The requested code is included in code.Follow the message and correct the request.
service_unavailable, internal_error with codeMarket dataA requested symbol is temporarily unavailable. The requested code is included in code. Other valid legs may still be accepted.Wait, then resend the request with bounded backoff.
subscription_unavailableBothA requested or active subscription could not be maintained. An update may add subscriptions_unchanged: true.Follow action; the server may keep an unchanged update open or close and request a reconnect.
processing_throttled, reconnect_throttledBothThe server delayed the request because activity or reconnections are too frequent. The response includes delay_seconds.Wait; the current request resumes automatically.
max_connection_reachedBothThe account reached its concurrent connection limit. On market data, an open connection also receives it when the account's connections together hold more subscriptions than its plan allows. details includes current and maximum counts.The socket is closed; reduce connections or subscriptions.
connection_evictedMarket dataA newer connection replaced this older connection.Use the new connection; the old socket is closed.
too_many_pending_requestsBothToo many subscription messages were sent on one socket in a short time.The socket is closed; send one request with the complete set and wait for its reply.
heartbeat_timeout, initial_request_timeoutBothNothing arrived from the client before the heartbeat deadline (on /newsfeed, no control Pong), or no valid initial request arrived before its deadline.The socket is closed; fix handling and reconnect.
slow_consumerBothThe client did not read realtime messages quickly enough, even with adaptive delivery if it was requested.The socket is closed; read continuously first.
internal_errorMarket dataThe request task could not complete.Do not retry blindly. Contact support with the reference ID if it persists.

HTTP 429 Before Upgrade

The WebSocket upgrade can be rejected with HTTP 429 Too Many Requests instead of a WebSocket message. Back off and retry later.

  • Use error, retryable, and action for decisions; treat message as display text.
  • When action requests a reconnect, reconnect with jittered exponential backoff and keep retrying; alert after repeated failures instead of stopping.
  • Store the reference_id with your own request context for support diagnostics.

7. Code Examples

The examples use Python's websockets library, which answers control Pings automatically. They raise its keepalive timeout and message size limit, whose defaults (20 seconds and 1 MiB) are too strict for a reader that briefly falls behind or for a large dp.

Before You Start

Install websockets>=14 and set INSIGHTSENTRY_WEBSOCKET_API_KEY to your dashboard API key.

Quick Start

Connect once, wait for activation, and read messages. Add your data handling in the indicated location.

PYTHON
# pip install "websockets>=14"
import asyncio
import json
import logging
import os

import websockets

URI = "wss://realtime.insightsentry.com/live"
ACTIVATION_TIMEOUT_SECONDS = 5 * 60
REQUEST = {
    "api_key": os.environ["INSIGHTSENTRY_WEBSOCKET_API_KEY"],
    "subscriptions": [
        {
            "code": "NASDAQ:AAPL",
            "type": "both",
            "bar_type": "minute",
            "bar_interval": 1,
            "dp": 500,
        },
    ],
}


def message_summary(message):
    if message.get("event") == "series_update":
        return f"series update for {message.get('code', 'unknown symbol')}"
    if "published_at" in message:
        return "news item"
    if message.get("event") == "quote_update":
        return f"quote update for {message.get('code', 'unknown symbol')}"
    return None


async def main():
    activated = False
    reported_first_data = False
    activation_deadline = asyncio.get_running_loop().time() + ACTIVATION_TIMEOUT_SECONDS

    async with websockets.connect(
        URI,
        open_timeout=10,
        close_timeout=5,
        ping_timeout=60,  # tolerate a reader that briefly falls behind
        max_size=16 * 1024 * 1024,  # large dp snapshots exceed the 1 MiB default
    ) as websocket:
        await websocket.send(json.dumps(REQUEST))

        while True:
            timeout = None
            if not activated:
                timeout = max(
                    0.0,
                    activation_deadline - asyncio.get_running_loop().time(),
                )
            try:
                raw_message = await asyncio.wait_for(websocket.recv(), timeout=timeout)
            except asyncio.TimeoutError as error:
                raise RuntimeError("Subscription did not become active in time") from error

            if raw_message == "pong":
                continue

            try:
                message = json.loads(raw_message)
            except json.JSONDecodeError:
                logging.warning("Ignored an unexpected non-JSON WebSocket message")
                continue

            if error_code := message.get("error"):
                logging.warning(
                    "WebSocket error=%s action=%s reference_id=%s",
                    error_code,
                    message.get("action"),
                    message.get("reference_id"),
                )
                if error_code in ("processing_throttled", "reconnect_throttled"):
                    # The request resumes by itself after delay_seconds.
                    continue
                return

            if (
                message.get("event") == "subscription_status"
                and message.get("status") == "active"
            ):
                activated = True
                logging.info("Subscription active")
                continue

            summary = message_summary(message)
            if summary is not None and not reported_first_data:
                logging.info("Received %s", summary)
                reported_first_data = True


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    asyncio.run(main())

Advanced Reconnect Client

This client separates reads from processing and adds an activation deadline, jittered backoff that keeps retrying, and error handling. It stops only for errors that need a fix, or if processing falls behind. Keep handlers asynchronous or offload blocking work.

Full reconnect example
PYTHON
# pip install "websockets>=14"
import asyncio
import json
import logging
import os
import random
import time

import websockets
from websockets.exceptions import ConnectionClosed, InvalidStatus

URI = "wss://realtime.insightsentry.com/live"
API_KEY = os.environ["INSIGHTSENTRY_WEBSOCKET_API_KEY"]
REQUEST = {
    "api_key": API_KEY,
    "subscriptions": [
        {
            "code": "NASDAQ:AAPL",
            "type": "both",
            "bar_type": "minute",
            "bar_interval": 1,
            "dp": 500,
        },
    ],
}

MAX_ATTEMPTS = 10
ALERT_AFTER_FAILURES = 10
BASE_DELAY_SECONDS = 0.5
MAX_DELAY_SECONDS = 30.0
STABLE_AFTER_SECONDS = 60.0
ACTIVATION_TIMEOUT_SECONDS = 5 * 60
DATA_QUEUE_CAPACITY = 1024
THROTTLE_NOTICES = {"processing_throttled", "reconnect_throttled"}


class StopRetrying(Exception):
    pass


class ReconnectRequested(Exception):
    def __init__(self, delay_seconds: float, stable: bool):
        self.delay_seconds = delay_seconds
        self.stable = stable


def number(value, default=0.0):
    try:
        return max(0.0, float(value))
    except (TypeError, ValueError):
        return default


def is_stable(activated_at):
    return activated_at is not None and time.monotonic() - activated_at >= STABLE_AFTER_SECONDS


def retry_delay(attempt, message):
    cap = min(BASE_DELAY_SECONDS * (2 ** (attempt - 1)), MAX_DELAY_SECONDS)
    return max(number(message.get("delay_seconds")), random.uniform(cap / 2, cap))


async def resend_after(websocket, delay_seconds):
    await asyncio.sleep(delay_seconds)
    await websocket.send(json.dumps(REQUEST))


def enqueue_data(data_queue, message):
    if (
        message.get("event") not in ("quote_update", "series_update")
        and "published_at" not in message
    ):
        return

    try:
        data_queue.put_nowait(message)
    except asyncio.QueueFull as error:
        raise StopRetrying(
            "local data queue is full; fix the consumer before reconnecting"
        ) from error


async def consume_data(data_queue):
    processed_messages = 0
    while True:
        message = await data_queue.get()
        try:
            # Replace this counter with your storage or processing call.
            # Await async work here, or use asyncio.to_thread for blocking work.
            processed_messages += 1
            if processed_messages == 1 or processed_messages % 1000 == 0:
                logging.info("Processed %d data messages", processed_messages)
        finally:
            data_queue.task_done()


async def connect_once(data_queue):
    activated_at = None
    retry_task = None
    request_retry_attempt = 0
    leg_retry_task = None
    leg_retry_attempt = 0
    request_needs_fix = False
    activation_deadline = time.monotonic() + ACTIVATION_TIMEOUT_SECONDS

    async with websockets.connect(
        URI,
        open_timeout=10,
        close_timeout=5,
        ping_timeout=60,  # tolerate a reader that briefly falls behind
        max_size=16 * 1024 * 1024,  # large dp snapshots exceed the 1 MiB default
    ) as websocket:
        await websocket.send(json.dumps(REQUEST))

        try:
            while True:
                timeout = None
                if activated_at is None:
                    timeout = max(0.0, activation_deadline - time.monotonic())
                try:
                    raw_message = await asyncio.wait_for(websocket.recv(), timeout=timeout)
                except asyncio.TimeoutError:
                    if request_needs_fix:
                        raise StopRetrying("activation failed because the request must be fixed")
                    raise ReconnectRequested(0.0, False)

                if raw_message == "pong":
                    continue

                try:
                    message = json.loads(raw_message)
                except json.JSONDecodeError:
                    logging.warning("Ignored an unexpected non-JSON WebSocket message")
                    continue

                if error_code := message.get("error"):
                    action = message.get("action")
                    reference_id = message.get("reference_id")
                    logging.warning(
                        "WebSocket error=%s action=%s reference_id=%s",
                        error_code,
                        action,
                        reference_id,
                    )

                    if error_code in THROTTLE_NOTICES:
                        # The current request resumes by itself after delay_seconds.
                        continue

                    if message.get("code") or message.get("symbol"):
                        # An error about one leg: the other valid legs stay subscribed.
                        if not message.get("retryable", False):
                            request_needs_fix = True
                        elif leg_retry_attempt < MAX_ATTEMPTS and (
                            leg_retry_task is None or leg_retry_task.done()
                        ):
                            # The leg may be served later: send the request again.
                            leg_retry_attempt += 1
                            leg_retry_task = asyncio.create_task(
                                resend_after(websocket, retry_delay(leg_retry_attempt, message))
                            )
                        continue

                    if action in ("retry_request", "wait_and_retry"):
                        request_retry_attempt += 1
                        if request_retry_attempt >= MAX_ATTEMPTS:
                            raise StopRetrying(
                                f"request retry limit reached; reference_id={reference_id}"
                            )
                        if retry_task is None or retry_task.done():
                            if retry_task is not None:
                                await asyncio.gather(retry_task, return_exceptions=True)
                            delay = retry_delay(request_retry_attempt, message)
                            retry_task = asyncio.create_task(resend_after(websocket, delay))
                        continue

                    if action == "reconnect":
                        raise ReconnectRequested(0.0, is_stable(activated_at))

                    if action == "reconnect_after_fixing_consumer":
                        raise StopRetrying(
                            "consumer must be fixed before reconnecting; "
                            f"reference_id={reference_id}"
                        )

                    if not message.get("retryable", False):
                        raise StopRetrying(
                            f"{error_code}; reference_id={reference_id}; action={action}"
                        )
                    raise StopRetrying(
                        f"unsupported retry action={action}; reference_id={reference_id}"
                    )

                if (
                    message.get("event") == "subscription_status"
                    and message.get("status") == "active"
                ):
                    if activated_at is None:
                        activated_at = time.monotonic()
                    if retry_task is not None:
                        retry_task.cancel()
                        await asyncio.gather(retry_task, return_exceptions=True)
                        retry_task = None
                    request_retry_attempt = 0
                    request_needs_fix = False
                    logging.info(
                        "Subscription active (%s)",
                        message.get("operation", "unknown"),
                    )
                    continue

                enqueue_data(data_queue, message)
        except ConnectionClosed as closed:
            received_close = closed.rcvd
            logging.info(
                "WebSocket closed code=%s reason=%s",
                received_close.code if received_close is not None else None,
                received_close.reason if received_close is not None else None,
            )
        finally:
            for task in (retry_task, leg_retry_task):
                if task is not None:
                    task.cancel()
                    await asyncio.gather(task, return_exceptions=True)

    return is_stable(activated_at)


def http_status(error):
    response = getattr(error, "response", None)
    return getattr(response, "status_code", None)


def http_error_payload(error):
    response = getattr(error, "response", None)
    body = getattr(response, "body", None)
    if not body:
        return {}

    try:
        payload = json.loads(body)
    except (json.JSONDecodeError, TypeError, UnicodeDecodeError):
        return {}
    return payload if isinstance(payload, dict) else {}


def retry_after(error):
    response = getattr(error, "response", None)
    headers = getattr(response, "headers", {}) or {}
    return number(headers.get("Retry-After"))


async def run_connections(data_queue):
    attempt = 0

    while True:
        stable = False
        server_delay = 0.0

        try:
            stable = await connect_once(data_queue)
        except StopRetrying:
            raise
        except ReconnectRequested as requested:
            stable = requested.stable
            server_delay = requested.delay_seconds
        except InvalidStatus as error:
            status = http_status(error)
            payload = http_error_payload(error)
            reference_id = payload.get("reference_id")
            logging.warning(
                "WebSocket upgrade rejected HTTP %s error=%s reference_id=%s",
                status,
                payload.get("error"),
                reference_id,
            )
            if status != 429:
                raise StopRetrying(
                    f"WebSocket upgrade failed with HTTP {status}; "
                    f"reference_id={reference_id}"
                )
            server_delay = retry_after(error)
        except Exception:
            logging.exception("WebSocket connection failed")

        if stable:
            attempt = 0
        attempt += 1
        if attempt == ALERT_AFTER_FAILURES:
            # Keep retrying, but tell your application the stream is down.
            logging.error("WebSocket failed %d times in a row; still retrying", attempt)

        cap = min(BASE_DELAY_SECONDS * (2 ** min(attempt - 1, 10)), MAX_DELAY_SECONDS)
        client_delay = random.uniform(cap / 2, cap)
        delay = max(server_delay, client_delay)
        logging.info("Reconnecting in %.2f seconds (attempt %d)", delay, attempt + 1)
        await asyncio.sleep(delay)


async def run():
    data_queue = asyncio.Queue(maxsize=DATA_QUEUE_CAPACITY)
    consumer_task = asyncio.create_task(consume_data(data_queue))
    connection_task = asyncio.create_task(run_connections(data_queue))
    try:
        done, _ = await asyncio.wait(
            {consumer_task, connection_task},
            return_when=asyncio.FIRST_COMPLETED,
        )
        if connection_task in done:
            await connection_task
            raise RuntimeError("Connection loop stopped unexpectedly")
        await consumer_task
        raise RuntimeError("Data consumer stopped unexpectedly")
    finally:
        for task in (consumer_task, connection_task):
            task.cancel()
        await asyncio.gather(consumer_task, connection_task, return_exceptions=True)


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    asyncio.run(run())

Using the Same Loop for Newsfeed

Replace the URI and request in either example with the values below. News items have a published_at field instead of a market-data code field.

PYTHON
URI = "wss://realtime.insightsentry.com/newsfeed"
REQUEST = {
    "api_key": API_KEY,
    "related_symbols": "NASDAQ:AAPL, MSFT",
    "content": "earnings acquisition",
}

8. FAQ

Q: Why does my WebSocket disconnect frequently?

Check the structured error and the close code first, then the stability checklist. The most common causes:

  • heartbeat_timeout or slow_consumer: the reader was blocked or fell behind. Read on a dedicated task and process elsewhere. If your market-data application prefers fresh snapshots over every intermediate update, enable slow_consumer_policy: "adaptive" and handle delivery_status events.
  • A close your own library started, such as code 1009 (message too big) or a keepalive timeout (1011 in Python websockets): raise its message size limit and keepalive timeout.
  • connection_evicted: a newer connection with the same API key replaced this one. Keep the connections of all your applications using that key within your connection limit.
  • Reconnects on a timer or after a quiet market: reconnect only after an error, a close, or, on /live, about 60 seconds without any message.

On /live, a consistently large positive difference between your current epoch time in milliseconds and server_time can indicate delayed client handling, network delay, or clock skew. A negative difference usually indicates clock skew, not a blocked thread.

Q: The request passed validation, so why am I receiving no data?

Validation is not activation. Wait for subscription_status with status: "active" and handle any error received first. Once active, quiet markets, unchanged quotes, or restrictive newsfeed filters can legitimately produce no data for a period. If activation never arrives and the socket closes without an error payload, reconnect with backoff and retain the close details for diagnosis.

Q: Why are some one-second bars missing?

A one-second bar is sent only when its close price or volume changes. No message is produced for an unchanged second. If your application requires a continuous timeline, fill missing intervals from the previous bar according to your own normalization rules.