InsightSentry

WebSocket API Documentation

1. Getting Started

Prerequisites

  1. Obtain Your WebSocket API Key: Retrieve your unique WebSocket API key by making a request to the /v2/websocket-key endpoint.
  2. Choose a WebSocket Library: Use a WebSocket client library for your programming language that supports automatic reconnection and retries.
  3. Avoid connection drops by increasing the timeout in your WebSocket library and sending a 'ping' every 20 to 30 seconds if needed.

Connecting to the Server

Once you have your WebSocket API key, establish a connection to one of the following endpoints:

Real-time Market Data Endpoint

TEXT
wss://realtime.insightsentry.com/live

News Feed Endpoint

TEXT
wss://realtime.insightsentry.com/newsfeed

Authentication

Both endpoints require authentication using your WebSocket API key, but the format differs slightly:

For Market Data Endpoint

Authentication is combined with your subscription request (detailed in the next section).

For News Feed Endpoint

Send only the API key in a simplified format:

JSON
{
  "api_key": "<your_websocket_api_key>"
  // No subscriptions needed for news feed
}

News Feed Initial Data

Upon connecting or reconnecting to the /newsfeed endpoint, the server will automatically send you the most recent 10 news items. This ensures you have immediate access to recent news without making additional requests.

2. Subscribing to Data Feeds

Initial Subscription

Upon establishing a WebSocket connection to the market data endpoint, you must send a JSON-encoded message to authenticate and subscribe to data feeds for specific symbols.

Message Format:

JSON
{
  "api_key": "<your_websocket_api_key>",
  "subscriptions": [
    // Array of subscription objects
  ]
}

Subscription Object Parameters:

  • code (string, required): The symbol identifier (e.g., "NASDAQ:AAPL", "BINANCE:BTCUSDT").
  • type (string, optional, default: "series"): The type of data feed. Valid options are "series" or "quote".
  • bar_type (string, required for type: "series"): The time interval for bars (e.g., "minute", "hour", "day"). Matches parameters in the /latest REST endpoint.
  • bar_interval (integer, required for type: "series"): The number of bar_type units per bar (e.g., 1, 5, 15). Matches parameters in the /latest REST endpoint.
  • extended (boolean, optional for type: "series", default: true): See Extended Hours.
  • dadj (boolean, optional for type: "series", default: false): See Dividend Adjustment.

Example Subscription Message:

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

Modifying Subscriptions

You can add, remove, or change subscriptions without disconnecting by sending a new subscription message containing the complete desired list of subscriptions. The server will replace your previous subscriptions with the ones in the latest message.

Example - Changing Subscriptions:

To change the previous example to track minute bars and quotes for AAPL, send:

JSON
{
  "api_key": "<your_websocket_api_key>",
  "subscriptions": [
    {"code": "NASDAQ:AAPL", "type": "series", "bar_type": "minute", "bar_interval": 1},
    {"code": "NASDAQ:AAPL", "type": "quote"}
    // NASDAQ:TSLA quote subscription is removed as it's not in the new list
  ]
}

Subscription Rules & Limits

  • API Key Required: Every subscription message must include your valid api_key.
  • Rate Limiting: There is a limit of 30 subscription messages per minute. If you exceed this limit, your messages will be ignored for one minute. Note: Your existing connection and subscriptions will remain active during this period.
  • No Empty Subscriptions: You cannot unsubscribe from all symbols by sending an empty subscriptions array. To stop receiving all data, disconnect the WebSocket client. Reconnect when you need data again.
  • Multiple Symbols: If your account plan permits, you can subscribe to multiple symbols within a single message by adding multiple objects to the subscriptions array.

3. Response Data Formats

The server pushes data updates as JSON-encoded messages. The format depends on the subscription type. For detailed field descriptions, refer to the corresponding REST API endpoints (/symbols/:symbol/series or /symbols/quotes).

Series Data (type: "series")

Provides OHLCV (Open, High, Low, Close, Volume) bar data.

JSON
{
  "code": "NASDAQ:AAPL",
  "bar_end": 1733432399,
  "last_update": 1733432399820,
  "bar_type": "1m",
  "series": [
    {
      "time": 1733432340,
      "open": 242.89,
      "high": 243.09,
      "low": 242.82,
      "close": 243.08,
      "volume": 533779
    }
  ]
}

Quote Data (type: "quote")

Provides real-time quote information, including price, volume, and bid/ask details.

JSON
{
  "code": "NASDAQ:AAPL",
  "lp_time": 1733432340,
  "volume": 533779,
  "last_price": 243.08,
  "change_percent": 0.41,
  "change": 979.96,
  "ask": 243.09,
  "bid": 243.08,
  "ask_size": 520.0,
  "bid_size": 430.0
}

4. Additional Parameters

The WebSocket API supports several additional parameters for fine-tuning your data feeds and customizing the response format.

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.

Example:

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

Dividend Adjustment (dadj)

For equities data, you can request dividend-adjusted price series.

  • dadj: true - Applies dividend adjustments to all price values.
  • dadj: false (default) - Shows unadjusted prices.

Example:

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

Initial Bar History (recent_bars)

Request historical bars when first subscribing to a symbol.

  • recent_bars: true - Includes up to 15 most recent complete bars with the initial response.
  • recent_bars: false (default) - Only receives new updates as they occur.

Example:

JSON
{
  "api_key": "<your_websocket_api_key>",
  "subscriptions": [
    {"code": "NASDAQ:AAPL", "bar_type": "minute", "bar_interval": 5, "recent_bars": true}
  ]
}

When recent_bars is enabled, the first message you receive will contain an array of recent bars in the series property, followed by subsequent updates with single bars.

5. Maintaining Connection & Best Practices

Automatic Re-subscription


Server Heartbeat (Keep-Alive)

The server periodically sends a timestamp message (approximately every 10 seconds) to help keep the connection alive and allow clients to verify connectivity.

Format:

JSON
{"server_time": 1741397070281}

Preventing Connection Drops

Some WebSocket libraries can drop connections during periods of inactivity. To maintain a stable connection:

  • Send a 'ping' text message every 20-30 seconds to keep the connection active.
  • The server will respond with a 'pong' message, confirming the connection is still alive.
  • Important: Do not send ping messages too frequently (e.g., more than once every 15 seconds) as this may trigger rate limiting.
  • This WebSocket message rate limit (only applies to messages sent from the client) is separate from any REST API rate limits you might have.
JAVASCRIPT
const ws = new WebSocket('wss://realtime.insightsentry.com/live');

const pingInterval = setInterval(() => {
  if (ws.readyState === WebSocket.OPEN) {
    ws.send('ping');
  }
}, 20000);

ws.onclose = () => {
  clearInterval(pingInterval);
  console.log('WebSocket connection closed');
};

ws.onmessage = (event) => {
  const data = event.data;
  if (data === 'pong') {
    console.log('Received pong from server');
    return;
  }
};

Client-Side Timeout

Configure your WebSocket library with an appropriate timeout value. We recommend a minimum timeout of 12 seconds. This helps handle periods of low market activity (e.g., weekends, holidays) where price updates might be infrequent, preventing premature disconnection by the client.

6. Error Handling

If you send an invalid request (e.g., incorrect format, invalid symbol) or if a server-side error occurs related to your request, the server will send a JSON-encoded error message:

JSON
{
  "message": "Invalid Symbol Code"
}
  • The WebSocket connection typically remains open after an error message is sent.
  • However, processing for the invalid request will stop.
  • Action Required: You should close the connection, correct the subscription request that caused the error, and then establish a new connection.
  • Always validate symbol codes and message formats before sending subscription requests.

7. API Key Rotation

The WebSocket API key can be rotated for security purposes. Important notes about WebSocket API keys:

Key Rotation Process

  1. Make a request to the /v2/websocket-key endpoint.
  2. Upon a successful request, your existing WebSocket API key will be invalidated, and a new one will be issued.
  3. Update your application to use the new WebSocket API key for subsequent connections.
  4. The response includes both the API key and its expiration timestamp in Unix epoch seconds format.

API Key Response Format

JSON
{
  "api_key": "your-websocket-api-key",
  "expiration": 1747580931
}

Key Management Best Practices

  • Refresh your key regularly - you can refresh it daily if desired, or at least once a week before expiration.
  • Store the WebSocket API key in your database along with its expiration timestamp.
  • Before using a stored key, check if it's expired or close to expiration.
  • If the key is expired or close to expiration, automatically issue a new WebSocket API key and update your database.
TYPESCRIPT
const baseUrl = 'https://insightsentry.p.rapidapi.com';

interface WebSocketKey {
  key: string;
  expiresAt: number;
}

async function getValidWebSocketKey(): Promise<string> {
  const storedKey = await database.getWebSocketKey();
  
  const now = Math.floor(Date.now() / 1000);
  const bufferTime = 24 * 60 * 60;
  
  if (storedKey && storedKey.expiresAt > (now + bufferTime)) {
    return storedKey.key;
  }
  
  const response = await fetch(`${baseUrl}/v2/websocket-key`, {
    method: 'GET',
    headers: {
      'x-rapidapi-key': 'YOUR_RAPID_API_KEY'
    }
  });
  
  const data = await response.json();
  
  await database.saveWebSocketKey({
    key: data.api_key,
    expiresAt: data.expiration
  });
  
  return data.api_key;
}

8. Code Examples

Below are basic examples demonstrating how to connect and subscribe using popular WebSocket libraries.

PYTHON
import websocket
import json
import ssl

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(f"Error: {error}")

def on_close(ws, close_status_code, close_msg):
    print(f"Disconnected with status code: {close_status_code}, message: {close_msg}")

def on_open(ws):
    print("Connection opened")
    subMsg = json.dumps({
        "api_key": "<your apikey>",
        "subscriptions": [
            {
                "code": "BINANCE:BTCUSDT",
                "bar_type": "second",
                "bar_interval": 1,
                "type": "series"
            }
        ]
    })
    ws.send(subMsg)

if __name__ == "__main__":
    ws = websocket.WebSocketApp("wss://realtime.insightsentry.com/live",
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    print("Starting WebSocket connection")
    ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
    print("WebSocket connection closed")