Skip to main content

WebSocket Integration

Connect directly to StocksEyes WebSocket service for real-time stock market data with minimal latency.

Prerequisites

  • Valid StocksEyes API key
  • Active internet connection
  • Node.js 16 or higher
  • Install dependency: npm install ws

Quick Start

Flow: Fetch URL → Connect → Subscribe → Receive Ticks → Unsubscribe → Close

Step 1: Fetch WebSocket URL

API Endpoint: GET https://api.stockseyes.com/v1/public/websocket

Response:

{
"url": "ws://***.***.***.***?token=***"
}
const https = require('https');

function fetchWebSocketUrl() {
return new Promise((resolve, reject) => {
https.get('https://api.stockseyes.com/v1/public/websocket', {
headers: { 'Authorization': '<API_KEY>' }
}, (res) => {
let body = '';
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
const { url } = JSON.parse(body);
resolve(url);
});
}).on('error', reject);
});
}

Step 2: Connect to WebSocket

const WebSocket = require('ws');

const wsUrl = await fetchWebSocketUrl();
const ws = new WebSocket(wsUrl);

ws.on('open', () => {
console.log('Connected');
});

Step 3: Subscribe to Instruments

// Single instrument
ws.send('SUBSCRIBE:738561'); // RELIANCE

// Multiple instruments
ws.send('SUBSCRIBE:738561,2953217,408065');

Step 4: Listen for Data

ws.on('message', (raw) => {
const msg = JSON.parse(raw.toString());

if (msg.type === 'ACK') {
console.log(`${msg.action}: [${msg.instruments}]`);
} else if (msg.type === 'TICK') {
const { trading_symbol, last_price, change } = msg.data;
console.log(`${trading_symbol}: ₹${last_price} (${change?.toFixed(2)}%)`);
}
});

ws.on('error', (err) => console.error('Error:', err.message));
ws.on('close', () => console.log('Connection closed'));

Step 5: Unsubscribe and Close

ws.send('UNSUBSCRIBE:738561');
ws.close();

WebSocket Commands

SUBSCRIBE

Subscribe to receive real-time data for instrument tokens.

Format:

SUBSCRIBE:token1,token2,token3

Example:

SUBSCRIBE:738561
SUBSCRIBE:738561,256265

Response:

{
"type": "ACK",
"action": "Subscribed",
"instruments": ["738561"]
}

UNSUBSCRIBE

Stop receiving data for instrument tokens.

Format:

UNSUBSCRIBE:token1,token2,token3

Example:

UNSUBSCRIBE:738561

Response:

{
"type": "ACK",
"action": "Unsubscribed",
"instruments": ["738561"]
}

Message Formats

ACK Message

Confirmation message sent by server after subscription/unsubscription.

{
"type": "ACK",
"action": "Subscribed",
"instruments": ["738561", "256265"]
}

Fields:

  • type: Always "ACK"
  • action: "Subscribed" or "Unsubscribed"
  • instruments: Array of instrument tokens

TICK Message

Real-time market data for subscribed instruments.

{
"type": "TICK",
"data": {
"instrument_token": 738561,
"trading_symbol": "RELIANCE",
"last_price": 1487.7,
"volume_traded": 5666888,
"last_traded_quantity": 1,
"average_traded_price": 1494.83,
"total_buy_quantity": 408982,
"total_sell_quantity": 761689,
"ohlc": {
"open": 1500.0,
"high": 1503.1,
"low": 1487.1,
"close": 1504.2
},
"change": -1.096,
"last_trade_time": "2025-10-30T08:48:56.000Z",
"exchange_timestamp": "2025-10-30T08:48:57.000Z",
"depth": {
"buy": [
{"quantity": 100, "price": 1487.5, "orders": 5},
{"quantity": 200, "price": 1487.0, "orders": 8}
],
"sell": [
{"quantity": 150, "price": 1488.0, "orders": 6},
{"quantity": 180, "price": 1488.5, "orders": 7}
]
},
"timestamp": 1761814138048
}
}

Key Fields:

  • instrument_token: Unique identifier for the instrument
  • trading_symbol: Stock symbol (e.g., "RELIANCE")
  • last_price: Current trading price
  • volume_traded: Total volume traded
  • ohlc: Open, High, Low, Close prices
  • change: Percentage change from previous close
  • depth: Order book depth (5 levels of buy/sell orders)
  • timestamp: Unix timestamp in milliseconds

Complete Example

const WebSocket = require('ws');
const https = require('https');

const API_URL = 'https://api.stockseyes.com/v1/public/websocket';
const INSTRUMENTS = [738561, 2953217, 408065]; // RELIANCE, TCS, INFY

// Step 1: Fetch WebSocket URL
function fetchWebSocketUrl() {
return new Promise((resolve, reject) => {
https.get(API_URL, {
headers: { 'Authorization': '<API_KEY>' }
}, (res) => {
let body = '';
res.on('data', (chunk) => body += chunk);
res.on('end', () => {
const { url } = JSON.parse(body);
resolve(url);
});
}).on('error', reject);
});
}

// Step 2-5: Connect, Subscribe, Receive, Close
async function main() {
const wsUrl = await fetchWebSocketUrl();
const ws = new WebSocket(wsUrl);

ws.on('open', () => {
console.log('Connected');
// Step 3: Subscribe
ws.send(`SUBSCRIBE:${INSTRUMENTS.join(',')}`);
});

ws.on('message', (raw) => {
const msg = JSON.parse(raw.toString());

if (msg.type === 'ACK') {
console.log(`${msg.action}: [${msg.instruments}]`);
} else if (msg.type === 'TICK') {
const { trading_symbol, last_price, change } = msg.data;
console.log(`${trading_symbol}: ₹${last_price} (${change?.toFixed(2)}%)`);
}
});

ws.on('error', (err) => console.error('Error:', err.message));
ws.on('close', () => console.log('Connection closed'));

// Cleanup after 30 seconds
setTimeout(() => {
ws.send(`UNSUBSCRIBE:${INSTRUMENTS.join(',')}`);
setTimeout(() => ws.close(), 2000);
}, 30000);
}

main();

Best Practices

Connection Management

DO:

  • Always close connections when done
  • Handle connection errors gracefully
  • Implement reconnection logic for production apps

DON'T:

  • Leave connections open indefinitely
  • Ignore error states
  • Create multiple connections for the same data

Subscription Management

DO:

  • Subscribe only to instruments you need
  • Unsubscribe when data is no longer needed
  • Batch multiple subscriptions in one command

DON'T:

  • Subscribe to hundreds of instruments at once
  • Keep subscriptions active when app is in background

Data Handling

DO:

  • Parse JSON safely with try-catch
  • Validate data before using
  • Use models/classes for type safety

DON'T:

  • Assume all fields are present
  • Ignore parsing errors
  • Use dynamic types everywhere

Common Instrument Tokens

SymbolTokenExchange
RELIANCE738561NSE
TCS2953217NSE
INFY408065NSE
HDFCBANK341249NSE
ICICIBANK1270529NSE

Troubleshooting

Connection Issues

Problem: Connection closes immediately

Solutions:

  • Verify API key is correct
  • Check if WebSocket URL includes token
  • Ensure network connectivity

Problem: "Unauthorized" error

Solutions:

  • Verify API key in Authorization header
  • Don't modify the URL returned by API
  • Token is already included in URL

Data Issues

Problem: Not receiving tick data

Solutions:

  • Verify you've sent SUBSCRIBE command
  • Check instrument token is valid
  • Ensure market is open (for live data)
  • Check connection state

Problem: Parsing errors

Solutions:

  • Use try-catch around JSON parsing
  • Check for null values
  • Validate data types before casting

Support

For issues or questions:


Last updated: 2025-10-30