Pix APIs - Realtime and Historical Data in Node.js

Pix APIs - Realtime and Historical Data in Node.js

Introduction

Pix APIs is a robust JavaScript library designed to connect and stream market data efficiently. Utilizing WebSocket and fallback transport mechanisms, this library provides comprehensive functionalities to access both End of Day (EOD) and live streaming data seamlessly. It ensures simple and straightforward integration with your web applications or portals, handling all the heavy lifting behind the scenes.

Features

  • Realtime Data Streaming: Access live market data with minimal latency.
  • Historical Data Retrieval: Fetch EOD, intra-day, and tick-level historical data.
  • Option Greeks: Monitor option Greek parameters for informed trading decisions.
  • Flexible Subscriptions: Subscribe and unsubscribe to various data streams as needed.
  • Easy Integration: Simple setup and integration with Node.js applications and browsers.

Installation

Install the Pix APIs library using npm:

  1. npm install pix-apidata --save

Importing the Library

Node.js

Import the Pix APIs library into your Node.js application:

  1. const apidata = require("pix-apidata");

Browser

For browser environments, modules are available in apidata from the bundled JavaScript file. Include the following script tag in your HTML:

  1. <script src="bundle.js"></script>

Ensure that bundle.js is correctly referenced to the bundled Pix APIs script.


Initialization

Initialization is the first API call and must be completed before making any other API calls.

Node.js

  1. const apiKey = "api-access-key"; // Provided by your data vendor const apiHost = "apidata.accelpix.in"; // Provided by your data vendor const scheme = "https"; // Use either 'http' (default) or 'https' await apidata.initialize(apiKey, apiHost, scheme); // *** IMPORTANT *** // The `initialize(...)` method returns a Promise. Ensure you wait for it to complete before making any other API calls.

Browser

  1. const apiKey = "api-access-key"; // Provided by your data vendor const apiHost = "apidata.accelpix.in"; // Provided by your data vendor const scheme = "https"; // Use either 'http' (default) or 'https' apidata.initialize(apiKey, apiHost, scheme) .then(() => { // Initialization successful console.log("API Initialized Successfully"); }) .catch((error) => { console.error("Initialization Failed:", error); }); // *** IMPORTANT *** // The `initialize(...)` method returns a Promise. Ensure you wait for it to complete before making any other API calls.

Symbol Master

Retrieve master data using the provided REST API endpoints. These endpoints are specifically for master data downloads due to their large data sizes.

API Endpoints

  • Without LOT Size:
  1. https://apidata.accelpix.in/api/hsd/Masters/2?fmt=json
  • With LOT Size:
  1. https://apidata.accelpix.in/api/hsd/Masters/3?fmt=json

Sample Response

  1. { "xid": 1, // Segment ID. 1 - EQ, 2 - F&O, 3 - NCD, 5 - MCX, etc. "tkr": "20MICRONS", // Ticker name - used to communicate with server for data "atkr": null, // Alternative ticker - used for mapping or display purposes "ctkr": null, // Contract ticker or current name of FUT - used for mapping or display purposes "exp": "1970-01-01T00:00:00.000Z", // Contract expiry or defaults to UNIX time "utkr": null, // Underlying ticker of F&O contract, e.g., NIFTY for NIFTY FUT or NIFTY OPT "inst": "EQUITY", // Instrument name of the symbol - EQUITY, FUTSTK, FUTIDX, OPTSTK, OPTIDX, etc. "a3tkr": null, // Another alternative ticker - used for mapping or display purposes "sp": "0.00", // Strike price of the option contract "tk": 16921, // Exchange-defined token of the symbol "lot": 0 // Lot size }

Modules Available

Pix APIs provides the following modules for different functionalities:

  • History Module: apidata.history
  • Streaming Module: apidata.stream
  • Callbacks Module: apidata.callbacks

Callbacks for Live Streaming

Pix APIs offers various callbacks to handle live streaming data effectively.

Trade Data

Registering the Trade Callback

  1. // Callback to listen for trade data apidata.callbacks.onTrade((msg) => { console.log(msg); });

Sample Response

  1. { "id": 0, "ticker": "BANKNIFTY-1", "segmentId": 2, "time": "2024-01-16T15:30:00.000Z", "price": 46560, "qty": 300, "volume": 7499525, "oi": 3215240, "kind": "T" }

Trade Snapshot Data

Registering the Trade Snapshot Callback

  1. // Callback to listen for trade snapshots, called during the subscription process // Listen to `onTrade` callback for continuous stream data apidata.callbacks.onTradeSnapshot((msg) => { console.log(msg); });

Sample Response

  1. { "id": 0, "ticker": "BANKNIFTY-1", "segmentId": 2, "time": "2024-01-12T15:30:00.000Z", "price": 47810, "qty": 300, "volume": 7499525, "oi": 1503450, "kind": "T" }

Best Data

Registering the Best Callback

  1. // Callback to listen for bid, ask, and respective quantities apidata.callbacks.onBest((msg) => { console.log(msg); });

Sample Response

  1. { "ticker": "NIFTY-1", "segmentId": 2, "kind": "B", "bidPrice": 21780, "bidQty": 350, "askPrice": 21782, "askQty": 250, "time": "2061-09-02T07:00:00.000Z" }

Recent Change in Refs Data

Registering the Refs Callback

  1. // Callback to listen for changes in open, high, low, close, open interest, and average data apidata.callbacks.onRefs((msg) => { console.log(msg); });

Sample Response

  1. { "kind": "A", "ticker": "NIFTY-1", "segmentId": 2, "price": 21760 }

Refs Snapshot Data

Registering the Refs Snapshot Callback

  1. // Callback to listen for snapshots of open, high, low, close, open interest, average, and band data apidata.callbacks.onRefsSnapshot((msg) => { console.log(msg); });

Sample Response

  1. { "kind": "V", "ticker": "BANKNIFTY-1", "segmentId": 2, "open": 47656.8, "close": 47573.7, "high": 48047, "low": 47568.6, "avg": 47540.8, "oi": 2013795, "upperBand": 0, "lowerBand": 0, "poi": 2275950 }

Option Greek Data

Registering the Option Greeks Callback

  1. // Callback to listen for Option Greeks data apidata.callbacks.onGreeks((msg) => { console.log(msg); });

Sample Response

  1. { "kind": "G", "token": 0, "ticker": "BANKNIFTY2411748500CE", "iv": 0.2588011622428894, "delta": 0.8822246193885803, "theta": -77.46974182128906, "vega": 2.561089515686035, "gamma": 0.0005879841046407819, "ivvwap": 0.18449798226356506, "vanna": -3.667503833770752, "charm": 1.109373927116394, "speed": -0.000002092838712997036, "zomma": 0.0009008663473650813, "color": 0.0002725007652770728, "volga": 5643.75439453125, "veta": 2929.610107421875, "tgr": -131754.828125, "tv": -30.24874496459961, "dtr": -0.011387989856302738, "highiv": 0, "lowiv": 0, "twapiv": 0.19661587476730347, "timestamp": 1333597502420254464 // Time in nanoseconds from 01-Jan-1980 00:00:00 UTC }

Greek Snapshot Data

Registering the Greek Snapshot Callback

  1. // Callback to listen for Option Greeks snapshot data apidata.callbacks.onGreekSnapshot((msg) => { console.log(msg); });

Sample Response

  1. { "kind": "G", "token": 0, "ticker": "BANKNIFTY2411748500CE", "iv": 0.2588011622428894, "delta": 0.8822246193885803, "theta": -77.46974182128906, "vega": 2.561089515686035, "gamma": 0.0005879841046407819, "ivvwap": 0.18449798226356506, "vanna": -3.667503833770752, "charm": 1.109373927116394, "speed": -0.000002092838712997036, "zomma": 0.0009008663473650813, "color": 0.0002725007652770728, "volga": 5643.75439453125, "veta": 2929.610107421875, "tgr": -131754.828125, "tv": -30.24874496459961, "dtr": -0.011387989856302738, "highiv": 0, "lowiv": 0, "twapiv": 0.19661587476730347, "timestamp": 1333597502420254464 // Time in nanoseconds from 01-Jan-1980 00:00:00 UTC }

Callbacks for Connection Status

Monitor the connection status using the following callbacks.

Connection Started

Registering the Connection Started Callback

  1. // Fired when the connection is successfully established apidata.callbacks.onConnected(() => { console.log("Connected successfully..."); });

Connection Stopped

Registering the Connection Stopped Callback

  1. // Fired when the connection is closed after an automatic retry or due to networking issues // You need to re-establish the connection manually apidata.callbacks.onClosed((err) => { console.log("Connection closed due to:", err); });

Live Stream Subscription

Subscribe to various live data streams based on your requirements.

Subscribe to Receive Updates of Segments Entitled to You

  1. const needSnapshot = false; const status = await apidata.stream.subscribeSegments(needSnapshot); /* IMPORTANT NOTE: If `needSnapshot = true`, buffer the updates received on `apidata.callbacks.onTradeSnapshot` and `apidata.callbacks.onRefsSnapshot` before processing. Data transfer is substantial, and you may get disconnected from the server if you don't process incoming updates quickly enough. It's advised to buffer the data and then process it once the `subscribeSegments` method returns. */

Subscribe to Receive All Updates of the Symbols Subscribed

Subscribe to a Single Symbol

  1. await apidata.stream.subscribeAll(['NIFTY-1']);

Subscribe to Multiple Symbols

  1. await apidata.stream.subscribeAll(['NIFTY-1', 'BANKNIFTY-1']);

Subscribe to Receive Trade Updates of the Symbols Subscribed

  1. await apidata.stream.subscribeTrade(['NIFTY-1', 'BANKNIFTY-1']);

Subscribe to Receive Refs and Best Updates of the Symbols Subscribed

  1. await apidata.stream.subscribeBestAndRefs(['NIFTY-1', 'INFY-1']);

Subscribe to Receive Greeks Updates

  1. await apidata.stream.subscribeGreeks(['NIFTY2411822200CE']);

Subscribe to Receive Option Chain Updates

  1. // Parameters: underlying ticker, Expiry Date // Subscribe to a full option chain await apidata.stream.subscribeOptionChain('NIFTY', '20240118'); // Subscribe to a range of strikes (CE, PE) considering the current spot value at the time of subscription as the mid-point. // This subscribes to 10 strikes (CE, PE) below and 10 strikes (CE, PE) above the mid-point, totaling 40 contracts. await apidata.stream.subscribeOptionChainRange('NIFTY', '20240118', 10);

Unsubscribe Live Stream

Unsubscribe Single Symbol

  1. await apidata.stream.unsubscribeAll(['NIFTY-1']);

Unsubscribe Multiple Symbols

  1. await apidata.stream.unsubscribeAll(['NIFTY-1', 'BANKNIFTY-1']);

Unsubscribe Option Chain Updates

  1. await apidata.stream.unsubscribeOptionChain('NIFTY', '20240118');

Unsubscribe Greeks Updates

  1. await apidata.stream.unsubscribeGreeks(['NIFTY2411822200CE', 'NIFTY24118221500PE']);

Subscribe and Unsubscribe Greeks Chain

Subscribe to Greeks Chain Range

  1. // Parameters: underlying ticker, Expiry Date, Number of Strikes // Subscribe to a range of strikes (CE, PE) considering the current spot value at the time of subscription as the mid-point. // This subscribes to 10 strikes (CE, PE) below and 10 strikes (CE, PE) above the mid-point, totaling 40 contracts. await apidata.stream.subscribeGreeksChainRange('NIFTY', '20240118', 10);

Unsubscribe from Greeks Chain

  1. await apidata.stream.unsubscribeGreeksChain('NIFTY', '20240118');

History Data

Access historical market data using the following methods.

End of Day (EOD)

Retrieve EOD data for specified tickers and date ranges.

  1. // Continuous data // Parameters: ticker, startDate, endDate await apidata.history.getEod("NIFTY-1", "20240112", "20240118"); // Contract data // Parameters: underlying ticker, startDate, endDate, contractExpiryDate await apidata.history.getEodContract("NIFTY", "20240109", "20240118", "20240125");

Sample Response

  1. { "td": "2024-01-18T00:00:00", "op": 21461.9, "hp": 21574, "lp": 21316.8, "cp": 21520.4, "vol": 260625, "oi": 11075450 }

Intra-Day

Retrieve intra-day data with minute-level resolution.

Features

  • Provides intra-EOD bars with time resolution in minutes (default: 5 minutes).
  • Supports resolutions of 1, 5, 10 minutes, and custom resolutions like 3, 7 minutes.
  • Passing the current date as a parameter in toDate returns live tick aggregation up to the time traded today. The last bar of the current day may be incomplete. Current day tick aggregation response always provides a complete list of bars from the beginning of the day.
  1. // Continuous data // Parameters: ticker, startDate, endDate, resolution await apidata.history.getIntraEod("NIFTY-1", "20240112", "20240118", "5"); // Contract data // Parameters: underlying ticker, startDate, endDate, contractExpiryDate, resolution await apidata.history.getIntraEodContract("NIFTY", "20240109", "20240118", "20240125", "5");

Sample Response

  1. { "td": "2024-01-18T09:15:00", "op": 21461.9, "hp": 21574, "lp": 21316.8, "cp": 21520.4, "vol": 260625, "oi": 11075450 }

Ticks

Retrieve tick data from a specified date and time up to the current live time.

  1. // Parameters: ticker, fromDateTime await apidata.history.getBackTicks("BANKNIFTY-1", "20240118 15:00:00");

Sample Response

  1. { "td": "2024-01-18T15:00:01.000Z", "pr": 45720, "vol": 135, "oi": 2357865 }

Sample API Example

Below is a working example demonstrating how to use the Pix APIs to subscribe to live data streams and retrieve historical data.

  1. const apidata = require('pix-apidata'); const apiKey = "your-api-key"; const apiServer = "apidata.accelpix.in"; apidata.callbacks.onTrade((t) => { console.log("Trade:", t); }); apidata.callbacks.onGreeks((greek) => { console.log("Greek:", greek); }); apidata.initialize(apiKey, apiServer) .then(async () => { // Subscribe to all symbols await apidata.stream.subscribeAll(['NIFTY-1']); // Subscribe to Greeks data await apidata.stream.subscribeGreeks(["NIFTY2220318500CE"]); // Subscribe to Option Chain Range await apidata.stream.subscribeOptionChainRange('NIFTY', '20240118', 7); // Subscribe to Greeks Chain Range await apidata.stream.subscribeGreeksChainRange('NIFTY', '20240118', 5); // Uncomment the following line to unsubscribe from Option Chain // await apidata.stream.unsubscribeOptionChain('NIFTY', '20240118'); // Retrieve EOD historical data let eod = await apidata.history.getEod('NIFTY 50', '20240112', '20240116'); console.log("EOD Data:", eod); }) .catch((error) => { console.error("Initialization Failed:", error); });

    • Related Articles

    • Pix APIs - Realtime and Historical Data in REST

      Introduction ACCELPIX REST API is a robust interface designed for downloading historical and tick data efficiently. Whether you're looking to retrieve End of Day (EOD) data, intra-EOD data, live intra OHLC (Open, High, Low, Close) data, or quotes, ...
    • Pix APIs - Realtime and Historical Data in Python

      Introduction AccelPix Data API is a Python library designed to connect and stream market data seamlessly. Leveraging WebSocket and fallback transport mechanisms, this library provides functionalities to access both End of Day (EOD) and live streaming ...
    • How to configure Realtime NSE Data in Excel ?

      India's Fastest Realtime (Tick by Tick 1 Sec Updates) Data in MS Excel. The following are the minimum requirements: - 1. Microsoft Office Excel 2010 or above 2. Pix Connect Elite and the Above plans can be used with Excel. How to Setup Pix Connect ...
    • Symbols Format for realtime data APIs

      We are providing all symbols as per NSE including Futures (Contract and Continuous Both) and Options (Weekly and Monthly). Let's go through some examples and understand the symbology. General Terminology in API:- T = Trade Packet B = Best Packet V = ...
    • How to download Daily IEOD Incremental Data using Pix Connect ?

      Intraday End of Day Data ( IEOD ) is too crucial for backtesting purposes, that's why we do provide for all our subscribers at FREE OF COST with REALTIME Data Subscription. We are updating these data every day within 25 min after the market close (at ...