Browse documentation
Integrations

WebSocket streams

Instead of polling REST endpoints for fresh filings, earnings, news, concalls, and alerts, open a single WebSocket connection and subscribe to the products you care about. Drishti pushes structured events as soon as they are published — useful for watchlist monitors, research desks, and agent workflows that need to react quickly.

How it works

  1. Use a paid plan. WebSocket streams require Starter, Pro, or Enterprise. Copy an API key from the Drishti platform console.
  2. Open a connection to wss://developers.manasija.in/v1/ws with your API key.
  3. Subscribe within 60 seconds. Send one subscribe message per product. A socket with no accepted subscription is closed after 60 seconds.
  4. Read every message by its shape. The server sends subscribe confirmations, data events, errors, heartbeats, and access-change notices on the same socket. See Server messages.
  5. Reconnect, resubscribe, and catch up. Subscriptions do not survive a disconnect and there is no replay buffer. Resubscribe on every new connection and use REST to fill the gap. See Reconnect and catch up.

The SDK websocket helper handles steps 2, 3, and the reconnect part of step 5 for you.

Message flow

A typical session, in order:

text
client  → connect wss://developers.manasija.in/v1/ws  (X-API-Key header or ?api_key=)
client  → {"op":"subscribe","product":"earnings","symbols":["RELIANCE","TCS"]}
server  ← {"status":"subscribed","product":"earnings","tier":"starter_100",...}
server  ← {"type":"heartbeat","sent_at":"2026-10-16T09:30:00+00:00"}       every 30 s
server  ← {"channel":"earnings","event":"earnings.ready","data":{...}}     when a filing is published
server  ← {"channel":"earnings","event":"earnings.updated","data":{...}}   when the same quarter changes
          … connection drops …
client  → reconnect, send the same subscribe messages, call REST to catch up

Endpoint and authentication

text
wss://developers.manasija.in/v1/ws

Use the same API key as REST. The connection request accepts either:

MethodValueUse it for
HeaderX-API-Key: <key>Server clients (Node ws, Python websockets, the SDKs).
Query string?api_key=<key>Runtimes that cannot set headers, such as the browser WebSocket API.

A missing or invalid key is rejected during the handshake with HTTP 403, so the socket never opens. A key revoked while connected closes the socket with code 4401. WebSocket access is checked separately from REST access: a key that can call REST can still be rejected at subscribe time. See Authentication.

SDK websocket helper

Use client.websocket() from the official SDK instead of managing raw sockets yourself. The session client connects in the background, sends subscribe messages for you, replays every subscription after a reconnect, watches heartbeats to detect dead connections, and keeps retrying until you call close().

Install

pnpm add drishti-sdk
bash
pip install drishti-sdk
bash
composer require manasija/drishti-sdk

For Java, add Maven io.github.techmanasija:drishti-sdk (see the Java SDK page). For .NET, run dotnet add package Manasija.Drishti (see the C# / .NET SDK page).

JavaScript / TypeScript

Create a session from any DrishtiClient instance, subscribe to one or more products, then handle events with callbacks or an async iterator:

ts
import { DrishtiClient } from "drishti-sdk"

const client = new DrishtiClient({ apiKey: process.env.DRISHTI_API_KEY! })
const ws = client.websocket({
  onAnnouncements: (announcement) => {
    console.log(announcement.symbol, announcement.summary)
  },
})

await ws.subscribe({ product: "announcements", symbols: ["RELIANCE", "TCS"] })

Prefer for await when you want one loop that also sees subscribe confirmations and socket errors:

ts
const ws = client.websocket()

await ws.subscribe({ product: "announcements", symbols: ["RELIANCE"], detailed: false })

for await (const event of ws.events()) {
  if (event.kind === "subscribed") {
    console.log(event.product, event.tier)
    continue
  }
  if (event.kind === "data") console.log(event.channel, event.data)
  if (event.kind === "error") console.error(event.message)
}

Channel listeners are also available via ws.on("announcements", handler) and product-specific helpers such as ws.onAnnouncements(handler), ws.onNews(handler), ws.onBlockDeals(handler), and ws.onAlerts(handler). Use ws.on("heartbeat", handler) if you want to observe heartbeats yourself.

Python

The Python helper is async-first. The session connects on the first subscribe, events, or async with call:

python
import asyncio
import os
from drishti_sdk import DrishtiClient

async def main() -> None:
    client = DrishtiClient(api_key=os.environ["DRISHTI_API_KEY"])
    async with client.websocket(
        on_announcements=lambda row: print(row.get("symbol"), row.get("summary")),
    ) as ws:
        await ws.subscribe("announcements", symbols=["RELIANCE", "TCS"])
        await asyncio.Event().wait()

asyncio.run(main())

Use async for event in ws.events() when you want subscribe confirmations and delivery events in one stream:

python
async with client.websocket() as ws:
    await ws.subscribe("announcements", symbols=["RELIANCE"], detailed=False)
    async for event in ws.events():
        if event.kind == "subscribed":
            print(event.product, event.tier)
            continue
        if event.kind == "data":
            print(event.channel, event.data)
        if event.kind == "error":
            print(event.message)

PHP

The PHP helper is blocking and is meant for a long-running CLI worker (supervisord, systemd, or a framework console command), not a web request. Register handlers and subscriptions, then call run():

php
use Drishti\DrishtiClient;

$client = new DrishtiClient(apiKey: getenv('DRISHTI_API_KEY'));
$ws = $client->websocket();

$ws->onAnnouncements(function (array $row): void {
    echo $row['symbol'] ?? '', ' ', $row['summary'] ?? '', PHP_EOL;
});

$ws->subscribe('announcements', symbols: ['RELIANCE', 'TCS']);
$ws->run(); // blocks until $ws->stop()

Use on('message', ...) when you want subscribe confirmations, delivery events, heartbeats, and errors in one handler:

php
$ws->on('message', function ($event): void {
    $e = $event->toArray();
    match ($e['kind']) {
        'subscribed' => print("{$e['product']} {$e['tier']}\n"),
        'data' => print($e['channel'] . PHP_EOL),
        'error' => print($e['message'] . PHP_EOL),
        default => null,
    };
});

Java

The Java session is blocking, like PHP, but it can also run on a background thread inside a web app or service. Register handlers and subscriptions, then call run() (blocking) or start() (background):

java
DrishtiWebSocketSession ws = DrishtiClient.fromEnvironment().websocket()
        .onSubscribed(ack -> System.out.println(ack.product() + " " + ack.tier()))
        .onAnnouncements(row -> System.out.println(row.path("symbol").asText() + " " + row.path("summary").asText()))
        .onError(error -> System.err.println(error.message()));

ws.subscribe("announcements", List.of("RELIANCE", "TCS"));
ws.start(); // background daemon thread; call ws.close() on shutdown

Use onMessage(handler) when you want subscribe confirmations, delivery events, heartbeats, and errors in one handler. Events are a sealed WebSocketEvent type: SubscribedEvent, DataEvent, ErrorEvent, HeartbeatEvent, and RawEvent.

C# / .NET

The .NET session is async and fits a BackgroundService or console app. Register handlers and subscriptions, then await RunAsync (until cancelled) or call StartAsync (background):

csharp
using Manasija.Drishti;
using Manasija.Drishti.WebSocket;

using var client = DrishtiClient.FromEnvironment();
await using var session = client.CreateWebSocketSession();
session
    .OnSubscribed(ack => { Console.WriteLine($"{ack.Product} {ack.Tier}"); return Task.CompletedTask; })
    .OnAnnouncements(a => Console.WriteLine($"{a.Symbol} {a.Summary}"))
    .OnError(e => { Console.Error.WriteLine(e.Message); return Task.CompletedTask; });

await session.SubscribeAsync(new SubscribeOptions("announcements") { Symbols = ["RELIANCE", "TCS"] });
await session.RunAsync(stoppingToken); // until cancelled

Use ReadEventsAsync(cancellationToken) when you want delivery events and errors in one await foreach loop. Events are WebSocketEvent records: DataEvent, ErrorEvent, SubscribedEvent, HeartbeatEvent, and RawEvent.

Session API

MethodJavaScript / TypeScriptPythonPHPDescription
Create sessionclient.websocket(options?)client.websocket(...)$client->websocket(...)Prepares a managed WebSocket session tied to the client API key.
Subscribeawait ws.subscribe({ product, symbols, detailed?, categories? })await ws.subscribe(product, symbols=..., detailed=..., categories=...)$ws->subscribe($product, symbols: ..., categories: ..., detailed: ...); sent when run() connects, or right away (throwing on rejection) when called from a handler on a live connectionSends the subscribe message. Before the socket is open (the usual case at startup), it returns at once, the SDK sends it on connect, and a rejection arrives in onError / on_error. On a live connection, it waits for the server's reply and throws on rejection. Read the confirmation (tier, symbols, full_feed, detailed, categories) from a subscribed event or onSubscribed / on_subscribed.
Event streamfor await (const event of ws.events())async for event in ws.events()$ws->on('message', $handler)Yields subscribed, data, heartbeat, and error events from one loop.
Channel listenersws.on(channel, handler) / ws.onAnnouncements(handler)on_announcements=..., on_news=..., etc.$ws->on(channel, $handler) / $ws->onAnnouncements($handler)Product-specific callbacks for data deliveries.
Lifecycle hooksonSubscribed, onError, onOpen, onReconnectAttempton_subscribed, on_error, on_open, on_reconnect_attemptonSubscribed:, onError:, onOpen:, onReconnectAttempt:onOpen / on_open runs after every successful connect, once subscriptions have been replayed — the right place for catch-up.
Closeawait ws.close()async with exit / await ws.close()$ws->stop() (ends run())Stops reconnect attempts and closes the socket.

SDK behavior worth knowing:

  • Heartbeat watchdog. If no message (including heartbeats) arrives for 90 seconds, the JavaScript, Java, PHP, and C# SDKs treat the connection as dead and reconnect. Tune it with heartbeatTimeoutMs (JavaScript), heartbeatTimeout (Java and PHP), or HeartbeatTimeout (C#). The Python SDK sends WebSocket pings every 20 seconds instead.
  • Handle subscribe errors in `onError`. Rejections with code forbidden, bad_request, or unauthorized arrive in onError / on_error. The SDK keeps the subscription and tries again on every reconnect, so close the session (close(), or stop() in Java and PHP) when the error cannot fix itself, such as a missing add-on or a revoked key.
  • The SDK does not backfill. Reconnects restore live delivery only. Run the catch-up step from onOpen / on_open.

Products

Every product can share one connection. Send one subscribe message per product; each product keeps its own symbols and settings.

ProductStreamREST equivalent
newsNews updates`GET /v1/news`
block-dealsBlock-deal updatesStream only
announcementsCorporate announcements`GET /v1/announcements`
earningsEarnings filings`GET /v1/earnings`
concallsConference-call updates`GET /v1/concalls`
alertsMarket alerts`GET /v1/alerts`

Subscribe message

subscribe is the only message the server accepts. There is no unsubscribe or ping message: to stop a product, close the connection and reconnect without it.

json
{"op":"subscribe","product":"announcements","symbols":["RELIANCE","TCS"],"detailed":true}
FieldTypeRequiredDescription
opstringYesMust be subscribe.
productstringYesOne of news, block-deals, announcements, earnings, concalls, or alerts. The SDKs call block deals block_deals (for example onBlockDeals / on_block_deals) and convert it for you.
symbolsstring[]Yes on Starter and ProNSE symbols to receive events for. Symbols are uppercased and deduplicated. Starter and Pro must send at least one symbol. An empty array requests the full feed and needs a full-market (Enterprise) entitlement.
detailedbooleanNoDefaults to true. false sends the smaller REST list-row shape on announcements, earnings, and concalls. Must be a JSON boolean, not a string.
categoriesstring[]Only on the announcement category planPrimary announcement categories to receive, for accounts on the 15-category announcements plan. Up to 15 distinct categories across all your connections; reusing a category on another connection does not use another slot. Names must match announcement categories. Omit it on every other plan.

Rules:

  • Re-subscribing replaces. A second subscribe for the same product on the same connection replaces that product's symbols, detailed mode, and categories. Other products are not affected.
  • Symbol caps are account-wide. Active symbols are counted across every open connection and product. A second connection that adds new symbols can be rejected even if each connection is under the cap on its own.
  • Filtering. A symbol-filtered subscription receives an event when the event's symbol (or symbol list) matches one of your subscribed symbols.

Server messages

Every message the server sends is a JSON object. Tell them apart by their keys, not by order:

MessageHow to recognize itWhat to do
Subscribe confirmationstatus is subscribedRecord the accepted tier, symbols, and full_feed.
Data eventHas channel, data, and usually eventHand off to your handler. SDKs expose the name as event.event.
ErrorHas errorLog it. The connection stays open unless a close code follows.
Heartbeattype is heartbeatIgnore it, or use it to detect a dead connection. Sent every 30 seconds.
Access changedstatus is entitlements_changed or entitlement_expiredThe server closes with 4003 right after. Reconnect and resubscribe.

Subscribe confirmation

json
{"status":"subscribed","product":"announcements","tier":"starter_100","full_feed":false,"symbols":["RELIANCE","TCS"],"detailed":true}
FieldDescription
statusAlways subscribed.
productThe product that was configured.
tierYour WebSocket tier for that product: starter_100, pro_1000, or scale.
full_feedtrue when you receive every event for the product; false when delivery is limited to symbols.
symbolsThe accepted symbol list after uppercasing and deduplication. Empty when full_feed is true.
detailedThe accepted detail mode.
categoriesOnly present on the announcement category plan: the accepted categories.

Data events

Every data event has the same top-level shape:

FieldTypeDescription
channelstringThe product that produced the event — same value as product in your subscribe message.
eventstringOptional. What happened, when the producer names it. See Event names.
dataobjectThe resource payload. Shape depends on channel and your detailed setting.
json
{
  "channel": "announcements",
  "data": {
    "id": "6a015e446ec560b11681e3c9",
    "symbol": "RELIANCE",
    "summary": "The board approved the quarterly financial results.",
    "category": "Board Meeting"
  }
}

Shapes by channel

Channeldata when detailed=truedata when detailed=false
newsNewsItemNewsItem
block-dealsBlockDealItemBlockDealItem
announcementsAnnouncementDetailAnnouncementListItem
earningsEarningsDetailEarningsListItem
concallsConcallDetailConcallListItem
alertsAlertAlert
  • Shapes match the REST list and detail rows for the same product.
  • Announcement events never include title, headline, or attachment URLs. Use summary for display text.
  • Earnings events may include attachment_url, so you do not need a separate attachments call for live events.
  • Block-deal events never include upstream headline text.
  • Alerts use the public Alert shape and keep type / alert_type compatibility. Each event has a UTC timestamp for when the alert was created; price alerts also include delayed price.value, signed price.change_percent, and price.as_of for the price observation time.
  • Known public alert type values: 52w_high, 52w_low, earnings, high_growth_concalls, price_alert, rvol_alert, volume_alert.

Event names

eventChannelMeaning
earnings.readyearningsFirst published result for a company and quarter.
earnings.updatedearningsA later change to the same company and quarter, such as a results table that finished late or a later filing. Replace the row you stored from earnings.ready.
concall.readyconcallsFirst analysis of a conference call.
concall.updatedconcallsThe same call was analysed again, for example from the official transcript after the audio. Replace the row you stored from concall.ready.
news.publishednewsA new news item.
block_deals.publishedblock-dealsA new block deal.

Other channels may not set event. Treat it as optional and do not fail when it is missing or has a value you do not recognize.

Handling repeat events for the same symbol

A symbol can produce several events over time — for example earnings.ready followed by earnings.updated when the results table lands, or concall.ready followed by concall.updated when the official transcript replaces the audio. Pick one approach:

  • Upsert by `data.id` — store the latest version of each record. This is the right default and also makes catch-up after a reconnect safe.
  • Notify only on first sight — alert users on earnings.ready / concall.ready and silently update on earnings.updated / concall.updated.
  • Process every event — when latency matters more than deduplication.

Examples by product

Product examples

Loading websocket examples...

Errors

A rejected message gets an error reply on the same socket. The connection stays open, so you can fix the request and send it again.

json
{"error":"The Starter plan allows at most 100 symbols","code":"forbidden"}

error is a readable message. code is present on access and limit errors; validation errors only have error.

error (example)codeCause
Invalid JSON—The message is not valid JSON.
Unsupported operation—op is missing or is not subscribe.
Missing product—product is missing or empty.
symbols must be an array—symbols is a string or object instead of an array.
categories must be an array of strings—categories has the wrong type.
detailed must be a boolean—detailed was sent as a string such as "true".
WebSocket addon '<product>' is not enabled for this keyforbiddenYour plan or key does not include this product.
The <plan> plan allows at most <n> symbolsforbiddenToo many symbols in one subscribe.
The <plan> plan requires at least one symbolforbiddenEmpty symbols on a plan without full-feed access.
Tier allows at most <n> active symbolssymbol_limit_exceededThe account-wide symbol cap is reached across all connections.

After 5 rejected subscribes on a connection with nothing accepted, the server closes the socket with 4403.

Close codes

When the server ends the connection, it uses one of these codes. Where a reason message is sent first, it arrives as an error or access-change message just before the close.

CodeReasonCauseReconnect?
4401—API key missing, invalid, or inactive.No. Fix the key first.
4429websocket_connection_limitToo many simultaneous connections for the account.Not until you close another connection.
4408websocket_subscribe_timeoutNo subscription was accepted within 60 seconds of connecting.Yes, and send subscribe messages straight away.
4403websocket_subscribe_rejected5 rejected subscribes with nothing accepted.No. Fix the subscribe message or plan first.
4003websocket_entitlements_changed / websocket_entitlement_expiredYour plan or WebSocket access changed or expired.Yes. Reconnect to pick up your current access.
1000–1015—Normal closure, network drop, proxy timeout, or server restart.Yes, with backoff.

Limits

PlanWebSocket accessSymbol capSimultaneous connectionsFull feed
SandboxNot available—0—
StarterAll products100 active symbols account-wide5No
ProAll products1,000 active symbols account-wide5No
EnterpriseBy agreementFull marketBy agreementYes — send empty symbols
  • Connections count as soon as they open, whether or not they have subscribed. Close sockets you no longer use.
  • Subscribe within 60 seconds of connecting, or the socket is closed with 4408.
  • Full-feed accounts can still filter. Sending symbols on a full-feed tier gives a filtered subscription.
  • No REST credits are charged for WebSocket delivery on paid plans.

Reconnect and catch up

Connections drop because of network interruptions, proxy timeouts, deploys, or access changes. Subscriptions belong to the connection, and there is no server-side replay: events published while you were disconnected are not resent.

On every reconnect:

  1. Back off. Wait before reconnecting, doubling the delay up to about 30 seconds. Do not reconnect after 4401 or 4403.
  2. Resubscribe. Send the same subscribe messages again. The SDK does this for you and then calls onOpen / on_open.
  3. Catch up over REST. For each product, call its REST list endpoint for your symbols and keep rows newer than the last data.date you processed.
  4. Upsert by `data.id` so records you already have are not processed twice.
ts
const ws = client.websocket({
  // Runs after every connect, once subscriptions are replayed
  onOpen: async () => {
    const missed = await client.getAnnouncements({ symbols: WATCHLIST, limit: 100 })
    for (const row of missed.data) {
      if (row.date > lastSeenDate) await upsertById(row)
    }
  },
})

Production checklist

  • Use the SDK session client when you can. It handles reconnects, resubscribes, and heartbeat checks.
  • Handle every message type. Heartbeats, confirmations, errors, and access-change notices share the socket with data events.
  • Keep handlers fast. Parse the message, enqueue heavy work, and return. Slow consumers back up the connection.
  • Catch up after every reconnect using REST, and upsert by data.id.
  • Stay under the limits. Watch the account-wide symbol cap and the 5-connection limit — staging and production on the same account share them.
  • Keep your API key out of client bundles. Query-string keys are visible in browser DevTools. Run subscribers on your backend and push to browsers yourself.
  • Use `wss://`, never ws://.

Troubleshooting

The handshake fails with HTTP `403`, or the socket closes with `4401`. The API key is missing, wrong, or revoked. Check the key in the platform console.

Socket closes immediately with `4429`. The account already has 5 open connections. Look for old processes, other environments, or reconnect loops that never close the previous socket.

Subscribe returns `WebSocket addon ... is not enabled`. The account is on Sandbox or the plan does not include that product. Check Get account profile for enabled WebSocket products.

Socket closes after 60 seconds with `4408`. No subscribe was accepted. Send subscribe messages right after connecting and check the error replies.

No events arrive after a successful subscribe. Markets are quiet between filings. Confirm the symbols in the confirmation are the ones you expect and use the REST list endpoint to check that recent data exists for them.

Events stop after a while with no close. The connection may be half-open. If you see no heartbeat for over 90 seconds, close and reconnect.

Events stop after a deploy or network blip. Raw sockets lose subscriptions on disconnect. Resubscribe after every reconnect, or switch to the SDK.

Next steps